Initial commit
This commit is contained in:
@@ -0,0 +1,156 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<artifactId>ProjectCranked</artifactId>
|
||||
<groupId>net.crankedpvp</groupId>
|
||||
<version>1.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>PlayerVaultsX</artifactId>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>8</maven.compiler.source>
|
||||
<maven.compiler.target>8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<defaultGoal>clean install</defaultGoal>
|
||||
<finalName>PlayerVaultsX</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<filtering>true</filtering>
|
||||
<directory>src/main/resources/</directory>
|
||||
<includes>
|
||||
<include>*.yml</include>
|
||||
<include>lang/*.yml</include>
|
||||
<include>credit/*.txt</include>
|
||||
</includes>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.2.4</version>
|
||||
<configuration>
|
||||
<createDependencyReducedPom>false</createDependencyReducedPom>
|
||||
<relocations>
|
||||
<relocation>
|
||||
<pattern>net.kyori</pattern>
|
||||
<shadedPattern>com.drtshock.playervaults.lib.net.kyori</shadedPattern>
|
||||
</relocation>
|
||||
<relocation>
|
||||
<pattern>com.google.gson</pattern>
|
||||
<shadedPattern>com.drtshock.playervaults.lib.com.google.gson</shadedPattern>
|
||||
</relocation>
|
||||
<relocation>
|
||||
<pattern>org.kitteh</pattern>
|
||||
<shadedPattern>com.drtshock.playervaults.lib.org.kitteh</shadedPattern>
|
||||
</relocation>
|
||||
</relocations>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
|
||||
<repository>
|
||||
<id>fuuid-repo</id>
|
||||
<url>https://github.com/factions-site/repo/raw/public</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>spigot-repo</id>
|
||||
<url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>sonatype</id>
|
||||
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
|
||||
<releases>
|
||||
<enabled>false</enabled>
|
||||
</releases>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>jitpack.io</id>
|
||||
<url>https://jitpack.io</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<artifactId>Utils</artifactId>
|
||||
<groupId>net.crankedpvp</groupId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.kyori</groupId>
|
||||
<artifactId>adventure-platform-bukkit</artifactId>
|
||||
<version>4.0.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.kyori</groupId>
|
||||
<artifactId>adventure-text-minimessage</artifactId>
|
||||
<version>4.11.0</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>2.8.8</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.kitteh</groupId>
|
||||
<artifactId>cardboardbox</artifactId>
|
||||
<version>0.2.2</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.MilkBowl</groupId>
|
||||
<artifactId>VaultAPI</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.kitteh</groupId>
|
||||
<artifactId>paste-gg-api</artifactId>
|
||||
<version>0.9.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.checkerframework</groupId>
|
||||
<artifactId>checker-qual</artifactId>
|
||||
<version>3.3.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.crankedpvp</groupId>
|
||||
<artifactId>StorageUtilsShaded</artifactId>
|
||||
<version>1.0</version>
|
||||
<scope>system</scope>
|
||||
<systemPath>${project.basedir}/../StorageUtils/target/StorageUtils-1.0-shaded.jar</systemPath>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,253 @@
|
||||
/*
|
||||
* PlayerVaultsX
|
||||
* Copyright (C) 2013 Trent Hensler
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.drtshock.playervaults;
|
||||
|
||||
import com.drtshock.playervaults.vaultmanagement.CardboardBoxSerialization;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.configuration.serialization.ConfigurationSerialization;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.util.io.BukkitObjectInputStream;
|
||||
import org.json.simple.JSONArray;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.JSONValue;
|
||||
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
class Conversion {
|
||||
/**
|
||||
* Fancy JSON serialization mostly by evilmidget38.
|
||||
*
|
||||
* @author evilmidget38, gomeow
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
static class OldestSerialization {
|
||||
private static Map<String, Object> toMap(JSONObject object) {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
|
||||
// Weird case of bad meta causing null map to be passed here.
|
||||
if (object == null) {
|
||||
return map;
|
||||
}
|
||||
|
||||
for (Object key : object.keySet()) {
|
||||
map.put(key.toString(), fromJson(object.get(key)));
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private static Object fromJson(Object json) {
|
||||
if (json == null) {
|
||||
return null;
|
||||
} else if (json instanceof JSONObject) {
|
||||
return toMap((JSONObject) json);
|
||||
} else if (json instanceof JSONArray) {
|
||||
return toList((JSONArray) json);
|
||||
} else {
|
||||
return json;
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Object> toList(JSONArray array) {
|
||||
List<Object> list = new ArrayList<>();
|
||||
for (Object value : array) {
|
||||
list.add(fromJson(value));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private static ItemStack[] getItems(List<String> stringItems) {
|
||||
List<ItemStack> contents = new ArrayList<>();
|
||||
for (String piece : stringItems) {
|
||||
if (piece.equalsIgnoreCase("null")) {
|
||||
contents.add(null);
|
||||
} else {
|
||||
ItemStack item = (ItemStack) deserialize(toMap((JSONObject) JSONValue.parse(piece)));
|
||||
contents.add(item);
|
||||
}
|
||||
}
|
||||
ItemStack[] items = new ItemStack[contents.size()];
|
||||
for (int x = 0; x < contents.size(); x++) {
|
||||
items[x] = contents.get(x);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
private static Map<String, Object> recreateMap(Map<String, Object> original) {
|
||||
return new HashMap<>(original);
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
private static Object deserialize(Map<String, Object> map) {
|
||||
for (Entry<String, Object> entry : map.entrySet()) {
|
||||
if (entry.getValue() instanceof Map) {
|
||||
entry.setValue(deserialize((Map) entry.getValue()));
|
||||
} else if (entry.getValue() instanceof Iterable) {
|
||||
entry.setValue(convertIterable((Iterable) entry.getValue()));
|
||||
} else if (entry.getValue() instanceof Number) {
|
||||
entry.setValue(convertNumber((Number) entry.getValue()));
|
||||
}
|
||||
}
|
||||
return map.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY) ? ConfigurationSerialization.deserializeObject(map) : map;
|
||||
}
|
||||
|
||||
private static List<?> convertIterable(Iterable<?> iterable) {
|
||||
List<Object> newList = new ArrayList<>();
|
||||
for (Object object : iterable) {
|
||||
if (object instanceof Map) {
|
||||
object = deserialize((Map<String, Object>) object);
|
||||
} else if (object instanceof List) {
|
||||
object = convertIterable((Iterable<?>) object);
|
||||
} else if (object instanceof Number) {
|
||||
object = convertNumber((Number) object);
|
||||
}
|
||||
newList.add(object);
|
||||
}
|
||||
return newList;
|
||||
}
|
||||
|
||||
private static Number convertNumber(Number number) {
|
||||
if (number instanceof Long) {
|
||||
Long longObj = (Long) number;
|
||||
if (longObj == longObj.intValue()) {
|
||||
return longObj.intValue();
|
||||
}
|
||||
}
|
||||
return number;
|
||||
}
|
||||
}
|
||||
|
||||
static void convert(PlayerVaults plugin) {
|
||||
Logger logger = plugin.getLogger();
|
||||
|
||||
File newDir = plugin.getVaultData();
|
||||
File oldVaults = plugin.getDataFolder().toPath().resolve("base64vaults").toFile();
|
||||
File reallyOldVaults = plugin.getDataFolder().toPath().resolve("uuidvaults").toFile();
|
||||
|
||||
if (newDir.exists()) {
|
||||
plugin.getDataFolder().toPath().resolve("oldVaultsData").toFile().mkdirs();
|
||||
if (oldVaults.exists()) {
|
||||
try {
|
||||
Files.move(oldVaults.toPath(), plugin.getDataFolder().toPath().resolve("oldVaultsData").resolve("base64vaults"));
|
||||
} catch (IOException e) {
|
||||
plugin.getLogger().warning("Failed to move old vaults dir: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
if (reallyOldVaults.exists()) {
|
||||
try {
|
||||
Files.move(reallyOldVaults.toPath(), plugin.getDataFolder().toPath().resolve("oldVaultsData").resolve("uuidvaults"));
|
||||
} catch (IOException e) {
|
||||
plugin.getLogger().warning("Failed to move old vaults dir: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
newDir.mkdirs();
|
||||
|
||||
File oldDir;
|
||||
boolean recent;
|
||||
if (oldVaults.exists() && oldVaults.isDirectory()) {
|
||||
logger.info("********** Starting data storage conversion **********");
|
||||
logger.info("This might take a while and might say \"unable to resolve\"");
|
||||
logger.info(oldVaults.toString() + " will remain as a backup.");
|
||||
recent = true;
|
||||
oldDir = oldVaults;
|
||||
} else if (reallyOldVaults.exists() && reallyOldVaults.isDirectory()) {
|
||||
logger.info("********** Starting data storage conversion **********");
|
||||
logger.info("This might take a while and might say \"unable to resolve\"");
|
||||
logger.info(reallyOldVaults.toString() + " will remain as a backup.");
|
||||
recent = false;
|
||||
oldDir = reallyOldVaults;
|
||||
} else {
|
||||
logger.info("No old vaults found to convert to new format. :)");
|
||||
return;
|
||||
}
|
||||
|
||||
int players = 0;
|
||||
int vaults = 0;
|
||||
int failed = 0;
|
||||
for (File file : oldDir.listFiles()) {
|
||||
if (file.isDirectory() || !file.getName().endsWith(".yml")) {
|
||||
continue; // backups folder.
|
||||
}
|
||||
|
||||
FileConfiguration uuidFile = YamlConfiguration.loadConfiguration(file);
|
||||
String stringUUID = file.getName().replace(".yml", "");
|
||||
|
||||
for (String key : uuidFile.getKeys(false)) {
|
||||
if (!key.startsWith("vault")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
int vaultNumber = Integer.parseInt(key.replace("vault", ""));
|
||||
|
||||
try {
|
||||
|
||||
ItemStack[] contents;
|
||||
if (recent) {
|
||||
String data = uuidFile.getString(key);
|
||||
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));
|
||||
BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);
|
||||
contents = new ItemStack[dataInput.readInt()];
|
||||
// Read the serialized inventory
|
||||
for (int i = 0; i < contents.length; i++) {
|
||||
contents[i] = (ItemStack) dataInput.readObject();
|
||||
}
|
||||
dataInput.close();
|
||||
} else {
|
||||
ConfigurationSection section = uuidFile.getConfigurationSection(key);
|
||||
List<String> data = new ArrayList<>();
|
||||
for (String s : section.getKeys(false)) {
|
||||
String value = section.getString(s);
|
||||
data.add(value);
|
||||
}
|
||||
contents = OldestSerialization.getItems(data);
|
||||
}
|
||||
String newData = Base64Coder.encodeLines(CardboardBoxSerialization.writeInventory(contents));
|
||||
uuidFile.set(key, newData);
|
||||
vaults++;
|
||||
} catch (Exception e) {
|
||||
logger.severe("Failed to parse vault " + vaultNumber + " for " + stringUUID);
|
||||
failed++;
|
||||
}
|
||||
}
|
||||
try {
|
||||
uuidFile.save(newDir.toPath().resolve(file.getName()).toFile());
|
||||
} catch (IOException e) {
|
||||
logger.severe("Failed to save new file " + file.getName());
|
||||
}
|
||||
|
||||
players++;
|
||||
}
|
||||
|
||||
logger.info(String.format("Converted %d vaults for %d players to new storage. %d failed to convert", vaults, players, failed));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,732 @@
|
||||
package com.drtshock.playervaults;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.plugin.RegisteredServiceProvider;
|
||||
import org.bukkit.plugin.ServicePriority;
|
||||
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.logging.Level;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
// CONTAINS CUSTOM MODIFICATIONS
|
||||
|
||||
/**
|
||||
* bStats collects some data for plugin authors.
|
||||
* <p>
|
||||
* Check out https://bStats.org/ to learn more about bStats!
|
||||
*/
|
||||
@SuppressWarnings({"WeakerAccess", "unused"})
|
||||
public class Metrics {
|
||||
|
||||
static {
|
||||
// Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D
|
||||
final String defaultPackage = new String(
|
||||
new byte[]{'c', 'o', 'm', '.', 'd', 'r', 't', 's', 'h', 'o', 'c', 'k', '.', 'p', 'l', 'a', 'y', 'e', 'r', 'v', 'a', 'u', 'l', 't', 's'});
|
||||
if (!Metrics.class.getPackage().getName().equals(defaultPackage)) {
|
||||
throw new IllegalStateException("You done screwed up! Go grab the right file to copy from bstats.org");
|
||||
}
|
||||
}
|
||||
|
||||
// The version of this bStats class
|
||||
public static final int B_STATS_VERSION = 1;
|
||||
|
||||
// The url to which the data is sent
|
||||
private static final String URL = "https://bStats.org/submitData/bukkit";
|
||||
|
||||
// Is bStats enabled on this server?
|
||||
private boolean enabled;
|
||||
|
||||
// Should failed requests be logged?
|
||||
private static boolean logFailedRequests;
|
||||
|
||||
// Should the sent data be logged?
|
||||
private static boolean logSentData;
|
||||
|
||||
// Should the response text be logged?
|
||||
private static boolean logResponseStatusText;
|
||||
|
||||
// The uuid of the server
|
||||
private static String serverUUID;
|
||||
|
||||
// The plugin
|
||||
private final Plugin plugin;
|
||||
|
||||
// The plugin id
|
||||
private final int pluginId;
|
||||
|
||||
// A list with all custom charts
|
||||
private final List<CustomChart> charts = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param plugin The plugin which stats should be submitted.
|
||||
* @param pluginId The id of the plugin.
|
||||
* It can be found at <a href="https://bstats.org/what-is-my-plugin-id">What is my plugin id?</a>
|
||||
*/
|
||||
public Metrics(Plugin plugin, int pluginId) {
|
||||
if (plugin == null) {
|
||||
throw new IllegalArgumentException("Plugin cannot be null!");
|
||||
}
|
||||
this.plugin = plugin;
|
||||
this.pluginId = pluginId;
|
||||
|
||||
// Get the config file
|
||||
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
|
||||
File configFile = new File(bStatsFolder, "config.yml");
|
||||
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
|
||||
|
||||
// Check if the config file exists
|
||||
if (!config.isSet("serverUuid")) {
|
||||
|
||||
// Add default values
|
||||
config.addDefault("enabled", true);
|
||||
// Every server gets it's unique random id.
|
||||
config.addDefault("serverUuid", UUID.randomUUID().toString());
|
||||
// Should failed request be logged?
|
||||
config.addDefault("logFailedRequests", false);
|
||||
// Should the sent data be logged?
|
||||
config.addDefault("logSentData", false);
|
||||
// Should the response text be logged?
|
||||
config.addDefault("logResponseStatusText", false);
|
||||
|
||||
// Inform the server owners about bStats
|
||||
config.options().header(
|
||||
"bStats collects some data for plugin authors like how many servers are using their plugins.\n" +
|
||||
"To honor their work, you should not disable it.\n" +
|
||||
"This has nearly no effect on the server performance!\n" +
|
||||
"Check out https://bStats.org/ to learn more :)"
|
||||
).copyDefaults(true);
|
||||
try {
|
||||
config.save(configFile);
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
// Load the data
|
||||
enabled = config.getBoolean("enabled", true);
|
||||
serverUUID = config.getString("serverUuid");
|
||||
logFailedRequests = config.getBoolean("logFailedRequests", false);
|
||||
logSentData = config.getBoolean("logSentData", false);
|
||||
logResponseStatusText = config.getBoolean("logResponseStatusText", false);
|
||||
|
||||
if (enabled) {
|
||||
boolean found = false;
|
||||
// Search for all other bStats Metrics classes to see if we are the first one
|
||||
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
|
||||
try {
|
||||
service.getField("B_STATS_VERSION"); // Our identifier :)
|
||||
found = true; // We aren't the first
|
||||
break;
|
||||
} catch (NoSuchFieldException ignored) {
|
||||
}
|
||||
}
|
||||
// Register our service
|
||||
Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal);
|
||||
if (!found) {
|
||||
// We are the first!
|
||||
startSubmitting();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if bStats is enabled.
|
||||
*
|
||||
* @return Whether bStats is enabled or not.
|
||||
*/
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a custom chart.
|
||||
*
|
||||
* @param chart The chart to add.
|
||||
*/
|
||||
public void addCustomChart(CustomChart chart) {
|
||||
if (chart == null) {
|
||||
throw new IllegalArgumentException("Chart cannot be null!");
|
||||
}
|
||||
charts.add(chart);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the Scheduler which submits our data every 30 minutes.
|
||||
*/
|
||||
private void startSubmitting() {
|
||||
final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
|
||||
timer.scheduleAtFixedRate(new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (!plugin.isEnabled()) { // Plugin was disabled
|
||||
timer.cancel();
|
||||
return;
|
||||
}
|
||||
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
|
||||
// Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
|
||||
Bukkit.getScheduler().runTask(plugin, () -> submitData());
|
||||
}
|
||||
}, 1000 * 60 * 5, 1000 * 60 * 30);
|
||||
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
|
||||
// WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
|
||||
// WARNING: Just don't do it!
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the plugin specific data.
|
||||
* This method is called using Reflection.
|
||||
*
|
||||
* @return The plugin specific data.
|
||||
*/
|
||||
public JsonObject getPluginData() {
|
||||
JsonObject data = new JsonObject();
|
||||
|
||||
String pluginName = "PlayerVaultsX";
|
||||
String pluginVersion = plugin.getDescription().getVersion();
|
||||
|
||||
data.addProperty("pluginName", pluginName); // Append the name of the plugin
|
||||
data.addProperty("id", pluginId); // Append the id of the plugin
|
||||
data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin
|
||||
JsonArray customCharts = new JsonArray();
|
||||
for (CustomChart customChart : charts) {
|
||||
// Add the data of the custom charts
|
||||
JsonObject chart = customChart.getRequestJsonObject();
|
||||
if (chart == null) { // If the chart is null, we skip it
|
||||
continue;
|
||||
}
|
||||
customCharts.add(chart);
|
||||
}
|
||||
data.add("customCharts", customCharts);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the server specific data.
|
||||
*
|
||||
* @return The server specific data.
|
||||
*/
|
||||
private JsonObject getServerData() {
|
||||
// Minecraft specific data
|
||||
int playerAmount;
|
||||
try {
|
||||
// Around MC 1.8 the return type was changed to a collection from an array,
|
||||
// This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
|
||||
Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
|
||||
playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
|
||||
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
|
||||
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
|
||||
} catch (Exception e) {
|
||||
playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
|
||||
}
|
||||
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
|
||||
String bukkitVersion = Bukkit.getVersion();
|
||||
String bukkitName = Bukkit.getName();
|
||||
|
||||
// OS/Java specific data
|
||||
String javaVersion = System.getProperty("java.version");
|
||||
String osName = System.getProperty("os.name");
|
||||
String osArch = System.getProperty("os.arch");
|
||||
String osVersion = System.getProperty("os.version");
|
||||
int coreCount = Runtime.getRuntime().availableProcessors();
|
||||
|
||||
JsonObject data = new JsonObject();
|
||||
|
||||
data.addProperty("serverUUID", serverUUID);
|
||||
|
||||
data.addProperty("playerAmount", playerAmount);
|
||||
data.addProperty("onlineMode", onlineMode);
|
||||
data.addProperty("bukkitVersion", bukkitVersion);
|
||||
data.addProperty("bukkitName", bukkitName);
|
||||
|
||||
data.addProperty("javaVersion", javaVersion);
|
||||
data.addProperty("osName", osName);
|
||||
data.addProperty("osArch", osArch);
|
||||
data.addProperty("osVersion", osVersion);
|
||||
data.addProperty("coreCount", coreCount);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects the data and sends it afterwards.
|
||||
*/
|
||||
private void submitData() {
|
||||
final JsonObject data = getServerData();
|
||||
|
||||
JsonArray pluginData = new JsonArray();
|
||||
// Search for all other bStats Metrics classes to get their plugin data
|
||||
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
|
||||
try {
|
||||
service.getField("B_STATS_VERSION"); // Our identifier :)
|
||||
|
||||
for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {
|
||||
try {
|
||||
Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider());
|
||||
if (plugin instanceof JsonObject) {
|
||||
pluginData.add((JsonObject) plugin);
|
||||
} else { // old bstats version compatibility
|
||||
try {
|
||||
Class<?> jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject");
|
||||
if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) {
|
||||
Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString");
|
||||
jsonStringGetter.setAccessible(true);
|
||||
String jsonString = (String) jsonStringGetter.invoke(plugin);
|
||||
JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject();
|
||||
pluginData.add(object);
|
||||
}
|
||||
} catch (ClassNotFoundException e) {
|
||||
// minecraft version 1.14+
|
||||
if (logFailedRequests) {
|
||||
this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
|
||||
}
|
||||
}
|
||||
} catch (NoSuchFieldException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
data.add("plugins", pluginData);
|
||||
|
||||
// Create a new thread for the connection to the bStats server
|
||||
new Thread(() -> {
|
||||
try {
|
||||
// Send the data
|
||||
sendData(plugin, data);
|
||||
} catch (Exception e) {
|
||||
// Something went wrong! :(
|
||||
if (logFailedRequests) {
|
||||
plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the data to the bStats server.
|
||||
*
|
||||
* @param plugin Any plugin. It's just used to get a logger instance.
|
||||
* @param data The data to send.
|
||||
* @throws Exception If the request failed.
|
||||
*/
|
||||
private static void sendData(Plugin plugin, JsonObject data) throws Exception {
|
||||
if (data == null) {
|
||||
throw new IllegalArgumentException("Data cannot be null!");
|
||||
}
|
||||
if (Bukkit.isPrimaryThread()) {
|
||||
throw new IllegalAccessException("This method must not be called from the main thread!");
|
||||
}
|
||||
if (logSentData) {
|
||||
plugin.getLogger().info("Sending data to bStats: " + data);
|
||||
}
|
||||
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
|
||||
|
||||
// Compress the data to save bandwidth
|
||||
byte[] compressedData = compress(data.toString());
|
||||
|
||||
// Add headers
|
||||
connection.setRequestMethod("POST");
|
||||
connection.addRequestProperty("Accept", "application/json");
|
||||
connection.addRequestProperty("Connection", "close");
|
||||
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
|
||||
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
|
||||
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
|
||||
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
|
||||
|
||||
// Send data
|
||||
connection.setDoOutput(true);
|
||||
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
|
||||
outputStream.write(compressedData);
|
||||
}
|
||||
|
||||
StringBuilder builder = new StringBuilder();
|
||||
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
|
||||
String line;
|
||||
while ((line = bufferedReader.readLine()) != null) {
|
||||
builder.append(line);
|
||||
}
|
||||
}
|
||||
|
||||
if (logResponseStatusText) {
|
||||
plugin.getLogger().info("Sent data to bStats and received response: " + builder);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gzips the given String.
|
||||
*
|
||||
* @param str The string to gzip.
|
||||
* @return The gzipped String.
|
||||
* @throws IOException If the compression failed.
|
||||
*/
|
||||
private static byte[] compress(final String str) throws IOException {
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) {
|
||||
gzip.write(str.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
return outputStream.toByteArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a custom chart.
|
||||
*/
|
||||
public static abstract class CustomChart {
|
||||
|
||||
// The id of the chart
|
||||
final String chartId;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
*/
|
||||
CustomChart(String chartId) {
|
||||
if (chartId == null || chartId.isEmpty()) {
|
||||
throw new IllegalArgumentException("ChartId cannot be null or empty!");
|
||||
}
|
||||
this.chartId = chartId;
|
||||
}
|
||||
|
||||
private JsonObject getRequestJsonObject() {
|
||||
JsonObject chart = new JsonObject();
|
||||
chart.addProperty("chartId", chartId);
|
||||
try {
|
||||
JsonObject data = getChartData();
|
||||
if (data == null) {
|
||||
// If the data is null we don't send the chart.
|
||||
return null;
|
||||
}
|
||||
chart.add("data", data);
|
||||
} catch (Throwable t) {
|
||||
if (logFailedRequests) {
|
||||
Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return chart;
|
||||
}
|
||||
|
||||
protected abstract JsonObject getChartData() throws Exception;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a custom simple pie.
|
||||
*/
|
||||
public static class SimplePie extends CustomChart {
|
||||
|
||||
private final Callable<String> callable;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public SimplePie(String chartId, Callable<String> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObject getChartData() throws Exception {
|
||||
JsonObject data = new JsonObject();
|
||||
String value = callable.call();
|
||||
if (value == null || value.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
data.addProperty("value", value);
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a custom advanced pie.
|
||||
*/
|
||||
public static class AdvancedPie extends CustomChart {
|
||||
|
||||
private final Callable<Map<String, Integer>> callable;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObject getChartData() throws Exception {
|
||||
JsonObject data = new JsonObject();
|
||||
JsonObject values = new JsonObject();
|
||||
Map<String, Integer> map = callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
boolean allSkipped = true;
|
||||
for (Map.Entry<String, Integer> entry : map.entrySet()) {
|
||||
if (entry.getValue() == 0) {
|
||||
continue; // Skip this invalid
|
||||
}
|
||||
allSkipped = false;
|
||||
values.addProperty(entry.getKey(), entry.getValue());
|
||||
}
|
||||
if (allSkipped) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
data.add("values", values);
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a custom drilldown pie.
|
||||
*/
|
||||
public static class DrilldownPie extends CustomChart {
|
||||
|
||||
private final Callable<Map<String, Map<String, Integer>>> callable;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JsonObject getChartData() throws Exception {
|
||||
JsonObject data = new JsonObject();
|
||||
JsonObject values = new JsonObject();
|
||||
Map<String, Map<String, Integer>> map = callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
boolean reallyAllSkipped = true;
|
||||
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
|
||||
JsonObject value = new JsonObject();
|
||||
boolean allSkipped = true;
|
||||
for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
|
||||
value.addProperty(valueEntry.getKey(), valueEntry.getValue());
|
||||
allSkipped = false;
|
||||
}
|
||||
if (!allSkipped) {
|
||||
reallyAllSkipped = false;
|
||||
values.add(entryValues.getKey(), value);
|
||||
}
|
||||
}
|
||||
if (reallyAllSkipped) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
data.add("values", values);
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a custom single line chart.
|
||||
*/
|
||||
public static class SingleLineChart extends CustomChart {
|
||||
|
||||
private final Callable<Integer> callable;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public SingleLineChart(String chartId, Callable<Integer> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObject getChartData() throws Exception {
|
||||
JsonObject data = new JsonObject();
|
||||
int value = callable.call();
|
||||
if (value == 0) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
data.addProperty("value", value);
|
||||
return data;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a custom multi line chart.
|
||||
*/
|
||||
public static class MultiLineChart extends CustomChart {
|
||||
|
||||
private final Callable<Map<String, Integer>> callable;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObject getChartData() throws Exception {
|
||||
JsonObject data = new JsonObject();
|
||||
JsonObject values = new JsonObject();
|
||||
Map<String, Integer> map = callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
boolean allSkipped = true;
|
||||
for (Map.Entry<String, Integer> entry : map.entrySet()) {
|
||||
if (entry.getValue() == 0) {
|
||||
continue; // Skip this invalid
|
||||
}
|
||||
allSkipped = false;
|
||||
values.addProperty(entry.getKey(), entry.getValue());
|
||||
}
|
||||
if (allSkipped) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
data.add("values", values);
|
||||
return data;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a custom simple bar chart.
|
||||
*/
|
||||
public static class SimpleBarChart extends CustomChart {
|
||||
|
||||
private final Callable<Map<String, Integer>> callable;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObject getChartData() throws Exception {
|
||||
JsonObject data = new JsonObject();
|
||||
JsonObject values = new JsonObject();
|
||||
Map<String, Integer> map = callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
for (Map.Entry<String, Integer> entry : map.entrySet()) {
|
||||
JsonArray categoryValues = new JsonArray();
|
||||
categoryValues.add(new JsonPrimitive(entry.getValue()));
|
||||
values.add(entry.getKey(), categoryValues);
|
||||
}
|
||||
data.add("values", values);
|
||||
return data;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a custom advanced bar chart.
|
||||
*/
|
||||
public static class AdvancedBarChart extends CustomChart {
|
||||
|
||||
private final Callable<Map<String, int[]>> callable;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObject getChartData() throws Exception {
|
||||
JsonObject data = new JsonObject();
|
||||
JsonObject values = new JsonObject();
|
||||
Map<String, int[]> map = callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
boolean allSkipped = true;
|
||||
for (Map.Entry<String, int[]> entry : map.entrySet()) {
|
||||
if (entry.getValue().length == 0) {
|
||||
continue; // Skip this invalid
|
||||
}
|
||||
allSkipped = false;
|
||||
JsonArray categoryValues = new JsonArray();
|
||||
for (int categoryValue : entry.getValue()) {
|
||||
categoryValues.add(new JsonPrimitive(categoryValue));
|
||||
}
|
||||
values.add(entry.getKey(), categoryValues);
|
||||
}
|
||||
if (allSkipped) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
data.add("values", values);
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,569 @@
|
||||
/*
|
||||
* PlayerVaultsX
|
||||
* Copyright (C) 2013 Trent Hensler
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.drtshock.playervaults;
|
||||
|
||||
import com.drtshock.playervaults.commands.*;
|
||||
import com.drtshock.playervaults.config.Loader;
|
||||
import com.drtshock.playervaults.config.file.Config;
|
||||
import com.drtshock.playervaults.config.file.Translation;
|
||||
import com.drtshock.playervaults.data.PlayerVaultsManager;
|
||||
import com.drtshock.playervaults.listeners.Listeners;
|
||||
import com.drtshock.playervaults.listeners.SignListener;
|
||||
import com.drtshock.playervaults.listeners.VaultPreloadListener;
|
||||
import com.drtshock.playervaults.tasks.Cleanup;
|
||||
import com.drtshock.playervaults.vaultmanagement.EconomyOperations;
|
||||
import com.drtshock.playervaults.vaultmanagement.VaultManager;
|
||||
import com.drtshock.playervaults.vaultmanagement.VaultViewInfo;
|
||||
import lombok.Getter;
|
||||
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.configuration.InvalidConfigurationException;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
import sun.misc.Unsafe;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.file.Files;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.logging.Level;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class PlayerVaults extends JavaPlugin {
|
||||
public static boolean DEBUG;
|
||||
private static PlayerVaults instance;
|
||||
private final HashMap<String, SignSetInfo> setSign = new HashMap<>();
|
||||
// Player name - VaultViewInfo
|
||||
private final HashMap<String, VaultViewInfo> inVault = new HashMap<>();
|
||||
// VaultViewInfo - Inventory
|
||||
private final HashMap<String, Inventory> openInventories = new HashMap<>();
|
||||
private final Set<Material> blockedMats = new HashSet<>();
|
||||
private boolean useVault;
|
||||
private YamlConfiguration signs;
|
||||
private File signsFile;
|
||||
private boolean saveQueued;
|
||||
private boolean backupsEnabled;
|
||||
private File backupsFolder;
|
||||
private File uuidData;
|
||||
private File vaultData;
|
||||
private String _versionString;
|
||||
private int maxVaultAmountPermTest;
|
||||
private Metrics metrics;
|
||||
private final Config config = new Config();
|
||||
private BukkitAudiences platform;
|
||||
private final Translation translation = new Translation(this);
|
||||
private final List<String> exceptions = new CopyOnWriteArrayList<>();
|
||||
@Getter
|
||||
private PlayerVaultsManager playerVaultsManager;
|
||||
|
||||
public static PlayerVaults getInstance() {
|
||||
return instance;
|
||||
}
|
||||
|
||||
public static void debug(String s, long start) {
|
||||
if (DEBUG) {
|
||||
instance.getLogger().log(Level.INFO, "{0} took {1}ms", new Object[]{s, (System.currentTimeMillis() - start)});
|
||||
}
|
||||
}
|
||||
|
||||
public static void debug(String s) {
|
||||
if (DEBUG) {
|
||||
instance.getLogger().log(Level.INFO, s);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
instance = this;
|
||||
long start = System.currentTimeMillis();
|
||||
long time = System.currentTimeMillis();
|
||||
this.platform = BukkitAudiences.create(this);
|
||||
debug("adventure!", time);
|
||||
time = System.currentTimeMillis();
|
||||
loadConfig();
|
||||
DEBUG = getConf().isDebug();
|
||||
debug("config", time);
|
||||
time = System.currentTimeMillis();
|
||||
vaultData = new File(this.getDataFolder(), "newvaults");
|
||||
Conversion.convert(this);
|
||||
new VaultManager(this);
|
||||
debug("conversion", time);
|
||||
time = System.currentTimeMillis();
|
||||
debug("uuidvaultmanager", time);
|
||||
time = System.currentTimeMillis();
|
||||
getServer().getPluginManager().registerEvents(new Listeners(this), this);
|
||||
getServer().getPluginManager().registerEvents(new VaultPreloadListener(), this);
|
||||
getServer().getPluginManager().registerEvents(new SignListener(this), this);
|
||||
debug("registering listeners", time);
|
||||
time = System.currentTimeMillis();
|
||||
this.backupsEnabled = this.getConf().getStorage().getFlatFile().isBackups();
|
||||
this.maxVaultAmountPermTest = this.getConf().getMaxVaultAmountPermTest();
|
||||
loadSigns();
|
||||
debug("loaded signs", time);
|
||||
time = System.currentTimeMillis();
|
||||
getCommand("pv").setExecutor(new VaultCommand(this));
|
||||
getCommand("pvdel").setExecutor(new DeleteCommand(this));
|
||||
getCommand("pvconvert").setExecutor(new ConvertCommand(this));
|
||||
getCommand("pvsign").setExecutor(new SignCommand(this));
|
||||
this.getCommand("pvsearch").setExecutor(new SearchCommand());
|
||||
debug("registered commands", time);
|
||||
time = System.currentTimeMillis();
|
||||
useVault = EconomyOperations.setup();
|
||||
debug("setup economy", time);
|
||||
|
||||
if (getConf().getPurge().isEnabled()) {
|
||||
getServer().getScheduler().runTaskAsynchronously(this, new Cleanup(getConf().getPurge().getDaysSinceLastEdit()));
|
||||
}
|
||||
|
||||
new BukkitRunnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (saveQueued) {
|
||||
saveSignsFile();
|
||||
}
|
||||
}
|
||||
}.runTaskTimer(this, 20, 20);
|
||||
|
||||
this.metrics = new Metrics(this, 6905);
|
||||
Plugin vault = getServer().getPluginManager().getPlugin("Vault");
|
||||
this.metricsDrillPie("vault", () -> this.metricsPluginInfo(vault));
|
||||
if (vault != null) {
|
||||
this.metricsDrillPie("vault_econ", () -> {
|
||||
Map<String, Map<String, Integer>> map = new HashMap<>();
|
||||
Map<String, Integer> entry = new HashMap<>();
|
||||
entry.put(!this.useVault ? "none" : EconomyOperations.getName(), 1);
|
||||
map.put(isEconomyEnabled() ? "enabled" : "disabled", entry);
|
||||
return map;
|
||||
});
|
||||
if (isEconomyEnabled()) {
|
||||
String name = EconomyOperations.getName();
|
||||
if (name.equals("Essentials Economy")) {
|
||||
name = "Essentials";
|
||||
}
|
||||
if (name.equals("CMIEconomy")) {
|
||||
name = "CMI";
|
||||
}
|
||||
Plugin plugin = getServer().getPluginManager().getPlugin(name);
|
||||
if (plugin != null) {
|
||||
this.metricsDrillPie("vault_econ_plugins", () -> {
|
||||
Map<String, Map<String, Integer>> map = new HashMap<>();
|
||||
Map<String, Integer> entry = new HashMap<>();
|
||||
entry.put(plugin.getDescription().getVersion(), 1);
|
||||
map.put(plugin.getName(), entry);
|
||||
return map;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (vault != null) {
|
||||
String name = EconomyOperations.getPermsName();
|
||||
if (name != null) {
|
||||
Plugin plugin = getServer().getPluginManager().getPlugin(name);
|
||||
final String version;
|
||||
if (plugin == null) {
|
||||
version = "unknown";
|
||||
} else {
|
||||
version = plugin.getDescription().getVersion();
|
||||
}
|
||||
this.metricsDrillPie("vault_perms", () -> {
|
||||
Map<String, Map<String, Integer>> map = new HashMap<>();
|
||||
Map<String, Integer> entry = new HashMap<>();
|
||||
entry.put(version, 1);
|
||||
map.put(name, entry);
|
||||
return map;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
this.metricsSimplePie("signs", () -> getConf().isSigns() ? "enabled" : "disabled");
|
||||
this.metricsSimplePie("cleanup", () -> getConf().getPurge().isEnabled() ? "enabled" : "disabled");
|
||||
|
||||
this.metricsDrillPie("block_items", () -> {
|
||||
Map<String, Map<String, Integer>> map = new HashMap<>();
|
||||
Map<String, Integer> entry = new HashMap<>();
|
||||
if (getConf().getItemBlocking().isEnabled()) {
|
||||
for (Material material : blockedMats) {
|
||||
entry.put(material.toString(), 1);
|
||||
}
|
||||
}
|
||||
if (entry.isEmpty()) {
|
||||
entry.put("none", 1);
|
||||
}
|
||||
map.put(getConf().getItemBlocking().isEnabled() ? "enabled" : "disabled", entry);
|
||||
return map;
|
||||
});
|
||||
|
||||
try {
|
||||
Field f = Unsafe.class.getDeclaredField("theUnsafe");
|
||||
f.setAccessible(true);
|
||||
Unsafe unsafe = (Unsafe) f.get(null);
|
||||
|
||||
Class<?> clazz = Class.forName(this.getServer().getClass().getPackage().getName() + ".util.CraftNBTTagConfigSerializer");
|
||||
Field field = clazz.getDeclaredField("INTEGER");
|
||||
|
||||
Pattern pattern = (Pattern) unsafe.getObject(clazz, unsafe.staticFieldOffset(field));
|
||||
|
||||
if (pattern.pattern().equals("[-+]?(?:0|[1-9][0-9]*)?i")) {
|
||||
unsafe.putObject(clazz, unsafe.staticFieldOffset(field), Pattern.compile("[-+]?(?:0|[1-9][0-9]*)i", Pattern.CASE_INSENSITIVE));
|
||||
this.getLogger().info("Patched Spigot item storage bug.");
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// Don't worry about it.
|
||||
}
|
||||
|
||||
this.playerVaultsManager = new PlayerVaultsManager();
|
||||
this.playerVaultsManager.loadAll();
|
||||
|
||||
this.getLogger().info("Loaded! Took " + (System.currentTimeMillis() - start) + "ms");
|
||||
}
|
||||
|
||||
private void metricsLine(String name, Callable<Integer> callable) {
|
||||
this.metrics.addCustomChart(new Metrics.SingleLineChart(name, callable));
|
||||
}
|
||||
|
||||
private void metricsDrillPie(String name, Callable<Map<String, Map<String, Integer>>> callable) {
|
||||
this.metrics.addCustomChart(new Metrics.DrilldownPie(name, callable));
|
||||
}
|
||||
|
||||
private void metricsSimplePie(String name, Callable<String> callable) {
|
||||
this.metrics.addCustomChart(new Metrics.SimplePie(name, callable));
|
||||
}
|
||||
|
||||
private Map<String, Map<String, Integer>> metricsPluginInfo(Plugin plugin) {
|
||||
return this.metricsInfo(plugin, () -> plugin.getDescription().getVersion());
|
||||
}
|
||||
|
||||
private Map<String, Map<String, Integer>> metricsInfo(Object plugin, Supplier<String> versionGetter) {
|
||||
Map<String, Map<String, Integer>> map = new HashMap<>();
|
||||
Map<String, Integer> entry = new HashMap<>();
|
||||
entry.put(plugin == null ? "nope" : versionGetter.get(), 1);
|
||||
map.put(plugin == null ? "absent" : "present", entry);
|
||||
return map;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
for (Player player : Bukkit.getOnlinePlayers()) {
|
||||
if (this.inVault.containsKey(player.getUniqueId().toString())) {
|
||||
Inventory inventory = player.getOpenInventory().getTopInventory();
|
||||
if (inventory.getViewers().size() == 1) {
|
||||
VaultViewInfo info = this.inVault.get(player.getUniqueId().toString());
|
||||
VaultManager.getInstance().saveVault(inventory, player.getUniqueId().toString(), info.getNumber());
|
||||
this.openInventories.remove(info.toString());
|
||||
// try this to make sure that they can't make further edits if the process hangs.
|
||||
player.closeInventory();
|
||||
}
|
||||
|
||||
this.inVault.remove(player.getUniqueId().toString());
|
||||
debug("Closing vault for " + player.getName());
|
||||
player.closeInventory();
|
||||
}
|
||||
}
|
||||
|
||||
if (getConf().getPurge().isEnabled()) {
|
||||
saveSignsFile();
|
||||
}
|
||||
|
||||
VaultManager.getInstance().getVaultCache().shutdown();
|
||||
|
||||
this.playerVaultsManager.saveAll();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
|
||||
if (cmd.getName().equalsIgnoreCase("pvreload")) {
|
||||
reloadConfig();
|
||||
loadConfig(); // To update blocked materials.
|
||||
reloadSigns();
|
||||
sender.sendMessage(ChatColor.GREEN + "Reloaded PlayerVault's configuration and lang files.");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void loadConfig() {
|
||||
File configYaml = new File(this.getDataFolder(), "config.yml");
|
||||
if (!(new File(this.getDataFolder(), "config.conf").exists()) && configYaml.exists()) {
|
||||
this.config.setFromConfig(this.getLogger(), this.getConfig());
|
||||
try {
|
||||
Files.move(configYaml.toPath(), this.getDataFolder().toPath().resolve("old_unused_config.yml"));
|
||||
} catch (Exception e) {
|
||||
this.getLogger().log(Level.SEVERE, "Failed to move config for backup: " + e.getMessage());
|
||||
configYaml.deleteOnExit();
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
Loader.loadAndSave("config", this.config);
|
||||
} catch (IOException | IllegalAccessException e) {
|
||||
this.getLogger().log(Level.SEVERE, "Could not load config.", e);
|
||||
}
|
||||
|
||||
// Clear just in case this is a reload.
|
||||
blockedMats.clear();
|
||||
if (getConf().getItemBlocking().isEnabled()) {
|
||||
for (String s : getConf().getItemBlocking().getList()) {
|
||||
Material mat = Material.matchMaterial(s);
|
||||
if (mat != null) {
|
||||
blockedMats.add(mat);
|
||||
getLogger().log(Level.INFO, "Added {0} to list of blocked materials.", mat.name());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File lang = new File(this.getDataFolder(), "lang");
|
||||
if (lang.exists()) {
|
||||
this.getLogger().warning("There is no clean way for us to migrate your old lang data.");
|
||||
this.getLogger().warning("If you made any customizations, or used another language, you need to migrate the info to the new format in lang.conf");
|
||||
try {
|
||||
Files.move(lang.toPath(), lang.getParentFile().toPath().resolve("old_unused_lang"));
|
||||
} catch (Exception e) {
|
||||
this.getLogger().log(Level.SEVERE, "Failed to rename lang folder as it is no longer used: " + e.getMessage());
|
||||
configYaml.deleteOnExit();
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
Loader.loadAndSave("lang", this.translation);
|
||||
} catch (IOException | IllegalAccessException e) {
|
||||
this.getLogger().log(Level.SEVERE, "Could not load lang.", e);
|
||||
}
|
||||
}
|
||||
|
||||
public Config getConf() {
|
||||
return this.config;
|
||||
}
|
||||
|
||||
private void loadSigns() {
|
||||
File signs = new File(getDataFolder(), "signs.yml");
|
||||
if (!signs.exists()) {
|
||||
try {
|
||||
signs.createNewFile();
|
||||
} catch (IOException e) {
|
||||
getLogger().severe("PlayerVaults has encountered a fatal error trying to load the signs file.");
|
||||
getLogger().severe("Please report this error on GitHub @ https://github.com/drtshock/PlayerVaults/");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
this.signsFile = signs;
|
||||
this.signs = YamlConfiguration.loadConfiguration(signs);
|
||||
}
|
||||
|
||||
private void reloadSigns() {
|
||||
if (!getConf().isSigns()) {
|
||||
return;
|
||||
}
|
||||
if (!signsFile.exists()) loadSigns();
|
||||
try {
|
||||
signs.load(signsFile);
|
||||
} catch (IOException | InvalidConfigurationException e) {
|
||||
getLogger().severe("PlayerVaults has encountered a fatal error trying to reload the signs file.");
|
||||
getLogger().severe("Please report this error on GitHub @ https://github.com/drtshock/PlayerVaults/");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the signs.yml config.
|
||||
*
|
||||
* @return The signs.yml config.
|
||||
*/
|
||||
public YamlConfiguration getSigns() {
|
||||
return this.signs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the signs.yml file.
|
||||
*/
|
||||
public void saveSigns() {
|
||||
saveQueued = true;
|
||||
}
|
||||
|
||||
private void saveSignsFile() {
|
||||
if (!getConf().isSigns()) {
|
||||
return;
|
||||
}
|
||||
|
||||
saveQueued = false;
|
||||
try {
|
||||
signs.save(this.signsFile);
|
||||
} catch (IOException e) {
|
||||
getLogger().severe("PlayerVaults has encountered an error trying to save the signs file.");
|
||||
getLogger().severe("Please report this error on GitHub @ https://github.com/drtshock/PlayerVaults/");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public HashMap<String, SignSetInfo> getSetSign() {
|
||||
return this.setSign;
|
||||
}
|
||||
|
||||
public HashMap<String, VaultViewInfo> getInVault() {
|
||||
return this.inVault;
|
||||
}
|
||||
|
||||
public HashMap<String, Inventory> getOpenInventories() {
|
||||
return this.openInventories;
|
||||
}
|
||||
|
||||
public boolean isEconomyEnabled() {
|
||||
return this.getConf().getEconomy().isEnabled() && this.useVault;
|
||||
}
|
||||
|
||||
public File getVaultData() {
|
||||
return this.vaultData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the legacy UUID vault data folder.
|
||||
* Deprecated in favor of base64 data.
|
||||
*
|
||||
* @return uuid folder
|
||||
*/
|
||||
@Deprecated
|
||||
public File getUuidData() {
|
||||
return this.uuidData;
|
||||
}
|
||||
|
||||
public boolean isBackupsEnabled() {
|
||||
return this.backupsEnabled;
|
||||
}
|
||||
|
||||
public File getBackupsFolder() {
|
||||
// having this in #onEnable() creates the 'uuidvaults' directory, preventing the conversion from running
|
||||
if (this.backupsFolder == null) {
|
||||
this.backupsFolder = new File(this.getVaultData(), "backups");
|
||||
this.backupsFolder.mkdirs();
|
||||
}
|
||||
|
||||
return this.backupsFolder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to get a name from a given String that we hope is a UUID.
|
||||
*
|
||||
* @param potentialUUID - potential UUID to try to get the name for.
|
||||
* @return the player's name if we can find it, otherwise return what got passed to us.
|
||||
*/
|
||||
public String getNameIfPlayer(String potentialUUID) {
|
||||
UUID uuid;
|
||||
try {
|
||||
uuid = UUID.fromString(potentialUUID);
|
||||
} catch (Exception e) {
|
||||
return potentialUUID;
|
||||
}
|
||||
|
||||
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid);
|
||||
return offlinePlayer != null ? offlinePlayer.getName() : potentialUUID;
|
||||
}
|
||||
|
||||
public boolean isBlockedMaterial(Material mat) {
|
||||
return blockedMats.contains(mat);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to grab the server version as a string.
|
||||
*
|
||||
* @return Version as raw string
|
||||
*/
|
||||
public String getVersion() {
|
||||
if (_versionString == null) {
|
||||
final String name = Bukkit.getServer().getClass().getPackage().getName();
|
||||
_versionString = name.substring(name.lastIndexOf(46) + 1) + ".";
|
||||
}
|
||||
return _versionString;
|
||||
}
|
||||
|
||||
public int getDefaultVaultRows() {
|
||||
int def = this.config.getDefaultVaultRows();
|
||||
return (def >= 1 && def <= 6) ? def : 6;
|
||||
}
|
||||
|
||||
public int getDefaultVaultSize() {
|
||||
return this.getDefaultVaultRows() * 9;
|
||||
}
|
||||
|
||||
public boolean isSign(Material mat) {
|
||||
return mat.name().toUpperCase().contains("SIGN");
|
||||
}
|
||||
|
||||
public int getMaxVaultAmountPermTest() {
|
||||
return this.maxVaultAmountPermTest;
|
||||
}
|
||||
|
||||
public BukkitAudiences getPlatform() {
|
||||
return this.platform;
|
||||
}
|
||||
|
||||
public Translation getTL() {
|
||||
return this.translation;
|
||||
}
|
||||
|
||||
public String getVaultTitle(String id) {
|
||||
return this.translation.vaultTitle().with("vault", id).getLegacy();
|
||||
}
|
||||
|
||||
public String getExceptions() {
|
||||
if (this.exceptions.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
StringBuilder builder = new StringBuilder();
|
||||
boolean more = false;
|
||||
for (String e : this.exceptions) {
|
||||
if (more) {
|
||||
builder.append("\n\n");
|
||||
} else {
|
||||
more = true;
|
||||
}
|
||||
builder.append(e);
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
public <T extends Throwable> T addException(T t) {
|
||||
if (this.getConf().isDebug()) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append(ZonedDateTime.now(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss"))).append('\n');
|
||||
StringWriter stringWriter = new StringWriter();
|
||||
PrintWriter printWriter = new PrintWriter(stringWriter);
|
||||
t.printStackTrace(printWriter);
|
||||
builder.append(stringWriter.toString());
|
||||
this.exceptions.add(builder.toString());
|
||||
}
|
||||
return t;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* PlayerVaultsX
|
||||
* Copyright (C) 2013 Trent Hensler
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.drtshock.playervaults.commands;
|
||||
|
||||
import com.drtshock.playervaults.PlayerVaults;
|
||||
import com.drtshock.playervaults.converters.BackpackConverter;
|
||||
import com.drtshock.playervaults.converters.Converter;
|
||||
import com.drtshock.playervaults.vaultmanagement.VaultOperations;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandExecutor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ConvertCommand implements CommandExecutor {
|
||||
|
||||
private final List<Converter> converters = new ArrayList<>();
|
||||
private final PlayerVaults plugin;
|
||||
|
||||
public ConvertCommand(PlayerVaults plugin) {
|
||||
converters.add(new BackpackConverter());
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(final CommandSender sender, Command command, String label, String[] args) {
|
||||
if (!sender.hasPermission("playervaults.convert")) {
|
||||
this.plugin.getTL().noPerms().title().send(sender);
|
||||
} else {
|
||||
if (args.length == 0) {
|
||||
sender.sendMessage("/" + label + " <all | plugin name>");
|
||||
} else {
|
||||
String name = args[0];
|
||||
final List<Converter> applicableConverters = new ArrayList<>();
|
||||
if (name.equalsIgnoreCase("all")) {
|
||||
applicableConverters.addAll(converters);
|
||||
} else {
|
||||
for (Converter converter : converters) {
|
||||
if (converter.getName().equalsIgnoreCase(name)) {
|
||||
applicableConverters.add(converter);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (applicableConverters.size() <= 0) {
|
||||
this.plugin.getTL().convertPluginNotFound().title().send(sender);
|
||||
} else {
|
||||
// Fork into background
|
||||
this.plugin.getTL().convertBackground().title().send(sender);
|
||||
PlayerVaults.getInstance().getServer().getScheduler().runTaskLaterAsynchronously(PlayerVaults.getInstance(), () -> {
|
||||
int converted = 0;
|
||||
VaultOperations.setLocked(true);
|
||||
for (Converter converter : applicableConverters) {
|
||||
if (converter.canConvert()) {
|
||||
converted += converter.run(sender);
|
||||
}
|
||||
}
|
||||
VaultOperations.setLocked(false);
|
||||
this.plugin.getTL().convertComplete().title().with("count", converted + "").send(sender);
|
||||
}, 5);
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* PlayerVaultsX
|
||||
* Copyright (C) 2013 Trent Hensler
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.drtshock.playervaults.commands;
|
||||
|
||||
import com.drtshock.playervaults.PlayerVaults;
|
||||
import com.drtshock.playervaults.vaultmanagement.VaultManager;
|
||||
import com.drtshock.playervaults.vaultmanagement.VaultOperations;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandExecutor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class DeleteCommand implements CommandExecutor {
|
||||
private final PlayerVaults plugin;
|
||||
|
||||
public DeleteCommand(PlayerVaults plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (VaultOperations.isLocked()) {
|
||||
this.plugin.getTL().locked().title().send(sender);
|
||||
return true;
|
||||
}
|
||||
switch (args.length) {
|
||||
case 1:
|
||||
if (sender instanceof Player) {
|
||||
VaultOperations.deleteOwnVault((Player) sender, args[0]);
|
||||
} else {
|
||||
this.plugin.getTL().playerOnly().title().send(sender);
|
||||
}
|
||||
break;
|
||||
case 2:
|
||||
OfflinePlayer searchPlayer = Bukkit.getOfflinePlayer(args[0]);
|
||||
String target = args[0];
|
||||
if (searchPlayer != null && searchPlayer.hasPlayedBefore()) {
|
||||
target = searchPlayer.getUniqueId().toString();
|
||||
}
|
||||
|
||||
// TODO: fix the stupid message inconsistencies where sometimes this class sends, sometimes vaultops does.
|
||||
if (args[1].equalsIgnoreCase("all")) {
|
||||
if (sender.hasPermission("playervaults.delete.all")) {
|
||||
VaultManager.getInstance().deleteAllVaults(target);
|
||||
this.plugin.getTL().deleteOtherVaultAll().title().with("player", target).send(sender);
|
||||
PlayerVaults.getInstance().getLogger().info(String.format("%s deleted ALL vaults belonging to %s", sender.getName(), target));
|
||||
} else {
|
||||
this.plugin.getTL().noPerms().title().send(sender);
|
||||
}
|
||||
|
||||
}
|
||||
VaultOperations.deleteOtherVault(sender, target, args[1]);
|
||||
break;
|
||||
default:
|
||||
sender.sendMessage("/" + label + " <number>");
|
||||
sender.sendMessage("/" + label + " <player> <number>");
|
||||
sender.sendMessage("/" + label + " <player> all");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package com.drtshock.playervaults.commands;
|
||||
|
||||
|
||||
import com.drtshock.playervaults.PlayerVaults;
|
||||
import com.drtshock.playervaults.guis.SearchGUI;
|
||||
import com.drtshock.playervaults.utils.CC;
|
||||
import com.drtshock.playervaults.vaultmanagement.VaultManager;
|
||||
import com.drtshock.playervaults.vaultmanagement.VaultOperations;
|
||||
import com.drtshock.playervaults.vaultmanagement.VaultViewInfo;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandExecutor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class SearchCommand implements CommandExecutor {
|
||||
public boolean onCommand(CommandSender commandSender, Command command, String s, String[] array) {
|
||||
if (VaultOperations.isLocked()) {
|
||||
commandSender.sendMessage(CC.translate("&b&lVaults &8➥ &7Vaults are locked!"));
|
||||
return true;
|
||||
} else {
|
||||
switch(array.length) {
|
||||
case 0:
|
||||
if (commandSender instanceof Player) {
|
||||
commandSender.sendMessage(CC.translate("&b&lVaults &8➥ &7/pvsearch <Item Name>"));
|
||||
if (commandSender.hasPermission("playervaults.search.other")) {
|
||||
commandSender.sendMessage(CC.translate("&b&lVaults &8➥ &7/pvsearch <item name> <Player>"));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
case 1:
|
||||
if (commandSender instanceof Player) {
|
||||
this.search((Player)commandSender, array[0], (Player)commandSender);
|
||||
} else {
|
||||
commandSender.sendMessage(CC.translate("&b&lVaults &8➥ &7Only players can execute this command!"));
|
||||
}
|
||||
|
||||
return true;
|
||||
case 2:
|
||||
if (!(commandSender instanceof Player)) {
|
||||
return true;
|
||||
} else if (!commandSender.hasPermission("playervaults.search.other")) {
|
||||
commandSender.sendMessage(CC.translate("&b&lVaults &8➥ &7No perms to search other players' pv!"));
|
||||
return true;
|
||||
} else {
|
||||
if (Bukkit.getPlayer(array[1]) == null) {
|
||||
commandSender.sendMessage(CC.translate("&b&lVaults &8➥ &7No online player found with this name"));
|
||||
return true;
|
||||
}
|
||||
|
||||
this.search((Player)commandSender, array[0], Bukkit.getPlayer(array[1]));
|
||||
return true;
|
||||
}
|
||||
default:
|
||||
commandSender.sendMessage(CC.translate("&b&lVaults &8➥ &7/pvsearch <item name>"));
|
||||
if (commandSender.hasPermission("playervaults.search.other")) {
|
||||
commandSender.sendMessage(CC.translate("&b&lVaults &8➥ &7/pvsearch <item name> <Player>"));
|
||||
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void openVault(Player player, UUID otherUUID, int vaultNr) {
|
||||
if (VaultOperations.openOtherVault(player, otherUUID.toString(), String.valueOf(vaultNr))) {
|
||||
PlayerVaults.getInstance().getInVault().put(player.getUniqueId().toString(), new VaultViewInfo(otherUUID.toString(), vaultNr));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void search(Player executor, String itemName, Player findFor) {
|
||||
Map<Integer, ArrayList<ItemStack>> found = new HashMap<>();
|
||||
itemName = itemName.toLowerCase();
|
||||
YamlConfiguration yamlConfiguration = VaultManager.getInstance().getPlayerVaultFile(findFor.getPlayer().getUniqueId().toString(), false);
|
||||
if (yamlConfiguration == null) {
|
||||
executor.sendMessage("&b&lVaults &8➥ &7You have no vaults to search trough.");
|
||||
} else {
|
||||
executor.sendMessage(CC.translate("&b&lVaults &8➥ &7Executing vault search query on &f\"" + itemName + "\"&7."));
|
||||
Iterator var6 = yamlConfiguration.getKeys(false).iterator();
|
||||
|
||||
label48:
|
||||
while(true) {
|
||||
int pvNumber;
|
||||
Inventory inventory;
|
||||
do {
|
||||
if (!var6.hasNext()) {
|
||||
break label48;
|
||||
}
|
||||
|
||||
String str = (String)var6.next();
|
||||
pvNumber = Integer.parseInt(str.replace("vault", ""));
|
||||
inventory = VaultManager.getInstance().getVault(findFor.getUniqueId().toString(), pvNumber);
|
||||
} while(inventory.getContents().length == 0);
|
||||
|
||||
ArrayList<ItemStack> arrayFoundItems = new ArrayList<>();
|
||||
ItemStack[] var11 = inventory.getContents();
|
||||
|
||||
for (ItemStack item : var11) {
|
||||
if (item != null && item.hasItemMeta() && item.getItemMeta().getDisplayName() != null) {
|
||||
String displayName = ChatColor.stripColor(item.getItemMeta().getDisplayName()).toLowerCase();
|
||||
if (displayName.contains(itemName) && !found.containsKey(pvNumber)) {
|
||||
arrayFoundItems.add(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!arrayFoundItems.isEmpty()) {
|
||||
found.put(pvNumber, arrayFoundItems);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Map<Integer, ArrayList<ItemStack>> sortedFound = new TreeMap<>(found);
|
||||
if (sortedFound.isEmpty()) {
|
||||
executor.sendMessage(CC.translate("&b&lVaults &8➥ &7No items found containing &f\"" + itemName + "\" &7in their name."));
|
||||
} else {
|
||||
SearchGUI searchCommand = new SearchGUI(executor, findFor, sortedFound);
|
||||
searchCommand.getExpShopUI().open(executor);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* PlayerVaultsX
|
||||
* Copyright (C) 2013 Trent Hensler
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.drtshock.playervaults.commands;
|
||||
|
||||
import com.drtshock.playervaults.PlayerVaults;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandExecutor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class SignCommand implements CommandExecutor {
|
||||
private final PlayerVaults plugin;
|
||||
|
||||
public SignCommand(PlayerVaults plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (sender.hasPermission("playervaults.signs.set")) {
|
||||
if (!PlayerVaults.getInstance().getConf().isSigns()) {
|
||||
this.plugin.getTL().signsDisabled().title().send(sender);
|
||||
return true;
|
||||
}
|
||||
if (sender instanceof Player) {
|
||||
if (args.length == 1) {
|
||||
int i;
|
||||
try {
|
||||
i = Integer.parseInt(args[0]);
|
||||
} catch (NumberFormatException nfe) {
|
||||
this.plugin.getTL().mustBeNumber().title().send(sender);
|
||||
sender.sendMessage(" /" + label + " [owner] <#>");
|
||||
return true;
|
||||
}
|
||||
PlayerVaults.getInstance().getSetSign().put(sender.getName(), new SignSetInfo(i));
|
||||
this.plugin.getTL().clickASign().title().send(sender);
|
||||
} else if (args.length >= 2) {
|
||||
int i;
|
||||
try {
|
||||
i = Integer.parseInt(args[1]);
|
||||
} catch (NumberFormatException nfe) {
|
||||
this.plugin.getTL().mustBeNumber().title().send(sender);
|
||||
sender.sendMessage(" /" + label + " [owner] <#>");
|
||||
return true;
|
||||
}
|
||||
PlayerVaults.getInstance().getSetSign().put(sender.getName(), new SignSetInfo(args[0].toLowerCase(), i));
|
||||
this.plugin.getTL().clickASign().title().send(sender);
|
||||
} else {
|
||||
this.plugin.getTL().invalidArgs().title().send(sender);
|
||||
}
|
||||
} else {
|
||||
this.plugin.getTL().playerOnly().title().send(sender);
|
||||
}
|
||||
} else {
|
||||
this.plugin.getTL().noPerms().title().send(sender);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* PlayerVaultsX
|
||||
* Copyright (C) 2013 Trent Hensler
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.drtshock.playervaults.commands;
|
||||
|
||||
/**
|
||||
* A class for setting signs. Stores information about the sign owner, number, and whether or not is opens a self vault
|
||||
* or another person's vault.
|
||||
*/
|
||||
public class SignSetInfo {
|
||||
|
||||
private final int number;
|
||||
private String owner;
|
||||
private boolean self = false;
|
||||
|
||||
/**
|
||||
* Construct a SignSetInfo object for another person.
|
||||
*
|
||||
* @param s The vault owner.
|
||||
* @param i The vault number.
|
||||
*/
|
||||
public SignSetInfo(String s, int i) {
|
||||
this.owner = s;
|
||||
this.number = i;
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a SignSetInfo object for opening to self.
|
||||
*
|
||||
* @param i The vault number.
|
||||
*/
|
||||
public SignSetInfo(int i) {
|
||||
this.number = i;
|
||||
this.self = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get whether or not the sign will open their own vault or another person's.
|
||||
*
|
||||
* @return Whether or not it is a 'self' sign.
|
||||
*/
|
||||
public boolean isSelf() {
|
||||
return this.self;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the owner of the vault.
|
||||
*
|
||||
* @return The owner of the vault.
|
||||
*/
|
||||
public String getOwner() {
|
||||
return this.owner;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the vault number.
|
||||
*
|
||||
* @return The vault number.
|
||||
*/
|
||||
public int getChest() {
|
||||
return this.number;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
/*
|
||||
* PlayerVaultsX
|
||||
* Copyright (C) 2013 Trent Hensler
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.drtshock.playervaults.commands;
|
||||
|
||||
import com.drtshock.playervaults.PlayerVaults;
|
||||
import com.drtshock.playervaults.data.PlayerVaultsManager;
|
||||
import com.drtshock.playervaults.data.PlayerVaultsPlayer;
|
||||
import com.drtshock.playervaults.guis.SelectPlayerVaultInventory;
|
||||
import com.drtshock.playervaults.vaultmanagement.VaultManager;
|
||||
import com.drtshock.playervaults.vaultmanagement.VaultOperations;
|
||||
import com.drtshock.playervaults.vaultmanagement.VaultViewInfo;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandExecutor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class VaultCommand implements CommandExecutor {
|
||||
private final PlayerVaults plugin;
|
||||
|
||||
public VaultCommand(PlayerVaults plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (VaultOperations.isLocked()) {
|
||||
this.plugin.getTL().locked().title().send(sender);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (sender instanceof Player) {
|
||||
Player player = (Player) sender;
|
||||
if (PlayerVaults.getInstance().getInVault().containsKey(player.getUniqueId().toString())) {
|
||||
// don't let them open another vault.
|
||||
return true;
|
||||
}
|
||||
|
||||
switch (args.length) {
|
||||
case 1:
|
||||
if (args[0].equalsIgnoreCase("search")) {
|
||||
sender.sendMessage(this.plugin.getTL().title() + "/pvsearch <Item Name>");
|
||||
return true;
|
||||
}
|
||||
if (VaultOperations.openOwnVault(player, args[0], true)) {
|
||||
PlayerVaults.getInstance().getInVault().put(player.getUniqueId().toString(), new VaultViewInfo(player.getUniqueId().toString(), Integer.parseInt(args[0])));
|
||||
} else if (sender.hasPermission("playervaults.admin")) {
|
||||
OfflinePlayer searchPlayer = Bukkit.getOfflinePlayer(args[0]);
|
||||
String target = args[0];
|
||||
if (searchPlayer != null && searchPlayer.hasPlayedBefore()) {
|
||||
target = searchPlayer.getUniqueId().toString();
|
||||
}
|
||||
|
||||
YamlConfiguration file = VaultManager.getInstance().getPlayerVaultFile(target, false);
|
||||
if (file == null) {
|
||||
this.plugin.getTL().vaultDoesNotExist().title().send(sender);
|
||||
} else {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (String key : file.getKeys(false)) {
|
||||
sb.append(key.replace("vault", "")).append(" ");
|
||||
}
|
||||
|
||||
this.plugin.getTL().existingVaults().title().with("player", args[0]).with("vault", sb.toString().trim()).send(sender);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 2:
|
||||
if (args[0].equalsIgnoreCase("search")) {
|
||||
sender.sendMessage(this.plugin.getTL().title() + "/pvsearch <Item Name>");
|
||||
return true;
|
||||
}
|
||||
if (!player.hasPermission("playervaults.admin")) {
|
||||
this.plugin.getTL().noPerms().title().send(sender);
|
||||
break;
|
||||
}
|
||||
|
||||
int number;
|
||||
try {
|
||||
number = Integer.parseInt(args[1]);
|
||||
} catch (NumberFormatException e) {
|
||||
this.plugin.getTL().mustBeNumber().title().send(sender);
|
||||
return true;
|
||||
}
|
||||
|
||||
String target = args[0];
|
||||
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(args[0]);
|
||||
if (offlinePlayer != null && offlinePlayer.hasPlayedBefore()) {
|
||||
target = offlinePlayer.getUniqueId().toString();
|
||||
}
|
||||
if (VaultOperations.openOtherVault(player, target, args[1])) {
|
||||
PlayerVaults.getInstance().getInVault().put(player.getUniqueId().toString(), new VaultViewInfo(target, number));
|
||||
} else {
|
||||
this.plugin.getTL().noOwnerFound().title().with("player", args[0]).send(sender);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
PlayerVaultsManager playerVaultsManager = this.plugin.getPlayerVaultsManager();
|
||||
if(playerVaultsManager.containsKey(player.getUniqueId())) {
|
||||
SelectPlayerVaultInventory selectPlayerVaultInventory = new SelectPlayerVaultInventory(playerVaultsManager.getFromCache(player.getUniqueId()));
|
||||
selectPlayerVaultInventory.getSelectPVInventory().open(player);
|
||||
return true;
|
||||
}
|
||||
playerVaultsManager.addToCache(new PlayerVaultsPlayer(player.getUniqueId()));
|
||||
//this.plugin.getTL().help().title().send(sender);
|
||||
}
|
||||
} else {
|
||||
this.plugin.getTL().playerOnly().title().send(sender);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* PlayerVaultsX
|
||||
* Copyright (C) 2013 Trent Hensler, Laxwashere, CmdrKittens
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package com.drtshock.playervaults.config;
|
||||
|
||||
|
||||
import com.drtshock.playervaults.PlayerVaults;
|
||||
import com.drtshock.playervaults.config.file.Config;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.logging.Level;
|
||||
|
||||
public class ConfigManager {
|
||||
private final PlayerVaults plugin;
|
||||
private final Config config = new Config();
|
||||
|
||||
public ConfigManager(@NonNull PlayerVaults plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
public void loadConfig() {
|
||||
try {
|
||||
Loader.loadAndSave("main", this.config);
|
||||
} catch (IOException | IllegalAccessException e) {
|
||||
this.plugin.getLogger().log(Level.SEVERE, "Could not load config. Using all default values until resolved.", e);
|
||||
}
|
||||
}
|
||||
|
||||
public @NonNull Config getConf() {
|
||||
return this.config;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
/*
|
||||
* PlayerVaultsX
|
||||
* Copyright (C) 2013 Trent Hensler, Laxwashere, CmdrKittens
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package com.drtshock.playervaults.config;
|
||||
|
||||
import com.drtshock.playervaults.PlayerVaults;
|
||||
import com.drtshock.playervaults.config.annotation.Comment;
|
||||
import com.drtshock.playervaults.config.annotation.ConfigName;
|
||||
import com.drtshock.playervaults.config.annotation.WipeOnReload;
|
||||
import com.drtshock.playervaults.config.file.Translation;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.Config;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigFactory;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigRenderOptions;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueFactory;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class Loader {
|
||||
public static void loadAndSave(@NonNull String fileName, @NonNull Object config) throws IOException, IllegalAccessException {
|
||||
File file = Loader.getFile(fileName);
|
||||
Loader.loadAndSave(file, Loader.getConf(file), config);
|
||||
}
|
||||
|
||||
public static @NonNull File getFile(@NonNull String file) {
|
||||
Path configFolder = PlayerVaults.getInstance().getDataFolder().toPath();
|
||||
if (!configFolder.toFile().exists()) {
|
||||
configFolder.toFile().mkdir();
|
||||
}
|
||||
Path path = configFolder.resolve(file + ".conf");
|
||||
return path.toFile();
|
||||
}
|
||||
|
||||
public static @NonNull Config getConf(@NonNull File file) {
|
||||
return ConfigFactory.parseFile(file);
|
||||
}
|
||||
|
||||
public static void loadAndSave(@NonNull File file, @NonNull Config config, @NonNull Object configObject) throws IOException, IllegalAccessException {
|
||||
ConfigValue value = Loader.loadNode(config, configObject);
|
||||
String s = value.render(ConfigRenderOptions.defaults().setOriginComments(false).setComments(true).setJson(false));
|
||||
Files.write(file.toPath(), s.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public static @NonNull ConfigValue load(Config config, Object configObject) throws IllegalAccessException {
|
||||
return Loader.loadNode(config, configObject);
|
||||
}
|
||||
|
||||
private static final Set<Class<?>> types = new HashSet<>();
|
||||
|
||||
static {
|
||||
Loader.types.add(Boolean.TYPE);
|
||||
Loader.types.add(Byte.TYPE);
|
||||
Loader.types.add(Character.TYPE);
|
||||
Loader.types.add(Double.TYPE);
|
||||
Loader.types.add(Float.TYPE);
|
||||
Loader.types.add(Integer.TYPE);
|
||||
Loader.types.add(Long.TYPE);
|
||||
Loader.types.add(Short.TYPE);
|
||||
Loader.types.add(List.class);
|
||||
Loader.types.add(Map.class);
|
||||
Loader.types.add(Set.class);
|
||||
Loader.types.add(String.class);
|
||||
Loader.types.add(Translation.TL.class);
|
||||
}
|
||||
|
||||
private static @NonNull ConfigValue loadNode(@NonNull Config config, @NonNull Object object) throws IllegalAccessException {
|
||||
return loadNode(config, "", object);
|
||||
}
|
||||
|
||||
private static @NonNull ConfigValue loadNode(@NonNull Config config, String path, @NonNull Object object) throws IllegalAccessException {
|
||||
Map<String, ConfigValue> map = new HashMap<>();
|
||||
for (Field field : Loader.getFields(object.getClass())) {
|
||||
if (field.isSynthetic()) {
|
||||
continue;
|
||||
}
|
||||
if ((field.getModifiers() & Modifier.TRANSIENT) != 0) {
|
||||
if (field.getAnnotation(WipeOnReload.class) != null) {
|
||||
field.setAccessible(true);
|
||||
field.set(object, null);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
field.setAccessible(true);
|
||||
ConfigName configName = field.getAnnotation(ConfigName.class);
|
||||
Comment comment = field.getAnnotation(Comment.class);
|
||||
String confName = configName == null || configName.value().isEmpty() ? field.getName() : configName.value();
|
||||
String newPath = path.isEmpty() ? confName : (path + '.' + confName);
|
||||
ConfigValue curValue = Loader.getOrNull(config, newPath);
|
||||
boolean needsValue = curValue == null;
|
||||
|
||||
ConfigValue newValue;
|
||||
Object defaultValue = field.get(object);
|
||||
if (Loader.types.contains(field.getType())) {
|
||||
if (needsValue) {
|
||||
if (Translation.TL.class.isAssignableFrom(field.getType())) {
|
||||
Translation.TL tl = (Translation.TL) defaultValue;
|
||||
newValue = tl.size() == 1 ? ConfigValueFactory.fromAnyRef(tl.get(0)) : ConfigValueFactory.fromAnyRef(tl);
|
||||
} else {
|
||||
newValue = ConfigValueFactory.fromAnyRef(defaultValue);
|
||||
}
|
||||
} else {
|
||||
dance:
|
||||
try {
|
||||
if (Translation.TL.class.isAssignableFrom(field.getType())) {
|
||||
Translation.TL tl;
|
||||
if (curValue.valueType() == ConfigValueType.STRING) {
|
||||
String s = curValue.unwrapped().toString();
|
||||
tl = Translation.TL.copyOf(Collections.singletonList(s));
|
||||
} else if (curValue.valueType() == ConfigValueType.LIST) {
|
||||
List<String> l = (List<String>) curValue.unwrapped();
|
||||
tl = Translation.TL.copyOf(l);
|
||||
} else {
|
||||
tl = (Translation.TL) defaultValue;
|
||||
}
|
||||
newValue = tl.size() == 1 ? ConfigValueFactory.fromAnyRef(tl.get(0)) : ConfigValueFactory.fromAnyRef(tl);
|
||||
field.set(object, tl);
|
||||
break dance;
|
||||
}
|
||||
if (List.class.isAssignableFrom(field.getType()) && curValue.valueType() == ConfigValueType.STRING) {
|
||||
List<?> list = Collections.singletonList(curValue.unwrapped());
|
||||
field.set(object, list);
|
||||
newValue = ConfigValueFactory.fromAnyRef(list);
|
||||
break dance;
|
||||
} else if (Set.class.isAssignableFrom(field.getType()) && curValue.valueType() == ConfigValueType.STRING) {
|
||||
Set<?> set = Collections.singleton(curValue.unwrapped());
|
||||
field.set(object, set);
|
||||
newValue = ConfigValueFactory.fromAnyRef(set);
|
||||
break dance;
|
||||
} else if (Set.class.isAssignableFrom(field.getType()) && curValue.valueType() == ConfigValueType.LIST) {
|
||||
field.set(object, new HashSet<Object>((List<?>) curValue.unwrapped()));
|
||||
} else {
|
||||
field.set(object, curValue.unwrapped());
|
||||
}
|
||||
newValue = curValue;
|
||||
} catch (IllegalArgumentException ex) {
|
||||
PlayerVaults.getInstance().getLogger().warning("Found incorrect type for " + confName + ": Expected " + field.getType() + ", found " + curValue.unwrapped().getClass());
|
||||
field.set(object, defaultValue);
|
||||
newValue = ConfigValueFactory.fromAnyRef(defaultValue);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
newValue = Loader.loadNode(config, newPath, defaultValue);
|
||||
}
|
||||
if (comment != null) {
|
||||
newValue = newValue.withOrigin(newValue.origin().withComments(Arrays.asList(comment.value().split("\n"))));
|
||||
}
|
||||
map.put(confName, newValue);
|
||||
}
|
||||
return ConfigValueFactory.fromMap(map);
|
||||
}
|
||||
|
||||
private static @Nullable ConfigValue getOrNull(@NonNull Config config, @NonNull String path) {
|
||||
return config.hasPath(path) ? config.getValue(path) : null;
|
||||
}
|
||||
|
||||
private static @NonNull List<Field> getFields(@NonNull Class<?> clazz) {
|
||||
return Loader.getFields(new ArrayList<>(), clazz);
|
||||
}
|
||||
|
||||
private static @NonNull List<Field> getFields(@NonNull List<Field> fields, @NonNull Class<?> clazz) {
|
||||
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
|
||||
|
||||
if (clazz.getSuperclass() != null) {
|
||||
Loader.getFields(fields, clazz.getSuperclass());
|
||||
}
|
||||
|
||||
return fields;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* PlayerVaultsX
|
||||
* Copyright (C) 2013 Trent Hensler, Laxwashere, CmdrKittens
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package com.drtshock.playervaults.config.annotation;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.FIELD)
|
||||
public @interface Comment {
|
||||
@NonNull String value();
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* PlayerVaultsX
|
||||
* Copyright (C) 2013 Trent Hensler, Laxwashere, CmdrKittens
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package com.drtshock.playervaults.config.annotation;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.FIELD)
|
||||
public @interface ConfigName {
|
||||
@NonNull String value();
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* PlayerVaultsX
|
||||
* Copyright (C) 2013 Trent Hensler, Laxwashere, CmdrKittens
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package com.drtshock.playervaults.config.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.FIELD)
|
||||
public @interface WipeOnReload {
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
/*
|
||||
* PlayerVaultsX
|
||||
* Copyright (C) 2013 Trent Hensler, Laxwashere, CmdrKittens
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package com.drtshock.playervaults.config.file;
|
||||
|
||||
import com.drtshock.playervaults.config.annotation.Comment;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@SuppressWarnings({"FieldMayBeFinal", "FieldCanBeLocal", "InnerClassMayBeStatic", "unused"})
|
||||
public class Config {
|
||||
public class Block {
|
||||
private boolean enabled = true;
|
||||
@Comment("Material list for blocked items (does not support ID's), only effective if the feature is enabled.\n" +
|
||||
" If you don't know material names: https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/Material.html")
|
||||
private List<String> list = new ArrayList<String>() {
|
||||
{
|
||||
this.add("PUMPKIN");
|
||||
this.add("DIAMOND_BLOCK");
|
||||
}
|
||||
};
|
||||
|
||||
public boolean isEnabled() {
|
||||
return this.enabled;
|
||||
}
|
||||
|
||||
public List<String> getList() {
|
||||
if (this.list == null) {
|
||||
this.list = new ArrayList<>();
|
||||
}
|
||||
return Collections.unmodifiableList(list);
|
||||
}
|
||||
}
|
||||
|
||||
public class Economy {
|
||||
@Comment("Set me to true to enable economy features!")
|
||||
private boolean enabled = false;
|
||||
private double feeToCreate = 100;
|
||||
private double feeToOpen = 10;
|
||||
private double refundOnDelete = 50;
|
||||
|
||||
public boolean isEnabled() {
|
||||
return this.enabled;
|
||||
}
|
||||
|
||||
public double getFeeToCreate() {
|
||||
return this.feeToCreate;
|
||||
}
|
||||
|
||||
public double getFeeToOpen() {
|
||||
return this.feeToOpen;
|
||||
}
|
||||
|
||||
public double getRefundOnDelete() {
|
||||
return this.refundOnDelete;
|
||||
}
|
||||
}
|
||||
|
||||
public class PurgePlanet {
|
||||
private boolean enabled = false;
|
||||
@Comment("Time, in days, since last edit")
|
||||
private int daysSinceLastEdit = 30;
|
||||
|
||||
public boolean isEnabled() {
|
||||
return this.enabled;
|
||||
}
|
||||
|
||||
public int getDaysSinceLastEdit() {
|
||||
return this.daysSinceLastEdit;
|
||||
}
|
||||
}
|
||||
|
||||
public class Storage {
|
||||
public class FlatFile {
|
||||
@Comment("Backups\n" +
|
||||
" Enabling this will create backups of vaults automagically.")
|
||||
private boolean backups = true;
|
||||
|
||||
public boolean isBackups() {
|
||||
return this.backups;
|
||||
}
|
||||
}
|
||||
|
||||
private FlatFile flatFile = new FlatFile();
|
||||
private String storageType = "flatfile";
|
||||
|
||||
public FlatFile getFlatFile() {
|
||||
return this.flatFile;
|
||||
}
|
||||
|
||||
public String getStorageType() {
|
||||
return this.storageType;
|
||||
}
|
||||
}
|
||||
|
||||
@Comment("PlayerVaults\n" +
|
||||
"Created by: https://github.com/drtshock/PlayerVaults/graphs/contributors/\n" +
|
||||
"Resource page: https://www.spigotmc.org/resources/51204/\n" +
|
||||
"Discord server: https://discordapp.com/invite/JZcWDEt/\n" +
|
||||
"Made with love <3")
|
||||
private boolean aPleasantHello = true;
|
||||
|
||||
@Comment("Debug Mode\n" +
|
||||
" This will print everything the plugin is doing to console.\n" +
|
||||
" You should only enable this if you're working with a contributor to fix something.")
|
||||
private boolean debug = false;
|
||||
|
||||
@Comment("Can be 1 through 6.\n" +
|
||||
"Default: 6")
|
||||
private int defaultVaultRows = 6;
|
||||
|
||||
@Comment("Signs\n" +
|
||||
" This will determine whether vault signs are enabled.\n" +
|
||||
" If you don't know what this is or if it's for you, see the resource page.")
|
||||
private boolean signs = false;
|
||||
|
||||
@Comment("Economy\n" +
|
||||
" These are all of the settings for the economy integration. (Requires Vault)\n" +
|
||||
" Bypass permission is: playervaults.free")
|
||||
private Economy economy = new Economy();
|
||||
|
||||
@Comment("Blocked Items\n" +
|
||||
" This will allow you to block specific materials from vaults.\n" +
|
||||
" Bypass permission is: playervaults.bypassblockeditems")
|
||||
private Block itemBlocking = new Block();
|
||||
|
||||
@Comment("Cleanup\n" +
|
||||
" Enabling this will purge vaults that haven't been touched in the specified time frame.\n" +
|
||||
" Reminder: This is only checked during startup.\n" +
|
||||
" This will not lag your server or touch the backups folder.")
|
||||
private PurgePlanet purge = new PurgePlanet();
|
||||
|
||||
@Comment("Sets the highest vault amount this plugin will test perms for")
|
||||
private int maxVaultAmountPermTest = 99;
|
||||
|
||||
@Comment("Storage option. Currently only flatfile, but soon more! :)")
|
||||
private Storage storage = new Storage();
|
||||
|
||||
public void setFromConfig(Logger l, FileConfiguration c) {
|
||||
l.info("Importing old configuration...");
|
||||
l.info("debug = " + (this.debug = c.getBoolean("debug", false)));
|
||||
l.info("signs = " + (this.signs = c.getBoolean("signs-enabled", false)));
|
||||
l.info("economy enabled = " + (this.economy.enabled = c.getBoolean("economy.enabled", false)));
|
||||
l.info(" creation fee = " + (this.economy.feeToCreate = c.getDouble("economy.cost-to-create", 100)));
|
||||
l.info(" open fee = " + (this.economy.feeToOpen = c.getDouble("economy.cost-to-open", 10)));
|
||||
l.info(" refund = " + (this.economy.refundOnDelete = c.getDouble("economy.refund-on-delete", 50)));
|
||||
l.info("item blocking enabled = " + (this.itemBlocking.enabled = c.getBoolean("blockitems", true)));
|
||||
l.info("blocked items = " + (this.itemBlocking.list = c.getStringList("blocked-items")));
|
||||
if (this.itemBlocking.list == null) {
|
||||
this.itemBlocking.list = new ArrayList<>();
|
||||
this.itemBlocking.list.add("PUMPKIN");
|
||||
this.itemBlocking.list.add("DIAMOND_BLOCK");
|
||||
l.info(" set defaults: " + this.itemBlocking.list);
|
||||
}
|
||||
l.info("cleanup purge enabled = " + (this.purge.enabled = c.getBoolean("cleanup.enable", false)));
|
||||
l.info(" days since last edit = " + (this.purge.daysSinceLastEdit = c.getInt("cleanup.lastEdit", 30)));
|
||||
l.info("flatfile storage backups = " + (this.storage.flatFile.backups = c.getBoolean("backups.enabled", true)));
|
||||
l.info("max vault amount to test via perms = " + (this.maxVaultAmountPermTest = c.getInt("max-vault-amount-perm-to-test", 99)));
|
||||
}
|
||||
|
||||
public boolean isDebug() {
|
||||
return this.debug;
|
||||
}
|
||||
|
||||
public int getDefaultVaultRows() {
|
||||
return this.defaultVaultRows;
|
||||
}
|
||||
|
||||
public boolean isSigns() {
|
||||
return this.signs;
|
||||
}
|
||||
|
||||
public Economy getEconomy() {
|
||||
return this.economy;
|
||||
}
|
||||
|
||||
public Block getItemBlocking() {
|
||||
return this.itemBlocking;
|
||||
}
|
||||
|
||||
public PurgePlanet getPurge() {
|
||||
return this.purge;
|
||||
}
|
||||
|
||||
public int getMaxVaultAmountPermTest() {
|
||||
return this.maxVaultAmountPermTest;
|
||||
}
|
||||
|
||||
public Storage getStorage() {
|
||||
return this.storage;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
package com.drtshock.playervaults.config.file;
|
||||
|
||||
import com.drtshock.playervaults.PlayerVaults;
|
||||
import com.drtshock.playervaults.config.annotation.Comment;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import net.kyori.adventure.audience.Audience;
|
||||
import net.kyori.adventure.platform.bukkit.BukkitComponentSerializer;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.minimessage.MiniMessage;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@SuppressWarnings("FieldMayBeFinal")
|
||||
public class Translation {
|
||||
public static class TL extends ArrayList<String> {
|
||||
private static transient PlayerVaults plugin;
|
||||
private static transient final Pattern REPLACEMENT_PATTERN = Pattern.compile("(?:\\{([a-zA-Z0-9\\-_]+)(?:(?::)([a-zA-Z0-9_\\-|]+))?})");
|
||||
private static transient final Pattern TAG_PATTERN = Pattern.compile("(?:<(/?)([a-zA-Z\\-_]+)>)");
|
||||
private static transient final String SKIP_LINE_IF_MISSING = "s";
|
||||
private static transient final String BLANK_IF_MISSING = "b";
|
||||
private static transient final String PRE_FORMATTED = "p";
|
||||
|
||||
private static @NonNull TL of(@NonNull String... strings) {
|
||||
TL list = new TL();
|
||||
Collections.addAll(list, strings);
|
||||
return list;
|
||||
}
|
||||
|
||||
public static @NonNull TL copyOf(@NonNull Collection<String> collection) {
|
||||
TL list = new TL();
|
||||
list.addAll(collection);
|
||||
return list;
|
||||
}
|
||||
|
||||
public class Builder {
|
||||
private transient ImmutableMap.Builder<String, String> map;
|
||||
private transient TL title;
|
||||
|
||||
private Builder(@NonNull TL title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
private Builder(@NonNull String key, @Nullable String value) {
|
||||
this.with(key, value);
|
||||
}
|
||||
|
||||
public @NonNull Builder with(@NonNull String key, @Nullable String value) {
|
||||
if (this.map == null) {
|
||||
this.map = ImmutableMap.builder();
|
||||
}
|
||||
this.map.put(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public void send(@NonNull CommandSender sender) {
|
||||
TL.this.send(sender, this.map == null ? Collections.emptyMap() : this.map.build(), this.title);
|
||||
}
|
||||
|
||||
public @NonNull String getLegacy() {
|
||||
return TL.this.getLegacy(this.map == null ? Collections.emptyMap() : this.map.build(), this.title);
|
||||
}
|
||||
}
|
||||
|
||||
public @NonNull Builder with(@NonNull String key, @Nullable String value) {
|
||||
return new Builder(key, value);
|
||||
}
|
||||
|
||||
public @NonNull Builder title() {
|
||||
return new Builder(TL.plugin.getTL().title());
|
||||
}
|
||||
|
||||
public @NonNull Builder title(@NonNull TL title) {
|
||||
return new Builder(title);
|
||||
}
|
||||
|
||||
public void send(@NonNull CommandSender sender) {
|
||||
this.send(sender, Collections.emptyMap(), null);
|
||||
}
|
||||
|
||||
private void send(@NonNull CommandSender sender, @NonNull Map<String, String> map, @Nullable TL title) {
|
||||
this.send(TL.plugin.getPlatform().sender(sender), map, title);
|
||||
}
|
||||
|
||||
private void send(@NonNull Audience audience, @NonNull Map<String, String> map, @Nullable TL title) {
|
||||
this.forEach(line -> {
|
||||
Component component = this.getComponent(line, map, title);
|
||||
if (component != null) {
|
||||
audience.sendMessage(component);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private @Nullable Component getComponent(@NonNull String line, @NonNull Map<String, String> map, @Nullable TL title) {
|
||||
if (title != null && !title.isEmpty()) {
|
||||
line = title.get(0) + line;
|
||||
}
|
||||
StringBuffer builder = null;
|
||||
String found;
|
||||
String foundDetails;
|
||||
String repl;
|
||||
String[] features;
|
||||
Matcher replMatcher = TL.REPLACEMENT_PATTERN.matcher(line);
|
||||
while (replMatcher.find()) {
|
||||
if (builder == null) {
|
||||
builder = new StringBuffer();
|
||||
}
|
||||
found = replMatcher.group(1);
|
||||
foundDetails = replMatcher.group(2);
|
||||
features = foundDetails == null ? null : foundDetails.split("\\|");
|
||||
repl = map.get(found);
|
||||
if (repl == null) {
|
||||
if (this.arrContains(features, TL.SKIP_LINE_IF_MISSING)) {
|
||||
return null;
|
||||
}
|
||||
if (this.arrContains(features, TL.BLANK_IF_MISSING)) {
|
||||
replMatcher.appendReplacement(builder, "");
|
||||
}
|
||||
} else {
|
||||
if (this.arrContains(features, TL.PRE_FORMATTED)) {
|
||||
repl = MiniMessage.miniMessage().escapeTags(repl).replace("\\", "\\\\");
|
||||
}
|
||||
replMatcher.appendReplacement(builder, repl);
|
||||
}
|
||||
}
|
||||
if (builder != null) {
|
||||
replMatcher.appendTail(builder);
|
||||
line = builder.toString();
|
||||
builder = null;
|
||||
}
|
||||
|
||||
Matcher tagMatcher = TL.TAG_PATTERN.matcher(line);
|
||||
while (tagMatcher.find()) {
|
||||
if (builder == null) {
|
||||
builder = new StringBuffer();
|
||||
}
|
||||
found = tagMatcher.group(2);
|
||||
repl = TL.plugin.getTL().colorMappings().get(found);
|
||||
if (repl != null) {
|
||||
tagMatcher.appendReplacement(builder, '<' + tagMatcher.group(1) + repl + '>');
|
||||
}
|
||||
}
|
||||
if (builder != null) {
|
||||
tagMatcher.appendTail(builder);
|
||||
line = builder.toString();
|
||||
}
|
||||
return MiniMessage.miniMessage().deserialize(line);
|
||||
}
|
||||
|
||||
public @NonNull String getLegacy() {
|
||||
return this.getLegacy(Collections.emptyMap(), null);
|
||||
}
|
||||
|
||||
public @NonNull String getLegacy(@NonNull Map<String, String> map) {
|
||||
return this.getLegacy(map, null);
|
||||
}
|
||||
|
||||
public @NonNull String getLegacy(@NonNull Map<String, String> map, @Nullable TL title) {
|
||||
return this.stream()
|
||||
.map(line -> this.getComponent(line, map, title))
|
||||
.filter(Objects::nonNull)
|
||||
.map(component -> BukkitComponentSerializer.legacy().serialize(component))
|
||||
.collect(Collectors.joining("\n"));
|
||||
}
|
||||
|
||||
public boolean arrContains(@Nullable String[] array, @NonNull String target) {
|
||||
if (array == null) {
|
||||
return false;
|
||||
}
|
||||
for (String string : array) {
|
||||
if (target.equals(string)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static class Placeholders {
|
||||
private TL title = TL.of("<dark_red>[<normal>PlayerVaults<dark_red>]: ");
|
||||
}
|
||||
|
||||
private static class Translations {
|
||||
private TL openVault = TL.of("<normal>Opening vault <info>{vault}</info>");
|
||||
private TL openOtherVault = TL.of("<normal>Opening vault <info>{vault}</info> of <info>{player}</info>");
|
||||
private TL invalidArgs = TL.of("<error>Invalid args!");
|
||||
private TL deleteVault = TL.of("<normal>Deleted vault <info>{vault}</info>");
|
||||
private TL deleteOtherVault = TL.of("<normal>Deleted vault <info>{vault}</info> <normal>of <info>{player}</info>");
|
||||
private TL deleteOtherVaultAll = TL.of("<dark_red>Deleted all vaults belonging to <info>{player}</info>");
|
||||
private TL playerOnly = TL.of("<error>Sorry but that can only be run by a player!");
|
||||
private TL mustBeNumber = TL.of("<error>You need to specify a valid number.");
|
||||
private TL noPerms = TL.of("<error>You don't have permission for that!");
|
||||
private TL insufficientFunds = TL.of("<error>You don't have enough money for that!");
|
||||
private TL refundAmount = TL.of("<normal>You were refunded <info>{price}</info> for deleting that vault.");
|
||||
private TL costToCreate = TL.of("<normal>You were charged <info>{price}</info> for creating a vault.");
|
||||
private TL costToOpen = TL.of("<normal>You were charged <info>{price}</info> for opening that vault.");
|
||||
private TL vaultDoesNotExist = TL.of("<error>That vault does not exist!");
|
||||
private TL clickASign = TL.of("<normal>Now click a sign!");
|
||||
private TL notASign = TL.of("<error>You must click a sign!");
|
||||
private TL setSign = TL.of("<normal>You have successfully set a PlayerVault access sign!");
|
||||
private TL existingVaults = TL.of("<normal>{player} has vaults: <info>{vault}</info>");
|
||||
private TL vaultTitle = TL.of("<dark_red>Vault #{vault}");
|
||||
private TL openWithSign = TL.of("<normal>Opening vault <info>{vault}</info> of <info>{player}</info>");
|
||||
private TL noOwnerFound = TL.of("<error>Cannot find vault owner: <info>{player}</info>");
|
||||
private TL convertPluginNotFound = TL.of("<error>No converter found for that plugin.");
|
||||
private TL convertComplete = TL.of("<normal>Converted <info>{count}</info> players to PlayerVaults.");
|
||||
private TL convertBackground = TL.of("<normal>Conversion has been forked to the background. See console for updates.");
|
||||
private TL locked = TL.of("<error>Vaults are currently locked while conversion occurs. Please try again in a moment!");
|
||||
private TL help = TL.of("/pv <number>");
|
||||
private TL blockedItem = TL.of("<gold>{item}</gold> <error>is blocked from vaults.");
|
||||
private TL signsDisabled = TL.of("<error>Vault signs are currently disabled.");
|
||||
private TL blockedBadItem = TL.of("<error>This item is not allowed in a vault.");
|
||||
}
|
||||
|
||||
private Placeholders placeholders = new Placeholders();
|
||||
private Translations translations = new Translations();
|
||||
|
||||
public Translation(@NonNull PlayerVaults plugin) {
|
||||
TL.plugin = plugin;
|
||||
}
|
||||
|
||||
@Comment("https://docs.adventure.kyori.net/minimessage.html#format")
|
||||
private Map<String, String> colorMappings = new HashMap<String, String>() {
|
||||
{
|
||||
this.put("error", "red");
|
||||
this.put("normal", "white");
|
||||
this.put("info", "green");
|
||||
}
|
||||
};
|
||||
|
||||
public @NonNull TL title() {
|
||||
return this.placeholders.title;
|
||||
}
|
||||
|
||||
public @NonNull TL openVault() {
|
||||
return this.translations.openVault;
|
||||
}
|
||||
|
||||
public @NonNull TL openOtherVault() {
|
||||
return this.translations.openOtherVault;
|
||||
}
|
||||
|
||||
public @NonNull TL invalidArgs() {
|
||||
return this.translations.invalidArgs;
|
||||
}
|
||||
|
||||
public @NonNull TL deleteVault() {
|
||||
return this.translations.deleteVault;
|
||||
}
|
||||
|
||||
public @NonNull TL deleteOtherVault() {
|
||||
return this.translations.deleteOtherVault;
|
||||
}
|
||||
|
||||
public @NonNull TL deleteOtherVaultAll() {
|
||||
return this.translations.deleteOtherVaultAll;
|
||||
}
|
||||
|
||||
public @NonNull TL playerOnly() {
|
||||
return this.translations.playerOnly;
|
||||
}
|
||||
|
||||
public @NonNull TL mustBeNumber() {
|
||||
return this.translations.mustBeNumber;
|
||||
}
|
||||
|
||||
public @NonNull TL noPerms() {
|
||||
return this.translations.noPerms;
|
||||
}
|
||||
|
||||
public @NonNull TL insufficientFunds() {
|
||||
return this.translations.insufficientFunds;
|
||||
}
|
||||
|
||||
public @NonNull TL refundAmount() {
|
||||
return this.translations.refundAmount;
|
||||
}
|
||||
|
||||
public @NonNull TL costToCreate() {
|
||||
return this.translations.costToCreate;
|
||||
}
|
||||
|
||||
public @NonNull TL costToOpen() {
|
||||
return this.translations.costToOpen;
|
||||
}
|
||||
|
||||
public @NonNull TL vaultDoesNotExist() {
|
||||
return this.translations.vaultDoesNotExist;
|
||||
}
|
||||
|
||||
public @NonNull TL clickASign() {
|
||||
return this.translations.clickASign;
|
||||
}
|
||||
|
||||
public @NonNull TL notASign() {
|
||||
return this.translations.notASign;
|
||||
}
|
||||
|
||||
public @NonNull TL setSign() {
|
||||
return this.translations.setSign;
|
||||
}
|
||||
|
||||
public @NonNull TL existingVaults() {
|
||||
return this.translations.existingVaults;
|
||||
}
|
||||
|
||||
public @NonNull TL vaultTitle() {
|
||||
return this.translations.vaultTitle;
|
||||
}
|
||||
|
||||
public @NonNull TL openWithSign() {
|
||||
return this.translations.openWithSign;
|
||||
}
|
||||
|
||||
public @NonNull TL noOwnerFound() {
|
||||
return this.translations.noOwnerFound;
|
||||
}
|
||||
|
||||
public @NonNull TL convertPluginNotFound() {
|
||||
return this.translations.convertPluginNotFound;
|
||||
}
|
||||
|
||||
public @NonNull TL convertComplete() {
|
||||
return this.translations.convertComplete;
|
||||
}
|
||||
|
||||
public @NonNull TL convertBackground() {
|
||||
return this.translations.convertBackground;
|
||||
}
|
||||
|
||||
public @NonNull TL locked() {
|
||||
return this.translations.locked;
|
||||
}
|
||||
|
||||
public @NonNull TL help() {
|
||||
return this.translations.help;
|
||||
}
|
||||
|
||||
public @NonNull TL blockedItem() {
|
||||
return this.translations.blockedItem;
|
||||
}
|
||||
|
||||
public @NonNull TL signsDisabled() {
|
||||
return this.translations.signsDisabled;
|
||||
}
|
||||
|
||||
public @NonNull TL blockedBadItem() {
|
||||
return this.translations.blockedBadItem;
|
||||
}
|
||||
|
||||
public @NonNull Map<String, String> colorMappings() {
|
||||
return Collections.unmodifiableMap(this.colorMappings);
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
/*
|
||||
* PlayerVaultsX
|
||||
* Copyright (C) 2013 Trent Hensler, turt2live
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.drtshock.playervaults.converters;
|
||||
|
||||
import com.drtshock.playervaults.PlayerVaults;
|
||||
import com.drtshock.playervaults.vaultmanagement.VaultManager;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Simple converter for Backpack (http://dev.bukkit.org/bukkit-plugins/backpack/)
|
||||
*
|
||||
* @author turt2live
|
||||
*/
|
||||
public class BackpackConverter implements Converter {
|
||||
|
||||
@Override
|
||||
public int run(CommandSender initiator) {
|
||||
|
||||
PlayerVaults plugin = PlayerVaults.getInstance();
|
||||
File destination = new File(plugin.getDataFolder().getParentFile(), "Backpack" + File.separator + "backpacks");
|
||||
if (!destination.exists()) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
int converted = 0;
|
||||
|
||||
File[] worldDirs = destination.listFiles();
|
||||
int vaultNum = 1;
|
||||
for (File file : worldDirs != null ? worldDirs : new File[0]) {
|
||||
if (file.isDirectory()) {
|
||||
converted += convert(file, vaultNum);
|
||||
vaultNum++;
|
||||
}
|
||||
}
|
||||
|
||||
return converted;
|
||||
}
|
||||
|
||||
private int convert(File worldFolder, int intoVaultNum) {
|
||||
PlayerVaults plugin = PlayerVaults.getInstance();
|
||||
VaultManager vaults = VaultManager.getInstance();
|
||||
int converted = 0;
|
||||
long lastUpdate = 0;
|
||||
File[] files = worldFolder.listFiles();
|
||||
for (File file : files != null ? files : new File[0]) {
|
||||
if (file.isFile() && file.getName().toLowerCase().endsWith(".yml")) {
|
||||
try {
|
||||
OfflinePlayer player = Bukkit.getOfflinePlayer(file.getName().substring(0, file.getName().lastIndexOf('.')));
|
||||
if (player == null || player.getUniqueId() == null) {
|
||||
plugin.getLogger().warning("Unable to convert Backpack for player: " + (player != null ? player.getName() : file.getName()));
|
||||
} else {
|
||||
UUID uuid = player.getUniqueId();
|
||||
FileConfiguration yaml = YamlConfiguration.loadConfiguration(file);
|
||||
ConfigurationSection section = yaml.getConfigurationSection("backpack");
|
||||
if (section.getKeys(false).size() <= 0) {
|
||||
continue; // No slots
|
||||
}
|
||||
|
||||
Inventory vault = vaults.getVault(uuid.toString(), intoVaultNum);
|
||||
if (vault == null) {
|
||||
vault = plugin.getServer().createInventory(null, section.getKeys(false).size());
|
||||
}
|
||||
for (String key : section.getKeys(false)) {
|
||||
ConfigurationSection slotSection = section.getConfigurationSection(key);
|
||||
ItemStack item = slotSection.getItemStack("ItemStack");
|
||||
if (item == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Overwrite
|
||||
vault.setItem(Integer.parseInt(key.split(" ")[1]), item);
|
||||
}
|
||||
vaults.saveVault(vault, uuid.toString(), intoVaultNum);
|
||||
converted++;
|
||||
|
||||
if (System.currentTimeMillis() - lastUpdate >= 1500) {
|
||||
plugin.getLogger().info(converted + " backpacks have been converted in " + worldFolder.getAbsolutePath());
|
||||
lastUpdate = System.currentTimeMillis();
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
plugin.getLogger().warning("Error converting " + file.getAbsolutePath());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
return converted;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert() {
|
||||
PlayerVaults plugin = PlayerVaults.getInstance();
|
||||
File expectedFolder = new File(plugin.getDataFolder().getParentFile(), "Backpack");
|
||||
if (!expectedFolder.exists()) {
|
||||
return false;
|
||||
}
|
||||
File backpackDir = new File(expectedFolder, "backpacks");
|
||||
return backpackDir.exists();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "Backpack";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* PlayerVaultsX
|
||||
* Copyright (C) 2013 Trent Hensler, turt2live
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.drtshock.playervaults.converters;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
/**
|
||||
* Represents a simple converter for converting another plugin's content to PlayerVaults.
|
||||
*
|
||||
* @author turt2live
|
||||
*/
|
||||
public interface Converter {
|
||||
|
||||
/**
|
||||
* Converts the other plugin's data.
|
||||
*
|
||||
* @param initiator the initiator of the conversion. May be null
|
||||
* @return the number of vaults converted. Returns 0 on none converted or -1 if no vaults were converted.
|
||||
*/
|
||||
int run(CommandSender initiator);
|
||||
|
||||
/**
|
||||
* Determines if this converter is applicable for converting to PlayerVaults. This may check for the existance of a
|
||||
* plugin, plugin folder, or otherwise.
|
||||
*
|
||||
* @return true if this converter can convert, false otherwise
|
||||
*/
|
||||
boolean canConvert();
|
||||
|
||||
/**
|
||||
* Gets the name of this converter
|
||||
*
|
||||
* @return the converter name
|
||||
*/
|
||||
String getName();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.drtshock.playervaults.data;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.bukkit.Material;
|
||||
|
||||
@Getter @Setter @AllArgsConstructor
|
||||
public class PlayerVaultItem {
|
||||
|
||||
private Material material;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.drtshock.playervaults.data;
|
||||
|
||||
import com.drtshock.playervaults.PlayerVaults;
|
||||
import net.crankedpvp.storageutils.StorageUtils;
|
||||
import net.crankedpvp.storageutils.struct.NewSaveLoadManager;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class PlayerVaultsManager extends NewSaveLoadManager<UUID, PlayerVaultsPlayer> {
|
||||
public PlayerVaultsManager() {
|
||||
super(PlayerVaults.getInstance(), StorageUtils.getInstance().getGson(), "player-gui-data", PlayerVaultsPlayer.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String serialize(UUID uuid) {
|
||||
return uuid.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID deserialize(String s) {
|
||||
return UUID.fromString(s);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.drtshock.playervaults.data;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import net.crankedpvp.storageutils.struct.NewKeyToSave;
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
@Getter @Setter
|
||||
public class PlayerVaultsPlayer implements NewKeyToSave<UUID> {
|
||||
|
||||
private UUID playerUUID;
|
||||
private Map<Integer, PlayerVaultItem> playerVaultItemMap;
|
||||
private String name;
|
||||
|
||||
public PlayerVaultsPlayer(UUID uuid) {
|
||||
this(uuid, new HashMap<>());
|
||||
}
|
||||
|
||||
public PlayerVaultsPlayer(UUID uuid, Map<Integer, PlayerVaultItem> playerVaultItemMap) {
|
||||
this.playerUUID = uuid;
|
||||
this.playerVaultItemMap = playerVaultItemMap;
|
||||
this.name = Bukkit.getOfflinePlayer(uuid).getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getKey() {
|
||||
return playerUUID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setKey(UUID uuid) {
|
||||
this.playerUUID = uuid;
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.drtshock.playervaults.guis;
|
||||
|
||||
import com.drtshock.playervaults.data.PlayerVaultItem;
|
||||
import com.drtshock.playervaults.data.PlayerVaultsPlayer;
|
||||
import dev.triumphteam.gui.guis.Gui;
|
||||
import dev.triumphteam.gui.guis.GuiItem;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class ChangeMaterialInventory {
|
||||
|
||||
private final static Material[] materials = new Material[]{
|
||||
Material.DIAMOND_SWORD, Material.DIAMOND_AXE, Material.DIAMOND_BOOTS, Material.DIAMOND_LEGGINGS, Material.DIAMOND_CHESTPLATE, Material.DIAMOND_HELMET,
|
||||
Material.GOLD_SWORD, Material.GOLD_AXE, Material.GOLD_BOOTS, Material.GOLD_LEGGINGS, Material.GOLD_CHESTPLATE, Material.GOLD_HELMET,
|
||||
Material.DIAMOND, Material.EMERALD, Material.GOLD_INGOT, Material.IRON_INGOT, Material.REDSTONE, Material.GOLDEN_APPLE, Material.COOKED_BEEF,
|
||||
Material.SKULL_ITEM, Material.FISHING_ROD, Material.ENDER_PEARL
|
||||
};
|
||||
|
||||
private List<ItemStack> itemStackList;
|
||||
|
||||
private final Gui selectPVInventory;
|
||||
|
||||
public Gui getSelectPVInventory() {
|
||||
return this.selectPVInventory;
|
||||
}
|
||||
|
||||
public ChangeMaterialInventory(Integer vault, PlayerVaultsPlayer playerVaultsPlayer) {
|
||||
this.selectPVInventory = new Gui(6, "PV Material Selector");
|
||||
this.selectPVInventory.setDefaultClickAction((event) -> event.setCancelled(true));
|
||||
|
||||
for(Material material : materials) {
|
||||
this.selectPVInventory.addItem(new GuiItem(new ItemStack(material), event -> {
|
||||
event.getWhoClicked().closeInventory();
|
||||
playerVaultsPlayer.getPlayerVaultItemMap().put(vault, new PlayerVaultItem(event.getCurrentItem().getType()));
|
||||
SelectPlayerVaultInventory selectPlayerVaultInventory = new SelectPlayerVaultInventory(playerVaultsPlayer);
|
||||
selectPlayerVaultInventory.getSelectPVInventory().open(event.getWhoClicked());
|
||||
}));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.drtshock.playervaults.guis;
|
||||
|
||||
import com.drtshock.playervaults.commands.SearchCommand;
|
||||
import com.drtshock.playervaults.utils.CC;
|
||||
import de.tr7zw.nbtapi.NBTItem;
|
||||
import dev.triumphteam.gui.guis.GuiItem;
|
||||
import dev.triumphteam.gui.guis.PaginatedGui;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
public class SearchGUI {
|
||||
private final PaginatedGui expShopUI;
|
||||
|
||||
public PaginatedGui getExpShopUI() {
|
||||
return this.expShopUI;
|
||||
}
|
||||
|
||||
public SearchGUI(Player executor, Player openFor, Map<Integer, ArrayList<ItemStack>> hashMap) {
|
||||
executor.sendMessage(CC.translate("&b&lVaults &8➥ &7Finished searching... Found &f" + hashMap.size() + "&7 unique vaults."));
|
||||
executor.playSound(executor.getLocation(), Sound.valueOf("CHEST_OPEN"), 10.0F, 10.0F);
|
||||
this.expShopUI = new PaginatedGui(6, 45, ChatColor.DARK_GRAY + openFor.getName() + " Vaults (" + hashMap.size() + " Unique)");
|
||||
this.expShopUI.setDefaultClickAction((event) -> {
|
||||
event.setCancelled(true);
|
||||
});
|
||||
this.expShopUI.getFiller().fillBottom(new GuiItem(this.createFillerItem()));
|
||||
ItemStack prevPage = new ItemStack(Material.ARROW);
|
||||
ItemMeta prevMeta = prevPage.getItemMeta();
|
||||
prevMeta.setDisplayName(CC.translate("&c<- Previous Page"));
|
||||
List<String> prevLore = new ArrayList<>();
|
||||
prevLore.add(CC.translate("&7Right-Click&7 to go to the previous page."));
|
||||
prevMeta.setLore(prevLore);
|
||||
prevPage.setItemMeta(prevMeta);
|
||||
ItemStack nextPage = new ItemStack(Material.ARROW);
|
||||
ItemMeta nextMeta = nextPage.getItemMeta();
|
||||
nextMeta.setDisplayName(CC.translate("&aNext Page ->"));
|
||||
List<String> nextLore = new ArrayList<>();
|
||||
nextLore.add(CC.translate("&7Right-Click&7 to go to the next page."));
|
||||
nextMeta.setLore(nextLore);
|
||||
nextPage.setItemMeta(nextMeta);
|
||||
this.expShopUI.setItem(6, 1, new GuiItem(prevPage, (event) -> {
|
||||
this.expShopUI.previous();
|
||||
event.setCancelled(true);
|
||||
}));
|
||||
this.expShopUI.setItem(6, 9, new GuiItem(nextPage, (event) -> {
|
||||
this.expShopUI.next();
|
||||
event.setCancelled(true);
|
||||
}));
|
||||
|
||||
for (Map.Entry<Integer, ArrayList<ItemStack>> entry : hashMap.entrySet()) {
|
||||
int key = entry.getKey();
|
||||
List<ItemStack> items = entry.getValue();
|
||||
for (ItemStack itemStack : items) {
|
||||
ItemMeta meta = itemStack.getItemMeta();
|
||||
meta.setDisplayName(CC.translate(meta.getDisplayName() + " &f&c&lVault &f#" + key));
|
||||
|
||||
List<String> lore = meta.hasLore() ? meta.getLore() : new ArrayList<>();
|
||||
|
||||
lore.add("");
|
||||
lore.add(CC.translate("&7&nLeft-Click&7 to open vault &f&n#" + key + "&7."));
|
||||
meta.setLore(lore);
|
||||
itemStack.setItemMeta(meta);
|
||||
NBTItem nbti = new NBTItem(itemStack);
|
||||
nbti.setInteger("vaultNr", key);
|
||||
this.expShopUI.addItem(new GuiItem(nbti.getItem(), (event) -> {
|
||||
int vaultNr = nbti.getInteger("vaultNr");
|
||||
SearchCommand.openVault(executor, openFor.getUniqueId(), vaultNr);
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public ItemStack createFillerItem() {
|
||||
ItemStack item = new ItemStack(Material.valueOf("STAINED_GLASS_PANE"), 1, (short)7);
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
meta.setDisplayName(CC.translate("&f"));
|
||||
item.setItemMeta(meta);
|
||||
return item;
|
||||
}
|
||||
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.drtshock.playervaults.guis;
|
||||
|
||||
import com.drtshock.playervaults.data.PlayerVaultsPlayer;
|
||||
import dev.triumphteam.gui.guis.GuiItem;
|
||||
import dev.triumphteam.gui.guis.PaginatedGui;
|
||||
import net.crankedpvp.crankedutils.utils.LuckpermUtils;
|
||||
import net.crankedpvp.crankedutils.utils.items.ItemBuilder;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.inventory.ClickType;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class SelectPlayerVaultInventory {
|
||||
|
||||
private final static Map<String, Integer> ranksAndPvs = new HashMap<String, Integer>() {{
|
||||
put("default", 3);
|
||||
put("explorer", 6);
|
||||
put("corrupt", 9);
|
||||
put("medusa", 12);
|
||||
put("dracula", 16);
|
||||
put("satan", 30);
|
||||
put("media", 30);
|
||||
}};
|
||||
|
||||
private final PaginatedGui selectPVInventory;
|
||||
|
||||
public PaginatedGui getSelectPVInventory() {
|
||||
return this.selectPVInventory;
|
||||
}
|
||||
|
||||
public SelectPlayerVaultInventory(PlayerVaultsPlayer playerVaultsObject) {
|
||||
this.selectPVInventory = new PaginatedGui(6, 54, playerVaultsObject.getName() + "'s Player Vaults");
|
||||
this.selectPVInventory.setDefaultClickAction((event) -> event.setCancelled(true));
|
||||
|
||||
|
||||
if(Bukkit.getPlayer(playerVaultsObject.getPlayerUUID()) == null) return;
|
||||
Player player = Bukkit.getPlayer(playerVaultsObject.getPlayerUUID());
|
||||
|
||||
int amountOfPvs = 0;
|
||||
for(String s : ranksAndPvs.keySet()) {
|
||||
if(LuckpermUtils.hasHigherRank(player, s)) amountOfPvs = ranksAndPvs.get(s);
|
||||
}
|
||||
|
||||
for(int i = 1; i <= amountOfPvs; i++) {
|
||||
Material material = playerVaultsObject.getPlayerVaultItemMap().containsKey(i) ? playerVaultsObject.getPlayerVaultItemMap().get(i).getMaterial() : Material.EMERALD;
|
||||
ItemBuilder itemBuilder = new ItemBuilder(material, "&c&l/pv " + i,
|
||||
"&cLeft Click: &fOpen vault",
|
||||
"&cRight Click: &fRename vault",
|
||||
"&cMiddle Click: &fChange vault material");
|
||||
ItemStack itemStack = itemBuilder.colorize().build();
|
||||
int finalI = i;
|
||||
this.selectPVInventory.addItem(new GuiItem(itemStack, event -> {
|
||||
if(event.getClick().equals(ClickType.LEFT)) {
|
||||
player.performCommand("pv " + finalI);
|
||||
return;
|
||||
}
|
||||
if(event.getClick().equals(ClickType.MIDDLE)) {
|
||||
ChangeMaterialInventory changeMaterialInventory = new ChangeMaterialInventory(finalI, playerVaultsObject);
|
||||
changeMaterialInventory.getSelectPVInventory().open(player);
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
+1139
File diff suppressed because it is too large
Load Diff
+49
@@ -0,0 +1,49 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.impl.ConfigBeanImpl;
|
||||
|
||||
/**
|
||||
* Factory for automatically creating a Java class from a {@link Config}.
|
||||
* See {@link #create(Config,Class)}.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*/
|
||||
public class ConfigBeanFactory {
|
||||
|
||||
/**
|
||||
* Creates an instance of a class, initializing its fields from a {@link Config}.
|
||||
*
|
||||
* Example usage:
|
||||
*
|
||||
* <pre>
|
||||
* Config configSource = ConfigFactory.load().getConfig("foo");
|
||||
* FooConfig config = ConfigBeanFactory.create(configSource, FooConfig.class);
|
||||
* </pre>
|
||||
*
|
||||
* The Java class should follow JavaBean conventions. Field types
|
||||
* can be any of the types you can normally get from a {@link
|
||||
* Config}, including <code>java.time.Duration</code> or {@link
|
||||
* ConfigMemorySize}. Fields may also be another JavaBean-style
|
||||
* class.
|
||||
*
|
||||
* Fields are mapped to config by converting the config key to
|
||||
* camel case. So the key <code>foo-bar</code> becomes JavaBean
|
||||
* setter <code>setFooBar</code>.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @param config source of config information
|
||||
* @param clazz class to be instantiated
|
||||
* @param <T> the type of the class to be instantiated
|
||||
* @return an instance of the class populated with data from the config
|
||||
* @throws ConfigException.BadBean
|
||||
* If something is wrong with the JavaBean
|
||||
* @throws ConfigException.ValidationFailed
|
||||
* If the config doesn't conform to the bean's implied schema
|
||||
* @throws ConfigException
|
||||
* Can throw the same exceptions as the getters on <code>Config</code>
|
||||
*/
|
||||
public static <T> T create(Config config, Class<T> clazz) {
|
||||
return ConfigBeanImpl.createInternal(config, clazz);
|
||||
}
|
||||
}
|
||||
+447
@@ -0,0 +1,447 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.impl.ConfigImplUtil;
|
||||
|
||||
/**
|
||||
* All exceptions thrown by the library are subclasses of
|
||||
* <code>ConfigException</code>.
|
||||
*/
|
||||
public abstract class ConfigException extends RuntimeException implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
final private transient ConfigOrigin origin;
|
||||
|
||||
protected ConfigException(ConfigOrigin origin, String message,
|
||||
Throwable cause) {
|
||||
super(origin.description() + ": " + message, cause);
|
||||
this.origin = origin;
|
||||
}
|
||||
|
||||
protected ConfigException(ConfigOrigin origin, String message) {
|
||||
this(origin.description() + ": " + message, null);
|
||||
}
|
||||
|
||||
protected ConfigException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
this.origin = null;
|
||||
}
|
||||
|
||||
protected ConfigException(String message) {
|
||||
this(message, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an "origin" (such as a filename and line number) for the
|
||||
* exception, or null if none is available. If there's no sensible origin
|
||||
* for a given exception, or the kind of exception doesn't meaningfully
|
||||
* relate to a particular origin file, this returns null. Never assume this
|
||||
* will return non-null, it can always return null.
|
||||
*
|
||||
* @return origin of the problem, or null if unknown/inapplicable
|
||||
*/
|
||||
public ConfigOrigin origin() {
|
||||
return origin;
|
||||
}
|
||||
|
||||
// we customize serialization because ConfigOrigin isn't
|
||||
// serializable and we don't want it to be (don't want to
|
||||
// support it)
|
||||
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
|
||||
out.defaultWriteObject();
|
||||
ConfigImplUtil.writeOrigin(out, origin);
|
||||
}
|
||||
|
||||
// For deserialization - uses reflection to set the final origin field on the object
|
||||
private static <T> void setOriginField(T hasOriginField, Class<T> clazz,
|
||||
ConfigOrigin origin) throws IOException {
|
||||
// circumvent "final"
|
||||
Field f;
|
||||
try {
|
||||
f = clazz.getDeclaredField("origin");
|
||||
} catch (NoSuchFieldException e) {
|
||||
throw new IOException(clazz.getSimpleName() + " has no origin field?", e);
|
||||
} catch (SecurityException e) {
|
||||
throw new IOException("unable to fill out origin field in " +
|
||||
clazz.getSimpleName(), e);
|
||||
}
|
||||
f.setAccessible(true);
|
||||
try {
|
||||
f.set(hasOriginField, origin);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new IOException("unable to set origin field", e);
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new IOException("unable to set origin field", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void readObject(java.io.ObjectInputStream in) throws IOException,
|
||||
ClassNotFoundException {
|
||||
in.defaultReadObject();
|
||||
ConfigOrigin origin = ConfigImplUtil.readOrigin(in);
|
||||
setOriginField(this, ConfigException.class, origin);
|
||||
}
|
||||
|
||||
/**
|
||||
* Exception indicating that the type of a value does not match the type you
|
||||
* requested.
|
||||
*
|
||||
*/
|
||||
public static class WrongType extends ConfigException {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public WrongType(ConfigOrigin origin, String path, String expected, String actual,
|
||||
Throwable cause) {
|
||||
super(origin, path + " has type " + actual + " rather than " + expected, cause);
|
||||
}
|
||||
|
||||
public WrongType(ConfigOrigin origin, String path, String expected, String actual) {
|
||||
this(origin, path, expected, actual, null);
|
||||
}
|
||||
|
||||
public WrongType(ConfigOrigin origin, String message, Throwable cause) {
|
||||
super(origin, message, cause);
|
||||
}
|
||||
|
||||
public WrongType(ConfigOrigin origin, String message) {
|
||||
super(origin, message, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Exception indicates that the setting was never set to anything, not even
|
||||
* null.
|
||||
*/
|
||||
public static class Missing extends ConfigException {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public Missing(String path, Throwable cause) {
|
||||
super("No configuration setting found for key '" + path + "'",
|
||||
cause);
|
||||
}
|
||||
|
||||
public Missing(String path) {
|
||||
this(path, null);
|
||||
}
|
||||
|
||||
protected Missing(ConfigOrigin origin, String message, Throwable cause) {
|
||||
super(origin, message, cause);
|
||||
}
|
||||
|
||||
protected Missing(ConfigOrigin origin, String message) {
|
||||
this(origin, message, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Exception indicates that the setting was treated as missing because it
|
||||
* was set to null.
|
||||
*/
|
||||
public static class Null extends Missing {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private static String makeMessage(String path, String expected) {
|
||||
if (expected != null) {
|
||||
return "Configuration key '" + path
|
||||
+ "' is set to null but expected " + expected;
|
||||
} else {
|
||||
return "Configuration key '" + path + "' is null";
|
||||
}
|
||||
}
|
||||
|
||||
public Null(ConfigOrigin origin, String path, String expected,
|
||||
Throwable cause) {
|
||||
super(origin, makeMessage(path, expected), cause);
|
||||
}
|
||||
|
||||
public Null(ConfigOrigin origin, String path, String expected) {
|
||||
this(origin, path, expected, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Exception indicating that a value was messed up, for example you may have
|
||||
* asked for a duration and the value can't be sensibly parsed as a
|
||||
* duration.
|
||||
*
|
||||
*/
|
||||
public static class BadValue extends ConfigException {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public BadValue(ConfigOrigin origin, String path, String message,
|
||||
Throwable cause) {
|
||||
super(origin, "Invalid value at '" + path + "': " + message, cause);
|
||||
}
|
||||
|
||||
public BadValue(ConfigOrigin origin, String path, String message) {
|
||||
this(origin, path, message, null);
|
||||
}
|
||||
|
||||
public BadValue(String path, String message, Throwable cause) {
|
||||
super("Invalid value at '" + path + "': " + message, cause);
|
||||
}
|
||||
|
||||
public BadValue(String path, String message) {
|
||||
this(path, message, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Exception indicating that a path expression was invalid. Try putting
|
||||
* double quotes around path elements that contain "special" characters.
|
||||
*
|
||||
*/
|
||||
public static class BadPath extends ConfigException {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public BadPath(ConfigOrigin origin, String path, String message,
|
||||
Throwable cause) {
|
||||
super(origin,
|
||||
path != null ? ("Invalid path '" + path + "': " + message)
|
||||
: message, cause);
|
||||
}
|
||||
|
||||
public BadPath(ConfigOrigin origin, String path, String message) {
|
||||
this(origin, path, message, null);
|
||||
}
|
||||
|
||||
public BadPath(String path, String message, Throwable cause) {
|
||||
super(path != null ? ("Invalid path '" + path + "': " + message)
|
||||
: message, cause);
|
||||
}
|
||||
|
||||
public BadPath(String path, String message) {
|
||||
this(path, message, null);
|
||||
}
|
||||
|
||||
public BadPath(ConfigOrigin origin, String message) {
|
||||
this(origin, null, message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Exception indicating that there's a bug in something (possibly the
|
||||
* library itself) or the runtime environment is broken. This exception
|
||||
* should never be handled; instead, something should be fixed to keep the
|
||||
* exception from occurring. This exception can be thrown by any method in
|
||||
* the library.
|
||||
*/
|
||||
public static class BugOrBroken extends ConfigException {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public BugOrBroken(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public BugOrBroken(String message) {
|
||||
this(message, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Exception indicating that there was an IO error.
|
||||
*
|
||||
*/
|
||||
public static class IO extends ConfigException {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public IO(ConfigOrigin origin, String message, Throwable cause) {
|
||||
super(origin, message, cause);
|
||||
}
|
||||
|
||||
public IO(ConfigOrigin origin, String message) {
|
||||
this(origin, message, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Exception indicating that there was a parse error.
|
||||
*
|
||||
*/
|
||||
public static class Parse extends ConfigException {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public Parse(ConfigOrigin origin, String message, Throwable cause) {
|
||||
super(origin, message, cause);
|
||||
}
|
||||
|
||||
public Parse(ConfigOrigin origin, String message) {
|
||||
this(origin, message, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Exception indicating that a substitution did not resolve to anything.
|
||||
* Thrown by {@link Config#resolve}.
|
||||
*/
|
||||
public static class UnresolvedSubstitution extends Parse {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public UnresolvedSubstitution(ConfigOrigin origin, String detail, Throwable cause) {
|
||||
super(origin, "Could not resolve substitution to a value: " + detail, cause);
|
||||
}
|
||||
|
||||
public UnresolvedSubstitution(ConfigOrigin origin, String detail) {
|
||||
this(origin, detail, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Exception indicating that you tried to use a function that requires
|
||||
* substitutions to be resolved, but substitutions have not been resolved
|
||||
* (that is, {@link Config#resolve} was not called). This is always a bug in
|
||||
* either application code or the library; it's wrong to write a handler for
|
||||
* this exception because you should be able to fix the code to avoid it by
|
||||
* adding calls to {@link Config#resolve}.
|
||||
*/
|
||||
public static class NotResolved extends BugOrBroken {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public NotResolved(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public NotResolved(String message) {
|
||||
this(message, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Information about a problem that occurred in {@link Config#checkValid}. A
|
||||
* {@link ConfigException.ValidationFailed} exception thrown from
|
||||
* <code>checkValid()</code> includes a list of problems encountered.
|
||||
*/
|
||||
public static class ValidationProblem implements Serializable {
|
||||
|
||||
final private String path;
|
||||
final private transient ConfigOrigin origin;
|
||||
final private String problem;
|
||||
|
||||
public ValidationProblem(String path, ConfigOrigin origin, String problem) {
|
||||
this.path = path;
|
||||
this.origin = origin;
|
||||
this.problem = problem;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the config setting causing the problem.
|
||||
* @return the path of the problem setting
|
||||
*/
|
||||
public String path() {
|
||||
return path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns where the problem occurred (origin may include info on the
|
||||
* file, line number, etc.).
|
||||
* @return the origin of the problem setting
|
||||
*/
|
||||
public ConfigOrigin origin() {
|
||||
return origin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a description of the problem.
|
||||
* @return description of the problem
|
||||
*/
|
||||
public String problem() {
|
||||
return problem;
|
||||
}
|
||||
|
||||
// We customize serialization because ConfigOrigin isn't
|
||||
// serializable and we don't want it to be
|
||||
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
|
||||
out.defaultWriteObject();
|
||||
ConfigImplUtil.writeOrigin(out, origin);
|
||||
}
|
||||
|
||||
private void readObject(java.io.ObjectInputStream in) throws IOException,
|
||||
ClassNotFoundException {
|
||||
in.defaultReadObject();
|
||||
ConfigOrigin origin = ConfigImplUtil.readOrigin(in);
|
||||
setOriginField(this, ValidationProblem.class, origin);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ValidationProblem(" + path + "," + origin + "," + problem + ")";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Exception indicating that {@link Config#checkValid} found validity
|
||||
* problems. The problems are available via the {@link #problems()} method.
|
||||
* The <code>getMessage()</code> of this exception is a potentially very
|
||||
* long string listing all the problems found.
|
||||
*/
|
||||
public static class ValidationFailed extends ConfigException {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
final private Iterable<ValidationProblem> problems;
|
||||
|
||||
public ValidationFailed(Iterable<ValidationProblem> problems) {
|
||||
super(makeMessage(problems), null);
|
||||
this.problems = problems;
|
||||
}
|
||||
|
||||
public Iterable<ValidationProblem> problems() {
|
||||
return problems;
|
||||
}
|
||||
|
||||
private static String makeMessage(Iterable<ValidationProblem> problems) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (ValidationProblem p : problems) {
|
||||
sb.append(p.origin().description());
|
||||
sb.append(": ");
|
||||
sb.append(p.path());
|
||||
sb.append(": ");
|
||||
sb.append(p.problem());
|
||||
sb.append(", ");
|
||||
}
|
||||
if (sb.length() == 0)
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"ValidationFailed must have a non-empty list of problems");
|
||||
sb.setLength(sb.length() - 2); // chop comma and space
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Some problem with a JavaBean we are trying to initialize.
|
||||
* @since 1.3.0
|
||||
*/
|
||||
public static class BadBean extends BugOrBroken {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public BadBean(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public BadBean(String message) {
|
||||
this(message, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Exception that doesn't fall into any other category.
|
||||
*/
|
||||
public static class Generic extends ConfigException {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public Generic(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public Generic(String message) {
|
||||
this(message, null);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+1066
File diff suppressed because it is too large
Load Diff
+56
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
|
||||
/**
|
||||
* Context provided to a {@link ConfigIncluder}; this interface is only useful
|
||||
* inside a {@code ConfigIncluder} implementation, and is not intended for apps
|
||||
* to implement.
|
||||
*
|
||||
* <p>
|
||||
* <em>Do not implement this interface</em>; it should only be implemented by
|
||||
* the config library. Arbitrary implementations will not work because the
|
||||
* library internals assume a specific concrete implementation. Also, this
|
||||
* interface is likely to grow new methods over time, so third-party
|
||||
* implementations will break.
|
||||
*/
|
||||
public interface ConfigIncludeContext {
|
||||
/**
|
||||
* Tries to find a name relative to whatever is doing the including, for
|
||||
* example in the same directory as the file doing the including. Returns
|
||||
* null if it can't meaningfully create a relative name. The returned
|
||||
* parseable may not exist; this function is not required to do any IO, just
|
||||
* compute what the name would be.
|
||||
*
|
||||
* The passed-in filename has to be a complete name (with extension), not
|
||||
* just a basename. (Include statements in config files are allowed to give
|
||||
* just a basename.)
|
||||
*
|
||||
* @param filename
|
||||
* the name to make relative to the resource doing the including
|
||||
* @return parseable item relative to the resource doing the including, or
|
||||
* null
|
||||
*/
|
||||
ConfigParseable relativeTo(String filename);
|
||||
|
||||
/**
|
||||
* Parse options to use (if you use another method to get a
|
||||
* {@link ConfigParseable} then use {@link ConfigParseable#options()}
|
||||
* instead though).
|
||||
*
|
||||
* @return the parse options
|
||||
*/
|
||||
ConfigParseOptions parseOptions();
|
||||
|
||||
|
||||
/**
|
||||
* Copy this {@link ConfigIncludeContext} giving it a new value for its parseOptions.
|
||||
*
|
||||
* @param options new parse options to use
|
||||
*
|
||||
* @return the updated copy of this context
|
||||
*/
|
||||
ConfigIncludeContext setParseOptions(ConfigParseOptions options);
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
/**
|
||||
* Implement this interface and provide an instance to
|
||||
* {@link ConfigParseOptions#setIncluder ConfigParseOptions.setIncluder()} to
|
||||
* customize handling of {@code include} statements in config files. You may
|
||||
* also want to implement {@link ConfigIncluderClasspath},
|
||||
* {@link ConfigIncluderFile}, and {@link ConfigIncluderURL}, or not.
|
||||
*/
|
||||
public interface ConfigIncluder {
|
||||
/**
|
||||
* Returns a new includer that falls back to the given includer. This is how
|
||||
* you can obtain the default includer; it will be provided as a fallback.
|
||||
* It's up to your includer to chain to it if you want to. You might want to
|
||||
* merge any files found by the fallback includer with any objects you load
|
||||
* yourself.
|
||||
*
|
||||
* It's important to handle the case where you already have the fallback
|
||||
* with a "return this", i.e. this method should not create a new object if
|
||||
* the fallback is the same one you already have. The same fallback may be
|
||||
* added repeatedly.
|
||||
*
|
||||
* @param fallback the previous includer for chaining
|
||||
* @return a new includer
|
||||
*/
|
||||
ConfigIncluder withFallback(ConfigIncluder fallback);
|
||||
|
||||
/**
|
||||
* Parses another item to be included. The returned object typically would
|
||||
* not have substitutions resolved. You can throw a ConfigException here to
|
||||
* abort parsing, or return an empty object, but may not return null.
|
||||
*
|
||||
* This method is used for a "heuristic" include statement that does not
|
||||
* specify file, URL, or classpath resource. If the include statement does
|
||||
* specify, then the same class implementing {@link ConfigIncluder} must
|
||||
* also implement {@link ConfigIncluderClasspath},
|
||||
* {@link ConfigIncluderFile}, or {@link ConfigIncluderURL} as needed, or a
|
||||
* default includer will be used.
|
||||
*
|
||||
* @param context
|
||||
* some info about the include context
|
||||
* @param what
|
||||
* the include statement's argument
|
||||
* @return a non-null ConfigObject
|
||||
*/
|
||||
ConfigObject include(ConfigIncludeContext context, String what);
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
/**
|
||||
* Implement this <em>in addition to</em> {@link ConfigIncluder} if you want to
|
||||
* support inclusion of files with the {@code include classpath("resource")}
|
||||
* syntax. If you do not implement this but do implement {@link ConfigIncluder},
|
||||
* attempts to load classpath resources will use the default includer.
|
||||
*/
|
||||
public interface ConfigIncluderClasspath {
|
||||
/**
|
||||
* Parses another item to be included. The returned object typically would
|
||||
* not have substitutions resolved. You can throw a ConfigException here to
|
||||
* abort parsing, or return an empty object, but may not return null.
|
||||
*
|
||||
* @param context
|
||||
* some info about the include context
|
||||
* @param what
|
||||
* the include statement's argument
|
||||
* @return a non-null ConfigObject
|
||||
*/
|
||||
ConfigObject includeResources(ConfigIncludeContext context, String what);
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* Implement this <em>in addition to</em> {@link ConfigIncluder} if you want to
|
||||
* support inclusion of files with the {@code include file("filename")} syntax.
|
||||
* If you do not implement this but do implement {@link ConfigIncluder},
|
||||
* attempts to load files will use the default includer.
|
||||
*/
|
||||
public interface ConfigIncluderFile {
|
||||
/**
|
||||
* Parses another item to be included. The returned object typically would
|
||||
* not have substitutions resolved. You can throw a ConfigException here to
|
||||
* abort parsing, or return an empty object, but may not return null.
|
||||
*
|
||||
* @param context
|
||||
* some info about the include context
|
||||
* @param what
|
||||
* the include statement's argument
|
||||
* @return a non-null ConfigObject
|
||||
*/
|
||||
ConfigObject includeFile(ConfigIncludeContext context, File what);
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
import java.net.URL;
|
||||
|
||||
/**
|
||||
* Implement this <em>in addition to</em> {@link ConfigIncluder} if you want to
|
||||
* support inclusion of files with the {@code include url("http://example.com")}
|
||||
* syntax. If you do not implement this but do implement {@link ConfigIncluder},
|
||||
* attempts to load URLs will use the default includer.
|
||||
*/
|
||||
public interface ConfigIncluderURL {
|
||||
/**
|
||||
* Parses another item to be included. The returned object typically would
|
||||
* not have substitutions resolved. You can throw a ConfigException here to
|
||||
* abort parsing, or return an empty object, but may not return null.
|
||||
*
|
||||
* @param context
|
||||
* some info about the include context
|
||||
* @param what
|
||||
* the include statement's argument
|
||||
* @return a non-null ConfigObject
|
||||
*/
|
||||
ConfigObject includeURL(ConfigIncludeContext context, URL what);
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Subtype of {@link ConfigValue} representing a list value, as in JSON's
|
||||
* {@code [1,2,3]} syntax.
|
||||
*
|
||||
* <p>
|
||||
* {@code ConfigList} implements {@code java.util.List<ConfigValue>} so you can
|
||||
* use it like a regular Java list. Or call {@link #unwrapped()} to unwrap the
|
||||
* list elements into plain Java values.
|
||||
*
|
||||
* <p>
|
||||
* Like all {@link ConfigValue} subtypes, {@code ConfigList} is immutable. This
|
||||
* makes it threadsafe and you never have to create "defensive copies." The
|
||||
* mutator methods from {@link java.util.List} all throw
|
||||
* {@link java.lang.UnsupportedOperationException}.
|
||||
*
|
||||
* <p>
|
||||
* The {@link ConfigValue#valueType} method on a list returns
|
||||
* {@link ConfigValueType#LIST}.
|
||||
*
|
||||
* <p>
|
||||
* <em>Do not implement {@code ConfigList}</em>; it should only be implemented
|
||||
* by the config library. Arbitrary implementations will not work because the
|
||||
* library internals assume a specific concrete implementation. Also, this
|
||||
* interface is likely to grow new methods over time, so third-party
|
||||
* implementations will break.
|
||||
*
|
||||
*/
|
||||
public interface ConfigList extends List<ConfigValue>, ConfigValue {
|
||||
|
||||
/**
|
||||
* Recursively unwraps the list, returning a list of plain Java values such
|
||||
* as Integer or String or whatever is in the list.
|
||||
*
|
||||
* @return a {@link java.util.List} containing plain Java objects
|
||||
*/
|
||||
@Override
|
||||
List<Object> unwrapped();
|
||||
|
||||
@Override
|
||||
ConfigList withOrigin(ConfigOrigin origin);
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
/**
|
||||
* This method allows you to alter default config loading strategy for all the code which
|
||||
* calls {@link ConfigFactory#load}.
|
||||
*
|
||||
* Usually you don't have to implement this interface but it may be required
|
||||
* when you fixing a improperly implemented library with unavailable source code.
|
||||
*
|
||||
* You have to define VM property {@code config.strategy} to replace default strategy with your own.
|
||||
*/
|
||||
public interface ConfigLoadingStrategy {
|
||||
/**
|
||||
* This method must load and parse application config.
|
||||
*
|
||||
* @param parseOptions {@link ConfigParseOptions} to use
|
||||
* @return loaded config
|
||||
*/
|
||||
Config parseApplicationConfig(ConfigParseOptions parseOptions);
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Copyright (C) 2015 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
/**
|
||||
* An immutable class representing an amount of memory. Use
|
||||
* static factory methods such as {@link
|
||||
* ConfigMemorySize#ofBytes(long)} to create instances.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*/
|
||||
public final class ConfigMemorySize {
|
||||
private final long bytes;
|
||||
|
||||
private ConfigMemorySize(long bytes) {
|
||||
if (bytes < 0)
|
||||
throw new IllegalArgumentException("Attempt to construct ConfigMemorySize with negative number: " + bytes);
|
||||
this.bytes = bytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a ConfigMemorySize representing the given
|
||||
* number of bytes.
|
||||
* @since 1.3.0
|
||||
* @param bytes a number of bytes
|
||||
* @return an instance representing the number of bytes
|
||||
*/
|
||||
public static ConfigMemorySize ofBytes(long bytes) {
|
||||
return new ConfigMemorySize(bytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the size in bytes.
|
||||
* @since 1.3.0
|
||||
* @return how many bytes
|
||||
*/
|
||||
public long toBytes() {
|
||||
return bytes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ConfigMemorySize(" + bytes + ")";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (other instanceof ConfigMemorySize) {
|
||||
return ((ConfigMemorySize)other).bytes == this.bytes;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
// in Java 8 this can become Long.hashCode(bytes)
|
||||
return Long.valueOf(bytes).hashCode();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
/**
|
||||
* Marker for types whose instances can be merged, that is {@link Config} and
|
||||
* {@link ConfigValue}. Instances of {@code Config} and {@code ConfigValue} can
|
||||
* be combined into a single new instance using the
|
||||
* {@link ConfigMergeable#withFallback withFallback()} method.
|
||||
*
|
||||
* <p>
|
||||
* <em>Do not implement this interface</em>; it should only be implemented by
|
||||
* the config library. Arbitrary implementations will not work because the
|
||||
* library internals assume a specific concrete implementation. Also, this
|
||||
* interface is likely to grow new methods over time, so third-party
|
||||
* implementations will break.
|
||||
*/
|
||||
public interface ConfigMergeable {
|
||||
/**
|
||||
* Returns a new value computed by merging this value with another, with
|
||||
* keys in this value "winning" over the other one.
|
||||
*
|
||||
* <p>
|
||||
* This associative operation may be used to combine configurations from
|
||||
* multiple sources (such as multiple configuration files).
|
||||
*
|
||||
* <p>
|
||||
* The semantics of merging are described in the <a
|
||||
* href="https://github.com/lightbend/config/blob/master/HOCON.md">spec
|
||||
* for HOCON</a>. Merging typically occurs when either the same object is
|
||||
* created twice in the same file, or two config files are both loaded. For
|
||||
* example:
|
||||
*
|
||||
* <pre>
|
||||
* foo = { a: 42 }
|
||||
* foo = { b: 43 }
|
||||
* </pre>
|
||||
*
|
||||
* Here, the two objects are merged as if you had written:
|
||||
*
|
||||
* <pre>
|
||||
* foo = { a: 42, b: 43 }
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* Only {@link ConfigObject} and {@link Config} instances do anything in
|
||||
* this method (they need to merge the fallback keys into themselves). All
|
||||
* other values just return the original value, since they automatically
|
||||
* override any fallback. This means that objects do not merge "across"
|
||||
* non-objects; if you write
|
||||
* <code>object.withFallback(nonObject).withFallback(otherObject)</code>,
|
||||
* then <code>otherObject</code> will simply be ignored. This is an
|
||||
* intentional part of how merging works, because non-objects such as
|
||||
* strings and integers replace (rather than merging with) any prior value:
|
||||
*
|
||||
* <pre>
|
||||
* foo = { a: 42 }
|
||||
* foo = 10
|
||||
* </pre>
|
||||
*
|
||||
* Here, the number 10 "wins" and the value of <code>foo</code> would be
|
||||
* simply 10. Again, for details see the spec.
|
||||
*
|
||||
* @param other
|
||||
* an object whose keys should be used as fallbacks, if the keys
|
||||
* are not present in this one
|
||||
* @return a new object (or the original one, if the fallback doesn't get
|
||||
* used)
|
||||
*/
|
||||
ConfigMergeable withFallback(ConfigMergeable other);
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Subtype of {@link ConfigValue} representing an object (AKA dictionary or map)
|
||||
* value, as in JSON's curly brace <code>{ "a" : 42 }</code> syntax.
|
||||
*
|
||||
* <p>
|
||||
* An object may also be viewed as a {@link Config} by calling
|
||||
* {@link ConfigObject#toConfig()}.
|
||||
*
|
||||
* <p>
|
||||
* {@code ConfigObject} implements {@code java.util.Map<String, ConfigValue>} so
|
||||
* you can use it like a regular Java map. Or call {@link #unwrapped()} to
|
||||
* unwrap the map to a map with plain Java values rather than
|
||||
* {@code ConfigValue}.
|
||||
*
|
||||
* <p>
|
||||
* Like all {@link ConfigValue} subtypes, {@code ConfigObject} is immutable.
|
||||
* This makes it threadsafe and you never have to create "defensive copies." The
|
||||
* mutator methods from {@link java.util.Map} all throw
|
||||
* {@link java.lang.UnsupportedOperationException}.
|
||||
*
|
||||
* <p>
|
||||
* The {@link ConfigValue#valueType} method on an object returns
|
||||
* {@link ConfigValueType#OBJECT}.
|
||||
*
|
||||
* <p>
|
||||
* In most cases you want to use the {@link Config} interface rather than this
|
||||
* one. Call {@link #toConfig()} to convert a {@code ConfigObject} to a
|
||||
* {@code Config}.
|
||||
*
|
||||
* <p>
|
||||
* The API for a {@code ConfigObject} is in terms of keys, while the API for a
|
||||
* {@link Config} is in terms of path expressions. Conceptually,
|
||||
* {@code ConfigObject} is a tree of maps from keys to values, while a
|
||||
* {@code Config} is a one-level map from paths to values.
|
||||
*
|
||||
* <p>
|
||||
* Use {@link ConfigUtil#joinPath} and {@link ConfigUtil#splitPath} to convert
|
||||
* between path expressions and individual path elements (keys).
|
||||
*
|
||||
* <p>
|
||||
* A {@code ConfigObject} may contain null values, which will have
|
||||
* {@link ConfigValue#valueType()} equal to {@link ConfigValueType#NULL}. If
|
||||
* {@link ConfigObject#get(Object)} returns Java's null then the key was not
|
||||
* present in the parsed file (or wherever this value tree came from). If
|
||||
* {@code get("key")} returns a {@link ConfigValue} with type
|
||||
* {@code ConfigValueType#NULL} then the key was set to null explicitly in the
|
||||
* config file.
|
||||
*
|
||||
* <p>
|
||||
* <em>Do not implement interface {@code ConfigObject}</em>; it should only be
|
||||
* implemented by the config library. Arbitrary implementations will not work
|
||||
* because the library internals assume a specific concrete implementation.
|
||||
* Also, this interface is likely to grow new methods over time, so third-party
|
||||
* implementations will break.
|
||||
*/
|
||||
public interface ConfigObject extends ConfigValue, Map<String, ConfigValue> {
|
||||
|
||||
/**
|
||||
* Converts this object to a {@link Config} instance, enabling you to use
|
||||
* path expressions to find values in the object. This is a constant-time
|
||||
* operation (it is not proportional to the size of the object).
|
||||
*
|
||||
* @return a {@link Config} with this object as its root
|
||||
*/
|
||||
Config toConfig();
|
||||
|
||||
/**
|
||||
* Recursively unwraps the object, returning a map from String to whatever
|
||||
* plain Java values are unwrapped from the object's values.
|
||||
*
|
||||
* @return a {@link java.util.Map} containing plain Java objects
|
||||
*/
|
||||
@Override
|
||||
Map<String, Object> unwrapped();
|
||||
|
||||
@Override
|
||||
ConfigObject withFallback(ConfigMergeable other);
|
||||
|
||||
/**
|
||||
* Gets a {@link ConfigValue} at the given key, or returns null if there is
|
||||
* no value. The returned {@link ConfigValue} may have
|
||||
* {@link ConfigValueType#NULL} or any other type, and the passed-in key
|
||||
* must be a key in this object (rather than a path expression).
|
||||
*
|
||||
* @param key
|
||||
* key to look up
|
||||
*
|
||||
* @return the value at the key or null if none
|
||||
*/
|
||||
@Override
|
||||
ConfigValue get(Object key);
|
||||
|
||||
/**
|
||||
* Clone the object with only the given key (and its children) retained; all
|
||||
* sibling keys are removed.
|
||||
*
|
||||
* @param key
|
||||
* key to keep
|
||||
* @return a copy of the object minus all keys except the one specified
|
||||
*/
|
||||
ConfigObject withOnlyKey(String key);
|
||||
|
||||
/**
|
||||
* Clone the object with the given key removed.
|
||||
*
|
||||
* @param key
|
||||
* key to remove
|
||||
* @return a copy of the object minus the specified key
|
||||
*/
|
||||
ConfigObject withoutKey(String key);
|
||||
|
||||
/**
|
||||
* Returns a {@code ConfigObject} based on this one, but with the given key
|
||||
* set to the given value. Does not modify this instance (since it's
|
||||
* immutable). If the key already has a value, that value is replaced. To
|
||||
* remove a value, use {@link ConfigObject#withoutKey(String)}.
|
||||
*
|
||||
* @param key
|
||||
* key to add
|
||||
* @param value
|
||||
* value at the new key
|
||||
* @return the new instance with the new map entry
|
||||
*/
|
||||
ConfigObject withValue(String key, ConfigValue value);
|
||||
|
||||
@Override
|
||||
ConfigObject withOrigin(ConfigOrigin origin);
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
import java.net.URL;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
/**
|
||||
* Represents the origin (such as filename and line number) of a
|
||||
* {@link ConfigValue} for use in error messages. Obtain the origin of a value
|
||||
* with {@link ConfigValue#origin}. Exceptions may have an origin, see
|
||||
* {@link ConfigException#origin}, but be careful because
|
||||
* <code>ConfigException.origin()</code> may return null.
|
||||
*
|
||||
* <p>
|
||||
* It's best to use this interface only for debugging; its accuracy is
|
||||
* "best effort" rather than guaranteed, and a potentially-noticeable amount of
|
||||
* memory could probably be saved if origins were not kept around, so in the
|
||||
* future there might be some option to discard origins.
|
||||
*
|
||||
* <p>
|
||||
* <em>Do not implement this interface</em>; it should only be implemented by
|
||||
* the config library. Arbitrary implementations will not work because the
|
||||
* library internals assume a specific concrete implementation. Also, this
|
||||
* interface is likely to grow new methods over time, so third-party
|
||||
* implementations will break.
|
||||
*/
|
||||
public interface ConfigOrigin {
|
||||
/**
|
||||
* Returns a string describing the origin of a value or exception. This will
|
||||
* never return null.
|
||||
*
|
||||
* @return string describing the origin
|
||||
*/
|
||||
public String description();
|
||||
|
||||
/**
|
||||
* Returns a filename describing the origin. This will return null if the
|
||||
* origin was not a file.
|
||||
*
|
||||
* @return filename of the origin or null
|
||||
*/
|
||||
public String filename();
|
||||
|
||||
/**
|
||||
* Returns a URL describing the origin. This will return null if the origin
|
||||
* has no meaningful URL.
|
||||
*
|
||||
* @return url of the origin or null
|
||||
*/
|
||||
public URL url();
|
||||
|
||||
/**
|
||||
* Returns a classpath resource name describing the origin. This will return
|
||||
* null if the origin was not a classpath resource.
|
||||
*
|
||||
* @return resource name of the origin or null
|
||||
*/
|
||||
public String resource();
|
||||
|
||||
/**
|
||||
* Returns a line number where the value or exception originated. This will
|
||||
* return -1 if there's no meaningful line number.
|
||||
*
|
||||
* @return line number or -1 if none is available
|
||||
*/
|
||||
public int lineNumber();
|
||||
|
||||
/**
|
||||
* Returns any comments that appeared to "go with" this place in the file.
|
||||
* Often an empty list, but never null. The details of this are subject to
|
||||
* change, but at the moment comments that are immediately before an array
|
||||
* element or object field, with no blank line after the comment, "go with"
|
||||
* that element or field.
|
||||
*
|
||||
* @return any comments that seemed to "go with" this origin, empty list if
|
||||
* none
|
||||
*/
|
||||
public List<String> comments();
|
||||
|
||||
/**
|
||||
* Returns a {@code ConfigOrigin} based on this one, but with the given
|
||||
* comments. Does not modify this instance or any {@code ConfigValue}s with
|
||||
* this origin (since they are immutable). To set the returned origin to a
|
||||
* {@code ConfigValue}, use {@link ConfigValue#withOrigin}.
|
||||
*
|
||||
* <p>
|
||||
* Note that when the given comments are equal to the comments on this object,
|
||||
* a new instance may not be created and {@code this} is returned directly.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @param comments the comments used on the returned origin
|
||||
* @return the ConfigOrigin with the given comments
|
||||
*/
|
||||
public ConfigOrigin withComments(List<String> comments);
|
||||
|
||||
/**
|
||||
* Returns a {@code ConfigOrigin} based on this one, but with the given
|
||||
* line number. This origin must be a FILE, URL or RESOURCE. Does not modify
|
||||
* this instance or any {@code ConfigValue}s with this origin (since they are
|
||||
* immutable). To set the returned origin to a {@code ConfigValue}, use
|
||||
* {@link ConfigValue#withOrigin}.
|
||||
*
|
||||
* <p>
|
||||
* Note that when the given lineNumber are equal to the lineNumber on this
|
||||
* object, a new instance may not be created and {@code this} is returned
|
||||
* directly.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @param lineNumber the new line number
|
||||
* @return the created ConfigOrigin
|
||||
*/
|
||||
public ConfigOrigin withLineNumber(int lineNumber);
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
import java.net.URL;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.impl.ConfigImpl;
|
||||
|
||||
/**
|
||||
* This class contains some static factory methods for building a {@link
|
||||
* ConfigOrigin}. {@code ConfigOrigin}s are automatically created when you
|
||||
* call other API methods to get a {@code ConfigValue} or {@code Config}.
|
||||
* But you can also set the origin of an existing {@code ConfigValue}, using
|
||||
* {@link ConfigValue#withOrigin(ConfigOrigin)}.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*/
|
||||
public final class ConfigOriginFactory {
|
||||
private ConfigOriginFactory() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the default origin for values when no other information is
|
||||
* provided. This is the origin used in {@link ConfigValueFactory
|
||||
* #fromAnyRef(Object)}.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @return the default origin
|
||||
*/
|
||||
public static ConfigOrigin newSimple() {
|
||||
return newSimple(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an origin with the given description.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @param description brief description of what the origin is
|
||||
* @return a new origin
|
||||
*/
|
||||
public static ConfigOrigin newSimple(String description) {
|
||||
return ConfigImpl.newSimpleOrigin(description);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a file origin with the given filename.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @param filename the filename of this origin
|
||||
* @return a new origin
|
||||
*/
|
||||
public static ConfigOrigin newFile(String filename) {
|
||||
return ConfigImpl.newFileOrigin(filename);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a url origin with the given URL object.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @param url the url of this origin
|
||||
* @return a new origin
|
||||
*/
|
||||
public static ConfigOrigin newURL(URL url) {
|
||||
return ConfigImpl.newURLOrigin(url);
|
||||
}
|
||||
}
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
|
||||
/**
|
||||
* A set of options related to parsing.
|
||||
*
|
||||
* <p>
|
||||
* This object is immutable, so the "setters" return a new object.
|
||||
*
|
||||
* <p>
|
||||
* Here is an example of creating a custom {@code ConfigParseOptions}:
|
||||
*
|
||||
* <pre>
|
||||
* ConfigParseOptions options = ConfigParseOptions.defaults()
|
||||
* .setSyntax(ConfigSyntax.JSON)
|
||||
* .setAllowMissing(false)
|
||||
* </pre>
|
||||
*
|
||||
*/
|
||||
public final class ConfigParseOptions {
|
||||
final ConfigSyntax syntax;
|
||||
final String originDescription;
|
||||
final boolean allowMissing;
|
||||
final ConfigIncluder includer;
|
||||
final ClassLoader classLoader;
|
||||
|
||||
private ConfigParseOptions(ConfigSyntax syntax, String originDescription, boolean allowMissing,
|
||||
ConfigIncluder includer, ClassLoader classLoader) {
|
||||
this.syntax = syntax;
|
||||
this.originDescription = originDescription;
|
||||
this.allowMissing = allowMissing;
|
||||
this.includer = includer;
|
||||
this.classLoader = classLoader;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets an instance of <code>ConfigParseOptions</code> with all fields
|
||||
* set to the default values. Start with this instance and make any
|
||||
* changes you need.
|
||||
* @return the default parse options
|
||||
*/
|
||||
public static ConfigParseOptions defaults() {
|
||||
return new ConfigParseOptions(null, null, true, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the file format. If set to null, try to guess from any available
|
||||
* filename extension; if guessing fails, assume {@link ConfigSyntax#CONF}.
|
||||
*
|
||||
* @param syntax
|
||||
* a syntax or {@code null} for best guess
|
||||
* @return options with the syntax set
|
||||
*/
|
||||
public ConfigParseOptions setSyntax(ConfigSyntax syntax) {
|
||||
if (this.syntax == syntax)
|
||||
return this;
|
||||
else
|
||||
return new ConfigParseOptions(syntax, this.originDescription, this.allowMissing,
|
||||
this.includer, this.classLoader);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current syntax option, which may be null for "any".
|
||||
* @return the current syntax or null
|
||||
*/
|
||||
public ConfigSyntax getSyntax() {
|
||||
return syntax;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a description for the thing being parsed. In most cases this will be
|
||||
* set up for you to something like the filename, but if you provide just an
|
||||
* input stream you might want to improve on it. Set to null to allow the
|
||||
* library to come up with something automatically. This description is the
|
||||
* basis for the {@link ConfigOrigin} of the parsed values.
|
||||
*
|
||||
* @param originDescription description to put in the {@link ConfigOrigin}
|
||||
* @return options with the origin description set
|
||||
*/
|
||||
public ConfigParseOptions setOriginDescription(String originDescription) {
|
||||
// findbugs complains about == here but is wrong, do not "fix"
|
||||
if (this.originDescription == originDescription)
|
||||
return this;
|
||||
else if (this.originDescription != null && originDescription != null
|
||||
&& this.originDescription.equals(originDescription))
|
||||
return this;
|
||||
else
|
||||
return new ConfigParseOptions(this.syntax, originDescription, this.allowMissing,
|
||||
this.includer, this.classLoader);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current origin description, which may be null for "automatic".
|
||||
* @return the current origin description or null
|
||||
*/
|
||||
public String getOriginDescription() {
|
||||
return originDescription;
|
||||
}
|
||||
|
||||
/** this is package-private, not public API */
|
||||
ConfigParseOptions withFallbackOriginDescription(String originDescription) {
|
||||
if (this.originDescription == null)
|
||||
return setOriginDescription(originDescription);
|
||||
else
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set to false to throw an exception if the item being parsed (for example
|
||||
* a file) is missing. Set to true to just return an empty document in that
|
||||
* case. Note that this setting applies on only to fetching the root document,
|
||||
* it has no effect on any nested includes.
|
||||
*
|
||||
* @param allowMissing true to silently ignore missing item
|
||||
* @return options with the "allow missing" flag set
|
||||
*/
|
||||
public ConfigParseOptions setAllowMissing(boolean allowMissing) {
|
||||
if (this.allowMissing == allowMissing)
|
||||
return this;
|
||||
else
|
||||
return new ConfigParseOptions(this.syntax, this.originDescription, allowMissing,
|
||||
this.includer, this.classLoader);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current "allow missing" flag.
|
||||
* @return whether we allow missing files
|
||||
*/
|
||||
public boolean getAllowMissing() {
|
||||
return allowMissing;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a {@link ConfigIncluder} which customizes how includes are handled.
|
||||
* null means to use the default includer.
|
||||
*
|
||||
* @param includer the includer to use or null for default
|
||||
* @return new version of the parse options with different includer
|
||||
*/
|
||||
public ConfigParseOptions setIncluder(ConfigIncluder includer) {
|
||||
if (this.includer == includer)
|
||||
return this;
|
||||
else
|
||||
return new ConfigParseOptions(this.syntax, this.originDescription, this.allowMissing,
|
||||
includer, this.classLoader);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepends a {@link ConfigIncluder} which customizes how
|
||||
* includes are handled. To prepend your includer, the
|
||||
* library calls {@link ConfigIncluder#withFallback} on your
|
||||
* includer to append the existing includer to it.
|
||||
*
|
||||
* @param includer the includer to prepend (may not be null)
|
||||
* @return new version of the parse options with different includer
|
||||
*/
|
||||
public ConfigParseOptions prependIncluder(ConfigIncluder includer) {
|
||||
if (includer == null)
|
||||
throw new NullPointerException("null includer passed to prependIncluder");
|
||||
if (this.includer == includer)
|
||||
return this;
|
||||
else if (this.includer != null)
|
||||
return setIncluder(includer.withFallback(this.includer));
|
||||
else
|
||||
return setIncluder(includer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends a {@link ConfigIncluder} which customizes how
|
||||
* includes are handled. To append, the library calls {@link
|
||||
* ConfigIncluder#withFallback} on the existing includer.
|
||||
*
|
||||
* @param includer the includer to append (may not be null)
|
||||
* @return new version of the parse options with different includer
|
||||
*/
|
||||
public ConfigParseOptions appendIncluder(ConfigIncluder includer) {
|
||||
if (includer == null)
|
||||
throw new NullPointerException("null includer passed to appendIncluder");
|
||||
if (this.includer == includer)
|
||||
return this;
|
||||
else if (this.includer != null)
|
||||
return setIncluder(this.includer.withFallback(includer));
|
||||
else
|
||||
return setIncluder(includer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current includer (will be null for the default includer).
|
||||
* @return current includer or null
|
||||
*/
|
||||
public ConfigIncluder getIncluder() {
|
||||
return includer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the class loader. If set to null,
|
||||
* <code>Thread.currentThread().getContextClassLoader()</code> will be used.
|
||||
*
|
||||
* @param loader
|
||||
* a class loader or {@code null} to use thread context class
|
||||
* loader
|
||||
* @return options with the class loader set
|
||||
*/
|
||||
public ConfigParseOptions setClassLoader(ClassLoader loader) {
|
||||
if (this.classLoader == loader)
|
||||
return this;
|
||||
else
|
||||
return new ConfigParseOptions(this.syntax, this.originDescription, this.allowMissing,
|
||||
this.includer, loader);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the class loader; never returns {@code null}, if the class loader was
|
||||
* unset, returns
|
||||
* <code>Thread.currentThread().getContextClassLoader()</code>.
|
||||
*
|
||||
* @return class loader to use
|
||||
*/
|
||||
public ClassLoader getClassLoader() {
|
||||
if (this.classLoader == null)
|
||||
return Thread.currentThread().getContextClassLoader();
|
||||
else
|
||||
return this.classLoader;
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
|
||||
/**
|
||||
* An opaque handle to something that can be parsed, obtained from
|
||||
* {@link ConfigIncludeContext}.
|
||||
*
|
||||
* <p>
|
||||
* <em>Do not implement this interface</em>; it should only be implemented by
|
||||
* the config library. Arbitrary implementations will not work because the
|
||||
* library internals assume a specific concrete implementation. Also, this
|
||||
* interface is likely to grow new methods over time, so third-party
|
||||
* implementations will break.
|
||||
*/
|
||||
public interface ConfigParseable {
|
||||
/**
|
||||
* Parse whatever it is. The options should come from
|
||||
* {@link ConfigParseable#options options()} but you could tweak them if you
|
||||
* like.
|
||||
*
|
||||
* @param options
|
||||
* parse options, should be based on the ones from
|
||||
* {@link ConfigParseable#options options()}
|
||||
* @return the parsed object
|
||||
*/
|
||||
ConfigObject parse(ConfigParseOptions options);
|
||||
|
||||
/**
|
||||
* Returns a {@link ConfigOrigin} describing the origin of the parseable
|
||||
* item.
|
||||
* @return the origin of the parseable item
|
||||
*/
|
||||
ConfigOrigin origin();
|
||||
|
||||
/**
|
||||
* Get the initial options, which can be modified then passed to parse().
|
||||
* These options will have the right description, includer, and other
|
||||
* parameters already set up.
|
||||
* @return the initial options
|
||||
*/
|
||||
ConfigParseOptions options();
|
||||
}
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* A set of options related to rendering a {@link ConfigValue}. Passed to
|
||||
* {@link ConfigValue#render(ConfigRenderOptions)}.
|
||||
*
|
||||
* <p>
|
||||
* Here is an example of creating a {@code ConfigRenderOptions}:
|
||||
*
|
||||
* <pre>
|
||||
* ConfigRenderOptions options =
|
||||
* ConfigRenderOptions.defaults().setComments(false)
|
||||
* </pre>
|
||||
*/
|
||||
public final class ConfigRenderOptions {
|
||||
private final boolean originComments;
|
||||
private final boolean comments;
|
||||
private final boolean formatted;
|
||||
private final boolean json;
|
||||
|
||||
private ConfigRenderOptions(boolean originComments, boolean comments, boolean formatted,
|
||||
boolean json) {
|
||||
this.originComments = originComments;
|
||||
this.comments = comments;
|
||||
this.formatted = formatted;
|
||||
this.json = json;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the default render options which are verbose (commented and
|
||||
* formatted). See {@link ConfigRenderOptions#concise} for stripped-down
|
||||
* options. This rendering will not be valid JSON since it has comments.
|
||||
*
|
||||
* @return the default render options
|
||||
*/
|
||||
public static ConfigRenderOptions defaults() {
|
||||
return new ConfigRenderOptions(true, true, true, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns concise render options (no whitespace or comments). For a
|
||||
* resolved {@link Config}, the concise rendering will be valid JSON.
|
||||
*
|
||||
* @return the concise render options
|
||||
*/
|
||||
public static ConfigRenderOptions concise() {
|
||||
return new ConfigRenderOptions(false, false, false, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns options with comments toggled. This controls human-written
|
||||
* comments but not the autogenerated "origin of this setting" comments,
|
||||
* which are controlled by {@link ConfigRenderOptions#setOriginComments}.
|
||||
*
|
||||
* @param value
|
||||
* true to include comments in the render
|
||||
* @return options with requested setting for comments
|
||||
*/
|
||||
public ConfigRenderOptions setComments(boolean value) {
|
||||
if (value == comments)
|
||||
return this;
|
||||
else
|
||||
return new ConfigRenderOptions(originComments, value, formatted, json);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the options enable comments. This method is mostly used
|
||||
* by the config lib internally, not by applications.
|
||||
*
|
||||
* @return true if comments should be rendered
|
||||
*/
|
||||
public boolean getComments() {
|
||||
return comments;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns options with origin comments toggled. If this is enabled, the
|
||||
* library generates comments for each setting based on the
|
||||
* {@link ConfigValue#origin} of that setting's value. For example these
|
||||
* comments might tell you which file a setting comes from.
|
||||
*
|
||||
* <p>
|
||||
* {@code setOriginComments()} controls only these autogenerated
|
||||
* "origin of this setting" comments, to toggle regular comments use
|
||||
* {@link ConfigRenderOptions#setComments}.
|
||||
*
|
||||
* @param value
|
||||
* true to include autogenerated setting-origin comments in the
|
||||
* render
|
||||
* @return options with origin comments toggled
|
||||
*/
|
||||
public ConfigRenderOptions setOriginComments(boolean value) {
|
||||
if (value == originComments)
|
||||
return this;
|
||||
else
|
||||
return new ConfigRenderOptions(value, comments, formatted, json);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the options enable automated origin comments. This method
|
||||
* is mostly used by the config lib internally, not by applications.
|
||||
*
|
||||
* @return true if origin comments should be rendered
|
||||
*/
|
||||
public boolean getOriginComments() {
|
||||
return originComments;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns options with formatting toggled. Formatting means indentation and
|
||||
* whitespace, enabling formatting makes things prettier but larger.
|
||||
*
|
||||
* @param value
|
||||
* true to enable formatting
|
||||
* @return options with requested setting for formatting
|
||||
*/
|
||||
public ConfigRenderOptions setFormatted(boolean value) {
|
||||
if (value == formatted)
|
||||
return this;
|
||||
else
|
||||
return new ConfigRenderOptions(originComments, comments, value, json);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the options enable formatting. This method is mostly used
|
||||
* by the config lib internally, not by applications.
|
||||
*
|
||||
* @return true if the options enable formatting
|
||||
*/
|
||||
public boolean getFormatted() {
|
||||
return formatted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns options with JSON toggled. JSON means that HOCON extensions
|
||||
* (omitting commas, quotes for example) won't be used. However, whether to
|
||||
* use comments is controlled by the separate {@link #setComments(boolean)}
|
||||
* and {@link #setOriginComments(boolean)} options. So if you enable
|
||||
* comments you will get invalid JSON despite setting this to true.
|
||||
*
|
||||
* @param value
|
||||
* true to include non-JSON extensions in the render
|
||||
* @return options with requested setting for JSON
|
||||
*/
|
||||
public ConfigRenderOptions setJson(boolean value) {
|
||||
if (value == json)
|
||||
return this;
|
||||
else
|
||||
return new ConfigRenderOptions(originComments, comments, formatted, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the options enable JSON. This method is mostly used by
|
||||
* the config lib internally, not by applications.
|
||||
*
|
||||
* @return true if only JSON should be rendered
|
||||
*/
|
||||
public boolean getJson() {
|
||||
return json;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder("ConfigRenderOptions(");
|
||||
if (originComments)
|
||||
sb.append("originComments,");
|
||||
if (comments)
|
||||
sb.append("comments,");
|
||||
if (formatted)
|
||||
sb.append("formatted,");
|
||||
if (json)
|
||||
sb.append("json,");
|
||||
if (sb.charAt(sb.length() - 1) == ',')
|
||||
sb.setLength(sb.length() - 1);
|
||||
sb.append(")");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
/**
|
||||
* A set of options related to resolving substitutions. Substitutions use the
|
||||
* <code>${foo.bar}</code> syntax and are documented in the <a
|
||||
* href="https://github.com/lightbend/config/blob/master/HOCON.md">HOCON</a>
|
||||
* spec.
|
||||
* <p>
|
||||
* Typically this class would be used with the method
|
||||
* {@link Config#resolve(ConfigResolveOptions)}.
|
||||
* <p>
|
||||
* This object is immutable, so the "setters" return a new object.
|
||||
* <p>
|
||||
* Here is an example of creating a custom {@code ConfigResolveOptions}:
|
||||
*
|
||||
* <pre>
|
||||
* ConfigResolveOptions options = ConfigResolveOptions.defaults()
|
||||
* .setUseSystemEnvironment(false)
|
||||
* </pre>
|
||||
* <p>
|
||||
* In addition to {@link ConfigResolveOptions#defaults}, there's a prebuilt
|
||||
* {@link ConfigResolveOptions#noSystem} which avoids looking at any system
|
||||
* environment variables or other external system information. (Right now,
|
||||
* environment variables are the only example.)
|
||||
*/
|
||||
public final class ConfigResolveOptions {
|
||||
private final boolean useSystemEnvironment;
|
||||
private final boolean allowUnresolved;
|
||||
private final ConfigResolver resolver;
|
||||
|
||||
private ConfigResolveOptions(boolean useSystemEnvironment, boolean allowUnresolved,
|
||||
ConfigResolver resolver) {
|
||||
this.useSystemEnvironment = useSystemEnvironment;
|
||||
this.allowUnresolved = allowUnresolved;
|
||||
this.resolver = resolver;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the default resolve options. By default the system environment
|
||||
* will be used and unresolved substitutions are not allowed.
|
||||
*
|
||||
* @return the default resolve options
|
||||
*/
|
||||
public static ConfigResolveOptions defaults() {
|
||||
return new ConfigResolveOptions(true, false, NULL_RESOLVER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns resolve options that disable any reference to "system" data
|
||||
* (currently, this means environment variables).
|
||||
*
|
||||
* @return the resolve options with env variables disabled
|
||||
*/
|
||||
public static ConfigResolveOptions noSystem() {
|
||||
return defaults().setUseSystemEnvironment(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns options with use of environment variables set to the given value.
|
||||
*
|
||||
* @param value
|
||||
* true to resolve substitutions falling back to environment
|
||||
* variables.
|
||||
* @return options with requested setting for use of environment variables
|
||||
*/
|
||||
public ConfigResolveOptions setUseSystemEnvironment(boolean value) {
|
||||
return new ConfigResolveOptions(value, allowUnresolved, resolver);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the options enable use of system environment variables.
|
||||
* This method is mostly used by the config lib internally, not by
|
||||
* applications.
|
||||
*
|
||||
* @return true if environment variables should be used
|
||||
*/
|
||||
public boolean getUseSystemEnvironment() {
|
||||
return useSystemEnvironment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns options with "allow unresolved" set to the given value. By
|
||||
* default, unresolved substitutions are an error. If unresolved
|
||||
* substitutions are allowed, then a future attempt to use the unresolved
|
||||
* value may fail, but {@link Config#resolve(ConfigResolveOptions)} itself
|
||||
* will not throw.
|
||||
*
|
||||
* @param value
|
||||
* true to silently ignore unresolved substitutions.
|
||||
* @return options with requested setting for whether to allow substitutions
|
||||
* @since 1.2.0
|
||||
*/
|
||||
public ConfigResolveOptions setAllowUnresolved(boolean value) {
|
||||
return new ConfigResolveOptions(useSystemEnvironment, value, resolver);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns options where the given resolver used as a fallback if a
|
||||
* reference cannot be otherwise resolved. This resolver will only be called
|
||||
* after resolution has failed to substitute with a value from within the
|
||||
* config itself and with any other resolvers that have been appended before
|
||||
* this one. Multiple resolvers can be added using,
|
||||
*
|
||||
* <pre>
|
||||
* ConfigResolveOptions options = ConfigResolveOptions.defaults()
|
||||
* .appendResolver(primary)
|
||||
* .appendResolver(secondary)
|
||||
* .appendResolver(tertiary);
|
||||
* </pre>
|
||||
*
|
||||
* With this config unresolved references will first be resolved with the
|
||||
* primary resolver, if that fails then the secondary, and finally if that
|
||||
* also fails the tertiary.
|
||||
*
|
||||
* If all fallbacks fail to return a substitution "allow unresolved"
|
||||
* determines whether resolution fails or continues.
|
||||
*`
|
||||
* @param value the resolver to fall back to
|
||||
* @return options that use the given resolver as a fallback
|
||||
* @since 1.3.2
|
||||
*/
|
||||
public ConfigResolveOptions appendResolver(ConfigResolver value) {
|
||||
if (value == null) {
|
||||
throw new ConfigException.BugOrBroken("null resolver passed to appendResolver");
|
||||
} else if (value == this.resolver) {
|
||||
return this;
|
||||
} else {
|
||||
return new ConfigResolveOptions(useSystemEnvironment, allowUnresolved,
|
||||
this.resolver.withFallback(value));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the resolver to use as a fallback if a substitution cannot be
|
||||
* otherwise resolved. Never returns null. This method is mostly used by the
|
||||
* config lib internally, not by applications.
|
||||
*
|
||||
* @return the non-null fallback resolver
|
||||
* @since 1.3.2
|
||||
*/
|
||||
public ConfigResolver getResolver() {
|
||||
return this.resolver;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the options allow unresolved substitutions. This method
|
||||
* is mostly used by the config lib internally, not by applications.
|
||||
*
|
||||
* @return true if unresolved substitutions are allowed
|
||||
* @since 1.2.0
|
||||
*/
|
||||
public boolean getAllowUnresolved() {
|
||||
return allowUnresolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* Singleton resolver that never resolves paths.
|
||||
*/
|
||||
private static final ConfigResolver NULL_RESOLVER = new ConfigResolver() {
|
||||
|
||||
@Override
|
||||
public ConfigValue lookup(String path) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigResolver withFallback(ConfigResolver fallback) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
/**
|
||||
* Implement this interface and provide an instance to
|
||||
* {@link ConfigResolveOptions#appendResolver ConfigResolveOptions.appendResolver()}
|
||||
* to provide custom behavior when unresolved substitutions are encountered
|
||||
* during resolution.
|
||||
* @since 1.3.2
|
||||
*/
|
||||
public interface ConfigResolver {
|
||||
|
||||
/**
|
||||
* Returns the value to substitute for the given unresolved path. To get the
|
||||
* components of the path use {@link ConfigUtil#splitPath(String)}. If a
|
||||
* non-null value is returned that value will be substituted, otherwise
|
||||
* resolution will continue to consider the substitution as still
|
||||
* unresolved.
|
||||
*
|
||||
* @param path the unresolved path
|
||||
* @return the value to use as a substitution or null
|
||||
*/
|
||||
public ConfigValue lookup(String path);
|
||||
|
||||
/**
|
||||
* Returns a new resolver that falls back to the given resolver if this
|
||||
* one doesn't provide a substitution itself.
|
||||
*
|
||||
* It's important to handle the case where you already have the fallback
|
||||
* with a "return this", i.e. this method should not create a new object if
|
||||
* the fallback is the same one you already have. The same fallback may be
|
||||
* added repeatedly.
|
||||
*
|
||||
* @param fallback the previous includer for chaining
|
||||
* @return a new resolver
|
||||
*/
|
||||
public ConfigResolver withFallback(ConfigResolver fallback);
|
||||
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
/**
|
||||
* The syntax of a character stream (<a href="http://json.org">JSON</a>, <a
|
||||
* href="https://github.com/lightbend/config/blob/master/HOCON.md">HOCON</a>
|
||||
* aka ".conf", or <a href=
|
||||
* "http://download.oracle.com/javase/7/docs/api/java/util/Properties.html#load%28java.io.Reader%29"
|
||||
* >Java properties</a>).
|
||||
*
|
||||
*/
|
||||
public enum ConfigSyntax {
|
||||
/**
|
||||
* Pedantically strict <a href="http://json.org">JSON</a> format; no
|
||||
* comments, no unexpected commas, no duplicate keys in the same object.
|
||||
* Associated with the <code>.json</code> file extension and
|
||||
* <code>application/json</code> Content-Type.
|
||||
*/
|
||||
JSON,
|
||||
/**
|
||||
* The JSON-superset <a
|
||||
* href="https://github.com/lightbend/config/blob/master/HOCON.md"
|
||||
* >HOCON</a> format. Associated with the <code>.conf</code> file extension
|
||||
* and <code>application/hocon</code> Content-Type.
|
||||
*/
|
||||
CONF,
|
||||
/**
|
||||
* Standard <a href=
|
||||
* "http://download.oracle.com/javase/7/docs/api/java/util/Properties.html#load%28java.io.Reader%29"
|
||||
* >Java properties</a> format. Associated with the <code>.properties</code>
|
||||
* file extension and <code>text/x-java-properties</code> Content-Type.
|
||||
*/
|
||||
PROPERTIES;
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.impl.ConfigImplUtil;
|
||||
|
||||
/**
|
||||
* Contains static utility methods.
|
||||
*
|
||||
*/
|
||||
public final class ConfigUtil {
|
||||
private ConfigUtil() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Quotes and escapes a string, as in the JSON specification.
|
||||
*
|
||||
* @param s
|
||||
* a string
|
||||
* @return the string quoted and escaped
|
||||
*/
|
||||
public static String quoteString(String s) {
|
||||
return ConfigImplUtil.renderJsonString(s);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a list of keys to a path expression, by quoting the path
|
||||
* elements as needed and then joining them separated by a period. A path
|
||||
* expression is usable with a {@link Config}, while individual path
|
||||
* elements are usable with a {@link ConfigObject}.
|
||||
* <p>
|
||||
* See the overview documentation for {@link Config} for more detail on path
|
||||
* expressions vs. keys.
|
||||
*
|
||||
* @param elements
|
||||
* the keys in the path
|
||||
* @return a path expression
|
||||
* @throws ConfigException
|
||||
* if there are no elements
|
||||
*/
|
||||
public static String joinPath(String... elements) {
|
||||
return ConfigImplUtil.joinPath(elements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a list of strings to a path expression, by quoting the path
|
||||
* elements as needed and then joining them separated by a period. A path
|
||||
* expression is usable with a {@link Config}, while individual path
|
||||
* elements are usable with a {@link ConfigObject}.
|
||||
* <p>
|
||||
* See the overview documentation for {@link Config} for more detail on path
|
||||
* expressions vs. keys.
|
||||
*
|
||||
* @param elements
|
||||
* the keys in the path
|
||||
* @return a path expression
|
||||
* @throws ConfigException
|
||||
* if the list is empty
|
||||
*/
|
||||
public static String joinPath(List<String> elements) {
|
||||
return ConfigImplUtil.joinPath(elements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a path expression into a list of keys, by splitting on period
|
||||
* and unquoting the individual path elements. A path expression is usable
|
||||
* with a {@link Config}, while individual path elements are usable with a
|
||||
* {@link ConfigObject}.
|
||||
* <p>
|
||||
* See the overview documentation for {@link Config} for more detail on path
|
||||
* expressions vs. keys.
|
||||
*
|
||||
* @param path
|
||||
* a path expression
|
||||
* @return the individual keys in the path
|
||||
* @throws ConfigException
|
||||
* if the path expression is invalid
|
||||
*/
|
||||
public static List<String> splitPath(String path) {
|
||||
return ConfigImplUtil.splitPath(path);
|
||||
}
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
/**
|
||||
* An immutable value, following the <a href="http://json.org">JSON</a> type
|
||||
* schema.
|
||||
*
|
||||
* <p>
|
||||
* Because this object is immutable, it is safe to use from multiple threads and
|
||||
* there's no need for "defensive copies."
|
||||
*
|
||||
* <p>
|
||||
* <em>Do not implement interface {@code ConfigValue}</em>; it should only be
|
||||
* implemented by the config library. Arbitrary implementations will not work
|
||||
* because the library internals assume a specific concrete implementation.
|
||||
* Also, this interface is likely to grow new methods over time, so third-party
|
||||
* implementations will break.
|
||||
*/
|
||||
public interface ConfigValue extends ConfigMergeable {
|
||||
/**
|
||||
* The origin of the value (file, line number, etc.), for debugging and
|
||||
* error messages.
|
||||
*
|
||||
* @return where the value came from
|
||||
*/
|
||||
ConfigOrigin origin();
|
||||
|
||||
/**
|
||||
* The {@link ConfigValueType} of the value; matches the JSON type schema.
|
||||
*
|
||||
* @return value's type
|
||||
*/
|
||||
ConfigValueType valueType();
|
||||
|
||||
/**
|
||||
* Returns the value as a plain Java boxed value, that is, a {@code String},
|
||||
* {@code Number}, {@code Boolean}, {@code Map<String,Object>},
|
||||
* {@code List<Object>}, or {@code null}, matching the {@link #valueType()}
|
||||
* of this {@code ConfigValue}. If the value is a {@link ConfigObject} or
|
||||
* {@link ConfigList}, it is recursively unwrapped.
|
||||
* @return a plain Java value corresponding to this ConfigValue
|
||||
*/
|
||||
Object unwrapped();
|
||||
|
||||
/**
|
||||
* Renders the config value as a HOCON string. This method is primarily
|
||||
* intended for debugging, so it tries to add helpful comments and
|
||||
* whitespace.
|
||||
*
|
||||
* <p>
|
||||
* If the config value has not been resolved (see {@link Config#resolve}),
|
||||
* it's possible that it can't be rendered as valid HOCON. In that case the
|
||||
* rendering should still be useful for debugging but you might not be able
|
||||
* to parse it. If the value has been resolved, it will always be parseable.
|
||||
*
|
||||
* <p>
|
||||
* This method is equivalent to
|
||||
* {@code render(ConfigRenderOptions.defaults())}.
|
||||
*
|
||||
* @return the rendered value
|
||||
*/
|
||||
String render();
|
||||
|
||||
/**
|
||||
* Renders the config value to a string, using the provided options.
|
||||
*
|
||||
* <p>
|
||||
* If the config value has not been resolved (see {@link Config#resolve}),
|
||||
* it's possible that it can't be rendered as valid HOCON. In that case the
|
||||
* rendering should still be useful for debugging but you might not be able
|
||||
* to parse it. If the value has been resolved, it will always be parseable.
|
||||
*
|
||||
* <p>
|
||||
* If the config value has been resolved and the options disable all
|
||||
* HOCON-specific features (such as comments), the rendering will be valid
|
||||
* JSON. If you enable HOCON-only features such as comments, the rendering
|
||||
* will not be valid JSON.
|
||||
*
|
||||
* @param options
|
||||
* the rendering options
|
||||
* @return the rendered value
|
||||
*/
|
||||
String render(ConfigRenderOptions options);
|
||||
|
||||
@Override
|
||||
ConfigValue withFallback(ConfigMergeable other);
|
||||
|
||||
/**
|
||||
* Places the value inside a {@link Config} at the given path. See also
|
||||
* {@link ConfigValue#atKey(String)}.
|
||||
*
|
||||
* @param path
|
||||
* path to store this value at.
|
||||
* @return a {@code Config} instance containing this value at the given
|
||||
* path.
|
||||
*/
|
||||
Config atPath(String path);
|
||||
|
||||
/**
|
||||
* Places the value inside a {@link Config} at the given key. See also
|
||||
* {@link ConfigValue#atPath(String)}.
|
||||
*
|
||||
* @param key
|
||||
* key to store this value at.
|
||||
* @return a {@code Config} instance containing this value at the given key.
|
||||
*/
|
||||
Config atKey(String key);
|
||||
|
||||
/**
|
||||
* Returns a {@code ConfigValue} based on this one, but with the given
|
||||
* origin. This is useful when you are parsing a new format of file or setting
|
||||
* comments for a single ConfigValue.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @param origin the origin set on the returned value
|
||||
* @return the new ConfigValue with the given origin
|
||||
*/
|
||||
ConfigValue withOrigin(ConfigOrigin origin);
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.impl.ConfigImpl;
|
||||
|
||||
/**
|
||||
* This class holds some static factory methods for building {@link ConfigValue}
|
||||
* instances. See also {@link ConfigFactory} which has methods for parsing files
|
||||
* and certain in-memory data structures.
|
||||
*/
|
||||
public final class ConfigValueFactory {
|
||||
private ConfigValueFactory() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a {@link ConfigValue} from a plain Java boxed value, which may be
|
||||
* a <code>Boolean</code>, <code>Number</code>, <code>String</code>,
|
||||
* <code>Map</code>, <code>Iterable</code>, or <code>null</code>. A
|
||||
* <code>Map</code> must be a <code>Map</code> from String to more values
|
||||
* that can be supplied to <code>fromAnyRef()</code>. An
|
||||
* <code>Iterable</code> must iterate over more values that can be supplied
|
||||
* to <code>fromAnyRef()</code>. A <code>Map</code> will become a
|
||||
* {@link ConfigObject} and an <code>Iterable</code> will become a
|
||||
* {@link ConfigList}. If the <code>Iterable</code> is not an ordered
|
||||
* collection, results could be strange, since <code>ConfigList</code> is
|
||||
* ordered.
|
||||
*
|
||||
* <p>
|
||||
* In a <code>Map</code> passed to <code>fromAnyRef()</code>, the map's keys
|
||||
* are plain keys, not path expressions. So if your <code>Map</code> has a
|
||||
* key "foo.bar" then you will get one object with a key called "foo.bar",
|
||||
* rather than an object with a key "foo" containing another object with a
|
||||
* key "bar".
|
||||
*
|
||||
* <p>
|
||||
* The originDescription will be used to set the origin() field on the
|
||||
* ConfigValue. It should normally be the name of the file the values came
|
||||
* from, or something short describing the value such as "default settings".
|
||||
* The originDescription is prefixed to error messages so users can tell
|
||||
* where problematic values are coming from.
|
||||
*
|
||||
* <p>
|
||||
* Supplying the result of ConfigValue.unwrapped() to this function is
|
||||
* guaranteed to work and should give you back a ConfigValue that matches
|
||||
* the one you unwrapped. The re-wrapped ConfigValue will lose some
|
||||
* information that was present in the original such as its origin, but it
|
||||
* will have matching values.
|
||||
*
|
||||
* <p>
|
||||
* If you pass in a <code>ConfigValue</code> to this
|
||||
* function, it will be returned unmodified. (The
|
||||
* <code>originDescription</code> will be ignored in this
|
||||
* case.)
|
||||
*
|
||||
* <p>
|
||||
* This function throws if you supply a value that cannot be converted to a
|
||||
* ConfigValue, but supplying such a value is a bug in your program, so you
|
||||
* should never handle the exception. Just fix your program (or report a bug
|
||||
* against this library).
|
||||
*
|
||||
* @param object
|
||||
* object to convert to ConfigValue
|
||||
* @param originDescription
|
||||
* name of origin file or brief description of what the value is
|
||||
* @return a new value
|
||||
*/
|
||||
public static ConfigValue fromAnyRef(Object object, String originDescription) {
|
||||
return ConfigImpl.fromAnyRef(object, originDescription);
|
||||
}
|
||||
|
||||
/**
|
||||
* See the {@link #fromAnyRef(Object,String)} documentation for details.
|
||||
* This is a typesafe wrapper that only works on {@link java.util.Map} and
|
||||
* returns {@link ConfigObject} rather than {@link ConfigValue}.
|
||||
*
|
||||
* <p>
|
||||
* If your <code>Map</code> has a key "foo.bar" then you will get one object
|
||||
* with a key called "foo.bar", rather than an object with a key "foo"
|
||||
* containing another object with a key "bar". The keys in the map are keys;
|
||||
* not path expressions. That is, the <code>Map</code> corresponds exactly
|
||||
* to a single {@code ConfigObject}. The keys will not be parsed or
|
||||
* modified, and the values are wrapped in ConfigValue. To get nested
|
||||
* {@code ConfigObject}, some of the values in the map would have to be more
|
||||
* maps.
|
||||
*
|
||||
* <p>
|
||||
* See also {@link ConfigFactory#parseMap(Map,String)} which interprets the
|
||||
* keys in the map as path expressions.
|
||||
*
|
||||
* @param values map from keys to plain Java values
|
||||
* @param originDescription description to use in {@link ConfigOrigin} of created values
|
||||
* @return a new {@link ConfigObject} value
|
||||
*/
|
||||
public static ConfigObject fromMap(Map<String, ? extends Object> values,
|
||||
String originDescription) {
|
||||
return (ConfigObject) fromAnyRef(values, originDescription);
|
||||
}
|
||||
|
||||
/**
|
||||
* See the {@link #fromAnyRef(Object,String)} documentation for details.
|
||||
* This is a typesafe wrapper that only works on {@link java.lang.Iterable}
|
||||
* and returns {@link ConfigList} rather than {@link ConfigValue}.
|
||||
*
|
||||
* @param values list of plain Java values
|
||||
* @param originDescription description to use in {@link ConfigOrigin} of created values
|
||||
* @return a new {@link ConfigList} value
|
||||
*/
|
||||
public static ConfigList fromIterable(Iterable<? extends Object> values,
|
||||
String originDescription) {
|
||||
return (ConfigList) fromAnyRef(values, originDescription);
|
||||
}
|
||||
|
||||
/**
|
||||
* See the other overload {@link #fromAnyRef(Object,String)} for details,
|
||||
* this one just uses a default origin description.
|
||||
*
|
||||
* @param object a plain Java value
|
||||
* @return a new {@link ConfigValue}
|
||||
*/
|
||||
public static ConfigValue fromAnyRef(Object object) {
|
||||
return fromAnyRef(object, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* See the other overload {@link #fromMap(Map,String)} for details, this one
|
||||
* just uses a default origin description.
|
||||
*
|
||||
* <p>
|
||||
* See also {@link ConfigFactory#parseMap(Map)} which interprets the keys in
|
||||
* the map as path expressions.
|
||||
*
|
||||
* @param values map from keys to plain Java values
|
||||
* @return a new {@link ConfigObject}
|
||||
*/
|
||||
public static ConfigObject fromMap(Map<String, ? extends Object> values) {
|
||||
return fromMap(values, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* See the other overload of {@link #fromIterable(Iterable, String)} for
|
||||
* details, this one just uses a default origin description.
|
||||
*
|
||||
* @param values list of plain Java values
|
||||
* @return a new {@link ConfigList}
|
||||
*/
|
||||
public static ConfigList fromIterable(Iterable<? extends Object> values) {
|
||||
return fromIterable(values, null);
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
/**
|
||||
* The type of a configuration value (following the <a
|
||||
* href="http://json.org">JSON</a> type schema).
|
||||
*/
|
||||
public enum ConfigValueType {
|
||||
OBJECT, LIST, NUMBER, BOOLEAN, NULL, STRING
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
import java.io.File;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
|
||||
/**
|
||||
* Default config loading strategy. Able to load resource, file or URL.
|
||||
* Behavior may be altered by defining one of VM properties
|
||||
* {@code config.resource}, {@code config.file} or {@code config.url}
|
||||
*/
|
||||
public class DefaultConfigLoadingStrategy implements ConfigLoadingStrategy {
|
||||
@Override
|
||||
public Config parseApplicationConfig(ConfigParseOptions parseOptions) {
|
||||
ClassLoader loader = parseOptions.getClassLoader();
|
||||
if (loader == null)
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"ClassLoader should have been set here; bug in ConfigFactory. "
|
||||
+ "(You can probably work around this bug by passing in a class loader or calling currentThread().setContextClassLoader() though.)");
|
||||
|
||||
int specified = 0;
|
||||
|
||||
// override application.conf with config.file, config.resource,
|
||||
// config.url if requested.
|
||||
String resource = System.getProperty("config.resource");
|
||||
if (resource != null)
|
||||
specified += 1;
|
||||
String file = System.getProperty("config.file");
|
||||
if (file != null)
|
||||
specified += 1;
|
||||
String url = System.getProperty("config.url");
|
||||
if (url != null)
|
||||
specified += 1;
|
||||
|
||||
if (specified == 0) {
|
||||
return ConfigFactory.parseResourcesAnySyntax("application", parseOptions);
|
||||
} else if (specified > 1) {
|
||||
throw new ConfigException.Generic("You set more than one of config.file='" + file
|
||||
+ "', config.url='" + url + "', config.resource='" + resource
|
||||
+ "'; don't know which one to use!");
|
||||
} else {
|
||||
// the override file/url/resource MUST be present or it's an error
|
||||
ConfigParseOptions overrideOptions = parseOptions.setAllowMissing(false);
|
||||
if (resource != null) {
|
||||
if (resource.startsWith("/"))
|
||||
resource = resource.substring(1);
|
||||
// this deliberately does not parseResourcesAnySyntax; if
|
||||
// people want that they can use an include statement.
|
||||
return ConfigFactory.parseResources(loader, resource, overrideOptions);
|
||||
} else if (file != null) {
|
||||
return ConfigFactory.parseFile(new File(file), overrideOptions);
|
||||
} else {
|
||||
try {
|
||||
return ConfigFactory.parseURL(new URL(url), overrideOptions);
|
||||
} catch (MalformedURLException e) {
|
||||
throw new ConfigException.Generic("Bad URL in config.url system property: '"
|
||||
+ url + "': " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
|
||||
/**
|
||||
* Allows an config property to be {@code null}.
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface Optional {
|
||||
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Copyright (C) 2015 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.parser.ConfigNode;
|
||||
import java.util.Collection;
|
||||
|
||||
abstract class AbstractConfigNode implements ConfigNode {
|
||||
abstract Collection<Token> tokens();
|
||||
final public String render() {
|
||||
StringBuilder origText = new StringBuilder();
|
||||
Iterable<Token> tokens = tokens();
|
||||
for (Token t : tokens) {
|
||||
origText.append(t.tokenText());
|
||||
}
|
||||
return origText.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
final public boolean equals(Object other) {
|
||||
return other instanceof AbstractConfigNode && render().equals(((AbstractConfigNode)other).render());
|
||||
}
|
||||
|
||||
@Override
|
||||
final public int hashCode() {
|
||||
return render().hashCode();
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Copyright (C) 2015 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
// This is required if we want
|
||||
// to be referencing the AbstractConfigNode class in implementation rather than the
|
||||
// ConfigNode interface, as we can't cast an AbstractConfigNode to an interface
|
||||
abstract class AbstractConfigNodeValue extends AbstractConfigNode {
|
||||
|
||||
}
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigMergeable;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigObject;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigRenderOptions;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType;
|
||||
|
||||
abstract class AbstractConfigObject extends AbstractConfigValue implements ConfigObject, Container {
|
||||
final private SimpleConfig config;
|
||||
|
||||
protected AbstractConfigObject(ConfigOrigin origin) {
|
||||
super(origin);
|
||||
this.config = new SimpleConfig(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SimpleConfig toConfig() {
|
||||
return config;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractConfigObject toFallbackValue() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
abstract public AbstractConfigObject withOnlyKey(String key);
|
||||
|
||||
@Override
|
||||
abstract public AbstractConfigObject withoutKey(String key);
|
||||
|
||||
@Override
|
||||
abstract public AbstractConfigObject withValue(String key, ConfigValue value);
|
||||
|
||||
abstract protected AbstractConfigObject withOnlyPathOrNull(Path path);
|
||||
|
||||
abstract AbstractConfigObject withOnlyPath(Path path);
|
||||
|
||||
abstract AbstractConfigObject withoutPath(Path path);
|
||||
|
||||
abstract AbstractConfigObject withValue(Path path, ConfigValue value);
|
||||
|
||||
/**
|
||||
* This looks up the key with no transformation or type conversion of any
|
||||
* kind, and returns null if the key is not present. The object must be
|
||||
* resolved along the nodes needed to get the key or
|
||||
* ConfigException.NotResolved will be thrown.
|
||||
*
|
||||
* @param key
|
||||
* @return the unmodified raw value or null
|
||||
*/
|
||||
protected final AbstractConfigValue peekAssumingResolved(String key, Path originalPath) {
|
||||
try {
|
||||
return attemptPeekWithPartialResolve(key);
|
||||
} catch (ConfigException.NotResolved e) {
|
||||
throw ConfigImpl.improveNotResolved(originalPath, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up the key on an only-partially-resolved object, with no
|
||||
* transformation or type conversion of any kind; if 'this' is not resolved
|
||||
* then try to look up the key anyway if possible.
|
||||
*
|
||||
* @param key
|
||||
* key to look up
|
||||
* @return the value of the key, or null if known not to exist
|
||||
* @throws ConfigException.NotResolved
|
||||
* if can't figure out key's value (or existence) without more
|
||||
* resolving
|
||||
*/
|
||||
abstract AbstractConfigValue attemptPeekWithPartialResolve(String key);
|
||||
|
||||
/**
|
||||
* Looks up the path with no transformation or type conversion. Returns null
|
||||
* if the path is not found; throws ConfigException.NotResolved if we need
|
||||
* to go through an unresolved node to look up the path.
|
||||
*/
|
||||
protected AbstractConfigValue peekPath(Path path) {
|
||||
return peekPath(this, path);
|
||||
}
|
||||
|
||||
private static AbstractConfigValue peekPath(AbstractConfigObject self, Path path) {
|
||||
try {
|
||||
// we'll fail if anything along the path can't
|
||||
// be looked at without resolving.
|
||||
Path next = path.remainder();
|
||||
AbstractConfigValue v = self.attemptPeekWithPartialResolve(path.first());
|
||||
|
||||
if (next == null) {
|
||||
return v;
|
||||
} else {
|
||||
if (v instanceof AbstractConfigObject) {
|
||||
return peekPath((AbstractConfigObject) v, next);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
} catch (ConfigException.NotResolved e) {
|
||||
throw ConfigImpl.improveNotResolved(path, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigValueType valueType() {
|
||||
return ConfigValueType.OBJECT;
|
||||
}
|
||||
|
||||
protected abstract AbstractConfigObject newCopy(ResolveStatus status, ConfigOrigin origin);
|
||||
|
||||
@Override
|
||||
protected AbstractConfigObject newCopy(ConfigOrigin origin) {
|
||||
return newCopy(resolveStatus(), origin);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected AbstractConfigObject constructDelayedMerge(ConfigOrigin origin,
|
||||
List<AbstractConfigValue> stack) {
|
||||
return new ConfigDelayedMergeObject(origin, stack);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected abstract AbstractConfigObject mergedWithObject(AbstractConfigObject fallback);
|
||||
|
||||
@Override
|
||||
public AbstractConfigObject withFallback(ConfigMergeable mergeable) {
|
||||
return (AbstractConfigObject) super.withFallback(mergeable);
|
||||
}
|
||||
|
||||
static ConfigOrigin mergeOrigins(
|
||||
Collection<? extends AbstractConfigValue> stack) {
|
||||
if (stack.isEmpty())
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"can't merge origins on empty list");
|
||||
List<ConfigOrigin> origins = new ArrayList<ConfigOrigin>();
|
||||
ConfigOrigin firstOrigin = null;
|
||||
int numMerged = 0;
|
||||
for (AbstractConfigValue v : stack) {
|
||||
if (firstOrigin == null)
|
||||
firstOrigin = v.origin();
|
||||
|
||||
if (v instanceof AbstractConfigObject
|
||||
&& ((AbstractConfigObject) v).resolveStatus() == ResolveStatus.RESOLVED
|
||||
&& ((ConfigObject) v).isEmpty()) {
|
||||
// don't include empty files or the .empty()
|
||||
// config in the description, since they are
|
||||
// likely to be "implementation details"
|
||||
} else {
|
||||
origins.add(v.origin());
|
||||
numMerged += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (numMerged == 0) {
|
||||
// the configs were all empty, so just use the first one
|
||||
origins.add(firstOrigin);
|
||||
}
|
||||
|
||||
return SimpleConfigOrigin.mergeOrigins(origins);
|
||||
}
|
||||
|
||||
static ConfigOrigin mergeOrigins(AbstractConfigObject... stack) {
|
||||
return mergeOrigins(Arrays.asList(stack));
|
||||
}
|
||||
|
||||
@Override
|
||||
abstract ResolveResult<? extends AbstractConfigObject> resolveSubstitutions(ResolveContext context,
|
||||
ResolveSource source)
|
||||
throws NotPossibleToResolve;
|
||||
|
||||
@Override
|
||||
abstract AbstractConfigObject relativized(final Path prefix);
|
||||
|
||||
@Override
|
||||
public abstract AbstractConfigValue get(Object key);
|
||||
|
||||
@Override
|
||||
protected abstract void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options);
|
||||
|
||||
private static UnsupportedOperationException weAreImmutable(String method) {
|
||||
return new UnsupportedOperationException("ConfigObject is immutable, you can't call Map."
|
||||
+ method);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
throw weAreImmutable("clear");
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigValue put(String arg0, ConfigValue arg1) {
|
||||
throw weAreImmutable("put");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void putAll(Map<? extends String, ? extends ConfigValue> arg0) {
|
||||
throw weAreImmutable("putAll");
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigValue remove(Object arg0) {
|
||||
throw weAreImmutable("remove");
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractConfigObject withOrigin(ConfigOrigin origin) {
|
||||
return (AbstractConfigObject) super.withOrigin(origin);
|
||||
}
|
||||
}
|
||||
+411
@@ -0,0 +1,411 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigMergeable;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigObject;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigRenderOptions;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue;
|
||||
|
||||
/**
|
||||
*
|
||||
* Trying very hard to avoid a parent reference in config values; when you have
|
||||
* a tree like this, the availability of parent() tends to result in a lot of
|
||||
* improperly-factored and non-modular code. Please don't add parent().
|
||||
*
|
||||
*/
|
||||
abstract class AbstractConfigValue implements ConfigValue, MergeableValue {
|
||||
|
||||
final private SimpleConfigOrigin origin;
|
||||
|
||||
AbstractConfigValue(ConfigOrigin origin) {
|
||||
this.origin = (SimpleConfigOrigin) origin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SimpleConfigOrigin origin() {
|
||||
return this.origin;
|
||||
}
|
||||
|
||||
/**
|
||||
* This exception means that a value is inherently not resolveable, at the
|
||||
* moment the only known cause is a cycle of substitutions. This is a
|
||||
* checked exception since it's internal to the library and we want to be
|
||||
* sure we handle it before passing it out to public API. This is only
|
||||
* supposed to be thrown by the target of a cyclic reference and it's
|
||||
* supposed to be caught by the ConfigReference looking up that reference,
|
||||
* so it should be impossible for an outermost resolve() to throw this.
|
||||
*
|
||||
* Contrast with ConfigException.NotResolved which just means nobody called
|
||||
* resolve().
|
||||
*/
|
||||
static class NotPossibleToResolve extends Exception {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
final private String traceString;
|
||||
|
||||
NotPossibleToResolve(ResolveContext context) {
|
||||
super("was not possible to resolve");
|
||||
this.traceString = context.traceString();
|
||||
}
|
||||
|
||||
String traceString() {
|
||||
return traceString;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called only by ResolveContext.resolve().
|
||||
*
|
||||
* @param context
|
||||
* state of the current resolve
|
||||
* @param source
|
||||
* where to look up values
|
||||
* @return a new value if there were changes, or this if no changes
|
||||
*/
|
||||
ResolveResult<? extends AbstractConfigValue> resolveSubstitutions(ResolveContext context, ResolveSource source)
|
||||
throws NotPossibleToResolve {
|
||||
return ResolveResult.make(context, this);
|
||||
}
|
||||
|
||||
ResolveStatus resolveStatus() {
|
||||
return ResolveStatus.RESOLVED;
|
||||
}
|
||||
|
||||
protected static List<AbstractConfigValue> replaceChildInList(List<AbstractConfigValue> list,
|
||||
AbstractConfigValue child, AbstractConfigValue replacement) {
|
||||
int i = 0;
|
||||
while (i < list.size() && list.get(i) != child)
|
||||
++i;
|
||||
if (i == list.size())
|
||||
throw new ConfigException.BugOrBroken("tried to replace " + child + " which is not in " + list);
|
||||
List<AbstractConfigValue> newStack = new ArrayList<AbstractConfigValue>(list);
|
||||
if (replacement != null)
|
||||
newStack.set(i, replacement);
|
||||
else
|
||||
newStack.remove(i);
|
||||
|
||||
if (newStack.isEmpty())
|
||||
return null;
|
||||
else
|
||||
return newStack;
|
||||
}
|
||||
|
||||
protected static boolean hasDescendantInList(List<AbstractConfigValue> list, AbstractConfigValue descendant) {
|
||||
for (AbstractConfigValue v : list) {
|
||||
if (v == descendant)
|
||||
return true;
|
||||
}
|
||||
// now the expensive traversal
|
||||
for (AbstractConfigValue v : list) {
|
||||
if (v instanceof Container && ((Container) v).hasDescendant(descendant))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* This is used when including one file in another; the included file is
|
||||
* relativized to the path it's included into in the parent file. The point
|
||||
* is that if you include a file at foo.bar in the parent, and the included
|
||||
* file as a substitution ${a.b.c}, the included substitution now needs to
|
||||
* be ${foo.bar.a.b.c} because we resolve substitutions globally only after
|
||||
* parsing everything.
|
||||
*
|
||||
* @param prefix
|
||||
* @return value relativized to the given path or the same value if nothing
|
||||
* to do
|
||||
*/
|
||||
AbstractConfigValue relativized(Path prefix) {
|
||||
return this;
|
||||
}
|
||||
|
||||
protected interface Modifier {
|
||||
// keyOrNull is null for non-objects
|
||||
AbstractConfigValue modifyChildMayThrow(String keyOrNull, AbstractConfigValue v)
|
||||
throws Exception;
|
||||
}
|
||||
|
||||
protected abstract class NoExceptionsModifier implements Modifier {
|
||||
@Override
|
||||
public final AbstractConfigValue modifyChildMayThrow(String keyOrNull, AbstractConfigValue v)
|
||||
throws Exception {
|
||||
try {
|
||||
return modifyChild(keyOrNull, v);
|
||||
} catch (RuntimeException e) {
|
||||
throw e;
|
||||
} catch(Exception e) {
|
||||
throw new ConfigException.BugOrBroken("Unexpected exception", e);
|
||||
}
|
||||
}
|
||||
|
||||
abstract AbstractConfigValue modifyChild(String keyOrNull, AbstractConfigValue v);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractConfigValue toFallbackValue() {
|
||||
return this;
|
||||
}
|
||||
|
||||
protected abstract AbstractConfigValue newCopy(ConfigOrigin origin);
|
||||
|
||||
// this is virtualized rather than a field because only some subclasses
|
||||
// really need to store the boolean, and they may be able to pack it
|
||||
// with another boolean to save space.
|
||||
protected boolean ignoresFallbacks() {
|
||||
// if we are not resolved, then somewhere in this value there's
|
||||
// a substitution that may need to look at the fallbacks.
|
||||
return resolveStatus() == ResolveStatus.RESOLVED;
|
||||
}
|
||||
|
||||
protected AbstractConfigValue withFallbacksIgnored() {
|
||||
if (ignoresFallbacks())
|
||||
return this;
|
||||
else
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"value class doesn't implement forced fallback-ignoring " + this);
|
||||
}
|
||||
|
||||
// the withFallback() implementation is supposed to avoid calling
|
||||
// mergedWith* if we're ignoring fallbacks.
|
||||
protected final void requireNotIgnoringFallbacks() {
|
||||
if (ignoresFallbacks())
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"method should not have been called with ignoresFallbacks=true "
|
||||
+ getClass().getSimpleName());
|
||||
}
|
||||
|
||||
protected AbstractConfigValue constructDelayedMerge(ConfigOrigin origin,
|
||||
List<AbstractConfigValue> stack) {
|
||||
return new ConfigDelayedMerge(origin, stack);
|
||||
}
|
||||
|
||||
protected final AbstractConfigValue mergedWithTheUnmergeable(
|
||||
Collection<AbstractConfigValue> stack, Unmergeable fallback) {
|
||||
requireNotIgnoringFallbacks();
|
||||
|
||||
// if we turn out to be an object, and the fallback also does,
|
||||
// then a merge may be required; delay until we resolve.
|
||||
List<AbstractConfigValue> newStack = new ArrayList<AbstractConfigValue>();
|
||||
newStack.addAll(stack);
|
||||
newStack.addAll(fallback.unmergedValues());
|
||||
return constructDelayedMerge(AbstractConfigObject.mergeOrigins(newStack), newStack);
|
||||
}
|
||||
|
||||
private final AbstractConfigValue delayMerge(Collection<AbstractConfigValue> stack,
|
||||
AbstractConfigValue fallback) {
|
||||
// if we turn out to be an object, and the fallback also does,
|
||||
// then a merge may be required.
|
||||
// if we contain a substitution, resolving it may need to look
|
||||
// back to the fallback.
|
||||
List<AbstractConfigValue> newStack = new ArrayList<AbstractConfigValue>();
|
||||
newStack.addAll(stack);
|
||||
newStack.add(fallback);
|
||||
return constructDelayedMerge(AbstractConfigObject.mergeOrigins(newStack), newStack);
|
||||
}
|
||||
|
||||
protected final AbstractConfigValue mergedWithObject(Collection<AbstractConfigValue> stack,
|
||||
AbstractConfigObject fallback) {
|
||||
requireNotIgnoringFallbacks();
|
||||
|
||||
if (this instanceof AbstractConfigObject)
|
||||
throw new ConfigException.BugOrBroken("Objects must reimplement mergedWithObject");
|
||||
|
||||
return mergedWithNonObject(stack, fallback);
|
||||
}
|
||||
|
||||
protected final AbstractConfigValue mergedWithNonObject(Collection<AbstractConfigValue> stack,
|
||||
AbstractConfigValue fallback) {
|
||||
requireNotIgnoringFallbacks();
|
||||
|
||||
if (resolveStatus() == ResolveStatus.RESOLVED) {
|
||||
// falling back to a non-object doesn't merge anything, and also
|
||||
// prohibits merging any objects that we fall back to later.
|
||||
// so we have to switch to ignoresFallbacks mode.
|
||||
return withFallbacksIgnored();
|
||||
} else {
|
||||
// if unresolved, we may have to look back to fallbacks as part of
|
||||
// the resolution process, so always delay
|
||||
return delayMerge(stack, fallback);
|
||||
}
|
||||
}
|
||||
|
||||
protected AbstractConfigValue mergedWithTheUnmergeable(Unmergeable fallback) {
|
||||
requireNotIgnoringFallbacks();
|
||||
|
||||
return mergedWithTheUnmergeable(Collections.singletonList(this), fallback);
|
||||
}
|
||||
|
||||
protected AbstractConfigValue mergedWithObject(AbstractConfigObject fallback) {
|
||||
requireNotIgnoringFallbacks();
|
||||
|
||||
return mergedWithObject(Collections.singletonList(this), fallback);
|
||||
}
|
||||
|
||||
protected AbstractConfigValue mergedWithNonObject(AbstractConfigValue fallback) {
|
||||
requireNotIgnoringFallbacks();
|
||||
|
||||
return mergedWithNonObject(Collections.singletonList(this), fallback);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractConfigValue withOrigin(ConfigOrigin origin) {
|
||||
if (this.origin == origin)
|
||||
return this;
|
||||
else
|
||||
return newCopy(origin);
|
||||
}
|
||||
|
||||
// this is only overridden to change the return type
|
||||
@Override
|
||||
public AbstractConfigValue withFallback(ConfigMergeable mergeable) {
|
||||
if (ignoresFallbacks()) {
|
||||
return this;
|
||||
} else {
|
||||
ConfigValue other = ((MergeableValue) mergeable).toFallbackValue();
|
||||
|
||||
if (other instanceof Unmergeable) {
|
||||
return mergedWithTheUnmergeable((Unmergeable) other);
|
||||
} else if (other instanceof AbstractConfigObject) {
|
||||
return mergedWithObject((AbstractConfigObject) other);
|
||||
} else {
|
||||
return mergedWithNonObject((AbstractConfigValue) other);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected boolean canEqual(Object other) {
|
||||
return other instanceof ConfigValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
// note that "origin" is deliberately NOT part of equality
|
||||
if (other instanceof ConfigValue) {
|
||||
return canEqual(other)
|
||||
&& (this.valueType() ==
|
||||
((ConfigValue) other).valueType())
|
||||
&& ConfigImplUtil.equalsHandlingNull(this.unwrapped(),
|
||||
((ConfigValue) other).unwrapped());
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
// note that "origin" is deliberately NOT part of equality
|
||||
Object o = this.unwrapped();
|
||||
if (o == null)
|
||||
return 0;
|
||||
else
|
||||
return o.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
render(sb, 0, true /* atRoot */, null /* atKey */, ConfigRenderOptions.concise());
|
||||
return getClass().getSimpleName() + "(" + sb.toString() + ")";
|
||||
}
|
||||
|
||||
protected static void indent(StringBuilder sb, int indent, ConfigRenderOptions options) {
|
||||
if (options.getFormatted()) {
|
||||
int remaining = indent;
|
||||
while (remaining > 0) {
|
||||
sb.append(" ");
|
||||
--remaining;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected void render(StringBuilder sb, int indent, boolean atRoot, String atKey, ConfigRenderOptions options) {
|
||||
if (atKey != null) {
|
||||
String renderedKey;
|
||||
if (options.getJson())
|
||||
renderedKey = ConfigImplUtil.renderJsonString(atKey);
|
||||
else
|
||||
renderedKey = ConfigImplUtil.renderStringUnquotedIfPossible(atKey);
|
||||
|
||||
sb.append(renderedKey);
|
||||
|
||||
if (options.getJson()) {
|
||||
if (options.getFormatted())
|
||||
sb.append(" : ");
|
||||
else
|
||||
sb.append(":");
|
||||
} else {
|
||||
// in non-JSON we can omit the colon or equals before an object
|
||||
if (this instanceof ConfigObject) {
|
||||
if (options.getFormatted())
|
||||
sb.append(' ');
|
||||
} else {
|
||||
sb.append("=");
|
||||
}
|
||||
}
|
||||
}
|
||||
render(sb, indent, atRoot, options);
|
||||
}
|
||||
|
||||
protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) {
|
||||
Object u = unwrapped();
|
||||
sb.append(u.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public final String render() {
|
||||
return render(ConfigRenderOptions.defaults());
|
||||
}
|
||||
|
||||
@Override
|
||||
public final String render(ConfigRenderOptions options) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
render(sb, 0, true, null, options);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
// toString() is a debugging-oriented string but this is defined
|
||||
// to create a string that would parse back to the value in JSON.
|
||||
// It only works for primitive values (that would be a single token)
|
||||
// which are auto-converted to strings when concatenating with
|
||||
// other strings or by the DefaultTransformer.
|
||||
String transformToString() {
|
||||
return null;
|
||||
}
|
||||
|
||||
SimpleConfig atKey(ConfigOrigin origin, String key) {
|
||||
Map<String, AbstractConfigValue> m = Collections.singletonMap(key, this);
|
||||
return (new SimpleConfigObject(origin, m)).toConfig();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SimpleConfig atKey(String key) {
|
||||
return atKey(SimpleConfigOrigin.newSimple("atKey(" + key + ")"), key);
|
||||
}
|
||||
|
||||
SimpleConfig atPath(ConfigOrigin origin, Path path) {
|
||||
Path parent = path.parent();
|
||||
SimpleConfig result = atKey(origin, path.last());
|
||||
while (parent != null) {
|
||||
String key = parent.last();
|
||||
result = result.atKey(origin, key);
|
||||
parent = parent.parent();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SimpleConfig atPath(String pathExpression) {
|
||||
SimpleConfigOrigin origin = SimpleConfigOrigin.newSimple("atPath(" + pathExpression + ")");
|
||||
return atPath(origin, Path.newPath(pathExpression));
|
||||
}
|
||||
}
|
||||
+305
@@ -0,0 +1,305 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.beans.BeanInfo;
|
||||
import java.beans.IntrospectionException;
|
||||
import java.beans.Introspector;
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.time.Duration;
|
||||
import java.util.Set;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.Config;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigObject;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigList;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigMemorySize;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.Optional;
|
||||
|
||||
/**
|
||||
* Internal implementation detail, not ABI stable, do not touch.
|
||||
* For use only by the {@link com.typesafe.config} package.
|
||||
*/
|
||||
public class ConfigBeanImpl {
|
||||
|
||||
/**
|
||||
* This is public ONLY for use by the "config" package, DO NOT USE this ABI
|
||||
* may change.
|
||||
* @param <T> type of the bean
|
||||
* @param config config to use
|
||||
* @param clazz class of the bean
|
||||
* @return the bean instance
|
||||
*/
|
||||
public static <T> T createInternal(Config config, Class<T> clazz) {
|
||||
if (((SimpleConfig)config).root().resolveStatus() != ResolveStatus.RESOLVED)
|
||||
throw new ConfigException.NotResolved(
|
||||
"need to Config#resolve() a config before using it to initialize a bean, see the API docs for Config#resolve()");
|
||||
|
||||
Map<String, AbstractConfigValue> configProps = new HashMap<String, AbstractConfigValue>();
|
||||
Map<String, String> originalNames = new HashMap<String, String>();
|
||||
for (Map.Entry<String, ConfigValue> configProp : config.root().entrySet()) {
|
||||
String originalName = configProp.getKey();
|
||||
String camelName = ConfigImplUtil.toCamelCase(originalName);
|
||||
// if a setting is in there both as some hyphen name and the camel name,
|
||||
// the camel one wins
|
||||
if (originalNames.containsKey(camelName) && !originalName.equals(camelName)) {
|
||||
// if we aren't a camel name to start with, we lose.
|
||||
// if we are or we are the first matching key, we win.
|
||||
} else {
|
||||
configProps.put(camelName, (AbstractConfigValue) configProp.getValue());
|
||||
originalNames.put(camelName, originalName);
|
||||
}
|
||||
}
|
||||
|
||||
BeanInfo beanInfo = null;
|
||||
try {
|
||||
beanInfo = Introspector.getBeanInfo(clazz);
|
||||
} catch (IntrospectionException e) {
|
||||
throw new ConfigException.BadBean("Could not get bean information for class " + clazz.getName(), e);
|
||||
}
|
||||
|
||||
try {
|
||||
List<PropertyDescriptor> beanProps = new ArrayList<PropertyDescriptor>();
|
||||
for (PropertyDescriptor beanProp : beanInfo.getPropertyDescriptors()) {
|
||||
if (beanProp.getReadMethod() == null || beanProp.getWriteMethod() == null) {
|
||||
continue;
|
||||
}
|
||||
beanProps.add(beanProp);
|
||||
}
|
||||
|
||||
// Try to throw all validation issues at once (this does not comprehensively
|
||||
// find every issue, but it should find common ones).
|
||||
List<ConfigException.ValidationProblem> problems = new ArrayList<ConfigException.ValidationProblem>();
|
||||
for (PropertyDescriptor beanProp : beanProps) {
|
||||
Method setter = beanProp.getWriteMethod();
|
||||
Class<?> parameterClass = setter.getParameterTypes()[0];
|
||||
|
||||
ConfigValueType expectedType = getValueTypeOrNull(parameterClass);
|
||||
if (expectedType != null) {
|
||||
String name = originalNames.get(beanProp.getName());
|
||||
if (name == null)
|
||||
name = beanProp.getName();
|
||||
Path path = Path.newKey(name);
|
||||
AbstractConfigValue configValue = configProps.get(beanProp.getName());
|
||||
if (configValue != null) {
|
||||
SimpleConfig.checkValid(path, expectedType, configValue, problems);
|
||||
} else {
|
||||
if (!isOptionalProperty(clazz, beanProp)) {
|
||||
SimpleConfig.addMissing(problems, expectedType, path, config.origin());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!problems.isEmpty()) {
|
||||
throw new ConfigException.ValidationFailed(problems);
|
||||
}
|
||||
|
||||
// Fill in the bean instance
|
||||
T bean = clazz.newInstance();
|
||||
for (PropertyDescriptor beanProp : beanProps) {
|
||||
Method setter = beanProp.getWriteMethod();
|
||||
Type parameterType = setter.getGenericParameterTypes()[0];
|
||||
Class<?> parameterClass = setter.getParameterTypes()[0];
|
||||
String configPropName = originalNames.get(beanProp.getName());
|
||||
// Is the property key missing in the config?
|
||||
if (configPropName == null) {
|
||||
// If so, continue if the field is marked as @{link Optional}
|
||||
if (isOptionalProperty(clazz, beanProp)) {
|
||||
continue;
|
||||
}
|
||||
// Otherwise, raise a {@link Missing} exception right here
|
||||
throw new ConfigException.Missing(beanProp.getName());
|
||||
}
|
||||
Object unwrapped = getValue(clazz, parameterType, parameterClass, config, configPropName);
|
||||
setter.invoke(bean, unwrapped);
|
||||
}
|
||||
return bean;
|
||||
} catch (InstantiationException e) {
|
||||
throw new ConfigException.BadBean(clazz.getName() + " needs a public no-args constructor to be used as a bean", e);
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new ConfigException.BadBean(clazz.getName() + " getters and setters are not accessible, they must be for use as a bean", e);
|
||||
} catch (InvocationTargetException e) {
|
||||
throw new ConfigException.BadBean("Calling bean method on " + clazz.getName() + " caused an exception", e);
|
||||
}
|
||||
}
|
||||
|
||||
// we could magically make this work in many cases by doing
|
||||
// getAnyRef() (or getValue().unwrapped()), but anytime we
|
||||
// rely on that, we aren't doing the type conversions Config
|
||||
// usually does, and we will throw ClassCastException instead
|
||||
// of a nicer error message giving the name of the bad
|
||||
// setting. So, instead, we only support a limited number of
|
||||
// types plus you can always use Object, ConfigValue, Config,
|
||||
// ConfigObject, etc. as an escape hatch.
|
||||
private static Object getValue(Class<?> beanClass, Type parameterType, Class<?> parameterClass, Config config,
|
||||
String configPropName) {
|
||||
if (parameterClass == Boolean.class || parameterClass == boolean.class) {
|
||||
return config.getBoolean(configPropName);
|
||||
} else if (parameterClass == Integer.class || parameterClass == int.class) {
|
||||
return config.getInt(configPropName);
|
||||
} else if (parameterClass == Double.class || parameterClass == double.class) {
|
||||
return config.getDouble(configPropName);
|
||||
} else if (parameterClass == Long.class || parameterClass == long.class) {
|
||||
return config.getLong(configPropName);
|
||||
} else if (parameterClass == String.class) {
|
||||
return config.getString(configPropName);
|
||||
} else if (parameterClass == Duration.class) {
|
||||
return config.getDuration(configPropName);
|
||||
} else if (parameterClass == ConfigMemorySize.class) {
|
||||
return config.getMemorySize(configPropName);
|
||||
} else if (parameterClass == Object.class) {
|
||||
return config.getAnyRef(configPropName);
|
||||
} else if (parameterClass == List.class) {
|
||||
return getListValue(beanClass, parameterType, parameterClass, config, configPropName);
|
||||
} else if (parameterClass == Set.class) {
|
||||
return getSetValue(beanClass, parameterType, parameterClass, config, configPropName);
|
||||
} else if (parameterClass == Map.class) {
|
||||
// we could do better here, but right now we don't.
|
||||
Type[] typeArgs = ((ParameterizedType)parameterType).getActualTypeArguments();
|
||||
if (typeArgs[0] != String.class || typeArgs[1] != Object.class) {
|
||||
throw new ConfigException.BadBean("Bean property '" + configPropName + "' of class " + beanClass.getName() + " has unsupported Map<" + typeArgs[0] + "," + typeArgs[1] + ">, only Map<String,Object> is supported right now");
|
||||
}
|
||||
return config.getObject(configPropName).unwrapped();
|
||||
} else if (parameterClass == Config.class) {
|
||||
return config.getConfig(configPropName);
|
||||
} else if (parameterClass == ConfigObject.class) {
|
||||
return config.getObject(configPropName);
|
||||
} else if (parameterClass == ConfigValue.class) {
|
||||
return config.getValue(configPropName);
|
||||
} else if (parameterClass == ConfigList.class) {
|
||||
return config.getList(configPropName);
|
||||
} else if (parameterClass.isEnum()) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Enum enumValue = config.getEnum((Class<Enum>) parameterClass, configPropName);
|
||||
return enumValue;
|
||||
} else if (hasAtLeastOneBeanProperty(parameterClass)) {
|
||||
return createInternal(config.getConfig(configPropName), parameterClass);
|
||||
} else {
|
||||
throw new ConfigException.BadBean("Bean property " + configPropName + " of class " + beanClass.getName() + " has unsupported type " + parameterType);
|
||||
}
|
||||
}
|
||||
|
||||
private static Object getSetValue(Class<?> beanClass, Type parameterType, Class<?> parameterClass, Config config, String configPropName) {
|
||||
return new HashSet((List) getListValue(beanClass, parameterType, parameterClass, config, configPropName));
|
||||
}
|
||||
|
||||
private static Object getListValue(Class<?> beanClass, Type parameterType, Class<?> parameterClass, Config config, String configPropName) {
|
||||
Type elementType = ((ParameterizedType)parameterType).getActualTypeArguments()[0];
|
||||
|
||||
if (elementType == Boolean.class) {
|
||||
return config.getBooleanList(configPropName);
|
||||
} else if (elementType == Integer.class) {
|
||||
return config.getIntList(configPropName);
|
||||
} else if (elementType == Double.class) {
|
||||
return config.getDoubleList(configPropName);
|
||||
} else if (elementType == Long.class) {
|
||||
return config.getLongList(configPropName);
|
||||
} else if (elementType == String.class) {
|
||||
return config.getStringList(configPropName);
|
||||
} else if (elementType == Duration.class) {
|
||||
return config.getDurationList(configPropName);
|
||||
} else if (elementType == ConfigMemorySize.class) {
|
||||
return config.getMemorySizeList(configPropName);
|
||||
} else if (elementType == Object.class) {
|
||||
return config.getAnyRefList(configPropName);
|
||||
} else if (elementType == Config.class) {
|
||||
return config.getConfigList(configPropName);
|
||||
} else if (elementType == ConfigObject.class) {
|
||||
return config.getObjectList(configPropName);
|
||||
} else if (elementType == ConfigValue.class) {
|
||||
return config.getList(configPropName);
|
||||
} else if (((Class<?>) elementType).isEnum()) {
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Enum> enumValues = config.getEnumList((Class<Enum>) elementType, configPropName);
|
||||
return enumValues;
|
||||
} else if (hasAtLeastOneBeanProperty((Class<?>) elementType)) {
|
||||
List<Object> beanList = new ArrayList<Object>();
|
||||
List<? extends Config> configList = config.getConfigList(configPropName);
|
||||
for (Config listMember : configList) {
|
||||
beanList.add(createInternal(listMember, (Class<?>) elementType));
|
||||
}
|
||||
return beanList;
|
||||
} else {
|
||||
throw new ConfigException.BadBean("Bean property '" + configPropName + "' of class " + beanClass.getName() + " has unsupported list element type " + elementType);
|
||||
}
|
||||
}
|
||||
|
||||
// null if we can't easily say; this is heuristic/best-effort
|
||||
private static ConfigValueType getValueTypeOrNull(Class<?> parameterClass) {
|
||||
if (parameterClass == Boolean.class || parameterClass == boolean.class) {
|
||||
return ConfigValueType.BOOLEAN;
|
||||
} else if (parameterClass == Integer.class || parameterClass == int.class) {
|
||||
return ConfigValueType.NUMBER;
|
||||
} else if (parameterClass == Double.class || parameterClass == double.class) {
|
||||
return ConfigValueType.NUMBER;
|
||||
} else if (parameterClass == Long.class || parameterClass == long.class) {
|
||||
return ConfigValueType.NUMBER;
|
||||
} else if (parameterClass == String.class) {
|
||||
return ConfigValueType.STRING;
|
||||
} else if (parameterClass == Duration.class) {
|
||||
return null;
|
||||
} else if (parameterClass == ConfigMemorySize.class) {
|
||||
return null;
|
||||
} else if (parameterClass == List.class) {
|
||||
return ConfigValueType.LIST;
|
||||
} else if (parameterClass == Map.class) {
|
||||
return ConfigValueType.OBJECT;
|
||||
} else if (parameterClass == Config.class) {
|
||||
return ConfigValueType.OBJECT;
|
||||
} else if (parameterClass == ConfigObject.class) {
|
||||
return ConfigValueType.OBJECT;
|
||||
} else if (parameterClass == ConfigList.class) {
|
||||
return ConfigValueType.LIST;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean hasAtLeastOneBeanProperty(Class<?> clazz) {
|
||||
BeanInfo beanInfo = null;
|
||||
try {
|
||||
beanInfo = Introspector.getBeanInfo(clazz);
|
||||
} catch (IntrospectionException e) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (PropertyDescriptor beanProp : beanInfo.getPropertyDescriptors()) {
|
||||
if (beanProp.getReadMethod() != null && beanProp.getWriteMethod() != null) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean isOptionalProperty(Class beanClass, PropertyDescriptor beanProp) {
|
||||
Field field = getField(beanClass, beanProp.getName());
|
||||
return field != null && (field.getAnnotationsByType(Optional.class).length > 0);
|
||||
}
|
||||
|
||||
private static Field getField(Class beanClass, String fieldName) {
|
||||
try {
|
||||
Field field = beanClass.getDeclaredField(fieldName);
|
||||
field.setAccessible(true);
|
||||
return field;
|
||||
} catch (NoSuchFieldException e) {
|
||||
// Don't give up yet. Try to look for field in super class, if any.
|
||||
}
|
||||
beanClass = beanClass.getSuperclass();
|
||||
if (beanClass == null) {
|
||||
return null;
|
||||
}
|
||||
return getField(beanClass, fieldName);
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.io.ObjectStreamException;
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType;
|
||||
|
||||
final class ConfigBoolean extends AbstractConfigValue implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 2L;
|
||||
|
||||
final private boolean value;
|
||||
|
||||
ConfigBoolean(ConfigOrigin origin, boolean value) {
|
||||
super(origin);
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigValueType valueType() {
|
||||
return ConfigValueType.BOOLEAN;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean unwrapped() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
String transformToString() {
|
||||
return value ? "true" : "false";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigBoolean newCopy(ConfigOrigin origin) {
|
||||
return new ConfigBoolean(origin, value);
|
||||
}
|
||||
|
||||
// serialization all goes through SerializedConfigValue
|
||||
private Object writeReplace() throws ObjectStreamException {
|
||||
return new SerializedConfigValue(this);
|
||||
}
|
||||
}
|
||||
+293
@@ -0,0 +1,293 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigObject;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigRenderOptions;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType;
|
||||
|
||||
/**
|
||||
* A ConfigConcatenation represents a list of values to be concatenated (see the
|
||||
* spec). It only has to exist if at least one value is an unresolved
|
||||
* substitution, otherwise we could go ahead and collapse the list into a single
|
||||
* value.
|
||||
*
|
||||
* Right now this is always a list of strings and ${} references, but in the
|
||||
* future should support a list of ConfigList. We may also support
|
||||
* concatenations of objects, but ConfigDelayedMerge should be used for that
|
||||
* since a concat of objects really will merge, not concatenate.
|
||||
*/
|
||||
final class ConfigConcatenation extends AbstractConfigValue implements Unmergeable, Container {
|
||||
|
||||
final private List<AbstractConfigValue> pieces;
|
||||
|
||||
ConfigConcatenation(ConfigOrigin origin, List<AbstractConfigValue> pieces) {
|
||||
super(origin);
|
||||
this.pieces = pieces;
|
||||
|
||||
if (pieces.size() < 2)
|
||||
throw new ConfigException.BugOrBroken("Created concatenation with less than 2 items: "
|
||||
+ this);
|
||||
|
||||
boolean hadUnmergeable = false;
|
||||
for (AbstractConfigValue p : pieces) {
|
||||
if (p instanceof ConfigConcatenation)
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"ConfigConcatenation should never be nested: " + this);
|
||||
if (p instanceof Unmergeable)
|
||||
hadUnmergeable = true;
|
||||
}
|
||||
if (!hadUnmergeable)
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"Created concatenation without an unmergeable in it: " + this);
|
||||
}
|
||||
|
||||
private ConfigException.NotResolved notResolved() {
|
||||
return new ConfigException.NotResolved(
|
||||
"need to Config#resolve(), see the API docs for Config#resolve(); substitution not resolved: "
|
||||
+ this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigValueType valueType() {
|
||||
throw notResolved();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object unwrapped() {
|
||||
throw notResolved();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigConcatenation newCopy(ConfigOrigin newOrigin) {
|
||||
return new ConfigConcatenation(newOrigin, pieces);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean ignoresFallbacks() {
|
||||
// we can never ignore fallbacks because if a child ConfigReference
|
||||
// is self-referential we have to look lower in the merge stack
|
||||
// for its value.
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<ConfigConcatenation> unmergedValues() {
|
||||
return Collections.singleton(this);
|
||||
}
|
||||
|
||||
private static boolean isIgnoredWhitespace(AbstractConfigValue value) {
|
||||
return (value instanceof ConfigString) && !((ConfigString)value).wasQuoted();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add left and right, or their merger, to builder.
|
||||
*/
|
||||
private static void join(ArrayList<AbstractConfigValue> builder, AbstractConfigValue origRight) {
|
||||
AbstractConfigValue left = builder.get(builder.size() - 1);
|
||||
AbstractConfigValue right = origRight;
|
||||
|
||||
// check for an object which can be converted to a list
|
||||
// (this will be an object with numeric keys, like foo.0, foo.1)
|
||||
if (left instanceof ConfigObject && right instanceof SimpleConfigList) {
|
||||
left = DefaultTransformer.transform(left, ConfigValueType.LIST);
|
||||
} else if (left instanceof SimpleConfigList && right instanceof ConfigObject) {
|
||||
right = DefaultTransformer.transform(right, ConfigValueType.LIST);
|
||||
}
|
||||
|
||||
// Since this depends on the type of two instances, I couldn't think
|
||||
// of much alternative to an instanceof chain. Visitors are sometimes
|
||||
// used for multiple dispatch but seems like overkill.
|
||||
AbstractConfigValue joined = null;
|
||||
if (left instanceof ConfigObject && right instanceof ConfigObject) {
|
||||
joined = right.withFallback(left);
|
||||
} else if (left instanceof SimpleConfigList && right instanceof SimpleConfigList) {
|
||||
joined = ((SimpleConfigList)left).concatenate((SimpleConfigList)right);
|
||||
} else if ((left instanceof SimpleConfigList || left instanceof ConfigObject) &&
|
||||
isIgnoredWhitespace(right)) {
|
||||
joined = left;
|
||||
// it should be impossible that left is whitespace and right is a list or object
|
||||
} else if (left instanceof ConfigConcatenation || right instanceof ConfigConcatenation) {
|
||||
throw new ConfigException.BugOrBroken("unflattened ConfigConcatenation");
|
||||
} else if (left instanceof Unmergeable || right instanceof Unmergeable) {
|
||||
// leave joined=null, cannot join
|
||||
} else {
|
||||
// handle primitive type or primitive type mixed with object or list
|
||||
String s1 = left.transformToString();
|
||||
String s2 = right.transformToString();
|
||||
if (s1 == null || s2 == null) {
|
||||
throw new ConfigException.WrongType(left.origin(),
|
||||
"Cannot concatenate object or list with a non-object-or-list, " + left
|
||||
+ " and " + right + " are not compatible");
|
||||
} else {
|
||||
ConfigOrigin joinedOrigin = SimpleConfigOrigin.mergeOrigins(left.origin(),
|
||||
right.origin());
|
||||
joined = new ConfigString.Quoted(joinedOrigin, s1 + s2);
|
||||
}
|
||||
}
|
||||
|
||||
if (joined == null) {
|
||||
builder.add(right);
|
||||
} else {
|
||||
builder.remove(builder.size() - 1);
|
||||
builder.add(joined);
|
||||
}
|
||||
}
|
||||
|
||||
static List<AbstractConfigValue> consolidate(List<AbstractConfigValue> pieces) {
|
||||
if (pieces.size() < 2) {
|
||||
return pieces;
|
||||
} else {
|
||||
List<AbstractConfigValue> flattened = new ArrayList<AbstractConfigValue>(pieces.size());
|
||||
for (AbstractConfigValue v : pieces) {
|
||||
if (v instanceof ConfigConcatenation) {
|
||||
flattened.addAll(((ConfigConcatenation) v).pieces);
|
||||
} else {
|
||||
flattened.add(v);
|
||||
}
|
||||
}
|
||||
|
||||
ArrayList<AbstractConfigValue> consolidated = new ArrayList<AbstractConfigValue>(
|
||||
flattened.size());
|
||||
for (AbstractConfigValue v : flattened) {
|
||||
if (consolidated.isEmpty())
|
||||
consolidated.add(v);
|
||||
else
|
||||
join(consolidated, v);
|
||||
}
|
||||
|
||||
return consolidated;
|
||||
}
|
||||
}
|
||||
|
||||
static AbstractConfigValue concatenate(List<AbstractConfigValue> pieces) {
|
||||
List<AbstractConfigValue> consolidated = consolidate(pieces);
|
||||
if (consolidated.isEmpty()) {
|
||||
return null;
|
||||
} else if (consolidated.size() == 1) {
|
||||
return consolidated.get(0);
|
||||
} else {
|
||||
ConfigOrigin mergedOrigin = SimpleConfigOrigin.mergeOrigins(consolidated);
|
||||
return new ConfigConcatenation(mergedOrigin, consolidated);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
ResolveResult<? extends AbstractConfigValue> resolveSubstitutions(ResolveContext context, ResolveSource source)
|
||||
throws NotPossibleToResolve {
|
||||
if (ConfigImpl.traceSubstitutionsEnabled()) {
|
||||
int indent = context.depth() + 2;
|
||||
ConfigImpl.trace(indent - 1, "concatenation has " + pieces.size() + " pieces:");
|
||||
int count = 0;
|
||||
for (AbstractConfigValue v : pieces) {
|
||||
ConfigImpl.trace(indent, count + ": " + v);
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Right now there's no reason to pushParent here because the
|
||||
// content of ConfigConcatenation should not need to replaceChild,
|
||||
// but if it did we'd have to do this.
|
||||
ResolveSource sourceWithParent = source; // .pushParent(this);
|
||||
ResolveContext newContext = context;
|
||||
|
||||
List<AbstractConfigValue> resolved = new ArrayList<AbstractConfigValue>(pieces.size());
|
||||
for (AbstractConfigValue p : pieces) {
|
||||
// to concat into a string we have to do a full resolve,
|
||||
// so unrestrict the context, then put restriction back afterward
|
||||
Path restriction = newContext.restrictToChild();
|
||||
ResolveResult<? extends AbstractConfigValue> result = newContext.unrestricted()
|
||||
.resolve(p, sourceWithParent);
|
||||
AbstractConfigValue r = result.value;
|
||||
newContext = result.context.restrict(restriction);
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(context.depth(), "resolved concat piece to " + r);
|
||||
if (r == null) {
|
||||
// it was optional... omit
|
||||
} else {
|
||||
resolved.add(r);
|
||||
}
|
||||
}
|
||||
|
||||
// now need to concat everything
|
||||
List<AbstractConfigValue> joined = consolidate(resolved);
|
||||
// if unresolved is allowed we can just become another
|
||||
// ConfigConcatenation
|
||||
if (joined.size() > 1 && context.options().getAllowUnresolved())
|
||||
return ResolveResult.make(newContext, new ConfigConcatenation(this.origin(), joined));
|
||||
else if (joined.isEmpty())
|
||||
// we had just a list of optional references using ${?}
|
||||
return ResolveResult.make(newContext, null);
|
||||
else if (joined.size() == 1)
|
||||
return ResolveResult.make(newContext, joined.get(0));
|
||||
else
|
||||
throw new ConfigException.BugOrBroken("Bug in the library; resolved list was joined to too many values: "
|
||||
+ joined);
|
||||
}
|
||||
|
||||
@Override
|
||||
ResolveStatus resolveStatus() {
|
||||
return ResolveStatus.UNRESOLVED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigConcatenation replaceChild(AbstractConfigValue child, AbstractConfigValue replacement) {
|
||||
List<AbstractConfigValue> newPieces = replaceChildInList(pieces, child, replacement);
|
||||
if (newPieces == null)
|
||||
return null;
|
||||
else
|
||||
return new ConfigConcatenation(origin(), newPieces);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasDescendant(AbstractConfigValue descendant) {
|
||||
return hasDescendantInList(pieces, descendant);
|
||||
}
|
||||
|
||||
// when you graft a substitution into another object,
|
||||
// you have to prefix it with the location in that object
|
||||
// where you grafted it; but save prefixLength so
|
||||
// system property and env variable lookups don't get
|
||||
// broken.
|
||||
@Override
|
||||
ConfigConcatenation relativized(Path prefix) {
|
||||
List<AbstractConfigValue> newPieces = new ArrayList<AbstractConfigValue>();
|
||||
for (AbstractConfigValue p : pieces) {
|
||||
newPieces.add(p.relativized(prefix));
|
||||
}
|
||||
return new ConfigConcatenation(origin(), newPieces);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean canEqual(Object other) {
|
||||
return other instanceof ConfigConcatenation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
// note that "origin" is deliberately NOT part of equality
|
||||
if (other instanceof ConfigConcatenation) {
|
||||
return canEqual(other) && this.pieces.equals(((ConfigConcatenation) other).pieces);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
// note that "origin" is deliberately NOT part of equality
|
||||
return pieces.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) {
|
||||
for (AbstractConfigValue p : pieces) {
|
||||
p.render(sb, indent, atRoot, options);
|
||||
}
|
||||
}
|
||||
}
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigRenderOptions;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType;
|
||||
|
||||
/**
|
||||
* The issue here is that we want to first merge our stack of config files, and
|
||||
* then we want to evaluate substitutions. But if two substitutions both expand
|
||||
* to an object, we might need to merge those two objects. Thus, we can't ever
|
||||
* "override" a substitution when we do a merge; instead we have to save the
|
||||
* stack of values that should be merged, and resolve the merge when we evaluate
|
||||
* substitutions.
|
||||
*/
|
||||
final class ConfigDelayedMerge extends AbstractConfigValue implements Unmergeable,
|
||||
ReplaceableMergeStack {
|
||||
|
||||
// earlier items in the stack win
|
||||
final private List<AbstractConfigValue> stack;
|
||||
|
||||
ConfigDelayedMerge(ConfigOrigin origin, List<AbstractConfigValue> stack) {
|
||||
super(origin);
|
||||
this.stack = stack;
|
||||
if (stack.isEmpty())
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"creating empty delayed merge value");
|
||||
|
||||
for (AbstractConfigValue v : stack) {
|
||||
if (v instanceof ConfigDelayedMerge || v instanceof ConfigDelayedMergeObject)
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"placed nested DelayedMerge in a ConfigDelayedMerge, should have consolidated stack");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigValueType valueType() {
|
||||
throw new ConfigException.NotResolved(
|
||||
"called valueType() on value with unresolved substitutions, need to Config#resolve() first, see API docs");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object unwrapped() {
|
||||
throw new ConfigException.NotResolved(
|
||||
"called unwrapped() on value with unresolved substitutions, need to Config#resolve() first, see API docs");
|
||||
}
|
||||
|
||||
@Override
|
||||
ResolveResult<? extends AbstractConfigValue> resolveSubstitutions(ResolveContext context, ResolveSource source)
|
||||
throws NotPossibleToResolve {
|
||||
return resolveSubstitutions(this, stack, context, source);
|
||||
}
|
||||
|
||||
// static method also used by ConfigDelayedMergeObject
|
||||
static ResolveResult<? extends AbstractConfigValue> resolveSubstitutions(ReplaceableMergeStack replaceable,
|
||||
List<AbstractConfigValue> stack,
|
||||
ResolveContext context, ResolveSource source) throws NotPossibleToResolve {
|
||||
if (ConfigImpl.traceSubstitutionsEnabled()) {
|
||||
ConfigImpl.trace(context.depth(), "delayed merge stack has " + stack.size() + " items:");
|
||||
int count = 0;
|
||||
for (AbstractConfigValue v : stack) {
|
||||
ConfigImpl.trace(context.depth() + 1, count + ": " + v);
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// to resolve substitutions, we need to recursively resolve
|
||||
// the stack of stuff to merge, and merge the stack so
|
||||
// we won't be a delayed merge anymore. If restrictToChildOrNull
|
||||
// is non-null, or resolve options allow partial resolves,
|
||||
// we may remain a delayed merge though.
|
||||
|
||||
ResolveContext newContext = context;
|
||||
int count = 0;
|
||||
AbstractConfigValue merged = null;
|
||||
for (AbstractConfigValue end : stack) {
|
||||
// the end value may or may not be resolved already
|
||||
|
||||
ResolveSource sourceForEnd;
|
||||
|
||||
if (end instanceof ReplaceableMergeStack)
|
||||
throw new ConfigException.BugOrBroken("A delayed merge should not contain another one: " + replaceable);
|
||||
else if (end instanceof Unmergeable) {
|
||||
// the remainder could be any kind of value, including another
|
||||
// ConfigDelayedMerge
|
||||
AbstractConfigValue remainder = replaceable.makeReplacement(context, count + 1);
|
||||
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(newContext.depth(), "remainder portion: " + remainder);
|
||||
|
||||
// If, while resolving 'end' we come back to the same
|
||||
// merge stack, we only want to look _below_ 'end'
|
||||
// in the stack. So we arrange to replace the
|
||||
// ConfigDelayedMerge with a value that is only
|
||||
// the remainder of the stack below this one.
|
||||
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(newContext.depth(), "building sourceForEnd");
|
||||
|
||||
// we resetParents() here because we'll be resolving "end"
|
||||
// against a root which does NOT contain "end"
|
||||
sourceForEnd = source.replaceWithinCurrentParent((AbstractConfigValue) replaceable, remainder);
|
||||
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(newContext.depth(), " sourceForEnd before reset parents but after replace: "
|
||||
+ sourceForEnd);
|
||||
|
||||
sourceForEnd = sourceForEnd.resetParents();
|
||||
} else {
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(newContext.depth(),
|
||||
"will resolve end against the original source with parent pushed");
|
||||
|
||||
sourceForEnd = source.pushParent(replaceable);
|
||||
}
|
||||
|
||||
if (ConfigImpl.traceSubstitutionsEnabled()) {
|
||||
ConfigImpl.trace(newContext.depth(), "sourceForEnd =" + sourceForEnd);
|
||||
}
|
||||
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(newContext.depth(), "Resolving highest-priority item in delayed merge " + end
|
||||
+ " against " + sourceForEnd + " endWasRemoved=" + (source != sourceForEnd));
|
||||
ResolveResult<? extends AbstractConfigValue> result = newContext.resolve(end, sourceForEnd);
|
||||
AbstractConfigValue resolvedEnd = result.value;
|
||||
newContext = result.context;
|
||||
|
||||
if (resolvedEnd != null) {
|
||||
if (merged == null) {
|
||||
merged = resolvedEnd;
|
||||
} else {
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(newContext.depth() + 1, "merging " + merged + " with fallback " + resolvedEnd);
|
||||
merged = merged.withFallback(resolvedEnd);
|
||||
}
|
||||
}
|
||||
|
||||
count += 1;
|
||||
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(newContext.depth(), "stack merged, yielding: " + merged);
|
||||
}
|
||||
|
||||
return ResolveResult.make(newContext, merged);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractConfigValue makeReplacement(ResolveContext context, int skipping) {
|
||||
return ConfigDelayedMerge.makeReplacement(context, stack, skipping);
|
||||
}
|
||||
|
||||
// static method also used by ConfigDelayedMergeObject; end may be null
|
||||
static AbstractConfigValue makeReplacement(ResolveContext context, List<AbstractConfigValue> stack, int skipping) {
|
||||
List<AbstractConfigValue> subStack = stack.subList(skipping, stack.size());
|
||||
|
||||
if (subStack.isEmpty()) {
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(context.depth(), "Nothing else in the merge stack, replacing with null");
|
||||
return null;
|
||||
} else {
|
||||
// generate a new merge stack from only the remaining items
|
||||
AbstractConfigValue merged = null;
|
||||
for (AbstractConfigValue v : subStack) {
|
||||
if (merged == null)
|
||||
merged = v;
|
||||
else
|
||||
merged = merged.withFallback(v);
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
ResolveStatus resolveStatus() {
|
||||
return ResolveStatus.UNRESOLVED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractConfigValue replaceChild(AbstractConfigValue child, AbstractConfigValue replacement) {
|
||||
List<AbstractConfigValue> newStack = replaceChildInList(stack, child, replacement);
|
||||
if (newStack == null)
|
||||
return null;
|
||||
else
|
||||
return new ConfigDelayedMerge(origin(), newStack);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasDescendant(AbstractConfigValue descendant) {
|
||||
return hasDescendantInList(stack, descendant);
|
||||
}
|
||||
|
||||
@Override
|
||||
ConfigDelayedMerge relativized(Path prefix) {
|
||||
List<AbstractConfigValue> newStack = new ArrayList<AbstractConfigValue>();
|
||||
for (AbstractConfigValue o : stack) {
|
||||
newStack.add(o.relativized(prefix));
|
||||
}
|
||||
return new ConfigDelayedMerge(origin(), newStack);
|
||||
}
|
||||
|
||||
// static utility shared with ConfigDelayedMergeObject
|
||||
static boolean stackIgnoresFallbacks(List<AbstractConfigValue> stack) {
|
||||
AbstractConfigValue last = stack.get(stack.size() - 1);
|
||||
return last.ignoresFallbacks();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean ignoresFallbacks() {
|
||||
return stackIgnoresFallbacks(stack);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected AbstractConfigValue newCopy(ConfigOrigin newOrigin) {
|
||||
return new ConfigDelayedMerge(newOrigin, stack);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final ConfigDelayedMerge mergedWithTheUnmergeable(Unmergeable fallback) {
|
||||
return (ConfigDelayedMerge) mergedWithTheUnmergeable(stack, fallback);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final ConfigDelayedMerge mergedWithObject(AbstractConfigObject fallback) {
|
||||
return (ConfigDelayedMerge) mergedWithObject(stack, fallback);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigDelayedMerge mergedWithNonObject(AbstractConfigValue fallback) {
|
||||
return (ConfigDelayedMerge) mergedWithNonObject(stack, fallback);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<AbstractConfigValue> unmergedValues() {
|
||||
return stack;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean canEqual(Object other) {
|
||||
return other instanceof ConfigDelayedMerge;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
// note that "origin" is deliberately NOT part of equality
|
||||
if (other instanceof ConfigDelayedMerge) {
|
||||
return canEqual(other)
|
||||
&& (this.stack == ((ConfigDelayedMerge) other).stack || this.stack
|
||||
.equals(((ConfigDelayedMerge) other).stack));
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
// note that "origin" is deliberately NOT part of equality
|
||||
return stack.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void render(StringBuilder sb, int indent, boolean atRoot, String atKey, ConfigRenderOptions options) {
|
||||
render(stack, sb, indent, atRoot, atKey, options);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) {
|
||||
render(sb, indent, atRoot, null, options);
|
||||
}
|
||||
|
||||
// static method also used by ConfigDelayedMergeObject.
|
||||
static void render(List<AbstractConfigValue> stack, StringBuilder sb, int indent, boolean atRoot, String atKey,
|
||||
ConfigRenderOptions options) {
|
||||
boolean commentMerge = options.getComments();
|
||||
if (commentMerge) {
|
||||
sb.append("# unresolved merge of " + stack.size() + " values follows (\n");
|
||||
if (atKey == null) {
|
||||
indent(sb, indent, options);
|
||||
sb.append("# this unresolved merge will not be parseable because it's at the root of the object\n");
|
||||
indent(sb, indent, options);
|
||||
sb.append("# the HOCON format has no way to list multiple root objects in a single file\n");
|
||||
}
|
||||
}
|
||||
|
||||
List<AbstractConfigValue> reversed = new ArrayList<AbstractConfigValue>();
|
||||
reversed.addAll(stack);
|
||||
Collections.reverse(reversed);
|
||||
|
||||
int i = 0;
|
||||
for (AbstractConfigValue v : reversed) {
|
||||
if (commentMerge) {
|
||||
indent(sb, indent, options);
|
||||
if (atKey != null) {
|
||||
sb.append("# unmerged value " + i + " for key "
|
||||
+ ConfigImplUtil.renderJsonString(atKey) + " from ");
|
||||
} else {
|
||||
sb.append("# unmerged value " + i + " from ");
|
||||
}
|
||||
i += 1;
|
||||
sb.append(v.origin().description());
|
||||
sb.append("\n");
|
||||
|
||||
for (String comment : v.origin().comments()) {
|
||||
indent(sb, indent, options);
|
||||
sb.append("# ");
|
||||
sb.append(comment);
|
||||
sb.append("\n");
|
||||
}
|
||||
}
|
||||
indent(sb, indent, options);
|
||||
|
||||
if (atKey != null) {
|
||||
sb.append(ConfigImplUtil.renderJsonString(atKey));
|
||||
if (options.getFormatted())
|
||||
sb.append(" : ");
|
||||
else
|
||||
sb.append(":");
|
||||
}
|
||||
v.render(sb, indent, atRoot, options);
|
||||
sb.append(",");
|
||||
if (options.getFormatted())
|
||||
sb.append('\n');
|
||||
}
|
||||
// chop comma or newline
|
||||
sb.setLength(sb.length() - 1);
|
||||
if (options.getFormatted()) {
|
||||
sb.setLength(sb.length() - 1); // also chop comma
|
||||
sb.append("\n"); // put a newline back
|
||||
}
|
||||
if (commentMerge) {
|
||||
indent(sb, indent, options);
|
||||
sb.append("# ) end of unresolved merge\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
+326
@@ -0,0 +1,326 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigList;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigMergeable;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigRenderOptions;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue;
|
||||
|
||||
// This is just like ConfigDelayedMerge except we know statically
|
||||
// that it will turn out to be an object.
|
||||
final class ConfigDelayedMergeObject extends AbstractConfigObject implements Unmergeable,
|
||||
ReplaceableMergeStack {
|
||||
|
||||
final private List<AbstractConfigValue> stack;
|
||||
|
||||
ConfigDelayedMergeObject(ConfigOrigin origin, List<AbstractConfigValue> stack) {
|
||||
super(origin);
|
||||
this.stack = stack;
|
||||
|
||||
if (stack.isEmpty())
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"creating empty delayed merge object");
|
||||
if (!(stack.get(0) instanceof AbstractConfigObject))
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"created a delayed merge object not guaranteed to be an object");
|
||||
|
||||
for (AbstractConfigValue v : stack) {
|
||||
if (v instanceof ConfigDelayedMerge || v instanceof ConfigDelayedMergeObject)
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"placed nested DelayedMerge in a ConfigDelayedMergeObject, should have consolidated stack");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigDelayedMergeObject newCopy(ResolveStatus status, ConfigOrigin origin) {
|
||||
if (status != resolveStatus())
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"attempt to create resolved ConfigDelayedMergeObject");
|
||||
return new ConfigDelayedMergeObject(origin, stack);
|
||||
}
|
||||
|
||||
@Override
|
||||
ResolveResult<? extends AbstractConfigObject> resolveSubstitutions(ResolveContext context, ResolveSource source)
|
||||
throws NotPossibleToResolve {
|
||||
ResolveResult<? extends AbstractConfigValue> merged = ConfigDelayedMerge.resolveSubstitutions(this, stack,
|
||||
context, source);
|
||||
return merged.asObjectResult();
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractConfigValue makeReplacement(ResolveContext context, int skipping) {
|
||||
return ConfigDelayedMerge.makeReplacement(context, stack, skipping);
|
||||
}
|
||||
|
||||
@Override
|
||||
ResolveStatus resolveStatus() {
|
||||
return ResolveStatus.UNRESOLVED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractConfigValue replaceChild(AbstractConfigValue child, AbstractConfigValue replacement) {
|
||||
List<AbstractConfigValue> newStack = replaceChildInList(stack, child, replacement);
|
||||
if (newStack == null)
|
||||
return null;
|
||||
else
|
||||
return new ConfigDelayedMergeObject(origin(), newStack);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasDescendant(AbstractConfigValue descendant) {
|
||||
return hasDescendantInList(stack, descendant);
|
||||
}
|
||||
|
||||
@Override
|
||||
ConfigDelayedMergeObject relativized(Path prefix) {
|
||||
List<AbstractConfigValue> newStack = new ArrayList<AbstractConfigValue>();
|
||||
for (AbstractConfigValue o : stack) {
|
||||
newStack.add(o.relativized(prefix));
|
||||
}
|
||||
return new ConfigDelayedMergeObject(origin(), newStack);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean ignoresFallbacks() {
|
||||
return ConfigDelayedMerge.stackIgnoresFallbacks(stack);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final ConfigDelayedMergeObject mergedWithTheUnmergeable(Unmergeable fallback) {
|
||||
requireNotIgnoringFallbacks();
|
||||
|
||||
return (ConfigDelayedMergeObject) mergedWithTheUnmergeable(stack, fallback);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final ConfigDelayedMergeObject mergedWithObject(AbstractConfigObject fallback) {
|
||||
return mergedWithNonObject(fallback);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final ConfigDelayedMergeObject mergedWithNonObject(AbstractConfigValue fallback) {
|
||||
requireNotIgnoringFallbacks();
|
||||
|
||||
return (ConfigDelayedMergeObject) mergedWithNonObject(stack, fallback);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigDelayedMergeObject withFallback(ConfigMergeable mergeable) {
|
||||
return (ConfigDelayedMergeObject) super.withFallback(mergeable);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigDelayedMergeObject withOnlyKey(String key) {
|
||||
throw notResolved();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigDelayedMergeObject withoutKey(String key) {
|
||||
throw notResolved();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected AbstractConfigObject withOnlyPathOrNull(Path path) {
|
||||
throw notResolved();
|
||||
}
|
||||
|
||||
@Override
|
||||
AbstractConfigObject withOnlyPath(Path path) {
|
||||
throw notResolved();
|
||||
}
|
||||
|
||||
@Override
|
||||
AbstractConfigObject withoutPath(Path path) {
|
||||
throw notResolved();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigDelayedMergeObject withValue(String key, ConfigValue value) {
|
||||
throw notResolved();
|
||||
}
|
||||
|
||||
@Override
|
||||
ConfigDelayedMergeObject withValue(Path path, ConfigValue value) {
|
||||
throw notResolved();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<AbstractConfigValue> unmergedValues() {
|
||||
return stack;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean canEqual(Object other) {
|
||||
return other instanceof ConfigDelayedMergeObject;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
// note that "origin" is deliberately NOT part of equality
|
||||
if (other instanceof ConfigDelayedMergeObject) {
|
||||
return canEqual(other)
|
||||
&& (this.stack == ((ConfigDelayedMergeObject) other).stack || this.stack
|
||||
.equals(((ConfigDelayedMergeObject) other).stack));
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
// note that "origin" is deliberately NOT part of equality
|
||||
return stack.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void render(StringBuilder sb, int indent, boolean atRoot, String atKey, ConfigRenderOptions options) {
|
||||
ConfigDelayedMerge.render(stack, sb, indent, atRoot, atKey, options);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) {
|
||||
render(sb, indent, atRoot, null, options);
|
||||
}
|
||||
|
||||
private static ConfigException notResolved() {
|
||||
return new ConfigException.NotResolved(
|
||||
"need to Config#resolve() before using this object, see the API docs for Config#resolve()");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> unwrapped() {
|
||||
throw notResolved();
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractConfigValue get(Object key) {
|
||||
throw notResolved();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean containsKey(Object key) {
|
||||
throw notResolved();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean containsValue(Object value) {
|
||||
throw notResolved();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<java.util.Map.Entry<String, ConfigValue>> entrySet() {
|
||||
throw notResolved();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
throw notResolved();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> keySet() {
|
||||
throw notResolved();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
throw notResolved();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<ConfigValue> values() {
|
||||
throw notResolved();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected AbstractConfigValue attemptPeekWithPartialResolve(String key) {
|
||||
// a partial resolve of a ConfigDelayedMergeObject always results in a
|
||||
// SimpleConfigObject because all the substitutions in the stack get
|
||||
// resolved in order to look up the partial.
|
||||
// So we know here that we have not been resolved at all even
|
||||
// partially.
|
||||
// Given that, all this code is probably gratuitous, since the app code
|
||||
// is likely broken. But in general we only throw NotResolved if you try
|
||||
// to touch the exact key that isn't resolved, so this is in that
|
||||
// spirit.
|
||||
|
||||
// we'll be able to return a key if we have a value that ignores
|
||||
// fallbacks, prior to any unmergeable values.
|
||||
for (AbstractConfigValue layer : stack) {
|
||||
if (layer instanceof AbstractConfigObject) {
|
||||
AbstractConfigObject objectLayer = (AbstractConfigObject) layer;
|
||||
AbstractConfigValue v = objectLayer.attemptPeekWithPartialResolve(key);
|
||||
if (v != null) {
|
||||
if (v.ignoresFallbacks()) {
|
||||
// we know we won't need to merge anything in to this
|
||||
// value
|
||||
return v;
|
||||
} else {
|
||||
// we can't return this value because we know there are
|
||||
// unmergeable values later in the stack that may
|
||||
// contain values that need to be merged with this
|
||||
// value. we'll throw the exception when we get to those
|
||||
// unmergeable values, so continue here.
|
||||
continue;
|
||||
}
|
||||
} else if (layer instanceof Unmergeable) {
|
||||
// an unmergeable object (which would be another
|
||||
// ConfigDelayedMergeObject) can't know that a key is
|
||||
// missing, so it can't return null; it can only return a
|
||||
// value or throw NotPossibleToResolve
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"should not be reached: unmergeable object returned null value");
|
||||
} else {
|
||||
// a non-unmergeable AbstractConfigObject that returned null
|
||||
// for the key in question is not relevant, we can keep
|
||||
// looking for a value.
|
||||
continue;
|
||||
}
|
||||
} else if (layer instanceof Unmergeable) {
|
||||
throw new ConfigException.NotResolved("Key '" + key + "' is not available at '"
|
||||
+ origin().description() + "' because value at '"
|
||||
+ layer.origin().description()
|
||||
+ "' has not been resolved and may turn out to contain or hide '" + key
|
||||
+ "'."
|
||||
+ " Be sure to Config#resolve() before using a config object.");
|
||||
} else if (layer.resolveStatus() == ResolveStatus.UNRESOLVED) {
|
||||
// if the layer is not an object, and not a substitution or
|
||||
// merge,
|
||||
// then it's something that's unresolved because it _contains_
|
||||
// an unresolved object... i.e. it's an array
|
||||
if (!(layer instanceof ConfigList))
|
||||
throw new ConfigException.BugOrBroken("Expecting a list here, not " + layer);
|
||||
// all later objects will be hidden so we can say we won't find
|
||||
// the key
|
||||
return null;
|
||||
} else {
|
||||
// non-object, but resolved, like an integer or something.
|
||||
// has no children so the one we're after won't be in it.
|
||||
// we would only have this in the stack in case something
|
||||
// else "looks back" to it due to a cycle.
|
||||
// anyway at this point we know we can't find the key anymore.
|
||||
if (!layer.ignoresFallbacks()) {
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"resolved non-object should ignore fallbacks");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
// If we get here, then we never found anything unresolved which means
|
||||
// the ConfigDelayedMergeObject should not have existed. some
|
||||
// invariant was violated.
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"Delayed merge stack does not contain any unmergeable values");
|
||||
|
||||
}
|
||||
}
|
||||
+716
@@ -0,0 +1,716 @@
|
||||
/**
|
||||
* Copyright (C) 2015 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigParseOptions;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigSyntax;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType;
|
||||
|
||||
final class ConfigDocumentParser {
|
||||
static ConfigNodeRoot parse(Iterator<Token> tokens, ConfigOrigin origin, ConfigParseOptions options) {
|
||||
ConfigSyntax syntax = options.getSyntax() == null ? ConfigSyntax.CONF : options.getSyntax();
|
||||
ParseContext context = new ParseContext(syntax, origin, tokens);
|
||||
return context.parse();
|
||||
}
|
||||
|
||||
static AbstractConfigNodeValue parseValue(Iterator<Token> tokens, ConfigOrigin origin, ConfigParseOptions options) {
|
||||
ConfigSyntax syntax = options.getSyntax() == null ? ConfigSyntax.CONF : options.getSyntax();
|
||||
ParseContext context = new ParseContext(syntax, origin, tokens);
|
||||
return context.parseSingleValue();
|
||||
}
|
||||
|
||||
static private final class ParseContext {
|
||||
private int lineNumber;
|
||||
final private Stack<Token> buffer;
|
||||
final private Iterator<Token> tokens;
|
||||
final private ConfigSyntax flavor;
|
||||
final private ConfigOrigin baseOrigin;
|
||||
// this is the number of "equals" we are inside,
|
||||
// used to modify the error message to reflect that
|
||||
// someone may think this is .properties format.
|
||||
int equalsCount;
|
||||
|
||||
ParseContext(ConfigSyntax flavor, ConfigOrigin origin, Iterator<Token> tokens) {
|
||||
lineNumber = 1;
|
||||
buffer = new Stack<Token>();
|
||||
this.tokens = tokens;
|
||||
this.flavor = flavor;
|
||||
this.equalsCount = 0;
|
||||
this.baseOrigin = origin;
|
||||
}
|
||||
|
||||
private Token popToken() {
|
||||
if (buffer.isEmpty()) {
|
||||
return tokens.next();
|
||||
}
|
||||
return buffer.pop();
|
||||
}
|
||||
|
||||
private Token nextToken() {
|
||||
Token t = popToken();
|
||||
if (flavor == ConfigSyntax.JSON) {
|
||||
if (Tokens.isUnquotedText(t) && !isUnquotedWhitespace(t)) {
|
||||
throw parseError("Token not allowed in valid JSON: '"
|
||||
+ Tokens.getUnquotedText(t) + "'");
|
||||
} else if (Tokens.isSubstitution(t)) {
|
||||
throw parseError("Substitutions (${} syntax) not allowed in JSON");
|
||||
}
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
private Token nextTokenCollectingWhitespace(Collection<AbstractConfigNode> nodes) {
|
||||
while (true) {
|
||||
Token t = nextToken();
|
||||
if (Tokens.isIgnoredWhitespace(t) || Tokens.isNewline(t) || isUnquotedWhitespace(t)) {
|
||||
nodes.add(new ConfigNodeSingleToken(t));
|
||||
if (Tokens.isNewline(t)) {
|
||||
lineNumber = t.lineNumber() + 1;
|
||||
}
|
||||
} else if (Tokens.isComment(t)) {
|
||||
nodes.add(new ConfigNodeComment(t));
|
||||
} else {
|
||||
int newNumber = t.lineNumber();
|
||||
if (newNumber >= 0)
|
||||
lineNumber = newNumber;
|
||||
return t;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void putBack(Token token) {
|
||||
buffer.push(token);
|
||||
}
|
||||
|
||||
// In arrays and objects, comma can be omitted
|
||||
// as long as there's at least one newline instead.
|
||||
// this skips any newlines in front of a comma,
|
||||
// skips the comma, and returns true if it found
|
||||
// either a newline or a comma. The iterator
|
||||
// is left just after the comma or the newline.
|
||||
private boolean checkElementSeparator(Collection<AbstractConfigNode> nodes) {
|
||||
if (flavor == ConfigSyntax.JSON) {
|
||||
Token t = nextTokenCollectingWhitespace(nodes);
|
||||
if (t == Tokens.COMMA) {
|
||||
nodes.add(new ConfigNodeSingleToken(t));
|
||||
return true;
|
||||
} else {
|
||||
putBack(t);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
boolean sawSeparatorOrNewline = false;
|
||||
Token t = nextToken();
|
||||
while (true) {
|
||||
if (Tokens.isIgnoredWhitespace(t) || isUnquotedWhitespace(t)) {
|
||||
nodes.add(new ConfigNodeSingleToken(t));
|
||||
} else if (Tokens.isComment(t)) {
|
||||
nodes.add(new ConfigNodeComment(t));
|
||||
} else if (Tokens.isNewline(t)) {
|
||||
sawSeparatorOrNewline = true;
|
||||
lineNumber++;
|
||||
nodes.add(new ConfigNodeSingleToken(t));
|
||||
// we want to continue to also eat
|
||||
// a comma if there is one.
|
||||
} else if (t == Tokens.COMMA) {
|
||||
nodes.add(new ConfigNodeSingleToken(t));
|
||||
return true;
|
||||
} else {
|
||||
// non-newline-or-comma
|
||||
putBack(t);
|
||||
return sawSeparatorOrNewline;
|
||||
}
|
||||
t = nextToken();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// parse a concatenation. If there is no concatenation, return the next value
|
||||
private AbstractConfigNodeValue consolidateValues(Collection<AbstractConfigNode> nodes) {
|
||||
// this trick is not done in JSON
|
||||
if (flavor == ConfigSyntax.JSON)
|
||||
return null;
|
||||
|
||||
// create only if we have value tokens
|
||||
ArrayList<AbstractConfigNode> values = new ArrayList<AbstractConfigNode>();
|
||||
int valueCount = 0;
|
||||
|
||||
// ignore a newline up front
|
||||
Token t = nextTokenCollectingWhitespace(nodes);
|
||||
while (true) {
|
||||
AbstractConfigNodeValue v = null;
|
||||
if (Tokens.isIgnoredWhitespace(t)) {
|
||||
values.add(new ConfigNodeSingleToken(t));
|
||||
t = nextToken();
|
||||
continue;
|
||||
}
|
||||
else if (Tokens.isValue(t) || Tokens.isUnquotedText(t)
|
||||
|| Tokens.isSubstitution(t) || t == Tokens.OPEN_CURLY
|
||||
|| t == Tokens.OPEN_SQUARE) {
|
||||
// there may be newlines _within_ the objects and arrays
|
||||
v = parseValue(t);
|
||||
valueCount++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
|
||||
if (v == null)
|
||||
throw new ConfigException.BugOrBroken("no value");
|
||||
|
||||
values.add(v);
|
||||
|
||||
t = nextToken(); // but don't consolidate across a newline
|
||||
}
|
||||
|
||||
putBack(t);
|
||||
|
||||
// No concatenation was seen, but a single value may have been parsed, so return it, and put back
|
||||
// all succeeding tokens
|
||||
if (valueCount < 2) {
|
||||
AbstractConfigNodeValue value = null;
|
||||
for (AbstractConfigNode node : values) {
|
||||
if (node instanceof AbstractConfigNodeValue)
|
||||
value = (AbstractConfigNodeValue)node;
|
||||
else if (value == null)
|
||||
nodes.add(node);
|
||||
else
|
||||
putBack((new ArrayList<Token>(node.tokens())).get(0));
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
// Put back any trailing whitespace, as the parent object is responsible for tracking
|
||||
// any leading/trailing whitespace
|
||||
for (int i = values.size() - 1; i >= 0; i--) {
|
||||
if (values.get(i) instanceof ConfigNodeSingleToken) {
|
||||
putBack(((ConfigNodeSingleToken) values.get(i)).token());
|
||||
values.remove(i);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return new ConfigNodeConcatenation(values);
|
||||
}
|
||||
|
||||
private ConfigException parseError(String message) {
|
||||
return parseError(message, null);
|
||||
}
|
||||
|
||||
private ConfigException parseError(String message, Throwable cause) {
|
||||
return new ConfigException.Parse(baseOrigin.withLineNumber(lineNumber), message, cause);
|
||||
}
|
||||
|
||||
private String addQuoteSuggestion(String badToken, String message) {
|
||||
return addQuoteSuggestion(null, equalsCount > 0, badToken, message);
|
||||
}
|
||||
|
||||
private String addQuoteSuggestion(Path lastPath, boolean insideEquals, String badToken,
|
||||
String message) {
|
||||
String previousFieldName = lastPath != null ? lastPath.render() : null;
|
||||
|
||||
String part;
|
||||
if (badToken.equals(Tokens.END.toString())) {
|
||||
// EOF requires special handling for the error to make sense.
|
||||
if (previousFieldName != null)
|
||||
part = message + " (if you intended '" + previousFieldName
|
||||
+ "' to be part of a value, instead of a key, "
|
||||
+ "try adding double quotes around the whole value";
|
||||
else
|
||||
return message;
|
||||
} else {
|
||||
if (previousFieldName != null) {
|
||||
part = message + " (if you intended " + badToken
|
||||
+ " to be part of the value for '" + previousFieldName + "', "
|
||||
+ "try enclosing the value in double quotes";
|
||||
} else {
|
||||
part = message + " (if you intended " + badToken
|
||||
+ " to be part of a key or string value, "
|
||||
+ "try enclosing the key or value in double quotes";
|
||||
}
|
||||
}
|
||||
|
||||
if (insideEquals)
|
||||
return part
|
||||
+ ", or you may be able to rename the file .properties rather than .conf)";
|
||||
else
|
||||
return part + ")";
|
||||
}
|
||||
|
||||
private AbstractConfigNodeValue parseValue(Token t) {
|
||||
AbstractConfigNodeValue v = null;
|
||||
int startingEqualsCount = equalsCount;
|
||||
|
||||
if (Tokens.isValue(t) || Tokens.isUnquotedText(t) || Tokens.isSubstitution(t)) {
|
||||
v = new ConfigNodeSimpleValue(t);
|
||||
} else if (t == Tokens.OPEN_CURLY) {
|
||||
v = parseObject(true);
|
||||
} else if (t== Tokens.OPEN_SQUARE) {
|
||||
v = parseArray();
|
||||
} else {
|
||||
throw parseError(addQuoteSuggestion(t.toString(),
|
||||
"Expecting a value but got wrong token: " + t));
|
||||
}
|
||||
|
||||
if (equalsCount != startingEqualsCount)
|
||||
throw new ConfigException.BugOrBroken("Bug in config parser: unbalanced equals count");
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
private ConfigNodePath parseKey(Token token) {
|
||||
if (flavor == ConfigSyntax.JSON) {
|
||||
if (Tokens.isValueWithType(token, ConfigValueType.STRING)) {
|
||||
return PathParser.parsePathNodeExpression(Collections.singletonList(token).iterator(),
|
||||
baseOrigin.withLineNumber(lineNumber));
|
||||
} else {
|
||||
throw parseError("Expecting close brace } or a field name here, got "
|
||||
+ token);
|
||||
}
|
||||
} else {
|
||||
List<Token> expression = new ArrayList<Token>();
|
||||
Token t = token;
|
||||
while (Tokens.isValue(t) || Tokens.isUnquotedText(t)) {
|
||||
expression.add(t);
|
||||
t = nextToken(); // note: don't cross a newline
|
||||
}
|
||||
|
||||
if (expression.isEmpty()) {
|
||||
throw parseError(ExpectingClosingParenthesisError + t);
|
||||
}
|
||||
|
||||
putBack(t); // put back the token we ended with
|
||||
return PathParser.parsePathNodeExpression(expression.iterator(),
|
||||
baseOrigin.withLineNumber(lineNumber));
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isIncludeKeyword(Token t) {
|
||||
return Tokens.isUnquotedText(t)
|
||||
&& Tokens.getUnquotedText(t).equals("include");
|
||||
}
|
||||
|
||||
private static boolean isUnquotedWhitespace(Token t) {
|
||||
if (!Tokens.isUnquotedText(t))
|
||||
return false;
|
||||
|
||||
String s = Tokens.getUnquotedText(t);
|
||||
|
||||
for (int i = 0; i < s.length(); ++i) {
|
||||
char c = s.charAt(i);
|
||||
if (!ConfigImplUtil.isWhitespace(c))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean isKeyValueSeparatorToken(Token t) {
|
||||
if (flavor == ConfigSyntax.JSON) {
|
||||
return t == Tokens.COLON;
|
||||
} else {
|
||||
return t == Tokens.COLON || t == Tokens.EQUALS || t == Tokens.PLUS_EQUALS;
|
||||
}
|
||||
}
|
||||
|
||||
private final String ExpectingClosingParenthesisError = "expecting a close parentheses ')' here, not: ";
|
||||
|
||||
private ConfigNodeInclude parseInclude(ArrayList<AbstractConfigNode> children) {
|
||||
|
||||
Token t = nextTokenCollectingWhitespace(children);
|
||||
|
||||
// we either have a 'required()' or a quoted string or the "file()" syntax
|
||||
if (Tokens.isUnquotedText(t)) {
|
||||
String kindText = Tokens.getUnquotedText(t);
|
||||
|
||||
if (kindText.startsWith("required(")) {
|
||||
String r = kindText.replaceFirst("required\\(","");
|
||||
if (r.length()>0) {
|
||||
putBack(Tokens.newUnquotedText(t.origin(),r));
|
||||
}
|
||||
|
||||
children.add(new ConfigNodeSingleToken(t));
|
||||
//children.add(new ConfigNodeSingleToken(tOpen));
|
||||
|
||||
ConfigNodeInclude res = parseIncludeResource(children, true);
|
||||
|
||||
t = nextTokenCollectingWhitespace(children);
|
||||
|
||||
if (Tokens.isUnquotedText(t) && Tokens.getUnquotedText(t).equals(")")) {
|
||||
// OK, close paren
|
||||
} else {
|
||||
throw parseError(ExpectingClosingParenthesisError + t);
|
||||
}
|
||||
|
||||
return res;
|
||||
} else {
|
||||
putBack(t);
|
||||
return parseIncludeResource(children, false);
|
||||
}
|
||||
}
|
||||
else {
|
||||
putBack(t);
|
||||
return parseIncludeResource(children, false);
|
||||
}
|
||||
}
|
||||
|
||||
private ConfigNodeInclude parseIncludeResource(ArrayList<AbstractConfigNode> children, boolean isRequired) {
|
||||
Token t = nextTokenCollectingWhitespace(children);
|
||||
|
||||
// we either have a quoted string or the "file()" syntax
|
||||
if (Tokens.isUnquotedText(t)) {
|
||||
// get foo(
|
||||
String kindText = Tokens.getUnquotedText(t);
|
||||
ConfigIncludeKind kind;
|
||||
String prefix;
|
||||
|
||||
if (kindText.startsWith("url(")) {
|
||||
kind = ConfigIncludeKind.URL;
|
||||
prefix = "url(";
|
||||
} else if (kindText.startsWith("file(")) {
|
||||
kind = ConfigIncludeKind.FILE;
|
||||
prefix = "file(";
|
||||
} else if (kindText.startsWith("classpath(")) {
|
||||
kind = ConfigIncludeKind.CLASSPATH;
|
||||
prefix = "classpath(";
|
||||
} else {
|
||||
throw parseError("expecting include parameter to be quoted filename, file(), classpath(), or url(). No spaces are allowed before the open paren. Not expecting: "
|
||||
+ t);
|
||||
}
|
||||
String r = kindText.replaceFirst("[^(]*\\(","");
|
||||
if (r.length()>0) {
|
||||
putBack(Tokens.newUnquotedText(t.origin(),r));
|
||||
}
|
||||
|
||||
children.add(new ConfigNodeSingleToken(t));
|
||||
|
||||
// skip space inside parens
|
||||
t = nextTokenCollectingWhitespace(children);
|
||||
|
||||
// quoted string
|
||||
if (!Tokens.isValueWithType(t, ConfigValueType.STRING)) {
|
||||
throw parseError("expecting include " + prefix + ") parameter to be a quoted string, rather than: " + t);
|
||||
}
|
||||
children.add(new ConfigNodeSimpleValue(t));
|
||||
// skip space after string, inside parens
|
||||
t = nextTokenCollectingWhitespace(children);
|
||||
|
||||
if (Tokens.isUnquotedText(t) && Tokens.getUnquotedText(t).startsWith(")")) {
|
||||
String rest = Tokens.getUnquotedText(t).substring(1);
|
||||
if (rest.length()>0) {
|
||||
putBack(Tokens.newUnquotedText(t.origin(),rest));
|
||||
}
|
||||
// OK, close paren
|
||||
} else {
|
||||
throw parseError(ExpectingClosingParenthesisError + t);
|
||||
}
|
||||
|
||||
return new ConfigNodeInclude(children, kind, isRequired);
|
||||
} else if (Tokens.isValueWithType(t, ConfigValueType.STRING)) {
|
||||
children.add(new ConfigNodeSimpleValue(t));
|
||||
return new ConfigNodeInclude(children, ConfigIncludeKind.HEURISTIC, isRequired);
|
||||
} else {
|
||||
throw parseError("include keyword is not followed by a quoted string, but by: " + t);
|
||||
}
|
||||
}
|
||||
|
||||
private ConfigNodeComplexValue parseObject(boolean hadOpenCurly) {
|
||||
// invoked just after the OPEN_CURLY (or START, if !hadOpenCurly)
|
||||
boolean afterComma = false;
|
||||
Path lastPath = null;
|
||||
boolean lastInsideEquals = false;
|
||||
ArrayList<AbstractConfigNode> objectNodes = new ArrayList<AbstractConfigNode>();
|
||||
ArrayList<AbstractConfigNode> keyValueNodes;
|
||||
HashMap<String, Boolean> keys = new HashMap<String, Boolean>();
|
||||
if (hadOpenCurly)
|
||||
objectNodes.add(new ConfigNodeSingleToken(Tokens.OPEN_CURLY));
|
||||
|
||||
while (true) {
|
||||
Token t = nextTokenCollectingWhitespace(objectNodes);
|
||||
if (t == Tokens.CLOSE_CURLY) {
|
||||
if (flavor == ConfigSyntax.JSON && afterComma) {
|
||||
throw parseError(addQuoteSuggestion(t.toString(),
|
||||
"expecting a field name after a comma, got a close brace } instead"));
|
||||
} else if (!hadOpenCurly) {
|
||||
throw parseError(addQuoteSuggestion(t.toString(),
|
||||
"unbalanced close brace '}' with no open brace"));
|
||||
}
|
||||
objectNodes.add(new ConfigNodeSingleToken(Tokens.CLOSE_CURLY));
|
||||
break;
|
||||
} else if (t == Tokens.END && !hadOpenCurly) {
|
||||
putBack(t);
|
||||
break;
|
||||
} else if (flavor != ConfigSyntax.JSON && isIncludeKeyword(t)) {
|
||||
ArrayList<AbstractConfigNode> includeNodes = new ArrayList<AbstractConfigNode>();
|
||||
includeNodes.add(new ConfigNodeSingleToken(t));
|
||||
objectNodes.add(parseInclude(includeNodes));
|
||||
afterComma = false;
|
||||
} else {
|
||||
keyValueNodes = new ArrayList<AbstractConfigNode>();
|
||||
Token keyToken = t;
|
||||
ConfigNodePath path = parseKey(keyToken);
|
||||
keyValueNodes.add(path);
|
||||
Token afterKey = nextTokenCollectingWhitespace(keyValueNodes);
|
||||
boolean insideEquals = false;
|
||||
|
||||
AbstractConfigNodeValue nextValue;
|
||||
if (flavor == ConfigSyntax.CONF && afterKey == Tokens.OPEN_CURLY) {
|
||||
// can omit the ':' or '=' before an object value
|
||||
nextValue = parseValue(afterKey);
|
||||
} else {
|
||||
if (!isKeyValueSeparatorToken(afterKey)) {
|
||||
throw parseError(addQuoteSuggestion(afterKey.toString(),
|
||||
"Key '" + path.render() + "' may not be followed by token: "
|
||||
+ afterKey));
|
||||
}
|
||||
|
||||
keyValueNodes.add(new ConfigNodeSingleToken(afterKey));
|
||||
|
||||
if (afterKey == Tokens.EQUALS) {
|
||||
insideEquals = true;
|
||||
equalsCount += 1;
|
||||
}
|
||||
|
||||
nextValue = consolidateValues(keyValueNodes);
|
||||
if (nextValue == null) {
|
||||
nextValue = parseValue(nextTokenCollectingWhitespace(keyValueNodes));
|
||||
}
|
||||
}
|
||||
|
||||
keyValueNodes.add(nextValue);
|
||||
if (insideEquals) {
|
||||
equalsCount -= 1;
|
||||
}
|
||||
lastInsideEquals = insideEquals;
|
||||
|
||||
String key = path.value().first();
|
||||
Path remaining = path.value().remainder();
|
||||
|
||||
if (remaining == null) {
|
||||
Boolean existing = keys.get(key);
|
||||
if (existing != null) {
|
||||
// In strict JSON, dups should be an error; while in
|
||||
// our custom config language, they should be merged
|
||||
// if the value is an object (or substitution that
|
||||
// could become an object).
|
||||
|
||||
if (flavor == ConfigSyntax.JSON) {
|
||||
throw parseError("JSON does not allow duplicate fields: '"
|
||||
+ key
|
||||
+ "' was already seen");
|
||||
}
|
||||
}
|
||||
keys.put(key, true);
|
||||
} else {
|
||||
if (flavor == ConfigSyntax.JSON) {
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"somehow got multi-element path in JSON mode");
|
||||
}
|
||||
keys.put(key, true);
|
||||
}
|
||||
|
||||
afterComma = false;
|
||||
objectNodes.add(new ConfigNodeField(keyValueNodes));
|
||||
}
|
||||
|
||||
if (checkElementSeparator(objectNodes)) {
|
||||
// continue looping
|
||||
afterComma = true;
|
||||
} else {
|
||||
t = nextTokenCollectingWhitespace(objectNodes);
|
||||
if (t == Tokens.CLOSE_CURLY) {
|
||||
if (!hadOpenCurly) {
|
||||
throw parseError(addQuoteSuggestion(lastPath, lastInsideEquals,
|
||||
t.toString(), "unbalanced close brace '}' with no open brace"));
|
||||
}
|
||||
objectNodes.add(new ConfigNodeSingleToken(t));
|
||||
break;
|
||||
} else if (hadOpenCurly) {
|
||||
throw parseError(addQuoteSuggestion(lastPath, lastInsideEquals,
|
||||
t.toString(), "Expecting close brace } or a comma, got " + t));
|
||||
} else {
|
||||
if (t == Tokens.END) {
|
||||
putBack(t);
|
||||
break;
|
||||
} else {
|
||||
throw parseError(addQuoteSuggestion(lastPath, lastInsideEquals,
|
||||
t.toString(), "Expecting end of input or a comma, got " + t));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new ConfigNodeObject(objectNodes);
|
||||
}
|
||||
|
||||
private ConfigNodeComplexValue parseArray() {
|
||||
ArrayList<AbstractConfigNode> children = new ArrayList<AbstractConfigNode>();
|
||||
children.add(new ConfigNodeSingleToken(Tokens.OPEN_SQUARE));
|
||||
// invoked just after the OPEN_SQUARE
|
||||
Token t;
|
||||
|
||||
AbstractConfigNodeValue nextValue = consolidateValues(children);
|
||||
if (nextValue != null) {
|
||||
children.add(nextValue);
|
||||
} else {
|
||||
t = nextTokenCollectingWhitespace(children);
|
||||
|
||||
// special-case the first element
|
||||
if (t == Tokens.CLOSE_SQUARE) {
|
||||
children.add(new ConfigNodeSingleToken(t));
|
||||
return new ConfigNodeArray(children);
|
||||
} else if (Tokens.isValue(t) || t == Tokens.OPEN_CURLY
|
||||
|| t == Tokens.OPEN_SQUARE || Tokens.isUnquotedText(t)
|
||||
|| Tokens.isSubstitution(t)) {
|
||||
nextValue = parseValue(t);
|
||||
children.add(nextValue);
|
||||
} else {
|
||||
throw parseError("List should have ] or a first element after the open [, instead had token: "
|
||||
+ t
|
||||
+ " (if you want "
|
||||
+ t
|
||||
+ " to be part of a string value, then double-quote it)");
|
||||
}
|
||||
}
|
||||
|
||||
// now remaining elements
|
||||
while (true) {
|
||||
// just after a value
|
||||
if (checkElementSeparator(children)) {
|
||||
// comma (or newline equivalent) consumed
|
||||
} else {
|
||||
t = nextTokenCollectingWhitespace(children);
|
||||
if (t == Tokens.CLOSE_SQUARE) {
|
||||
children.add(new ConfigNodeSingleToken(t));
|
||||
return new ConfigNodeArray(children);
|
||||
} else {
|
||||
throw parseError("List should have ended with ] or had a comma, instead had token: "
|
||||
+ t
|
||||
+ " (if you want "
|
||||
+ t
|
||||
+ " to be part of a string value, then double-quote it)");
|
||||
}
|
||||
}
|
||||
|
||||
// now just after a comma
|
||||
nextValue = consolidateValues(children);
|
||||
if (nextValue != null) {
|
||||
children.add(nextValue);
|
||||
} else {
|
||||
t = nextTokenCollectingWhitespace(children);
|
||||
if (Tokens.isValue(t) || t == Tokens.OPEN_CURLY
|
||||
|| t == Tokens.OPEN_SQUARE || Tokens.isUnquotedText(t)
|
||||
|| Tokens.isSubstitution(t)) {
|
||||
nextValue = parseValue(t);
|
||||
children.add(nextValue);
|
||||
} else if (flavor != ConfigSyntax.JSON && t == Tokens.CLOSE_SQUARE) {
|
||||
// we allow one trailing comma
|
||||
putBack(t);
|
||||
} else {
|
||||
throw parseError("List should have had new element after a comma, instead had token: "
|
||||
+ t
|
||||
+ " (if you want the comma or "
|
||||
+ t
|
||||
+ " to be part of a string value, then double-quote it)");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ConfigNodeRoot parse() {
|
||||
ArrayList<AbstractConfigNode> children = new ArrayList<AbstractConfigNode>();
|
||||
Token t = nextToken();
|
||||
if (t == Tokens.START) {
|
||||
// OK
|
||||
} else {
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"token stream did not begin with START, had " + t);
|
||||
}
|
||||
|
||||
t = nextTokenCollectingWhitespace(children);
|
||||
AbstractConfigNode result = null;
|
||||
boolean missingCurly = false;
|
||||
if (t == Tokens.OPEN_CURLY || t == Tokens.OPEN_SQUARE) {
|
||||
result = parseValue(t);
|
||||
} else {
|
||||
if (flavor == ConfigSyntax.JSON) {
|
||||
if (t == Tokens.END) {
|
||||
throw parseError("Empty document");
|
||||
} else {
|
||||
throw parseError("Document must have an object or array at root, unexpected token: "
|
||||
+ t);
|
||||
}
|
||||
} else {
|
||||
// the root object can omit the surrounding braces.
|
||||
// this token should be the first field's key, or part
|
||||
// of it, so put it back.
|
||||
putBack(t);
|
||||
missingCurly = true;
|
||||
result = parseObject(false);
|
||||
}
|
||||
}
|
||||
// Need to pull the children out of the resulting node so we can keep leading
|
||||
// and trailing whitespace if this was a no-brace object. Otherwise, we need to add
|
||||
// the result into the list of children.
|
||||
if (result instanceof ConfigNodeObject && missingCurly) {
|
||||
children.addAll(((ConfigNodeComplexValue) result).children());
|
||||
} else {
|
||||
children.add(result);
|
||||
}
|
||||
t = nextTokenCollectingWhitespace(children);
|
||||
if (t == Tokens.END) {
|
||||
if (missingCurly) {
|
||||
// If there were no braces, the entire document should be treated as a single object
|
||||
return new ConfigNodeRoot(Collections.singletonList((AbstractConfigNode)new ConfigNodeObject(children)), baseOrigin);
|
||||
} else {
|
||||
return new ConfigNodeRoot(children, baseOrigin);
|
||||
}
|
||||
} else {
|
||||
throw parseError("Document has trailing tokens after first object or array: "
|
||||
+ t);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse a given input stream into a single value node. Used when doing a replace inside a ConfigDocument.
|
||||
AbstractConfigNodeValue parseSingleValue() {
|
||||
Token t = nextToken();
|
||||
if (t == Tokens.START) {
|
||||
// OK
|
||||
} else {
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"token stream did not begin with START, had " + t);
|
||||
}
|
||||
|
||||
t = nextToken();
|
||||
if (Tokens.isIgnoredWhitespace(t) || Tokens.isNewline(t) || isUnquotedWhitespace(t) || Tokens.isComment(t)) {
|
||||
throw parseError("The value from withValueText cannot have leading or trailing newlines, whitespace, or comments");
|
||||
}
|
||||
if (t == Tokens.END) {
|
||||
throw parseError("Empty value");
|
||||
}
|
||||
if (flavor == ConfigSyntax.JSON) {
|
||||
AbstractConfigNodeValue node = parseValue(t);
|
||||
t = nextToken();
|
||||
if (t == Tokens.END) {
|
||||
return node;
|
||||
} else {
|
||||
throw parseError("Parsing JSON and the value set in withValueText was either a concatenation or " +
|
||||
"had trailing whitespace, newlines, or comments");
|
||||
}
|
||||
} else {
|
||||
putBack(t);
|
||||
ArrayList<AbstractConfigNode> nodes = new ArrayList<AbstractConfigNode>();
|
||||
AbstractConfigNodeValue node = consolidateValues(nodes);
|
||||
t = nextToken();
|
||||
if (t == Tokens.END) {
|
||||
return node;
|
||||
} else {
|
||||
throw parseError("The value from withValueText cannot have leading or trailing newlines, whitespace, or comments");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.io.ObjectStreamException;
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType;
|
||||
|
||||
final class ConfigDouble extends ConfigNumber implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 2L;
|
||||
|
||||
final private double value;
|
||||
|
||||
ConfigDouble(ConfigOrigin origin, double value, String originalText) {
|
||||
super(origin, originalText);
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigValueType valueType() {
|
||||
return ConfigValueType.NUMBER;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Double unwrapped() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
String transformToString() {
|
||||
String s = super.transformToString();
|
||||
if (s == null)
|
||||
return Double.toString(value);
|
||||
else
|
||||
return s;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected long longValue() {
|
||||
return (long) value;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected double doubleValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigDouble newCopy(ConfigOrigin origin) {
|
||||
return new ConfigDouble(origin, value, originalText);
|
||||
}
|
||||
|
||||
// serialization all goes through SerializedConfigValue
|
||||
private Object writeReplace() throws ObjectStreamException {
|
||||
return new SerializedConfigValue(this);
|
||||
}
|
||||
}
|
||||
+477
@@ -0,0 +1,477 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.io.File;
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.net.URL;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.Config;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigIncluder;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigMemorySize;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigObject;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigParseOptions;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigParseable;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.impl.SimpleIncluder.NameSource;
|
||||
|
||||
/**
|
||||
* Internal implementation detail, not ABI stable, do not touch.
|
||||
* For use only by the {@link com.typesafe.config} package.
|
||||
*/
|
||||
public class ConfigImpl {
|
||||
|
||||
private static class LoaderCache {
|
||||
private Config currentSystemProperties;
|
||||
private WeakReference<ClassLoader> currentLoader;
|
||||
private Map<String, Config> cache;
|
||||
|
||||
LoaderCache() {
|
||||
this.currentSystemProperties = null;
|
||||
this.currentLoader = new WeakReference<ClassLoader>(null);
|
||||
this.cache = new HashMap<String, Config>();
|
||||
}
|
||||
|
||||
// for now, caching as long as the loader remains the same,
|
||||
// drop entire cache if it changes.
|
||||
synchronized Config getOrElseUpdate(ClassLoader loader, String key, Callable<Config> updater) {
|
||||
if (loader != currentLoader.get()) {
|
||||
// reset the cache if we start using a different loader
|
||||
cache.clear();
|
||||
currentLoader = new WeakReference<ClassLoader>(loader);
|
||||
}
|
||||
|
||||
Config systemProperties = systemPropertiesAsConfig();
|
||||
if (systemProperties != currentSystemProperties) {
|
||||
cache.clear();
|
||||
currentSystemProperties = systemProperties;
|
||||
}
|
||||
|
||||
Config config = cache.get(key);
|
||||
if (config == null) {
|
||||
try {
|
||||
config = updater.call();
|
||||
} catch (RuntimeException e) {
|
||||
throw e; // this will include ConfigException
|
||||
} catch (Exception e) {
|
||||
throw new ConfigException.Generic(e.getMessage(), e);
|
||||
}
|
||||
if (config == null)
|
||||
throw new ConfigException.BugOrBroken("null config from cache updater");
|
||||
cache.put(key, config);
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
}
|
||||
|
||||
private static class LoaderCacheHolder {
|
||||
static final LoaderCache cache = new LoaderCache();
|
||||
}
|
||||
|
||||
public static Config computeCachedConfig(ClassLoader loader, String key,
|
||||
Callable<Config> updater) {
|
||||
LoaderCache cache;
|
||||
try {
|
||||
cache = LoaderCacheHolder.cache;
|
||||
} catch (ExceptionInInitializerError e) {
|
||||
throw ConfigImplUtil.extractInitializerError(e);
|
||||
}
|
||||
return cache.getOrElseUpdate(loader, key, updater);
|
||||
}
|
||||
|
||||
|
||||
static class FileNameSource implements SimpleIncluder.NameSource {
|
||||
@Override
|
||||
public ConfigParseable nameToParseable(String name, ConfigParseOptions parseOptions) {
|
||||
return Parseable.newFile(new File(name), parseOptions);
|
||||
}
|
||||
};
|
||||
|
||||
static class ClasspathNameSource implements SimpleIncluder.NameSource {
|
||||
@Override
|
||||
public ConfigParseable nameToParseable(String name, ConfigParseOptions parseOptions) {
|
||||
return Parseable.newResources(name, parseOptions);
|
||||
}
|
||||
};
|
||||
|
||||
static class ClasspathNameSourceWithClass implements SimpleIncluder.NameSource {
|
||||
final private Class<?> klass;
|
||||
|
||||
public ClasspathNameSourceWithClass(Class<?> klass) {
|
||||
this.klass = klass;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigParseable nameToParseable(String name, ConfigParseOptions parseOptions) {
|
||||
return Parseable.newResources(klass, name, parseOptions);
|
||||
}
|
||||
};
|
||||
|
||||
public static ConfigObject parseResourcesAnySyntax(Class<?> klass, String resourceBasename,
|
||||
ConfigParseOptions baseOptions) {
|
||||
NameSource source = new ClasspathNameSourceWithClass(klass);
|
||||
return SimpleIncluder.fromBasename(source, resourceBasename, baseOptions);
|
||||
}
|
||||
|
||||
public static ConfigObject parseResourcesAnySyntax(String resourceBasename,
|
||||
ConfigParseOptions baseOptions) {
|
||||
NameSource source = new ClasspathNameSource();
|
||||
return SimpleIncluder.fromBasename(source, resourceBasename, baseOptions);
|
||||
}
|
||||
|
||||
public static ConfigObject parseFileAnySyntax(File basename, ConfigParseOptions baseOptions) {
|
||||
NameSource source = new FileNameSource();
|
||||
return SimpleIncluder.fromBasename(source, basename.getPath(), baseOptions);
|
||||
}
|
||||
|
||||
static AbstractConfigObject emptyObject(String originDescription) {
|
||||
ConfigOrigin origin = originDescription != null ? SimpleConfigOrigin
|
||||
.newSimple(originDescription) : null;
|
||||
return emptyObject(origin);
|
||||
}
|
||||
|
||||
public static Config emptyConfig(String originDescription) {
|
||||
return emptyObject(originDescription).toConfig();
|
||||
}
|
||||
|
||||
static AbstractConfigObject empty(ConfigOrigin origin) {
|
||||
return emptyObject(origin);
|
||||
}
|
||||
|
||||
// default origin for values created with fromAnyRef and no origin specified
|
||||
final private static ConfigOrigin defaultValueOrigin = SimpleConfigOrigin
|
||||
.newSimple("hardcoded value");
|
||||
final private static ConfigBoolean defaultTrueValue = new ConfigBoolean(
|
||||
defaultValueOrigin, true);
|
||||
final private static ConfigBoolean defaultFalseValue = new ConfigBoolean(
|
||||
defaultValueOrigin, false);
|
||||
final private static ConfigNull defaultNullValue = new ConfigNull(
|
||||
defaultValueOrigin);
|
||||
final private static SimpleConfigList defaultEmptyList = new SimpleConfigList(
|
||||
defaultValueOrigin, Collections.<AbstractConfigValue> emptyList());
|
||||
final private static SimpleConfigObject defaultEmptyObject = SimpleConfigObject
|
||||
.empty(defaultValueOrigin);
|
||||
|
||||
private static SimpleConfigList emptyList(ConfigOrigin origin) {
|
||||
if (origin == null || origin == defaultValueOrigin)
|
||||
return defaultEmptyList;
|
||||
else
|
||||
return new SimpleConfigList(origin,
|
||||
Collections.<AbstractConfigValue> emptyList());
|
||||
}
|
||||
|
||||
private static AbstractConfigObject emptyObject(ConfigOrigin origin) {
|
||||
// we want null origin to go to SimpleConfigObject.empty() to get the
|
||||
// origin "empty config" rather than "hardcoded value"
|
||||
if (origin == defaultValueOrigin)
|
||||
return defaultEmptyObject;
|
||||
else
|
||||
return SimpleConfigObject.empty(origin);
|
||||
}
|
||||
|
||||
private static ConfigOrigin valueOrigin(String originDescription) {
|
||||
if (originDescription == null)
|
||||
return defaultValueOrigin;
|
||||
else
|
||||
return SimpleConfigOrigin.newSimple(originDescription);
|
||||
}
|
||||
|
||||
public static ConfigValue fromAnyRef(Object object, String originDescription) {
|
||||
ConfigOrigin origin = valueOrigin(originDescription);
|
||||
return fromAnyRef(object, origin, FromMapMode.KEYS_ARE_KEYS);
|
||||
}
|
||||
|
||||
public static ConfigObject fromPathMap(
|
||||
Map<String, ? extends Object> pathMap, String originDescription) {
|
||||
ConfigOrigin origin = valueOrigin(originDescription);
|
||||
return (ConfigObject) fromAnyRef(pathMap, origin,
|
||||
FromMapMode.KEYS_ARE_PATHS);
|
||||
}
|
||||
|
||||
static AbstractConfigValue fromAnyRef(Object object, ConfigOrigin origin,
|
||||
FromMapMode mapMode) {
|
||||
if (origin == null)
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"origin not supposed to be null");
|
||||
|
||||
if (object == null) {
|
||||
if (origin != defaultValueOrigin)
|
||||
return new ConfigNull(origin);
|
||||
else
|
||||
return defaultNullValue;
|
||||
} else if(object instanceof AbstractConfigValue) {
|
||||
return (AbstractConfigValue) object;
|
||||
} else if (object instanceof Boolean) {
|
||||
if (origin != defaultValueOrigin) {
|
||||
return new ConfigBoolean(origin, (Boolean) object);
|
||||
} else if ((Boolean) object) {
|
||||
return defaultTrueValue;
|
||||
} else {
|
||||
return defaultFalseValue;
|
||||
}
|
||||
} else if (object instanceof String) {
|
||||
return new ConfigString.Quoted(origin, (String) object);
|
||||
} else if (object instanceof Number) {
|
||||
// here we always keep the same type that was passed to us,
|
||||
// rather than figuring out if a Long would fit in an Int
|
||||
// or a Double has no fractional part. i.e. deliberately
|
||||
// not using ConfigNumber.newNumber() when we have a
|
||||
// Double, Integer, or Long.
|
||||
if (object instanceof Double) {
|
||||
return new ConfigDouble(origin, (Double) object, null);
|
||||
} else if (object instanceof Integer) {
|
||||
return new ConfigInt(origin, (Integer) object, null);
|
||||
} else if (object instanceof Long) {
|
||||
return new ConfigLong(origin, (Long) object, null);
|
||||
} else {
|
||||
return ConfigNumber.newNumber(origin,
|
||||
((Number) object).doubleValue(), null);
|
||||
}
|
||||
} else if (object instanceof Duration) {
|
||||
return new ConfigLong(origin, ((Duration) object).toMillis(), null);
|
||||
} else if (object instanceof Map) {
|
||||
if (((Map<?, ?>) object).isEmpty())
|
||||
return emptyObject(origin);
|
||||
|
||||
if (mapMode == FromMapMode.KEYS_ARE_KEYS) {
|
||||
Map<String, AbstractConfigValue> values = new HashMap<String, AbstractConfigValue>();
|
||||
for (Map.Entry<?, ?> entry : ((Map<?, ?>) object).entrySet()) {
|
||||
Object key = entry.getKey();
|
||||
if (!(key instanceof String))
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"bug in method caller: not valid to create ConfigObject from map with non-String key: "
|
||||
+ key);
|
||||
AbstractConfigValue value = fromAnyRef(entry.getValue(),
|
||||
origin, mapMode);
|
||||
values.put((String) key, value);
|
||||
}
|
||||
|
||||
return new SimpleConfigObject(origin, values);
|
||||
} else {
|
||||
return PropertiesParser.fromPathMap(origin, (Map<?, ?>) object);
|
||||
}
|
||||
} else if (object instanceof Iterable) {
|
||||
Iterator<?> i = ((Iterable<?>) object).iterator();
|
||||
if (!i.hasNext())
|
||||
return emptyList(origin);
|
||||
|
||||
List<AbstractConfigValue> values = new ArrayList<AbstractConfigValue>();
|
||||
while (i.hasNext()) {
|
||||
AbstractConfigValue v = fromAnyRef(i.next(), origin, mapMode);
|
||||
values.add(v);
|
||||
}
|
||||
|
||||
return new SimpleConfigList(origin, values);
|
||||
} else if (object instanceof ConfigMemorySize) {
|
||||
return new ConfigLong(origin, ((ConfigMemorySize) object).toBytes(), null);
|
||||
} else {
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"bug in method caller: not valid to create ConfigValue from: "
|
||||
+ object);
|
||||
}
|
||||
}
|
||||
|
||||
private static class DefaultIncluderHolder {
|
||||
static final ConfigIncluder defaultIncluder = new SimpleIncluder(null);
|
||||
}
|
||||
|
||||
static ConfigIncluder defaultIncluder() {
|
||||
try {
|
||||
return DefaultIncluderHolder.defaultIncluder;
|
||||
} catch (ExceptionInInitializerError e) {
|
||||
throw ConfigImplUtil.extractInitializerError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static Properties getSystemProperties() {
|
||||
// Avoid ConcurrentModificationException due to parallel setting of system properties by copying properties
|
||||
final Properties systemProperties = System.getProperties();
|
||||
final Properties systemPropertiesCopy = new Properties();
|
||||
synchronized (systemProperties) {
|
||||
systemPropertiesCopy.putAll(systemProperties);
|
||||
}
|
||||
return systemPropertiesCopy;
|
||||
}
|
||||
|
||||
private static AbstractConfigObject loadSystemProperties() {
|
||||
return (AbstractConfigObject) Parseable.newProperties(getSystemProperties(),
|
||||
ConfigParseOptions.defaults().setOriginDescription("system properties")).parse();
|
||||
}
|
||||
|
||||
private static class SystemPropertiesHolder {
|
||||
// this isn't final due to the reloadSystemPropertiesConfig() hack below
|
||||
static volatile AbstractConfigObject systemProperties = loadSystemProperties();
|
||||
}
|
||||
|
||||
static AbstractConfigObject systemPropertiesAsConfigObject() {
|
||||
try {
|
||||
return SystemPropertiesHolder.systemProperties;
|
||||
} catch (ExceptionInInitializerError e) {
|
||||
throw ConfigImplUtil.extractInitializerError(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static Config systemPropertiesAsConfig() {
|
||||
return systemPropertiesAsConfigObject().toConfig();
|
||||
}
|
||||
|
||||
public static void reloadSystemPropertiesConfig() {
|
||||
// ConfigFactory.invalidateCaches() relies on this having the side
|
||||
// effect that it drops all caches
|
||||
SystemPropertiesHolder.systemProperties = loadSystemProperties();
|
||||
}
|
||||
|
||||
private static AbstractConfigObject loadEnvVariables() {
|
||||
return PropertiesParser.fromStringMap(newSimpleOrigin("env variables"), System.getenv());
|
||||
}
|
||||
|
||||
private static class EnvVariablesHolder {
|
||||
static volatile AbstractConfigObject envVariables = loadEnvVariables();
|
||||
}
|
||||
|
||||
static AbstractConfigObject envVariablesAsConfigObject() {
|
||||
try {
|
||||
return EnvVariablesHolder.envVariables;
|
||||
} catch (ExceptionInInitializerError e) {
|
||||
throw ConfigImplUtil.extractInitializerError(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static Config envVariablesAsConfig() {
|
||||
return envVariablesAsConfigObject().toConfig();
|
||||
}
|
||||
|
||||
public static void reloadEnvVariablesConfig() {
|
||||
// ConfigFactory.invalidateCaches() relies on this having the side
|
||||
// effect that it drops all caches
|
||||
EnvVariablesHolder.envVariables = loadEnvVariables();
|
||||
}
|
||||
|
||||
public static Config defaultReference(final ClassLoader loader) {
|
||||
return computeCachedConfig(loader, "defaultReference", new Callable<Config>() {
|
||||
@Override
|
||||
public Config call() {
|
||||
Config unresolvedResources = Parseable
|
||||
.newResources("reference.conf",
|
||||
ConfigParseOptions.defaults().setClassLoader(loader))
|
||||
.parse().toConfig();
|
||||
return systemPropertiesAsConfig().withFallback(unresolvedResources).resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static class DebugHolder {
|
||||
private static String LOADS = "loads";
|
||||
private static String SUBSTITUTIONS = "substitutions";
|
||||
|
||||
private static Map<String, Boolean> loadDiagnostics() {
|
||||
Map<String, Boolean> result = new HashMap<String, Boolean>();
|
||||
result.put(LOADS, false);
|
||||
result.put(SUBSTITUTIONS, false);
|
||||
|
||||
// People do -Dconfig.trace=foo,bar to enable tracing of different things
|
||||
String s = System.getProperty("config.trace");
|
||||
if (s == null) {
|
||||
return result;
|
||||
} else {
|
||||
String[] keys = s.split(",");
|
||||
for (String k : keys) {
|
||||
if (k.equals(LOADS)) {
|
||||
result.put(LOADS, true);
|
||||
} else if (k.equals(SUBSTITUTIONS)) {
|
||||
result.put(SUBSTITUTIONS, true);
|
||||
} else {
|
||||
System.err.println("config.trace property contains unknown trace topic '"
|
||||
+ k + "'");
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private static final Map<String, Boolean> diagnostics = loadDiagnostics();
|
||||
|
||||
private static final boolean traceLoadsEnabled = diagnostics.get(LOADS);
|
||||
private static final boolean traceSubstitutionsEnabled = diagnostics.get(SUBSTITUTIONS);
|
||||
|
||||
static boolean traceLoadsEnabled() {
|
||||
return traceLoadsEnabled;
|
||||
}
|
||||
|
||||
static boolean traceSubstitutionsEnabled() {
|
||||
return traceSubstitutionsEnabled;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean traceLoadsEnabled() {
|
||||
try {
|
||||
return DebugHolder.traceLoadsEnabled();
|
||||
} catch (ExceptionInInitializerError e) {
|
||||
throw ConfigImplUtil.extractInitializerError(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean traceSubstitutionsEnabled() {
|
||||
try {
|
||||
return DebugHolder.traceSubstitutionsEnabled();
|
||||
} catch (ExceptionInInitializerError e) {
|
||||
throw ConfigImplUtil.extractInitializerError(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void trace(String message) {
|
||||
System.err.println(message);
|
||||
}
|
||||
|
||||
public static void trace(int indentLevel, String message) {
|
||||
while (indentLevel > 0) {
|
||||
System.err.print(" ");
|
||||
indentLevel -= 1;
|
||||
}
|
||||
System.err.println(message);
|
||||
}
|
||||
|
||||
// the basic idea here is to add the "what" and have a canonical
|
||||
// toplevel error message. the "original" exception may however have extra
|
||||
// detail about what happened. call this if you have a better "what" than
|
||||
// further down on the stack.
|
||||
static ConfigException.NotResolved improveNotResolved(Path what,
|
||||
ConfigException.NotResolved original) {
|
||||
String newMessage = what.render()
|
||||
+ " has not been resolved, you need to call Config#resolve(),"
|
||||
+ " see API docs for Config#resolve()";
|
||||
if (newMessage.equals(original.getMessage()))
|
||||
return original;
|
||||
else
|
||||
return new ConfigException.NotResolved(newMessage, original);
|
||||
}
|
||||
|
||||
public static ConfigOrigin newSimpleOrigin(String description) {
|
||||
if (description == null) {
|
||||
return defaultValueOrigin;
|
||||
} else {
|
||||
return SimpleConfigOrigin.newSimple(description);
|
||||
}
|
||||
}
|
||||
|
||||
public static ConfigOrigin newFileOrigin(String filename) {
|
||||
return SimpleConfigOrigin.newFile(filename);
|
||||
}
|
||||
|
||||
public static ConfigOrigin newURLOrigin(URL url) {
|
||||
return SimpleConfigOrigin.newURL(url);
|
||||
}
|
||||
}
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin;
|
||||
|
||||
/**
|
||||
* Internal implementation detail, not ABI stable, do not touch.
|
||||
* For use only by the {@link com.typesafe.config} package.
|
||||
*/
|
||||
final public class ConfigImplUtil {
|
||||
static boolean equalsHandlingNull(Object a, Object b) {
|
||||
if (a == null && b != null)
|
||||
return false;
|
||||
else if (a != null && b == null)
|
||||
return false;
|
||||
else if (a == b) // catches null == null plus optimizes identity case
|
||||
return true;
|
||||
else
|
||||
return a.equals(b);
|
||||
}
|
||||
|
||||
static boolean isC0Control(int codepoint) {
|
||||
return (codepoint >= 0x0000 && codepoint <= 0x001F);
|
||||
}
|
||||
|
||||
public static String renderJsonString(String s) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append('"');
|
||||
for (int i = 0; i < s.length(); ++i) {
|
||||
char c = s.charAt(i);
|
||||
switch (c) {
|
||||
case '"':
|
||||
sb.append("\\\"");
|
||||
break;
|
||||
case '\\':
|
||||
sb.append("\\\\");
|
||||
break;
|
||||
case '\n':
|
||||
sb.append("\\n");
|
||||
break;
|
||||
case '\b':
|
||||
sb.append("\\b");
|
||||
break;
|
||||
case '\f':
|
||||
sb.append("\\f");
|
||||
break;
|
||||
case '\r':
|
||||
sb.append("\\r");
|
||||
break;
|
||||
case '\t':
|
||||
sb.append("\\t");
|
||||
break;
|
||||
default:
|
||||
if (isC0Control(c))
|
||||
sb.append(String.format("\\u%04x", (int) c));
|
||||
else
|
||||
sb.append(c);
|
||||
}
|
||||
}
|
||||
sb.append('"');
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
static String renderStringUnquotedIfPossible(String s) {
|
||||
// this can quote unnecessarily as long as it never fails to quote when
|
||||
// necessary
|
||||
if (s.length() == 0)
|
||||
return renderJsonString(s);
|
||||
|
||||
// if it starts with a hyphen or number, we have to quote
|
||||
// to ensure we end up with a string and not a number
|
||||
int first = s.codePointAt(0);
|
||||
if (Character.isDigit(first) || first == '-')
|
||||
return renderJsonString(s);
|
||||
|
||||
if (s.startsWith("include") || s.startsWith("true") || s.startsWith("false")
|
||||
|| s.startsWith("null") || s.contains("//"))
|
||||
return renderJsonString(s);
|
||||
|
||||
// only unquote if it's pure alphanumeric
|
||||
for (int i = 0; i < s.length(); ++i) {
|
||||
char c = s.charAt(i);
|
||||
if (!(Character.isLetter(c) || Character.isDigit(c) || c == '-'))
|
||||
return renderJsonString(s);
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
static boolean isWhitespace(int codepoint) {
|
||||
switch (codepoint) {
|
||||
// try to hit the most common ASCII ones first, then the nonbreaking
|
||||
// spaces that Java brokenly leaves out of isWhitespace.
|
||||
case ' ':
|
||||
case '\n':
|
||||
case '\u00A0':
|
||||
case '\u2007':
|
||||
case '\u202F':
|
||||
// this one is the BOM, see
|
||||
// http://www.unicode.org/faq/utf_bom.html#BOM
|
||||
// we just accept it as a zero-width nonbreaking space.
|
||||
case '\uFEFF':
|
||||
return true;
|
||||
default:
|
||||
return Character.isWhitespace(codepoint);
|
||||
}
|
||||
}
|
||||
|
||||
public static String unicodeTrim(String s) {
|
||||
// this is dumb because it looks like there aren't any whitespace
|
||||
// characters that need surrogate encoding. But, points for
|
||||
// pedantic correctness! It's future-proof or something.
|
||||
// String.trim() actually is broken, since there are plenty of
|
||||
// non-ASCII whitespace characters.
|
||||
final int length = s.length();
|
||||
if (length == 0)
|
||||
return s;
|
||||
|
||||
int start = 0;
|
||||
while (start < length) {
|
||||
char c = s.charAt(start);
|
||||
if (c == ' ' || c == '\n') {
|
||||
start += 1;
|
||||
} else {
|
||||
int cp = s.codePointAt(start);
|
||||
if (isWhitespace(cp))
|
||||
start += Character.charCount(cp);
|
||||
else
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
int end = length;
|
||||
while (end > start) {
|
||||
char c = s.charAt(end - 1);
|
||||
if (c == ' ' || c == '\n') {
|
||||
--end;
|
||||
} else {
|
||||
int cp;
|
||||
int delta;
|
||||
if (Character.isLowSurrogate(c)) {
|
||||
cp = s.codePointAt(end - 2);
|
||||
delta = 2;
|
||||
} else {
|
||||
cp = s.codePointAt(end - 1);
|
||||
delta = 1;
|
||||
}
|
||||
if (isWhitespace(cp))
|
||||
end -= delta;
|
||||
else
|
||||
break;
|
||||
}
|
||||
}
|
||||
return s.substring(start, end);
|
||||
}
|
||||
|
||||
|
||||
public static ConfigException extractInitializerError(ExceptionInInitializerError e) {
|
||||
Throwable cause = e.getCause();
|
||||
if (cause != null && cause instanceof ConfigException) {
|
||||
return (ConfigException) cause;
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
static File urlToFile(URL url) {
|
||||
// this isn't really right, clearly, but not sure what to do.
|
||||
try {
|
||||
// this will properly handle hex escapes, etc.
|
||||
return new File(url.toURI());
|
||||
} catch (URISyntaxException e) {
|
||||
// this handles some stuff like file:///c:/Whatever/
|
||||
// apparently but mangles handling of hex escapes
|
||||
return new File(url.getPath());
|
||||
} catch (IllegalArgumentException e) {
|
||||
// file://foo with double slash causes
|
||||
// IllegalArgumentException "url has an authority component"
|
||||
return new File(url.getPath());
|
||||
}
|
||||
}
|
||||
|
||||
public static String joinPath(String... elements) {
|
||||
return (new Path(elements)).render();
|
||||
}
|
||||
|
||||
public static String joinPath(List<String> elements) {
|
||||
return joinPath(elements.toArray(new String[0]));
|
||||
}
|
||||
|
||||
public static List<String> splitPath(String path) {
|
||||
Path p = Path.newPath(path);
|
||||
List<String> elements = new ArrayList<String>();
|
||||
while (p != null) {
|
||||
elements.add(p.first());
|
||||
p = p.remainder();
|
||||
}
|
||||
return elements;
|
||||
}
|
||||
|
||||
public static ConfigOrigin readOrigin(ObjectInputStream in) throws IOException {
|
||||
return SerializedConfigValue.readOrigin(in, null);
|
||||
}
|
||||
|
||||
public static void writeOrigin(ObjectOutputStream out, ConfigOrigin origin) throws IOException {
|
||||
SerializedConfigValue.writeOrigin(new DataOutputStream(out), (SimpleConfigOrigin) origin,
|
||||
null);
|
||||
}
|
||||
|
||||
static String toCamelCase(String originalName) {
|
||||
String[] words = originalName.split("-+");
|
||||
StringBuilder nameBuilder = new StringBuilder(originalName.length());
|
||||
for (String word : words) {
|
||||
if (nameBuilder.length() == 0) {
|
||||
nameBuilder.append(word);
|
||||
} else {
|
||||
nameBuilder.append(word.substring(0, 1).toUpperCase());
|
||||
nameBuilder.append(word.substring(1));
|
||||
}
|
||||
}
|
||||
return nameBuilder.toString();
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
enum ConfigIncludeKind {
|
||||
URL, FILE, CLASSPATH, HEURISTIC
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.io.ObjectStreamException;
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType;
|
||||
|
||||
final class ConfigInt extends ConfigNumber implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 2L;
|
||||
|
||||
final private int value;
|
||||
|
||||
ConfigInt(ConfigOrigin origin, int value, String originalText) {
|
||||
super(origin, originalText);
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigValueType valueType() {
|
||||
return ConfigValueType.NUMBER;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer unwrapped() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
String transformToString() {
|
||||
String s = super.transformToString();
|
||||
if (s == null)
|
||||
return Integer.toString(value);
|
||||
else
|
||||
return s;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected long longValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected double doubleValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigInt newCopy(ConfigOrigin origin) {
|
||||
return new ConfigInt(origin, value, originalText);
|
||||
}
|
||||
|
||||
// serialization all goes through SerializedConfigValue
|
||||
private Object writeReplace() throws ObjectStreamException {
|
||||
return new SerializedConfigValue(this);
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.io.ObjectStreamException;
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType;
|
||||
|
||||
final class ConfigLong extends ConfigNumber implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 2L;
|
||||
|
||||
final private long value;
|
||||
|
||||
ConfigLong(ConfigOrigin origin, long value, String originalText) {
|
||||
super(origin, originalText);
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigValueType valueType() {
|
||||
return ConfigValueType.NUMBER;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long unwrapped() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
String transformToString() {
|
||||
String s = super.transformToString();
|
||||
if (s == null)
|
||||
return Long.toString(value);
|
||||
else
|
||||
return s;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected long longValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected double doubleValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigLong newCopy(ConfigOrigin origin) {
|
||||
return new ConfigLong(origin, value, originalText);
|
||||
}
|
||||
|
||||
// serialization all goes through SerializedConfigValue
|
||||
private Object writeReplace() throws ObjectStreamException {
|
||||
return new SerializedConfigValue(this);
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
final class ConfigNodeArray extends ConfigNodeComplexValue {
|
||||
ConfigNodeArray(Collection<AbstractConfigNode> children) {
|
||||
super(children);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigNodeArray newNode(Collection<AbstractConfigNode> nodes) {
|
||||
return new ConfigNodeArray(nodes);
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
|
||||
final class ConfigNodeComment extends ConfigNodeSingleToken {
|
||||
ConfigNodeComment(Token comment) {
|
||||
super(comment);
|
||||
if (!Tokens.isComment(super.token)) {
|
||||
throw new ConfigException.BugOrBroken("Tried to create a ConfigNodeComment from a non-comment token");
|
||||
}
|
||||
}
|
||||
|
||||
protected String commentText() {
|
||||
return Tokens.getCommentText(super.token);
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Copyright (C) 2015 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
abstract class ConfigNodeComplexValue extends AbstractConfigNodeValue {
|
||||
final protected ArrayList<AbstractConfigNode> children;
|
||||
|
||||
ConfigNodeComplexValue(Collection<AbstractConfigNode> children) {
|
||||
this.children = new ArrayList<AbstractConfigNode>(children);
|
||||
}
|
||||
|
||||
final public Collection<AbstractConfigNode> children() {
|
||||
return children;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Collection<Token> tokens() {
|
||||
ArrayList<Token> tokens = new ArrayList<Token>();
|
||||
for (AbstractConfigNode child : children) {
|
||||
tokens.addAll(child.tokens());
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
protected ConfigNodeComplexValue indentText(AbstractConfigNode indentation) {
|
||||
ArrayList<AbstractConfigNode> childrenCopy = new ArrayList<AbstractConfigNode>(children);
|
||||
for (int i = 0; i < childrenCopy.size(); i++) {
|
||||
AbstractConfigNode child = childrenCopy.get(i);
|
||||
if (child instanceof ConfigNodeSingleToken &&
|
||||
Tokens.isNewline(((ConfigNodeSingleToken) child).token())) {
|
||||
childrenCopy.add(i + 1, indentation);
|
||||
i++;
|
||||
} else if (child instanceof ConfigNodeField) {
|
||||
AbstractConfigNode value = ((ConfigNodeField) child).value();
|
||||
if (value instanceof ConfigNodeComplexValue) {
|
||||
childrenCopy.set(i, ((ConfigNodeField) child).replaceValue(((ConfigNodeComplexValue) value).indentText(indentation)));
|
||||
}
|
||||
} else if (child instanceof ConfigNodeComplexValue) {
|
||||
childrenCopy.set(i, ((ConfigNodeComplexValue) child).indentText(indentation));
|
||||
}
|
||||
}
|
||||
return newNode(childrenCopy);
|
||||
}
|
||||
|
||||
// This method will just call into the object's constructor, but it's needed
|
||||
// for use in the indentText() method so we can avoid a gross if/else statement
|
||||
// checking the type of this
|
||||
abstract ConfigNodeComplexValue newNode(Collection<AbstractConfigNode> nodes);
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
final class ConfigNodeConcatenation extends ConfigNodeComplexValue {
|
||||
ConfigNodeConcatenation(Collection<AbstractConfigNode> children) {
|
||||
super(children);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigNodeConcatenation newNode(Collection<AbstractConfigNode> nodes) {
|
||||
return new ConfigNodeConcatenation(nodes);
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* Copyright (C) 2015 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
final class ConfigNodeField extends AbstractConfigNode {
|
||||
final private ArrayList<AbstractConfigNode> children;
|
||||
|
||||
public ConfigNodeField(Collection<AbstractConfigNode> children) {
|
||||
this.children = new ArrayList<AbstractConfigNode>(children);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Collection<Token> tokens() {
|
||||
ArrayList<Token> tokens = new ArrayList<Token>();
|
||||
for (AbstractConfigNode child : children) {
|
||||
tokens.addAll(child.tokens());
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
public ConfigNodeField replaceValue(AbstractConfigNodeValue newValue) {
|
||||
ArrayList<AbstractConfigNode> childrenCopy = new ArrayList<AbstractConfigNode>(children);
|
||||
for (int i = 0; i < childrenCopy.size(); i++) {
|
||||
if (childrenCopy.get(i) instanceof AbstractConfigNodeValue) {
|
||||
childrenCopy.set(i, newValue);
|
||||
return new ConfigNodeField(childrenCopy);
|
||||
}
|
||||
}
|
||||
throw new ConfigException.BugOrBroken("Field node doesn't have a value");
|
||||
}
|
||||
|
||||
public AbstractConfigNodeValue value() {
|
||||
for (int i = 0; i < children.size(); i++) {
|
||||
if (children.get(i) instanceof AbstractConfigNodeValue) {
|
||||
return (AbstractConfigNodeValue)children.get(i);
|
||||
}
|
||||
}
|
||||
throw new ConfigException.BugOrBroken("Field node doesn't have a value");
|
||||
}
|
||||
|
||||
public ConfigNodePath path() {
|
||||
for (int i = 0; i < children.size(); i++) {
|
||||
if (children.get(i) instanceof ConfigNodePath) {
|
||||
return (ConfigNodePath)children.get(i);
|
||||
}
|
||||
}
|
||||
throw new ConfigException.BugOrBroken("Field node doesn't have a path");
|
||||
}
|
||||
|
||||
protected Token separator() {
|
||||
for (AbstractConfigNode child : children) {
|
||||
if (child instanceof ConfigNodeSingleToken) {
|
||||
Token t = ((ConfigNodeSingleToken) child).token();
|
||||
if (t == Tokens.PLUS_EQUALS || t == Tokens.COLON || t == Tokens.EQUALS) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
protected List<String> comments() {
|
||||
List<String> comments = new ArrayList<String>();
|
||||
for (AbstractConfigNode child : children) {
|
||||
if (child instanceof ConfigNodeComment) {
|
||||
comments.add(((ConfigNodeComment) child).commentText());
|
||||
}
|
||||
}
|
||||
return comments;
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
|
||||
final class ConfigNodeInclude extends AbstractConfigNode {
|
||||
final private ArrayList<AbstractConfigNode> children;
|
||||
final private ConfigIncludeKind kind;
|
||||
final private boolean isRequired;
|
||||
|
||||
ConfigNodeInclude(Collection<AbstractConfigNode> children, ConfigIncludeKind kind, boolean isRequired) {
|
||||
this.children = new ArrayList<AbstractConfigNode>(children);
|
||||
this.kind = kind;
|
||||
this.isRequired = isRequired;
|
||||
}
|
||||
|
||||
final public Collection<AbstractConfigNode> children() {
|
||||
return children;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Collection<Token> tokens() {
|
||||
ArrayList<Token> tokens = new ArrayList<Token>();
|
||||
for (AbstractConfigNode child : children) {
|
||||
tokens.addAll(child.tokens());
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
protected ConfigIncludeKind kind() {
|
||||
return kind;
|
||||
}
|
||||
|
||||
protected boolean isRequired() {
|
||||
return isRequired;
|
||||
}
|
||||
|
||||
protected String name() {
|
||||
for (AbstractConfigNode n : children) {
|
||||
if (n instanceof ConfigNodeSimpleValue) {
|
||||
return (String)Tokens.getValue(((ConfigNodeSimpleValue) n).token()).unwrapped();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+281
@@ -0,0 +1,281 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigSyntax;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
|
||||
final class ConfigNodeObject extends ConfigNodeComplexValue {
|
||||
ConfigNodeObject(Collection<AbstractConfigNode> children) {
|
||||
super(children);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigNodeObject newNode(Collection<AbstractConfigNode> nodes) {
|
||||
return new ConfigNodeObject(nodes);
|
||||
}
|
||||
|
||||
public boolean hasValue(Path desiredPath) {
|
||||
for (AbstractConfigNode node : children) {
|
||||
if (node instanceof ConfigNodeField) {
|
||||
ConfigNodeField field = (ConfigNodeField) node;
|
||||
Path key = field.path().value();
|
||||
if (key.equals(desiredPath) || key.startsWith(desiredPath)) {
|
||||
return true;
|
||||
} else if (desiredPath.startsWith(key)) {
|
||||
if (field.value() instanceof ConfigNodeObject) {
|
||||
ConfigNodeObject obj = (ConfigNodeObject) field.value();
|
||||
Path remainingPath = desiredPath.subPath(key.length());
|
||||
if (obj.hasValue(remainingPath)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
protected ConfigNodeObject changeValueOnPath(Path desiredPath, AbstractConfigNodeValue value, ConfigSyntax flavor) {
|
||||
ArrayList<AbstractConfigNode> childrenCopy = new ArrayList<AbstractConfigNode>(super.children);
|
||||
boolean seenNonMatching = false;
|
||||
// Copy the value so we can change it to null but not modify the original parameter
|
||||
AbstractConfigNodeValue valueCopy = value;
|
||||
for (int i = childrenCopy.size() - 1; i >= 0; i--) {
|
||||
if (childrenCopy.get(i) instanceof ConfigNodeSingleToken) {
|
||||
Token t = ((ConfigNodeSingleToken) childrenCopy.get(i)).token();
|
||||
// Ensure that, when we are removing settings in JSON, we don't end up with a trailing comma
|
||||
if (flavor == ConfigSyntax.JSON && !seenNonMatching && t == Tokens.COMMA) {
|
||||
childrenCopy.remove(i);
|
||||
}
|
||||
continue;
|
||||
} else if (!(childrenCopy.get(i) instanceof ConfigNodeField)) {
|
||||
continue;
|
||||
}
|
||||
ConfigNodeField node = (ConfigNodeField) childrenCopy.get(i);
|
||||
Path key = node.path().value();
|
||||
|
||||
// Delete all multi-element paths that start with the desired path, since technically they are duplicates
|
||||
if ((valueCopy == null && key.equals(desiredPath))|| (key.startsWith(desiredPath) && !key.equals(desiredPath))) {
|
||||
childrenCopy.remove(i);
|
||||
// Remove any whitespace or commas after the deleted setting
|
||||
for (int j = i; j < childrenCopy.size(); j++) {
|
||||
if (childrenCopy.get(j) instanceof ConfigNodeSingleToken) {
|
||||
Token t = ((ConfigNodeSingleToken) childrenCopy.get(j)).token();
|
||||
if (Tokens.isIgnoredWhitespace(t) || t == Tokens.COMMA) {
|
||||
childrenCopy.remove(j);
|
||||
j--;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if (key.equals(desiredPath)) {
|
||||
seenNonMatching = true;
|
||||
AbstractConfigNodeValue indentedValue;
|
||||
AbstractConfigNode before = i - 1 > 0 ? childrenCopy.get(i - 1) : null;
|
||||
if (value instanceof ConfigNodeComplexValue &&
|
||||
before instanceof ConfigNodeSingleToken &&
|
||||
Tokens.isIgnoredWhitespace(((ConfigNodeSingleToken) before).token()))
|
||||
indentedValue = ((ConfigNodeComplexValue) value).indentText(before);
|
||||
else
|
||||
indentedValue = value;
|
||||
childrenCopy.set(i, node.replaceValue(indentedValue));
|
||||
valueCopy = null;
|
||||
} else if (desiredPath.startsWith(key)) {
|
||||
seenNonMatching = true;
|
||||
if (node.value() instanceof ConfigNodeObject) {
|
||||
Path remainingPath = desiredPath.subPath(key.length());
|
||||
childrenCopy.set(i, node.replaceValue(((ConfigNodeObject) node.value()).changeValueOnPath(remainingPath, valueCopy, flavor)));
|
||||
if (valueCopy != null && !node.equals(super.children.get(i)))
|
||||
valueCopy = null;
|
||||
}
|
||||
} else {
|
||||
seenNonMatching = true;
|
||||
}
|
||||
}
|
||||
return new ConfigNodeObject(childrenCopy);
|
||||
}
|
||||
|
||||
public ConfigNodeObject setValueOnPath(String desiredPath, AbstractConfigNodeValue value) {
|
||||
return setValueOnPath(desiredPath, value, ConfigSyntax.CONF);
|
||||
}
|
||||
|
||||
public ConfigNodeObject setValueOnPath(String desiredPath, AbstractConfigNodeValue value, ConfigSyntax flavor) {
|
||||
ConfigNodePath path = PathParser.parsePathNode(desiredPath, flavor);
|
||||
return setValueOnPath(path, value, flavor);
|
||||
}
|
||||
|
||||
private ConfigNodeObject setValueOnPath(ConfigNodePath desiredPath, AbstractConfigNodeValue value, ConfigSyntax flavor) {
|
||||
ConfigNodeObject node = changeValueOnPath(desiredPath.value(), value, flavor);
|
||||
|
||||
// If the desired Path did not exist, add it
|
||||
if (!node.hasValue(desiredPath.value())) {
|
||||
return node.addValueOnPath(desiredPath, value, flavor);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private Collection<AbstractConfigNode> indentation() {
|
||||
boolean seenNewLine = false;
|
||||
ArrayList<AbstractConfigNode> indentation = new ArrayList<AbstractConfigNode>();
|
||||
if (children.isEmpty()) {
|
||||
return indentation;
|
||||
}
|
||||
for (int i = 0; i < children.size(); i++) {
|
||||
if (!seenNewLine) {
|
||||
if (children.get(i) instanceof ConfigNodeSingleToken &&
|
||||
Tokens.isNewline(((ConfigNodeSingleToken) children.get(i)).token())) {
|
||||
seenNewLine = true;
|
||||
indentation.add(new ConfigNodeSingleToken(Tokens.newLine(null)));
|
||||
}
|
||||
} else {
|
||||
if (children.get(i) instanceof ConfigNodeSingleToken &&
|
||||
Tokens.isIgnoredWhitespace(((ConfigNodeSingleToken) children.get(i)).token()) &&
|
||||
i + 1 < children.size() && (children.get(i+1) instanceof ConfigNodeField ||
|
||||
children.get(i+1) instanceof ConfigNodeInclude)) {
|
||||
// Return the indentation of the first setting on its own line
|
||||
indentation.add(children.get(i));
|
||||
return indentation;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (indentation.isEmpty()) {
|
||||
indentation.add(new ConfigNodeSingleToken(Tokens.newIgnoredWhitespace(null, " ")));
|
||||
} else {
|
||||
// Calculate the indentation of the ending curly-brace to get the indentation of the root object
|
||||
AbstractConfigNode last = children.get(children.size() - 1);
|
||||
if (last instanceof ConfigNodeSingleToken && ((ConfigNodeSingleToken) last).token() == Tokens.CLOSE_CURLY) {
|
||||
AbstractConfigNode beforeLast = children.get(children.size() - 2);
|
||||
String indent = "";
|
||||
if (beforeLast instanceof ConfigNodeSingleToken &&
|
||||
Tokens.isIgnoredWhitespace(((ConfigNodeSingleToken) beforeLast).token()))
|
||||
indent = ((ConfigNodeSingleToken) beforeLast).token().tokenText();
|
||||
indent += " ";
|
||||
indentation.add(new ConfigNodeSingleToken(Tokens.newIgnoredWhitespace(null, indent)));
|
||||
return indentation;
|
||||
}
|
||||
}
|
||||
|
||||
// The object has no curly braces and is at the root level, so don't indent
|
||||
return indentation;
|
||||
}
|
||||
|
||||
protected ConfigNodeObject addValueOnPath(ConfigNodePath desiredPath, AbstractConfigNodeValue value, ConfigSyntax flavor) {
|
||||
Path path = desiredPath.value();
|
||||
ArrayList<AbstractConfigNode> childrenCopy = new ArrayList<AbstractConfigNode>(super.children);
|
||||
ArrayList<AbstractConfigNode> indentation = new ArrayList<AbstractConfigNode>(indentation());
|
||||
|
||||
// If the value we're inserting is a complex value, we'll need to indent it for insertion
|
||||
AbstractConfigNodeValue indentedValue;
|
||||
if (value instanceof ConfigNodeComplexValue && !indentation.isEmpty()) {
|
||||
indentedValue = ((ConfigNodeComplexValue) value).indentText(indentation.get(indentation.size() - 1));
|
||||
} else {
|
||||
indentedValue = value;
|
||||
}
|
||||
boolean sameLine = !(indentation.size() > 0 && indentation.get(0) instanceof ConfigNodeSingleToken &&
|
||||
Tokens.isNewline(((ConfigNodeSingleToken) indentation.get(0)).token()));
|
||||
|
||||
// If the path is of length greater than one, see if the value needs to be added further down
|
||||
if (path.length() > 1) {
|
||||
for (int i = super.children.size() - 1; i >= 0; i--) {
|
||||
if (!(super.children.get(i) instanceof ConfigNodeField)) {
|
||||
continue;
|
||||
}
|
||||
ConfigNodeField node = (ConfigNodeField) super.children.get(i);
|
||||
Path key = node.path().value();
|
||||
if (path.startsWith(key) && node.value() instanceof ConfigNodeObject) {
|
||||
ConfigNodePath remainingPath = desiredPath.subPath(key.length());
|
||||
ConfigNodeObject newValue = (ConfigNodeObject) node.value();
|
||||
childrenCopy.set(i, node.replaceValue(newValue.addValueOnPath(remainingPath, value, flavor)));
|
||||
return new ConfigNodeObject(childrenCopy);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise, construct the new setting
|
||||
boolean startsWithBrace = !super.children.isEmpty() && super.children.get(0) instanceof ConfigNodeSingleToken &&
|
||||
((ConfigNodeSingleToken) super.children.get(0)).token() == Tokens.OPEN_CURLY;
|
||||
ArrayList<AbstractConfigNode> newNodes = new ArrayList<AbstractConfigNode>();
|
||||
newNodes.addAll(indentation);
|
||||
newNodes.add(desiredPath.first());
|
||||
newNodes.add(new ConfigNodeSingleToken(Tokens.newIgnoredWhitespace(null, " ")));
|
||||
newNodes.add(new ConfigNodeSingleToken(Tokens.COLON));
|
||||
newNodes.add(new ConfigNodeSingleToken(Tokens.newIgnoredWhitespace(null, " ")));
|
||||
|
||||
if (path.length() == 1) {
|
||||
newNodes.add(indentedValue);
|
||||
} else {
|
||||
// If the path is of length greater than one add the required new objects along the path
|
||||
ArrayList<AbstractConfigNode> newObjectNodes = new ArrayList<AbstractConfigNode>();
|
||||
newObjectNodes.add(new ConfigNodeSingleToken(Tokens.OPEN_CURLY));
|
||||
if (indentation.isEmpty()) {
|
||||
newObjectNodes.add(new ConfigNodeSingleToken(Tokens.newLine(null)));
|
||||
}
|
||||
newObjectNodes.addAll(indentation);
|
||||
newObjectNodes.add(new ConfigNodeSingleToken(Tokens.CLOSE_CURLY));
|
||||
ConfigNodeObject newObject = new ConfigNodeObject(newObjectNodes);
|
||||
newNodes.add(newObject.addValueOnPath(desiredPath.subPath(1), indentedValue, flavor));
|
||||
}
|
||||
|
||||
// Combine these two cases so that we only have to iterate once
|
||||
if (flavor == ConfigSyntax.JSON || startsWithBrace || sameLine) {
|
||||
for (int i = childrenCopy.size() - 1; i >= 0; i--) {
|
||||
|
||||
// If we are in JSON or are adding a setting on the same line, we need to add a comma to the
|
||||
// last setting
|
||||
if ((flavor == ConfigSyntax.JSON || sameLine) && childrenCopy.get(i) instanceof ConfigNodeField) {
|
||||
if (i+1 >= childrenCopy.size() ||
|
||||
!(childrenCopy.get(i+1) instanceof ConfigNodeSingleToken
|
||||
&& ((ConfigNodeSingleToken) childrenCopy.get(i+1)).token() == Tokens.COMMA))
|
||||
childrenCopy.add(i+1, new ConfigNodeSingleToken(Tokens.COMMA));
|
||||
break;
|
||||
}
|
||||
|
||||
// Add the value into the copy of the children map, keeping any whitespace/newlines
|
||||
// before the close curly brace
|
||||
if (startsWithBrace && childrenCopy.get(i) instanceof ConfigNodeSingleToken &&
|
||||
((ConfigNodeSingleToken) childrenCopy.get(i)).token == Tokens.CLOSE_CURLY) {
|
||||
AbstractConfigNode previous = childrenCopy.get(i - 1);
|
||||
if (previous instanceof ConfigNodeSingleToken &&
|
||||
Tokens.isNewline(((ConfigNodeSingleToken) previous).token())) {
|
||||
childrenCopy.add(i - 1, new ConfigNodeField(newNodes));
|
||||
i--;
|
||||
} else if (previous instanceof ConfigNodeSingleToken &&
|
||||
Tokens.isIgnoredWhitespace(((ConfigNodeSingleToken) previous).token())) {
|
||||
AbstractConfigNode beforePrevious = childrenCopy.get(i - 2);
|
||||
if (sameLine) {
|
||||
childrenCopy.add(i - 1, new ConfigNodeField(newNodes));
|
||||
i--;
|
||||
}
|
||||
else if (beforePrevious instanceof ConfigNodeSingleToken &&
|
||||
Tokens.isNewline(((ConfigNodeSingleToken) beforePrevious).token())) {
|
||||
childrenCopy.add(i - 2, new ConfigNodeField(newNodes));
|
||||
i -= 2;
|
||||
} else {
|
||||
childrenCopy.add(i, new ConfigNodeField(newNodes));
|
||||
}
|
||||
|
||||
}
|
||||
else
|
||||
childrenCopy.add(i, new ConfigNodeField(newNodes));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!startsWithBrace) {
|
||||
if (!childrenCopy.isEmpty() && childrenCopy.get(childrenCopy.size() - 1) instanceof ConfigNodeSingleToken &&
|
||||
Tokens.isNewline(((ConfigNodeSingleToken) childrenCopy.get(childrenCopy.size() - 1)).token()))
|
||||
childrenCopy.add(childrenCopy.size() - 1, new ConfigNodeField(newNodes));
|
||||
else
|
||||
childrenCopy.add(new ConfigNodeField(newNodes));
|
||||
}
|
||||
return new ConfigNodeObject(childrenCopy);
|
||||
}
|
||||
|
||||
public ConfigNodeObject removeValueOnPath(String desiredPath, ConfigSyntax flavor) {
|
||||
Path path = PathParser.parsePathNode(desiredPath, flavor).value();
|
||||
return changeValueOnPath(path, null, flavor);
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Copyright (C) 2015 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
|
||||
final class ConfigNodePath extends AbstractConfigNode {
|
||||
final private Path path;
|
||||
final ArrayList<Token> tokens;
|
||||
ConfigNodePath(Path path, Collection<Token> tokens) {
|
||||
this.path = path;
|
||||
this.tokens = new ArrayList<Token>(tokens);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Collection<Token> tokens() {
|
||||
return tokens;
|
||||
}
|
||||
|
||||
protected Path value() {
|
||||
return path;
|
||||
}
|
||||
|
||||
protected ConfigNodePath subPath(int toRemove) {
|
||||
int periodCount = 0;
|
||||
ArrayList<Token> tokensCopy = new ArrayList<Token>(tokens);
|
||||
for (int i = 0; i < tokensCopy.size(); i++) {
|
||||
if (Tokens.isUnquotedText(tokensCopy.get(i)) &&
|
||||
tokensCopy.get(i).tokenText().equals("."))
|
||||
periodCount++;
|
||||
|
||||
if (periodCount == toRemove) {
|
||||
return new ConfigNodePath(path.subPath(toRemove), tokensCopy.subList(i + 1, tokensCopy.size()));
|
||||
}
|
||||
}
|
||||
throw new ConfigException.BugOrBroken("Tried to remove too many elements from a Path node");
|
||||
}
|
||||
|
||||
protected ConfigNodePath first() {
|
||||
ArrayList<Token> tokensCopy = new ArrayList<Token>(tokens);
|
||||
for (int i = 0; i < tokensCopy.size(); i++) {
|
||||
if (Tokens.isUnquotedText(tokensCopy.get(i)) &&
|
||||
tokensCopy.get(i).tokenText().equals("."))
|
||||
return new ConfigNodePath(path.subPath(0, 1), tokensCopy.subList(0, i));
|
||||
}
|
||||
return this;
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigSyntax;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
|
||||
final class ConfigNodeRoot extends ConfigNodeComplexValue {
|
||||
final private ConfigOrigin origin;
|
||||
|
||||
ConfigNodeRoot(Collection<AbstractConfigNode> children, ConfigOrigin origin) {
|
||||
super(children);
|
||||
this.origin = origin;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigNodeRoot newNode(Collection<AbstractConfigNode> nodes) {
|
||||
throw new ConfigException.BugOrBroken("Tried to indent the root object");
|
||||
}
|
||||
|
||||
protected ConfigNodeComplexValue value() {
|
||||
for (AbstractConfigNode node : children) {
|
||||
if (node instanceof ConfigNodeComplexValue) {
|
||||
return (ConfigNodeComplexValue)node;
|
||||
}
|
||||
}
|
||||
throw new ConfigException.BugOrBroken("ConfigNodeRoot did not contain a value");
|
||||
}
|
||||
|
||||
protected ConfigNodeRoot setValue(String desiredPath, AbstractConfigNodeValue value, ConfigSyntax flavor) {
|
||||
ArrayList<AbstractConfigNode> childrenCopy = new ArrayList<AbstractConfigNode>(children);
|
||||
for (int i = 0; i < childrenCopy.size(); i++) {
|
||||
AbstractConfigNode node = childrenCopy.get(i);
|
||||
if (node instanceof ConfigNodeComplexValue) {
|
||||
if (node instanceof ConfigNodeArray) {
|
||||
throw new ConfigException.WrongType(origin, "The ConfigDocument had an array at the root level, and values cannot be modified inside an array.");
|
||||
} else if (node instanceof ConfigNodeObject) {
|
||||
if (value == null) {
|
||||
childrenCopy.set(i, ((ConfigNodeObject)node).removeValueOnPath(desiredPath, flavor));
|
||||
} else {
|
||||
childrenCopy.set(i, ((ConfigNodeObject) node).setValueOnPath(desiredPath, value, flavor));
|
||||
}
|
||||
return new ConfigNodeRoot(childrenCopy, origin);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new ConfigException.BugOrBroken("ConfigNodeRoot did not contain a value");
|
||||
}
|
||||
|
||||
protected boolean hasValue(String desiredPath) {
|
||||
Path path = PathParser.parsePath(desiredPath);
|
||||
ArrayList<AbstractConfigNode> childrenCopy = new ArrayList<AbstractConfigNode>(children);
|
||||
for (int i = 0; i < childrenCopy.size(); i++) {
|
||||
AbstractConfigNode node = childrenCopy.get(i);
|
||||
if (node instanceof ConfigNodeComplexValue) {
|
||||
if (node instanceof ConfigNodeArray) {
|
||||
throw new ConfigException.WrongType(origin, "The ConfigDocument had an array at the root level, and values cannot be modified inside an array.");
|
||||
} else if (node instanceof ConfigNodeObject) {
|
||||
return ((ConfigNodeObject) node).hasValue(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new ConfigException.BugOrBroken("ConfigNodeRoot did not contain a value");
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Copyright (C) 2015 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
final class ConfigNodeSimpleValue extends AbstractConfigNodeValue {
|
||||
final Token token;
|
||||
ConfigNodeSimpleValue(Token value) {
|
||||
token = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Collection<Token> tokens() {
|
||||
return Collections.singletonList(token);
|
||||
}
|
||||
|
||||
protected Token token() { return token; }
|
||||
|
||||
protected AbstractConfigValue value() {
|
||||
if (Tokens.isValue(token))
|
||||
return Tokens.getValue(token);
|
||||
else if (Tokens.isUnquotedText(token))
|
||||
return new ConfigString.Unquoted(token.origin(), Tokens.getUnquotedText(token));
|
||||
else if (Tokens.isSubstitution(token)) {
|
||||
List<Token> expression = Tokens.getSubstitutionPathExpression(token);
|
||||
Path path = PathParser.parsePathExpression(expression.iterator(), token.origin());
|
||||
boolean optional = Tokens.getSubstitutionOptional(token);
|
||||
|
||||
return new ConfigReference(token.origin(), new SubstitutionExpression(path, optional));
|
||||
}
|
||||
throw new ConfigException.BugOrBroken("ConfigNodeSimpleValue did not contain a valid value token");
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Copyright (C) 2015 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
|
||||
class ConfigNodeSingleToken extends AbstractConfigNode {
|
||||
final Token token;
|
||||
ConfigNodeSingleToken(Token t) {
|
||||
token = t;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Collection<Token> tokens() {
|
||||
return Collections.singletonList(token);
|
||||
}
|
||||
|
||||
protected Token token() { return token; }
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.io.ObjectStreamException;
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigRenderOptions;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType;
|
||||
|
||||
/**
|
||||
* This exists because sometimes null is not the same as missing. Specifically,
|
||||
* if a value is set to null we can give a better error message (indicating
|
||||
* where it was set to null) in case someone asks for the value. Also, null
|
||||
* overrides values set "earlier" in the search path, while missing values do
|
||||
* not.
|
||||
*
|
||||
*/
|
||||
final class ConfigNull extends AbstractConfigValue implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 2L;
|
||||
|
||||
ConfigNull(ConfigOrigin origin) {
|
||||
super(origin);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigValueType valueType() {
|
||||
return ConfigValueType.NULL;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object unwrapped() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
String transformToString() {
|
||||
return "null";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) {
|
||||
sb.append("null");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigNull newCopy(ConfigOrigin origin) {
|
||||
return new ConfigNull(origin);
|
||||
}
|
||||
|
||||
// serialization all goes through SerializedConfigValue
|
||||
private Object writeReplace() throws ObjectStreamException {
|
||||
return new SerializedConfigValue(this);
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.io.ObjectStreamException;
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin;
|
||||
|
||||
abstract class ConfigNumber extends AbstractConfigValue implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 2L;
|
||||
|
||||
// This is so when we concatenate a number into a string (say it appears in
|
||||
// a sentence) we always have it exactly as the person typed it into the
|
||||
// config file. It's purely cosmetic; equals/hashCode don't consider this
|
||||
// for example.
|
||||
final protected String originalText;
|
||||
|
||||
protected ConfigNumber(ConfigOrigin origin, String originalText) {
|
||||
super(origin);
|
||||
this.originalText = originalText;
|
||||
}
|
||||
|
||||
@Override
|
||||
public abstract Number unwrapped();
|
||||
|
||||
@Override
|
||||
String transformToString() {
|
||||
return originalText;
|
||||
}
|
||||
|
||||
int intValueRangeChecked(String path) {
|
||||
long l = longValue();
|
||||
if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
|
||||
throw new ConfigException.WrongType(origin(), path, "32-bit integer",
|
||||
"out-of-range value " + l);
|
||||
}
|
||||
return (int) l;
|
||||
}
|
||||
|
||||
protected abstract long longValue();
|
||||
|
||||
protected abstract double doubleValue();
|
||||
|
||||
private boolean isWhole() {
|
||||
long asLong = longValue();
|
||||
return asLong == doubleValue();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean canEqual(Object other) {
|
||||
return other instanceof ConfigNumber;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
// note that "origin" is deliberately NOT part of equality
|
||||
if (other instanceof ConfigNumber && canEqual(other)) {
|
||||
ConfigNumber n = (ConfigNumber) other;
|
||||
if (isWhole()) {
|
||||
return n.isWhole() && this.longValue() == n.longValue();
|
||||
} else {
|
||||
return (!n.isWhole()) && this.doubleValue() == n.doubleValue();
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
// note that "origin" is deliberately NOT part of equality
|
||||
|
||||
// this matches what standard Long.hashCode and Double.hashCode
|
||||
// do, though I don't think it really matters.
|
||||
long asLong;
|
||||
if (isWhole()) {
|
||||
asLong = longValue();
|
||||
} else {
|
||||
asLong = Double.doubleToLongBits(doubleValue());
|
||||
}
|
||||
return (int) (asLong ^ (asLong >>> 32));
|
||||
}
|
||||
|
||||
static ConfigNumber newNumber(ConfigOrigin origin, long number,
|
||||
String originalText) {
|
||||
if (number <= Integer.MAX_VALUE && number >= Integer.MIN_VALUE)
|
||||
return new ConfigInt(origin, (int) number, originalText);
|
||||
else
|
||||
return new ConfigLong(origin, number, originalText);
|
||||
}
|
||||
|
||||
static ConfigNumber newNumber(ConfigOrigin origin, double number,
|
||||
String originalText) {
|
||||
long asLong = (long) number;
|
||||
if (asLong == number) {
|
||||
return newNumber(origin, asLong, originalText);
|
||||
} else {
|
||||
return new ConfigDouble(origin, number, originalText);
|
||||
}
|
||||
}
|
||||
|
||||
// serialization all goes through SerializedConfigValue
|
||||
private Object writeReplace() throws ObjectStreamException {
|
||||
return new SerializedConfigValue(this);
|
||||
}
|
||||
}
|
||||
+426
@@ -0,0 +1,426 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.io.File;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
import java.util.Map;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigIncludeContext;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigParseOptions;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigSyntax;
|
||||
|
||||
final class ConfigParser {
|
||||
static AbstractConfigValue parse(ConfigNodeRoot document,
|
||||
ConfigOrigin origin, ConfigParseOptions options,
|
||||
ConfigIncludeContext includeContext) {
|
||||
ParseContext context = new ParseContext(options.getSyntax(), origin, document,
|
||||
SimpleIncluder.makeFull(options.getIncluder()), includeContext);
|
||||
return context.parse();
|
||||
}
|
||||
|
||||
static private final class ParseContext {
|
||||
private int lineNumber;
|
||||
final private ConfigNodeRoot document;
|
||||
final private FullIncluder includer;
|
||||
final private ConfigIncludeContext includeContext;
|
||||
final private ConfigSyntax flavor;
|
||||
final private ConfigOrigin baseOrigin;
|
||||
final private LinkedList<Path> pathStack;
|
||||
|
||||
// the number of lists we are inside; this is used to detect the "cannot
|
||||
// generate a reference to a list element" problem, and once we fix that
|
||||
// problem we should be able to get rid of this variable.
|
||||
int arrayCount;
|
||||
|
||||
ParseContext(ConfigSyntax flavor, ConfigOrigin origin, ConfigNodeRoot document,
|
||||
FullIncluder includer, ConfigIncludeContext includeContext) {
|
||||
lineNumber = 1;
|
||||
this.document = document;
|
||||
this.flavor = flavor;
|
||||
this.baseOrigin = origin;
|
||||
this.includer = includer;
|
||||
this.includeContext = includeContext;
|
||||
this.pathStack = new LinkedList<Path>();
|
||||
this.arrayCount = 0;
|
||||
}
|
||||
|
||||
// merge a bunch of adjacent values into one
|
||||
// value; change unquoted text into a string
|
||||
// value.
|
||||
private AbstractConfigValue parseConcatenation(ConfigNodeConcatenation n) {
|
||||
// this trick is not done in JSON
|
||||
if (flavor == ConfigSyntax.JSON)
|
||||
throw new ConfigException.BugOrBroken("Found a concatenation node in JSON");
|
||||
|
||||
List<AbstractConfigValue> values = new ArrayList<AbstractConfigValue>();
|
||||
|
||||
for (AbstractConfigNode node : n.children()) {
|
||||
AbstractConfigValue v = null;
|
||||
if (node instanceof AbstractConfigNodeValue) {
|
||||
v = parseValue((AbstractConfigNodeValue)node, null);
|
||||
values.add(v);
|
||||
}
|
||||
}
|
||||
|
||||
return ConfigConcatenation.concatenate(values);
|
||||
}
|
||||
|
||||
private SimpleConfigOrigin lineOrigin() {
|
||||
return ((SimpleConfigOrigin) baseOrigin).withLineNumber(lineNumber);
|
||||
}
|
||||
|
||||
private ConfigException parseError(String message) {
|
||||
return parseError(message, null);
|
||||
}
|
||||
|
||||
private ConfigException parseError(String message, Throwable cause) {
|
||||
return new ConfigException.Parse(lineOrigin(), message, cause);
|
||||
}
|
||||
|
||||
private Path fullCurrentPath() {
|
||||
// pathStack has top of stack at front
|
||||
if (pathStack.isEmpty())
|
||||
throw new ConfigException.BugOrBroken("Bug in parser; tried to get current path when at root");
|
||||
else
|
||||
return new Path(pathStack.descendingIterator());
|
||||
}
|
||||
|
||||
private AbstractConfigValue parseValue(AbstractConfigNodeValue n, List<String> comments) {
|
||||
AbstractConfigValue v;
|
||||
|
||||
int startingArrayCount = arrayCount;
|
||||
|
||||
if (n instanceof ConfigNodeSimpleValue) {
|
||||
v = ((ConfigNodeSimpleValue) n).value();
|
||||
} else if (n instanceof ConfigNodeObject) {
|
||||
v = parseObject((ConfigNodeObject)n);
|
||||
} else if (n instanceof ConfigNodeArray) {
|
||||
v = parseArray((ConfigNodeArray)n);
|
||||
} else if (n instanceof ConfigNodeConcatenation) {
|
||||
v = parseConcatenation((ConfigNodeConcatenation)n);
|
||||
} else {
|
||||
throw parseError("Expecting a value but got wrong node type: " + n.getClass());
|
||||
}
|
||||
|
||||
if (comments != null && !comments.isEmpty()) {
|
||||
v = v.withOrigin(v.origin().prependComments(new ArrayList<String>(comments)));
|
||||
comments.clear();
|
||||
}
|
||||
|
||||
if (arrayCount != startingArrayCount)
|
||||
throw new ConfigException.BugOrBroken("Bug in config parser: unbalanced array count");
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
private static AbstractConfigObject createValueUnderPath(Path path,
|
||||
AbstractConfigValue value) {
|
||||
// for path foo.bar, we are creating
|
||||
// { "foo" : { "bar" : value } }
|
||||
List<String> keys = new ArrayList<String>();
|
||||
|
||||
String key = path.first();
|
||||
Path remaining = path.remainder();
|
||||
while (key != null) {
|
||||
keys.add(key);
|
||||
if (remaining == null) {
|
||||
break;
|
||||
} else {
|
||||
key = remaining.first();
|
||||
remaining = remaining.remainder();
|
||||
}
|
||||
}
|
||||
|
||||
// the withComments(null) is to ensure comments are only
|
||||
// on the exact leaf node they apply to.
|
||||
// a comment before "foo.bar" applies to the full setting
|
||||
// "foo.bar" not also to "foo"
|
||||
ListIterator<String> i = keys.listIterator(keys.size());
|
||||
String deepest = i.previous();
|
||||
AbstractConfigObject o = new SimpleConfigObject(value.origin().withComments(null),
|
||||
Collections.<String, AbstractConfigValue> singletonMap(
|
||||
deepest, value));
|
||||
while (i.hasPrevious()) {
|
||||
Map<String, AbstractConfigValue> m = Collections.<String, AbstractConfigValue> singletonMap(
|
||||
i.previous(), o);
|
||||
o = new SimpleConfigObject(value.origin().withComments(null), m);
|
||||
}
|
||||
|
||||
return o;
|
||||
}
|
||||
|
||||
private void parseInclude(Map<String, AbstractConfigValue> values, ConfigNodeInclude n) {
|
||||
boolean isRequired = n.isRequired();
|
||||
ConfigIncludeContext cic = includeContext.setParseOptions(includeContext.parseOptions().setAllowMissing(!isRequired));
|
||||
|
||||
AbstractConfigObject obj;
|
||||
switch (n.kind()) {
|
||||
case URL:
|
||||
URL url;
|
||||
try {
|
||||
url = new URL(n.name());
|
||||
} catch (MalformedURLException e) {
|
||||
throw parseError("include url() specifies an invalid URL: " + n.name(), e);
|
||||
}
|
||||
obj = (AbstractConfigObject) includer.includeURL(cic, url);
|
||||
break;
|
||||
|
||||
case FILE:
|
||||
obj = (AbstractConfigObject) includer.includeFile(cic,
|
||||
new File(n.name()));
|
||||
break;
|
||||
|
||||
case CLASSPATH:
|
||||
obj = (AbstractConfigObject) includer.includeResources(cic, n.name());
|
||||
break;
|
||||
|
||||
case HEURISTIC:
|
||||
obj = (AbstractConfigObject) includer
|
||||
.include(cic, n.name());
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new ConfigException.BugOrBroken("should not be reached");
|
||||
}
|
||||
|
||||
// we really should make this work, but for now throwing an
|
||||
// exception is better than producing an incorrect result.
|
||||
// See https://github.com/lightbend/config/issues/160
|
||||
if (arrayCount > 0 && obj.resolveStatus() != ResolveStatus.RESOLVED)
|
||||
throw parseError("Due to current limitations of the config parser, when an include statement is nested inside a list value, "
|
||||
+ "${} substitutions inside the included file cannot be resolved correctly. Either move the include outside of the list value or "
|
||||
+ "remove the ${} statements from the included file.");
|
||||
|
||||
if (!pathStack.isEmpty()) {
|
||||
Path prefix = fullCurrentPath();
|
||||
obj = obj.relativized(prefix);
|
||||
}
|
||||
|
||||
for (String key : obj.keySet()) {
|
||||
AbstractConfigValue v = obj.get(key);
|
||||
AbstractConfigValue existing = values.get(key);
|
||||
if (existing != null) {
|
||||
values.put(key, v.withFallback(existing));
|
||||
} else {
|
||||
values.put(key, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private AbstractConfigObject parseObject(ConfigNodeObject n) {
|
||||
Map<String, AbstractConfigValue> values = new HashMap<String, AbstractConfigValue>();
|
||||
SimpleConfigOrigin objectOrigin = lineOrigin();
|
||||
boolean lastWasNewline = false;
|
||||
|
||||
ArrayList<AbstractConfigNode> nodes = new ArrayList<AbstractConfigNode>(n.children());
|
||||
List<String> comments = new ArrayList<String>();
|
||||
for (int i = 0; i < nodes.size(); i++) {
|
||||
AbstractConfigNode node = nodes.get(i);
|
||||
if (node instanceof ConfigNodeComment) {
|
||||
lastWasNewline = false;
|
||||
comments.add(((ConfigNodeComment) node).commentText());
|
||||
} else if (node instanceof ConfigNodeSingleToken && Tokens.isNewline(((ConfigNodeSingleToken) node).token())) {
|
||||
lineNumber++;
|
||||
if (lastWasNewline) {
|
||||
// Drop all comments if there was a blank line and start a new comment block
|
||||
comments.clear();
|
||||
}
|
||||
lastWasNewline = true;
|
||||
} else if (flavor != ConfigSyntax.JSON && node instanceof ConfigNodeInclude) {
|
||||
parseInclude(values, (ConfigNodeInclude)node);
|
||||
lastWasNewline = false;
|
||||
} else if (node instanceof ConfigNodeField) {
|
||||
lastWasNewline = false;
|
||||
Path path = ((ConfigNodeField) node).path().value();
|
||||
comments.addAll(((ConfigNodeField) node).comments());
|
||||
|
||||
// path must be on-stack while we parse the value
|
||||
pathStack.push(path);
|
||||
if (((ConfigNodeField) node).separator() == Tokens.PLUS_EQUALS) {
|
||||
// we really should make this work, but for now throwing
|
||||
// an exception is better than producing an incorrect
|
||||
// result. See
|
||||
// https://github.com/lightbend/config/issues/160
|
||||
if (arrayCount > 0)
|
||||
throw parseError("Due to current limitations of the config parser, += does not work nested inside a list. "
|
||||
+ "+= expands to a ${} substitution and the path in ${} cannot currently refer to list elements. "
|
||||
+ "You might be able to move the += outside of the list and then refer to it from inside the list with ${}.");
|
||||
|
||||
// because we will put it in an array after the fact so
|
||||
// we want this to be incremented during the parseValue
|
||||
// below in order to throw the above exception.
|
||||
arrayCount += 1;
|
||||
}
|
||||
|
||||
AbstractConfigNodeValue valueNode;
|
||||
AbstractConfigValue newValue;
|
||||
|
||||
valueNode = ((ConfigNodeField) node).value();
|
||||
|
||||
// comments from the key token go to the value token
|
||||
newValue = parseValue(valueNode, comments);
|
||||
|
||||
if (((ConfigNodeField) node).separator() == Tokens.PLUS_EQUALS) {
|
||||
arrayCount -= 1;
|
||||
|
||||
List<AbstractConfigValue> concat = new ArrayList<AbstractConfigValue>(2);
|
||||
AbstractConfigValue previousRef = new ConfigReference(newValue.origin(),
|
||||
new SubstitutionExpression(fullCurrentPath(), true /* optional */));
|
||||
AbstractConfigValue list = new SimpleConfigList(newValue.origin(),
|
||||
Collections.singletonList(newValue));
|
||||
concat.add(previousRef);
|
||||
concat.add(list);
|
||||
newValue = ConfigConcatenation.concatenate(concat);
|
||||
}
|
||||
|
||||
// Grab any trailing comments on the same line
|
||||
if (i < nodes.size() - 1) {
|
||||
i++;
|
||||
while (i < nodes.size()) {
|
||||
if (nodes.get(i) instanceof ConfigNodeComment) {
|
||||
ConfigNodeComment comment = (ConfigNodeComment) nodes.get(i);
|
||||
newValue = newValue.withOrigin(newValue.origin().appendComments(
|
||||
Collections.singletonList(comment.commentText())));
|
||||
break;
|
||||
} else if (nodes.get(i) instanceof ConfigNodeSingleToken) {
|
||||
ConfigNodeSingleToken curr = (ConfigNodeSingleToken) nodes.get(i);
|
||||
if (curr.token() == Tokens.COMMA || Tokens.isIgnoredWhitespace(curr.token())) {
|
||||
// keep searching, as there could still be a comment
|
||||
} else {
|
||||
i--;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
i--;
|
||||
break;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
pathStack.pop();
|
||||
|
||||
String key = path.first();
|
||||
Path remaining = path.remainder();
|
||||
|
||||
if (remaining == null) {
|
||||
AbstractConfigValue existing = values.get(key);
|
||||
if (existing != null) {
|
||||
// In strict JSON, dups should be an error; while in
|
||||
// our custom config language, they should be merged
|
||||
// if the value is an object (or substitution that
|
||||
// could become an object).
|
||||
|
||||
if (flavor == ConfigSyntax.JSON) {
|
||||
throw parseError("JSON does not allow duplicate fields: '"
|
||||
+ key
|
||||
+ "' was already seen at "
|
||||
+ existing.origin().description());
|
||||
} else {
|
||||
newValue = newValue.withFallback(existing);
|
||||
}
|
||||
}
|
||||
values.put(key, newValue);
|
||||
} else {
|
||||
if (flavor == ConfigSyntax.JSON) {
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"somehow got multi-element path in JSON mode");
|
||||
}
|
||||
|
||||
AbstractConfigObject obj = createValueUnderPath(
|
||||
remaining, newValue);
|
||||
AbstractConfigValue existing = values.get(key);
|
||||
if (existing != null) {
|
||||
obj = obj.withFallback(existing);
|
||||
}
|
||||
values.put(key, obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new SimpleConfigObject(objectOrigin, values);
|
||||
}
|
||||
|
||||
private SimpleConfigList parseArray(ConfigNodeArray n) {
|
||||
arrayCount += 1;
|
||||
|
||||
SimpleConfigOrigin arrayOrigin = lineOrigin();
|
||||
List<AbstractConfigValue> values = new ArrayList<AbstractConfigValue>();
|
||||
|
||||
boolean lastWasNewLine = false;
|
||||
List<String> comments = new ArrayList<String>();
|
||||
|
||||
AbstractConfigValue v = null;
|
||||
|
||||
for (AbstractConfigNode node : n.children()) {
|
||||
if (node instanceof ConfigNodeComment) {
|
||||
comments.add(((ConfigNodeComment) node).commentText());
|
||||
lastWasNewLine = false;
|
||||
} else if (node instanceof ConfigNodeSingleToken && Tokens.isNewline(((ConfigNodeSingleToken) node).token())) {
|
||||
lineNumber++;
|
||||
if (lastWasNewLine && v == null) {
|
||||
comments.clear();
|
||||
} else if (v != null) {
|
||||
values.add(v.withOrigin(v.origin().appendComments(new ArrayList<String>(comments))));
|
||||
comments.clear();
|
||||
v = null;
|
||||
}
|
||||
lastWasNewLine = true;
|
||||
} else if (node instanceof AbstractConfigNodeValue) {
|
||||
lastWasNewLine = false;
|
||||
if (v != null) {
|
||||
values.add(v.withOrigin(v.origin().appendComments(new ArrayList<String>(comments))));
|
||||
comments.clear();
|
||||
}
|
||||
v = parseValue((AbstractConfigNodeValue)node, comments);
|
||||
}
|
||||
}
|
||||
// There shouldn't be any comments at this point, but add them just in case
|
||||
if (v != null) {
|
||||
values.add(v.withOrigin(v.origin().appendComments(new ArrayList<String>(comments))));
|
||||
}
|
||||
arrayCount -= 1;
|
||||
return new SimpleConfigList(arrayOrigin, values);
|
||||
}
|
||||
|
||||
AbstractConfigValue parse() {
|
||||
AbstractConfigValue result = null;
|
||||
ArrayList<String> comments = new ArrayList<String>();
|
||||
boolean lastWasNewLine = false;
|
||||
for (AbstractConfigNode node : document.children()) {
|
||||
if (node instanceof ConfigNodeComment) {
|
||||
comments.add(((ConfigNodeComment) node).commentText());
|
||||
lastWasNewLine = false;
|
||||
} else if (node instanceof ConfigNodeSingleToken) {
|
||||
Token t = ((ConfigNodeSingleToken) node).token();
|
||||
if (Tokens.isNewline(t)) {
|
||||
lineNumber++;
|
||||
if (lastWasNewLine && result == null) {
|
||||
comments.clear();
|
||||
} else if (result != null) {
|
||||
result = result.withOrigin(result.origin().appendComments(new ArrayList<String>(comments)));
|
||||
comments.clear();
|
||||
break;
|
||||
}
|
||||
lastWasNewLine = true;
|
||||
}
|
||||
} else if (node instanceof ConfigNodeComplexValue) {
|
||||
result = parseValue((ConfigNodeComplexValue)node, comments);
|
||||
lastWasNewLine = false;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigRenderOptions;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType;
|
||||
|
||||
/**
|
||||
* ConfigReference replaces ConfigReference (the older class kept for back
|
||||
* compat) and represents the ${} substitution syntax. It can resolve to any
|
||||
* kind of value.
|
||||
*/
|
||||
final class ConfigReference extends AbstractConfigValue implements Unmergeable {
|
||||
|
||||
final private SubstitutionExpression expr;
|
||||
// the length of any prefixes added with relativized()
|
||||
final private int prefixLength;
|
||||
|
||||
ConfigReference(ConfigOrigin origin, SubstitutionExpression expr) {
|
||||
this(origin, expr, 0);
|
||||
}
|
||||
|
||||
private ConfigReference(ConfigOrigin origin, SubstitutionExpression expr, int prefixLength) {
|
||||
super(origin);
|
||||
this.expr = expr;
|
||||
this.prefixLength = prefixLength;
|
||||
}
|
||||
|
||||
private ConfigException.NotResolved notResolved() {
|
||||
return new ConfigException.NotResolved(
|
||||
"need to Config#resolve(), see the API docs for Config#resolve(); substitution not resolved: "
|
||||
+ this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigValueType valueType() {
|
||||
throw notResolved();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object unwrapped() {
|
||||
throw notResolved();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigReference newCopy(ConfigOrigin newOrigin) {
|
||||
return new ConfigReference(newOrigin, expr, prefixLength);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean ignoresFallbacks() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<ConfigReference> unmergedValues() {
|
||||
return Collections.singleton(this);
|
||||
}
|
||||
|
||||
// ConfigReference should be a firewall against NotPossibleToResolve going
|
||||
// further up the stack; it should convert everything to ConfigException.
|
||||
// This way it's impossible for NotPossibleToResolve to "escape" since
|
||||
// any failure to resolve has to start with a ConfigReference.
|
||||
@Override
|
||||
ResolveResult<? extends AbstractConfigValue> resolveSubstitutions(ResolveContext context, ResolveSource source) {
|
||||
ResolveContext newContext = context.addCycleMarker(this);
|
||||
AbstractConfigValue v;
|
||||
try {
|
||||
ResolveSource.ResultWithPath resultWithPath = source.lookupSubst(newContext, expr, prefixLength);
|
||||
newContext = resultWithPath.result.context;
|
||||
|
||||
if (resultWithPath.result.value != null) {
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(newContext.depth(), "recursively resolving " + resultWithPath
|
||||
+ " which was the resolution of " + expr + " against " + source);
|
||||
|
||||
ResolveSource recursiveResolveSource = (new ResolveSource(
|
||||
(AbstractConfigObject) resultWithPath.pathFromRoot.last(), resultWithPath.pathFromRoot));
|
||||
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(newContext.depth(), "will recursively resolve against " + recursiveResolveSource);
|
||||
|
||||
ResolveResult<? extends AbstractConfigValue> result = newContext.resolve(resultWithPath.result.value,
|
||||
recursiveResolveSource);
|
||||
v = result.value;
|
||||
newContext = result.context;
|
||||
} else {
|
||||
ConfigValue fallback = context.options().getResolver().lookup(expr.path().render());
|
||||
v = (AbstractConfigValue) fallback;
|
||||
}
|
||||
} catch (NotPossibleToResolve e) {
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(newContext.depth(),
|
||||
"not possible to resolve " + expr + ", cycle involved: " + e.traceString());
|
||||
if (expr.optional())
|
||||
v = null;
|
||||
else
|
||||
throw new ConfigException.UnresolvedSubstitution(origin(), expr
|
||||
+ " was part of a cycle of substitutions involving " + e.traceString(), e);
|
||||
}
|
||||
|
||||
if (v == null && !expr.optional()) {
|
||||
if (newContext.options().getAllowUnresolved())
|
||||
return ResolveResult.make(newContext.removeCycleMarker(this), this);
|
||||
else
|
||||
throw new ConfigException.UnresolvedSubstitution(origin(), expr.toString());
|
||||
} else {
|
||||
return ResolveResult.make(newContext.removeCycleMarker(this), v);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
ResolveStatus resolveStatus() {
|
||||
return ResolveStatus.UNRESOLVED;
|
||||
}
|
||||
|
||||
// when you graft a substitution into another object,
|
||||
// you have to prefix it with the location in that object
|
||||
// where you grafted it; but save prefixLength so
|
||||
// system property and env variable lookups don't get
|
||||
// broken.
|
||||
@Override
|
||||
ConfigReference relativized(Path prefix) {
|
||||
SubstitutionExpression newExpr = expr.changePath(expr.path().prepend(prefix));
|
||||
return new ConfigReference(origin(), newExpr, prefixLength + prefix.length());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean canEqual(Object other) {
|
||||
return other instanceof ConfigReference;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
// note that "origin" is deliberately NOT part of equality
|
||||
if (other instanceof ConfigReference) {
|
||||
return canEqual(other) && this.expr.equals(((ConfigReference) other).expr);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
// note that "origin" is deliberately NOT part of equality
|
||||
return expr.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) {
|
||||
sb.append(expr.toString());
|
||||
}
|
||||
|
||||
SubstitutionExpression expression() {
|
||||
return expr;
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.io.ObjectStreamException;
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigRenderOptions;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType;
|
||||
|
||||
abstract class ConfigString extends AbstractConfigValue implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 2L;
|
||||
|
||||
final protected String value;
|
||||
|
||||
protected ConfigString(ConfigOrigin origin, String value) {
|
||||
super(origin);
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
|
||||
final static class Quoted extends ConfigString {
|
||||
Quoted(ConfigOrigin origin, String value) {
|
||||
super(origin, value);
|
||||
}
|
||||
@Override
|
||||
protected Quoted newCopy(ConfigOrigin origin) {
|
||||
return new Quoted(origin, value);
|
||||
}
|
||||
// serialization all goes through SerializedConfigValue
|
||||
private Object writeReplace() throws ObjectStreamException {
|
||||
return new SerializedConfigValue(this);
|
||||
}
|
||||
}
|
||||
|
||||
// this is sort of a hack; we want to preserve whether whitespace
|
||||
// was quoted until we process substitutions, so we can ignore
|
||||
// unquoted whitespace when concatenating lists or objects.
|
||||
// We dump this distinction when serializing and deserializing,
|
||||
// but that's OK because it isn't in equals/hashCode, and we
|
||||
// don't allow serializing unresolved objects which is where
|
||||
// quoted-ness matters. If we later make ConfigOrigin point
|
||||
// to the original token range, we could use that to implement
|
||||
// wasQuoted()
|
||||
final static class Unquoted extends ConfigString {
|
||||
Unquoted(ConfigOrigin origin, String value) {
|
||||
super(origin, value);
|
||||
}
|
||||
@Override
|
||||
protected Unquoted newCopy(ConfigOrigin origin) {
|
||||
return new Unquoted(origin, value);
|
||||
}
|
||||
// serialization all goes through SerializedConfigValue
|
||||
private Object writeReplace() throws ObjectStreamException {
|
||||
return new SerializedConfigValue(this);
|
||||
}
|
||||
}
|
||||
|
||||
boolean wasQuoted() {
|
||||
return (this instanceof Quoted);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigValueType valueType() {
|
||||
return ConfigValueType.STRING;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String unwrapped() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
String transformToString() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) {
|
||||
sb.append(ConfigImplUtil.renderJsonString(value));
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Copyright (C) 2014 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue;
|
||||
|
||||
/**
|
||||
* An AbstractConfigValue which contains other values. Java has no way to
|
||||
* express "this has to be an AbstractConfigValue also" other than making
|
||||
* AbstractConfigValue an interface which would be aggravating. But we can say
|
||||
* we are a ConfigValue.
|
||||
*/
|
||||
interface Container extends ConfigValue {
|
||||
/**
|
||||
* Replace a child of this value. CAUTION if replacement is null, delete the
|
||||
* child, which may also delete the parent, or make the parent into a
|
||||
* non-container.
|
||||
*/
|
||||
AbstractConfigValue replaceChild(AbstractConfigValue child, AbstractConfigValue replacement);
|
||||
|
||||
/**
|
||||
* Super-expensive full traversal to see if descendant is anywhere
|
||||
* underneath this container.
|
||||
*/
|
||||
boolean hasDescendant(AbstractConfigValue descendant);
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType;
|
||||
|
||||
/**
|
||||
* Default automatic type transformations.
|
||||
*/
|
||||
final class DefaultTransformer {
|
||||
|
||||
static AbstractConfigValue transform(AbstractConfigValue value,
|
||||
ConfigValueType requested) {
|
||||
if (value.valueType() == ConfigValueType.STRING) {
|
||||
String s = (String) value.unwrapped();
|
||||
switch (requested) {
|
||||
case NUMBER:
|
||||
try {
|
||||
Long v = Long.parseLong(s);
|
||||
return new ConfigLong(value.origin(), v, s);
|
||||
} catch (NumberFormatException e) {
|
||||
// try Double
|
||||
}
|
||||
try {
|
||||
Double v = Double.parseDouble(s);
|
||||
return new ConfigDouble(value.origin(), v, s);
|
||||
} catch (NumberFormatException e) {
|
||||
// oh well.
|
||||
}
|
||||
break;
|
||||
case NULL:
|
||||
if (s.equals("null"))
|
||||
return new ConfigNull(value.origin());
|
||||
break;
|
||||
case BOOLEAN:
|
||||
if (s.equals("true") || s.equals("yes") || s.equals("on")) {
|
||||
return new ConfigBoolean(value.origin(), true);
|
||||
} else if (s.equals("false") || s.equals("no")
|
||||
|| s.equals("off")) {
|
||||
return new ConfigBoolean(value.origin(), false);
|
||||
}
|
||||
break;
|
||||
case LIST:
|
||||
// can't go STRING to LIST automatically
|
||||
break;
|
||||
case OBJECT:
|
||||
// can't go STRING to OBJECT automatically
|
||||
break;
|
||||
case STRING:
|
||||
// no-op STRING to STRING
|
||||
break;
|
||||
}
|
||||
} else if (requested == ConfigValueType.STRING) {
|
||||
// if we converted null to string here, then you wouldn't properly
|
||||
// get a missing-value error if you tried to get a null value
|
||||
// as a string.
|
||||
switch (value.valueType()) {
|
||||
case NUMBER: // FALL THROUGH
|
||||
case BOOLEAN:
|
||||
return new ConfigString.Quoted(value.origin(),
|
||||
value.transformToString());
|
||||
case NULL:
|
||||
// want to be sure this throws instead of returning "null" as a
|
||||
// string
|
||||
break;
|
||||
case OBJECT:
|
||||
// no OBJECT to STRING automatically
|
||||
break;
|
||||
case LIST:
|
||||
// no LIST to STRING automatically
|
||||
break;
|
||||
case STRING:
|
||||
// no-op STRING to STRING
|
||||
break;
|
||||
}
|
||||
} else if (requested == ConfigValueType.LIST && value.valueType() == ConfigValueType.OBJECT) {
|
||||
// attempt to convert an array-like (numeric indices) object to a
|
||||
// list. This would be used with .properties syntax for example:
|
||||
// -Dfoo.0=bar -Dfoo.1=baz
|
||||
// To ensure we still throw type errors for objects treated
|
||||
// as lists in most cases, we'll refuse to convert if the object
|
||||
// does not contain any numeric keys. This means we don't allow
|
||||
// empty objects here though :-/
|
||||
AbstractConfigObject o = (AbstractConfigObject) value;
|
||||
Map<Integer, AbstractConfigValue> values = new HashMap<Integer, AbstractConfigValue>();
|
||||
for (String key : o.keySet()) {
|
||||
int i;
|
||||
try {
|
||||
i = Integer.parseInt(key, 10);
|
||||
if (i < 0)
|
||||
continue;
|
||||
values.put(i, o.get(key));
|
||||
} catch (NumberFormatException e) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (!values.isEmpty()) {
|
||||
ArrayList<Map.Entry<Integer, AbstractConfigValue>> entryList = new ArrayList<Map.Entry<Integer, AbstractConfigValue>>(
|
||||
values.entrySet());
|
||||
// sort by numeric index
|
||||
Collections.sort(entryList,
|
||||
new Comparator<Map.Entry<Integer, AbstractConfigValue>>() {
|
||||
@Override
|
||||
public int compare(Map.Entry<Integer, AbstractConfigValue> a,
|
||||
Map.Entry<Integer, AbstractConfigValue> b) {
|
||||
return Integer.compare(a.getKey(), b.getKey());
|
||||
}
|
||||
});
|
||||
// drop the indices (we allow gaps in the indices, for better or
|
||||
// worse)
|
||||
ArrayList<AbstractConfigValue> list = new ArrayList<AbstractConfigValue>();
|
||||
for (Map.Entry<Integer, AbstractConfigValue> entry : entryList) {
|
||||
list.add(entry.getValue());
|
||||
}
|
||||
return new SimpleConfigList(value.origin(), list);
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
enum FromMapMode {
|
||||
KEYS_ARE_PATHS, KEYS_ARE_KEYS
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigIncluder;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigIncluderClasspath;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigIncluderFile;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigIncluderURL;
|
||||
|
||||
interface FullIncluder extends ConfigIncluder, ConfigIncluderFile, ConfigIncluderURL,
|
||||
ConfigIncluderClasspath {
|
||||
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
/** The key used to memoize already-traversed nodes when resolving substitutions */
|
||||
final class MemoKey {
|
||||
MemoKey(AbstractConfigValue value, Path restrictToChildOrNull) {
|
||||
this.value = value;
|
||||
this.restrictToChildOrNull = restrictToChildOrNull;
|
||||
}
|
||||
|
||||
final private AbstractConfigValue value;
|
||||
final private Path restrictToChildOrNull;
|
||||
|
||||
@Override
|
||||
public final int hashCode() {
|
||||
int h = System.identityHashCode(value);
|
||||
if (restrictToChildOrNull != null) {
|
||||
return h + 41 * (41 + restrictToChildOrNull.hashCode());
|
||||
} else {
|
||||
return h;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public final boolean equals(Object other) {
|
||||
if (other instanceof MemoKey) {
|
||||
MemoKey o = (MemoKey) other;
|
||||
if (o.value != this.value)
|
||||
return false;
|
||||
else if (o.restrictToChildOrNull == this.restrictToChildOrNull)
|
||||
return true;
|
||||
else if (o.restrictToChildOrNull == null || this.restrictToChildOrNull == null)
|
||||
return false;
|
||||
else
|
||||
return o.restrictToChildOrNull.equals(this.restrictToChildOrNull);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public final String toString() {
|
||||
return "MemoKey(" + value + "@" + System.identityHashCode(value) + "," + restrictToChildOrNull + ")";
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigMergeable;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue;
|
||||
|
||||
interface MergeableValue extends ConfigMergeable {
|
||||
// converts a Config to its root object and a ConfigValue to itself
|
||||
ConfigValue toFallbackValue();
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
// caution: ordinals used in serialization
|
||||
enum OriginType {
|
||||
GENERIC,
|
||||
FILE,
|
||||
URL,
|
||||
RESOURCE
|
||||
}
|
||||
+891
@@ -0,0 +1,891 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FilterReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
import java.io.StringReader;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.util.*;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigIncludeContext;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigObject;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigParseOptions;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigParseable;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigSyntax;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValue;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.parser.ConfigDocument;
|
||||
|
||||
/**
|
||||
* Internal implementation detail, not ABI stable, do not touch.
|
||||
* For use only by the {@link com.typesafe.config} package.
|
||||
* The point of this class is to avoid "propagating" each
|
||||
* overload on "thing which can be parsed" through multiple
|
||||
* interfaces. Most interfaces can have just one overload that
|
||||
* takes a Parseable. Also it's used as an abstract "resource
|
||||
* handle" in the ConfigIncluder interface.
|
||||
*/
|
||||
public abstract class Parseable implements ConfigParseable {
|
||||
private ConfigIncludeContext includeContext;
|
||||
private ConfigParseOptions initialOptions;
|
||||
private ConfigOrigin initialOrigin;
|
||||
|
||||
/**
|
||||
* Internal implementation detail, not ABI stable, do not touch.
|
||||
*/
|
||||
protected interface Relativizer {
|
||||
ConfigParseable relativeTo(String filename);
|
||||
}
|
||||
|
||||
private static final ThreadLocal<LinkedList<Parseable>> parseStack = new ThreadLocal<LinkedList<Parseable>>() {
|
||||
@Override
|
||||
protected LinkedList<Parseable> initialValue() {
|
||||
return new LinkedList<Parseable>();
|
||||
}
|
||||
};
|
||||
|
||||
private static final int MAX_INCLUDE_DEPTH = 50;
|
||||
|
||||
protected Parseable() {
|
||||
}
|
||||
|
||||
private ConfigParseOptions fixupOptions(ConfigParseOptions baseOptions) {
|
||||
ConfigSyntax syntax = baseOptions.getSyntax();
|
||||
if (syntax == null) {
|
||||
syntax = guessSyntax();
|
||||
}
|
||||
if (syntax == null) {
|
||||
syntax = ConfigSyntax.CONF;
|
||||
}
|
||||
ConfigParseOptions modified = baseOptions.setSyntax(syntax);
|
||||
|
||||
// make sure the app-provided includer falls back to default
|
||||
modified = modified.appendIncluder(ConfigImpl.defaultIncluder());
|
||||
// make sure the app-provided includer is complete
|
||||
modified = modified.setIncluder(SimpleIncluder.makeFull(modified.getIncluder()));
|
||||
|
||||
return modified;
|
||||
}
|
||||
|
||||
protected void postConstruct(ConfigParseOptions baseOptions) {
|
||||
this.initialOptions = fixupOptions(baseOptions);
|
||||
|
||||
this.includeContext = new SimpleIncludeContext(this);
|
||||
|
||||
if (initialOptions.getOriginDescription() != null)
|
||||
initialOrigin = SimpleConfigOrigin.newSimple(initialOptions.getOriginDescription());
|
||||
else
|
||||
initialOrigin = createOrigin();
|
||||
}
|
||||
|
||||
// the general idea is that any work should be in here, not in the
|
||||
// constructor, so that exceptions are thrown from the public parse()
|
||||
// function and not from the creation of the Parseable.
|
||||
// Essentially this is a lazy field. The parser should close the
|
||||
// reader when it's done with it.
|
||||
// ALSO, IMPORTANT: if the file or URL is not found, this must throw.
|
||||
// to support the "allow missing" feature.
|
||||
protected abstract Reader reader() throws IOException;
|
||||
|
||||
protected Reader reader(ConfigParseOptions options) throws IOException {
|
||||
return reader();
|
||||
}
|
||||
|
||||
protected static void trace(String message) {
|
||||
if (ConfigImpl.traceLoadsEnabled()) {
|
||||
ConfigImpl.trace(message);
|
||||
}
|
||||
}
|
||||
|
||||
ConfigSyntax guessSyntax() {
|
||||
return null;
|
||||
}
|
||||
|
||||
ConfigSyntax contentType() {
|
||||
return null;
|
||||
}
|
||||
|
||||
ConfigParseable relativeTo(String filename) {
|
||||
// fall back to classpath; we treat the "filename" as absolute
|
||||
// (don't add a package name in front),
|
||||
// if it starts with "/" then remove the "/", for consistency
|
||||
// with ParseableResources.relativeTo
|
||||
String resource = filename;
|
||||
if (filename.startsWith("/"))
|
||||
resource = filename.substring(1);
|
||||
return newResources(resource, options().setOriginDescription(null));
|
||||
}
|
||||
|
||||
ConfigIncludeContext includeContext() {
|
||||
return includeContext;
|
||||
}
|
||||
|
||||
static AbstractConfigObject forceParsedToObject(ConfigValue value) {
|
||||
if (value instanceof AbstractConfigObject) {
|
||||
return (AbstractConfigObject) value;
|
||||
} else {
|
||||
throw new ConfigException.WrongType(value.origin(), "", "object at file root", value
|
||||
.valueType().name());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigObject parse(ConfigParseOptions baseOptions) {
|
||||
|
||||
LinkedList<Parseable> stack = parseStack.get();
|
||||
if (stack.size() >= MAX_INCLUDE_DEPTH) {
|
||||
throw new ConfigException.Parse(initialOrigin, "include statements nested more than "
|
||||
+ MAX_INCLUDE_DEPTH
|
||||
+ " times, you probably have a cycle in your includes. Trace: " + stack);
|
||||
}
|
||||
|
||||
stack.addFirst(this);
|
||||
try {
|
||||
return forceParsedToObject(parseValue(baseOptions));
|
||||
} finally {
|
||||
stack.removeFirst();
|
||||
if (stack.isEmpty()) {
|
||||
parseStack.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final AbstractConfigValue parseValue(ConfigParseOptions baseOptions) {
|
||||
// note that we are NOT using our "initialOptions",
|
||||
// but using the ones from the passed-in options. The idea is that
|
||||
// callers can get our original options and then parse with different
|
||||
// ones if they want.
|
||||
ConfigParseOptions options = fixupOptions(baseOptions);
|
||||
|
||||
// passed-in options can override origin
|
||||
ConfigOrigin origin;
|
||||
if (options.getOriginDescription() != null)
|
||||
origin = SimpleConfigOrigin.newSimple(options.getOriginDescription());
|
||||
else
|
||||
origin = initialOrigin;
|
||||
return parseValue(origin, options);
|
||||
}
|
||||
|
||||
final private AbstractConfigValue parseValue(ConfigOrigin origin,
|
||||
ConfigParseOptions finalOptions) {
|
||||
try {
|
||||
return rawParseValue(origin, finalOptions);
|
||||
} catch (IOException e) {
|
||||
if (finalOptions.getAllowMissing()) {
|
||||
trace(e.getMessage() + ". Allowing Missing File, this can be turned off by setting" +
|
||||
" ConfigParseOptions.allowMissing = false");
|
||||
return SimpleConfigObject.emptyMissing(origin);
|
||||
} else {
|
||||
trace("exception loading " + origin.description() + ": " + e.getClass().getName()
|
||||
+ ": " + e.getMessage());
|
||||
throw new ConfigException.IO(origin,
|
||||
e.getClass().getName() + ": " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final ConfigDocument parseDocument(ConfigParseOptions baseOptions) {
|
||||
// note that we are NOT using our "initialOptions",
|
||||
// but using the ones from the passed-in options. The idea is that
|
||||
// callers can get our original options and then parse with different
|
||||
// ones if they want.
|
||||
ConfigParseOptions options = fixupOptions(baseOptions);
|
||||
|
||||
// passed-in options can override origin
|
||||
ConfigOrigin origin;
|
||||
if (options.getOriginDescription() != null)
|
||||
origin = SimpleConfigOrigin.newSimple(options.getOriginDescription());
|
||||
else
|
||||
origin = initialOrigin;
|
||||
return parseDocument(origin, options);
|
||||
}
|
||||
|
||||
final private ConfigDocument parseDocument(ConfigOrigin origin,
|
||||
ConfigParseOptions finalOptions) {
|
||||
try {
|
||||
return rawParseDocument(origin, finalOptions);
|
||||
} catch (IOException e) {
|
||||
if (finalOptions.getAllowMissing()) {
|
||||
ArrayList<AbstractConfigNode> children = new ArrayList<AbstractConfigNode>();
|
||||
children.add(new ConfigNodeObject(new ArrayList<AbstractConfigNode>()));
|
||||
return new SimpleConfigDocument(new ConfigNodeRoot(children, origin), finalOptions);
|
||||
} else {
|
||||
trace("exception loading " + origin.description() + ": " + e.getClass().getName()
|
||||
+ ": " + e.getMessage());
|
||||
throw new ConfigException.IO(origin,
|
||||
e.getClass().getName() + ": " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// this is parseValue without post-processing the IOException or handling
|
||||
// options.getAllowMissing()
|
||||
protected AbstractConfigValue rawParseValue(ConfigOrigin origin, ConfigParseOptions finalOptions)
|
||||
throws IOException {
|
||||
Reader reader = reader(finalOptions);
|
||||
|
||||
// after reader() we will have loaded the Content-Type.
|
||||
ConfigSyntax contentType = contentType();
|
||||
|
||||
ConfigParseOptions optionsWithContentType;
|
||||
if (contentType != null) {
|
||||
if (ConfigImpl.traceLoadsEnabled() && finalOptions.getSyntax() != null)
|
||||
trace("Overriding syntax " + finalOptions.getSyntax()
|
||||
+ " with Content-Type which specified " + contentType);
|
||||
|
||||
optionsWithContentType = finalOptions.setSyntax(contentType);
|
||||
} else {
|
||||
optionsWithContentType = finalOptions;
|
||||
}
|
||||
|
||||
try {
|
||||
return rawParseValue(reader, origin, optionsWithContentType);
|
||||
} finally {
|
||||
reader.close();
|
||||
}
|
||||
}
|
||||
|
||||
private AbstractConfigValue rawParseValue(Reader reader, ConfigOrigin origin,
|
||||
ConfigParseOptions finalOptions) throws IOException {
|
||||
if (finalOptions.getSyntax() == ConfigSyntax.PROPERTIES) {
|
||||
return PropertiesParser.parse(reader, origin);
|
||||
} else {
|
||||
Iterator<Token> tokens = Tokenizer.tokenize(origin, reader, finalOptions.getSyntax());
|
||||
ConfigNodeRoot document = ConfigDocumentParser.parse(tokens, origin, finalOptions);
|
||||
return ConfigParser.parse(document, origin, finalOptions, includeContext());
|
||||
}
|
||||
}
|
||||
|
||||
// this is parseDocument without post-processing the IOException or handling
|
||||
// options.getAllowMissing()
|
||||
protected ConfigDocument rawParseDocument(ConfigOrigin origin, ConfigParseOptions finalOptions)
|
||||
throws IOException {
|
||||
Reader reader = reader(finalOptions);
|
||||
|
||||
// after reader() we will have loaded the Content-Type.
|
||||
ConfigSyntax contentType = contentType();
|
||||
|
||||
ConfigParseOptions optionsWithContentType;
|
||||
if (contentType != null) {
|
||||
if (ConfigImpl.traceLoadsEnabled() && finalOptions.getSyntax() != null)
|
||||
trace("Overriding syntax " + finalOptions.getSyntax()
|
||||
+ " with Content-Type which specified " + contentType);
|
||||
|
||||
optionsWithContentType = finalOptions.setSyntax(contentType);
|
||||
} else {
|
||||
optionsWithContentType = finalOptions;
|
||||
}
|
||||
|
||||
try {
|
||||
return rawParseDocument(reader, origin, optionsWithContentType);
|
||||
} finally {
|
||||
reader.close();
|
||||
}
|
||||
}
|
||||
|
||||
private ConfigDocument rawParseDocument(Reader reader, ConfigOrigin origin,
|
||||
ConfigParseOptions finalOptions) throws IOException {
|
||||
Iterator<Token> tokens = Tokenizer.tokenize(origin, reader, finalOptions.getSyntax());
|
||||
return new SimpleConfigDocument(ConfigDocumentParser.parse(tokens, origin, finalOptions), finalOptions);
|
||||
}
|
||||
|
||||
public ConfigObject parse() {
|
||||
return forceParsedToObject(parseValue(options()));
|
||||
}
|
||||
|
||||
public ConfigDocument parseConfigDocument() {
|
||||
return parseDocument(options());
|
||||
}
|
||||
|
||||
AbstractConfigValue parseValue() {
|
||||
return parseValue(options());
|
||||
}
|
||||
|
||||
@Override
|
||||
public final ConfigOrigin origin() {
|
||||
return initialOrigin;
|
||||
}
|
||||
|
||||
protected abstract ConfigOrigin createOrigin();
|
||||
|
||||
@Override
|
||||
public ConfigParseOptions options() {
|
||||
return initialOptions;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getClass().getSimpleName();
|
||||
}
|
||||
|
||||
private static ConfigSyntax syntaxFromExtension(String name) {
|
||||
if (name.endsWith(".json"))
|
||||
return ConfigSyntax.JSON;
|
||||
else if (name.endsWith(".conf"))
|
||||
return ConfigSyntax.CONF;
|
||||
else if (name.endsWith(".properties"))
|
||||
return ConfigSyntax.PROPERTIES;
|
||||
else
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Reader readerFromStream(InputStream input) {
|
||||
return readerFromStream(input, "UTF-8");
|
||||
}
|
||||
|
||||
private static Reader readerFromStream(InputStream input, String encoding) {
|
||||
try {
|
||||
// well, this is messed up. If we aren't going to close
|
||||
// the passed-in InputStream then we have no way to
|
||||
// close these readers. So maybe we should not have an
|
||||
// InputStream version, only a Reader version.
|
||||
Reader reader = new InputStreamReader(input, encoding);
|
||||
return new BufferedReader(reader);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new ConfigException.BugOrBroken("Java runtime does not support UTF-8", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static Reader doNotClose(Reader input) {
|
||||
return new FilterReader(input) {
|
||||
@Override
|
||||
public void close() {
|
||||
// NOTHING.
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
static URL relativeTo(URL url, String filename) {
|
||||
// I'm guessing this completely fails on Windows, help wanted
|
||||
if (new File(filename).isAbsolute())
|
||||
return null;
|
||||
|
||||
try {
|
||||
URI siblingURI = url.toURI();
|
||||
URI relative = new URI(filename);
|
||||
|
||||
// this seems wrong, but it's documented that the last
|
||||
// element of the path in siblingURI gets stripped out,
|
||||
// so to get something in the same directory as
|
||||
// siblingURI we just call resolve().
|
||||
URL resolved = siblingURI.resolve(relative).toURL();
|
||||
|
||||
return resolved;
|
||||
} catch (MalformedURLException e) {
|
||||
return null;
|
||||
} catch (URISyntaxException e) {
|
||||
return null;
|
||||
} catch (IllegalArgumentException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static File relativeTo(File file, String filename) {
|
||||
File child = new File(filename);
|
||||
|
||||
if (child.isAbsolute())
|
||||
return null;
|
||||
|
||||
File parent = file.getParentFile();
|
||||
|
||||
if (parent == null)
|
||||
return null;
|
||||
else
|
||||
return new File(parent, filename);
|
||||
}
|
||||
|
||||
// this is a parseable that doesn't exist and just throws when you try to
|
||||
// parse it
|
||||
private final static class ParseableNotFound extends Parseable {
|
||||
final private String what;
|
||||
final private String message;
|
||||
|
||||
ParseableNotFound(String what, String message, ConfigParseOptions options) {
|
||||
this.what = what;
|
||||
this.message = message;
|
||||
postConstruct(options);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Reader reader() throws IOException {
|
||||
throw new FileNotFoundException(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigOrigin createOrigin() {
|
||||
return SimpleConfigOrigin.newSimple(what);
|
||||
}
|
||||
}
|
||||
|
||||
public static Parseable newNotFound(String whatNotFound, String message,
|
||||
ConfigParseOptions options) {
|
||||
return new ParseableNotFound(whatNotFound, message, options);
|
||||
}
|
||||
|
||||
private final static class ParseableReader extends Parseable {
|
||||
final private Reader reader;
|
||||
|
||||
ParseableReader(Reader reader, ConfigParseOptions options) {
|
||||
this.reader = reader;
|
||||
postConstruct(options);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Reader reader() {
|
||||
if (ConfigImpl.traceLoadsEnabled())
|
||||
trace("Loading config from reader " + reader);
|
||||
return reader;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigOrigin createOrigin() {
|
||||
return SimpleConfigOrigin.newSimple("Reader");
|
||||
}
|
||||
}
|
||||
|
||||
// note that we will never close this reader; you have to do it when parsing
|
||||
// is complete.
|
||||
public static Parseable newReader(Reader reader, ConfigParseOptions options) {
|
||||
|
||||
return new ParseableReader(doNotClose(reader), options);
|
||||
}
|
||||
|
||||
private final static class ParseableString extends Parseable {
|
||||
final private String input;
|
||||
|
||||
ParseableString(String input, ConfigParseOptions options) {
|
||||
this.input = input;
|
||||
postConstruct(options);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Reader reader() {
|
||||
if (ConfigImpl.traceLoadsEnabled())
|
||||
trace("Loading config from a String " + input);
|
||||
return new StringReader(input);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigOrigin createOrigin() {
|
||||
return SimpleConfigOrigin.newSimple("String");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getClass().getSimpleName() + "(" + input + ")";
|
||||
}
|
||||
}
|
||||
|
||||
public static Parseable newString(String input, ConfigParseOptions options) {
|
||||
return new ParseableString(input, options);
|
||||
}
|
||||
|
||||
private static final String jsonContentType = "application/json";
|
||||
private static final String propertiesContentType = "text/x-java-properties";
|
||||
private static final String hoconContentType = "application/hocon";
|
||||
|
||||
private static class ParseableURL extends Parseable {
|
||||
final protected URL input;
|
||||
private String contentType = null;
|
||||
|
||||
protected ParseableURL(URL input) {
|
||||
this.input = input;
|
||||
// does not postConstruct (subclass does it)
|
||||
}
|
||||
|
||||
ParseableURL(URL input, ConfigParseOptions options) {
|
||||
this(input);
|
||||
postConstruct(options);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Reader reader() throws IOException {
|
||||
throw new ConfigException.BugOrBroken("reader() without options should not be called on ParseableURL");
|
||||
}
|
||||
|
||||
private static String acceptContentType(ConfigParseOptions options) {
|
||||
if (options.getSyntax() == null)
|
||||
return null;
|
||||
|
||||
switch (options.getSyntax()) {
|
||||
case JSON:
|
||||
return jsonContentType;
|
||||
case CONF:
|
||||
return hoconContentType;
|
||||
case PROPERTIES:
|
||||
return propertiesContentType;
|
||||
}
|
||||
|
||||
// not sure this is reachable but javac thinks it is
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Reader reader(ConfigParseOptions options) throws IOException {
|
||||
try {
|
||||
if (ConfigImpl.traceLoadsEnabled())
|
||||
trace("Loading config from a URL: " + input.toExternalForm());
|
||||
URLConnection connection = input.openConnection();
|
||||
|
||||
// allow server to serve multiple types from one URL
|
||||
String acceptContent = acceptContentType(options);
|
||||
if (acceptContent != null) {
|
||||
connection.setRequestProperty("Accept", acceptContent);
|
||||
}
|
||||
|
||||
connection.connect();
|
||||
|
||||
// save content type for later
|
||||
contentType = connection.getContentType();
|
||||
if (contentType != null) {
|
||||
if (ConfigImpl.traceLoadsEnabled())
|
||||
trace("URL sets Content-Type: '" + contentType + "'");
|
||||
contentType = contentType.trim();
|
||||
int semi = contentType.indexOf(';');
|
||||
if (semi >= 0)
|
||||
contentType = contentType.substring(0, semi);
|
||||
}
|
||||
|
||||
InputStream stream = connection.getInputStream();
|
||||
|
||||
return readerFromStream(stream);
|
||||
} catch (FileNotFoundException fnf) {
|
||||
// If the resource is not found (HTTP response
|
||||
// code 404 or something alike), then it's fine to
|
||||
// treat it according to the allowMissing setting
|
||||
// and "include" spec. But if we have something
|
||||
// like HTTP 503 it seems to be better to fail
|
||||
// early, because this may be a sign of broken
|
||||
// environment. Java throws FileNotFoundException
|
||||
// if it sees 404 or 410.
|
||||
throw fnf;
|
||||
} catch (IOException e) {
|
||||
throw new ConfigException.BugOrBroken("Cannot load config from URL: " + input.toExternalForm(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
ConfigSyntax guessSyntax() {
|
||||
return syntaxFromExtension(input.getPath());
|
||||
}
|
||||
|
||||
@Override
|
||||
ConfigSyntax contentType() {
|
||||
if (contentType != null) {
|
||||
if (contentType.equals(jsonContentType))
|
||||
return ConfigSyntax.JSON;
|
||||
else if (contentType.equals(propertiesContentType))
|
||||
return ConfigSyntax.PROPERTIES;
|
||||
else if (contentType.equals(hoconContentType))
|
||||
return ConfigSyntax.CONF;
|
||||
else {
|
||||
if (ConfigImpl.traceLoadsEnabled())
|
||||
trace("'" + contentType + "' isn't a known content type");
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
ConfigParseable relativeTo(String filename) {
|
||||
URL url = relativeTo(input, filename);
|
||||
if (url == null)
|
||||
return null;
|
||||
return newURL(url, options().setOriginDescription(null));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigOrigin createOrigin() {
|
||||
return SimpleConfigOrigin.newURL(input);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getClass().getSimpleName() + "(" + input.toExternalForm() + ")";
|
||||
}
|
||||
}
|
||||
|
||||
public static Parseable newURL(URL input, ConfigParseOptions options) {
|
||||
// we want file: URLs and files to always behave the same, so switch
|
||||
// to a file if it's a file: URL
|
||||
if (input.getProtocol().equals("file")) {
|
||||
return newFile(ConfigImplUtil.urlToFile(input), options);
|
||||
} else {
|
||||
return new ParseableURL(input, options);
|
||||
}
|
||||
}
|
||||
|
||||
private final static class ParseableFile extends Parseable {
|
||||
final private File input;
|
||||
|
||||
ParseableFile(File input, ConfigParseOptions options) {
|
||||
this.input = input;
|
||||
postConstruct(options);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Reader reader() throws IOException {
|
||||
if (ConfigImpl.traceLoadsEnabled())
|
||||
trace("Loading config from a file: " + input);
|
||||
InputStream stream = new FileInputStream(input);
|
||||
return readerFromStream(stream);
|
||||
}
|
||||
|
||||
@Override
|
||||
ConfigSyntax guessSyntax() {
|
||||
return syntaxFromExtension(input.getName());
|
||||
}
|
||||
|
||||
@Override
|
||||
ConfigParseable relativeTo(String filename) {
|
||||
File sibling;
|
||||
if ((new File(filename)).isAbsolute()) {
|
||||
sibling = new File(filename);
|
||||
} else {
|
||||
// this may return null
|
||||
sibling = relativeTo(input, filename);
|
||||
}
|
||||
if (sibling == null)
|
||||
return null;
|
||||
if (sibling.exists()) {
|
||||
trace(sibling + " exists, so loading it as a file");
|
||||
return newFile(sibling, options().setOriginDescription(null));
|
||||
} else {
|
||||
trace(sibling + " does not exist, so trying it as a classpath resource");
|
||||
return super.relativeTo(filename);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigOrigin createOrigin() {
|
||||
return SimpleConfigOrigin.newFile(input.getPath());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getClass().getSimpleName() + "(" + input.getPath() + ")";
|
||||
}
|
||||
}
|
||||
|
||||
public static Parseable newFile(File input, ConfigParseOptions options) {
|
||||
return new ParseableFile(input, options);
|
||||
}
|
||||
|
||||
|
||||
private final static class ParseableResourceURL extends ParseableURL {
|
||||
|
||||
private final Relativizer relativizer;
|
||||
private final String resource;
|
||||
|
||||
ParseableResourceURL(URL input, ConfigParseOptions options, String resource, Relativizer relativizer) {
|
||||
super(input);
|
||||
this.relativizer = relativizer;
|
||||
this.resource = resource;
|
||||
postConstruct(options);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigOrigin createOrigin() {
|
||||
return SimpleConfigOrigin.newResource(resource, input);
|
||||
}
|
||||
|
||||
@Override
|
||||
ConfigParseable relativeTo(String filename) {
|
||||
return relativizer.relativeTo(filename);
|
||||
}
|
||||
}
|
||||
|
||||
private static Parseable newResourceURL(URL input, ConfigParseOptions options, String resource, Relativizer relativizer) {
|
||||
return new ParseableResourceURL(input, options, resource, relativizer);
|
||||
}
|
||||
|
||||
private final static class ParseableResources extends Parseable implements Relativizer {
|
||||
final private String resource;
|
||||
|
||||
ParseableResources(String resource, ConfigParseOptions options) {
|
||||
this.resource = resource;
|
||||
postConstruct(options);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Reader reader() throws IOException {
|
||||
throw new ConfigException.BugOrBroken("reader() should not be called on resources");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected AbstractConfigObject rawParseValue(ConfigOrigin origin,
|
||||
ConfigParseOptions finalOptions) throws IOException {
|
||||
ClassLoader loader = finalOptions.getClassLoader();
|
||||
if (loader == null)
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"null class loader; pass in a class loader or use Thread.currentThread().setContextClassLoader()");
|
||||
Enumeration<URL> e = loader.getResources(resource);
|
||||
if (!e.hasMoreElements()) {
|
||||
if (ConfigImpl.traceLoadsEnabled())
|
||||
trace("Loading config from class loader " + loader
|
||||
+ " but there were no resources called " + resource);
|
||||
throw new IOException("resource not found on classpath: " + resource);
|
||||
}
|
||||
AbstractConfigObject merged = SimpleConfigObject.empty(origin);
|
||||
while (e.hasMoreElements()) {
|
||||
URL url = e.nextElement();
|
||||
|
||||
if (ConfigImpl.traceLoadsEnabled())
|
||||
trace("Loading config from resource '" + resource + "' URL " + url.toExternalForm() + " from class loader "
|
||||
+ loader);
|
||||
|
||||
Parseable element = newResourceURL(url, finalOptions, resource, this);
|
||||
|
||||
AbstractConfigValue v = element.parseValue();
|
||||
|
||||
merged = merged.withFallback(v);
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
|
||||
@Override
|
||||
ConfigSyntax guessSyntax() {
|
||||
return syntaxFromExtension(resource);
|
||||
}
|
||||
|
||||
static String parent(String resource) {
|
||||
// the "resource" is not supposed to begin with a "/"
|
||||
// because it's supposed to be the raw resource
|
||||
// (ClassLoader#getResource), not the
|
||||
// resource "syntax" (Class#getResource)
|
||||
int i = resource.lastIndexOf('/');
|
||||
if (i < 0) {
|
||||
return null;
|
||||
} else {
|
||||
return resource.substring(0, i);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigParseable relativeTo(String sibling) {
|
||||
if (sibling.startsWith("/")) {
|
||||
// if it starts with "/" then don't make it relative to
|
||||
// the including resource
|
||||
return newResources(sibling.substring(1), options().setOriginDescription(null));
|
||||
} else {
|
||||
// here we want to build a new resource name and let
|
||||
// the class loader have it, rather than getting the
|
||||
// url with getResource() and relativizing to that url.
|
||||
// This is needed in case the class loader is going to
|
||||
// search a classpath.
|
||||
String parent = parent(resource);
|
||||
if (parent == null)
|
||||
return newResources(sibling, options().setOriginDescription(null));
|
||||
else
|
||||
return newResources(parent + "/" + sibling, options()
|
||||
.setOriginDescription(null));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigOrigin createOrigin() {
|
||||
return SimpleConfigOrigin.newResource(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getClass().getSimpleName() + "(" + resource + ")";
|
||||
}
|
||||
}
|
||||
|
||||
public static Parseable newResources(Class<?> klass, String resource, ConfigParseOptions options) {
|
||||
return newResources(convertResourceName(klass, resource),
|
||||
options.setClassLoader(klass.getClassLoader()));
|
||||
}
|
||||
|
||||
// this function is supposed to emulate the difference
|
||||
// between Class.getResource and ClassLoader.getResource
|
||||
// (unfortunately there doesn't seem to be public API for it).
|
||||
// We're using it because the Class API is more limited,
|
||||
// for example it lacks getResources(). So we want to be able to
|
||||
// use ClassLoader directly.
|
||||
private static String convertResourceName(Class<?> klass, String resource) {
|
||||
if (resource.startsWith("/")) {
|
||||
// "absolute" resource, chop the slash
|
||||
return resource.substring(1);
|
||||
} else {
|
||||
String className = klass.getName();
|
||||
int i = className.lastIndexOf('.');
|
||||
if (i < 0) {
|
||||
// no package
|
||||
return resource;
|
||||
} else {
|
||||
// need to be relative to the package
|
||||
String packageName = className.substring(0, i);
|
||||
String packagePath = packageName.replace('.', '/');
|
||||
return packagePath + "/" + resource;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static Parseable newResources(String resource, ConfigParseOptions options) {
|
||||
if (options.getClassLoader() == null)
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"null class loader; pass in a class loader or use Thread.currentThread().setContextClassLoader()");
|
||||
return new ParseableResources(resource, options);
|
||||
}
|
||||
|
||||
private final static class ParseableProperties extends Parseable {
|
||||
final private Properties props;
|
||||
|
||||
ParseableProperties(Properties props, ConfigParseOptions options) {
|
||||
this.props = props;
|
||||
postConstruct(options);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Reader reader() throws IOException {
|
||||
throw new ConfigException.BugOrBroken("reader() should not be called on props");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected AbstractConfigObject rawParseValue(ConfigOrigin origin,
|
||||
ConfigParseOptions finalOptions) {
|
||||
if (ConfigImpl.traceLoadsEnabled())
|
||||
trace("Loading config from properties " + props);
|
||||
return PropertiesParser.fromProperties(origin, props);
|
||||
}
|
||||
|
||||
@Override
|
||||
ConfigSyntax guessSyntax() {
|
||||
return ConfigSyntax.PROPERTIES;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigOrigin createOrigin() {
|
||||
return SimpleConfigOrigin.newSimple("properties");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getClass().getSimpleName() + "(" + props.size() + " props)";
|
||||
}
|
||||
}
|
||||
|
||||
public static Parseable newProperties(Properties properties, ConfigParseOptions options) {
|
||||
return new ParseableProperties(properties, options);
|
||||
}
|
||||
}
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
|
||||
final class Path {
|
||||
|
||||
final private String first;
|
||||
final private Path remainder;
|
||||
|
||||
Path(String first, Path remainder) {
|
||||
this.first = first;
|
||||
this.remainder = remainder;
|
||||
}
|
||||
|
||||
Path(String... elements) {
|
||||
if (elements.length == 0)
|
||||
throw new ConfigException.BugOrBroken("empty path");
|
||||
this.first = elements[0];
|
||||
if (elements.length > 1) {
|
||||
PathBuilder pb = new PathBuilder();
|
||||
for (int i = 1; i < elements.length; ++i) {
|
||||
pb.appendKey(elements[i]);
|
||||
}
|
||||
this.remainder = pb.result();
|
||||
} else {
|
||||
this.remainder = null;
|
||||
}
|
||||
}
|
||||
|
||||
// append all the paths in the list together into one path
|
||||
Path(List<Path> pathsToConcat) {
|
||||
this(pathsToConcat.iterator());
|
||||
}
|
||||
|
||||
// append all the paths in the iterator together into one path
|
||||
Path(Iterator<Path> i) {
|
||||
if (!i.hasNext())
|
||||
throw new ConfigException.BugOrBroken("empty path");
|
||||
|
||||
Path firstPath = i.next();
|
||||
this.first = firstPath.first;
|
||||
|
||||
PathBuilder pb = new PathBuilder();
|
||||
if (firstPath.remainder != null) {
|
||||
pb.appendPath(firstPath.remainder);
|
||||
}
|
||||
while (i.hasNext()) {
|
||||
pb.appendPath(i.next());
|
||||
}
|
||||
this.remainder = pb.result();
|
||||
}
|
||||
|
||||
String first() {
|
||||
return first;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return path minus the first element or null if no more elements
|
||||
*/
|
||||
Path remainder() {
|
||||
return remainder;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return path minus the last element or null if we have just one element
|
||||
*/
|
||||
Path parent() {
|
||||
if (remainder == null)
|
||||
return null;
|
||||
|
||||
PathBuilder pb = new PathBuilder();
|
||||
Path p = this;
|
||||
while (p.remainder != null) {
|
||||
pb.appendKey(p.first);
|
||||
p = p.remainder;
|
||||
}
|
||||
return pb.result();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return last element in the path
|
||||
*/
|
||||
String last() {
|
||||
Path p = this;
|
||||
while (p.remainder != null) {
|
||||
p = p.remainder;
|
||||
}
|
||||
return p.first;
|
||||
}
|
||||
|
||||
Path prepend(Path toPrepend) {
|
||||
PathBuilder pb = new PathBuilder();
|
||||
pb.appendPath(toPrepend);
|
||||
pb.appendPath(this);
|
||||
return pb.result();
|
||||
}
|
||||
|
||||
int length() {
|
||||
int count = 1;
|
||||
Path p = remainder;
|
||||
while (p != null) {
|
||||
count += 1;
|
||||
p = p.remainder;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
Path subPath(int removeFromFront) {
|
||||
int count = removeFromFront;
|
||||
Path p = this;
|
||||
while (p != null && count > 0) {
|
||||
count -= 1;
|
||||
p = p.remainder;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
Path subPath(int firstIndex, int lastIndex) {
|
||||
if (lastIndex < firstIndex)
|
||||
throw new ConfigException.BugOrBroken("bad call to subPath");
|
||||
|
||||
Path from = subPath(firstIndex);
|
||||
PathBuilder pb = new PathBuilder();
|
||||
int count = lastIndex - firstIndex;
|
||||
while (count > 0) {
|
||||
count -= 1;
|
||||
pb.appendKey(from.first());
|
||||
from = from.remainder();
|
||||
if (from == null)
|
||||
throw new ConfigException.BugOrBroken("subPath lastIndex out of range " + lastIndex);
|
||||
}
|
||||
return pb.result();
|
||||
}
|
||||
|
||||
boolean startsWith(Path other) {
|
||||
Path myRemainder = this;
|
||||
Path otherRemainder = other;
|
||||
if (otherRemainder.length() <= myRemainder.length()) {
|
||||
while(otherRemainder != null) {
|
||||
if (!otherRemainder.first().equals(myRemainder.first()))
|
||||
return false;
|
||||
myRemainder = myRemainder.remainder();
|
||||
otherRemainder = otherRemainder.remainder();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (other instanceof Path) {
|
||||
Path that = (Path) other;
|
||||
return this.first.equals(that.first)
|
||||
&& ConfigImplUtil.equalsHandlingNull(this.remainder,
|
||||
that.remainder);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return 41 * (41 + first.hashCode())
|
||||
+ (remainder == null ? 0 : remainder.hashCode());
|
||||
}
|
||||
|
||||
// this doesn't have a very precise meaning, just to reduce
|
||||
// noise from quotes in the rendered path for average cases
|
||||
static boolean hasFunkyChars(String s) {
|
||||
int length = s.length();
|
||||
|
||||
if (length == 0)
|
||||
return false;
|
||||
|
||||
for (int i = 0; i < length; ++i) {
|
||||
char c = s.charAt(i);
|
||||
|
||||
if (Character.isLetterOrDigit(c) || c == '-' || c == '_')
|
||||
continue;
|
||||
else
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void appendToStringBuilder(StringBuilder sb) {
|
||||
if (hasFunkyChars(first) || first.isEmpty())
|
||||
sb.append(ConfigImplUtil.renderJsonString(first));
|
||||
else
|
||||
sb.append(first);
|
||||
if (remainder != null) {
|
||||
sb.append(".");
|
||||
remainder.appendToStringBuilder(sb);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("Path(");
|
||||
appendToStringBuilder(sb);
|
||||
sb.append(")");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* toString() is a debugging-oriented version while this is an
|
||||
* error-message-oriented human-readable one.
|
||||
*/
|
||||
String render() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
appendToStringBuilder(sb);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
static Path newKey(String key) {
|
||||
return new Path(key, null);
|
||||
}
|
||||
|
||||
static Path newPath(String path) {
|
||||
return PathParser.parsePath(path);
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.util.Stack;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
|
||||
final class PathBuilder {
|
||||
// the keys are kept "backward" (top of stack is end of path)
|
||||
final private Stack<String> keys;
|
||||
private Path result;
|
||||
|
||||
PathBuilder() {
|
||||
keys = new Stack<String>();
|
||||
}
|
||||
|
||||
private void checkCanAppend() {
|
||||
if (result != null)
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"Adding to PathBuilder after getting result");
|
||||
}
|
||||
|
||||
void appendKey(String key) {
|
||||
checkCanAppend();
|
||||
|
||||
keys.push(key);
|
||||
}
|
||||
|
||||
void appendPath(Path path) {
|
||||
checkCanAppend();
|
||||
|
||||
String first = path.first();
|
||||
Path remainder = path.remainder();
|
||||
while (true) {
|
||||
keys.push(first);
|
||||
if (remainder != null) {
|
||||
first = remainder.first();
|
||||
remainder = remainder.remainder();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Path result() {
|
||||
// note: if keys is empty, we want to return null, which is a valid
|
||||
// empty path
|
||||
if (result == null) {
|
||||
Path remainder = null;
|
||||
while (!keys.isEmpty()) {
|
||||
String key = keys.pop();
|
||||
remainder = new Path(key, remainder);
|
||||
}
|
||||
result = remainder;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+281
@@ -0,0 +1,281 @@
|
||||
/**
|
||||
* Copyright (C) 2015 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigSyntax;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigValueType;
|
||||
|
||||
import java.io.StringReader;
|
||||
import java.util.*;
|
||||
|
||||
final class PathParser {
|
||||
static class Element {
|
||||
StringBuilder sb;
|
||||
// an element can be empty if it has a quoted empty string "" in it
|
||||
boolean canBeEmpty;
|
||||
|
||||
Element(String initial, boolean canBeEmpty) {
|
||||
this.canBeEmpty = canBeEmpty;
|
||||
this.sb = new StringBuilder(initial);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Element(" + sb.toString() + "," + canBeEmpty + ")";
|
||||
}
|
||||
}
|
||||
|
||||
static ConfigOrigin apiOrigin = SimpleConfigOrigin.newSimple("path parameter");
|
||||
|
||||
static ConfigNodePath parsePathNode(String path) {
|
||||
return parsePathNode(path, ConfigSyntax.CONF);
|
||||
}
|
||||
|
||||
static ConfigNodePath parsePathNode(String path, ConfigSyntax flavor) {
|
||||
StringReader reader = new StringReader(path);
|
||||
|
||||
try {
|
||||
Iterator<Token> tokens = Tokenizer.tokenize(apiOrigin, reader,
|
||||
flavor);
|
||||
tokens.next(); // drop START
|
||||
return parsePathNodeExpression(tokens, apiOrigin, path, flavor);
|
||||
} finally {
|
||||
reader.close();
|
||||
}
|
||||
}
|
||||
|
||||
static Path parsePath(String path) {
|
||||
Path speculated = speculativeFastParsePath(path);
|
||||
if (speculated != null)
|
||||
return speculated;
|
||||
|
||||
StringReader reader = new StringReader(path);
|
||||
|
||||
try {
|
||||
Iterator<Token> tokens = Tokenizer.tokenize(apiOrigin, reader,
|
||||
ConfigSyntax.CONF);
|
||||
tokens.next(); // drop START
|
||||
return parsePathExpression(tokens, apiOrigin, path);
|
||||
} finally {
|
||||
reader.close();
|
||||
}
|
||||
}
|
||||
|
||||
protected static Path parsePathExpression(Iterator<Token> expression,
|
||||
ConfigOrigin origin) {
|
||||
return parsePathExpression(expression, origin, null, null, ConfigSyntax.CONF);
|
||||
}
|
||||
|
||||
protected static Path parsePathExpression(Iterator<Token> expression,
|
||||
ConfigOrigin origin, String originalText) {
|
||||
return parsePathExpression(expression, origin, originalText, null, ConfigSyntax.CONF);
|
||||
}
|
||||
|
||||
protected static ConfigNodePath parsePathNodeExpression(Iterator<Token> expression,
|
||||
ConfigOrigin origin) {
|
||||
return parsePathNodeExpression(expression, origin, null, ConfigSyntax.CONF);
|
||||
}
|
||||
|
||||
protected static ConfigNodePath parsePathNodeExpression(Iterator<Token> expression,
|
||||
ConfigOrigin origin, String originalText, ConfigSyntax flavor) {
|
||||
ArrayList<Token> pathTokens = new ArrayList<Token>();
|
||||
Path path = parsePathExpression(expression, origin, originalText, pathTokens, flavor);
|
||||
return new ConfigNodePath(path, pathTokens);
|
||||
}
|
||||
|
||||
// originalText may be null if not available
|
||||
protected static Path parsePathExpression(Iterator<Token> expression,
|
||||
ConfigOrigin origin, String originalText,
|
||||
ArrayList<Token> pathTokens,
|
||||
ConfigSyntax flavor) {
|
||||
// each builder in "buf" is an element in the path.
|
||||
List<Element> buf = new ArrayList<Element>();
|
||||
buf.add(new Element("", false));
|
||||
|
||||
if (!expression.hasNext()) {
|
||||
throw new ConfigException.BadPath(origin, originalText,
|
||||
"Expecting a field name or path here, but got nothing");
|
||||
}
|
||||
|
||||
while (expression.hasNext()) {
|
||||
Token t = expression.next();
|
||||
|
||||
if (pathTokens != null)
|
||||
pathTokens.add(t);
|
||||
|
||||
// Ignore all IgnoredWhitespace tokens
|
||||
if (Tokens.isIgnoredWhitespace(t))
|
||||
continue;
|
||||
|
||||
if (Tokens.isValueWithType(t, ConfigValueType.STRING)) {
|
||||
AbstractConfigValue v = Tokens.getValue(t);
|
||||
// this is a quoted string; so any periods
|
||||
// in here don't count as path separators
|
||||
String s = v.transformToString();
|
||||
|
||||
addPathText(buf, true, s);
|
||||
} else if (t == Tokens.END) {
|
||||
// ignore this; when parsing a file, it should not happen
|
||||
// since we're parsing a token list rather than the main
|
||||
// token iterator, and when parsing a path expression from the
|
||||
// API, it's expected to have an END.
|
||||
} else {
|
||||
// any periods outside of a quoted string count as
|
||||
// separators
|
||||
String text;
|
||||
if (Tokens.isValue(t)) {
|
||||
// appending a number here may add
|
||||
// a period, but we _do_ count those as path
|
||||
// separators, because we basically want
|
||||
// "foo 3.0bar" to parse as a string even
|
||||
// though there's a number in it. The fact that
|
||||
// we tokenize non-string values is largely an
|
||||
// implementation detail.
|
||||
AbstractConfigValue v = Tokens.getValue(t);
|
||||
|
||||
// We need to split the tokens on a . so that we can get sub-paths but still preserve
|
||||
// the original path text when doing an insertion
|
||||
if (pathTokens != null) {
|
||||
pathTokens.remove(pathTokens.size() - 1);
|
||||
pathTokens.addAll(splitTokenOnPeriod(t, flavor));
|
||||
}
|
||||
text = v.transformToString();
|
||||
} else if (Tokens.isUnquotedText(t)) {
|
||||
// We need to split the tokens on a . so that we can get sub-paths but still preserve
|
||||
// the original path text when doing an insertion on ConfigNodeObjects
|
||||
if (pathTokens != null) {
|
||||
pathTokens.remove(pathTokens.size() - 1);
|
||||
pathTokens.addAll(splitTokenOnPeriod(t, flavor));
|
||||
}
|
||||
text = Tokens.getUnquotedText(t);
|
||||
} else {
|
||||
throw new ConfigException.BadPath(
|
||||
origin,
|
||||
originalText,
|
||||
"Token not allowed in path expression: "
|
||||
+ t
|
||||
+ " (you can double-quote this token if you really want it here)");
|
||||
}
|
||||
|
||||
addPathText(buf, false, text);
|
||||
}
|
||||
}
|
||||
|
||||
PathBuilder pb = new PathBuilder();
|
||||
for (Element e : buf) {
|
||||
if (e.sb.length() == 0 && !e.canBeEmpty) {
|
||||
throw new ConfigException.BadPath(
|
||||
origin,
|
||||
originalText,
|
||||
"path has a leading, trailing, or two adjacent period '.' (use quoted \"\" empty string if you want an empty element)");
|
||||
} else {
|
||||
pb.appendKey(e.sb.toString());
|
||||
}
|
||||
}
|
||||
|
||||
return pb.result();
|
||||
}
|
||||
|
||||
private static Collection<Token> splitTokenOnPeriod(Token t, ConfigSyntax flavor) {
|
||||
String tokenText = t.tokenText();
|
||||
if (tokenText.equals(".")) {
|
||||
return Collections.singletonList(t);
|
||||
}
|
||||
String[] splitToken = tokenText.split("\\.");
|
||||
ArrayList<Token> splitTokens = new ArrayList<Token>();
|
||||
for (String s : splitToken) {
|
||||
if (flavor == ConfigSyntax.CONF)
|
||||
splitTokens.add(Tokens.newUnquotedText(t.origin(), s));
|
||||
else
|
||||
splitTokens.add(Tokens.newString(t.origin(), s, "\"" + s + "\""));
|
||||
splitTokens.add(Tokens.newUnquotedText(t.origin(), "."));
|
||||
}
|
||||
if (tokenText.charAt(tokenText.length() - 1) != '.')
|
||||
splitTokens.remove(splitTokens.size() - 1);
|
||||
return splitTokens;
|
||||
}
|
||||
|
||||
private static void addPathText(List<Element> buf, boolean wasQuoted,
|
||||
String newText) {
|
||||
int i = wasQuoted ? -1 : newText.indexOf('.');
|
||||
Element current = buf.get(buf.size() - 1);
|
||||
if (i < 0) {
|
||||
// add to current path element
|
||||
current.sb.append(newText);
|
||||
// any empty quoted string means this element can
|
||||
// now be empty.
|
||||
if (wasQuoted && current.sb.length() == 0)
|
||||
current.canBeEmpty = true;
|
||||
} else {
|
||||
// "buf" plus up to the period is an element
|
||||
current.sb.append(newText.substring(0, i));
|
||||
// then start a new element
|
||||
buf.add(new Element("", false));
|
||||
// recurse to consume remainder of newText
|
||||
addPathText(buf, false, newText.substring(i + 1));
|
||||
}
|
||||
}
|
||||
|
||||
// the idea is to see if the string has any chars or features
|
||||
// that might require the full parser to deal with.
|
||||
private static boolean looksUnsafeForFastParser(String s) {
|
||||
boolean lastWasDot = true; // start of path is also a "dot"
|
||||
int len = s.length();
|
||||
if (s.isEmpty())
|
||||
return true;
|
||||
if (s.charAt(0) == '.')
|
||||
return true;
|
||||
if (s.charAt(len - 1) == '.')
|
||||
return true;
|
||||
|
||||
for (int i = 0; i < len; ++i) {
|
||||
char c = s.charAt(i);
|
||||
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_') {
|
||||
lastWasDot = false;
|
||||
continue;
|
||||
} else if (c == '.') {
|
||||
if (lastWasDot)
|
||||
return true; // ".." means we need to throw an error
|
||||
lastWasDot = true;
|
||||
} else if (c == '-') {
|
||||
if (lastWasDot)
|
||||
return true;
|
||||
continue;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (lastWasDot)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static Path fastPathBuild(Path tail, String s, int end) {
|
||||
// lastIndexOf takes last index it should look at, end - 1 not end
|
||||
int splitAt = s.lastIndexOf('.', end - 1);
|
||||
ArrayList<Token> tokens = new ArrayList<Token>();
|
||||
tokens.add(Tokens.newUnquotedText(null, s));
|
||||
// this works even if splitAt is -1; then we start the substring at 0
|
||||
Path withOneMoreElement = new Path(s.substring(splitAt + 1, end), tail);
|
||||
if (splitAt < 0) {
|
||||
return withOneMoreElement;
|
||||
} else {
|
||||
return fastPathBuild(withOneMoreElement, s, splitAt);
|
||||
}
|
||||
}
|
||||
|
||||
// do something much faster than the full parser if
|
||||
// we just have something like "foo" or "foo.bar"
|
||||
private static Path speculativeFastParsePath(String path) {
|
||||
String s = ConfigImplUtil.unicodeTrim(path);
|
||||
if (looksUnsafeForFastParser(s))
|
||||
return null;
|
||||
|
||||
return fastPathBuild(null, s, s.length());
|
||||
}
|
||||
}
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
/**
|
||||
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
|
||||
*/
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigOrigin;
|
||||
|
||||
final class PropertiesParser {
|
||||
static AbstractConfigObject parse(Reader reader,
|
||||
ConfigOrigin origin) throws IOException {
|
||||
Properties props = new Properties();
|
||||
props.load(reader);
|
||||
return fromProperties(origin, props);
|
||||
}
|
||||
|
||||
static String lastElement(String path) {
|
||||
int i = path.lastIndexOf('.');
|
||||
if (i < 0)
|
||||
return path;
|
||||
else
|
||||
return path.substring(i + 1);
|
||||
}
|
||||
|
||||
static String exceptLastElement(String path) {
|
||||
int i = path.lastIndexOf('.');
|
||||
if (i < 0)
|
||||
return null;
|
||||
else
|
||||
return path.substring(0, i);
|
||||
}
|
||||
|
||||
static Path pathFromPropertyKey(String key) {
|
||||
String last = lastElement(key);
|
||||
String exceptLast = exceptLastElement(key);
|
||||
Path path = new Path(last, null);
|
||||
while (exceptLast != null) {
|
||||
last = lastElement(exceptLast);
|
||||
exceptLast = exceptLastElement(exceptLast);
|
||||
path = new Path(last, path);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
static AbstractConfigObject fromProperties(ConfigOrigin origin,
|
||||
Properties props) {
|
||||
return fromEntrySet(origin, props.entrySet());
|
||||
}
|
||||
|
||||
private static <K, V> AbstractConfigObject fromEntrySet(ConfigOrigin origin, Set<Map.Entry<K, V>> entries) {
|
||||
final Map<Path, Object> pathMap = getPathMap(entries);
|
||||
return fromPathMap(origin, pathMap, true /* from properties */);
|
||||
}
|
||||
|
||||
private static <K, V> Map<Path, Object> getPathMap(Set<Map.Entry<K, V>> entries) {
|
||||
Map<Path, Object> pathMap = new HashMap<Path, Object>();
|
||||
for (Map.Entry<K, V> entry : entries) {
|
||||
Object key = entry.getKey();
|
||||
if (key instanceof String) {
|
||||
Path path = pathFromPropertyKey((String) key);
|
||||
pathMap.put(path, entry.getValue());
|
||||
}
|
||||
}
|
||||
return pathMap;
|
||||
}
|
||||
|
||||
static AbstractConfigObject fromStringMap(ConfigOrigin origin, Map<String, String> stringMap) {
|
||||
return fromEntrySet(origin, stringMap.entrySet());
|
||||
}
|
||||
|
||||
static AbstractConfigObject fromPathMap(ConfigOrigin origin,
|
||||
Map<?, ?> pathExpressionMap) {
|
||||
Map<Path, Object> pathMap = new HashMap<Path, Object>();
|
||||
for (Map.Entry<?, ?> entry : pathExpressionMap.entrySet()) {
|
||||
Object keyObj = entry.getKey();
|
||||
if (!(keyObj instanceof String)) {
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"Map has a non-string as a key, expecting a path expression as a String");
|
||||
}
|
||||
Path path = Path.newPath((String) keyObj);
|
||||
pathMap.put(path, entry.getValue());
|
||||
}
|
||||
return fromPathMap(origin, pathMap, false /* from properties */);
|
||||
}
|
||||
|
||||
private static AbstractConfigObject fromPathMap(ConfigOrigin origin,
|
||||
Map<Path, Object> pathMap, boolean convertedFromProperties) {
|
||||
/*
|
||||
* First, build a list of paths that will have values, either string or
|
||||
* object values.
|
||||
*/
|
||||
Set<Path> scopePaths = new HashSet<Path>();
|
||||
Set<Path> valuePaths = new HashSet<Path>();
|
||||
for (Path path : pathMap.keySet()) {
|
||||
// add value's path
|
||||
valuePaths.add(path);
|
||||
|
||||
// all parent paths are objects
|
||||
Path next = path.parent();
|
||||
while (next != null) {
|
||||
scopePaths.add(next);
|
||||
next = next.parent();
|
||||
}
|
||||
}
|
||||
|
||||
if (convertedFromProperties) {
|
||||
/*
|
||||
* If any string values are also objects containing other values,
|
||||
* drop those string values - objects "win".
|
||||
*/
|
||||
valuePaths.removeAll(scopePaths);
|
||||
} else {
|
||||
/* If we didn't start out as properties, then this is an error. */
|
||||
for (Path path : valuePaths) {
|
||||
if (scopePaths.contains(path)) {
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"In the map, path '"
|
||||
+ path.render()
|
||||
+ "' occurs as both the parent object of a value and as a value. "
|
||||
+ "Because Map has no defined ordering, this is a broken situation.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Create maps for the object-valued values.
|
||||
*/
|
||||
Map<String, AbstractConfigValue> root = new HashMap<String, AbstractConfigValue>();
|
||||
Map<Path, Map<String, AbstractConfigValue>> scopes = new HashMap<Path, Map<String, AbstractConfigValue>>();
|
||||
|
||||
for (Path path : scopePaths) {
|
||||
Map<String, AbstractConfigValue> scope = new HashMap<String, AbstractConfigValue>();
|
||||
scopes.put(path, scope);
|
||||
}
|
||||
|
||||
/* Store string values in the associated scope maps */
|
||||
for (Path path : valuePaths) {
|
||||
Path parentPath = path.parent();
|
||||
Map<String, AbstractConfigValue> parent = parentPath != null ? scopes
|
||||
.get(parentPath) : root;
|
||||
|
||||
String last = path.last();
|
||||
Object rawValue = pathMap.get(path);
|
||||
AbstractConfigValue value;
|
||||
if (convertedFromProperties) {
|
||||
if (rawValue instanceof String) {
|
||||
value = new ConfigString.Quoted(origin, (String) rawValue);
|
||||
} else {
|
||||
// silently ignore non-string values in Properties
|
||||
value = null;
|
||||
}
|
||||
} else {
|
||||
value = ConfigImpl.fromAnyRef(pathMap.get(path), origin,
|
||||
FromMapMode.KEYS_ARE_PATHS);
|
||||
}
|
||||
if (value != null)
|
||||
parent.put(last, value);
|
||||
}
|
||||
|
||||
/*
|
||||
* Make a list of scope paths from longest to shortest, so children go
|
||||
* before parents.
|
||||
*/
|
||||
List<Path> sortedScopePaths = new ArrayList<Path>();
|
||||
sortedScopePaths.addAll(scopePaths);
|
||||
// sort descending by length
|
||||
Collections.sort(sortedScopePaths, new Comparator<Path>() {
|
||||
@Override
|
||||
public int compare(Path a, Path b) {
|
||||
// Path.length() is O(n) so in theory this sucks
|
||||
// but in practice we can make Path precompute length
|
||||
// if it ever matters.
|
||||
return b.length() - a.length();
|
||||
}
|
||||
});
|
||||
|
||||
/*
|
||||
* Create ConfigObject for each scope map, working from children to
|
||||
* parents to avoid modifying any already-created ConfigObject. This is
|
||||
* where we need the sorted list.
|
||||
*/
|
||||
for (Path scopePath : sortedScopePaths) {
|
||||
Map<String, AbstractConfigValue> scope = scopes.get(scopePath);
|
||||
|
||||
Path parentPath = scopePath.parent();
|
||||
Map<String, AbstractConfigValue> parent = parentPath != null ? scopes
|
||||
.get(parentPath) : root;
|
||||
|
||||
AbstractConfigObject o = new SimpleConfigObject(origin, scope,
|
||||
ResolveStatus.RESOLVED, false /* ignoresFallbacks */);
|
||||
parent.put(scopePath.last(), o);
|
||||
}
|
||||
|
||||
// return root config object
|
||||
return new SimpleConfigObject(origin, root, ResolveStatus.RESOLVED,
|
||||
false /* ignoresFallbacks */);
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
/**
|
||||
* Implemented by a merge stack (ConfigDelayedMerge, ConfigDelayedMergeObject)
|
||||
* that replaces itself during substitution resolution in order to implement
|
||||
* "look backwards only" semantics.
|
||||
*/
|
||||
interface ReplaceableMergeStack extends Container {
|
||||
/**
|
||||
* Make a replacement for this object skipping the given number of elements
|
||||
* which are lower in merge priority.
|
||||
*/
|
||||
AbstractConfigValue makeReplacement(ResolveContext context, int skipping);
|
||||
}
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Set;
|
||||
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigException;
|
||||
import com.drtshock.playervaults.lib.com.typesafe.config.ConfigResolveOptions;
|
||||
|
||||
final class ResolveContext {
|
||||
final private ResolveMemos memos;
|
||||
|
||||
final private ConfigResolveOptions options;
|
||||
// the current path restriction, used to ensure lazy
|
||||
// resolution and avoid gratuitous cycles. without this,
|
||||
// any sibling of an object we're traversing could
|
||||
// cause a cycle "by side effect"
|
||||
// CAN BE NULL for a full resolve.
|
||||
final private Path restrictToChild;
|
||||
|
||||
// This is used for tracing and debugging and nice error messages;
|
||||
// contains every node as we call resolve on it.
|
||||
final private List<AbstractConfigValue> resolveStack;
|
||||
|
||||
final private Set<AbstractConfigValue> cycleMarkers;
|
||||
|
||||
ResolveContext(ResolveMemos memos, ConfigResolveOptions options, Path restrictToChild,
|
||||
List<AbstractConfigValue> resolveStack, Set<AbstractConfigValue> cycleMarkers) {
|
||||
this.memos = memos;
|
||||
this.options = options;
|
||||
this.restrictToChild = restrictToChild;
|
||||
this.resolveStack = Collections.unmodifiableList(resolveStack);
|
||||
this.cycleMarkers = Collections.unmodifiableSet(cycleMarkers);
|
||||
}
|
||||
|
||||
private static Set<AbstractConfigValue> newCycleMarkers() {
|
||||
return Collections.newSetFromMap(new IdentityHashMap<AbstractConfigValue, Boolean>());
|
||||
}
|
||||
|
||||
ResolveContext(ConfigResolveOptions options, Path restrictToChild) {
|
||||
// LinkedHashSet keeps the traversal order which is at least useful
|
||||
// in error messages if nothing else
|
||||
this(new ResolveMemos(), options, restrictToChild, new ArrayList<AbstractConfigValue>(), newCycleMarkers());
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(depth(), "ResolveContext restrict to child " + restrictToChild);
|
||||
}
|
||||
|
||||
ResolveContext addCycleMarker(AbstractConfigValue value) {
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(depth(), "++ Cycle marker " + value + "@" + System.identityHashCode(value));
|
||||
if (cycleMarkers.contains(value))
|
||||
throw new ConfigException.BugOrBroken("Added cycle marker twice " + value);
|
||||
Set<AbstractConfigValue> copy = newCycleMarkers();
|
||||
copy.addAll(cycleMarkers);
|
||||
copy.add(value);
|
||||
return new ResolveContext(memos, options, restrictToChild, resolveStack, copy);
|
||||
}
|
||||
|
||||
ResolveContext removeCycleMarker(AbstractConfigValue value) {
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(depth(), "-- Cycle marker " + value + "@" + System.identityHashCode(value));
|
||||
|
||||
Set<AbstractConfigValue> copy = newCycleMarkers();
|
||||
copy.addAll(cycleMarkers);
|
||||
copy.remove(value);
|
||||
return new ResolveContext(memos, options, restrictToChild, resolveStack, copy);
|
||||
}
|
||||
|
||||
private ResolveContext memoize(MemoKey key, AbstractConfigValue value) {
|
||||
ResolveMemos changed = memos.put(key, value);
|
||||
return new ResolveContext(changed, options, restrictToChild, resolveStack, cycleMarkers);
|
||||
}
|
||||
|
||||
ConfigResolveOptions options() {
|
||||
return options;
|
||||
}
|
||||
|
||||
boolean isRestrictedToChild() {
|
||||
return restrictToChild != null;
|
||||
}
|
||||
|
||||
Path restrictToChild() {
|
||||
return restrictToChild;
|
||||
}
|
||||
|
||||
// restrictTo may be null to unrestrict
|
||||
ResolveContext restrict(Path restrictTo) {
|
||||
if (restrictTo == restrictToChild)
|
||||
return this;
|
||||
else
|
||||
return new ResolveContext(memos, options, restrictTo, resolveStack, cycleMarkers);
|
||||
}
|
||||
|
||||
ResolveContext unrestricted() {
|
||||
return restrict(null);
|
||||
}
|
||||
|
||||
String traceString() {
|
||||
String separator = ", ";
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (AbstractConfigValue value : resolveStack) {
|
||||
if (value instanceof ConfigReference) {
|
||||
sb.append(((ConfigReference) value).expression().toString());
|
||||
sb.append(separator);
|
||||
}
|
||||
}
|
||||
if (sb.length() > 0)
|
||||
sb.setLength(sb.length() - separator.length());
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private ResolveContext pushTrace(AbstractConfigValue value) {
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(depth(), "pushing trace " + value);
|
||||
List<AbstractConfigValue> copy = new ArrayList<AbstractConfigValue>(resolveStack);
|
||||
copy.add(value);
|
||||
return new ResolveContext(memos, options, restrictToChild, copy, cycleMarkers);
|
||||
}
|
||||
|
||||
ResolveContext popTrace() {
|
||||
List<AbstractConfigValue> copy = new ArrayList<AbstractConfigValue>(resolveStack);
|
||||
AbstractConfigValue old = copy.remove(resolveStack.size() - 1);
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(depth() - 1, "popped trace " + old);
|
||||
return new ResolveContext(memos, options, restrictToChild, copy, cycleMarkers);
|
||||
}
|
||||
|
||||
int depth() {
|
||||
if (resolveStack.size() > 30)
|
||||
throw new ConfigException.BugOrBroken("resolve getting too deep");
|
||||
return resolveStack.size();
|
||||
}
|
||||
|
||||
ResolveResult<? extends AbstractConfigValue> resolve(AbstractConfigValue original, ResolveSource source)
|
||||
throws AbstractConfigValue.NotPossibleToResolve {
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl
|
||||
.trace(depth(), "resolving " + original + " restrictToChild=" + restrictToChild + " in " + source);
|
||||
return pushTrace(original).realResolve(original, source).popTrace();
|
||||
}
|
||||
|
||||
private ResolveResult<? extends AbstractConfigValue> realResolve(AbstractConfigValue original, ResolveSource source)
|
||||
throws AbstractConfigValue.NotPossibleToResolve {
|
||||
// a fully-resolved (no restrictToChild) object can satisfy a
|
||||
// request for a restricted object, so always check that first.
|
||||
final MemoKey fullKey = new MemoKey(original, null);
|
||||
MemoKey restrictedKey = null;
|
||||
|
||||
AbstractConfigValue cached = memos.get(fullKey);
|
||||
|
||||
// but if there was no fully-resolved object cached, we'll only
|
||||
// compute the restrictToChild object so use a more limited
|
||||
// memo key
|
||||
if (cached == null && isRestrictedToChild()) {
|
||||
restrictedKey = new MemoKey(original, restrictToChild());
|
||||
cached = memos.get(restrictedKey);
|
||||
}
|
||||
|
||||
if (cached != null) {
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(depth(), "using cached resolution " + cached + " for " + original
|
||||
+ " restrictToChild " + restrictToChild());
|
||||
return ResolveResult.make(this, cached);
|
||||
} else {
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(depth(),
|
||||
"not found in cache, resolving " + original + "@" + System.identityHashCode(original));
|
||||
|
||||
if (cycleMarkers.contains(original)) {
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(depth(),
|
||||
"Cycle detected, can't resolve; " + original + "@" + System.identityHashCode(original));
|
||||
throw new AbstractConfigValue.NotPossibleToResolve(this);
|
||||
}
|
||||
|
||||
ResolveResult<? extends AbstractConfigValue> result = original.resolveSubstitutions(this, source);
|
||||
AbstractConfigValue resolved = result.value;
|
||||
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(depth(), "resolved to " + resolved + "@" + System.identityHashCode(resolved)
|
||||
+ " from " + original + "@" + System.identityHashCode(resolved));
|
||||
|
||||
ResolveContext withMemo = result.context;
|
||||
|
||||
if (resolved == null || resolved.resolveStatus() == ResolveStatus.RESOLVED) {
|
||||
// if the resolved object is fully resolved by resolving
|
||||
// only the restrictToChildOrNull, then it can be cached
|
||||
// under fullKey since the child we were restricted to
|
||||
// turned out to be the only unresolved thing.
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(depth(), "caching " + fullKey + " result " + resolved);
|
||||
|
||||
withMemo = withMemo.memoize(fullKey, resolved);
|
||||
} else {
|
||||
// if we have an unresolved object then either we did a
|
||||
// partial resolve restricted to a certain child, or we are
|
||||
// allowing incomplete resolution, or it's a bug.
|
||||
if (isRestrictedToChild()) {
|
||||
if (restrictedKey == null) {
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"restrictedKey should not be null here");
|
||||
}
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(depth(), "caching " + restrictedKey + " result " + resolved);
|
||||
|
||||
withMemo = withMemo.memoize(restrictedKey, resolved);
|
||||
} else if (options().getAllowUnresolved()) {
|
||||
if (ConfigImpl.traceSubstitutionsEnabled())
|
||||
ConfigImpl.trace(depth(), "caching " + fullKey + " result " + resolved);
|
||||
|
||||
withMemo = withMemo.memoize(fullKey, resolved);
|
||||
} else {
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"resolveSubstitutions() did not give us a resolved object");
|
||||
}
|
||||
}
|
||||
|
||||
return ResolveResult.make(withMemo, resolved);
|
||||
}
|
||||
}
|
||||
|
||||
static AbstractConfigValue resolve(AbstractConfigValue value, AbstractConfigObject root,
|
||||
ConfigResolveOptions options) {
|
||||
ResolveSource source = new ResolveSource(root);
|
||||
ResolveContext context = new ResolveContext(options, null /* restrictToChild */);
|
||||
|
||||
try {
|
||||
return context.resolve(value, source).value;
|
||||
} catch (AbstractConfigValue.NotPossibleToResolve e) {
|
||||
// ConfigReference was supposed to catch NotPossibleToResolve
|
||||
throw new ConfigException.BugOrBroken(
|
||||
"NotPossibleToResolve was thrown from an outermost resolve", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.drtshock.playervaults.lib.com.typesafe.config.impl;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* This exists because we have to memoize resolved substitutions as we go
|
||||
* through the config tree; otherwise we could end up creating multiple copies
|
||||
* of values or whole trees of values as we follow chains of substitutions.
|
||||
*/
|
||||
final class ResolveMemos {
|
||||
// note that we can resolve things to undefined (represented as Java null,
|
||||
// rather than ConfigNull) so this map can have null values.
|
||||
final private Map<MemoKey, AbstractConfigValue> memos;
|
||||
|
||||
private ResolveMemos(Map<MemoKey, AbstractConfigValue> memos) {
|
||||
this.memos = memos;
|
||||
}
|
||||
|
||||
ResolveMemos() {
|
||||
this(new HashMap<MemoKey, AbstractConfigValue>());
|
||||
}
|
||||
|
||||
AbstractConfigValue get(MemoKey key) {
|
||||
return memos.get(key);
|
||||
}
|
||||
|
||||
ResolveMemos put(MemoKey key, AbstractConfigValue value) {
|
||||
// completely inefficient, but so far nobody cares about resolve()
|
||||
// performance, we can clean it up someday...
|
||||
Map<MemoKey, AbstractConfigValue> copy = new HashMap<MemoKey, AbstractConfigValue>(memos);
|
||||
copy.put(key, value);
|
||||
return new ResolveMemos(copy);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user