mirror of
https://e.coding.net/circlecloud/RealBackpacks.git
synced 2024-12-04 03:49:07 +00:00
init project...
Signed-off-by: j502647092 <jtb1@163.com>
This commit is contained in:
commit
98b244f452
40
.gitignore
vendored
Normal file
40
.gitignore
vendored
Normal file
@ -0,0 +1,40 @@
|
||||
# Eclipse stuff
|
||||
/.classpath
|
||||
/.project
|
||||
/.settings
|
||||
|
||||
# netbeans
|
||||
/nbproject
|
||||
|
||||
# we use maven!
|
||||
/build.xml
|
||||
|
||||
# maven
|
||||
/target
|
||||
/repo
|
||||
|
||||
# vim
|
||||
.*.sw[a-p]
|
||||
|
||||
# various other potential build files
|
||||
/build
|
||||
/bin
|
||||
/dist
|
||||
/manifest.mf
|
||||
|
||||
/world
|
||||
|
||||
# Mac filesystem dust
|
||||
*.DS_Store
|
||||
|
||||
# intellij
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.idea/
|
||||
|
||||
# Project Stuff
|
||||
/src/main/resources/Soulbound
|
||||
|
||||
# Atlassian Stuff
|
||||
/atlassian-ide-plugin.xml
|
BIN
lib/Vault.jar
Normal file
BIN
lib/Vault.jar
Normal file
Binary file not shown.
59
pom.xml
Normal file
59
pom.xml
Normal file
@ -0,0 +1,59 @@
|
||||
<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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>cn.CityCraft</groupId>
|
||||
<artifactId>RealBackpacks</artifactId>
|
||||
<version>0.1.1-SNAPSHOT</version>
|
||||
<name>RealBackpacks</name>
|
||||
<build>
|
||||
<sourceDirectory>src</sourceDirectory>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src</directory>
|
||||
<excludes>
|
||||
<exclude>**/*.java</exclude>
|
||||
</excludes>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.1</version>
|
||||
<configuration>
|
||||
<source>1.7</source>
|
||||
<target>1.7</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>spigot-repo</id>
|
||||
<url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.spigotmc</groupId>
|
||||
<artifactId>spigot-api</artifactId>
|
||||
<type>jar</type>
|
||||
<version>1.8.3-R0.1-SNAPSHOT</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.CityCraft</groupId>
|
||||
<artifactId>BVLib</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<type>jar</type>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.milkbowl.vault</groupId>
|
||||
<artifactId>VaultAPI</artifactId>
|
||||
<version>1.5</version>
|
||||
<scope>system</scope>
|
||||
<systemPath>${project.basedir}/lib/Vault.jar</systemPath>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
</project>
|
495
src/cn/citycraft/plugins/MainCommand.java
Normal file
495
src/cn/citycraft/plugins/MainCommand.java
Normal file
@ -0,0 +1,495 @@
|
||||
package cn.citycraft.plugins;
|
||||
|
||||
import java.io.File;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandExecutor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import cn.citycraft.plugins.util.MysqlFunctions;
|
||||
import cn.citycraft.plugins.util.RBUtil;
|
||||
import cn.citycraft.plugins.util.Serialization;
|
||||
|
||||
public class MainCommand implements CommandExecutor {
|
||||
|
||||
private final RealBackpacks plugin;
|
||||
|
||||
private boolean exist = false;
|
||||
|
||||
private String[] helps = new String[]{
|
||||
"§6====== 真实背包插件 By:喵♂呜 ======",
|
||||
"§4* §a查看可购买列表 §7/rb list ",
|
||||
"§4* §a购买背包 §7/rb buy <背包名称> ",
|
||||
"§4* §a给玩家指定背包 §7/rb give <玩家名称> <背包名称>",
|
||||
"§4* §a查看玩家指定背包 §7/rb view <玩家名称> <背包名称>" ,
|
||||
"§4* §a数据转移至MySQL §7/rb filetomysql"
|
||||
};
|
||||
|
||||
public MainCommand(final RealBackpacks plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("deprecation")
|
||||
public boolean onCommand(final CommandSender sender, final Command cmd,
|
||||
final String label, final String[] args) {
|
||||
if (cmd.getName().equalsIgnoreCase("rb")) {
|
||||
if (args.length == 0) {
|
||||
sender.sendMessage(helps);
|
||||
}
|
||||
if (args.length >= 1) {
|
||||
final String command = args[0];
|
||||
if (command.equalsIgnoreCase("reload")) {
|
||||
if (plugin.isUsingPerms()
|
||||
&& !sender.hasPermission("rb.reload")) {
|
||||
sender.sendMessage(ChatColor.RED + "没有足够的权限购买");
|
||||
return false;
|
||||
}
|
||||
final Long first = System.currentTimeMillis();
|
||||
plugin.reloadConfig();
|
||||
plugin.setupLists();
|
||||
plugin.getServer().resetRecipes();
|
||||
plugin.setup();
|
||||
sender.sendMessage(ChatColor.GRAY + "配置文件重载.");
|
||||
sender.sendMessage(ChatColor.GRAY + "用时 "
|
||||
+ ChatColor.YELLOW
|
||||
+ (System.currentTimeMillis() - first) + "毫秒"
|
||||
+ ChatColor.GRAY + ".");
|
||||
return true;
|
||||
} else if (command.equalsIgnoreCase("buy")
|
||||
|| command.equalsIgnoreCase("purchase")) {
|
||||
if (!plugin.isUsingVault()) {
|
||||
sender.sendMessage(ChatColor.RED
|
||||
+ "当前命令无法使用,因为没有安装经济插件.");
|
||||
return false;
|
||||
}
|
||||
if (!(sender instanceof Player)) {
|
||||
sender.sendMessage(ChatColor.RED + "控制台不能使用此命令.");
|
||||
return false;
|
||||
}
|
||||
if (!(args.length == 2)) {
|
||||
sender.sendMessage(ChatColor.RED + "命令错误. 正确命令:"
|
||||
+ ChatColor.GRAY + " /rb buy <backpack>");
|
||||
return false;
|
||||
}
|
||||
String backpack = null;
|
||||
backpack = RBUtil.stringToBackpack(args[1]);
|
||||
if (backpack == null) {
|
||||
sender.sendMessage("背包不存在.");
|
||||
return false;
|
||||
}
|
||||
if (plugin.isUsingPerms()
|
||||
&& !sender.hasPermission("rb." + backpack + ".buy")) {
|
||||
sender.sendMessage("没有购买的权限.");
|
||||
return false;
|
||||
}
|
||||
if (plugin.backpackData.get(backpack).get(13) != null
|
||||
&& !plugin.backpackData.get(backpack).get(13)
|
||||
.equals("true")) {
|
||||
sender.sendMessage("不能被购买.");
|
||||
return false;
|
||||
}
|
||||
final double price = Double.parseDouble(plugin.backpackData
|
||||
.get(backpack).get(14));
|
||||
if (RealBackpacks.econ.getBalance(sender.getName()) < price) {
|
||||
sender.sendMessage(ChatColor.RED + "你没有足够的钱购买这个背包.");
|
||||
return false;
|
||||
}
|
||||
final Player p = (Player) sender;
|
||||
final Inventory inv = p.getInventory();
|
||||
final ItemStack backpackItem = plugin.backpackItems
|
||||
.get(backpack);
|
||||
if (inv.firstEmpty() != -1) {
|
||||
RealBackpacks.econ.withdrawPlayer(p.getName(),
|
||||
price);
|
||||
if (plugin.backpackData.get(backpack).get(18) != null
|
||||
&& plugin.backpackData.get(backpack).get(18)
|
||||
.equalsIgnoreCase("true")) {
|
||||
if (RealBackpacks.globalGlow
|
||||
&& plugin.backpackData.get(backpack)
|
||||
.get(17) != null
|
||||
&& plugin.backpackData.get(backpack)
|
||||
.get(17).equalsIgnoreCase("true")) {
|
||||
inv.setItem(inv.firstEmpty(),
|
||||
RealBackpacks.NMS
|
||||
.addGlow(backpackItem));
|
||||
} else {
|
||||
inv.setItem(inv.firstEmpty(), backpackItem);
|
||||
}
|
||||
} else {
|
||||
if (RealBackpacks.globalGlow
|
||||
&& plugin.backpackData.get(backpack)
|
||||
.get(17) != null
|
||||
&& plugin.backpackData.get(backpack)
|
||||
.get(17).equalsIgnoreCase("true")) {
|
||||
inv.addItem(RealBackpacks.NMS
|
||||
.addGlow(backpackItem));
|
||||
} else {
|
||||
inv.addItem(backpackItem);
|
||||
}
|
||||
}
|
||||
p.updateInventory();
|
||||
sender.sendMessage(ChatColor.GREEN + "你花费了 "
|
||||
+ ChatColor.GOLD + price + ChatColor.GREEN
|
||||
+ " 购买了背包: " + ChatColor.GOLD + backpack);
|
||||
return true;
|
||||
} else {
|
||||
sender.sendMessage(ChatColor.RED + "你的背包是空的.");
|
||||
return false;
|
||||
}
|
||||
} else if (command.equalsIgnoreCase("list")) {
|
||||
if (plugin.isUsingPerms()
|
||||
&& !sender.hasPermission("rb.list")) {
|
||||
sender.sendMessage(ChatColor.RED + "你没有此命令的权限!");
|
||||
return false;
|
||||
}
|
||||
sender.sendMessage(ChatColor.LIGHT_PURPLE + " 名称 "
|
||||
+ ChatColor.GOLD + "|" + ChatColor.AQUA + " 大小 "
|
||||
+ ChatColor.GOLD + "|" + ChatColor.GREEN + " 价格 ");
|
||||
sender.sendMessage(ChatColor.GOLD
|
||||
+ "-----------------------------------");
|
||||
if (plugin.isUsingPerms()) {
|
||||
for (final String backpack : plugin.backpacks) {
|
||||
final boolean hasPerm = sender.hasPermission("rb."
|
||||
+ backpack + ".buy");
|
||||
final List<String> key = plugin.backpackData
|
||||
.get(backpack);
|
||||
if (plugin.backpackData.get(backpack).get(13)
|
||||
.equalsIgnoreCase("true")
|
||||
&& hasPerm) {
|
||||
sender.sendMessage(ChatColor.LIGHT_PURPLE
|
||||
+ backpack + ChatColor.GOLD + " | "
|
||||
+ ChatColor.AQUA + key.get(0)
|
||||
+ ChatColor.GOLD + " | "
|
||||
+ ChatColor.GREEN
|
||||
+ Double.parseDouble(key.get(14)));
|
||||
} else if (plugin.backpackData.get(backpack)
|
||||
.get(13) != null
|
||||
&& !plugin.backpackData.get(backpack)
|
||||
.get(13).equalsIgnoreCase("true")
|
||||
&& hasPerm) {
|
||||
sender.sendMessage(ChatColor.LIGHT_PURPLE
|
||||
+ backpack + ChatColor.GOLD + " | "
|
||||
+ ChatColor.AQUA + key.get(0)
|
||||
+ ChatColor.GOLD + " | "
|
||||
+ ChatColor.RED + "不能购买");
|
||||
} else {
|
||||
sender.sendMessage(ChatColor.LIGHT_PURPLE
|
||||
+ backpack + ChatColor.GOLD + " | "
|
||||
+ ChatColor.AQUA + key.get(0)
|
||||
+ ChatColor.GOLD + " | "
|
||||
+ ChatColor.RED + "没有足够的权限购买");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (final String backpack : plugin.backpacks) {
|
||||
final List<String> key = plugin.backpackData
|
||||
.get(backpack);
|
||||
if (plugin.backpackData.get(backpack).get(13) != null
|
||||
&& plugin.backpackData.get(backpack)
|
||||
.get(13).equalsIgnoreCase("true")) {
|
||||
sender.sendMessage(ChatColor.LIGHT_PURPLE
|
||||
+ backpack + ChatColor.GOLD + " | "
|
||||
+ ChatColor.AQUA + key.get(0)
|
||||
+ ChatColor.GOLD + " | "
|
||||
+ ChatColor.GREEN
|
||||
+ Double.parseDouble(key.get(14)));
|
||||
} else {
|
||||
sender.sendMessage(ChatColor.LIGHT_PURPLE
|
||||
+ backpack + ChatColor.GOLD + " | "
|
||||
+ ChatColor.AQUA + key.get(0)
|
||||
+ ChatColor.GOLD + " | "
|
||||
+ ChatColor.RED + "不能购买");
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (command.equalsIgnoreCase("give")) {
|
||||
if (!(args.length == 3)) {
|
||||
sender.sendMessage(ChatColor.RED + "错误的命令. 正确方式:"
|
||||
+ ChatColor.GRAY + " /rb give <玩家> <背包名称>");
|
||||
return false;
|
||||
}
|
||||
String backpack = null;
|
||||
backpack = RBUtil.stringToBackpack(args[2]);
|
||||
if (plugin.isUsingPerms()
|
||||
&& !sender
|
||||
.hasPermission("rb." + backpack + ".give")) {
|
||||
sender.sendMessage(ChatColor.RED + "没有足够的权限");
|
||||
return false;
|
||||
}
|
||||
if (backpack == null) {
|
||||
sender.sendMessage(ChatColor.RED + "背包不存在");
|
||||
return false;
|
||||
}
|
||||
final Player other = plugin.getServer().getPlayer(args[1]);
|
||||
if (other == null) {
|
||||
sender.sendMessage(ChatColor.RED + "玩家不存在");
|
||||
return false;
|
||||
}
|
||||
final Inventory inv = other.getInventory();
|
||||
final ItemStack backpackItem = plugin.backpackItems
|
||||
.get(backpack);
|
||||
if (inv.firstEmpty() != -1) {
|
||||
if (plugin.backpackData.get(backpack).get(18) != null
|
||||
&& plugin.backpackData.get(backpack).get(18)
|
||||
.equalsIgnoreCase("true")) {
|
||||
if (RealBackpacks.globalGlow
|
||||
&& plugin.backpackData.get(backpack)
|
||||
.get(17) != null
|
||||
&& plugin.backpackData.get(backpack)
|
||||
.get(17).equalsIgnoreCase("true")) {
|
||||
inv.setItem(inv.firstEmpty(),
|
||||
RealBackpacks.NMS
|
||||
.addGlow(backpackItem));
|
||||
} else {
|
||||
inv.setItem(inv.firstEmpty(), backpackItem);
|
||||
}
|
||||
} else {
|
||||
if (RealBackpacks.globalGlow
|
||||
&& plugin.backpackData.get(backpack)
|
||||
.get(17) != null
|
||||
&& plugin.backpackData.get(backpack)
|
||||
.get(17).equalsIgnoreCase("true")) {
|
||||
inv.addItem(RealBackpacks.NMS
|
||||
.addGlow(backpackItem));
|
||||
} else {
|
||||
inv.addItem(backpackItem);
|
||||
}
|
||||
}
|
||||
other.updateInventory();
|
||||
sender.sendMessage(ChatColor.GREEN + "你把背包 "
|
||||
+ ChatColor.GOLD + backpack + ChatColor.GREEN
|
||||
+ " 发送给了 " + ChatColor.GOLD + other.getName());
|
||||
return true;
|
||||
} else {
|
||||
sender.sendMessage(ChatColor.RED + other.getName()
|
||||
+ "的背包已经满了");
|
||||
return false;
|
||||
}
|
||||
} else if (command.equalsIgnoreCase("filetomysql")) {
|
||||
if (plugin.isUsingPerms()
|
||||
&& !sender.hasPermission("rb.filetomysql")) {
|
||||
return false;
|
||||
}
|
||||
plugin.getServer().getScheduler()
|
||||
.runTaskAsynchronously(plugin, new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (!MysqlFunctions
|
||||
.checkIfTableExists("rb_data")) {
|
||||
MysqlFunctions.createTables();
|
||||
exist = false;
|
||||
} else {
|
||||
exist = true;
|
||||
}
|
||||
try {
|
||||
final Connection conn = DriverManager
|
||||
.getConnection(plugin.getUrl(),
|
||||
plugin.getUser(),
|
||||
plugin.getPass());
|
||||
final File dir = new File(plugin
|
||||
.getDataFolder()
|
||||
+ File.separator + "userdata");
|
||||
int i = 0, times = 0;
|
||||
final int files = dir.listFiles().length;
|
||||
for (final File child : dir.listFiles()) {
|
||||
final FileConfiguration config = YamlConfiguration
|
||||
.loadConfiguration(child);
|
||||
final String player = child
|
||||
.getName().replace(".yml",
|
||||
"");
|
||||
i++;
|
||||
PreparedStatement statement = null;
|
||||
PreparedStatement state = null;
|
||||
for (final String backpack : config
|
||||
.getConfigurationSection("")
|
||||
.getKeys(false)) {
|
||||
if (exist) {
|
||||
statement = conn
|
||||
.prepareStatement("SELECT EXISTS(SELECT 1 FROM rb_data WHERE player = ? AND backpack = ? LIMIT 1);");
|
||||
statement.setString(1,
|
||||
player);
|
||||
statement.setString(2,
|
||||
backpack);
|
||||
final ResultSet res = statement
|
||||
.executeQuery();
|
||||
if (res.next()) {
|
||||
if (res.getInt(1) == 1) {
|
||||
state = conn
|
||||
.prepareStatement("UPDATE rb_data SET player=?, backpack=?, inventory=? WHERE player=? AND backpack=?;");
|
||||
state.setString(1,
|
||||
player);
|
||||
state.setString(2,
|
||||
backpack);
|
||||
state.setString(
|
||||
3,
|
||||
Serialization
|
||||
.listToString(config
|
||||
.getStringList(backpack
|
||||
+ ".Inventory")));
|
||||
state.setString(4,
|
||||
player);
|
||||
state.setString(5,
|
||||
backpack);
|
||||
} else {
|
||||
state = conn
|
||||
.prepareStatement("INSERT INTO rb_data (player, backpack, inventory) VALUES(?, ?, ?);");
|
||||
state.setString(1,
|
||||
player);
|
||||
state.setString(2,
|
||||
backpack);
|
||||
state.setString(
|
||||
3,
|
||||
Serialization
|
||||
.listToString(config
|
||||
.getStringList(backpack
|
||||
+ ".Inventory")));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
state = conn
|
||||
.prepareStatement("INSERT INTO rb_data (player, backpack, inventory) VALUES(?, ?, ?);");
|
||||
state.setString(1, player);
|
||||
state.setString(2, backpack);
|
||||
state.setString(
|
||||
3,
|
||||
Serialization
|
||||
.listToString(config
|
||||
.getStringList(backpack
|
||||
+ ".Inventory")));
|
||||
}
|
||||
state.executeUpdate();
|
||||
state.close();
|
||||
}
|
||||
if (i == 50) {
|
||||
i = 0;
|
||||
times++;
|
||||
sender.sendMessage(ChatColor.LIGHT_PURPLE
|
||||
+ ""
|
||||
+ times
|
||||
* 50
|
||||
+ "/"
|
||||
+ files
|
||||
+ " files have been transferred.");
|
||||
}
|
||||
}
|
||||
conn.close();
|
||||
sender.sendMessage(ChatColor.LIGHT_PURPLE
|
||||
+ "数据转换完成.");
|
||||
} catch (final SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
} else if (command.equalsIgnoreCase("view")) {
|
||||
if (!(args.length == 3)) {
|
||||
sender.sendMessage(ChatColor.RED + "命令错误. 正确命令:"
|
||||
+ ChatColor.GRAY
|
||||
+ " /rb view <player> <backpack>");
|
||||
return false;
|
||||
}
|
||||
String backpack = null;
|
||||
backpack = RBUtil.stringToBackpack(args[2]);
|
||||
boolean fullview = false;
|
||||
boolean restrictedview = false;
|
||||
if (plugin.isUsingPerms()
|
||||
&& sender.hasPermission("rb.fullview")) {
|
||||
fullview = true;
|
||||
} else if (plugin.isUsingPerms()
|
||||
&& sender.hasPermission("rb.restrictedview")) {
|
||||
restrictedview = true;
|
||||
}
|
||||
if (plugin.isUsingPerms() && !fullview && !restrictedview) {
|
||||
sender.sendMessage(ChatColor.RED + "没有足够的权限购买");
|
||||
return false;
|
||||
}
|
||||
if (backpack == null) {
|
||||
sender.sendMessage(ChatColor.RED + "背包不存在");
|
||||
return false;
|
||||
}
|
||||
Inventory inv = null;
|
||||
String name = args[1];
|
||||
final Player p = (Player) sender;
|
||||
final List<String> key = plugin.backpackData.get(backpack);
|
||||
if (!plugin.isUsingMysql()) {
|
||||
boolean fileExists = false;
|
||||
String fullName = null;
|
||||
File file = null;
|
||||
final File dir = new File(plugin.getDataFolder()
|
||||
+ File.separator + "userdata");
|
||||
for (final File f : dir.listFiles()) {
|
||||
final String fileName = f.getName();
|
||||
fullName = fileName.replace(".yml", "");
|
||||
if (fullName.equalsIgnoreCase(name)) {
|
||||
name = fullName;
|
||||
file = f;
|
||||
fileExists = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!fileExists) {
|
||||
sender.sendMessage(ChatColor.RED
|
||||
+ "这货从来没打开过背包,所以是空的,2333.");
|
||||
return false;
|
||||
}
|
||||
final FileConfiguration config = YamlConfiguration
|
||||
.loadConfiguration(file);
|
||||
if (config.getStringList(backpack + ".Inventory") == null) {
|
||||
inv = plugin.getServer().createInventory(
|
||||
p,
|
||||
Integer.parseInt(key.get(0)),
|
||||
ChatColor.translateAlternateColorCodes('&',
|
||||
fullName + "'s " + backpack
|
||||
+ " data"));
|
||||
} else {
|
||||
inv = Serialization.toInventory(
|
||||
config.getStringList(backpack
|
||||
+ ".Inventory"), fullName + "'s "
|
||||
+ backpack + " data",
|
||||
Integer.parseInt(key.get(0)));
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
inv = MysqlFunctions.getBackpackInv(name, backpack);
|
||||
} catch (final SQLException e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
if (inv == null) {
|
||||
sender.sendMessage(ChatColor.RED
|
||||
+ "这货从来没打开过背包,所以是空的,2333.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (plugin.playerData.containsKey(name)) {
|
||||
sender.sendMessage(ChatColor.RED + "玩家打开了背包,请等待玩家关闭.");
|
||||
return false;
|
||||
}
|
||||
if (fullview || !plugin.isUsingPerms()) {
|
||||
plugin.adminFullView.put(sender.getName(), backpack
|
||||
+ ":" + name);
|
||||
} else {
|
||||
plugin.adminRestrictedView.add(sender.getName());
|
||||
}
|
||||
p.openInventory(inv);
|
||||
} else {
|
||||
sender.sendMessage(ChatColor.RED + "命令未找到.");
|
||||
sender.sendMessage(helps);
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
14
src/cn/citycraft/plugins/RBInterface.java
Normal file
14
src/cn/citycraft/plugins/RBInterface.java
Normal file
@ -0,0 +1,14 @@
|
||||
package cn.citycraft.plugins;
|
||||
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
public interface RBInterface {
|
||||
|
||||
public String inventoryToString(Inventory inventory);
|
||||
|
||||
public Inventory stringToInventory(String data, String name);
|
||||
|
||||
public ItemStack addGlow(ItemStack item);
|
||||
|
||||
}
|
452
src/cn/citycraft/plugins/RealBackpacks.java
Normal file
452
src/cn/citycraft/plugins/RealBackpacks.java
Normal file
@ -0,0 +1,452 @@
|
||||
package cn.citycraft.plugins;
|
||||
|
||||
import java.io.File;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
import net.milkbowl.vault.economy.Economy;
|
||||
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.ShapedRecipe;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.material.MaterialData;
|
||||
import org.bukkit.plugin.RegisteredServiceProvider;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
import cn.citycraft.plugins.listeners.CraftListener;
|
||||
import cn.citycraft.plugins.listeners.EntityListener;
|
||||
import cn.citycraft.plugins.listeners.InventoryListener;
|
||||
import cn.citycraft.plugins.listeners.PlayerListener;
|
||||
import cn.citycraft.plugins.util.MysqlFunctions;
|
||||
import cn.citycraft.plugins.util.RBUtil;
|
||||
|
||||
public class RealBackpacks extends JavaPlugin {
|
||||
|
||||
@Override
|
||||
public FileConfiguration getConfig() {
|
||||
// TODO 自动生成的方法存根
|
||||
return super.getConfig();
|
||||
}
|
||||
|
||||
public static RBInterface NMS;
|
||||
|
||||
public static Economy econ = null;
|
||||
public static boolean globalGlow = true;
|
||||
|
||||
private boolean usingMysql = false;
|
||||
private boolean vault = true;
|
||||
private boolean usingPermissions = true;
|
||||
private static boolean average = false;
|
||||
private static boolean add = false;
|
||||
private String user = null;
|
||||
private String password = null;
|
||||
private String url;
|
||||
|
||||
public List<String> backpacks = new ArrayList<String>();
|
||||
public HashMap<String, List<String>> backpackData = new HashMap<String, List<String>>();
|
||||
public HashMap<String, List<String>> backpackLore = new HashMap<String, List<String>>();
|
||||
public HashMap<String, List<String>> backpackRecipe = new HashMap<String, List<String>>();
|
||||
public HashMap<String, ItemStack> backpackItems = new HashMap<String, ItemStack>();
|
||||
public HashMap<String, ItemStack> backpackOverrides = new HashMap<String, ItemStack>();
|
||||
public HashMap<String, List<String>> backpackBlacklist = new HashMap<String, List<String>>();
|
||||
public HashMap<String, List<String>> backpackWhitelist = new HashMap<String, List<String>>();
|
||||
|
||||
public HashMap<String, String> playerData = new HashMap<String, String>();
|
||||
public HashMap<String, String> adminFullView = new HashMap<String, String>();
|
||||
public List<String> adminRestrictedView = new ArrayList<String>();
|
||||
public List<String> slowedPlayers = new ArrayList<String>();
|
||||
|
||||
/*
|
||||
* List key ---------
|
||||
* 0 =Size
|
||||
* 1 = UseRecipe
|
||||
* 2 = id
|
||||
* 3 = name
|
||||
* 4 =destroyContents
|
||||
* 5 = dropContents
|
||||
* 6 = dropBackpack
|
||||
* 7 = keepBackpack
|
||||
* 8 =walkSpeedEnabled
|
||||
* 9 = walkSpeedMultiplier
|
||||
* 10 = increasedHungerEnabled
|
||||
* 11 =hungerBarsToDeplete
|
||||
* 12 = hungerBarsToSubtractWhenEating
|
||||
* 13 = Purchasable
|
||||
* 14 = Price
|
||||
* 15 = OpenWith
|
||||
* 16 = UseWhitelist
|
||||
* 17 = addGlow
|
||||
* 18 = Unstackable
|
||||
*/
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
|
||||
final String p = getServer().getClass().getPackage().getName();
|
||||
final String version = p.substring(p.lastIndexOf('.') + 1);
|
||||
String classname = getClass().getPackage().getName() + ".versions."
|
||||
+ version;
|
||||
try {
|
||||
final Class<?> clazz = Class.forName(classname);
|
||||
final Constructor<?> cons = clazz
|
||||
.getDeclaredConstructor(getClass());
|
||||
final Object obj = cons.newInstance(this);
|
||||
if (obj instanceof RBInterface) {
|
||||
NMS = (RBInterface) obj;
|
||||
}
|
||||
} catch (final Exception e) {
|
||||
globalGlow = false;
|
||||
}
|
||||
|
||||
if (isEnabled()) {
|
||||
saveDefaultConfig();
|
||||
MysqlFunctions.setMysqlFunc(this);
|
||||
RBUtil.setRBUtil(this);
|
||||
if (!setupEconomy()) {
|
||||
getLogger().info("Vault not found, economy features disabled.");
|
||||
vault = false;
|
||||
} else {
|
||||
getLogger().info("Vault found, economy features enabled.");
|
||||
}
|
||||
reloadConfig();
|
||||
setupLists();
|
||||
final File userdata = new File(getDataFolder() + File.separator
|
||||
+ "userdata");
|
||||
setup();
|
||||
if (!userdata.exists()) {
|
||||
userdata.mkdirs();
|
||||
}
|
||||
if (isEnabled()) {
|
||||
getServer().getPluginManager().registerEvents(
|
||||
new PlayerListener(this), this);
|
||||
getServer().getPluginManager().registerEvents(
|
||||
new CraftListener(this), this);
|
||||
getServer().getPluginManager().registerEvents(
|
||||
new InventoryListener(this), this);
|
||||
getServer().getPluginManager().registerEvents(
|
||||
new EntityListener(this), this);
|
||||
getCommand("rb").setExecutor(new MainCommand(this));
|
||||
getServer().getScheduler().runTaskTimer(this,
|
||||
new WalkSpeedRunnable(this), 20, 20);
|
||||
getLogger().info("Realistic Backpacks has been enabled.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
econ = null;
|
||||
HandlerList.unregisterAll(this);
|
||||
getServer().getPluginManager().disablePlugin(this);
|
||||
getLogger().info("Realistic Backpacks has been disabled.");
|
||||
}
|
||||
|
||||
private boolean setupEconomy() {
|
||||
if (getServer().getPluginManager().getPlugin("Vault") == null) {
|
||||
return false;
|
||||
}
|
||||
final RegisteredServiceProvider<Economy> rsp = getServer()
|
||||
.getServicesManager().getRegistration(Economy.class);
|
||||
if (rsp == null) {
|
||||
return false;
|
||||
}
|
||||
econ = rsp.getProvider();
|
||||
return econ != null;
|
||||
}
|
||||
|
||||
public void setupLists() {
|
||||
backpacks.clear();
|
||||
backpackRecipe.clear();
|
||||
backpackData.clear();
|
||||
backpackLore.clear();
|
||||
for (final String backpack : getConfig().getConfigurationSection(
|
||||
"Backpacks").getKeys(false)) {
|
||||
final List<String> list = new ArrayList<String>();
|
||||
backpacks.add(backpack);
|
||||
list.add(0, getConfig()
|
||||
.getString("Backpacks." + backpack + ".Size"));
|
||||
list.add(
|
||||
1,
|
||||
getConfig().getString(
|
||||
"Backpacks." + backpack + ".UseRecipe"));
|
||||
if (getConfig().getStringList("Backpacks." + backpack + ".Recipe") != null) {
|
||||
backpackRecipe.put(
|
||||
backpack,
|
||||
getConfig().getStringList(
|
||||
"Backpacks." + backpack + ".Recipe"));
|
||||
} else {
|
||||
backpackRecipe.put(backpack, null);
|
||||
}
|
||||
list.add(
|
||||
2,
|
||||
getConfig().getString(
|
||||
"Backpacks." + backpack + ".BackpackItem.id"));
|
||||
list.add(
|
||||
3,
|
||||
getConfig().getString(
|
||||
"Backpacks." + backpack + ".BackpackItem.name"));
|
||||
if (getConfig().getStringList(
|
||||
"Backpacks." + backpack + ".BackpackItem.lore") != null) {
|
||||
backpackLore
|
||||
.put(backpack,
|
||||
getConfig().getStringList(
|
||||
"Backpacks." + backpack
|
||||
+ ".BackpackItem.lore"));
|
||||
} else {
|
||||
backpackLore.put(backpack, null);
|
||||
}
|
||||
list.add(
|
||||
4,
|
||||
getConfig().getString(
|
||||
"Backpacks." + backpack
|
||||
+ ".onDeath.destroyContents"));
|
||||
list.add(
|
||||
5,
|
||||
getConfig().getString(
|
||||
"Backpacks." + backpack + ".onDeath.dropContents"));
|
||||
list.add(
|
||||
6,
|
||||
getConfig().getString(
|
||||
"Backpacks." + backpack + ".onDeath.dropBackpack"));
|
||||
list.add(
|
||||
7,
|
||||
getConfig().getString(
|
||||
"Backpacks." + backpack + ".onDeath.keepBackpack"));
|
||||
list.add(
|
||||
8,
|
||||
getConfig().getString(
|
||||
"Backpacks." + backpack
|
||||
+ ".WalkSpeedFeature.enabled"));
|
||||
list.add(
|
||||
9,
|
||||
getConfig().getString(
|
||||
"Backpacks." + backpack
|
||||
+ ".WalkSpeedFeature.walkingSpeed"));
|
||||
list.add(
|
||||
10,
|
||||
getConfig().getString(
|
||||
"Backpacks." + backpack
|
||||
+ ".IncreasedHungerFeature.enabled"));
|
||||
list.add(
|
||||
11,
|
||||
getConfig()
|
||||
.getString(
|
||||
"Backpacks."
|
||||
+ backpack
|
||||
+ ".IncreasedHungerFeature.extraHungerBarsToDeplete"));
|
||||
list.add(
|
||||
12,
|
||||
getConfig()
|
||||
.getString(
|
||||
"Backpacks."
|
||||
+ backpack
|
||||
+ ".IncreasedHungerFeature.hungerBarsToSubtractWhenEating"));
|
||||
list.add(
|
||||
13,
|
||||
getConfig().getString(
|
||||
"Backpacks." + backpack + ".Purchasable"));
|
||||
list.add(14,
|
||||
getConfig().getString("Backpacks." + backpack + ".Price"));
|
||||
list.add(15,
|
||||
getConfig()
|
||||
.getString("Backpacks." + backpack + ".OpenWith"));
|
||||
list.add(
|
||||
16,
|
||||
getConfig().getString(
|
||||
"Backpacks." + backpack + ".UseWhitelist"));
|
||||
list.add(17,
|
||||
getConfig().getString("Backpacks." + backpack + ".addGlow"));
|
||||
list.add(
|
||||
18,
|
||||
getConfig().getString(
|
||||
"Backpacks." + backpack + ".Unstackable"));
|
||||
backpackData.put(backpack, list);
|
||||
backpackBlacklist.put(
|
||||
backpack,
|
||||
getConfig().getStringList(
|
||||
"Backpacks." + backpack + ".ItemBlacklist"));
|
||||
backpackWhitelist.put(
|
||||
backpack,
|
||||
getConfig().getStringList(
|
||||
"Backpacks." + backpack + ".ItemWhitelist"));
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public void setup() {
|
||||
user = getConfig().getString("Data.MySQL.username");
|
||||
password = getConfig().getString("Data.MySQL.password");
|
||||
url = "jdbc:mysql://" + getConfig().getString("Data.MySQL.ip") + ":"
|
||||
+ getConfig().getInt("Data.MySQL.port") + "/"
|
||||
+ getConfig().getString("Data.MySQL.database");
|
||||
|
||||
if (!getConfig().isSet("Config.MultipleBackpacksInInventory.average")) {
|
||||
average = false;
|
||||
} else {
|
||||
average = getConfig().getBoolean(
|
||||
"Config.MultipleBackpacksInInventory.average");
|
||||
}
|
||||
|
||||
if (!getConfig().isSet("Config.MultipleBackpacksInInventory.add")) {
|
||||
add = false;
|
||||
} else {
|
||||
add = getConfig().getBoolean(
|
||||
"Config.MultipleBackpacksInInventory.add");
|
||||
}
|
||||
|
||||
if (!getConfig().isSet("Data.FileSystem")) {
|
||||
usingMysql = false;
|
||||
} else if (getConfig().getString("Data.FileSystem").equalsIgnoreCase(
|
||||
"mysql")
|
||||
|| getConfig().getString("Data.FileSystem").equalsIgnoreCase(
|
||||
"sql")) {
|
||||
usingMysql = true;
|
||||
if (!MysqlFunctions.checkIfTableExists("rb_data")) {
|
||||
MysqlFunctions.createTables();
|
||||
}
|
||||
} else {
|
||||
usingMysql = false;
|
||||
}
|
||||
|
||||
if (!getConfig().isSet("Config.usePermissions")) {
|
||||
usingPermissions = true;
|
||||
} else {
|
||||
usingPermissions = getConfig().getBoolean("Config.usePermissions");
|
||||
}
|
||||
|
||||
for (final String backpack : backpacks) {
|
||||
|
||||
final String override = getConfig().getString(
|
||||
"Backpacks." + backpack + ".Override");
|
||||
if (override != null) {
|
||||
backpackOverrides.put(backpack,
|
||||
RBUtil.getItemstackFromString(override));
|
||||
} else {
|
||||
backpackOverrides.put(backpack, null);
|
||||
}
|
||||
|
||||
final List<String> key = backpackData.get(backpack);
|
||||
final String backpackItem = key.get(2);
|
||||
backpackItems.put(
|
||||
backpack,
|
||||
getConfigLore(RBUtil.getItemstackFromString(backpackItem),
|
||||
backpack));
|
||||
|
||||
ShapedRecipe recipe = null;
|
||||
if (key.get(1).equalsIgnoreCase("true")) {
|
||||
recipe = new ShapedRecipe(backpackItems.get(backpack));
|
||||
recipe.shape("abc", "def", "ghi");
|
||||
int i = 0;
|
||||
for (final String s : backpackRecipe.get(backpack)) {
|
||||
final String[] itemIds = s.split(",");
|
||||
char shapechar = 0;
|
||||
for (final String itemid : itemIds) {
|
||||
i++;
|
||||
switch (i) {
|
||||
case 1:
|
||||
shapechar = 'a';
|
||||
break;
|
||||
case 2:
|
||||
shapechar = 'b';
|
||||
break;
|
||||
case 3:
|
||||
shapechar = 'c';
|
||||
break;
|
||||
case 4:
|
||||
shapechar = 'd';
|
||||
break;
|
||||
case 5:
|
||||
shapechar = 'e';
|
||||
break;
|
||||
case 6:
|
||||
shapechar = 'f';
|
||||
break;
|
||||
case 7:
|
||||
shapechar = 'g';
|
||||
break;
|
||||
case 8:
|
||||
shapechar = 'h';
|
||||
break;
|
||||
case 9:
|
||||
shapechar = 'i';
|
||||
break;
|
||||
}
|
||||
final String[] itemsplit = itemid.split(":");
|
||||
if (itemsplit[0].equals("0")) {
|
||||
continue;
|
||||
}
|
||||
if (itemsplit.length > 1) {
|
||||
final Material baseblock = Material
|
||||
.getMaterial(Integer.parseInt(itemsplit[0]));
|
||||
final MaterialData ingredient = new MaterialData(
|
||||
baseblock,
|
||||
(byte) Integer.parseInt(itemsplit[1]));
|
||||
recipe.setIngredient(shapechar, ingredient);
|
||||
} else {
|
||||
final Material baseblock = Material
|
||||
.getMaterial(Integer.parseInt(itemsplit[0]));
|
||||
recipe.setIngredient(shapechar, baseblock);
|
||||
}
|
||||
}
|
||||
}
|
||||
getServer().addRecipe(recipe);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ItemStack getConfigLore(final ItemStack item, final String backpack) {
|
||||
final List<String> key = backpackData.get(backpack);
|
||||
final ItemMeta meta = item.getItemMeta();
|
||||
final ArrayList<String> lore = new ArrayList<String>();
|
||||
lore.clear();
|
||||
if (backpackLore.get(backpack) != null) {
|
||||
for (final String s : backpackLore.get(backpack)) {
|
||||
lore.add(ChatColor.translateAlternateColorCodes('&', s));
|
||||
}
|
||||
meta.setLore(lore);
|
||||
}
|
||||
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&',
|
||||
key.get(3)));
|
||||
item.setItemMeta(meta);
|
||||
return item;
|
||||
}
|
||||
|
||||
public boolean isAveraging() {
|
||||
return average;
|
||||
}
|
||||
|
||||
public boolean isAdding() {
|
||||
return add;
|
||||
}
|
||||
|
||||
public boolean isUsingMysql() {
|
||||
return usingMysql;
|
||||
}
|
||||
|
||||
public boolean isUsingVault() {
|
||||
return vault;
|
||||
}
|
||||
|
||||
public boolean isUsingPerms() {
|
||||
return usingPermissions;
|
||||
}
|
||||
|
||||
public String getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public String getPass() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
}
|
68
src/cn/citycraft/plugins/WalkSpeedRunnable.java
Normal file
68
src/cn/citycraft/plugins/WalkSpeedRunnable.java
Normal file
@ -0,0 +1,68 @@
|
||||
package cn.citycraft.plugins;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
|
||||
|
||||
public class WalkSpeedRunnable implements Runnable {
|
||||
private RealBackpacks plugin;
|
||||
|
||||
public WalkSpeedRunnable(RealBackpacks plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
for (Player p : plugin.getServer().getOnlinePlayers()) {
|
||||
final String name = p.getName();
|
||||
if (plugin.slowedPlayers.contains(name)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Inventory inv = p.getInventory();
|
||||
final List<String> backpackList = new ArrayList<String>();
|
||||
for (final String backpack : plugin.backpacks) {
|
||||
final List<String> key = plugin.backpackData.get(backpack);
|
||||
if (key.get(8) != null && key.get(8).equalsIgnoreCase("true") && inv != null && inv.contains(plugin.backpackItems.get(backpack))) {
|
||||
backpackList.add(backpack);
|
||||
}
|
||||
}
|
||||
final int listsize = backpackList.size();
|
||||
if (listsize > 0) {
|
||||
float walkSpeedMultiplier = 0.0F;
|
||||
if (listsize > 1) {
|
||||
if (plugin.isAveraging()) {
|
||||
float average = 0;
|
||||
for (final String backpack : backpackList) {
|
||||
average += Float.parseFloat(plugin.backpackData.get(backpack).get(9));
|
||||
}
|
||||
walkSpeedMultiplier = average / listsize;
|
||||
} else {
|
||||
if (plugin.isAdding()) {
|
||||
float sum = 0;
|
||||
for (final String backpack : backpackList) {
|
||||
sum += 0.2F - Float.parseFloat(plugin.backpackData.get(backpack).get(9));
|
||||
}
|
||||
walkSpeedMultiplier = 0.2F - sum;
|
||||
} else {
|
||||
final List<Float> floatList = new ArrayList<Float>();
|
||||
for (final String backpack : backpackList) {
|
||||
floatList.add(Float.parseFloat(plugin.backpackData.get(backpack).get(9)));
|
||||
}
|
||||
walkSpeedMultiplier = Collections.max(floatList);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (listsize == 1) {
|
||||
walkSpeedMultiplier = Float.parseFloat(plugin.backpackData.get(backpackList.get(0)).get(9));
|
||||
}
|
||||
}
|
||||
plugin.slowedPlayers.add(name);
|
||||
p.setWalkSpeed(walkSpeedMultiplier);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
415
src/cn/citycraft/plugins/json/JSONArray.java
Normal file
415
src/cn/citycraft/plugins/json/JSONArray.java
Normal file
@ -0,0 +1,415 @@
|
||||
package cn.citycraft.plugins.json;
|
||||
|
||||
/*
|
||||
* Copyright (c) 2002 JSON.org
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* The Software shall be used for Good, not Evil.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringWriter;
|
||||
import java.io.Writer;
|
||||
import java.lang.reflect.Array;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
public class JSONArray {
|
||||
|
||||
private final ArrayList<Object> myArrayList;
|
||||
|
||||
public JSONArray() {
|
||||
this.myArrayList = new ArrayList<Object>();
|
||||
}
|
||||
|
||||
public JSONArray(JSONTokener x) throws JSONException {
|
||||
this();
|
||||
if (x.nextClean() != '[') {
|
||||
throw x.syntaxError("A JSONArray text must start with '['");
|
||||
}
|
||||
if (x.nextClean() != ']') {
|
||||
x.back();
|
||||
for (;;) {
|
||||
if (x.nextClean() == ',') {
|
||||
x.back();
|
||||
this.myArrayList.add(JSONObject.NULL);
|
||||
} else {
|
||||
x.back();
|
||||
this.myArrayList.add(x.nextValue());
|
||||
}
|
||||
switch (x.nextClean()) {
|
||||
case ';':
|
||||
case ',':
|
||||
if (x.nextClean() == ']') {
|
||||
return;
|
||||
}
|
||||
x.back();
|
||||
break;
|
||||
case ']':
|
||||
return;
|
||||
default:
|
||||
throw x.syntaxError("Expected a ',' or ']'");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public JSONArray(String source) throws JSONException {
|
||||
this(new JSONTokener(source));
|
||||
}
|
||||
|
||||
public JSONArray(Collection<?> collection) {
|
||||
this.myArrayList = new ArrayList<Object>();
|
||||
if (collection != null) {
|
||||
Iterator<?> iter = collection.iterator();
|
||||
while (iter.hasNext()) {
|
||||
this.myArrayList.add(JSONObject.wrap(iter.next()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public JSONArray(Object array) throws JSONException {
|
||||
this();
|
||||
if (array.getClass().isArray()) {
|
||||
int length = Array.getLength(array);
|
||||
for (int i = 0; i < length; i += 1) {
|
||||
this.put(JSONObject.wrap(Array.get(array, i)));
|
||||
}
|
||||
} else {
|
||||
throw new JSONException("JSONArray initial value should be a string or collection or array.");
|
||||
}
|
||||
}
|
||||
|
||||
public Object get(int index) throws JSONException {
|
||||
Object object = this.opt(index);
|
||||
if (object == null) {
|
||||
throw new JSONException("JSONArray[" + index + "] not found.");
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
public boolean getBoolean(int index) throws JSONException {
|
||||
Object object = this.get(index);
|
||||
if (object.equals(Boolean.FALSE) || (object instanceof String && ((String) object).equalsIgnoreCase("false"))) {
|
||||
return false;
|
||||
} else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String) object).equalsIgnoreCase("true"))) {
|
||||
return true;
|
||||
}
|
||||
throw new JSONException("JSONArray[" + index + "] is not a boolean.");
|
||||
}
|
||||
|
||||
public double getDouble(int index) throws JSONException {
|
||||
Object object = this.get(index);
|
||||
try {
|
||||
return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object);
|
||||
} catch (Exception e) {
|
||||
throw new JSONException("JSONArray[" + index + "] is not a number.");
|
||||
}
|
||||
}
|
||||
|
||||
public int getInt(int index) throws JSONException {
|
||||
Object object = this.get(index);
|
||||
try {
|
||||
return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object);
|
||||
} catch (Exception e) {
|
||||
throw new JSONException("JSONArray[" + index + "] is not a number.");
|
||||
}
|
||||
}
|
||||
|
||||
public JSONArray getJSONArray(int index) throws JSONException {
|
||||
Object object = this.get(index);
|
||||
if (object instanceof JSONArray) {
|
||||
return (JSONArray) object;
|
||||
}
|
||||
throw new JSONException("JSONArray[" + index + "] is not a JSONArray.");
|
||||
}
|
||||
|
||||
public JSONObject getJSONObject(int index) throws JSONException {
|
||||
Object object = this.get(index);
|
||||
if (object instanceof JSONObject) {
|
||||
return (JSONObject) object;
|
||||
}
|
||||
throw new JSONException("JSONArray[" + index + "] is not a JSONObject.");
|
||||
}
|
||||
|
||||
public long getLong(int index) throws JSONException {
|
||||
Object object = this.get(index);
|
||||
try {
|
||||
return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object);
|
||||
} catch (Exception e) {
|
||||
throw new JSONException("JSONArray[" + index + "] is not a number.");
|
||||
}
|
||||
}
|
||||
|
||||
public String getString(int index) throws JSONException {
|
||||
Object object = this.get(index);
|
||||
if (object instanceof String) {
|
||||
return (String) object;
|
||||
}
|
||||
throw new JSONException("JSONArray[" + index + "] not a string.");
|
||||
}
|
||||
|
||||
public boolean isNull(int index) {
|
||||
return JSONObject.NULL.equals(this.opt(index));
|
||||
}
|
||||
|
||||
public String join(String separator) throws JSONException {
|
||||
int len = this.length();
|
||||
StringBuffer sb = new StringBuffer();
|
||||
|
||||
for (int i = 0; i < len; i += 1) {
|
||||
if (i > 0) {
|
||||
sb.append(separator);
|
||||
}
|
||||
sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public int length() {
|
||||
return this.myArrayList.size();
|
||||
}
|
||||
|
||||
public Object opt(int index) {
|
||||
return (index < 0 || index >= this.length()) ? null : this.myArrayList.get(index);
|
||||
}
|
||||
|
||||
public boolean optBoolean(int index) {
|
||||
return this.optBoolean(index, false);
|
||||
}
|
||||
|
||||
public boolean optBoolean(int index, boolean defaultValue) {
|
||||
try {
|
||||
return this.getBoolean(index);
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
public double optDouble(int index) {
|
||||
return this.optDouble(index, Double.NaN);
|
||||
}
|
||||
|
||||
public double optDouble(int index, double defaultValue) {
|
||||
try {
|
||||
return this.getDouble(index);
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
public int optInt(int index) {
|
||||
return this.optInt(index, 0);
|
||||
}
|
||||
|
||||
public int optInt(int index, int defaultValue) {
|
||||
try {
|
||||
return this.getInt(index);
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
public JSONArray optJSONArray(int index) {
|
||||
Object o = this.opt(index);
|
||||
return o instanceof JSONArray ? (JSONArray) o : null;
|
||||
}
|
||||
|
||||
public JSONObject optJSONObject(int index) {
|
||||
Object o = this.opt(index);
|
||||
return o instanceof JSONObject ? (JSONObject) o : null;
|
||||
}
|
||||
|
||||
public long optLong(int index) {
|
||||
return this.optLong(index, 0);
|
||||
}
|
||||
|
||||
public long optLong(int index, long defaultValue) {
|
||||
try {
|
||||
return this.getLong(index);
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
public String optString(int index) {
|
||||
return this.optString(index, "");
|
||||
}
|
||||
|
||||
public String optString(int index, String defaultValue) {
|
||||
Object object = this.opt(index);
|
||||
return JSONObject.NULL.equals(object) ? defaultValue : object.toString();
|
||||
}
|
||||
|
||||
public JSONArray put(boolean value) {
|
||||
this.put(value ? Boolean.TRUE : Boolean.FALSE);
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSONArray put(Collection<?> value) {
|
||||
this.put(new JSONArray(value));
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSONArray put(double value) throws JSONException {
|
||||
Double d = new Double(value);
|
||||
JSONObject.testValidity(d);
|
||||
this.put(d);
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSONArray put(int value) {
|
||||
this.put(new Integer(value));
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSONArray put(long value) {
|
||||
this.put(new Long(value));
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSONArray put(Map<?, ?> value) {
|
||||
this.put(new JSONObject());
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSONArray put(Object value) {
|
||||
this.myArrayList.add(value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSONArray put(int index, boolean value) throws JSONException {
|
||||
this.put(index, value ? Boolean.TRUE : Boolean.FALSE);
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSONArray put(int index, Collection<?> value) throws JSONException {
|
||||
this.put(index, new JSONArray(value));
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSONArray put(int index, double value) throws JSONException {
|
||||
this.put(index, new Double(value));
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSONArray put(int index, int value) throws JSONException {
|
||||
this.put(index, new Integer(value));
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSONArray put(int index, long value) throws JSONException {
|
||||
this.put(index, new Long(value));
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSONArray put(int index, Map<?, ?> value) throws JSONException {
|
||||
this.put(index, new JSONObject(value));
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSONArray put(int index, Object value) throws JSONException {
|
||||
JSONObject.testValidity(value);
|
||||
if (index < 0) {
|
||||
throw new JSONException("JSONArray[" + index + "] not found.");
|
||||
}
|
||||
if (index < this.length()) {
|
||||
this.myArrayList.set(index, value);
|
||||
} else {
|
||||
while (index != this.length()) {
|
||||
this.put(JSONObject.NULL);
|
||||
}
|
||||
this.put(value);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public Object remove(int index) {
|
||||
Object o = this.opt(index);
|
||||
this.myArrayList.remove(index);
|
||||
return o;
|
||||
}
|
||||
|
||||
public JSONObject toJSONObject(JSONArray names) throws JSONException {
|
||||
if (names == null || names.length() == 0 || this.length() == 0) {
|
||||
return null;
|
||||
}
|
||||
JSONObject jo = new JSONObject();
|
||||
for (int i = 0; i < names.length(); i += 1) {
|
||||
jo.put(names.getString(i), this.opt(i));
|
||||
}
|
||||
return jo;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
try {
|
||||
return this.toString(0);
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public String toString(int indentFactor) throws JSONException {
|
||||
StringWriter sw = new StringWriter();
|
||||
synchronized (sw.getBuffer()) {
|
||||
return this.write(sw, indentFactor, 0).toString();
|
||||
}
|
||||
}
|
||||
|
||||
public Writer write(Writer writer) throws JSONException {
|
||||
return this.write(writer, 0, 0);
|
||||
}
|
||||
|
||||
Writer write(Writer writer, int indentFactor, int indent) throws JSONException {
|
||||
try {
|
||||
boolean commanate = false;
|
||||
int length = this.length();
|
||||
writer.write('[');
|
||||
|
||||
if (length == 1) {
|
||||
JSONObject.writeValue(writer, this.myArrayList.get(0), indentFactor, indent);
|
||||
} else if (length != 0) {
|
||||
final int newindent = indent + indentFactor;
|
||||
|
||||
for (int i = 0; i < length; i += 1) {
|
||||
if (commanate) {
|
||||
writer.write(',');
|
||||
}
|
||||
if (indentFactor > 0) {
|
||||
writer.write('\n');
|
||||
}
|
||||
JSONObject.indent(writer, newindent);
|
||||
JSONObject.writeValue(writer, this.myArrayList.get(i), indentFactor, newindent);
|
||||
commanate = true;
|
||||
}
|
||||
if (indentFactor > 0) {
|
||||
writer.write('\n');
|
||||
}
|
||||
JSONObject.indent(writer, indent);
|
||||
}
|
||||
writer.write(']');
|
||||
return writer;
|
||||
} catch (IOException e) {
|
||||
throw new JSONException(e);
|
||||
}
|
||||
}
|
||||
}
|
21
src/cn/citycraft/plugins/json/JSONException.java
Normal file
21
src/cn/citycraft/plugins/json/JSONException.java
Normal file
@ -0,0 +1,21 @@
|
||||
package cn.citycraft.plugins.json;
|
||||
|
||||
public class JSONException extends Exception {
|
||||
|
||||
private static final long serialVersionUID = 0;
|
||||
private Throwable cause;
|
||||
|
||||
public JSONException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public JSONException(final Throwable cause) {
|
||||
super(cause.getMessage());
|
||||
this.cause = cause;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Throwable getCause() {
|
||||
return this.cause;
|
||||
}
|
||||
}
|
926
src/cn/citycraft/plugins/json/JSONObject.java
Normal file
926
src/cn/citycraft/plugins/json/JSONObject.java
Normal file
@ -0,0 +1,926 @@
|
||||
package cn.citycraft.plugins.json;
|
||||
|
||||
/*
|
||||
* Copyright (c) 2002 JSON.org
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* The Software shall be used for Good, not Evil.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringWriter;
|
||||
import java.io.Writer;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.Collection;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.ResourceBundle;
|
||||
import java.util.Set;
|
||||
|
||||
public class JSONObject {
|
||||
|
||||
private static final int keyPoolSize = 100;
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
private static HashMap keyPool = new HashMap(keyPoolSize);
|
||||
|
||||
private static final class Null {
|
||||
|
||||
@Override
|
||||
protected final Object clone() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object object) {
|
||||
return object == null || object == this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "null";
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
private final Map map;
|
||||
|
||||
public static final Object NULL = new Null();
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public JSONObject() {
|
||||
this.map = new HashMap();
|
||||
}
|
||||
|
||||
public JSONObject(final JSONObject jo, final String[] names) {
|
||||
this();
|
||||
for (int i = 0; i < names.length; i += 1) {
|
||||
try {
|
||||
this.putOnce(names[i], jo.opt(names[i]));
|
||||
} catch (final Exception ignore) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public JSONObject(final JSONTokener x) throws JSONException {
|
||||
this();
|
||||
char c;
|
||||
String key;
|
||||
|
||||
if (x.nextClean() != '{') {
|
||||
throw x.syntaxError("A JSONObject text must begin with '{'");
|
||||
}
|
||||
for (;;) {
|
||||
c = x.nextClean();
|
||||
switch (c) {
|
||||
case 0:
|
||||
throw x.syntaxError("A JSONObject text must end with '}'");
|
||||
case '}':
|
||||
return;
|
||||
default:
|
||||
x.back();
|
||||
key = x.nextValue().toString();
|
||||
}
|
||||
|
||||
// The key is followed by ':'. We will also tolerate '=' or '=>'.
|
||||
|
||||
c = x.nextClean();
|
||||
if (c == '=') {
|
||||
if (x.next() != '>') {
|
||||
x.back();
|
||||
}
|
||||
} else if (c != ':') {
|
||||
throw x.syntaxError("Expected a ':' after a key");
|
||||
}
|
||||
this.putOnce(key, x.nextValue());
|
||||
|
||||
// Pairs are separated by ','. We will also tolerate ';'.
|
||||
|
||||
switch (x.nextClean()) {
|
||||
case ';':
|
||||
case ',':
|
||||
if (x.nextClean() == '}') {
|
||||
return;
|
||||
}
|
||||
x.back();
|
||||
break;
|
||||
case '}':
|
||||
return;
|
||||
default:
|
||||
throw x.syntaxError("Expected a ',' or '}'");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public JSONObject(final Map map) {
|
||||
this.map = new HashMap();
|
||||
if (map != null) {
|
||||
final Iterator i = map.entrySet().iterator();
|
||||
while (i.hasNext()) {
|
||||
final Map.Entry e = (Map.Entry) i.next();
|
||||
final Object value = e.getValue();
|
||||
if (value != null) {
|
||||
this.map.put(e.getKey(), wrap(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public JSONObject(final Object bean) {
|
||||
this();
|
||||
this.populateMap(bean);
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public JSONObject(final Object object, final String names[]) {
|
||||
this();
|
||||
final Class c = object.getClass();
|
||||
for (int i = 0; i < names.length; i += 1) {
|
||||
final String name = names[i];
|
||||
try {
|
||||
this.putOpt(name, c.getField(name).get(object));
|
||||
} catch (final Exception ignore) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public JSONObject(final String source) throws JSONException {
|
||||
this(new JSONTokener(source));
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public JSONObject(final String baseName, final Locale locale) throws JSONException {
|
||||
this();
|
||||
final ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, Thread.currentThread().getContextClassLoader());
|
||||
|
||||
// Iterate through the keys in the bundle.
|
||||
|
||||
final Enumeration keys = bundle.getKeys();
|
||||
while (keys.hasMoreElements()) {
|
||||
final Object key = keys.nextElement();
|
||||
if (key instanceof String) {
|
||||
|
||||
// Go through the path, ensuring that there is a nested JSONObject for each
|
||||
// segment except the last. Add the value using the last segment's name into
|
||||
// the deepest nested JSONObject.
|
||||
|
||||
final String[] path = ((String) key).split("\\.");
|
||||
final int last = path.length - 1;
|
||||
JSONObject target = this;
|
||||
for (int i = 0; i < last; i += 1) {
|
||||
final String segment = path[i];
|
||||
JSONObject nextTarget = target.optJSONObject(segment);
|
||||
if (nextTarget == null) {
|
||||
nextTarget = new JSONObject();
|
||||
target.put(segment, nextTarget);
|
||||
}
|
||||
target = nextTarget;
|
||||
}
|
||||
target.put(path[last], bundle.getString((String) key));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public JSONObject accumulate(final String key, final Object value) throws JSONException {
|
||||
testValidity(value);
|
||||
final Object object = this.opt(key);
|
||||
if (object == null) {
|
||||
this.put(key, value instanceof JSONArray ? new JSONArray().put(value) : value);
|
||||
} else if (object instanceof JSONArray) {
|
||||
((JSONArray) object).put(value);
|
||||
} else {
|
||||
this.put(key, new JSONArray().put(object).put(value));
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSONObject append(final String key, final Object value) throws JSONException {
|
||||
testValidity(value);
|
||||
final Object object = this.opt(key);
|
||||
if (object == null) {
|
||||
this.put(key, new JSONArray().put(value));
|
||||
} else if (object instanceof JSONArray) {
|
||||
this.put(key, ((JSONArray) object).put(value));
|
||||
} else {
|
||||
throw new JSONException("JSONObject[" + key + "] is not a JSONArray.");
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public static String doubleToString(final double d) {
|
||||
if (Double.isInfinite(d) || Double.isNaN(d)) {
|
||||
return "null";
|
||||
}
|
||||
|
||||
// Shave off trailing zeros and decimal point, if possible.
|
||||
|
||||
String string = Double.toString(d);
|
||||
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) {
|
||||
while (string.endsWith("0")) {
|
||||
string = string.substring(0, string.length() - 1);
|
||||
}
|
||||
if (string.endsWith(".")) {
|
||||
string = string.substring(0, string.length() - 1);
|
||||
}
|
||||
}
|
||||
return string;
|
||||
}
|
||||
|
||||
public Object get(final String key) throws JSONException {
|
||||
if (key == null) {
|
||||
throw new JSONException("Null key.");
|
||||
}
|
||||
final Object object = this.opt(key);
|
||||
if (object == null) {
|
||||
throw new JSONException("JSONObject[" + quote(key) + "] not found.");
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
public boolean getBoolean(final String key) throws JSONException {
|
||||
final Object object = this.get(key);
|
||||
if (object.equals(Boolean.FALSE) || (object instanceof String && ((String) object).equalsIgnoreCase("false"))) {
|
||||
return false;
|
||||
} else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String) object).equalsIgnoreCase("true"))) {
|
||||
return true;
|
||||
}
|
||||
throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean.");
|
||||
}
|
||||
|
||||
public double getDouble(final String key) throws JSONException {
|
||||
final Object object = this.get(key);
|
||||
try {
|
||||
return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object);
|
||||
} catch (final Exception e) {
|
||||
throw new JSONException("JSONObject[" + quote(key) + "] is not a number.");
|
||||
}
|
||||
}
|
||||
|
||||
public int getInt(final String key) throws JSONException {
|
||||
final Object object = this.get(key);
|
||||
try {
|
||||
return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object);
|
||||
} catch (final Exception e) {
|
||||
throw new JSONException("JSONObject[" + quote(key) + "] is not an int.");
|
||||
}
|
||||
}
|
||||
|
||||
public JSONArray getJSONArray(final String key) throws JSONException {
|
||||
final Object object = this.get(key);
|
||||
if (object instanceof JSONArray) {
|
||||
return (JSONArray) object;
|
||||
}
|
||||
throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray.");
|
||||
}
|
||||
|
||||
public JSONObject getJSONObject(final String key) throws JSONException {
|
||||
final Object object = this.get(key);
|
||||
if (object instanceof JSONObject) {
|
||||
return (JSONObject) object;
|
||||
}
|
||||
throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject.");
|
||||
}
|
||||
|
||||
public long getLong(final String key) throws JSONException {
|
||||
final Object object = this.get(key);
|
||||
try {
|
||||
return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object);
|
||||
} catch (final Exception e) {
|
||||
throw new JSONException("JSONObject[" + quote(key) + "] is not a long.");
|
||||
}
|
||||
}
|
||||
|
||||
public static String[] getNames(final JSONObject jo) {
|
||||
final int length = jo.length();
|
||||
if (length == 0) {
|
||||
return null;
|
||||
}
|
||||
@SuppressWarnings("rawtypes")
|
||||
final Iterator iterator = jo.keys();
|
||||
final String[] names = new String[length];
|
||||
int i = 0;
|
||||
while (iterator.hasNext()) {
|
||||
names[i] = (String) iterator.next();
|
||||
i += 1;
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static String[] getNames(final Object object) {
|
||||
if (object == null) {
|
||||
return null;
|
||||
}
|
||||
final Class klass = object.getClass();
|
||||
final Field[] fields = klass.getFields();
|
||||
final int length = fields.length;
|
||||
if (length == 0) {
|
||||
return null;
|
||||
}
|
||||
final String[] names = new String[length];
|
||||
for (int i = 0; i < length; i += 1) {
|
||||
names[i] = fields[i].getName();
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
public String getString(final String key) throws JSONException {
|
||||
final Object object = this.get(key);
|
||||
if (object instanceof String) {
|
||||
return (String) object;
|
||||
}
|
||||
throw new JSONException("JSONObject[" + quote(key) + "] not a string.");
|
||||
}
|
||||
|
||||
public boolean has(final String key) {
|
||||
return this.map.containsKey(key);
|
||||
}
|
||||
|
||||
public JSONObject increment(final String key) throws JSONException {
|
||||
final Object value = this.opt(key);
|
||||
if (value == null) {
|
||||
this.put(key, 1);
|
||||
} else if (value instanceof Integer) {
|
||||
this.put(key, ((Integer) value).intValue() + 1);
|
||||
} else if (value instanceof Long) {
|
||||
this.put(key, ((Long) value).longValue() + 1);
|
||||
} else if (value instanceof Double) {
|
||||
this.put(key, ((Double) value).doubleValue() + 1);
|
||||
} else if (value instanceof Float) {
|
||||
this.put(key, ((Float) value).floatValue() + 1);
|
||||
} else {
|
||||
throw new JSONException("Unable to increment [" + quote(key) + "].");
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean isNull(final String key) {
|
||||
return JSONObject.NULL.equals(this.opt(key));
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public Iterator keys() {
|
||||
return this.keySet().iterator();
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public Set keySet() {
|
||||
return this.map.keySet();
|
||||
}
|
||||
|
||||
public int length() {
|
||||
return this.map.size();
|
||||
}
|
||||
|
||||
public JSONArray names() {
|
||||
final JSONArray ja = new JSONArray();
|
||||
@SuppressWarnings("rawtypes")
|
||||
final Iterator keys = this.keys();
|
||||
while (keys.hasNext()) {
|
||||
ja.put(keys.next());
|
||||
}
|
||||
return ja.length() == 0 ? null : ja;
|
||||
}
|
||||
|
||||
public static String numberToString(final Number number) throws JSONException {
|
||||
if (number == null) {
|
||||
throw new JSONException("Null pointer");
|
||||
}
|
||||
testValidity(number);
|
||||
|
||||
// Shave off trailing zeros and decimal point, if possible.
|
||||
|
||||
String string = number.toString();
|
||||
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) {
|
||||
while (string.endsWith("0")) {
|
||||
string = string.substring(0, string.length() - 1);
|
||||
}
|
||||
if (string.endsWith(".")) {
|
||||
string = string.substring(0, string.length() - 1);
|
||||
}
|
||||
}
|
||||
return string;
|
||||
}
|
||||
|
||||
public Object opt(final String key) {
|
||||
return key == null ? null : this.map.get(key);
|
||||
}
|
||||
|
||||
public boolean optBoolean(final String key) {
|
||||
return this.optBoolean(key, false);
|
||||
}
|
||||
|
||||
public boolean optBoolean(final String key, final boolean defaultValue) {
|
||||
try {
|
||||
return this.getBoolean(key);
|
||||
} catch (final Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
public double optDouble(final String key) {
|
||||
return this.optDouble(key, Double.NaN);
|
||||
}
|
||||
|
||||
public double optDouble(final String key, final double defaultValue) {
|
||||
try {
|
||||
return this.getDouble(key);
|
||||
} catch (final Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
public int optInt(final String key) {
|
||||
return this.optInt(key, 0);
|
||||
}
|
||||
|
||||
public int optInt(final String key, final int defaultValue) {
|
||||
try {
|
||||
return this.getInt(key);
|
||||
} catch (final Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
public JSONArray optJSONArray(final String key) {
|
||||
final Object o = this.opt(key);
|
||||
return o instanceof JSONArray ? (JSONArray) o : null;
|
||||
}
|
||||
|
||||
public JSONObject optJSONObject(final String key) {
|
||||
final Object object = this.opt(key);
|
||||
return object instanceof JSONObject ? (JSONObject) object : null;
|
||||
}
|
||||
|
||||
public long optLong(final String key) {
|
||||
return this.optLong(key, 0);
|
||||
}
|
||||
|
||||
public long optLong(final String key, final long defaultValue) {
|
||||
try {
|
||||
return this.getLong(key);
|
||||
} catch (final Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
public String optString(final String key) {
|
||||
return this.optString(key, "");
|
||||
}
|
||||
|
||||
public String optString(final String key, final String defaultValue) {
|
||||
final Object object = this.opt(key);
|
||||
return NULL.equals(object) ? defaultValue : object.toString();
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
private void populateMap(final Object bean) {
|
||||
final Class klass = bean.getClass();
|
||||
|
||||
// If klass is a System class then set includeSuperClass to false.
|
||||
|
||||
final boolean includeSuperClass = klass.getClassLoader() != null;
|
||||
|
||||
final Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods();
|
||||
for (int i = 0; i < methods.length; i += 1) {
|
||||
try {
|
||||
final Method method = methods[i];
|
||||
if (Modifier.isPublic(method.getModifiers())) {
|
||||
final String name = method.getName();
|
||||
String key = "";
|
||||
if (name.startsWith("get")) {
|
||||
if ("getClass".equals(name) || "getDeclaringClass".equals(name)) {
|
||||
key = "";
|
||||
} else {
|
||||
key = name.substring(3);
|
||||
}
|
||||
} else if (name.startsWith("is")) {
|
||||
key = name.substring(2);
|
||||
}
|
||||
if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) {
|
||||
if (key.length() == 1) {
|
||||
key = key.toLowerCase();
|
||||
} else if (!Character.isUpperCase(key.charAt(1))) {
|
||||
key = key.substring(0, 1).toLowerCase() + key.substring(1);
|
||||
}
|
||||
|
||||
final Object result = method.invoke(bean, (Object[]) null);
|
||||
if (result != null) {
|
||||
this.map.put(key, wrap(result));
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (final Exception ignore) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public JSONObject put(final String key, final boolean value) throws JSONException {
|
||||
this.put(key, value ? Boolean.TRUE : Boolean.FALSE);
|
||||
return this;
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public JSONObject put(final String key, final Collection value) throws JSONException {
|
||||
this.put(key, new JSONArray(value));
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSONObject put(final String key, final double value) throws JSONException {
|
||||
this.put(key, new Double(value));
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSONObject put(final String key, final int value) throws JSONException {
|
||||
this.put(key, new Integer(value));
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSONObject put(final String key, final long value) throws JSONException {
|
||||
this.put(key, new Long(value));
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSONObject put(final String key, @SuppressWarnings("rawtypes") final Map value) throws JSONException {
|
||||
this.put(key, new JSONObject(value));
|
||||
return this;
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public JSONObject put(String key, final Object value) throws JSONException {
|
||||
String pooled;
|
||||
if (key == null) {
|
||||
throw new JSONException("Null key.");
|
||||
}
|
||||
if (value != null) {
|
||||
testValidity(value);
|
||||
pooled = (String) keyPool.get(key);
|
||||
if (pooled == null) {
|
||||
if (keyPool.size() >= keyPoolSize) {
|
||||
keyPool = new HashMap(keyPoolSize);
|
||||
}
|
||||
keyPool.put(key, key);
|
||||
} else {
|
||||
key = pooled;
|
||||
}
|
||||
this.map.put(key, value);
|
||||
} else {
|
||||
this.remove(key);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSONObject putOnce(final String key, final Object value) throws JSONException {
|
||||
if (key != null && value != null) {
|
||||
if (this.opt(key) != null) {
|
||||
throw new JSONException("Duplicate key \"" + key + "\"");
|
||||
}
|
||||
this.put(key, value);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSONObject putOpt(final String key, final Object value) throws JSONException {
|
||||
if (key != null && value != null) {
|
||||
this.put(key, value);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public static String quote(final String string) {
|
||||
final StringWriter sw = new StringWriter();
|
||||
synchronized (sw.getBuffer()) {
|
||||
try {
|
||||
return quote(string, sw).toString();
|
||||
} catch (final IOException ignored) {
|
||||
// will never happen - we are writing to a string writer
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static Writer quote(final String string, final Writer w) throws IOException {
|
||||
if (string == null || string.length() == 0) {
|
||||
w.write("\"\"");
|
||||
return w;
|
||||
}
|
||||
|
||||
char b;
|
||||
char c = 0;
|
||||
String hhhh;
|
||||
int i;
|
||||
final int len = string.length();
|
||||
|
||||
w.write('"');
|
||||
for (i = 0; i < len; i += 1) {
|
||||
b = c;
|
||||
c = string.charAt(i);
|
||||
switch (c) {
|
||||
case '\\':
|
||||
case '"':
|
||||
w.write('\\');
|
||||
w.write(c);
|
||||
break;
|
||||
case '/':
|
||||
if (b == '<') {
|
||||
w.write('\\');
|
||||
}
|
||||
w.write(c);
|
||||
break;
|
||||
case '\b':
|
||||
w.write("\\b");
|
||||
break;
|
||||
case '\t':
|
||||
w.write("\\t");
|
||||
break;
|
||||
case '\n':
|
||||
w.write("\\n");
|
||||
break;
|
||||
case '\f':
|
||||
w.write("\\f");
|
||||
break;
|
||||
case '\r':
|
||||
w.write("\\r");
|
||||
break;
|
||||
default:
|
||||
if (c < ' ' || (c >= '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')) {
|
||||
w.write("\\u");
|
||||
hhhh = Integer.toHexString(c);
|
||||
w.write("0000", 0, 4 - hhhh.length());
|
||||
w.write(hhhh);
|
||||
} else {
|
||||
w.write(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
w.write('"');
|
||||
return w;
|
||||
}
|
||||
|
||||
public Object remove(final String key) {
|
||||
return this.map.remove(key);
|
||||
}
|
||||
|
||||
public static Object stringToValue(final String string) {
|
||||
Double d;
|
||||
if (string.equals("")) {
|
||||
return string;
|
||||
}
|
||||
if (string.equalsIgnoreCase("true")) {
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
if (string.equalsIgnoreCase("false")) {
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
if (string.equalsIgnoreCase("null")) {
|
||||
return JSONObject.NULL;
|
||||
}
|
||||
|
||||
/*
|
||||
* If it might be a number, try converting it.
|
||||
* If a number cannot be produced, then the value will just
|
||||
* be a string. Note that the plus and implied string
|
||||
* conventions are non-standard. A JSON parser may accept
|
||||
* non-JSON forms as long as it accepts all correct JSON forms.
|
||||
*/
|
||||
|
||||
final char b = string.charAt(0);
|
||||
if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') {
|
||||
try {
|
||||
if (string.indexOf('.') > -1 || string.indexOf('e') > -1 || string.indexOf('E') > -1) {
|
||||
d = Double.valueOf(string);
|
||||
if (!d.isInfinite() && !d.isNaN()) {
|
||||
return d;
|
||||
}
|
||||
} else {
|
||||
final Long myLong = new Long(string);
|
||||
if (myLong.longValue() == myLong.intValue()) {
|
||||
return new Integer(myLong.intValue());
|
||||
} else {
|
||||
return myLong;
|
||||
}
|
||||
}
|
||||
} catch (final Exception ignore) {
|
||||
}
|
||||
}
|
||||
return string;
|
||||
}
|
||||
|
||||
public static void testValidity(final Object o) throws JSONException {
|
||||
if (o != null) {
|
||||
if (o instanceof Double) {
|
||||
if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
|
||||
throw new JSONException("JSON does not allow non-finite numbers.");
|
||||
}
|
||||
} else if (o instanceof Float) {
|
||||
if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
|
||||
throw new JSONException("JSON does not allow non-finite numbers.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public JSONArray toJSONArray(final JSONArray names) throws JSONException {
|
||||
if (names == null || names.length() == 0) {
|
||||
return null;
|
||||
}
|
||||
final JSONArray ja = new JSONArray();
|
||||
for (int i = 0; i < names.length(); i += 1) {
|
||||
ja.put(this.opt(names.getString(i)));
|
||||
}
|
||||
return ja;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
try {
|
||||
return this.toString(0);
|
||||
} catch (final Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public String toString(final int indentFactor) throws JSONException {
|
||||
final StringWriter w = new StringWriter();
|
||||
synchronized (w.getBuffer()) {
|
||||
return this.write(w, indentFactor, 0).toString();
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static String valueToString(final Object value) throws JSONException {
|
||||
if (value == null || value.equals(null)) {
|
||||
return "null";
|
||||
}
|
||||
if (value instanceof JSONString) {
|
||||
Object object;
|
||||
try {
|
||||
object = ((JSONString) value).toJSONString();
|
||||
} catch (final Exception e) {
|
||||
throw new JSONException(e);
|
||||
}
|
||||
if (object instanceof String) {
|
||||
return (String) object;
|
||||
}
|
||||
throw new JSONException("Bad value from toJSONString: " + object);
|
||||
}
|
||||
if (value instanceof Number) {
|
||||
return numberToString((Number) value);
|
||||
}
|
||||
if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) {
|
||||
return value.toString();
|
||||
}
|
||||
if (value instanceof Map) {
|
||||
return new JSONObject((Map) value).toString();
|
||||
}
|
||||
if (value instanceof Collection) {
|
||||
return new JSONArray((Collection) value).toString();
|
||||
}
|
||||
if (value.getClass().isArray()) {
|
||||
return new JSONArray(value).toString();
|
||||
}
|
||||
return quote(value.toString());
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static Object wrap(final Object object) {
|
||||
try {
|
||||
if (object == null) {
|
||||
return NULL;
|
||||
}
|
||||
if (object instanceof JSONObject || object instanceof JSONArray || NULL.equals(object) || object instanceof JSONString || object instanceof Byte || object instanceof Character || object instanceof Short || object instanceof Integer || object instanceof Long || object instanceof Boolean || object instanceof Float || object instanceof Double || object instanceof String) {
|
||||
return object;
|
||||
}
|
||||
|
||||
if (object instanceof Collection) {
|
||||
return new JSONArray((Collection) object);
|
||||
}
|
||||
if (object.getClass().isArray()) {
|
||||
return new JSONArray(object);
|
||||
}
|
||||
if (object instanceof Map) {
|
||||
return new JSONObject((Map) object);
|
||||
}
|
||||
final Package objectPackage = object.getClass().getPackage();
|
||||
final String objectPackageName = objectPackage != null ? objectPackage.getName() : "";
|
||||
if (objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.") || object.getClass().getClassLoader() == null) {
|
||||
return object.toString();
|
||||
}
|
||||
return new JSONObject(object);
|
||||
} catch (final Exception exception) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public Writer write(final Writer writer) throws JSONException {
|
||||
return this.write(writer, 0, 0);
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
static final Writer writeValue(final Writer writer, final Object value, final int indentFactor, final int indent) throws JSONException, IOException {
|
||||
if (value == null || value.equals(null)) {
|
||||
writer.write("null");
|
||||
} else if (value instanceof JSONObject) {
|
||||
((JSONObject) value).write(writer, indentFactor, indent);
|
||||
} else if (value instanceof JSONArray) {
|
||||
((JSONArray) value).write(writer, indentFactor, indent);
|
||||
} else if (value instanceof Map) {
|
||||
new JSONObject((Map) value).write(writer, indentFactor, indent);
|
||||
} else if (value instanceof Collection) {
|
||||
new JSONArray((Collection) value).write(writer, indentFactor, indent);
|
||||
} else if (value.getClass().isArray()) {
|
||||
new JSONArray(value).write(writer, indentFactor, indent);
|
||||
} else if (value instanceof Number) {
|
||||
writer.write(numberToString((Number) value));
|
||||
} else if (value instanceof Boolean) {
|
||||
writer.write(value.toString());
|
||||
} else if (value instanceof JSONString) {
|
||||
Object o;
|
||||
try {
|
||||
o = ((JSONString) value).toJSONString();
|
||||
} catch (final Exception e) {
|
||||
throw new JSONException(e);
|
||||
}
|
||||
writer.write(o != null ? o.toString() : quote(value.toString()));
|
||||
} else {
|
||||
quote(value.toString(), writer);
|
||||
}
|
||||
return writer;
|
||||
}
|
||||
|
||||
static final void indent(final Writer writer, final int indent) throws IOException {
|
||||
for (int i = 0; i < indent; i += 1) {
|
||||
writer.write(' ');
|
||||
}
|
||||
}
|
||||
|
||||
Writer write(final Writer writer, final int indentFactor, final int indent) throws JSONException {
|
||||
try {
|
||||
boolean commanate = false;
|
||||
final int length = this.length();
|
||||
@SuppressWarnings("rawtypes")
|
||||
final Iterator keys = this.keys();
|
||||
writer.write('{');
|
||||
|
||||
if (length == 1) {
|
||||
final Object key = keys.next();
|
||||
writer.write(quote(key.toString()));
|
||||
writer.write(':');
|
||||
if (indentFactor > 0) {
|
||||
writer.write(' ');
|
||||
}
|
||||
writeValue(writer, this.map.get(key), indentFactor, indent);
|
||||
} else if (length != 0) {
|
||||
final int newindent = indent + indentFactor;
|
||||
while (keys.hasNext()) {
|
||||
final Object key = keys.next();
|
||||
if (commanate) {
|
||||
writer.write(',');
|
||||
}
|
||||
if (indentFactor > 0) {
|
||||
writer.write('\n');
|
||||
}
|
||||
indent(writer, newindent);
|
||||
writer.write(quote(key.toString()));
|
||||
writer.write(':');
|
||||
if (indentFactor > 0) {
|
||||
writer.write(' ');
|
||||
}
|
||||
writeValue(writer, this.map.get(key), indentFactor, newindent);
|
||||
commanate = true;
|
||||
}
|
||||
if (indentFactor > 0) {
|
||||
writer.write('\n');
|
||||
}
|
||||
indent(writer, indent);
|
||||
}
|
||||
writer.write('}');
|
||||
return writer;
|
||||
} catch (final IOException exception) {
|
||||
throw new JSONException(exception);
|
||||
}
|
||||
}
|
||||
}
|
6
src/cn/citycraft/plugins/json/JSONString.java
Normal file
6
src/cn/citycraft/plugins/json/JSONString.java
Normal file
@ -0,0 +1,6 @@
|
||||
package cn.citycraft.plugins.json;
|
||||
|
||||
public interface JSONString {
|
||||
|
||||
public String toJSONString();
|
||||
}
|
315
src/cn/citycraft/plugins/json/JSONTokener.java
Normal file
315
src/cn/citycraft/plugins/json/JSONTokener.java
Normal file
@ -0,0 +1,315 @@
|
||||
package cn.citycraft.plugins.json;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
import java.io.StringReader;
|
||||
|
||||
/*
|
||||
* Copyright (c) 2002 JSON.org
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* The Software shall be used for Good, not Evil.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
public class JSONTokener {
|
||||
|
||||
private long character;
|
||||
private boolean eof;
|
||||
private long index;
|
||||
private long line;
|
||||
private char previous;
|
||||
private final Reader reader;
|
||||
private boolean usePrevious;
|
||||
|
||||
public JSONTokener(final Reader reader) {
|
||||
this.reader = reader.markSupported() ? reader : new BufferedReader(reader);
|
||||
this.eof = false;
|
||||
this.usePrevious = false;
|
||||
this.previous = 0;
|
||||
this.index = 0;
|
||||
this.character = 1;
|
||||
this.line = 1;
|
||||
}
|
||||
|
||||
public JSONTokener(final InputStream inputStream) throws JSONException {
|
||||
this(new InputStreamReader(inputStream));
|
||||
}
|
||||
|
||||
public JSONTokener(final String s) {
|
||||
this(new StringReader(s));
|
||||
}
|
||||
|
||||
public void back() throws JSONException {
|
||||
if (this.usePrevious || this.index <= 0) {
|
||||
throw new JSONException("Stepping back two steps is not supported");
|
||||
}
|
||||
this.index -= 1;
|
||||
this.character -= 1;
|
||||
this.usePrevious = true;
|
||||
this.eof = false;
|
||||
}
|
||||
|
||||
public static int dehexchar(final char c) {
|
||||
if (c >= '0' && c <= '9') {
|
||||
return c - '0';
|
||||
}
|
||||
if (c >= 'A' && c <= 'F') {
|
||||
return c - ('A' - 10);
|
||||
}
|
||||
if (c >= 'a' && c <= 'f') {
|
||||
return c - ('a' - 10);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public boolean end() {
|
||||
return this.eof && !this.usePrevious;
|
||||
}
|
||||
|
||||
public boolean more() throws JSONException {
|
||||
this.next();
|
||||
if (this.end()) {
|
||||
return false;
|
||||
}
|
||||
this.back();
|
||||
return true;
|
||||
}
|
||||
|
||||
public char next() throws JSONException {
|
||||
int c;
|
||||
if (this.usePrevious) {
|
||||
this.usePrevious = false;
|
||||
c = this.previous;
|
||||
} else {
|
||||
try {
|
||||
c = this.reader.read();
|
||||
} catch (final IOException exception) {
|
||||
throw new JSONException(exception);
|
||||
}
|
||||
|
||||
if (c <= 0) { // End of stream
|
||||
this.eof = true;
|
||||
c = 0;
|
||||
}
|
||||
}
|
||||
this.index += 1;
|
||||
if (this.previous == '\r') {
|
||||
this.line += 1;
|
||||
this.character = c == '\n' ? 0 : 1;
|
||||
} else if (c == '\n') {
|
||||
this.line += 1;
|
||||
this.character = 0;
|
||||
} else {
|
||||
this.character += 1;
|
||||
}
|
||||
this.previous = (char) c;
|
||||
return this.previous;
|
||||
}
|
||||
|
||||
public char next(final char c) throws JSONException {
|
||||
final char n = this.next();
|
||||
if (n != c) {
|
||||
throw this.syntaxError("Expected '" + c + "' and instead saw '" + n + "'");
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
public String next(final int n) throws JSONException {
|
||||
if (n == 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
final char[] chars = new char[n];
|
||||
int pos = 0;
|
||||
|
||||
while (pos < n) {
|
||||
chars[pos] = this.next();
|
||||
if (this.end()) {
|
||||
throw this.syntaxError("Substring bounds error");
|
||||
}
|
||||
pos += 1;
|
||||
}
|
||||
return new String(chars);
|
||||
}
|
||||
|
||||
public char nextClean() throws JSONException {
|
||||
for (;;) {
|
||||
final char c = this.next();
|
||||
if (c == 0 || c > ' ') {
|
||||
return c;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String nextString(final char quote) throws JSONException {
|
||||
char c;
|
||||
final StringBuffer sb = new StringBuffer();
|
||||
for (;;) {
|
||||
c = this.next();
|
||||
switch (c) {
|
||||
case 0:
|
||||
case '\n':
|
||||
case '\r':
|
||||
throw this.syntaxError("Unterminated string");
|
||||
case '\\':
|
||||
c = this.next();
|
||||
switch (c) {
|
||||
case 'b':
|
||||
sb.append('\b');
|
||||
break;
|
||||
case 't':
|
||||
sb.append('\t');
|
||||
break;
|
||||
case 'n':
|
||||
sb.append('\n');
|
||||
break;
|
||||
case 'f':
|
||||
sb.append('\f');
|
||||
break;
|
||||
case 'r':
|
||||
sb.append('\r');
|
||||
break;
|
||||
case 'u':
|
||||
sb.append((char) Integer.parseInt(this.next(4), 16));
|
||||
break;
|
||||
case '"':
|
||||
case '\'':
|
||||
case '\\':
|
||||
case '/':
|
||||
sb.append(c);
|
||||
break;
|
||||
default:
|
||||
throw this.syntaxError("Illegal escape.");
|
||||
}
|
||||
break;
|
||||
default:
|
||||
if (c == quote) {
|
||||
return sb.toString();
|
||||
}
|
||||
sb.append(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String nextTo(final char delimiter) throws JSONException {
|
||||
final StringBuffer sb = new StringBuffer();
|
||||
for (;;) {
|
||||
final char c = this.next();
|
||||
if (c == delimiter || c == 0 || c == '\n' || c == '\r') {
|
||||
if (c != 0) {
|
||||
this.back();
|
||||
}
|
||||
return sb.toString().trim();
|
||||
}
|
||||
sb.append(c);
|
||||
}
|
||||
}
|
||||
|
||||
public String nextTo(final String delimiters) throws JSONException {
|
||||
char c;
|
||||
final StringBuffer sb = new StringBuffer();
|
||||
for (;;) {
|
||||
c = this.next();
|
||||
if (delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r') {
|
||||
if (c != 0) {
|
||||
this.back();
|
||||
}
|
||||
return sb.toString().trim();
|
||||
}
|
||||
sb.append(c);
|
||||
}
|
||||
}
|
||||
|
||||
public Object nextValue() throws JSONException {
|
||||
char c = this.nextClean();
|
||||
String string;
|
||||
|
||||
switch (c) {
|
||||
case '"':
|
||||
case '\'':
|
||||
return this.nextString(c);
|
||||
case '{':
|
||||
this.back();
|
||||
return new JSONObject(this);
|
||||
case '[':
|
||||
this.back();
|
||||
return new JSONArray(this);
|
||||
}
|
||||
|
||||
/*
|
||||
* Handle unquoted text. This could be the values true, false, or
|
||||
* null, or it can be a number. An implementation (such as this one)
|
||||
* is allowed to also accept non-standard forms.
|
||||
*
|
||||
* Accumulate characters until we reach the end of the text or a
|
||||
* formatting character.
|
||||
*/
|
||||
|
||||
final StringBuffer sb = new StringBuffer();
|
||||
while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
|
||||
sb.append(c);
|
||||
c = this.next();
|
||||
}
|
||||
this.back();
|
||||
|
||||
string = sb.toString().trim();
|
||||
if ("".equals(string)) {
|
||||
throw this.syntaxError("Missing value");
|
||||
}
|
||||
return JSONObject.stringToValue(string);
|
||||
}
|
||||
|
||||
public char skipTo(final char to) throws JSONException {
|
||||
char c;
|
||||
try {
|
||||
final long startIndex = this.index;
|
||||
final long startCharacter = this.character;
|
||||
final long startLine = this.line;
|
||||
this.reader.mark(1000000);
|
||||
do {
|
||||
c = this.next();
|
||||
if (c == 0) {
|
||||
this.reader.reset();
|
||||
this.index = startIndex;
|
||||
this.character = startCharacter;
|
||||
this.line = startLine;
|
||||
return c;
|
||||
}
|
||||
} while (c != to);
|
||||
} catch (final IOException exc) {
|
||||
throw new JSONException(exc);
|
||||
}
|
||||
|
||||
this.back();
|
||||
return c;
|
||||
}
|
||||
|
||||
public JSONException syntaxError(final String message) {
|
||||
return new JSONException(message + this.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return " at " + this.index + " [character " + this.character + " line " + this.line + "]";
|
||||
}
|
||||
}
|
59
src/cn/citycraft/plugins/listeners/CraftListener.java
Normal file
59
src/cn/citycraft/plugins/listeners/CraftListener.java
Normal file
@ -0,0 +1,59 @@
|
||||
package cn.citycraft.plugins.listeners;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.entity.HumanEntity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.inventory.PrepareItemCraftEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import cn.citycraft.plugins.RealBackpacks;
|
||||
|
||||
public class CraftListener implements Listener {
|
||||
|
||||
private final RealBackpacks plugin;
|
||||
|
||||
public CraftListener(final RealBackpacks plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
|
||||
public void onPrepareCraft(final PrepareItemCraftEvent e) {
|
||||
final ItemStack result = e.getInventory().getResult();
|
||||
final HumanEntity human = e.getView().getPlayer();
|
||||
if (!(human instanceof Player) || result == null) {
|
||||
return;
|
||||
}
|
||||
for (final String backpack : plugin.backpacks) {
|
||||
if (plugin.backpackOverrides.get(backpack) != null && result.isSimilar(plugin.backpackOverrides.get(backpack))) {
|
||||
if (RealBackpacks.globalGlow && plugin.backpackData.get(backpack).get(17) != null && plugin.backpackData.get(backpack).get(17).equalsIgnoreCase("true")) {
|
||||
e.getInventory().setResult(RealBackpacks.NMS.addGlow(plugin.backpackItems.get(backpack)));
|
||||
} else {
|
||||
e.getInventory().setResult(plugin.backpackItems.get(backpack));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (result.hasItemMeta() && result.getItemMeta().hasDisplayName()) {
|
||||
for (final String backpack : plugin.backpacks) {
|
||||
final List<String> key = plugin.backpackData.get(backpack);
|
||||
if (!result.getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', key.get(3)))) {
|
||||
continue;
|
||||
}
|
||||
if (!human.hasPermission("rb." + backpack + ".craft") && plugin.isUsingPerms()) {
|
||||
e.getInventory().setResult(null);
|
||||
((Player) human).sendMessage(ChatColor.RED + "你没有合成此背包的权限...");
|
||||
break;
|
||||
}
|
||||
if (RealBackpacks.globalGlow && plugin.backpackData.get(backpack).get(17) != null && plugin.backpackData.get(backpack).get(17).equalsIgnoreCase("true")) {
|
||||
e.getInventory().setResult(RealBackpacks.NMS.addGlow(plugin.backpackItems.get(backpack)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
66
src/cn/citycraft/plugins/listeners/EntityListener.java
Normal file
66
src/cn/citycraft/plugins/listeners/EntityListener.java
Normal file
@ -0,0 +1,66 @@
|
||||
package cn.citycraft.plugins.listeners;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.entity.FoodLevelChangeEvent;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
|
||||
import cn.citycraft.plugins.RealBackpacks;
|
||||
import cn.citycraft.plugins.util.RBUtil;
|
||||
|
||||
public class EntityListener implements Listener {
|
||||
|
||||
private final RealBackpacks plugin;
|
||||
|
||||
private int setlevel = 0;
|
||||
|
||||
public EntityListener(final RealBackpacks plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
|
||||
public void onFoodChange(final FoodLevelChangeEvent e) {
|
||||
if (e.getEntity() instanceof Player) {
|
||||
final int foodlevel = e.getFoodLevel();
|
||||
final Player p = (Player) e.getEntity();
|
||||
final int pLevel = p.getFoodLevel();
|
||||
final Inventory inv = p.getInventory();
|
||||
|
||||
final List<String> backpackList = new ArrayList<String>();
|
||||
for (final String backpack : plugin.backpacks) {
|
||||
final List<String> key = plugin.backpackData.get(backpack);
|
||||
if (!key.get(10).equals("true")) {
|
||||
continue;
|
||||
}
|
||||
if (!inv.contains(plugin.backpackItems.get(backpack))) {
|
||||
continue;
|
||||
}
|
||||
backpackList.add(backpack);
|
||||
}
|
||||
final int listsize = backpackList.size();
|
||||
if (listsize > 0) {
|
||||
if (pLevel > foodlevel) {
|
||||
//Starving
|
||||
setlevel = RBUtil.getFoodLevel(foodlevel, pLevel, listsize, 11, backpackList);
|
||||
if (setlevel < 0) {
|
||||
setlevel = 0;
|
||||
}
|
||||
} else {
|
||||
//Ate food
|
||||
setlevel = RBUtil.getFoodLevel(foodlevel, pLevel, listsize, 12, backpackList);
|
||||
if (setlevel < pLevel) {
|
||||
setlevel = pLevel;
|
||||
}
|
||||
}
|
||||
|
||||
e.setCancelled(true);
|
||||
p.setFoodLevel(setlevel);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
238
src/cn/citycraft/plugins/listeners/InventoryListener.java
Normal file
238
src/cn/citycraft/plugins/listeners/InventoryListener.java
Normal file
@ -0,0 +1,238 @@
|
||||
package cn.citycraft.plugins.listeners;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.event.inventory.InventoryCloseEvent;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import cn.citycraft.plugins.RealBackpacks;
|
||||
import cn.citycraft.plugins.util.MysqlFunctions;
|
||||
import cn.citycraft.plugins.util.RBUtil;
|
||||
import cn.citycraft.plugins.util.Serialization;
|
||||
|
||||
public class InventoryListener implements Listener {
|
||||
|
||||
private final RealBackpacks plugin;
|
||||
|
||||
public InventoryListener(final RealBackpacks plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onInventoryClose(final InventoryCloseEvent e) {
|
||||
final String name = e.getPlayer().getName();
|
||||
final Inventory inv = e.getView().getTopInventory();
|
||||
final List<String> invString = Serialization.toString(inv);
|
||||
final String backpack = plugin.playerData.get(name);
|
||||
plugin.playerData.remove(name);
|
||||
final String adminBackpack = plugin.adminFullView.get(name);
|
||||
plugin.adminFullView.remove(name);
|
||||
if (backpack != null) {
|
||||
plugin.getServer().getScheduler()
|
||||
.runTaskAsynchronously(plugin, new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (plugin.isUsingMysql()) {
|
||||
try {
|
||||
MysqlFunctions.addBackpackData(name,
|
||||
backpack, invString);
|
||||
} catch (final SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
} else {
|
||||
final File file = new File(plugin
|
||||
.getDataFolder()
|
||||
+ File.separator
|
||||
+ "userdata"
|
||||
+ File.separator
|
||||
+ name
|
||||
+ ".yml");
|
||||
final FileConfiguration config = YamlConfiguration
|
||||
.loadConfiguration(file);
|
||||
config.set(backpack + ".Inventory", invString);
|
||||
try {
|
||||
config.save(file);
|
||||
} catch (final IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
} else if (adminBackpack != null) {
|
||||
plugin.getServer().getScheduler()
|
||||
.runTaskAsynchronously(plugin, new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
final String[] split = adminBackpack.split(":");
|
||||
if (plugin.isUsingMysql()) {
|
||||
try {
|
||||
MysqlFunctions.addBackpackData(split[0],
|
||||
split[1], invString);
|
||||
} catch (final SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
} else {
|
||||
final List<String> invString = Serialization
|
||||
.toString(inv);
|
||||
final File file = new File(plugin
|
||||
.getDataFolder()
|
||||
+ File.separator
|
||||
+ "userdata"
|
||||
+ File.separator
|
||||
+ split[1] + ".yml");
|
||||
final FileConfiguration config = YamlConfiguration
|
||||
.loadConfiguration(file);
|
||||
config.set(split[0] + ".Inventory", invString);
|
||||
try {
|
||||
config.save(file);
|
||||
} catch (final IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
} else if (plugin.adminRestrictedView.contains(name)) {
|
||||
plugin.adminRestrictedView.remove(name);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
|
||||
public void onInventoryClick(final InventoryClickEvent e) {
|
||||
if (e.getWhoClicked() instanceof Player) {
|
||||
|
||||
final Player p = (Player) e.getWhoClicked();
|
||||
final String name = p.getName();
|
||||
|
||||
if (plugin.adminRestrictedView.contains(name)) {
|
||||
e.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
final Inventory otherInv = e.getView().getTopInventory();
|
||||
final ItemStack curItem = e.getCurrentItem();
|
||||
boolean otherInvPresent = false;
|
||||
|
||||
if (otherInv != null)
|
||||
otherInvPresent = true;
|
||||
|
||||
if (curItem != null && curItem.hasItemMeta()
|
||||
&& curItem.getItemMeta().hasDisplayName()) {
|
||||
for (final String backpack : plugin.backpacks) {
|
||||
if (curItem.isSimilar(plugin.backpackItems.get(backpack))) {
|
||||
plugin.slowedPlayers.remove(name);
|
||||
p.setWalkSpeed(0.2F);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!e.isCancelled() && curItem != null && otherInvPresent) {
|
||||
|
||||
if (plugin.playerData.containsKey(name)) {
|
||||
|
||||
final String backpack = plugin.playerData.get(name);
|
||||
final List<String> key = plugin.backpackData.get(backpack);
|
||||
final ItemStack cursor = e.getCursor();
|
||||
boolean go = true;
|
||||
|
||||
if (key.get(16) != null
|
||||
&& key.get(16).equalsIgnoreCase("true")) {
|
||||
for (final String whitelist : plugin.backpackWhitelist
|
||||
.get(backpack)) {
|
||||
if (whitelist == null) {
|
||||
continue;
|
||||
}
|
||||
String potentialBackpack = RBUtil
|
||||
.stringToBackpack(whitelist);
|
||||
if (potentialBackpack != null
|
||||
&& plugin.backpackItems
|
||||
.containsKey(potentialBackpack)) {
|
||||
if (curItem.isSimilar(plugin.backpackItems
|
||||
.get(potentialBackpack))
|
||||
|| cursor
|
||||
.isSimilar(plugin.backpackItems
|
||||
.get(potentialBackpack))) {
|
||||
go = false;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (RBUtil.itemsAreEqual(curItem, whitelist)
|
||||
|| RBUtil.itemsAreEqual(cursor,
|
||||
whitelist)) {
|
||||
go = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (go) {
|
||||
e.setCancelled(true);
|
||||
p.sendMessage(ChatColor.RED + "当前物品不能放入背包...");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
for (final String blacklist : plugin.backpackBlacklist
|
||||
.get(backpack)) {
|
||||
if (blacklist == null) {
|
||||
continue;
|
||||
}
|
||||
String potentialBackpack = RBUtil
|
||||
.stringToBackpack(blacklist);
|
||||
if (potentialBackpack != null
|
||||
&& plugin.backpackItems
|
||||
.containsKey(potentialBackpack)) {
|
||||
if (curItem.isSimilar(plugin.backpackItems
|
||||
.get(potentialBackpack))) {
|
||||
e.setCancelled(true);
|
||||
p.sendMessage(ChatColor.RED + "当前物品不能放入背包...");
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
if (RBUtil.itemsAreEqual(curItem, blacklist)) {
|
||||
e.setCancelled(true);
|
||||
p.sendMessage(ChatColor.RED + "当前物品不能放入背包...");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
* Dupes for (String backpack : plugin.backpackItems.keySet()) { if
|
||||
* (p.getInventory().contains(plugin.backpackItems.get(backpack))) {
|
||||
* plugin.getServer().getScheduler().runTaskLater(plugin, new
|
||||
* Runnable() {
|
||||
*
|
||||
* @Override public void run() { Location loc = p.getLocation();
|
||||
* World world = p.getWorld(); for (ItemStack item :
|
||||
* p.getInventory().getContents()) { if (item != null &&
|
||||
* item.hasItemMeta() && item.getAmount() > 1) { for (String
|
||||
* backpack : plugin.backpacks) { String unstackable =
|
||||
* plugin.backpackData.get(backpack).get(18); if (unstackable ==
|
||||
* null || unstackable.equalsIgnoreCase("false")) { continue; } if
|
||||
* (item.isSimilar(plugin.backpackItems.get(backpack))) { while
|
||||
* (item.getAmount() > 1) { item.setAmount(item.getAmount() - 1); if
|
||||
* (p.getInventory().firstEmpty() != -1) {
|
||||
* p.getInventory().setItem(p.getInventory().firstEmpty(), item);
|
||||
* p.updateInventory(); } else { world.dropItemNaturally(loc,
|
||||
* plugin.backpackItems.get(backpack)); } } } } } } } }, 2L); break;
|
||||
* } }
|
||||
*/
|
||||
|
||||
}
|
||||
}
|
||||
}
|
267
src/cn/citycraft/plugins/listeners/PlayerListener.java
Normal file
267
src/cn/citycraft/plugins/listeners/PlayerListener.java
Normal file
@ -0,0 +1,267 @@
|
||||
package cn.citycraft.plugins.listeners;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.sql.SQLException;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.block.Action;
|
||||
import org.bukkit.event.entity.PlayerDeathEvent;
|
||||
import org.bukkit.event.player.PlayerDropItemEvent;
|
||||
import org.bukkit.event.player.PlayerInteractEvent;
|
||||
import org.bukkit.event.player.PlayerPickupItemEvent;
|
||||
import org.bukkit.event.player.PlayerRespawnEvent;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import cn.citycraft.plugins.RealBackpacks;
|
||||
import cn.citycraft.plugins.util.MysqlFunctions;
|
||||
import cn.citycraft.plugins.util.RBUtil;
|
||||
import cn.citycraft.plugins.util.Serialization;
|
||||
|
||||
public class PlayerListener implements Listener {
|
||||
|
||||
private final RealBackpacks plugin;
|
||||
|
||||
private final HashMap<String, String> deadPlayers = new HashMap<String, String>();
|
||||
|
||||
public PlayerListener(final RealBackpacks plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGH)
|
||||
public void onInteract(final PlayerInteractEvent e) {
|
||||
if (e.getAction().equals(Action.PHYSICAL)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Action act = e.getAction();
|
||||
final Player p = e.getPlayer();
|
||||
final ItemStack item = p.getItemInHand();
|
||||
final String name = p.getName();
|
||||
if (item.hasItemMeta()) {
|
||||
for (final String backpack : plugin.backpacks) {
|
||||
final List<String> key = plugin.backpackData.get(backpack);
|
||||
if (item.getItemMeta().hasDisplayName() && item.getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', key.get(3)))) {
|
||||
if (plugin.isUsingPerms() && !p.hasPermission("rb." + backpack + ".use")) {
|
||||
p.sendMessage(ChatColor.RED + "你没有打开此背包的权限...");
|
||||
continue;
|
||||
}
|
||||
final String openWith = key.get(15);
|
||||
if (openWith != null) {
|
||||
if (openWith.equalsIgnoreCase("left_click")) {
|
||||
if (act.equals(Action.RIGHT_CLICK_AIR)) {
|
||||
continue;
|
||||
}
|
||||
if (act.equals(Action.RIGHT_CLICK_BLOCK)) {
|
||||
continue;
|
||||
}
|
||||
} else if (openWith.equalsIgnoreCase("right_click")) {
|
||||
if (act.equals(Action.LEFT_CLICK_AIR)) {
|
||||
continue;
|
||||
}
|
||||
if (act.equals(Action.LEFT_CLICK_BLOCK)) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (act.equals(Action.LEFT_CLICK_AIR)) {
|
||||
continue;
|
||||
}
|
||||
if (act.equals(Action.LEFT_CLICK_BLOCK)) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (act.equals(Action.RIGHT_CLICK_BLOCK)) {
|
||||
e.setCancelled(true);
|
||||
p.updateInventory();
|
||||
}
|
||||
Inventory inv = null;
|
||||
if (plugin.isUsingMysql()) {
|
||||
try {
|
||||
inv = MysqlFunctions.getBackpackInv(name, backpack);
|
||||
} catch (final SQLException e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
if (inv == null) {
|
||||
inv = plugin.getServer().createInventory(p, Integer.parseInt(key.get(0)), ChatColor.translateAlternateColorCodes('&', key.get(3)));
|
||||
}
|
||||
} else {
|
||||
final File file = new File(plugin.getDataFolder() + File.separator + "userdata" + File.separator + name + ".yml");
|
||||
if (!file.exists()) {
|
||||
try {
|
||||
file.createNewFile();
|
||||
} catch (final IOException e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
}
|
||||
final FileConfiguration config = YamlConfiguration.loadConfiguration(file);
|
||||
if (!config.isSet(backpack + ".Inventory")) {
|
||||
inv = plugin.getServer().createInventory(p, Integer.parseInt(key.get(0)), ChatColor.translateAlternateColorCodes('&', key.get(3)));
|
||||
} else {
|
||||
inv = Serialization.toInventory(config.getStringList(backpack + ".Inventory"), key.get(3), Integer.parseInt(key.get(0)));
|
||||
}
|
||||
}
|
||||
if (p.getOpenInventory().getTopInventory() != null) {
|
||||
p.closeInventory();
|
||||
}
|
||||
plugin.playerData.put(name, backpack);
|
||||
p.openInventory(inv);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
|
||||
public void onDrop(final PlayerDropItemEvent e) {
|
||||
final Player p = e.getPlayer();
|
||||
final String name = p.getName();
|
||||
final ItemStack item = e.getItemDrop().getItemStack();
|
||||
if (plugin.slowedPlayers.contains(name)) {
|
||||
for (final String backpack : plugin.backpacks) {
|
||||
if (plugin.backpackItems.get(backpack).equals(item)) {
|
||||
plugin.slowedPlayers.remove(name);
|
||||
p.setWalkSpeed(0.2F);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
|
||||
public void onPickup(final PlayerPickupItemEvent e) {
|
||||
final ItemStack item = e.getItem().getItemStack();
|
||||
final Player p = e.getPlayer();
|
||||
final String name = p.getName();
|
||||
for (final String backpack : plugin.backpacks) {
|
||||
if (!item.isSimilar(plugin.backpackItems.get(backpack))) {
|
||||
continue;
|
||||
}
|
||||
final List<String> key = plugin.backpackData.get(backpack);
|
||||
if (!plugin.slowedPlayers.contains(name)) {
|
||||
plugin.slowedPlayers.add(name);
|
||||
}
|
||||
p.setWalkSpeed(Float.parseFloat(key.get(9)));
|
||||
if (key.get(18) != null && key.get(18).equalsIgnoreCase("true")) {
|
||||
final Inventory inv = p.getInventory();
|
||||
final Location loc = e.getItem().getLocation();
|
||||
final ItemStack backpackItem = plugin.backpackItems.get(backpack);
|
||||
int emptySlots = 0, itemAmount = item.getAmount();
|
||||
for (final ItemStack invItem : inv.getContents()) {
|
||||
if (invItem == null) {
|
||||
emptySlots++;
|
||||
}
|
||||
}
|
||||
if (emptySlots == 0) {
|
||||
e.setCancelled(true);
|
||||
} else {
|
||||
e.getItem().remove();
|
||||
e.setCancelled(true);
|
||||
if (itemAmount > emptySlots) {
|
||||
final ItemStack dropItem = backpackItem;
|
||||
dropItem.setAmount(itemAmount - emptySlots);
|
||||
p.getWorld().dropItem(loc, dropItem);
|
||||
itemAmount = emptySlots;
|
||||
}
|
||||
if (itemAmount == 1) {
|
||||
backpackItem.setAmount(1);
|
||||
inv.setItem(inv.firstEmpty(), backpackItem);
|
||||
} else if (itemAmount > 1) {
|
||||
int x = itemAmount;
|
||||
backpackItem.setAmount(1);
|
||||
while (x > 0) {
|
||||
x--;
|
||||
inv.setItem(inv.firstEmpty(), backpackItem);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
|
||||
public void onDeath(final PlayerDeathEvent e) {
|
||||
final Player p = e.getEntity();
|
||||
final String name = p.getName();
|
||||
for (final String backpack : plugin.backpacks) {
|
||||
if (!p.getInventory().contains(plugin.backpackItems.get(backpack))) {
|
||||
continue;
|
||||
}
|
||||
p.setWalkSpeed(0.2F);
|
||||
final List<String> key = plugin.backpackData.get(backpack);
|
||||
if (key.get(5) != null && key.get(5).equalsIgnoreCase("true")) {
|
||||
//Drop contents
|
||||
Inventory binv = null;
|
||||
if (plugin.isUsingMysql()) {
|
||||
try {
|
||||
binv = MysqlFunctions.getBackpackInv(name, backpack);
|
||||
} catch (final SQLException e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
} else {
|
||||
final File file = new File(plugin.getDataFolder() + File.separator + "userdata" + File.separator + name + ".yml");
|
||||
if (!file.exists()) {
|
||||
continue;
|
||||
}
|
||||
final FileConfiguration config = YamlConfiguration.loadConfiguration(file);
|
||||
if (config.getStringList(backpack + ".Inventory") == null) {
|
||||
continue;
|
||||
}
|
||||
binv = Serialization.toInventory(config.getStringList(backpack + ".Inventory"), key.get(3), Integer.parseInt(key.get(0)));
|
||||
}
|
||||
if (plugin.playerData.containsKey(name)) {
|
||||
if (p.getItemOnCursor() != null) {
|
||||
p.setItemOnCursor(null);
|
||||
}
|
||||
}
|
||||
if (binv != null) {
|
||||
for (final ItemStack item : binv.getContents()) {
|
||||
if (item != null) {
|
||||
p.getWorld().dropItemNaturally(p.getLocation(), item);
|
||||
}
|
||||
}
|
||||
}
|
||||
RBUtil.destroyContents(name, backpack);
|
||||
}
|
||||
if (key.get(4) != null && key.get(4).equalsIgnoreCase("true")) {
|
||||
//Destroy contents
|
||||
RBUtil.destroyContents(name, backpack);
|
||||
p.sendMessage(ChatColor.RED + "因为死亡背包物品已销毁...");
|
||||
}
|
||||
if (key.get(6) != null && key.get(6).equalsIgnoreCase("false")) {
|
||||
//Drop backpack
|
||||
e.getDrops().remove(plugin.backpackItems.get(backpack));
|
||||
}
|
||||
if (key.get(7) != null && key.get(7).equalsIgnoreCase("true")) {
|
||||
deadPlayers.put(name, backpack);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
|
||||
public void onRespawn(final PlayerRespawnEvent e) {
|
||||
final Player p = e.getPlayer();
|
||||
final String name = p.getName();
|
||||
for (final String backpack : plugin.backpacks) {
|
||||
final List<String> key = plugin.backpackData.get(backpack);
|
||||
if (key.get(7) != null && key.get(7).equalsIgnoreCase("true") && deadPlayers.get(name) != null && deadPlayers.get(name).equals(backpack)) {
|
||||
//Keep backpack
|
||||
p.getInventory().addItem(plugin.backpackItems.get(backpack));
|
||||
p.updateInventory();
|
||||
deadPlayers.remove(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
135
src/cn/citycraft/plugins/util/MysqlFunctions.java
Normal file
135
src/cn/citycraft/plugins/util/MysqlFunctions.java
Normal file
@ -0,0 +1,135 @@
|
||||
package cn.citycraft.plugins.util;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.List;
|
||||
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
|
||||
import cn.citycraft.plugins.RealBackpacks;
|
||||
|
||||
public class MysqlFunctions {
|
||||
|
||||
private static RealBackpacks plugin;
|
||||
|
||||
public static void setMysqlFunc(final RealBackpacks plugin) {
|
||||
MysqlFunctions.plugin = plugin;
|
||||
}
|
||||
|
||||
public static boolean checkIfTableExists(final String table) {
|
||||
try {
|
||||
final Connection conn = DriverManager.getConnection(plugin.getUrl(), plugin.getUser(), plugin.getPass());
|
||||
final Statement state = conn.createStatement();
|
||||
final DatabaseMetaData dbm = conn.getMetaData();
|
||||
final ResultSet tables = dbm.getTables(null, null, "rb_data", null);
|
||||
state.close();
|
||||
conn.close();
|
||||
if (tables.next()) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} catch (final SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void createTables() {
|
||||
try {
|
||||
final Connection conn = DriverManager.getConnection(plugin.getUrl(), plugin.getUser(), plugin.getPass());
|
||||
final PreparedStatement state = conn.prepareStatement("CREATE TABLE rb_data (player VARCHAR(16), backpack VARCHAR(20), inventory TEXT);");
|
||||
state.executeUpdate();
|
||||
state.close();
|
||||
conn.close();
|
||||
} catch (final SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void addBackpackData(final String playerName, final String backpack, final List<String> invString) throws SQLException {
|
||||
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
final Connection conn = DriverManager.getConnection(plugin.getUrl(), plugin.getUser(), plugin.getPass());
|
||||
PreparedStatement statement = conn.prepareStatement("SELECT EXISTS(SELECT 1 FROM rb_data WHERE player = ? AND backpack = ? LIMIT 1);");
|
||||
statement.setString(1, playerName);
|
||||
statement.setString(2, backpack);
|
||||
final ResultSet res = statement.executeQuery();
|
||||
PreparedStatement state = null;
|
||||
if (res.next()) {
|
||||
if (res.getInt(1) == 1) {
|
||||
state = conn.prepareStatement("UPDATE rb_data SET player=?, backpack=?, inventory=? WHERE player=? AND backpack=?;");
|
||||
state.setString(1, playerName);
|
||||
state.setString(2, backpack);
|
||||
state.setString(3, Serialization.listToString(invString));
|
||||
state.setString(4, playerName);
|
||||
state.setString(5, backpack);
|
||||
} else {
|
||||
state = conn.prepareStatement("INSERT INTO rb_data (player, backpack, inventory) VALUES(?, ?, ?);");
|
||||
state.setString(1, playerName);
|
||||
state.setString(2, backpack);
|
||||
state.setString(3, Serialization.listToString(invString));
|
||||
}
|
||||
}
|
||||
state.executeUpdate();
|
||||
state.close();
|
||||
conn.close();
|
||||
} catch (final SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static Inventory getBackpackInv(final String playerName, final String backpack) throws SQLException {
|
||||
Inventory returnInv = null;
|
||||
try {
|
||||
final Connection conn = DriverManager.getConnection(plugin.getUrl(), plugin.getUser(), plugin.getPass());
|
||||
final PreparedStatement state = conn.prepareStatement("SELECT inventory FROM rb_data WHERE player=? AND backpack=? LIMIT 1;");
|
||||
state.setString(1, playerName);
|
||||
state.setString(2, backpack);
|
||||
final ResultSet res = state.executeQuery();
|
||||
if (res.next()) {
|
||||
final String invString = res.getString(1);
|
||||
if (invString != null) {
|
||||
returnInv = Serialization.toInventory(Serialization.stringToList(invString), ChatColor.translateAlternateColorCodes('&', plugin.backpackData.get(backpack).get(3)), Integer.parseInt(plugin.backpackData.get(backpack).get(0)));
|
||||
} else {
|
||||
returnInv = null;
|
||||
}
|
||||
}
|
||||
state.close();
|
||||
conn.close();
|
||||
} catch (final SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return returnInv;
|
||||
}
|
||||
|
||||
public static void delete(final String playerName, final String backpack) {
|
||||
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
final Connection conn = DriverManager.getConnection(plugin.getUrl(), plugin.getUser(), plugin.getPass());
|
||||
final PreparedStatement state = conn.prepareStatement("DELETE FROM rb_data WHERE player = ? AND backpack = ?;");
|
||||
state.setString(1, playerName);
|
||||
state.setString(2, backpack);
|
||||
state.executeUpdate();
|
||||
state.close();
|
||||
conn.close();
|
||||
} catch (final SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
159
src/cn/citycraft/plugins/util/RBUtil.java
Normal file
159
src/cn/citycraft/plugins/util/RBUtil.java
Normal file
@ -0,0 +1,159 @@
|
||||
package cn.citycraft.plugins.util;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import cn.citycraft.plugins.RealBackpacks;
|
||||
|
||||
public class RBUtil {
|
||||
|
||||
private static RealBackpacks plugin;
|
||||
|
||||
public static void setRBUtil(final RealBackpacks plugin) {
|
||||
RBUtil.plugin = plugin;
|
||||
}
|
||||
|
||||
public static void destroyContents(final String name, final String backpack) {
|
||||
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (plugin.isUsingMysql()) {
|
||||
MysqlFunctions.delete(name, backpack);
|
||||
} else {
|
||||
final File file = new File(plugin.getDataFolder() + File.separator + "userdata" + File.separator + name + ".yml");
|
||||
final FileConfiguration config = YamlConfiguration.loadConfiguration(file);
|
||||
config.set(backpack + ".Inventory", null);
|
||||
try {
|
||||
config.save(file);
|
||||
} catch (final IOException e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static int getFoodLevel(final int foodlevel, final int pLevel, final int listsize, final int key, final List<String> backpackList) {
|
||||
int i = 0;
|
||||
if (plugin.isAveraging()) {
|
||||
int average = 0;
|
||||
for (final String backpack : backpackList) {
|
||||
average += Integer.parseInt(plugin.backpackData.get(backpack).get(key));
|
||||
}
|
||||
i = foodlevel - (average / listsize);
|
||||
} else if (plugin.isAdding()) {
|
||||
int sum = 0;
|
||||
for (final String backpack : backpackList) {
|
||||
sum += Integer.parseInt(plugin.backpackData.get(backpack).get(key));
|
||||
}
|
||||
i = foodlevel - sum;
|
||||
} else {
|
||||
final List<Integer> list = new ArrayList<Integer>();
|
||||
for (final String backpack : backpackList) {
|
||||
list.add(Integer.parseInt(plugin.backpackData.get(backpack).get(key)));
|
||||
}
|
||||
i = foodlevel - Collections.max(list);
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
public static String stringToBackpack(String s) {
|
||||
for (final String b : plugin.backpacks) {
|
||||
if (b.equalsIgnoreCase(s)) {
|
||||
return b;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static ItemStack getItemstackFromString(final String s) {
|
||||
ItemStack item = null;
|
||||
final String[] split = s.split(":");
|
||||
if (split.length == 1) {
|
||||
item = new ItemStack(Material.getMaterial(Integer.parseInt(split[0])), 1);
|
||||
} else {
|
||||
if (split[1].equalsIgnoreCase("enchant") || split[1].equalsIgnoreCase("lore") || split[1].equalsIgnoreCase("all")) {
|
||||
item = new ItemStack(Material.getMaterial(Integer.parseInt(split[0])));
|
||||
} else {
|
||||
item = new ItemStack(Material.getMaterial(Integer.parseInt(split[0])), 1, (byte) Integer.parseInt(split[1]));
|
||||
}
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
public static boolean isEnchanted(final String s) {
|
||||
final String[] split = s.split(":");
|
||||
int i = 0;
|
||||
if (split.length != 1) {
|
||||
for (i = 1; i < split.length; i++) {
|
||||
if (split[i].equalsIgnoreCase("enchant") || split[i].equalsIgnoreCase("all")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean isLored(final String s) {
|
||||
final String[] split = s.split(":");
|
||||
int i = 0;
|
||||
if (split.length != 1) {
|
||||
for (i = 1; i < split.length; i++) {
|
||||
if (split[i].equalsIgnoreCase("lore") || split[i].equalsIgnoreCase("all")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean hasLore(final ItemStack item) {
|
||||
if (item.getItemMeta() != null) {
|
||||
if (item.getItemMeta().hasDisplayName() || item.getItemMeta().hasLore()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean itemsAreEqual(final ItemStack item, final String s) {
|
||||
final boolean lore = hasLore(item);
|
||||
final boolean enchant = item.getEnchantments().size() >= 1;
|
||||
final boolean isLored = isLored(s);
|
||||
final boolean isEnchanted = isEnchanted(s);
|
||||
if (!isLored && !isEnchanted && item.isSimilar(getItemstackFromString(s))) {
|
||||
return true;
|
||||
} else if (item.getType() == getItemstackFromString(s).getType()) {
|
||||
if (enchant && !lore) {
|
||||
if (isEnchanted && !isLored) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else if (enchant && lore) {
|
||||
if (isEnchanted && isLored) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else if (!enchant && lore) {
|
||||
if (isLored && !isEnchanted) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
144
src/cn/citycraft/plugins/util/Serialization.java
Normal file
144
src/cn/citycraft/plugins/util/Serialization.java
Normal file
@ -0,0 +1,144 @@
|
||||
package cn.citycraft.plugins.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.configuration.serialization.ConfigurationSerializable;
|
||||
import org.bukkit.configuration.serialization.ConfigurationSerialization;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import cn.citycraft.plugins.json.JSONArray;
|
||||
import cn.citycraft.plugins.json.JSONException;
|
||||
import cn.citycraft.plugins.json.JSONObject;
|
||||
|
||||
/**
|
||||
* Fancy JSON serialization mostly by evilmidget38.
|
||||
*
|
||||
* @author evilmidget38, gomeow
|
||||
*
|
||||
*/
|
||||
public class Serialization {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static Map<String, Object> toMap(final JSONObject object) throws JSONException {
|
||||
final Map<String, Object> map = new HashMap<String, Object>();
|
||||
final Iterator<String> keys = object.keys();
|
||||
while (keys.hasNext()) {
|
||||
final String key = keys.next();
|
||||
map.put(key, fromJson(object.get(key)));
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private static Object fromJson(final Object json) throws JSONException {
|
||||
if (json == JSONObject.NULL) {
|
||||
return null;
|
||||
} else if (json instanceof JSONObject) {
|
||||
return toMap((JSONObject) json);
|
||||
} else if (json instanceof JSONArray) {
|
||||
return toList((JSONArray) json);
|
||||
} else {
|
||||
return json;
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Object> toList(final JSONArray array) throws JSONException {
|
||||
final List<Object> list = new ArrayList<Object>();
|
||||
for (int i = 0; i < array.length(); i++) {
|
||||
list.add(fromJson(array.get(i)));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<String> stringToList(final String listString) {
|
||||
return Arrays.asList(listString.split("<->"));
|
||||
}
|
||||
|
||||
public static String listToString(final List<String> list) {
|
||||
String newString = null;
|
||||
for (final String s : list) {
|
||||
if (newString == null) {
|
||||
newString = s;
|
||||
} else {
|
||||
newString = newString + "<->" + s;
|
||||
}
|
||||
}
|
||||
return newString;
|
||||
}
|
||||
|
||||
public static List<String> toString(final Inventory inv) {
|
||||
final List<String> result = new ArrayList<String>();
|
||||
final List<ConfigurationSerializable> items = new ArrayList<ConfigurationSerializable>();
|
||||
for (final ItemStack is : inv.getContents()) {
|
||||
items.add(is);
|
||||
}
|
||||
for (final ConfigurationSerializable cs : items) {
|
||||
if (cs == null) {
|
||||
result.add("null");
|
||||
} else {
|
||||
result.add(new JSONObject(serialize(cs)).toString());
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static Inventory toInventory(final List<String> stringItems, final String name, final int size) {
|
||||
final Inventory inv = Bukkit.createInventory(null, size, ChatColor.translateAlternateColorCodes('&', name));
|
||||
final List<ItemStack> contents = new ArrayList<ItemStack>();
|
||||
for (final String piece : stringItems) {
|
||||
if (piece.equalsIgnoreCase("null")) {
|
||||
contents.add(null);
|
||||
} else {
|
||||
try {
|
||||
final ItemStack item = (ItemStack) deserialize(toMap(new JSONObject(piece)));
|
||||
contents.add(item);
|
||||
} catch (final JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
final ItemStack[] items = new ItemStack[contents.size()];
|
||||
for (int x = 0; x < contents.size(); x++) {
|
||||
items[x] = contents.get(x);
|
||||
}
|
||||
inv.setContents(items);
|
||||
return inv;
|
||||
}
|
||||
|
||||
public static Map<String, Object> serialize(final ConfigurationSerializable cs) {
|
||||
final Map<String, Object> serialized = recreateMap(cs.serialize());
|
||||
for (final Entry<String, Object> entry : serialized.entrySet()) {
|
||||
if (entry.getValue() instanceof ConfigurationSerializable) {
|
||||
entry.setValue(serialize((ConfigurationSerializable) entry.getValue()));
|
||||
}
|
||||
}
|
||||
serialized.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, ConfigurationSerialization.getAlias(cs.getClass()));
|
||||
return serialized;
|
||||
}
|
||||
|
||||
public static Map<String, Object> recreateMap(final Map<String, Object> original) {
|
||||
final Map<String, Object> map = new HashMap<String, Object>();
|
||||
for (final Entry<String, Object> entry : original.entrySet()) {
|
||||
map.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public static ConfigurationSerializable deserialize(final Map<String, Object> map) {
|
||||
for (final Entry<String, Object> entry : map.entrySet()) {
|
||||
if (entry.getValue() instanceof Map && ((Map) entry.getValue()).containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) {
|
||||
entry.setValue(deserialize((Map) entry.getValue()));
|
||||
}
|
||||
}
|
||||
return ConfigurationSerialization.deserializeObject(map);
|
||||
}
|
||||
}
|
223
src/config.yml
Normal file
223
src/config.yml
Normal file
@ -0,0 +1,223 @@
|
||||
Data:
|
||||
FileSystem: flatfile
|
||||
MySQL:
|
||||
database: minecraft
|
||||
username: root
|
||||
password:
|
||||
ip: localhost
|
||||
port: 3306
|
||||
Config:
|
||||
usePermissions: true
|
||||
MultipleBackpacksInInventory:
|
||||
average: false
|
||||
add: true
|
||||
Backpacks:
|
||||
Bp-18:
|
||||
Size: 18
|
||||
addGlow: true
|
||||
OpenWith: right_click
|
||||
Purchasable: true
|
||||
Price: 2000
|
||||
UseRecipe: true
|
||||
Override: '0'
|
||||
Recipe:
|
||||
- 334,334,334
|
||||
- 334,54,334
|
||||
- 334,334,334
|
||||
BackpackItem:
|
||||
id: 334
|
||||
name: "&a背包-18"
|
||||
lore:
|
||||
- "&5一个随身携带的背包."
|
||||
- "&b有&d18&b个格子的物品可存放."
|
||||
- "&3移动速度下降5%."
|
||||
- "&6背包掉落或丢失,再次购买即可,物品不丢失."
|
||||
- "&c每种背包仅需购买一次,多个不叠加."
|
||||
UseWhitelist: false
|
||||
ItemWhitelist: []
|
||||
ItemBlacklist:
|
||||
- Bp-18
|
||||
- Bp-27
|
||||
- Bp-36
|
||||
- Bp-45
|
||||
- Bp-54
|
||||
- 276:all
|
||||
onDeath:
|
||||
dropContents: false
|
||||
destroyContents: false
|
||||
dropBackpack: false
|
||||
keepBackpack: false
|
||||
WalkSpeedFeature:
|
||||
enabled: true
|
||||
walkingSpeed: 0.19
|
||||
IncreasedHungerFeature:
|
||||
enabled: true
|
||||
extraHungerBarsToDeplete: 1
|
||||
hungerBarsToSubtractWhenEating: 0
|
||||
Bp-27:
|
||||
Size: 27
|
||||
addGlow: true
|
||||
OpenWith: right_click
|
||||
Purchasable: true
|
||||
Price: 3000
|
||||
UseRecipe: true
|
||||
Override: '0'
|
||||
Recipe:
|
||||
- 334,334,334
|
||||
- 334,146,334
|
||||
- 334,334,334
|
||||
BackpackItem:
|
||||
id: 334
|
||||
name: "&a背包-27"
|
||||
lore:
|
||||
- "&5一个随身携带的背包."
|
||||
- "&b有&d27&b个格子的物品可存放."
|
||||
- "&3移动速度下降10%."
|
||||
- "&6背包掉落或丢失,再次购买即可,物品不丢失."
|
||||
- "&c每种背包仅需购买一次,多个不叠加."
|
||||
UseWhitelist: false
|
||||
ItemWhitelist: []
|
||||
ItemBlacklist:
|
||||
- Bp-18
|
||||
- Bp-27
|
||||
- Bp-36
|
||||
- Bp-45
|
||||
- Bp-54
|
||||
- 276:all
|
||||
onDeath:
|
||||
dropContents: false
|
||||
destroyContents: false
|
||||
dropBackpack: false
|
||||
keepBackpack: false
|
||||
WalkSpeedFeature:
|
||||
enabled: true
|
||||
walkingSpeed: 0.18
|
||||
IncreasedHungerFeature:
|
||||
enabled: true
|
||||
extraHungerBarsToDeplete: 1
|
||||
hungerBarsToSubtractWhenEating: 0
|
||||
Bp-36:
|
||||
Size: 36
|
||||
addGlow: true
|
||||
OpenWith: right_click
|
||||
Purchasable: true
|
||||
Price: 3000
|
||||
UseRecipe: true
|
||||
Override: '0'
|
||||
Recipe:
|
||||
- 334,334,334
|
||||
- 334,154,334
|
||||
- 334,334,334
|
||||
BackpackItem:
|
||||
id: 334
|
||||
name: "&a背包-36"
|
||||
lore:
|
||||
- "&5一个随身携带的背包."
|
||||
- "&b有&d36&b个格子的物品可存放."
|
||||
- "&3移动速度下降15%."
|
||||
- "&6背包掉落或丢失,再次购买即可,物品不丢失."
|
||||
- "&c每种背包仅需购买一次,多个不叠加."
|
||||
UseWhitelist: false
|
||||
ItemWhitelist: []
|
||||
ItemBlacklist:
|
||||
- Bp-18
|
||||
- Bp-27
|
||||
- Bp-36
|
||||
- Bp-45
|
||||
- Bp-54
|
||||
- 276:all
|
||||
onDeath:
|
||||
dropContents: false
|
||||
destroyContents: false
|
||||
dropBackpack: false
|
||||
keepBackpack: false
|
||||
WalkSpeedFeature:
|
||||
enabled: true
|
||||
walkingSpeed: 0.17
|
||||
IncreasedHungerFeature:
|
||||
enabled: true
|
||||
extraHungerBarsToDeplete: 1
|
||||
hungerBarsToSubtractWhenEating: 0
|
||||
Bp-45:
|
||||
Size: 45
|
||||
addGlow: true
|
||||
OpenWith: right_click
|
||||
Purchasable: true
|
||||
Price: 4000
|
||||
UseRecipe: false
|
||||
Override: '0'
|
||||
Recipe:
|
||||
- 334,334,334
|
||||
- 334,154,334
|
||||
- 334,334,334
|
||||
BackpackItem:
|
||||
id: 334
|
||||
name: "&a背包-45"
|
||||
lore:
|
||||
- "&5一个随身携带的背包."
|
||||
- "&b有&d45&b个格子的物品可存放."
|
||||
- "&3移动速度下降20%."
|
||||
- "&6背包掉落或丢失,再次购买即可,物品不丢失."
|
||||
- "&c每种背包仅需购买一次,多个不叠加."
|
||||
UseWhitelist: false
|
||||
ItemWhitelist: []
|
||||
ItemBlacklist:
|
||||
- Bp-18
|
||||
- Bp-27
|
||||
- Bp-36
|
||||
- Bp-45
|
||||
- Bp-54
|
||||
- 276:all
|
||||
onDeath:
|
||||
dropContents: false
|
||||
destroyContents: false
|
||||
dropBackpack: false
|
||||
keepBackpack: false
|
||||
WalkSpeedFeature:
|
||||
enabled: true
|
||||
walkingSpeed: 0.16
|
||||
IncreasedHungerFeature:
|
||||
enabled: true
|
||||
extraHungerBarsToDeplete: 1
|
||||
hungerBarsToSubtractWhenEating: 0
|
||||
Bp-54:
|
||||
Size: 54
|
||||
addGlow: true
|
||||
OpenWith: right_click
|
||||
Purchasable: true
|
||||
Price: 5000
|
||||
UseRecipe: false
|
||||
Override: '0'
|
||||
Recipe:
|
||||
- 334,334,334
|
||||
- 334,154,334
|
||||
- 334,334,334
|
||||
BackpackItem:
|
||||
id: 334
|
||||
name: "&a背包-54"
|
||||
lore:
|
||||
- "&5一个随身携带的背包."
|
||||
- "&b有&d54&b个格子的物品可存放."
|
||||
- "&6背包掉落或丢失,再次购买即可,物品不丢失."
|
||||
- "&c每种背包仅需购买一次,多个不叠加."
|
||||
UseWhitelist: false
|
||||
ItemWhitelist: []
|
||||
ItemBlacklist:
|
||||
- Bp-18
|
||||
- Bp-27
|
||||
- Bp-36
|
||||
- Bp-45
|
||||
- Bp-54
|
||||
- 276:all
|
||||
onDeath:
|
||||
dropContents: false
|
||||
destroyContents: false
|
||||
dropBackpack: false
|
||||
keepBackpack: false
|
||||
WalkSpeedFeature:
|
||||
enabled: true
|
||||
walkingSpeed: 0.2
|
||||
IncreasedHungerFeature:
|
||||
enabled: true
|
||||
extraHungerBarsToDeplete: 1
|
||||
hungerBarsToSubtractWhenEating: 0
|
18
src/plugin.yml
Normal file
18
src/plugin.yml
Normal file
@ -0,0 +1,18 @@
|
||||
name: RealBackpacks
|
||||
main: cn.citycraft.plugins.RealBackpacks
|
||||
version: 1.6.5
|
||||
author: Slayr288,喵♂呜
|
||||
softdepend: [Vault]
|
||||
commands:
|
||||
rb:
|
||||
description: Main commands.
|
||||
aliases: [realbackpacks, realb, rbs]
|
||||
permissions:
|
||||
rb.reload:
|
||||
default: op
|
||||
rb.list:
|
||||
default: op
|
||||
rb.filetomysql:
|
||||
default: op
|
||||
rb.fullview:
|
||||
default: op
|
Loading…
Reference in New Issue
Block a user