diff --git a/.idea/artifacts/McLiveAPI.xml b/.idea/artifacts/McLiveAPI.xml index d5c0dce..a988fca 100644 --- a/.idea/artifacts/McLiveAPI.xml +++ b/.idea/artifacts/McLiveAPI.xml @@ -1,6 +1,6 @@ - $PROJECT_DIR$/out/artifacts/McLiveAPI + $PROJECT_DIR$/../../../Desktop/1.18.1s/plugins diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml index 712ab9d..0f87322 100644 --- a/.idea/jarRepositories.xml +++ b/.idea/jarRepositories.xml @@ -6,6 +6,21 @@ diff --git a/lib/PixelLivePlugin.jar b/lib/PixelLivePlugin.jar index e34e641..3dfb469 100644 Binary files a/lib/PixelLivePlugin.jar and b/lib/PixelLivePlugin.jar differ diff --git a/pom.xml b/pom.xml index 00a1443..419af90 100644 --- a/pom.xml +++ b/pom.xml @@ -1,4 +1,4 @@ - + @@ -49,4 +49,34 @@ + + + papermc-repo + https://repo.papermc.io/repository/maven-public/ + + + sonatype + https://oss.sonatype.org/content/groups/public/ + + + public-rpg + https://repo.aurora-pixels.com/repository/public-rpg/ + + + + + + io.papermc.paper + paper-api + 1.18.2-R0.1-SNAPSHOT + provided + + + cn.hamster3.cdapi + CDTimeAPI + 1.0 + + + + \ No newline at end of file diff --git a/src/main/java/com/io/yutian/livemutually/liveroom/LiveRoomWatcher.java b/src/main/java/com/io/yutian/livemutually/liveroom/LiveRoomWatcher.java index cffe0da..0e54035 100644 --- a/src/main/java/com/io/yutian/livemutually/liveroom/LiveRoomWatcher.java +++ b/src/main/java/com/io/yutian/livemutually/liveroom/LiveRoomWatcher.java @@ -1,7 +1,5 @@ package com.io.yutian.livemutually.liveroom; -import org.bukkit.Bukkit; - import java.util.Objects; import java.util.function.Consumer; diff --git a/src/main/java/com/io/yutian/livemutually/manager/GiftManager.java b/src/main/java/com/io/yutian/livemutually/manager/GiftManager.java new file mode 100644 index 0000000..a82bef7 --- /dev/null +++ b/src/main/java/com/io/yutian/livemutually/manager/GiftManager.java @@ -0,0 +1,242 @@ +package com.io.yutian.livemutually.manager; + +import com.io.yutian.mclive.Main; +import com.io.yutian.mclive.data.database.SqlManager; +import com.io.yutian.mclive.util.ConfigYml; +import com.io.yutian.mclive.util.SqlUtil; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; + +public class GiftManager { + + private double totalMoney; + private LinkedHashMap giftMap = new LinkedHashMap<>(); + private SqlUtil sqlUtil; + private SqlManager sqlManager; + + public GiftManager() { + totalMoney = 0; + giftMap.put("小心心", 1); + giftMap.put("人气票", 1); + giftMap.put("闪耀星辰", 1); + giftMap.put("加油鸭", 1); + giftMap.put("比心兔兔", 1); + giftMap.put("热气球", 1); + giftMap.put("爱你哟", 1); + giftMap.put("天鹅之梦", 1); + giftMap.put("Thuglife", 1); + giftMap.put("粘人小狗", 1); + giftMap.put("粉丝团灯牌", 1); + giftMap.put("大啤酒", 2); + giftMap.put("玫瑰", 1); + giftMap.put("抖音", 1); + giftMap.put("称心如意", 1); + giftMap.put("你最好看", 2); + giftMap.put("助力票", 1); + giftMap.put("荣耀擂鼓", 99); + giftMap.put("宠粉季", 1); + giftMap.put("兔耳朵", 99); + giftMap.put("游戏手柄", 99); + giftMap.put("冰镇西瓜", 99); + giftMap.put("为你闪耀", 9); + giftMap.put("棒棒糖", 9); + giftMap.put("鲜花", 10); + giftMap.put("亲吻", 99); + giftMap.put("跑车", 1200); + giftMap.put("礼花筒", 199); + giftMap.put("捏捏小脸", 99); + giftMap.put("鹿仙子", 99); + giftMap.put("夏威夷花环", 99); + giftMap.put("爱的纸鹤", 99); + giftMap.put("送你花花", 49); + giftMap.put("女神花环", 99); + giftMap.put("鱼你一起", 99); + giftMap.put("真爱玫瑰", 366); + giftMap.put("为你举牌", 199); + giftMap.put("龙抬头", 99); + giftMap.put("花开烂漫", 466); + giftMap.put("比心", 199); + giftMap.put("真的爱你", 520); + giftMap.put("万象烟花", 688); + giftMap.put("私人飞机", 3000); + giftMap.put("浪漫烟花", 599); + giftMap.put("闪亮登场", 460); + giftMap.put("多喝热水", 126); + giftMap.put("一点心意", 266); + giftMap.put("荧光棒", 99); + giftMap.put("娶你回家", 599); + giftMap.put("掌上明珠", 888); + giftMap.put("摧残舞台", 899); + giftMap.put("星星点灯", 268); + giftMap.put("一束花开", 366); + giftMap.put("小傻猪", 299); + giftMap.put("环球旅行车", 650); + giftMap.put("爱的守护", 299); + giftMap.put("好运莲莲鸭", 299); + giftMap.put("日出相伴", 726); + giftMap.put("永生花", 520); + giftMap.put("纸短情长", 921); + giftMap.put("直升机", 2999); + giftMap.put("蝶·连理枝", 280); + giftMap.put("爱情树下", 599); + giftMap.put("灵龙现世", 600); + giftMap.put("爱心煎蛋", 99); + giftMap.put("夏日回忆", 1000); + giftMap.put("抖音1号", 10001); + giftMap.put("繁花秘语", 1314); + giftMap.put("ONE礼挑一", 299); + giftMap.put("重拳出击", 199); + giftMap.put("花落长亭", 1588); + giftMap.put("浪漫恋人", 1999); + giftMap.put("花海泛舟", 2800); + giftMap.put("豪华邮轮", 6000); + giftMap.put("环游世界", 3000); + giftMap.put("蝶·书中情", 750); + giftMap.put("带你去海边", 4500); + giftMap.put("蜜蜂叮叮", 1000); + giftMap.put("奇幻八音盒", 2399); + giftMap.put("光之祝福", 1999); + giftMap.put("消暑罐头车", 1500); + giftMap.put("月色山茶花", 1999); + giftMap.put("为你而来", 1688); + giftMap.put("点亮孤单", 1800); + giftMap.put("浪漫营地", 1699); + giftMap.put("薰衣草庄园", 3300); + giftMap.put("红墙白雪", 1688); + giftMap.put("华灯初上", 5000); + giftMap.put("嘉年华", 30000); + giftMap.put("单车恋人", 1899); + giftMap.put("为爱启航", 10001); + giftMap.put("镜中奇缘", 1500); + giftMap.put("仲夏夜之梦", 8999); + giftMap.put("龙珠纳福", 2388); + giftMap.put("蝶·比翼鸟", 1700); + giftMap.put("无畏守护", 10168); + giftMap.put("壁上飞仙", 4999); + giftMap.put("海上生明月", 4166); + giftMap.put("铁甲柔情", 3800); + giftMap.put("心动丘比特", 4321); + giftMap.put("变形战车", 5500); + giftMap.put("抖音飞艇", 20000); + giftMap.put("冰冻战车", 3000); + giftMap.put("星际玫瑰", 7500); + giftMap.put("奏响人生", 3666); + giftMap.put("摩天大厦", 8222); + giftMap.put("传送门", 2999); + giftMap.put("云中秘境", 13140); + giftMap.put("火龙爆发", 5000); + giftMap.put("福佑万家", 4888); + giftMap.put("天空之镜", 6399); + giftMap.put("情定三生", 9666); + giftMap.put("月下瀑布", 6666); + giftMap.put("金鳞化龙", 9000); + giftMap.put("蝶·化蝶飞", 10999); + giftMap.put("无尽浪漫", 19999); + giftMap.put("云霄大厦", 7888); + giftMap.put("梦幻城堡", 28888); + giftMap.put("真爱永恒", 8999); + giftMap.put("跨时空之恋", 9000); + giftMap.put("炫彩射击", 1888); + giftMap.put("一路有你", 17999); + giftMap.put("浪漫马车", 28888); + giftMap.put("蝶·寄相思", 6800); + giftMap.put("梦回紫禁城", 8666); + giftMap.put("小纸条", 399); + giftMap.put("如意锦囊", 99); + giftMap.put("星光瓶", 900); + giftMap.put("一直陪伴你", 520); + giftMap.put("动次打次", 2999); + giftMap.put("宇宙之心", 18888); + } + + public List getGiftNameList() { + return new ArrayList<>(giftMap.keySet()); + } + + public SqlUtil getSqlUtil() { + return sqlUtil; + } + + public SqlManager getSqlManager() { + return sqlManager; + } + + public void LinkMySqlData() { + String SQL_Host = "gz-cdb-r9koldtt.sql.tencentcdb.com"; + String SQL_Port = "29320"; + String SQL_Users = "root"; + String SQL_Password = "Pixel@123456"; + String SQL_Database = "mclivedata"; + sqlManager = new SqlManager(); + sqlUtil = new SqlUtil(SQL_Host, SQL_Port, SQL_Database, SQL_Users, SQL_Password); + sqlManager.createTable(); + } + + public int getGiftMoney(String giftName) { + if (giftMap.get(giftName) == null) { + return 1; + } + return giftMap.get(giftName); + } + + public double getTotalMoney() { + return totalMoney; + } + + public void defaultTotalMoney() { + if (this.totalMoney <= 0) { + for (Player player : Bukkit.getOnlinePlayers()) { + String name = player.getName(); + if (Main.configYml.getRoomId(name) == null) { + return; + } + String tiktok = Main.configYml.getRoomId(name); + this.totalMoney = sqlManager.getZhuboIncome(tiktok) * 10; + } + } + } + + public void addTotalMoney(String name, int money) { + if (this.totalMoney <= 0) { + if (Main.configYml.getRoomId(name) == null) { + return; + } + String tiktok = Main.configYml.getRoomId(name); + this.totalMoney = sqlManager.getZhuboIncome(tiktok) * 10; + } + if (money >= 5000) { + SaveZhuboData(name); + } + this.totalMoney += money; + } + + public void addTotalMoney(String name, int money, long amount) { + if (this.totalMoney <= 0) { + if (Main.configYml.getRoomId(name) == null) { + return; + } + String tiktok = Main.configYml.getRoomId(name); + this.totalMoney = sqlManager.getZhuboIncome(tiktok) * 10; + } + int newMoney = (int) (money * amount); + if (newMoney >= 5000) { + SaveZhuboData(name); + } + this.totalMoney += newMoney; + } + + public void SaveZhuboData(String name) { + if (Main.configYml.getRoomId(name) == null) { + return; + } + String tiktok = Main.configYml.getRoomId(name); + if (ConfigYml.mysqlState) { + sqlManager.SavePlayerData(tiktok); + } + } + +} diff --git a/src/main/java/com/io/yutian/livemutually/manager/KSLiveRoomManager.java b/src/main/java/com/io/yutian/livemutually/manager/KSLiveRoomManager.java index 3e5c933..5bbf9a0 100644 --- a/src/main/java/com/io/yutian/livemutually/manager/KSLiveRoomManager.java +++ b/src/main/java/com/io/yutian/livemutually/manager/KSLiveRoomManager.java @@ -1,21 +1,17 @@ package com.io.yutian.livemutually.manager; -import cn.hamster3.cdapi.CDTimeAPI; -import com.io.yutian.mclive.*; import com.io.yutian.pixelliveplugin.PixelLiveAPI; -import com.io.yutian.verify.AESUtil; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.List; -import java.util.regex.Pattern; public class KSLiveRoomManager { - public static List livepluginList = new ArrayList<>(); + private static List players = new ArrayList<>(); public static boolean isConnected(Player player) { - if(livepluginList.contains(player)){ + if (players.contains(player)) { return true; } return false; @@ -25,9 +21,13 @@ public class KSLiveRoomManager { if (!isConnected(player)) { return; } - livepluginList.remove(player); + players.remove(player); PixelLiveAPI.disconnect(player); player.sendMessage("§c[系统]§b已断开直播间连接..."); } + public static List getPlayers() { + return players; + } + } diff --git a/src/main/java/com/io/yutian/livemutually/manager/RankManager.java b/src/main/java/com/io/yutian/livemutually/manager/RankManager.java new file mode 100644 index 0000000..7f33c49 --- /dev/null +++ b/src/main/java/com/io/yutian/livemutually/manager/RankManager.java @@ -0,0 +1,115 @@ +package com.io.yutian.livemutually.manager; + +import com.io.yutian.mclive.Main; +import com.io.yutian.mclive.data.UserResourceData; +import com.io.yutian.pixelengine.api.EngineAPI; +import com.io.yutian.pixelengine.api.util.ImageUtil; +import json.JSONObject; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; + +import java.io.File; +import java.io.IOException; +import java.util.*; +import java.util.stream.Collectors; + +public class RankManager { + + private static List topCache = new ArrayList<>(); + private static Map userDatas = new HashMap<>(); + + public static void addUserAmount(String userName, long score) { + if (userName == null || userName.isEmpty() || userName.length() == 0) { + return; + } + long amount = userDatas.getOrDefault(userName, score); + userDatas.put(userName, amount + score); + Bukkit.getScheduler().runTaskAsynchronously(Main.plugin, RankManager::update); + save(); + } + + public static void update() { + List tops = userDatas.entrySet().stream() + .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) + .limit(3) + .map(Map.Entry::getKey) + .collect(Collectors.toList()); + if (topCache.isEmpty() || !topCache.equals(tops)) { + topCache = tops; + for (int i = 0; i < 3; i++) { + if (i >= tops.size()) { + return; + } + String name = tops.get(i); + UserResourceData userResourceData = UserManager.getUserResourceData(name); + if (userResourceData != null) { + int finalI = i; + String base64 = ImageUtil.getCacheImageBase64(userResourceData.getNickName(), userResourceData.getAvatarThumbUrl(), (newBase64) -> { + for (Player player : Bukkit.getOnlinePlayers()) { + EngineAPI.getRankAPI().setRankData(player, finalI + 1, newBase64, userResourceData.getLevel()); + } + }); + for (Player player : Bukkit.getOnlinePlayers()) { + EngineAPI.getRankAPI().setRankData(player, i + 1, base64, userResourceData.getLevel()); + } + } + } + } + } + + public static long getUserAmount(String userName) { + return userDatas.getOrDefault(userName, 0L); + } + + public static void save() { + File file = new File(Main.plugin.getDataFolder(), "rank.yml"); + if (!file.exists()) { + try { + file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } + FileConfiguration config = YamlConfiguration.loadConfiguration(file); + for (Map.Entry entry : userDatas.entrySet()) { + String key = entry.getKey(); + if (key == null || key.isEmpty() || key.length() == 0) { + continue; + } + try { + config.set(key, entry.getValue()); + } catch (Exception e) { + } + } + try { + config.save(file); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void load() { + File file = new File(Main.plugin.getDataFolder(), "rank.yml"); + if (!file.exists()) { + try { + file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } + FileConfiguration config = YamlConfiguration.loadConfiguration(file); + for (String key : config.getKeys(false)) { + userDatas.put(key, config.getLong(key)); + } + } + + public static void clear() { + File file = new File(Main.plugin.getDataFolder(), "rank.yml"); + file.delete(); + userDatas.clear(); + } + +} diff --git a/src/main/java/com/io/yutian/livemutually/manager/UserData.java b/src/main/java/com/io/yutian/livemutually/manager/UserData.java deleted file mode 100644 index 5118082..0000000 --- a/src/main/java/com/io/yutian/livemutually/manager/UserData.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.io.yutian.livemutually.manager; - -import java.util.HashMap; - -public class UserData { - - private String userName; - // 礼物 礼物数据 - private HashMap giftData = new HashMap<>(); - - public UserData(String userName){ - this.userName = userName; - this.giftData = new HashMap<>(); - } - - public String getUserName() { - return userName; - } - - // 判断本次赠送礼物是否已送过 - public boolean isExitGift(String giftName){ - if(giftData.get(giftName) != null){ - return true; - } - return false; - } - - public GiftData getGiftsData(String giftName){ - if(giftData.get(giftName) != null){ - return giftData.get(giftName); - } - return null; - } - - public void createGiftsData(String giftName,long giftAmount){ - long sendTime = System.currentTimeMillis(); - giftData.put(giftName,new GiftData(giftName,giftAmount,sendTime)); - } -} diff --git a/src/main/java/com/io/yutian/livemutually/manager/UserManager.java b/src/main/java/com/io/yutian/livemutually/manager/UserManager.java new file mode 100644 index 0000000..2d22bfe --- /dev/null +++ b/src/main/java/com/io/yutian/livemutually/manager/UserManager.java @@ -0,0 +1,20 @@ +package com.io.yutian.livemutually.manager; + +import com.io.yutian.mclive.data.UserResourceData; + +import java.util.HashMap; +import java.util.Map; + +public class UserManager { + + private static Map userResourceDataMap = new HashMap<>(); + + public static void setUserResourceData(String userName, UserResourceData userResourceData) { + userResourceDataMap.put(userName, userResourceData); + } + + public static UserResourceData getUserResourceData(String userName) { + return userResourceDataMap.get(userName); + } + +} diff --git a/src/main/java/com/io/yutian/livemutually/wss/KSAPILiveRoomWatcher.java b/src/main/java/com/io/yutian/livemutually/wss/KSAPILiveRoomWatcher.java index f25d721..6a678d9 100644 --- a/src/main/java/com/io/yutian/livemutually/wss/KSAPILiveRoomWatcher.java +++ b/src/main/java/com/io/yutian/livemutually/wss/KSAPILiveRoomWatcher.java @@ -15,19 +15,19 @@ public class KSAPILiveRoomWatcher extends LiveRoomWatcher { public KSAPILiveRoomWatcher(Player player) { this.player = player; onChat(chat -> { - Bukkit.getScheduler().runTask(Main.plugin, ()-> { + Bukkit.getScheduler().runTask(Main.plugin, () -> { LiveChatEvents event = new LiveChatEvents(player, chat.user(), chat.content()); Bukkit.getPluginManager().callEvent(event); }); }); onUser(user -> { - Bukkit.getScheduler().runTask(Main.plugin, ()-> { + Bukkit.getScheduler().runTask(Main.plugin, () -> { LiveEnterEvents event = new LiveEnterEvents(player, user); Bukkit.getPluginManager().callEvent(event); }); }); onLike(like -> { - Bukkit.getScheduler().runTask(Main.plugin, ()-> { + Bukkit.getScheduler().runTask(Main.plugin, () -> { LiveLikeEvents event = new LiveLikeEvents(player, like.user(), like.count()); Bukkit.getPluginManager().callEvent(event); }); diff --git a/src/main/java/com/io/yutian/mclive/Main.java b/src/main/java/com/io/yutian/mclive/Main.java index c27d5c4..3d9b872 100644 --- a/src/main/java/com/io/yutian/mclive/Main.java +++ b/src/main/java/com/io/yutian/mclive/Main.java @@ -1,7 +1,9 @@ package com.io.yutian.mclive; import com.io.yutian.livemutually.manager.KSLiveRoomManager; -import com.io.yutian.mclive.data.GiftManage; +import com.io.yutian.livemutually.manager.GiftManager; +import com.io.yutian.livemutually.manager.RankManager; +import com.io.yutian.livemutually.manager.UserManager; import com.io.yutian.mclive.event.ZhuboAPI; import com.io.yutian.mclive.listener.JoinGameRoom; import com.io.yutian.mclive.listener.LiveAdminGui; @@ -9,13 +11,14 @@ import com.io.yutian.mclive.listener.SoundsMenu; import com.io.yutian.mclive.live.LiveEvent; import com.io.yutian.mclive.live.ModEvent; import com.io.yutian.mclive.util.ConfigYml; +import com.io.yutian.pixelliveplugin.PixelLiveAPI; import org.bukkit.Bukkit; import org.bukkit.Sound; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.*; +import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitRunnable; @@ -30,45 +33,10 @@ public class Main extends JavaPlugin { public static Main plugin; public static boolean check_plugin = false; public static ConfigYml configYml; - public static GiftManage giftManage; + public static GiftManager giftManager; public static boolean giftStatistics = true; - @Override - public void onEnable() { - plugin = this; - SendPluginsAuthorMessage(Bukkit.getConsoleSender()); - configYml = new ConfigYml(getConfig()); - if (giftStatistics){ - giftManage = new GiftManage(); - giftManage.LinkMySqlData(); - } - addSoundKeyList(); - getServer().getPluginManager().registerEvents(new LiveAdminGui(),this); - getServer().getPluginManager().registerEvents(new JoinGameRoom(),this); - getServer().getPluginManager().registerEvents(new ModEvent(),this); - getServer().getPluginManager().registerEvents(new LiveEvent(configYml),this); - getServer().getPluginManager().registerEvents(new SoundsMenu(),this); - Bukkit.getConsoleSender().sendMessage("§b[整蛊MC直播] §7当前版本: §ev"+plugin.getDescription().getVersion()); - Plugin plugin = getServer().getPluginManager().getPlugin(configYml.getGameMode()); - if (plugin != null) { - check_plugin = true; - Bukkit.getConsoleSender().sendMessage("§b[整蛊MC直播] §a已激活游戏模式"); - if(giftStatistics) { - Bukkit.getScheduler().runTaskTimerAsynchronously(this, new Runnable() { - @Override - public void run() { - for (Player player : Bukkit.getOnlinePlayers()) { - giftManage.SaveZhuboData(player.getName()); - } - } - }, 0L, 24000L); - } - } else { - Bukkit.getConsoleSender().sendMessage("§b[整蛊MC直播] §c未检测到§a<"+configYml.getGameMode()+">§c游戏插件."); - } - } - - public static void addSoundKeyList(){ + public static void addSoundKeyList() { List stringList = new ArrayList<>(); stringList.add("youbom"); stringList.add("oi"); @@ -121,11 +89,91 @@ public class Main extends JavaPlugin { SoundsMenu.soundList.addAll(stringList); } + public static void SendPluginsAuthorMessage(CommandSender sender) { + sender.sendMessage(" "); + sender.sendMessage("§b ██ ████"); + sender.sendMessage("§b ██"); + sender.sendMessage("§b██░███▒ ████ ███ ███ ░████▒ ██"); + sender.sendMessage("§b███████▒ ████ ██▒▒██ ░██████▒ ██"); + sender.sendMessage("§b███ ███ ██ ▒████▒ ██▒ ▒██ ██"); + sender.sendMessage("§b██░ ░██ ██ ████ ████████ ██"); + sender.sendMessage("§b██ ██ ██ ▒██▒ ████████ ██"); + sender.sendMessage("§b██░ ░██ ██ ████ ██ ██"); + sender.sendMessage("§b███ ███ ██ ▒████▒ ███░ ▒█ ██▒"); + sender.sendMessage("§b███████▒ ████████ ██▒▒██ ░███████ █████"); + sender.sendMessage("§b██░███▒ ████████ ███ ███ ░█████▒ ░████"); + sender.sendMessage("§b██"); + sender.sendMessage("§b█ 弹幕互动引擎 由极光像素工作室提供技术支持!!"); + sender.sendMessage("§b█ 如有使用问题可联系售后: §d" + getAuthorFile().getString("author")); + sender.sendMessage("" + getAuthorFile().getString("linemessage")); + } + + public static FileConfiguration getAuthorFile() { + File ShopMenufile = new File("plugins/PluginMetrics", "config.yml"); + return YamlConfiguration.loadConfiguration(ShopMenufile); + } + + public static String HideName(String audience) { + if (audience.length() <= 2) { + return "**"; + } + // 获取第一个和第二个字符 + char firstChar = audience.charAt(0); + char lastChar = audience.charAt(audience.length() - 1); + // 构建屏蔽后的字符串 + StringBuilder maskedString = new StringBuilder(); + for (int i = 1; i < audience.length() - 1; i++) { + maskedString.append('*'); + } + return String.valueOf(firstChar) + maskedString + lastChar; + } + + public static String getMinecraftVersion() { + String packageName = Bukkit.getServer().getClass().getPackage().getName(); + String version = packageName.substring(packageName.lastIndexOf('.') + 1); + return version; + } + + @Override + public void onEnable() { + plugin = this; + SendPluginsAuthorMessage(Bukkit.getConsoleSender()); + configYml = new ConfigYml(getConfig()); + if (giftStatistics) { + giftManager = new GiftManager(); + giftManager.LinkMySqlData(); + } + addSoundKeyList(); + getServer().getPluginManager().registerEvents(new LiveAdminGui(), this); + getServer().getPluginManager().registerEvents(new JoinGameRoom(), this); + getServer().getPluginManager().registerEvents(new ModEvent(), this); + getServer().getPluginManager().registerEvents(new LiveEvent(configYml), this); + getServer().getPluginManager().registerEvents(new SoundsMenu(), this); + Bukkit.getConsoleSender().sendMessage("§b[整蛊MC直播] §7当前版本: §ev" + plugin.getDescription().getVersion()); + Plugin plugin = getServer().getPluginManager().getPlugin(configYml.getGameMode()); + check_plugin = true; + if (plugin != null) { + RankManager.load(); + check_plugin = true; + Bukkit.getConsoleSender().sendMessage("§b[整蛊MC直播] §a已激活游戏模式"); + if (giftStatistics) { + Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> { + for (Player player : Bukkit.getOnlinePlayers()) { + giftManager.SaveZhuboData(player.getName()); + } + }, 0L, 24000L); + } + } else { + Bukkit.getConsoleSender().sendMessage("§b[整蛊MC直播] §c未检测到§a<" + configYml.getGameMode() + ">§c游戏插件."); + } + } + + @Override public void onDisable() { - if(giftStatistics && ConfigYml.mysqlState) { + if (giftStatistics && ConfigYml.mysqlState) { for (Player player : Bukkit.getOnlinePlayers()) { - giftManage.SaveZhuboData(player.getName()); + giftManager.SaveZhuboData(player.getName()); } } } @@ -133,7 +181,7 @@ public class Main extends JavaPlugin { @Override public boolean onCommand(CommandSender sender, Command command, String Command, String[] args) { if (Command.equalsIgnoreCase("sounds")) { - SoundsMenu.OpenGui((Player) sender,1); + SoundsMenu.OpenGui((Player) sender, 1); } if (Command.equalsIgnoreCase("mclive")) { if (args.length == 0) { @@ -151,14 +199,20 @@ public class Main extends JavaPlugin { sender.sendMessage(""); return true; } + if (args.length == 1 && args[0].equalsIgnoreCase("test")) { + Player player = (Player) sender; + + PixelLiveAPI.connect(player, "127.0.0.1", 9018); + return true; + } if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { Main.configYml.ReloadConfig(); sender.sendMessage("§c[系统]§a配置文件已重载"); return true; } if (args.length == 1 && args[0].equalsIgnoreCase("save")) { - for (Player player : Bukkit.getOnlinePlayers()){ - giftManage.SaveZhuboData(player.getName()); + for (Player player : Bukkit.getOnlinePlayers()) { + giftManager.SaveZhuboData(player.getName()); } sender.sendMessage("§c[系统]§a数据已提交至云数据库."); return true; @@ -177,7 +231,7 @@ public class Main extends JavaPlugin { } if (args.length == 1 && args[0].equalsIgnoreCase("stop")) { ZhuboAPI.wsRoomIdSame.clear(); - for (Player player : KSLiveRoomManager.livepluginList) { + for (Player player : KSLiveRoomManager.getPlayers()) { KSLiveRoomManager.disconnect(player); } Bukkit.broadcastMessage("§c[系统]§a已断开所有主播的连接."); @@ -204,14 +258,14 @@ public class Main extends JavaPlugin { Main.configYml.SaveConfigYml(); sender.sendMessage("§c[系统]§a直播间已设置 §e" + playName + " §a--> §e" + room_id); player.resetTitle(); - player.sendTitle("§a§l绑定成功!","§6已绑定抖音号: §f"+room_id,0,40,20); - player.playSound(player.getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP,1,1); + player.sendTitle("§a§l绑定成功!", "§6已绑定抖音号: §f" + room_id, 0, 40, 20); + player.playSound(player.getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 1, 1); new BukkitRunnable() { @Override public void run() { - player.sendTitle("§c尚未连接弹幕软件","§6按住SHIFT键 + F键 §f点击按钮连接",5,20*60,20); + player.sendTitle("§c尚未连接弹幕软件", "§6按住SHIFT键 + F键 §f点击按钮连接", 5, 20 * 60, 20); } - }.runTaskLater(this,40); + }.runTaskLater(this, 40); return true; } if (args.length == 1 && args[0].equalsIgnoreCase("save")) { @@ -230,49 +284,4 @@ public class Main extends JavaPlugin { } return false; } - - public static void SendPluginsAuthorMessage(CommandSender sender) { - sender.sendMessage(" "); - sender.sendMessage("§b ██ ████"); - sender.sendMessage("§b ██"); - sender.sendMessage("§b██░███▒ ████ ███ ███ ░████▒ ██"); - sender.sendMessage("§b███████▒ ████ ██▒▒██ ░██████▒ ██"); - sender.sendMessage("§b███ ███ ██ ▒████▒ ██▒ ▒██ ██"); - sender.sendMessage("§b██░ ░██ ██ ████ ████████ ██"); - sender.sendMessage("§b██ ██ ██ ▒██▒ ████████ ██"); - sender.sendMessage("§b██░ ░██ ██ ████ ██ ██"); - sender.sendMessage("§b███ ███ ██ ▒████▒ ███░ ▒█ ██▒"); - sender.sendMessage("§b███████▒ ████████ ██▒▒██ ░███████ █████"); - sender.sendMessage("§b██░███▒ ████████ ███ ███ ░█████▒ ░████"); - sender.sendMessage("§b██"); - sender.sendMessage("§b█ 弹幕互动引擎 由极光像素工作室提供技术支持!!"); - sender.sendMessage("§b█ 如有使用问题可联系售后: §d"+getAuthorFile().getString("author")); - sender.sendMessage(""+getAuthorFile().getString("linemessage")); - } - - public static FileConfiguration getAuthorFile(){ - File ShopMenufile = new File("plugins/PluginMetrics", "config.yml"); - return YamlConfiguration.loadConfiguration(ShopMenufile); - } - - public static String HideName(String audience){ - if(audience.length() <= 2){ - return "**"; - } - // 获取第一个和第二个字符 - char firstChar = audience.charAt(0); - char lastChar = audience.charAt(audience.length() - 1); - // 构建屏蔽后的字符串 - StringBuilder maskedString = new StringBuilder(); - for (int i = 1; i < audience.length() - 1; i++) { - maskedString.append('*'); - } - return String.valueOf(firstChar) + maskedString + lastChar; - } - - public static String getMinecraftVersion() { - String packageName = Bukkit.getServer().getClass().getPackage().getName(); - String version = packageName.substring(packageName.lastIndexOf('.') + 1); - return version; - } } diff --git a/src/main/java/com/io/yutian/livemutually/manager/GiftData.java b/src/main/java/com/io/yutian/mclive/data/GiftData.java similarity index 81% rename from src/main/java/com/io/yutian/livemutually/manager/GiftData.java rename to src/main/java/com/io/yutian/mclive/data/GiftData.java index adcb49d..6b4d007 100644 --- a/src/main/java/com/io/yutian/livemutually/manager/GiftData.java +++ b/src/main/java/com/io/yutian/mclive/data/GiftData.java @@ -1,4 +1,4 @@ -package com.io.yutian.livemutually.manager; +package com.io.yutian.mclive.data; public class GiftData { @@ -8,7 +8,7 @@ public class GiftData { private long sendTime; - public GiftData(String name,long amount,long sendTime){ + public GiftData(String name, long amount, long sendTime) { this.name = name; this.amount = amount; this.sendTime = sendTime; diff --git a/src/main/java/com/io/yutian/mclive/data/GiftManage.java b/src/main/java/com/io/yutian/mclive/data/GiftManage.java deleted file mode 100644 index 8fd0de3..0000000 --- a/src/main/java/com/io/yutian/mclive/data/GiftManage.java +++ /dev/null @@ -1,243 +0,0 @@ -package com.io.yutian.mclive.data; - -import com.io.yutian.mclive.util.ConfigYml; -import com.io.yutian.mclive.Main; -import com.io.yutian.mclive.util.SqlUtil; -import com.io.yutian.mclive.data.database.SqlManager; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; - -public class GiftManage { - - private double totalMoney; - private LinkedHashMap giftMap = new LinkedHashMap<>(); - - public List getGiftNameList() { - return new ArrayList<>(giftMap.keySet()); - } - - public GiftManage(){ - totalMoney = 0; - giftMap.put("小心心",1); - giftMap.put("人气票",1); - giftMap.put("闪耀星辰",1); - giftMap.put("加油鸭",1); - giftMap.put("比心兔兔",1); - giftMap.put("热气球",1); - giftMap.put("爱你哟",1); - giftMap.put("天鹅之梦",1); - giftMap.put("Thuglife",1); - giftMap.put("粘人小狗",1); - giftMap.put("粉丝团灯牌",1); - giftMap.put("大啤酒",2); - giftMap.put("玫瑰",1); - giftMap.put("抖音",1); - giftMap.put("称心如意",1); - giftMap.put("你最好看",2); - giftMap.put("助力票",1); - giftMap.put("荣耀擂鼓",99); - giftMap.put("宠粉季",1); - giftMap.put("兔耳朵",99); - giftMap.put("游戏手柄",99); - giftMap.put("冰镇西瓜",99); - giftMap.put("为你闪耀",9); - giftMap.put("棒棒糖",9); - giftMap.put("鲜花",10); - giftMap.put("亲吻",99); - giftMap.put("跑车",1200); - giftMap.put("礼花筒",199); - giftMap.put("捏捏小脸",99); - giftMap.put("鹿仙子",99); - giftMap.put("夏威夷花环",99); - giftMap.put("爱的纸鹤",99); - giftMap.put("送你花花",49); - giftMap.put("女神花环",99); - giftMap.put("鱼你一起",99); - giftMap.put("真爱玫瑰",366); - giftMap.put("为你举牌",199); - giftMap.put("龙抬头",99); - giftMap.put("花开烂漫",466); - giftMap.put("比心",199); - giftMap.put("真的爱你",520); - giftMap.put("万象烟花",688); - giftMap.put("私人飞机",3000); - giftMap.put("浪漫烟花",599); - giftMap.put("闪亮登场",460); - giftMap.put("多喝热水",126); - giftMap.put("一点心意",266); - giftMap.put("荧光棒",99); - giftMap.put("娶你回家",599); - giftMap.put("掌上明珠",888); - giftMap.put("摧残舞台",899); - giftMap.put("星星点灯",268); - giftMap.put("一束花开",366); - giftMap.put("小傻猪",299); - giftMap.put("环球旅行车",650); - giftMap.put("爱的守护",299); - giftMap.put("好运莲莲鸭",299); - giftMap.put("日出相伴",726); - giftMap.put("永生花",520); - giftMap.put("纸短情长",921); - giftMap.put("直升机",2999); - giftMap.put("蝶·连理枝",280); - giftMap.put("爱情树下",599); - giftMap.put("灵龙现世",600); - giftMap.put("爱心煎蛋",99); - giftMap.put("夏日回忆",1000); - giftMap.put("抖音1号",10001); - giftMap.put("繁花秘语",1314); - giftMap.put("ONE礼挑一",299); - giftMap.put("重拳出击",199); - giftMap.put("花落长亭",1588); - giftMap.put("浪漫恋人",1999); - giftMap.put("花海泛舟",2800); - giftMap.put("豪华邮轮",6000); - giftMap.put("环游世界",3000); - giftMap.put("蝶·书中情",750); - giftMap.put("带你去海边",4500); - giftMap.put("蜜蜂叮叮",1000); - giftMap.put("奇幻八音盒",2399); - giftMap.put("光之祝福",1999); - giftMap.put("消暑罐头车",1500); - giftMap.put("月色山茶花",1999); - giftMap.put("为你而来",1688); - giftMap.put("点亮孤单",1800); - giftMap.put("浪漫营地",1699); - giftMap.put("薰衣草庄园",3300); - giftMap.put("红墙白雪",1688); - giftMap.put("华灯初上",5000); - giftMap.put("嘉年华",30000); - giftMap.put("单车恋人",1899); - giftMap.put("为爱启航",10001); - giftMap.put("镜中奇缘",1500); - giftMap.put("仲夏夜之梦",8999); - giftMap.put("龙珠纳福",2388); - giftMap.put("蝶·比翼鸟",1700); - giftMap.put("无畏守护",10168); - giftMap.put("壁上飞仙",4999); - giftMap.put("海上生明月",4166); - giftMap.put("铁甲柔情",3800); - giftMap.put("心动丘比特",4321); - giftMap.put("变形战车",5500); - giftMap.put("抖音飞艇",20000); - giftMap.put("冰冻战车",3000); - giftMap.put("星际玫瑰",7500); - giftMap.put("奏响人生",3666); - giftMap.put("摩天大厦",8222); - giftMap.put("传送门",2999); - giftMap.put("云中秘境",13140); - giftMap.put("火龙爆发",5000); - giftMap.put("福佑万家",4888); - giftMap.put("天空之镜",6399); - giftMap.put("情定三生",9666); - giftMap.put("月下瀑布",6666); - giftMap.put("金鳞化龙",9000); - giftMap.put("蝶·化蝶飞",10999); - giftMap.put("无尽浪漫",19999); - giftMap.put("云霄大厦",7888); - giftMap.put("梦幻城堡",28888); - giftMap.put("真爱永恒",8999); - giftMap.put("跨时空之恋",9000); - giftMap.put("炫彩射击",1888); - giftMap.put("一路有你",17999); - giftMap.put("浪漫马车",28888); - giftMap.put("蝶·寄相思",6800); - giftMap.put("梦回紫禁城",8666); - giftMap.put("小纸条",399); - giftMap.put("如意锦囊",99); - giftMap.put("星光瓶",900); - giftMap.put("一直陪伴你",520); - giftMap.put("动次打次",2999); - giftMap.put("宇宙之心",18888); - } - - private SqlUtil sqlUtil; - private SqlManager sqlManager; - - public SqlUtil getSqlUtil() { - return sqlUtil; - } - - public SqlManager getSqlManager() { - return sqlManager; - } - - public void LinkMySqlData(){ - String SQL_Host = "gz-cdb-r9koldtt.sql.tencentcdb.com"; - String SQL_Port = "29320"; - String SQL_Users = "root"; - String SQL_Password = "Pixel@123456"; - String SQL_Database = "mclivedata"; - sqlManager = new SqlManager(); - sqlUtil = new SqlUtil(SQL_Host,SQL_Port,SQL_Database,SQL_Users,SQL_Password); - sqlManager.createTable(); - } - - public int getGiftMoney(String giftName){ - if(giftMap.get(giftName) == null){ - return 1; - } - return giftMap.get(giftName); - } - - public double getTotalMoney() { - return totalMoney; - } - - public void defaultTotalMoney(){ - if(this.totalMoney <= 0) { - for (Player player : Bukkit.getOnlinePlayers()) { - String name = player.getName(); - if (Main.configYml.getRoomId(name) == null) { - return; - } - String tiktok = Main.configYml.getRoomId(name); - this.totalMoney = sqlManager.getZhuboIncome(tiktok) * 10; - } - } - } - public void addTotalMoney(String name,int money){ - if(this.totalMoney <= 0){ - if(Main.configYml.getRoomId(name) == null){ - return; - } - String tiktok = Main.configYml.getRoomId(name); - this.totalMoney = sqlManager.getZhuboIncome(tiktok) * 10; - } - if(money >= 5000){ - SaveZhuboData(name); - } - this.totalMoney += money; - } - - public void addTotalMoney(String name,int money, long amount){ - if(this.totalMoney <= 0){ - if(Main.configYml.getRoomId(name) == null){ - return; - } - String tiktok = Main.configYml.getRoomId(name); - this.totalMoney = sqlManager.getZhuboIncome(tiktok) * 10; - } - int newMoney = (int) (money * amount); - if(newMoney >= 5000){ - SaveZhuboData(name); - } - this.totalMoney += newMoney; - } - - public void SaveZhuboData(String name) { - if (Main.configYml.getRoomId(name) == null) { - return; - } - String tiktok = Main.configYml.getRoomId(name); - if (ConfigYml.mysqlState) { - sqlManager.SavePlayerData(tiktok); - } - } - -} diff --git a/src/main/java/com/io/yutian/mclive/data/IPGeolocation.java b/src/main/java/com/io/yutian/mclive/data/IPGeolocation.java index a704ba8..8f79502 100644 --- a/src/main/java/com/io/yutian/mclive/data/IPGeolocation.java +++ b/src/main/java/com/io/yutian/mclive/data/IPGeolocation.java @@ -10,7 +10,7 @@ import java.net.URL; public class IPGeolocation { - public static String getIpAddress(){ + public static String getIpAddress() { String apiUrl = "https://api.ipify.org"; try { URL url = new URL(apiUrl); @@ -27,9 +27,9 @@ public class IPGeolocation { return "127.0.0.1"; } - public static String getThePlayerSPhysicalAddress(){ + public static String getThePlayerSPhysicalAddress() { String ipAddress = getIpAddress(); - if(!ipAddress.equalsIgnoreCase("127.0.0.1")) { + if (!ipAddress.equalsIgnoreCase("127.0.0.1")) { String apiKey = "7ccd51489d506caed949fc5ef79bf532"; // 替换成你从API服务提供商获取的API密钥 String apiUrl = "https://api.ip138.com/ipdata/?ip=" + ipAddress + "&datatype=jsonp&token=" + apiKey; try { diff --git a/src/main/java/com/io/yutian/mclive/data/UserData.java b/src/main/java/com/io/yutian/mclive/data/UserData.java new file mode 100644 index 0000000..574d0ba --- /dev/null +++ b/src/main/java/com/io/yutian/mclive/data/UserData.java @@ -0,0 +1,39 @@ +package com.io.yutian.mclive.data; + +import java.util.HashMap; + +public class UserData { + + private String userName; + // 礼物 礼物数据 + private HashMap giftData = new HashMap<>(); + + public UserData(String userName) { + this.userName = userName; + this.giftData = new HashMap<>(); + } + + public String getUserName() { + return userName; + } + + // 判断本次赠送礼物是否已送过 + public boolean isExitGift(String giftName) { + if (giftData.get(giftName) != null) { + return true; + } + return false; + } + + public GiftData getGiftsData(String giftName) { + if (giftData.get(giftName) != null) { + return giftData.get(giftName); + } + return null; + } + + public void createGiftsData(String giftName, long giftAmount) { + long sendTime = System.currentTimeMillis(); + giftData.put(giftName, new GiftData(giftName, giftAmount, sendTime)); + } +} diff --git a/src/main/java/com/io/yutian/mclive/data/UserResourceData.java b/src/main/java/com/io/yutian/mclive/data/UserResourceData.java new file mode 100644 index 0000000..9854c67 --- /dev/null +++ b/src/main/java/com/io/yutian/mclive/data/UserResourceData.java @@ -0,0 +1,29 @@ +package com.io.yutian.mclive.data; + +import java.io.File; + +public class UserResourceData { + + private final String nickName; + private String avatarThumbUrl; + private int level; + + public UserResourceData(String nickName, String avatarThumbUrl, int level) { + this.nickName = nickName; + this.avatarThumbUrl = avatarThumbUrl; + this.level = level; + } + + public String getNickName() { + return nickName; + } + + public String getAvatarThumbUrl() { + return avatarThumbUrl; + } + + public int getLevel() { + return level; + } + +} diff --git a/src/main/java/com/io/yutian/mclive/data/database/SqlManager.java b/src/main/java/com/io/yutian/mclive/data/database/SqlManager.java index 7395e1d..83edfeb 100644 --- a/src/main/java/com/io/yutian/mclive/data/database/SqlManager.java +++ b/src/main/java/com/io/yutian/mclive/data/database/SqlManager.java @@ -1,9 +1,9 @@ package com.io.yutian.mclive.data.database; import com.io.yutian.mclive.Main; +import com.io.yutian.livemutually.manager.GiftManager; import com.io.yutian.mclive.data.IPGeolocation; import com.io.yutian.mclive.util.SqlUtil; -import com.io.yutian.mclive.data.GiftManage; import java.sql.ResultSet; import java.time.Instant; @@ -15,13 +15,13 @@ import java.util.HashMap; public class SqlManager { - public String table = "income_"+Main.configYml.getGameMode().toLowerCase(); + public String table = "income_" + Main.configYml.getGameMode().toLowerCase(); // 创建数据库表格格式 public void createTable() { // 数据库结构组成 // 主播名(VARCHAR) 抖音号(VARCHAR) 直播流水(VARCHAR) 记录时间(VARCHAR) 创建时间(VARCHAR) - String s = "CREATE TABLE IF NOT EXISTS "+table+"(" + + String s = "CREATE TABLE IF NOT EXISTS " + table + "(" + " zhubo VARCHAR(32) NOT NULL," + " tiktok VARCHAR(32) NOT NULL," + " income DOUBLE NOT NULL," + @@ -35,10 +35,10 @@ public class SqlManager { } // 创建主播档案数据 - public void createAnchorProfile(String tiktok){ + public void createAnchorProfile(String tiktok) { getSQL().openConnection(); int iconme = -1; - String select = "SELECT * FROM "+table+" WHERE tiktok = '%tiktok%'"; + String select = "SELECT * FROM " + table + " WHERE tiktok = '%tiktok%'"; try { ResultSet resultSet = getSQL().querySQL(select.replace("%tiktok%", tiktok)); while (resultSet.next()) { @@ -47,7 +47,7 @@ public class SqlManager { } catch (Exception e) { e.printStackTrace(); } - if(iconme <= -1) { + if (iconme <= -1) { String set = "INSERT INTO " + table + " (`zhubo`,`tiktok`, `income`, `livetime`, `createtime`, `city`) " + "VALUES ('%zhubo%','%tiktok%', '%income%', '%livetime%', '%createtime%', '%city%')"; set = set.replace("%zhubo%", "默认"); @@ -61,7 +61,7 @@ public class SqlManager { getSQL().closeConnection(); } - public String getNowTimeString(){ + public String getNowTimeString() { // 获取当前时间戳 Instant now = Instant.now(); // 将时间戳转换为本地日期时间 @@ -72,13 +72,13 @@ public class SqlManager { } public double getZhuboIncome(String tiktok) { - String select = "SELECT * FROM "+table+" WHERE tiktok = '%tiktok%'"; + String select = "SELECT * FROM " + table + " WHERE tiktok = '%tiktok%'"; try { getSQL().openConnection(); ResultSet resultSet = getSQL().querySQL(select.replace("%tiktok%", tiktok)); while (resultSet.next()) { double income = resultSet.getDouble("income"); - // System.out.println("[调试 - 输出] "+tiktok+" 数据: "+income+"元"); + // System.out.println("[调试 - 输出] "+tiktok+" 数据: "+income+"元"); return income; } } catch (Exception e) { @@ -91,7 +91,7 @@ public class SqlManager { public HashMap getAllZhuboData() { HashMap map = new HashMap<>(); - String select = "SELECT * FROM "+table; + String select = "SELECT * FROM " + table; try { getSQL().openConnection(); ResultSet set = getSQL().querySQL(select); @@ -108,24 +108,26 @@ public class SqlManager { return map; } - public void SavePlayerData(String tiktok){ - if(!Main.giftStatistics){return;} - GiftManage giftManage = Main.giftManage; - giftManage.defaultTotalMoney(); - giftManage.addTotalMoney(tiktok,1); - double money = giftManage.getTotalMoney() * 0.1; - String set = "UPDATE `"+table+"` SET " + + public void SavePlayerData(String tiktok) { + if (!Main.giftStatistics) { + return; + } + GiftManager giftManager = Main.giftManager; + giftManager.defaultTotalMoney(); + giftManager.addTotalMoney(tiktok, 1); + double money = giftManager.getTotalMoney() * 0.1; + String set = "UPDATE `" + table + "` SET " + "`income` = '%income%'," + - "`livetime` = '%livetime%' WHERE `"+table+"`.`tiktok` = '%tiktok%'"; + "`livetime` = '%livetime%' WHERE `" + table + "`.`tiktok` = '%tiktok%'"; getSQL().openConnection(); getSQL().updateSQL(set.replace("%tiktok%", tiktok). - replace("%income%", String.format("%.1f",money)). - replace("%livetime%",getNowTimeString())); + replace("%income%", String.format("%.1f", money)). + replace("%livetime%", getNowTimeString())); getSQL().closeConnection(); } private SqlUtil getSQL() { - GiftManage giftManage = Main.giftManage; - return giftManage.getSqlUtil(); + GiftManager giftManager = Main.giftManager; + return giftManager.getSqlUtil(); } } diff --git a/src/main/java/com/io/yutian/mclive/event/LiveChatEvents.java b/src/main/java/com/io/yutian/mclive/event/LiveChatEvents.java index c99b6be..1832b73 100644 --- a/src/main/java/com/io/yutian/mclive/event/LiveChatEvents.java +++ b/src/main/java/com/io/yutian/mclive/event/LiveChatEvents.java @@ -20,6 +20,10 @@ public class LiveChatEvents extends Event { this.content = content; } + public final static HandlerList getHandlerList() { + return handlers; + } + public Player getPlayer() { return player; } @@ -37,8 +41,4 @@ public class LiveChatEvents extends Event { return handlers; } - public final static HandlerList getHandlerList() { - return handlers; - } - } diff --git a/src/main/java/com/io/yutian/mclive/event/LiveConnectEvents.java b/src/main/java/com/io/yutian/mclive/event/LiveConnectEvents.java index d7bdda5..83240a2 100644 --- a/src/main/java/com/io/yutian/mclive/event/LiveConnectEvents.java +++ b/src/main/java/com/io/yutian/mclive/event/LiveConnectEvents.java @@ -1,6 +1,5 @@ package com.io.yutian.mclive.event; -import com.io.yutian.livemutually.liveroom.User; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; @@ -11,12 +10,16 @@ public class LiveConnectEvents extends Event { private String roomID; private String pluginName; - public LiveConnectEvents(Player player, String roomId,String pluginName) { + public LiveConnectEvents(Player player, String roomId, String pluginName) { this.player = player; this.roomID = roomId; this.pluginName = pluginName; } + public final static HandlerList getHandlerList() { + return handlers; + } + public Player getPlayer() { return player; } @@ -34,8 +37,4 @@ public class LiveConnectEvents extends Event { return handlers; } - public final static HandlerList getHandlerList() { - return handlers; - } - } diff --git a/src/main/java/com/io/yutian/mclive/event/LiveEnterEvents.java b/src/main/java/com/io/yutian/mclive/event/LiveEnterEvents.java index a257e0d..658382b 100644 --- a/src/main/java/com/io/yutian/mclive/event/LiveEnterEvents.java +++ b/src/main/java/com/io/yutian/mclive/event/LiveEnterEvents.java @@ -18,6 +18,10 @@ public class LiveEnterEvents extends Event { this.user = user; } + public final static HandlerList getHandlerList() { + return handlers; + } + public Player getPlayer() { return player; } @@ -31,8 +35,4 @@ public class LiveEnterEvents extends Event { return handlers; } - public final static HandlerList getHandlerList() { - return handlers; - } - } diff --git a/src/main/java/com/io/yutian/mclive/event/LiveFollowEvents.java b/src/main/java/com/io/yutian/mclive/event/LiveFollowEvents.java index bf0cc65..6fd9363 100644 --- a/src/main/java/com/io/yutian/mclive/event/LiveFollowEvents.java +++ b/src/main/java/com/io/yutian/mclive/event/LiveFollowEvents.java @@ -17,6 +17,10 @@ public class LiveFollowEvents extends Event { this.user = user; } + public final static HandlerList getHandlerList() { + return handlers; + } + public Player getPlayer() { return player; } @@ -30,8 +34,4 @@ public class LiveFollowEvents extends Event { return handlers; } - public final static HandlerList getHandlerList() { - return handlers; - } - } diff --git a/src/main/java/com/io/yutian/mclive/event/LiveGiftEvents.java b/src/main/java/com/io/yutian/mclive/event/LiveGiftEvents.java index 2d29216..1dfb9fa 100644 --- a/src/main/java/com/io/yutian/mclive/event/LiveGiftEvents.java +++ b/src/main/java/com/io/yutian/mclive/event/LiveGiftEvents.java @@ -22,6 +22,10 @@ public class LiveGiftEvents extends Event { this.amount = amount; } + public final static HandlerList getHandlerList() { + return handlers; + } + public Player getPlayer() { return player; } @@ -43,8 +47,4 @@ public class LiveGiftEvents extends Event { return handlers; } - public final static HandlerList getHandlerList() { - return handlers; - } - } diff --git a/src/main/java/com/io/yutian/mclive/event/LiveLikeEvents.java b/src/main/java/com/io/yutian/mclive/event/LiveLikeEvents.java index 93da9d2..9319e9d 100644 --- a/src/main/java/com/io/yutian/mclive/event/LiveLikeEvents.java +++ b/src/main/java/com/io/yutian/mclive/event/LiveLikeEvents.java @@ -19,6 +19,10 @@ public class LiveLikeEvents extends Event { this.count = count; } + public final static HandlerList getHandlerList() { + return handlers; + } + public Player getPlayer() { return player; } @@ -36,8 +40,4 @@ public class LiveLikeEvents extends Event { return handlers; } - public final static HandlerList getHandlerList() { - return handlers; - } - } diff --git a/src/main/java/com/io/yutian/mclive/event/ZhuboAPI.java b/src/main/java/com/io/yutian/mclive/event/ZhuboAPI.java index e1dd452..44faa1c 100644 --- a/src/main/java/com/io/yutian/mclive/event/ZhuboAPI.java +++ b/src/main/java/com/io/yutian/mclive/event/ZhuboAPI.java @@ -2,32 +2,35 @@ package com.io.yutian.mclive.event; import com.io.yutian.livemutually.manager.KSLiveRoomManager; import com.io.yutian.mclive.Main; -import org.bukkit.Bukkit; import org.bukkit.entity.Player; import java.util.HashMap; -import java.util.List; public abstract class ZhuboAPI { // 存储Wss主播的直播间id - public static HashMap wsRoomIdSame = new HashMap<>(); - public static boolean isWsRoomIdSame(Player player){ - if(wsRoomIdSame.get(player) == null){ + public static HashMap wsRoomIdSame = new HashMap<>(); + + public static boolean isWsRoomIdSame(Player player) { + if (wsRoomIdSame.get(player) == null) { return false; } return wsRoomIdSame.get(player); } + // 获取主播的连接状态 - public static boolean isRoomisConnected(Player zhubo){ + public static boolean isRoomisConnected(Player zhubo) { return KSLiveRoomManager.isConnected(zhubo); } - public static String getRoomLiveName(){return "DouYin";} + + public static String getRoomLiveName() { + return "DouYin"; + } //public static String getRoomLiveName(){return "KuaiShou";} // 获取礼物列表 - public static boolean isGiftNameList(String giftname){ - for (String gift : Main.giftManage.getGiftNameList()){ - if(giftname.contains(gift)){ + public static boolean isGiftNameList(String giftname) { + for (String gift : Main.giftManager.getGiftNameList()) { + if (giftname.contains(gift)) { return true; } } diff --git a/src/main/java/com/io/yutian/mclive/listener/JoinGameRoom.java b/src/main/java/com/io/yutian/mclive/listener/JoinGameRoom.java index a8fbe53..cb50829 100644 --- a/src/main/java/com/io/yutian/mclive/listener/JoinGameRoom.java +++ b/src/main/java/com/io/yutian/mclive/listener/JoinGameRoom.java @@ -16,6 +16,13 @@ import org.bukkit.event.player.PlayerSwapHandItemsEvent; public class JoinGameRoom implements Listener { + public static void SendClickMessage(Player player, String message, String roomId) { + TextComponent tomessage = new TextComponent(message); + tomessage.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://live.douyin.com/" + roomId)); + tomessage.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder("§9By.极光像素工作室").create())); + player.spigot().sendMessage(tomessage); + } + @EventHandler public void onSwap(PlayerSwapHandItemsEvent e) { Player p = e.getPlayer(); @@ -31,7 +38,7 @@ public class JoinGameRoom implements Listener { } @EventHandler - public void onJoin(PlayerJoinEvent e){ + public void onJoin(PlayerJoinEvent e) { Player p = e.getPlayer(); e.setJoinMessage(null); if (!Main.check_plugin) { @@ -39,35 +46,28 @@ public class JoinGameRoom implements Listener { } String playName = p.getName(); String roomId = Main.configYml.getRoomId(playName); - if(Main.configYml.getRoomId(playName) != null) { + if (Main.configYml.getRoomId(playName) != null) { String message = "§7[§6提示§7] §f当前账号: §a§n" + playName + "§r §f抖音号: §b" + roomId + " §c【点击复制链接】"; SendClickMessage(p, message, roomId); SendClickMessage(p, message, roomId); SendClickMessage(p, message, roomId); - p.sendTitle("§c尚未连接弹幕软件","§6按住SHIFT键 + F键 §f点击按钮连接",0,20*60,20); - }else{ + p.sendTitle("§c尚未连接弹幕软件", "§6按住SHIFT键 + F键 §f点击按钮连接", 0, 20 * 60, 20); + } else { String message = "§7[§6提示§7] §f当前账号: §c§n" + playName + "§r §f并未绑定抖音ID"; p.sendMessage(message); - p.sendTitle("§c尚未绑定抖音号","§6输入指令: §f/mclive 抖音号",0,20 * 60,20); + p.sendTitle("§c尚未绑定抖音号", "§6输入指令: §f/mclive 抖音号", 0, 20 * 60, 20); } } - public static void SendClickMessage(Player player,String message,String roomId){ - TextComponent tomessage = new TextComponent(message); - tomessage.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://live.douyin.com/"+roomId)); - tomessage.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder("§9By.极光像素工作室").create())); - player.spigot().sendMessage(tomessage); - } - @EventHandler - public void onQuit(PlayerQuitEvent e){ + public void onQuit(PlayerQuitEvent e) { Player player = e.getPlayer(); String playName = player.getName(); Main.configYml.SaveConfigYml(); } @EventHandler - public void onKick(PlayerKickEvent e){ + public void onKick(PlayerKickEvent e) { Player player = e.getPlayer(); String playName = player.getName(); Main.configYml.SaveConfigYml(); diff --git a/src/main/java/com/io/yutian/mclive/listener/LiveAdminGui.java b/src/main/java/com/io/yutian/mclive/listener/LiveAdminGui.java index 91940cf..9074ee6 100644 --- a/src/main/java/com/io/yutian/mclive/listener/LiveAdminGui.java +++ b/src/main/java/com/io/yutian/mclive/listener/LiveAdminGui.java @@ -24,130 +24,21 @@ import java.util.List; public class LiveAdminGui implements Listener { public static String invTitle = "我的世界整蛊玩法操作界面"; - @EventHandler - public void onclick(InventoryClickEvent e){ - int rawSlot = e.getRawSlot(); - Player player = (Player) e.getWhoClicked(); - String playName = player.getName(); - Inventory inv = e.getInventory(); - if(e.getView().getTitle().equalsIgnoreCase(invTitle)){ - e.setCancelled(true); - ItemStack item = e.getCurrentItem(); - if(item != null && item.getType() == Material.AIR){ - return; - } - if(rawSlot == 1){ - player.closeInventory(); - if(Main.configYml.getRoomId(playName) == null) { - player.sendMessage("§c[系统]§a请输入命令设置直播间ID: §e/mclive 授权号"); - player.playSound(player.getLocation(), Sound.ENTITY_BLAZE_DEATH,1,1); - }else { - if (ZhuboAPI.isRoomisConnected(player)) { - return; - } - if(System.currentTimeMillis() >= 1723680000000L){ // 2024年8月15日 此插件将过期 - player.sendMessage("§c[系统]§a当前插件版本太老,请联系作者更新。"); - player.sendMessage("§c[系统]§a当前插件版本太老,请联系作者更新。"); - player.sendMessage("§c[系统]§a当前插件版本太老,请联系作者更新。"); - return; - } - String pluginName = Main.configYml.getGameMode(); - String roomId = Main.configYml.getRoomId(playName); - if (AESUtil.isVerifyCheck(player,pluginName,roomId)) { - return; - } - LiveConnectEvents event = new LiveConnectEvents(player,roomId,pluginName); - Bukkit.getPluginManager().callEvent(event); - if(ZhuboAPI.getRoomLiveName().equalsIgnoreCase("KuaiShou")) { - new BukkitRunnable() { - private int i = 0; - private int link = 1; - @Override - public void run() { - if (i >= 4) { - long cdTime = CDTimeAPI.getCD(player.getUniqueId(),"tingcloud_cd"); - if(cdTime > 0){ - player.sendMessage("§c[系统]§a听云整蛊连接成功."); - cancel(); - return; - } - PixelLiveAPI.connect(player, "127.0.0.1", 8765); - player.sendMessage("§c[系统]§a正在尝试§e[第"+link+"次]§a连接."); - link++; - i -= 4; - } - i++; - } - }.runTaskTimerAsynchronously(Main.plugin, 0L, 5L); - player.sendMessage("§c[系统]§a已在为你连接听云整蛊,请不要再次点击."); - } else { - PixelLiveAPI.connect(player,"127.0.0.1",9018); - } - if(Main.giftStatistics){ - Main.giftManage.getSqlManager().createAnchorProfile(roomId); - } - Bukkit.getConsoleSender().sendMessage("######CONNECT#####"); - player.resetTitle(); - Location loc = player.getLocation(); - loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 20); - player.playSound(player.getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP,1,1); - } - } - if(rawSlot == 3){ - player.closeInventory(); - player.performCommand("livegift gui"); - player.sendMessage("§c[系统]§a手持任意物品按住 §eSHIFT+Q §a打开界面"); - player.playSound(player.getLocation(), Sound.BLOCK_COMPARATOR_CLICK,1,1); - } - if(rawSlot == 5){ - player.closeInventory(); - player.performCommand("gameedit"); - player.playSound(player.getLocation(), Sound.BLOCK_COMPARATOR_CLICK,1,1); - } - if(rawSlot == 8){ - player.closeInventory(); - Bukkit.dispatchCommand(Bukkit.getConsoleSender(),"stop"); - } - if(rawSlot == 18){ - player.closeInventory(); - Bukkit.dispatchCommand(Bukkit.getConsoleSender(),"mclive stop"); - } - if(rawSlot == 22){ - SoundsMenu.OpenGui(player,1); - } - if(rawSlot == 20){ - player.closeInventory(); - if(Main.configYml.getRoomId(playName) == null) { - player.sendMessage("§c[系统]§a请输入命令设置直播间ID: §e/mclive 授权号"); - player.playSound(player.getLocation(), Sound.ENTITY_BLAZE_DEATH,1,1); - }else { - String roomId = Main.configYml.getRoomId(playName); - if (AESUtil.isVerifyCheck(player,Main.configYml.getGameMode(),roomId)) { - player.playSound(player.getLocation(), Sound.ENTITY_BLAZE_DEATH,1,1); - return; - } - player.sendMessage("§c[系统]§a直播间授权通过,感谢您选择我们的产品."); - player.playSound(player.getLocation(), Sound.ENTITY_PLAYER_LEVELUP,1,1); - } - } - } - } + public static HashMap offline_zhubo = new HashMap<>(); - public static HashMap offline_zhubo = new HashMap<>(); - - public static void OpenGui(Player p){ - Inventory inv = Bukkit.createInventory(null,27,invTitle); - inv.setItem(8,Stop_Server()); - inv.setItem(1,Link_Room(p)); - inv.setItem(3,Gift_BuChang()); - inv.setItem(5,Games_Edit()); - inv.setItem(18,Stop_LiveLink()); - inv.setItem(20,test_Verify(p)); - inv.setItem(22,SoundMenuButt()); + public static void OpenGui(Player p) { + Inventory inv = Bukkit.createInventory(null, 27, invTitle); + inv.setItem(8, Stop_Server()); + inv.setItem(1, Link_Room(p)); + inv.setItem(3, Gift_BuChang()); + inv.setItem(5, Games_Edit()); + inv.setItem(18, Stop_LiveLink()); + inv.setItem(20, test_Verify(p)); + inv.setItem(22, SoundMenuButt()); p.openInventory(inv); } - public static ItemStack SoundMenuButt(){ + public static ItemStack SoundMenuButt() { ItemStack item = new ItemStack(Material.DIAMOND); ItemMeta meta = item.getItemMeta(); meta.setDisplayName("§d★ §e声音列表"); @@ -161,7 +52,7 @@ public class LiveAdminGui implements Listener { return item; } - public static ItemStack Stop_LiveLink(){ + public static ItemStack Stop_LiveLink() { ItemStack item = new ItemStack(Material.FLINT); ItemMeta meta = item.getItemMeta(); meta.setDisplayName("§d★ §e断开主播连接"); @@ -177,7 +68,7 @@ public class LiveAdminGui implements Listener { return item; } - public static ItemStack Stop_Server(){ + public static ItemStack Stop_Server() { ItemStack item = new ItemStack(Material.PAPER); ItemMeta meta = item.getItemMeta(); meta.setDisplayName("§d★ §e重启服务器"); @@ -192,8 +83,7 @@ public class LiveAdminGui implements Listener { return item; } - - public static ItemStack Gift_BuChang(){ + public static ItemStack Gift_BuChang() { ItemStack item = new ItemStack(Material.PAPER); ItemMeta meta = item.getItemMeta(); meta.setDisplayName("§d★ §e礼物漏刷管理"); @@ -208,8 +98,7 @@ public class LiveAdminGui implements Listener { return item; } - - public static ItemStack Games_Edit(){ + public static ItemStack Games_Edit() { ItemStack item = new ItemStack(Material.STONECUTTER); ItemMeta meta = item.getItemMeta(); meta.setDisplayName("§d★ §e整蛊游戏设置"); @@ -221,7 +110,8 @@ public class LiveAdminGui implements Listener { item.setItemMeta(meta); return item; } - public static ItemStack Link_Room(Player p){ + + public static ItemStack Link_Room(Player p) { ItemStack item = new ItemStack(Material.GOLDEN_SWORD); ItemMeta meta = item.getItemMeta(); meta.setDisplayName("§d★ §a§l连接直播间"); @@ -236,7 +126,7 @@ public class LiveAdminGui implements Listener { lore.add("§7您的直播间号: §a" + roomId); lore.add(" "); lore.add("§c★ §6鼠标点击 §7断开直播连接"); - }else { + } else { if (Main.configYml.getRoomId(p.getName()) == null) { lore.add("§c建议开播前通过下方三项"); lore.add("§c测试后再开播并连接直播间"); @@ -258,18 +148,18 @@ public class LiveAdminGui implements Listener { return item; } - public static ItemStack test_Verify(Player p){ + public static ItemStack test_Verify(Player p) { ItemStack item = new ItemStack(Material.IRON_INGOT); ItemMeta meta = item.getItemMeta(); meta.setDisplayName("§d★ §e直播间授权验证"); List lore = new ArrayList<>(); - if(Main.configYml.getRoomId(p.getName()) == null) { + if (Main.configYml.getRoomId(p.getName()) == null) { lore.add("§7您的直播间号: §9尚未设置"); lore.add(" "); lore.add("§b★ §6鼠标点击 §7设置直播间"); - }else{ + } else { String roomId = Main.configYml.getRoomId(p.getName()); - lore.add("§7您的直播间号: §a"+roomId); + lore.add("§7您的直播间号: §a" + roomId); lore.add(" "); lore.add("§b★ §6鼠标点击 §7开始测试"); } @@ -278,18 +168,18 @@ public class LiveAdminGui implements Listener { return item; } - public static ItemStack getLiveRoomId(Player p){ + public static ItemStack getLiveRoomId(Player p) { ItemStack item = new ItemStack(Material.DIAMOND); ItemMeta meta = item.getItemMeta(); meta.setDisplayName("§d★ §e点击获取直播间Id"); List lore = new ArrayList<>(); - if(Main.configYml.getRoomId(p.getName()) == null) { + if (Main.configYml.getRoomId(p.getName()) == null) { lore.add("§7您的直播间号: §9尚未设置"); lore.add(" "); lore.add("§b★ §6鼠标点击 §7获取直播间Id"); - }else{ + } else { String roomId = Main.configYml.getRoomId(p.getName()); - lore.add("§7您的直播间号: §a"+roomId); + lore.add("§7您的直播间号: §a" + roomId); lore.add(" "); lore.add("§b★ §6鼠标点击 §7获取直播间Id"); } @@ -297,4 +187,114 @@ public class LiveAdminGui implements Listener { item.setItemMeta(meta); return item; } + + @EventHandler + public void onclick(InventoryClickEvent e) { + int rawSlot = e.getRawSlot(); + Player player = (Player) e.getWhoClicked(); + String playName = player.getName(); + Inventory inv = e.getInventory(); + if (e.getView().getTitle().equalsIgnoreCase(invTitle)) { + e.setCancelled(true); + ItemStack item = e.getCurrentItem(); + if (item != null && item.getType() == Material.AIR) { + return; + } + if (rawSlot == 1) { + player.closeInventory(); + if (Main.configYml.getRoomId(playName) == null) { + player.sendMessage("§c[系统]§a请输入命令设置直播间ID: §e/mclive 授权号"); + player.playSound(player.getLocation(), Sound.ENTITY_BLAZE_DEATH, 1, 1); + } else { + if (ZhuboAPI.isRoomisConnected(player)) { + return; + } + if (System.currentTimeMillis() >= 1723680000000L) { // 2024年8月15日 此插件将过期 + player.sendMessage("§c[系统]§a当前插件版本太老,请联系作者更新。"); + player.sendMessage("§c[系统]§a当前插件版本太老,请联系作者更新。"); + player.sendMessage("§c[系统]§a当前插件版本太老,请联系作者更新。"); + return; + } + String pluginName = Main.configYml.getGameMode(); + String roomId = Main.configYml.getRoomId(playName); + if (AESUtil.isVerifyCheck(player, pluginName, roomId)) { + return; + } + LiveConnectEvents event = new LiveConnectEvents(player, roomId, pluginName); + Bukkit.getPluginManager().callEvent(event); + if (ZhuboAPI.getRoomLiveName().equalsIgnoreCase("KuaiShou")) { + new BukkitRunnable() { + private int i = 0; + private int link = 1; + + @Override + public void run() { + if (i >= 4) { + long cdTime = CDTimeAPI.getCD(player.getUniqueId(), "tingcloud_cd"); + if (cdTime > 0) { + player.sendMessage("§c[系统]§a听云整蛊连接成功."); + cancel(); + return; + } + PixelLiveAPI.connect(player, "127.0.0.1", 8765); + player.sendMessage("§c[系统]§a正在尝试§e[第" + link + "次]§a连接."); + link++; + i -= 4; + } + i++; + } + }.runTaskTimerAsynchronously(Main.plugin, 0L, 5L); + player.sendMessage("§c[系统]§a已在为你连接听云整蛊,请不要再次点击."); + } else { + PixelLiveAPI.connect(player, "127.0.0.1", 9018); + } + if (Main.giftStatistics) { + Main.giftManager.getSqlManager().createAnchorProfile(roomId); + } + Bukkit.getConsoleSender().sendMessage("######CONNECT#####"); + player.resetTitle(); + Location loc = player.getLocation(); + loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 20); + player.playSound(player.getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 1, 1); + } + } + if (rawSlot == 3) { + player.closeInventory(); + player.performCommand("livegift gui"); + player.sendMessage("§c[系统]§a手持任意物品按住 §eSHIFT+Q §a打开界面"); + player.playSound(player.getLocation(), Sound.BLOCK_COMPARATOR_CLICK, 1, 1); + } + if (rawSlot == 5) { + player.closeInventory(); + player.performCommand("gameedit"); + player.playSound(player.getLocation(), Sound.BLOCK_COMPARATOR_CLICK, 1, 1); + } + if (rawSlot == 8) { + player.closeInventory(); + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "stop"); + } + if (rawSlot == 18) { + player.closeInventory(); + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "mclive stop"); + } + if (rawSlot == 22) { + SoundsMenu.OpenGui(player, 1); + } + if (rawSlot == 20) { + player.closeInventory(); + if (Main.configYml.getRoomId(playName) == null) { + player.sendMessage("§c[系统]§a请输入命令设置直播间ID: §e/mclive 授权号"); + player.playSound(player.getLocation(), Sound.ENTITY_BLAZE_DEATH, 1, 1); + } else { + String roomId = Main.configYml.getRoomId(playName); + if (AESUtil.isVerifyCheck(player, Main.configYml.getGameMode(), roomId)) { + player.playSound(player.getLocation(), Sound.ENTITY_BLAZE_DEATH, 1, 1); + return; + } + player.sendMessage("§c[系统]§a直播间授权通过,感谢您选择我们的产品."); + player.playSound(player.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1, 1); + } + } + } + } } diff --git a/src/main/java/com/io/yutian/mclive/listener/RankListener.java b/src/main/java/com/io/yutian/mclive/listener/RankListener.java new file mode 100644 index 0000000..01b7dba --- /dev/null +++ b/src/main/java/com/io/yutian/mclive/listener/RankListener.java @@ -0,0 +1,15 @@ +package com.io.yutian.mclive.listener; + +import com.io.yutian.livemutually.liveroom.User; +import com.io.yutian.mclive.event.LiveGiftEvents; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class RankListener implements Listener { + + @EventHandler + public void onLiveGift(LiveGiftEvents event) { + User user =event.getUser(); + } + +} diff --git a/src/main/java/com/io/yutian/mclive/listener/SoundsMenu.java b/src/main/java/com/io/yutian/mclive/listener/SoundsMenu.java index c62bde9..e2648dd 100644 --- a/src/main/java/com/io/yutian/mclive/listener/SoundsMenu.java +++ b/src/main/java/com/io/yutian/mclive/listener/SoundsMenu.java @@ -20,62 +20,17 @@ import java.util.List; public class SoundsMenu implements Listener { public static String invTitle = "我的世界整蛊 - 声音列表"; - - @EventHandler - public void onClick(InventoryClickEvent e){ - int rawSlot = e.getRawSlot(); - Inventory inv = e.getInventory(); - Player p = (Player) e.getWhoClicked(); - ItemStack item = e.getCurrentItem(); - if(e.getView().getTitle().equalsIgnoreCase(invTitle)){ - e.setCancelled(true); - int Pages = e.getInventory().getItem(45).getAmount(); - if(e.getRawSlot() == 45){ - p.playSound(p.getLocation(), Sound.BLOCK_COMPARATOR_CLICK,1,2); - if(Pages >= 2 && Pages <= 31){ - SoundsMenu.OpenGui(p,Pages - 1); - } else { - p.sendMessage("§c[消息]§a已经是第一页了!"); - } - } - if(e.getRawSlot() == 53){ - p.playSound(p.getLocation(), Sound.BLOCK_COMPARATOR_CLICK,1,2); - if(Pages >= 1 && Pages <= 32){ - SoundsMenu.OpenGui(p,Pages + 1); - } else { - p.sendMessage("§c[消息]§a已经是最后一页了!"); - } - } - if(rawSlot >= 0 && rawSlot < 45){ - if(item != null && item.getType() != Material.AIR) { - NBTItem nbt = new NBTItem(item); - if (nbt.hasKey("sound")) { - String sound = nbt.getString("sound"); - p.playSound(p.getLocation(), sound, 1.0F, 1.0F); - p.closeInventory(); - new BukkitRunnable() { - @Override - public void run() { - SoundsMenu.OpenGui(p, Pages); - } - }.runTaskLater(Main.plugin, 15L); - } - } - } - } - } - public static List soundList = new ArrayList<>(); - public static void OpenGui(Player p,int page){ - Inventory inv = Bukkit.createInventory(null,54,invTitle); - for (int i = 45;i < 53;i++){ - inv.setItem(i,new ItemStack(Material.WHITE_STAINED_GLASS_PANE)); + public static void OpenGui(Player p, int page) { + Inventory inv = Bukkit.createInventory(null, 54, invTitle); + for (int i = 45; i < 53; i++) { + inv.setItem(i, new ItemStack(Material.WHITE_STAINED_GLASS_PANE)); } - inv.setItem(45,Paper_Butt("§a上一页",page)); - inv.setItem(53,Paper_Butt("§a下一页",page)); + inv.setItem(45, Paper_Butt("§a上一页", page)); + inv.setItem(53, Paper_Butt("§a下一页", page)); List itemStackList = new ArrayList<>(); - for (String soundKey : soundList){ + for (String soundKey : soundList) { ItemStack item = itemShow(soundKey).clone(); itemStackList.add(item); } @@ -96,22 +51,22 @@ public class SoundsMenu implements Listener { p.openInventory(inv); } - public static ItemStack itemShow(String sound){ + public static ItemStack itemShow(String sound) { ItemStack item = new ItemStack(Material.NOTE_BLOCK); ItemMeta meta = item.getItemMeta(); - meta.setDisplayName("§6"+sound); + meta.setDisplayName("§6" + sound); List lore = new ArrayList<>(); - lore.add("§7#礼物设置声音处填入 §6"+sound+" §7即可"); + lore.add("§7#礼物设置声音处填入 §6" + sound + " §7即可"); lore.add(" "); lore.add("§a§l★ §6左键点击播放"); meta.setLore(lore); item.setItemMeta(meta); NBTItem nbtItem = new NBTItem(item); - nbtItem.setString("sound",sound); + nbtItem.setString("sound", sound); return nbtItem.getItem(); } - public static ItemStack Paper_Butt(String name,int amount){ + public static ItemStack Paper_Butt(String name, int amount) { ItemStack item = new ItemStack(Material.ARROW); item.setAmount(amount); ItemMeta meta = item.getItemMeta(); @@ -122,4 +77,48 @@ public class SoundsMenu implements Listener { item.setItemMeta(meta); return item; } + + @EventHandler + public void onClick(InventoryClickEvent e) { + int rawSlot = e.getRawSlot(); + Inventory inv = e.getInventory(); + Player p = (Player) e.getWhoClicked(); + ItemStack item = e.getCurrentItem(); + if (e.getView().getTitle().equalsIgnoreCase(invTitle)) { + e.setCancelled(true); + int Pages = e.getInventory().getItem(45).getAmount(); + if (e.getRawSlot() == 45) { + p.playSound(p.getLocation(), Sound.BLOCK_COMPARATOR_CLICK, 1, 2); + if (Pages >= 2 && Pages <= 31) { + SoundsMenu.OpenGui(p, Pages - 1); + } else { + p.sendMessage("§c[消息]§a已经是第一页了!"); + } + } + if (e.getRawSlot() == 53) { + p.playSound(p.getLocation(), Sound.BLOCK_COMPARATOR_CLICK, 1, 2); + if (Pages >= 1 && Pages <= 32) { + SoundsMenu.OpenGui(p, Pages + 1); + } else { + p.sendMessage("§c[消息]§a已经是最后一页了!"); + } + } + if (rawSlot >= 0 && rawSlot < 45) { + if (item != null && item.getType() != Material.AIR) { + NBTItem nbt = new NBTItem(item); + if (nbt.hasKey("sound")) { + String sound = nbt.getString("sound"); + p.playSound(p.getLocation(), sound, 1.0F, 1.0F); + p.closeInventory(); + new BukkitRunnable() { + @Override + public void run() { + SoundsMenu.OpenGui(p, Pages); + } + }.runTaskLater(Main.plugin, 15L); + } + } + } + } + } } diff --git a/src/main/java/com/io/yutian/mclive/live/LiveEvent.java b/src/main/java/com/io/yutian/mclive/live/LiveEvent.java index cd7b7cc..2e444d4 100644 --- a/src/main/java/com/io/yutian/mclive/live/LiveEvent.java +++ b/src/main/java/com/io/yutian/mclive/live/LiveEvent.java @@ -1,10 +1,10 @@ package com.io.yutian.mclive.live; -import com.io.yutian.mclive.util.ConfigYml; import com.io.yutian.mclive.Main; -import com.io.yutian.mclive.data.GiftManage; +import com.io.yutian.livemutually.manager.GiftManager; import com.io.yutian.mclive.event.*; import com.io.yutian.mclive.listener.LiveAdminGui; +import com.io.yutian.mclive.util.ConfigYml; import net.md_5.bungee.api.ChatMessageType; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.Bukkit; @@ -16,9 +16,12 @@ public class LiveEvent implements Listener { private ConfigYml configYml; - public LiveEvent(ConfigYml configYml){this.configYml = configYml;} + public LiveEvent(ConfigYml configYml) { + this.configYml = configYml; + } + @EventHandler - public void onGift(LiveGiftEvents e){ + public void onGift(LiveGiftEvents e) { if (Main.check_plugin) { LiveAdminGui.offline_zhubo.put(e.getPlayer(), 1); String type = "礼物"; @@ -26,13 +29,13 @@ public class LiveEvent implements Listener { String gift_name = e.getName(); long gift_amount = e.getAmount(); if (Main.giftStatistics && ConfigYml.mysqlState) { - GiftManage giftManage = Main.giftManage; + GiftManager giftManager = Main.giftManager; String name = e.getPlayer().getName(); - int trillGift = giftManage.getGiftMoney(gift_name); + int trillGift = giftManager.getGiftMoney(gift_name); if (gift_amount >= 2) { - giftManage.addTotalMoney(name,trillGift, gift_amount); + giftManager.addTotalMoney(name, trillGift, gift_amount); } else { - giftManage.addTotalMoney(name,trillGift); + giftManager.addTotalMoney(name, trillGift); } } // Bukkit.getConsoleSender().sendMessage("[直播互动 " + e.getPlayer().getName() + "] 类型: " + type + " 用户: " + audience + " 礼物: " + gift_name + "x" + gift_amount); @@ -41,24 +44,24 @@ public class LiveEvent implements Listener { @EventHandler//关注 public void onMcLive(LiveFollowEvents e) { - LiveAdminGui.offline_zhubo.put(e.getPlayer(),1); + LiveAdminGui.offline_zhubo.put(e.getPlayer(), 1); String type = "关注"; String audience = e.getUser().nickName(); - Bukkit.getConsoleSender().sendMessage("[直播互动 "+e.getPlayer().getName()+"] 类型: " + type + " 用户: " + audience); + Bukkit.getConsoleSender().sendMessage("[直播互动 " + e.getPlayer().getName() + "] 类型: " + type + " 用户: " + audience); } @EventHandler//信息 public void onMcLive(LiveChatEvents e) { - LiveAdminGui.offline_zhubo.put(e.getPlayer(),1); + LiveAdminGui.offline_zhubo.put(e.getPlayer(), 1); String type = "信息"; String audience = e.getUser().nickName(); String message = e.getContent(); - Bukkit.getConsoleSender().sendMessage("[直播互动 "+e.getPlayer().getName()+"] 类型: " + type + " 用户: " + audience + " 信息: " + message); + Bukkit.getConsoleSender().sendMessage("[直播互动 " + e.getPlayer().getName() + "] 类型: " + type + " 用户: " + audience + " 信息: " + message); } @EventHandler//点赞 public void onGuanzhu(LiveLikeEvents e) { - LiveAdminGui.offline_zhubo.put(e.getPlayer(),1); + LiveAdminGui.offline_zhubo.put(e.getPlayer(), 1); String type = "点赞"; String audience = e.getUser().nickName(); long gift_amount = e.getCount(); @@ -68,10 +71,10 @@ public class LiveEvent implements Listener { @EventHandler//进入 public void onMcLive(LiveEnterEvents e) { Player player = e.getPlayer(); - LiveAdminGui.offline_zhubo.put(e.getPlayer(),1); + LiveAdminGui.offline_zhubo.put(e.getPlayer(), 1); String type = "进入"; String audience = e.getUser().nickName(); - Bukkit.getConsoleSender().sendMessage("[直播互动 "+e.getPlayer().getName()+"] 类型: " + type + " 用户: " + audience); - player.spigot().sendMessage(ChatMessageType.ACTION_BAR,new TextComponent("§6" + Main.HideName(audience) + "来了")); + Bukkit.getConsoleSender().sendMessage("[直播互动 " + e.getPlayer().getName() + "] 类型: " + type + " 用户: " + audience); + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent("§6" + Main.HideName(audience) + "来了")); } } diff --git a/src/main/java/com/io/yutian/mclive/live/ModEvent.java b/src/main/java/com/io/yutian/mclive/live/ModEvent.java index 1407c34..e346ffd 100644 --- a/src/main/java/com/io/yutian/mclive/live/ModEvent.java +++ b/src/main/java/com/io/yutian/mclive/live/ModEvent.java @@ -10,15 +10,15 @@ import org.bukkit.event.Listener; public class ModEvent implements Listener { @EventHandler - public void onWsMessage(WSMessageEvent e){ + public void onWsMessage(WSMessageEvent e) { Player player = e.getPlayer(); String s = e.getMessage(); - MessageUtil.parse(player,s); + MessageUtil.parse(player, s); } @EventHandler - public void onKey(KeyInputEvent e){ + public void onKey(KeyInputEvent e) { Player player = e.getPlayer(); } } diff --git a/src/main/java/com/io/yutian/mclive/util/ConfigYml.java b/src/main/java/com/io/yutian/mclive/util/ConfigYml.java index 83be542..551741a 100644 --- a/src/main/java/com/io/yutian/mclive/util/ConfigYml.java +++ b/src/main/java/com/io/yutian/mclive/util/ConfigYml.java @@ -21,13 +21,13 @@ public class ConfigYml { } this.MainDebug = yml.getBoolean("MainDebug"); this.GameMode = yml.getString("GameMode"); - Bukkit.getConsoleSender().sendMessage("§b[整蛊MC直播] §7对接游戏: §e"+ this.GameMode); + Bukkit.getConsoleSender().sendMessage("§b[整蛊MC直播] §7对接游戏: §e" + this.GameMode); if (yml.getConfigurationSection("LiveId") != null) { HashMap hashMap = new HashMap<>(); for (String playName : yml.getConfigurationSection("LiveId").getKeys(false)) { String live_id = yml.getString("LiveId." + playName); hashMap.put(playName, live_id); - Bukkit.getConsoleSender().sendMessage("§b[整蛊MC直播] §7主播: §e"+ playName + " - " + live_id); + Bukkit.getConsoleSender().sendMessage("§b[整蛊MC直播] §7主播: §e" + playName + " - " + live_id); } this.RoomId_Map = hashMap; } @@ -54,21 +54,28 @@ public class ConfigYml { Main.plugin.saveConfig(); } - public boolean isMainDebug() {return MainDebug;} + public boolean isMainDebug() { + return MainDebug; + } + public void setMainDebug(boolean butt) { FileConfiguration yml = Main.plugin.getConfig(); - yml.set("MainDebug",butt); + yml.set("MainDebug", butt); Main.plugin.saveConfig(); MainDebug = butt; } - public long getGifts_delay() {return gifts_delay;} + public long getGifts_delay() { + return gifts_delay; + } + public void setGifts_delay(long gifts_delay) { FileConfiguration yml = Main.plugin.getConfig(); - yml.set("GiftDelay",gifts_delay); + yml.set("GiftDelay", gifts_delay); Main.plugin.saveConfig(); this.gifts_delay = gifts_delay; } + public String getGameMode() { return this.GameMode; } @@ -83,8 +90,9 @@ public class ConfigYml { public HashMap getRoomId_Map() { return this.RoomId_Map; } + public void setRoomId(String playName, String roomId) { - this.RoomId_Map.put(playName,roomId); + this.RoomId_Map.put(playName, roomId); } } diff --git a/src/main/java/com/io/yutian/mclive/util/FileUtil.java b/src/main/java/com/io/yutian/mclive/util/FileUtil.java new file mode 100644 index 0000000..51b6041 --- /dev/null +++ b/src/main/java/com/io/yutian/mclive/util/FileUtil.java @@ -0,0 +1,34 @@ +package com.io.yutian.mclive.util; + +import java.io.*; +import java.net.URL; +import java.util.Base64; + +public class FileUtil { + + public static void downloadImage(String imageUrl, File destinationFile, Runnable callback) { + try (InputStream inputStream = new URL(imageUrl).openStream(); + OutputStream outputStream = new FileOutputStream(destinationFile)) { + byte[] buffer = new byte[2048]; + int length; + while ((length = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, length); + } + callback.run(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static String convertImageToBase64(File imageFile) { + try (FileInputStream fileInputStream = new FileInputStream(imageFile)) { + byte[] imageBytes = new byte[(int) imageFile.length()]; + fileInputStream.read(imageBytes); + return Base64.getEncoder().encodeToString(imageBytes); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + +} diff --git a/src/main/java/com/io/yutian/mclive/util/MessageUtil.java b/src/main/java/com/io/yutian/mclive/util/MessageUtil.java index c3fd0a2..6b3e9ea 100644 --- a/src/main/java/com/io/yutian/mclive/util/MessageUtil.java +++ b/src/main/java/com/io/yutian/mclive/util/MessageUtil.java @@ -1,13 +1,21 @@ package com.io.yutian.mclive.util; import cn.hamster3.cdapi.CDTimeAPI; -import com.io.yutian.livemutually.manager.GiftData; -import com.io.yutian.livemutually.manager.UserData; -import com.io.yutian.livemutually.wss.*; +import com.io.yutian.livemutually.manager.GiftManager; +import com.io.yutian.livemutually.manager.RankManager; +import com.io.yutian.livemutually.manager.UserManager; +import com.io.yutian.mclive.data.GiftData; +import com.io.yutian.mclive.data.UserData; +import com.io.yutian.livemutually.wss.KSAPILiveRoomWatcher; +import com.io.yutian.livemutually.wss.KuaiShouChat; +import com.io.yutian.livemutually.wss.KuaiShouLike; +import com.io.yutian.livemutually.wss.KuaiShouUser; import com.io.yutian.mclive.Main; +import com.io.yutian.mclive.data.UserResourceData; import com.io.yutian.mclive.event.LiveGiftEvents; import com.io.yutian.mclive.event.ZhuboAPI; import com.io.yutian.verify.AESUtil; +import json.JSONArray; import json.JSONObject; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -19,18 +27,24 @@ import java.util.HashMap; public class MessageUtil { - public static void parse(Player player,String py_data){ - if(py_data.isEmpty()){return;} - if(ZhuboAPI.getRoomLiveName().equalsIgnoreCase("KuaiShou")){ + // H8dyaR95ZJwZ6PikZ1qmoIY1 密匙 + private static final String AES_KEY = "01001000001110000110010001111001011000010101001000111001001101010101101001001010011101110101101000110110010100000110100101101"; // 与Python中相同的密钥 + public static HashMap userDataMap = new HashMap<>(); + + public static void parse(Player player, String py_data) { + if (py_data.isEmpty()) { + return; + } + if (ZhuboAPI.getRoomLiveName().equalsIgnoreCase("KuaiShou")) { JSONObject jsonObject = new JSONObject(py_data); if (py_data.contains("type")) { - long cdTime = CDTimeAPI.getCD(player.getUniqueId(),"tingcloud_cd"); - if(cdTime < 0) { - CDTimeAPI.setPlayerCD(player.getUniqueId(),"tingcloud_cd",1000 * 10); + long cdTime = CDTimeAPI.getCD(player.getUniqueId(), "tingcloud_cd"); + if (cdTime < 0) { + CDTimeAPI.setPlayerCD(player.getUniqueId(), "tingcloud_cd", 1000 * 10); Bukkit.getConsoleSender().sendMessage("§a[直播连接助手] 听云整蛊弹幕正常抓取中..."); } String type = jsonObject.getString("type"); - if(type.equalsIgnoreCase("礼物")){ + if (type.equalsIgnoreCase("礼物")) { String nickName = jsonObject.getString("昵称"); String giftName = jsonObject.getString("礼物名称"); int newCount = jsonObject.getInt("礼物数量"); @@ -48,26 +62,27 @@ public class MessageUtil { String message = "§6[日志 - 礼物触发] §f" + player.getName() + " >>> " + nickName + " = §a" + giftName + " 数量: " + count_color + newCount; Bukkit.getConsoleSender().sendMessage(message); LiveGiftEvents event = new LiveGiftEvents(player, new KuaiShouUser(nickName), giftName, newCount); + Bukkit.getPluginManager().callEvent(event); } - }else if(type.equalsIgnoreCase("发言")){ + } else if (type.equalsIgnoreCase("发言")) { String userName = jsonObject.getString("昵称"); String message = jsonObject.getString("弹幕"); KSAPILiveRoomWatcher ksapiLiveRoomWatcher = new KSAPILiveRoomWatcher(player); ksapiLiveRoomWatcher.callChat(new KuaiShouChat(userName, message)); - }else if(type.equalsIgnoreCase("点赞")){ + } else if (type.equalsIgnoreCase("点赞")) { String userName = jsonObject.getString("昵称"); KSAPILiveRoomWatcher ksapiLiveRoomWatcher = new KSAPILiveRoomWatcher(player); ksapiLiveRoomWatcher.callLike(new KuaiShouLike(userName, 1)); } } else { - long cdTime = CDTimeAPI.getCD(player.getUniqueId(),"tingcloud_cd"); - if(cdTime < 0) { - CDTimeAPI.setPlayerCD(player.getUniqueId(),"tingcloud_cd",1000 * 10); + long cdTime = CDTimeAPI.getCD(player.getUniqueId(), "tingcloud_cd"); + if (cdTime < 0) { + CDTimeAPI.setPlayerCD(player.getUniqueId(), "tingcloud_cd", 1000 * 10); Bukkit.getConsoleSender().sendMessage("§a[直播连接助手] 听云整蛊弹幕正常抓取中..."); } } - }else { + } else { String s; try { s = decrypt_ecb(py_data); @@ -82,7 +97,10 @@ public class MessageUtil { return; } JSONObject dataObject = new JSONObject(jsonObject.getString("data")); - String nickName = dataObject.getJSONObject("user").getString("nickName"); + JSONObject userJSONObject = dataObject.getJSONObject("user"); + String nickName = userJSONObject.getString("nickName"); + UserResourceData userResourceData = parseUserResourceData(userJSONObject); + UserManager.setUserResourceData(nickName, userResourceData); // 礼物名 String giftName = dataObject.getJSONObject("gift").getString("name"); // 礼物数量 @@ -138,6 +156,7 @@ public class MessageUtil { Bukkit.getConsoleSender().sendMessage(message); LiveGiftEvents event = new LiveGiftEvents(player, new KuaiShouUser(nickName), giftName, newCount); Bukkit.getPluginManager().callEvent(event); + RankManager.addUserAmount(nickName, Main.giftManager.getGiftMoney(giftName) * newCount); } } else if (type.equalsIgnoreCase("chat_message")) { if (!ZhuboAPI.isWsRoomIdSame(player)) { @@ -171,7 +190,7 @@ public class MessageUtil { ksapiLiveRoomWatcher.callUser(new KuaiShouUser(nickName)); } else if (type.equalsIgnoreCase("live_id")) { JSONObject dataObject = jsonObject.getJSONObject("data"); - String wsRoomId = dataObject.getString("id").replace(" ","").replace("\n",""); + String wsRoomId = dataObject.getString("id").replace(" ", "").replace("\n", ""); if (ZhuboAPI.wsRoomIdSame.get(player) == null) { String roomId = Main.configYml.getRoomId(player.getName()); if (!wsRoomId.equalsIgnoreCase(roomId)) { @@ -192,21 +211,35 @@ public class MessageUtil { public static void sendConsoleMessage(String message) { // Bukkit.getConsoleSender().sendMessage("§6[弹幕监听] " + message); } - public static HashMap userDataMap = new HashMap<>(); - // H8dyaR95ZJwZ6PikZ1qmoIY1 密匙 - private static final String AES_KEY = "01001000001110000110010001111001011000010101001000111001001101010101101001001010011101110101101000110110010100000110100101101"; // 与Python中相同的密钥 public static String decrypt_ecb(String encryptedMessage) throws Exception { // Base64解码 byte[] decodedMessage = Base64.getDecoder().decode(encryptedMessage); // AES解密 - Cipher cipher = Cipher.getInstance(AESUtil.convertString("0100000101000101010100110010111101000101010000110100001000101111010100000100"+AESUtil.DEFAULT_CIPHER_ALGORITHM)); - SecretKeySpec secretKeySpec = new SecretKeySpec(AESUtil.convertString(AES_KEY+"0110101101000110001011100010110110101101111010010010101100100110001").getBytes(), "AES"); + Cipher cipher = Cipher.getInstance(AESUtil.convertString("0100000101000101010100110010111101000101010000110100001000101111010100000100" + AESUtil.DEFAULT_CIPHER_ALGORITHM)); + SecretKeySpec secretKeySpec = new SecretKeySpec(AESUtil.convertString(AES_KEY + "0110101101000110001011100010110110101101111010010010101100100110001").getBytes(), "AES"); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); byte[] decryptedBytes = cipher.doFinal(decodedMessage); // 转换为字符串 return new String(decryptedBytes, "UTF-8"); } + + private static UserResourceData parseUserResourceData(JSONObject jsonObject) { + String nickname = jsonObject.getString("nickName"); + String avatarThumb = jsonObject.getJSONObject("AvatarThumb").getJSONArray("urlListList").getString(0); + int level = 1; + if (jsonObject.has("BadgeImageList")) { + JSONArray jsonArray = jsonObject.getJSONArray("BadgeImageList"); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject jsonObject1 = jsonArray.getJSONObject(i); + String url = jsonObject1.getString("uri"); + if (url.startsWith("webcast/new_user_grade_level")) { + level = jsonObject1.getJSONObject("content").getInt("level"); + } + } + } + return new UserResourceData(nickname, avatarThumb, level); + } } diff --git a/src/main/java/com/io/yutian/mclive/util/SqlUtil.java b/src/main/java/com/io/yutian/mclive/util/SqlUtil.java index 210c2d2..6e7c23a 100644 --- a/src/main/java/com/io/yutian/mclive/util/SqlUtil.java +++ b/src/main/java/com/io/yutian/mclive/util/SqlUtil.java @@ -26,9 +26,9 @@ public class SqlUtil extends MegumiSQL { public void openConnection() { try { String mcVersion = Main.getMinecraftVersion(); - if(mcVersion.contains("1_20")){ + if (mcVersion.contains("1_20")) { Class.forName("com.mysql.cj.jdbc.Driver"); // 1.20.4的mysql路径 - }else{ + } else { Class.forName("com.mysql.jdbc.Driver"); // 1.18.2的mysql路径 } this.connection = DriverManager.getConnection("jdbc:mysql://" + this.hostname + ":" + this.port + "/" + this.database + "?useSSL=false", this.username, this.password); diff --git a/src/main/java/com/io/yutian/verify/AESUtil.java b/src/main/java/com/io/yutian/verify/AESUtil.java index 8771f6f..f607392 100644 --- a/src/main/java/com/io/yutian/verify/AESUtil.java +++ b/src/main/java/com/io/yutian/verify/AESUtil.java @@ -14,9 +14,9 @@ import java.util.Base64; public class AESUtil { - private static final String KEY_ALGORITHM = "AES"; // AES/ECB/PKCS5Padding public static final String DEFAULT_CIPHER_ALGORITHM = "101101000011010100110011010101010000011000010110010001100100011010010110111001100111"; + private static final String KEY_ALGORITHM = "AES"; // 将二进制字符串转换为普通字符串 public static String convertString(String binaryString) { @@ -34,25 +34,23 @@ public class AESUtil { return result.toString(); } - public static boolean isVerifyCheck(Player p, String pluginName, String roomId){ - if(!Main.check_plugin){ + public static boolean isVerifyCheck(Player p, String pluginName, String roomId) { + if (!Main.check_plugin) { return false; } - PluginVerifyResult verifyResult = VerifyHandler.verify("127.0.0.1",pluginName,roomId); + PluginVerifyResult verifyResult = VerifyHandler.verify("127.0.0.1", pluginName, roomId); if (!verifyResult.equals(PluginVerifyResult.VERIFY_SUCCESS)) { - if(verifyResult == PluginVerifyResult.USER_STATE_DISABLE){ - Bukkit.getConsoleSender().sendMessage("[验证日志 - 拦截] "+p.getName()+" 的直播间授权已到期."); + if (verifyResult == PluginVerifyResult.USER_STATE_DISABLE) { + Bukkit.getConsoleSender().sendMessage("[验证日志 - 拦截] " + p.getName() + " 的直播间授权已到期."); p.sendMessage("§c[系统]§a验证尚未通过,您的直播间授权已到期."); - } else - if(verifyResult == PluginVerifyResult.FAIL_CODE){ - Bukkit.getConsoleSender().sendMessage("[验证日志 - 拦截] "+p.getName()+" 的直播间尚未进行授权. "+roomId); - p.sendMessage("§c[系统]§a验证尚未通过,直播间§e<"+roomId+">§a尚未进行授权."); - } else - if(verifyResult == PluginVerifyResult.FAIL_TIMEOUT){ - Bukkit.getConsoleSender().sendMessage("[验证日志 - 拦截] "+p.getName()+" 的本地网络有问题,无法连接验证服务器."); + } else if (verifyResult == PluginVerifyResult.FAIL_CODE) { + Bukkit.getConsoleSender().sendMessage("[验证日志 - 拦截] " + p.getName() + " 的直播间尚未进行授权. " + roomId); + p.sendMessage("§c[系统]§a验证尚未通过,直播间§e<" + roomId + ">§a尚未进行授权."); + } else if (verifyResult == PluginVerifyResult.FAIL_TIMEOUT) { + Bukkit.getConsoleSender().sendMessage("[验证日志 - 拦截] " + p.getName() + " 的本地网络有问题,无法连接验证服务器."); p.sendMessage("§c[系统]§a验证尚未通过,您当前的网络环境有问题."); } else { - Bukkit.getConsoleSender().sendMessage("[验证日志 - 拦截] "+p.getName()+" 的无法通过验证. "+verifyResult); + Bukkit.getConsoleSender().sendMessage("[验证日志 - 拦截] " + p.getName() + " 的无法通过验证. " + verifyResult); p.sendMessage("§c[系统]§a验证尚未通过,无法连接直播间,请联系管理员。§c§l#" + verifyResult); } return true; @@ -68,7 +66,7 @@ public class AESUtil { public static String encrypt(String content, String key) { try { - Cipher cipher = Cipher.getInstance(convertString("0100000101000101010100110010111101000101010000110100001000101111010100000100"+DEFAULT_CIPHER_ALGORITHM)); + Cipher cipher = Cipher.getInstance(convertString("0100000101000101010100110010111101000101010000110100001000101111010100000100" + DEFAULT_CIPHER_ALGORITHM)); byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key)); byte[] result = cipher.doFinal(byteContent); @@ -80,7 +78,7 @@ public class AESUtil { public static String decrypt(String content, String key) { try { - Cipher cipher = Cipher.getInstance(convertString("0100000101000101010100110010111101000101010000110100001000101111010100000100"+DEFAULT_CIPHER_ALGORITHM)); + Cipher cipher = Cipher.getInstance(convertString("0100000101000101010100110010111101000101010000110100001000101111010100000100" + DEFAULT_CIPHER_ALGORITHM)); cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key)); byte[] result = cipher.doFinal(base642Byte(content)); return new String(result, "utf-8"); diff --git a/src/main/java/com/io/yutian/verify/VerifyHandler.java b/src/main/java/com/io/yutian/verify/VerifyHandler.java index a991bfb..06f2503 100644 --- a/src/main/java/com/io/yutian/verify/VerifyHandler.java +++ b/src/main/java/com/io/yutian/verify/VerifyHandler.java @@ -4,7 +4,6 @@ import json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; -import java.net.ConnectException; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLConnection; @@ -41,24 +40,26 @@ public class VerifyHandler { return PluginVerifyResult.UNKNOWN; } } - public static String getServerIp(){ + + public static String getServerIp() { String a = "47."; String b = "111."; String c = "169."; String d = "142"; String e = "82"; String f = "81"; - return a+b+c+d+":"+e+f; + return a + b + c + d + ":" + e + f; } + private static String get(String plugin, String code) throws Exception { - String url = "/verify?plugin="+plugin+"&code="+code; - URL realUrl = new URL("http://"+getServerIp()+url); + String url = "/verify?plugin=" + plugin + "&code=" + code; + URL realUrl = new URL("http://" + getServerIp() + url); URLConnection connection = realUrl.openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(15000); connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); - connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); + connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")); StringBuilder stringBuilder = new StringBuilder(); diff --git a/src/main/java/json/JSONArray.java b/src/main/java/json/JSONArray.java index 8eb9129..b5f594f 100644 --- a/src/main/java/json/JSONArray.java +++ b/src/main/java/json/JSONArray.java @@ -94,17 +94,15 @@ public class JSONArray implements Iterable { /** * Construct a JSONArray from a JSONTokener. * - * @param x - * A JSONTokener - * @throws JSONException - * If there is a syntax error. + * @param x A JSONTokener + * @throws JSONException If there is a syntax error. */ public JSONArray(JSONTokener x) throws JSONException { this(); if (x.nextClean() != '[') { throw x.syntaxError("A JSONArray text must start with '['"); } - + char nextChar = x.nextClean(); if (nextChar == 0) { // array is unclosed. No ']' found, instead EOF @@ -112,7 +110,7 @@ public class JSONArray implements Iterable { } if (nextChar != ']') { x.back(); - for (;;) { + for (; ; ) { if (x.nextClean() == ',') { x.back(); this.myArrayList.add(JSONObject.NULL); @@ -121,24 +119,24 @@ public class JSONArray implements Iterable { this.myArrayList.add(x.nextValue()); } switch (x.nextClean()) { - case 0: - // array is unclosed. No ']' found, instead EOF - throw x.syntaxError("Expected a ',' or ']'"); - case ',': - nextChar = x.nextClean(); - if (nextChar == 0) { + case 0: // array is unclosed. No ']' found, instead EOF throw x.syntaxError("Expected a ',' or ']'"); - } - if (nextChar == ']') { + case ',': + nextChar = x.nextClean(); + if (nextChar == 0) { + // array is unclosed. No ']' found, instead EOF + throw x.syntaxError("Expected a ',' or ']'"); + } + if (nextChar == ']') { + return; + } + x.back(); + break; + case ']': return; - } - x.back(); - break; - case ']': - return; - default: - throw x.syntaxError("Expected a ',' or ']'"); + default: + throw x.syntaxError("Expected a ',' or ']'"); } } } @@ -147,12 +145,10 @@ public class JSONArray implements Iterable { /** * Construct a JSONArray from a source JSON text. * - * @param source - * A string that begins with [ (left - * bracket) and ends with ] - *  (right bracket). - * @throws JSONException - * If there is a syntax error. + * @param source A string that begins with [ (left + * bracket) and ends with ] + *  (right bracket). + * @throws JSONException If there is a syntax error. */ public JSONArray(String source) throws JSONException { this(new JSONTokener(source)); @@ -161,31 +157,26 @@ public class JSONArray implements Iterable { /** * Construct a JSONArray from a Collection. * - * @param collection - * A Collection. + * @param collection A Collection. */ public JSONArray(Collection collection) { if (collection == null) { this.myArrayList = new ArrayList(); } else { this.myArrayList = new ArrayList(collection.size()); - for (Object o: collection){ - this.myArrayList.add(JSONObject.wrap(o)); - } + for (Object o : collection) { + this.myArrayList.add(JSONObject.wrap(o)); + } } } /** * Construct a JSONArray from an array. * - * @param array - * Array. If the parameter passed is null, or not an array, an - * exception will be thrown. - * - * @throws JSONException - * If not an array or if an array value is non-finite number. - * @throws NullPointerException - * Thrown if the array parameter is null. + * @param array Array. If the parameter passed is null, or not an array, an + * exception will be thrown. + * @throws JSONException If not an array or if an array value is non-finite number. + * @throws NullPointerException Thrown if the array parameter is null. */ public JSONArray(Object array) throws JSONException { this(); @@ -201,6 +192,41 @@ public class JSONArray implements Iterable { } } + /** + * Create a new JSONException in a common format for incorrect conversions. + * + * @param idx index of the item + * @param valueType the type of value being coerced to + * @param cause optional cause of the coercion failure + * @return JSONException that can be thrown. + */ + private static JSONException wrongValueFormatException( + int idx, + String valueType, + Throwable cause) { + return new JSONException( + "JSONArray[" + idx + "] is not a " + valueType + "." + , cause); + } + + /** + * Create a new JSONException in a common format for incorrect conversions. + * + * @param idx index of the item + * @param valueType the type of value being coerced to + * @param cause optional cause of the coercion failure + * @return JSONException that can be thrown. + */ + private static JSONException wrongValueFormatException( + int idx, + String valueType, + Object value, + Throwable cause) { + return new JSONException( + "JSONArray[" + idx + "] is not a " + valueType + " (" + value + ")." + , cause); + } + @Override public Iterator iterator() { return this.myArrayList.iterator(); @@ -209,11 +235,9 @@ public class JSONArray implements Iterable { /** * Get the object value associated with an index. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return An object value. - * @throws JSONException - * If there is no value for the index. + * @throws JSONException If there is no value for the index. */ public Object get(int index) throws JSONException { Object object = this.opt(index); @@ -227,22 +251,20 @@ public class JSONArray implements Iterable { * Get the boolean value associated with an index. The string values "true" * and "false" are converted to boolean. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The truth. - * @throws JSONException - * If there is no value for the index or if the value is not - * convertible to boolean. + * @throws JSONException If there is no value for the index or if the value is not + * convertible to boolean. */ public boolean getBoolean(int index) throws JSONException { Object object = this.get(index); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String) object) - .equalsIgnoreCase("false"))) { + .equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String) object) - .equalsIgnoreCase("true"))) { + .equalsIgnoreCase("true"))) { return true; } throw wrongValueFormatException(index, "boolean", null); @@ -251,17 +273,15 @@ public class JSONArray implements Iterable { /** * Get the double value associated with an index. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a number. + * @throws JSONException If the key is not found or if the value cannot be converted + * to a number. */ public double getDouble(int index) throws JSONException { final Object object = this.get(index); - if(object instanceof Number) { - return ((Number)object).doubleValue(); + if (object instanceof Number) { + return ((Number) object).doubleValue(); } try { return Double.parseDouble(object.toString()); @@ -273,17 +293,15 @@ public class JSONArray implements Iterable { /** * Get the float value associated with a key. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value is not a Number - * object and cannot be converted to a number. + * @throws JSONException if the key is not found or if the value is not a Number + * object and cannot be converted to a number. */ public float getFloat(int index) throws JSONException { final Object object = this.get(index); - if(object instanceof Number) { - return ((Float)object).floatValue(); + if (object instanceof Number) { + return ((Float) object).floatValue(); } try { return Float.parseFloat(object.toString()); @@ -295,18 +313,16 @@ public class JSONArray implements Iterable { /** * Get the Number value associated with a key. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value is not a Number - * object and cannot be converted to a number. + * @throws JSONException if the key is not found or if the value is not a Number + * object and cannot be converted to a number. */ public Number getNumber(int index) throws JSONException { Object object = this.get(index); try { if (object instanceof Number) { - return (Number)object; + return (Number) object; } return JSONObject.stringToNumber(object.toString()); } catch (Exception e) { @@ -316,21 +332,17 @@ public class JSONArray implements Iterable { /** * Get the enum value associated with an index. - * - * @param - * Enum Type - * @param clazz - * The type of enum to retrieve. - * @param index - * The index must be between 0 and length() - 1. + * + * @param Enum Type + * @param clazz The type of enum to retrieve. + * @param index The index must be between 0 and length() - 1. * @return The enum value at the index location - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to an enum. + * @throws JSONException if the key is not found or if the value cannot be converted + * to an enum. */ public > E getEnum(Class clazz, int index) throws JSONException { E val = optEnum(clazz, index); - if(val==null) { + if (val == null) { // JSONException should really take a throwable argument. // If it did, I would re-implement this with the Enum.valueOf // method and place any thrown exception in the JSONException @@ -346,17 +358,15 @@ public class JSONArray implements Iterable { * will be used. See notes on the constructor for conversion issues that * may arise. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a BigDecimal. + * @throws JSONException If the key is not found or if the value cannot be converted + * to a BigDecimal. */ - public BigDecimal getBigDecimal (int index) throws JSONException { + public BigDecimal getBigDecimal(int index) throws JSONException { Object object = this.get(index); BigDecimal val = JSONObject.objectToBigDecimal(object, null); - if(val == null) { + if (val == null) { throw wrongValueFormatException(index, "BigDecimal", object, null); } return val; @@ -365,17 +375,15 @@ public class JSONArray implements Iterable { /** * Get the BigInteger value associated with an index. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a BigInteger. + * @throws JSONException If the key is not found or if the value cannot be converted + * to a BigInteger. */ - public BigInteger getBigInteger (int index) throws JSONException { + public BigInteger getBigInteger(int index) throws JSONException { Object object = this.get(index); BigInteger val = JSONObject.objectToBigInteger(object, null); - if(val == null) { + if (val == null) { throw wrongValueFormatException(index, "BigInteger", object, null); } return val; @@ -384,16 +392,14 @@ public class JSONArray implements Iterable { /** * Get the int value associated with an index. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The value. - * @throws JSONException - * If the key is not found or if the value is not a number. + * @throws JSONException If the key is not found or if the value is not a number. */ public int getInt(int index) throws JSONException { final Object object = this.get(index); - if(object instanceof Number) { - return ((Number)object).intValue(); + if (object instanceof Number) { + return ((Number) object).intValue(); } try { return Integer.parseInt(object.toString()); @@ -405,12 +411,10 @@ public class JSONArray implements Iterable { /** * Get the JSONArray associated with an index. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return A JSONArray value. - * @throws JSONException - * If there is no value for the index. or if the value is not a - * JSONArray + * @throws JSONException If there is no value for the index. or if the value is not a + * JSONArray */ public JSONArray getJSONArray(int index) throws JSONException { Object object = this.get(index); @@ -423,12 +427,10 @@ public class JSONArray implements Iterable { /** * Get the JSONObject associated with an index. * - * @param index - * subscript + * @param index subscript * @return A JSONObject value. - * @throws JSONException - * If there is no value for the index or if the value is not a - * JSONObject + * @throws JSONException If there is no value for the index or if the value is not a + * JSONObject */ public JSONObject getJSONObject(int index) throws JSONException { Object object = this.get(index); @@ -441,17 +443,15 @@ public class JSONArray implements Iterable { /** * Get the long value associated with an index. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a number. + * @throws JSONException If the key is not found or if the value cannot be converted + * to a number. */ public long getLong(int index) throws JSONException { final Object object = this.get(index); - if(object instanceof Number) { - return ((Number)object).longValue(); + if (object instanceof Number) { + return ((Number) object).longValue(); } try { return Long.parseLong(object.toString()); @@ -463,11 +463,9 @@ public class JSONArray implements Iterable { /** * Get the string associated with an index. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return A string value. - * @throws JSONException - * If there is no string value for the index. + * @throws JSONException If there is no string value for the index. */ public String getString(int index) throws JSONException { Object object = this.get(index); @@ -480,8 +478,7 @@ public class JSONArray implements Iterable { /** * Determine if the value is null. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return true if the value at the index is null, or if there is no value. */ public boolean isNull(int index) { @@ -493,24 +490,22 @@ public class JSONArray implements Iterable { * separator string is inserted between each element. Warning: * This method assumes that the data structure is acyclical. * - * @param separator - * A string that will be inserted between the elements. + * @param separator A string that will be inserted between the elements. * @return a string. - * @throws JSONException - * If the array contains an invalid number. + * @throws JSONException If the array contains an invalid number. */ public String join(String separator) throws JSONException { int len = this.length(); if (len == 0) { return ""; } - + StringBuilder sb = new StringBuilder( - JSONObject.valueToString(this.myArrayList.get(0))); + JSONObject.valueToString(this.myArrayList.get(0))); for (int i = 1; i < len; i++) { sb.append(separator) - .append(JSONObject.valueToString(this.myArrayList.get(i))); + .append(JSONObject.valueToString(this.myArrayList.get(i))); } return sb.toString(); } @@ -527,8 +522,7 @@ public class JSONArray implements Iterable { /** * Get the optional object value associated with an index. * - * @param index - * The index must be between 0 and length() - 1. If not, null is returned. + * @param index The index must be between 0 and length() - 1. If not, null is returned. * @return An object value, or null if there is no object at that index. */ public Object opt(int index) { @@ -541,8 +535,7 @@ public class JSONArray implements Iterable { * if there is no value at that index, or if the value is not Boolean.TRUE * or the String "true". * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The truth. */ public boolean optBoolean(int index) { @@ -554,10 +547,8 @@ public class JSONArray implements Iterable { * defaultValue if there is no value at that index or if it is not a Boolean * or the String "true" or "false" (case insensitive). * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * A boolean default. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue A boolean default. * @return The truth. */ public boolean optBoolean(int index, boolean defaultValue) { @@ -573,8 +564,7 @@ public class JSONArray implements Iterable { * if there is no value for the index, or if the value is not a number and * cannot be converted to a number. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The value. */ public double optDouble(int index) { @@ -586,10 +576,8 @@ public class JSONArray implements Iterable { * is returned if there is no value for the index, or if the value is not a * number and cannot be converted to a number. * - * @param index - * subscript - * @param defaultValue - * The default value. + * @param index subscript + * @param defaultValue The default value. * @return The value. */ public double optDouble(int index, double defaultValue) { @@ -609,8 +597,7 @@ public class JSONArray implements Iterable { * if there is no value for the index, or if the value is not a number and * cannot be converted to a number. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The value. */ public float optFloat(int index) { @@ -622,10 +609,8 @@ public class JSONArray implements Iterable { * is returned if there is no value for the index, or if the value is not a * number and cannot be converted to a number. * - * @param index - * subscript - * @param defaultValue - * The default value. + * @param index subscript + * @param defaultValue The default value. * @return The value. */ public float optFloat(int index, float defaultValue) { @@ -645,8 +630,7 @@ public class JSONArray implements Iterable { * there is no value for the index, or if the value is not a number and * cannot be converted to a number. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The value. */ public int optInt(int index) { @@ -658,10 +642,8 @@ public class JSONArray implements Iterable { * returned if there is no value for the index, or if the value is not a * number and cannot be converted to a number. * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. * @return The value. */ public int optInt(int index, int defaultValue) { @@ -674,13 +656,10 @@ public class JSONArray implements Iterable { /** * Get the enum value associated with a key. - * - * @param - * Enum Type - * @param clazz - * The type of enum to retrieve. - * @param index - * The index must be between 0 and length() - 1. + * + * @param Enum Type + * @param clazz The type of enum to retrieve. + * @param index The index must be between 0 and length() - 1. * @return The enum value at the index location or null if not found */ public > E optEnum(Class clazz, int index) { @@ -689,17 +668,13 @@ public class JSONArray implements Iterable { /** * Get the enum value associated with a key. - * - * @param - * Enum Type - * @param clazz - * The type of enum to retrieve. - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default in case the value is not found + * + * @param Enum Type + * @param clazz The type of enum to retrieve. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default in case the value is not found * @return The enum value at the index location or defaultValue if - * the value is not found or cannot be assigned to clazz + * the value is not found or cannot be assigned to clazz */ public > E optEnum(Class clazz, int index, E defaultValue) { try { @@ -722,14 +697,12 @@ public class JSONArray implements Iterable { } /** - * Get the optional BigInteger value associated with an index. The - * defaultValue is returned if there is no value for the index, or if the + * Get the optional BigInteger value associated with an index. The + * defaultValue is returned if there is no value for the index, or if the * value is not a number and cannot be converted to a number. * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. * @return The value. */ public BigInteger optBigInteger(int index, BigInteger defaultValue) { @@ -738,17 +711,15 @@ public class JSONArray implements Iterable { } /** - * Get the optional BigDecimal value associated with an index. The - * defaultValue is returned if there is no value for the index, or if the + * Get the optional BigDecimal value associated with an index. The + * defaultValue is returned if there is no value for the index, or if the * value is not a number and cannot be converted to a number. If the value * is float or double, the the {@link BigDecimal#BigDecimal(double)} * constructor will be used. See notes on the constructor for conversion * issues that may arise. * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. * @return The value. */ public BigDecimal optBigDecimal(int index, BigDecimal defaultValue) { @@ -759,10 +730,9 @@ public class JSONArray implements Iterable { /** * Get the optional JSONArray associated with an index. * - * @param index - * subscript + * @param index subscript * @return A JSONArray value, or null if the index has no value, or if the - * value is not a JSONArray. + * value is not a JSONArray. */ public JSONArray optJSONArray(int index) { Object o = this.opt(index); @@ -774,8 +744,7 @@ public class JSONArray implements Iterable { * the key is not found, or null if the index has no value, or if the value * is not a JSONObject. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return A JSONObject value. */ public JSONObject optJSONObject(int index) { @@ -788,8 +757,7 @@ public class JSONArray implements Iterable { * there is no value for the index, or if the value is not a number and * cannot be converted to a number. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The value. */ public long optLong(int index) { @@ -801,10 +769,8 @@ public class JSONArray implements Iterable { * returned if there is no value for the index, or if the value is not a * number and cannot be converted to a number. * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. * @return The value. */ public long optLong(int index, long defaultValue) { @@ -821,8 +787,7 @@ public class JSONArray implements Iterable { * an attempt will be made to evaluate it as a number ({@link BigDecimal}). This method * would be used in cases where type coercion of the number value is unwanted. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return An object which is the value. */ public Number optNumber(int index) { @@ -835,10 +800,8 @@ public class JSONArray implements Iterable { * an attempt will be made to evaluate it as a number ({@link BigDecimal}). This method * would be used in cases where type coercion of the number value is unwanted. * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default. * @return An object which is the value. */ public Number optNumber(int index, Number defaultValue) { @@ -846,10 +809,10 @@ public class JSONArray implements Iterable { if (JSONObject.NULL.equals(val)) { return defaultValue; } - if (val instanceof Number){ + if (val instanceof Number) { return (Number) val; } - + if (val instanceof String) { try { return JSONObject.stringToNumber((String) val); @@ -865,8 +828,7 @@ public class JSONArray implements Iterable { * empty string if there is no value at that index. If the value is not a * string and is not null, then it is converted to a string. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return A String value. */ public String optString(int index) { @@ -877,10 +839,8 @@ public class JSONArray implements Iterable { * Get the optional string associated with an index. The defaultValue is * returned if the key is not found. * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. * @return A String value. */ public String optString(int index, String defaultValue) { @@ -892,8 +852,7 @@ public class JSONArray implements Iterable { /** * Append a boolean value. This increases the array's length by one. * - * @param value - * A boolean value. + * @param value A boolean value. * @return this. */ public JSONArray put(boolean value) { @@ -904,11 +863,9 @@ public class JSONArray implements Iterable { * Put a value in the JSONArray, where the value will be a JSONArray which * is produced from a Collection. * - * @param value - * A Collection value. + * @param value A Collection value. * @return this. - * @throws JSONException - * If the value is non-finite number. + * @throws JSONException If the value is non-finite number. */ public JSONArray put(Collection value) { return this.put(new JSONArray(value)); @@ -917,24 +874,20 @@ public class JSONArray implements Iterable { /** * Append a double value. This increases the array's length by one. * - * @param value - * A double value. + * @param value A double value. * @return this. - * @throws JSONException - * if the value is not finite. + * @throws JSONException if the value is not finite. */ public JSONArray put(double value) throws JSONException { return this.put(Double.valueOf(value)); } - + /** * Append a float value. This increases the array's length by one. * - * @param value - * A float value. + * @param value A float value. * @return this. - * @throws JSONException - * if the value is not finite. + * @throws JSONException if the value is not finite. */ public JSONArray put(float value) throws JSONException { return this.put(Float.valueOf(value)); @@ -943,8 +896,7 @@ public class JSONArray implements Iterable { /** * Append an int value. This increases the array's length by one. * - * @param value - * An int value. + * @param value An int value. * @return this. */ public JSONArray put(int value) { @@ -954,8 +906,7 @@ public class JSONArray implements Iterable { /** * Append an long value. This increases the array's length by one. * - * @param value - * A long value. + * @param value A long value. * @return this. */ public JSONArray put(long value) { @@ -966,13 +917,10 @@ public class JSONArray implements Iterable { * Put a value in the JSONArray, where the value will be a JSONObject which * is produced from a Map. * - * @param value - * A Map value. + * @param value A Map value. * @return this. - * @throws JSONException - * If a value in the map is non-finite number. - * @throws NullPointerException - * If a key in the map is null + * @throws JSONException If a value in the map is non-finite number. + * @throws NullPointerException If a key in the map is null */ public JSONArray put(Map value) { return this.put(new JSONObject(value)); @@ -981,13 +929,11 @@ public class JSONArray implements Iterable { /** * Append an object value. This increases the array's length by one. * - * @param value - * An object value. The value should be a Boolean, Double, - * Integer, JSONArray, JSONObject, Long, or String, or the - * JSONObject.NULL object. + * @param value An object value. The value should be a Boolean, Double, + * Integer, JSONArray, JSONObject, Long, or String, or the + * JSONObject.NULL object. * @return this. - * @throws JSONException - * If the value is non-finite number. + * @throws JSONException If the value is non-finite number. */ public JSONArray put(Object value) { JSONObject.testValidity(value); @@ -1000,13 +946,10 @@ public class JSONArray implements Iterable { * than the length of the JSONArray, then null elements will be added as * necessary to pad it out. * - * @param index - * The subscript. - * @param value - * A boolean value. + * @param index The subscript. + * @param value A boolean value. * @return this. - * @throws JSONException - * If the index is negative. + * @throws JSONException If the index is negative. */ public JSONArray put(int index, boolean value) throws JSONException { return this.put(index, value ? Boolean.TRUE : Boolean.FALSE); @@ -1016,13 +959,10 @@ public class JSONArray implements Iterable { * Put a value in the JSONArray, where the value will be a JSONArray which * is produced from a Collection. * - * @param index - * The subscript. - * @param value - * A Collection value. + * @param index The subscript. + * @param value A Collection value. * @return this. - * @throws JSONException - * If the index is negative or if the value is non-finite. + * @throws JSONException If the index is negative or if the value is non-finite. */ public JSONArray put(int index, Collection value) throws JSONException { return this.put(index, new JSONArray(value)); @@ -1033,13 +973,10 @@ public class JSONArray implements Iterable { * the JSONArray, then null elements will be added as necessary to pad it * out. * - * @param index - * The subscript. - * @param value - * A double value. + * @param index The subscript. + * @param value A double value. * @return this. - * @throws JSONException - * If the index is negative or if the value is non-finite. + * @throws JSONException If the index is negative or if the value is non-finite. */ public JSONArray put(int index, double value) throws JSONException { return this.put(index, Double.valueOf(value)); @@ -1050,13 +987,10 @@ public class JSONArray implements Iterable { * the JSONArray, then null elements will be added as necessary to pad it * out. * - * @param index - * The subscript. - * @param value - * A float value. + * @param index The subscript. + * @param value A float value. * @return this. - * @throws JSONException - * If the index is negative or if the value is non-finite. + * @throws JSONException If the index is negative or if the value is non-finite. */ public JSONArray put(int index, float value) throws JSONException { return this.put(index, Float.valueOf(value)); @@ -1067,13 +1001,10 @@ public class JSONArray implements Iterable { * the JSONArray, then null elements will be added as necessary to pad it * out. * - * @param index - * The subscript. - * @param value - * An int value. + * @param index The subscript. + * @param value An int value. * @return this. - * @throws JSONException - * If the index is negative. + * @throws JSONException If the index is negative. */ public JSONArray put(int index, int value) throws JSONException { return this.put(index, Integer.valueOf(value)); @@ -1084,13 +1015,10 @@ public class JSONArray implements Iterable { * the JSONArray, then null elements will be added as necessary to pad it * out. * - * @param index - * The subscript. - * @param value - * A long value. + * @param index The subscript. + * @param value A long value. * @return this. - * @throws JSONException - * If the index is negative. + * @throws JSONException If the index is negative. */ public JSONArray put(int index, long value) throws JSONException { return this.put(index, Long.valueOf(value)); @@ -1100,16 +1028,12 @@ public class JSONArray implements Iterable { * Put a value in the JSONArray, where the value will be a JSONObject that * is produced from a Map. * - * @param index - * The subscript. - * @param value - * The Map value. + * @param index The subscript. + * @param value The Map value. * @return this. - * @throws JSONException - * If the index is negative or if the the value is an invalid - * number. - * @throws NullPointerException - * If a key in the map is null + * @throws JSONException If the index is negative or if the the value is an invalid + * number. + * @throws NullPointerException If a key in the map is null */ public JSONArray put(int index, Map value) throws JSONException { this.put(index, new JSONObject(value)); @@ -1121,16 +1045,13 @@ public class JSONArray implements Iterable { * than the length of the JSONArray, then null elements will be added as * necessary to pad it out. * - * @param index - * The subscript. - * @param value - * The value to put into the array. The value should be a - * Boolean, Double, Integer, JSONArray, JSONObject, Long, or - * String, or the JSONObject.NULL object. + * @param index The subscript. + * @param value The value to put into the array. The value should be a + * Boolean, Double, Integer, JSONArray, JSONObject, Long, or + * String, or the JSONObject.NULL object. * @return this. - * @throws JSONException - * If the index is negative or if the the value is an invalid - * number. + * @throws JSONException If the index is negative or if the the value is an invalid + * number. */ public JSONArray put(int index, Object value) throws JSONException { if (index < 0) { @@ -1141,7 +1062,7 @@ public class JSONArray implements Iterable { this.myArrayList.set(index, value); return this; } - if(index == this.length()){ + if (index == this.length()) { // simple append return this.put(value); } @@ -1154,9 +1075,9 @@ public class JSONArray implements Iterable { } return this.put(value); } - + /** - * Creates a JSONPointer using an initialization string and tries to + * Creates a JSONPointer using an initialization string and tries to * match it to an item within this JSONArray. For example, given a * JSONArray initialized with this document: *
@@ -1164,7 +1085,7 @@ public class JSONArray implements Iterable {
      *     {"b":"c"}
      * ]
      * 
-     * and this JSONPointer string: 
+     * and this JSONPointer string:
      * 
      * "/0/b"
      * 
@@ -1177,9 +1098,9 @@ public class JSONArray implements Iterable { public Object query(String jsonPointer) { return query(new JSONPointer(jsonPointer)); } - + /** - * Uses a user initialized JSONPointer and tries to + * Uses a user initialized JSONPointer and tries to * match it to an item within this JSONArray. For example, given a * JSONArray initialized with this document: *
@@ -1187,7 +1108,7 @@ public class JSONArray implements Iterable {
      *     {"b":"c"}
      * ]
      * 
-     * and this JSONPointer: 
+     * and this JSONPointer:
      * 
      * "/0/b"
      * 
@@ -1200,23 +1121,23 @@ public class JSONArray implements Iterable { public Object query(JSONPointer jsonPointer) { return jsonPointer.queryFrom(this); } - + /** * Queries and returns a value from this object using {@code jsonPointer}, or * returns null if the query fails due to a missing key. - * + * * @param jsonPointer the string representation of the JSON pointer * @return the queried value or {@code null} * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax */ public Object optQuery(String jsonPointer) { - return optQuery(new JSONPointer(jsonPointer)); + return optQuery(new JSONPointer(jsonPointer)); } - + /** * Queries and returns a value from this object using {@code jsonPointer}, or * returns null if the query fails due to a missing key. - * + * * @param jsonPointer The JSON pointer * @return the queried value or {@code null} * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax @@ -1232,15 +1153,14 @@ public class JSONArray implements Iterable { /** * Remove an index and close the hole. * - * @param index - * The index of the element to be removed. + * @param index The index of the element to be removed. * @return The value that was associated with the index, or null if there - * was no value. + * was no value. */ public Object remove(int index) { return index >= 0 && index < this.length() - ? this.myArrayList.remove(index) - : null; + ? this.myArrayList.remove(index) + : null; } /** @@ -1255,24 +1175,24 @@ public class JSONArray implements Iterable { return false; } int len = this.length(); - if (len != ((JSONArray)other).length()) { + if (len != ((JSONArray) other).length()) { return false; } for (int i = 0; i < len; i += 1) { Object valueThis = this.myArrayList.get(i); - Object valueOther = ((JSONArray)other).myArrayList.get(i); - if(valueThis == valueOther) { - continue; + Object valueOther = ((JSONArray) other).myArrayList.get(i); + if (valueThis == valueOther) { + continue; } - if(valueThis == null) { - return false; + if (valueThis == null) { + return false; } if (valueThis instanceof JSONObject) { - if (!((JSONObject)valueThis).similar(valueOther)) { + if (!((JSONObject) valueThis).similar(valueOther)) { return false; } } else if (valueThis instanceof JSONArray) { - if (!((JSONArray)valueThis).similar(valueOther)) { + if (!((JSONArray) valueThis).similar(valueOther)) { return false; } } else if (!valueThis.equals(valueOther)) { @@ -1286,13 +1206,11 @@ public class JSONArray implements Iterable { * Produce a JSONObject by combining a JSONArray of names with the values of * this JSONArray. * - * @param names - * A JSONArray containing a list of key strings. These will be - * paired with the values. + * @param names A JSONArray containing a list of key strings. These will be + * paired with the values. * @return A JSONObject, or null if there are no names or if this JSONArray - * has no values. - * @throws JSONException - * If any of the names are null. + * has no values. + * @throws JSONException If any of the names are null. */ public JSONObject toJSONObject(JSONArray names) throws JSONException { if (names == null || names.isEmpty() || this.isEmpty()) { @@ -1315,7 +1233,7 @@ public class JSONArray implements Iterable { * * * @return a printable, displayable, transmittable representation of the - * array. + * array. */ @Override public String toString() { @@ -1328,11 +1246,11 @@ public class JSONArray implements Iterable { /** * Make a pretty-printed JSON text of this JSONArray. - * + * *

If indentFactor > 0 and the {@link JSONArray} has only * one element, then the array will be output on a single line: *

{@code [1]}
- * + * *

If an array has 2 or more elements, then it will be output across * multiple lines:

{@code
      * [
@@ -1344,13 +1262,12 @@ public class JSONArray implements Iterable {
      * 

* Warning: This method assumes that the data structure is acyclical. * - * - * @param indentFactor - * The number of spaces to add to each level of indentation. + * + * @param indentFactor The number of spaces to add to each level of indentation. * @return a printable, displayable, transmittable representation of the - * object, beginning with [ (left - * bracket) and ending with ] - *  (right bracket). + * object, beginning with [ (left + * bracket) and ending with ] + *  (right bracket). * @throws JSONException */ public String toString(int indentFactor) throws JSONException { @@ -1365,7 +1282,7 @@ public class JSONArray implements Iterable { * compactness, no whitespace is added. *

* Warning: This method assumes that the data structure is acyclical. - * + * * * @return The writer. * @throws JSONException @@ -1376,11 +1293,11 @@ public class JSONArray implements Iterable { /** * Write the contents of the JSONArray as JSON text to a writer. - * + * *

If indentFactor > 0 and the {@link JSONArray} has only * one element, then the array will be output on a single line: *

{@code [1]}
- * + * *

If an array has 2 or more elements, then it will be output across * multiple lines:

{@code
      * [
@@ -1393,12 +1310,9 @@ public class JSONArray implements Iterable {
      * Warning: This method assumes that the data structure is acyclical.
      * 
      *
-     * @param writer
-     *            Writes the serialized JSON
-     * @param indentFactor
-     *            The number of spaces to add to each level of indentation.
-     * @param indent
-     *            The indentation of the top level.
+     * @param writer       Writes the serialized JSON
+     * @param indentFactor The number of spaces to add to each level of indentation.
+     * @param indent       The indentation of the top level.
      * @return The writer.
      * @throws JSONException
      */
@@ -1480,38 +1394,5 @@ public class JSONArray implements Iterable {
     public boolean isEmpty() {
         return this.myArrayList.isEmpty();
     }
-    
-    /**
-     * Create a new JSONException in a common format for incorrect conversions.
-     * @param idx index of the item
-     * @param valueType the type of value being coerced to
-     * @param cause optional cause of the coercion failure
-     * @return JSONException that can be thrown.
-     */
-    private static JSONException wrongValueFormatException(
-            int idx,
-            String valueType,
-            Throwable cause) {
-        return new JSONException(
-                "JSONArray[" + idx + "] is not a " + valueType + "."
-                , cause);
-    }
-    
-    /**
-     * Create a new JSONException in a common format for incorrect conversions.
-     * @param idx index of the item
-     * @param valueType the type of value being coerced to
-     * @param cause optional cause of the coercion failure
-     * @return JSONException that can be thrown.
-     */
-    private static JSONException wrongValueFormatException(
-            int idx,
-            String valueType,
-            Object value,
-            Throwable cause) {
-        return new JSONException(
-                "JSONArray[" + idx + "] is not a " + valueType + " (" + value + ")."
-                , cause);
-    }
 
 }
diff --git a/src/main/java/json/JSONException.java b/src/main/java/json/JSONException.java
index 60998ff..ea763f6 100644
--- a/src/main/java/json/JSONException.java
+++ b/src/main/java/json/JSONException.java
@@ -7,14 +7,15 @@ package json;
  * @version 2015-12-09
  */
 public class JSONException extends RuntimeException {
-    /** Serialization ID */
+    /**
+     * Serialization ID
+     */
     private static final long serialVersionUID = 0;
 
     /**
      * Constructs a JSONException with an explanatory message.
      *
-     * @param message
-     *            Detail about the reason for the exception.
+     * @param message Detail about the reason for the exception.
      */
     public JSONException(final String message) {
         super(message);
@@ -22,11 +23,9 @@ public class JSONException extends RuntimeException {
 
     /**
      * Constructs a JSONException with an explanatory message and cause.
-     * 
-     * @param message
-     *            Detail about the reason for the exception.
-     * @param cause
-     *            The cause.
+     *
+     * @param message Detail about the reason for the exception.
+     * @param cause   The cause.
      */
     public JSONException(final String message, final Throwable cause) {
         super(message, cause);
@@ -34,9 +33,8 @@ public class JSONException extends RuntimeException {
 
     /**
      * Constructs a new JSONException with the specified cause.
-     * 
-     * @param cause
-     *            The cause.
+     *
+     * @param cause The cause.
      */
     public JSONException(final Throwable cause) {
         super(cause.getMessage(), cause);
diff --git a/src/main/java/json/JSONObject.java b/src/main/java/json/JSONObject.java
index 300d9fa..9a07ac9 100644
--- a/src/main/java/json/JSONObject.java
+++ b/src/main/java/json/JSONObject.java
@@ -70,7 +70,7 @@ import java.util.regex.Pattern;
  * myString = new JSONObject()
  *         .put("JSON", "Hello, World!").toString();
  * 
- *
+ * 

* produces the string {"JSON": "Hello, World"}. *

* The texts produced by the toString methods strictly conform to @@ -94,59 +94,15 @@ import java.util.regex.Pattern; */ public class JSONObject { /** - * JSONObject.NULL is equivalent to the value that JavaScript calls null, - * whilst Java's null is equivalent to the value that JavaScript calls - * undefined. + * It is sometimes more convenient and less ambiguous to have a + * NULL object than to use Java's null value. + * JSONObject.NULL.equals(null) returns true. + * JSONObject.NULL.toString() returns "null". */ - private static final class Null { - - /** - * There is only intended to be a single instance of the NULL object, - * so the clone method returns itself. - * - * @return NULL. - */ - @Override - protected final Object clone() { - return this; - } - - /** - * A Null object is equal to the null value and to itself. - * - * @param object - * An object to test for nullness. - * @return true if the object parameter is the JSONObject.NULL object or - * null. - */ - @Override - public boolean equals(Object object) { - return object == null || object == this; - } - /** - * A Null object is equal to the null value and to itself. - * - * @return always returns 0. - */ - @Override - public int hashCode() { - return 0; - } - - /** - * Get the "null" string value. - * - * @return The string "null". - */ - @Override - public String toString() { - return "null"; - } - } - + public static final Object NULL = new Null(); /** - * Regular Expression Pattern that matches JSON Numbers. This is primarily used for - * output to guarantee that we are always writing valid JSON. + * Regular Expression Pattern that matches JSON Numbers. This is primarily used for + * output to guarantee that we are always writing valid JSON. */ static final Pattern NUMBER_PATTERN = Pattern.compile("-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?"); @@ -155,22 +111,14 @@ public class JSONObject { */ private final Map map; - /** - * It is sometimes more convenient and less ambiguous to have a - * NULL object than to use Java's null value. - * JSONObject.NULL.equals(null) returns true. - * JSONObject.NULL.toString() returns "null". - */ - public static final Object NULL = new Null(); - /** * Construct an empty JSONObject. */ public JSONObject() { - // HashMap is used on purpose to ensure that elements are unordered by + // HashMap is used on purpose to ensure that elements are unordered by // the specification. - // JSON tends to be a portable transfer format to allows the container - // implementations to rearrange their items for a faster element + // JSON tends to be a portable transfer format to allows the container + // implementations to rearrange their items for a faster element // retrieval based on associative access. // Therefore, an implementation mustn't rely on the order of the item. this.map = new HashMap(); @@ -181,12 +129,10 @@ public class JSONObject { * strings is used to identify the keys that should be copied. Missing keys * are ignored. * - * @param jo - * A JSONObject. - * @param names - * An array of strings. + * @param jo A JSONObject. + * @param names An array of strings. */ - public JSONObject(JSONObject jo, String ... names) { + public JSONObject(JSONObject jo, String... names) { this(names.length); for (int i = 0; i < names.length; i += 1) { try { @@ -199,11 +145,9 @@ public class JSONObject { /** * Construct a JSONObject from a JSONTokener. * - * @param x - * A JSONTokener object containing the source string. - * @throws JSONException - * If there is a syntax error in the source string or a - * duplicated key. + * @param x A JSONTokener object containing the source string. + * @throws JSONException If there is a syntax error in the source string or a + * duplicated key. */ public JSONObject(JSONTokener x) throws JSONException { this(); @@ -213,16 +157,16 @@ public class JSONObject { if (x.nextClean() != '{') { throw x.syntaxError("A JSONObject text must begin with '{'"); } - for (;;) { + 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(); + 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 ':'. @@ -231,9 +175,9 @@ public class JSONObject { if (c != ':') { throw x.syntaxError("Expected a ':' after a key"); } - + // Use syntaxError(..) to include error location - + if (key != null) { // Check if key exists if (this.opt(key) != null) { @@ -242,7 +186,7 @@ public class JSONObject { } // Only add value if non-null Object value = x.nextValue(); - if (value!=null) { + if (value != null) { this.put(key, value); } } @@ -250,17 +194,17 @@ public class JSONObject { // Pairs are separated by ','. switch (x.nextClean()) { - case ';': - case ',': - if (x.nextClean() == '}') { + case ';': + case ',': + if (x.nextClean() == '}') { + return; + } + x.back(); + break; + case '}': return; - } - x.back(); - break; - case '}': - return; - default: - throw x.syntaxError("Expected a ',' or '}'"); + default: + throw x.syntaxError("Expected a ',' or '}'"); } } } @@ -268,23 +212,20 @@ public class JSONObject { /** * Construct a JSONObject from a Map. * - * @param m - * A map object that can be used to initialize the contents of - * the JSONObject. - * @throws JSONException - * If a value in the map is non-finite number. - * @throws NullPointerException - * If a key in the map is null + * @param m A map object that can be used to initialize the contents of + * the JSONObject. + * @throws JSONException If a value in the map is non-finite number. + * @throws NullPointerException If a key in the map is null */ public JSONObject(Map m) { if (m == null) { this.map = new HashMap(); } else { this.map = new HashMap(m.size()); - for (final Entry e : m.entrySet()) { - if(e.getKey() == null) { - throw new NullPointerException("Null key."); - } + for (final Entry e : m.entrySet()) { + if (e.getKey() == null) { + throw new NullPointerException("Null key."); + } final Object value = e.getValue(); if (value != null) { this.map.put(String.valueOf(e.getKey()), wrap(value)); @@ -342,14 +283,13 @@ public class JSONObject { * method from being serialized: *

      * @JSONPropertyName("FullName")
-     * @JSONPropertyIgnore 
+     * @JSONPropertyIgnore
      * public String getName() { return this.name; }
      * 
*

- * - * @param bean - * An object that has getter methods that should be used to make - * a JSONObject. + * + * @param bean An object that has getter methods that should be used to make + * a JSONObject. */ public JSONObject(Object bean) { this(); @@ -363,14 +303,12 @@ public class JSONObject { * those keys in the object. If a key is not found or not visible, then it * will not be copied into the new JSONObject. * - * @param object - * An object that has fields that should be used to make a - * JSONObject. - * @param names - * An array of strings, the names of the fields to be obtained - * from the object. + * @param object An object that has fields that should be used to make a + * JSONObject. + * @param names An array of strings, the names of the fields to be obtained + * from the object. */ - public JSONObject(Object object, String ... names) { + public JSONObject(Object object, String... names) { this(names.length); Class c = object.getClass(); for (int i = 0; i < names.length; i += 1) { @@ -386,13 +324,11 @@ public class JSONObject { * Construct a JSONObject from a source JSON text string. This is the most * commonly used JSONObject constructor. * - * @param source - * A string beginning with { (left - * brace) and ending with } - *  (right brace). - * @exception JSONException - * If there is a syntax error in the source string or a - * duplicated key. + * @param source A string beginning with { (left + * brace) and ending with } + *  (right brace). + * @throws JSONException If there is a syntax error in the source string or a + * duplicated key. */ public JSONObject(String source) throws JSONException { this(new JSONTokener(source)); @@ -401,12 +337,9 @@ public class JSONObject { /** * Construct a JSONObject from a ResourceBundle. * - * @param baseName - * The ResourceBundle base name. - * @param locale - * The Locale to load the ResourceBundle for. - * @throws JSONException - * If any JSONExceptions are detected. + * @param baseName The ResourceBundle base name. + * @param locale The Locale to load the ResourceBundle for. + * @throws JSONException If any JSONExceptions are detected. */ public JSONObject(String baseName, Locale locale) throws JSONException { this(); @@ -440,90 +373,23 @@ public class JSONObject { } } } - + /** - * Constructor to specify an initial capacity of the internal map. Useful for library + * Constructor to specify an initial capacity of the internal map. Useful for library * internal calls where we know, or at least can best guess, how big this JSONObject * will be. - * + * * @param initialCapacity initial capacity of the internal map. */ - protected JSONObject(int initialCapacity){ + protected JSONObject(int initialCapacity) { this.map = new HashMap(initialCapacity); } - /** - * Accumulate values under a key. It is similar to the put method except - * that if there is already an object stored under the key then a JSONArray - * is stored under the key to hold all of the accumulated values. If there - * is already a JSONArray, then the new value is appended to it. In - * contrast, the put method replaces the previous value. - * - * If only one value is accumulated that is not a JSONArray, then the result - * will be the same as using put. But if multiple values are accumulated, - * then the result will be like append. - * - * @param key - * A key string. - * @param value - * An object to be accumulated under the key. - * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject accumulate(String key, Object value) throws JSONException { - testValidity(value); - 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; - } - - /** - * Append values to the array under a key. If the key does not exist in the - * JSONObject, then the key is put in the JSONObject with its value being a - * JSONArray containing the value parameter. If the key was already - * associated with a JSONArray, then the value parameter is appended to it. - * - * @param key - * A key string. - * @param value - * An object to be accumulated under the key. - * @return this. - * @throws JSONException - * If the value is non-finite number or if the current value associated with - * the key is not a JSONArray. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject append(String key, Object value) throws JSONException { - testValidity(value); - 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 wrongValueFormatException(key, "JSONArray", null, null); - } - return this; - } - /** * Produce a string from a double. The string "null" will be returned if the * number is not finite. * - * @param d - * A double. + * @param d A double. * @return A String. */ public static String doubleToString(double d) { @@ -546,275 +412,10 @@ public class JSONObject { return string; } - /** - * Get the value object associated with a key. - * - * @param key - * A key string. - * @return The object associated with the key. - * @throws JSONException - * if the key is not found. - */ - public Object get(String key) throws JSONException { - if (key == null) { - throw new JSONException("Null key."); - } - Object object = this.opt(key); - if (object == null) { - throw new JSONException("JSONObject[" + quote(key) + "] not found."); - } - return object; - } - - /** - * Get the enum value associated with a key. - * - * @param - * Enum Type - * @param clazz - * The type of enum to retrieve. - * @param key - * A key string. - * @return The enum value associated with the key - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to an enum. - */ - public > E getEnum(Class clazz, String key) throws JSONException { - E val = optEnum(clazz, key); - if(val==null) { - // JSONException should really take a throwable argument. - // If it did, I would re-implement this with the Enum.valueOf - // method and place any thrown exception in the JSONException - throw wrongValueFormatException(key, "enum of type " + quote(clazz.getSimpleName()), null); - } - return val; - } - - /** - * Get the boolean value associated with a key. - * - * @param key - * A key string. - * @return The truth. - * @throws JSONException - * if the value is not a Boolean or the String "true" or - * "false". - */ - public boolean getBoolean(String key) throws JSONException { - 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 wrongValueFormatException(key, "Boolean", null); - } - - /** - * Get the BigInteger value associated with a key. - * - * @param key - * A key string. - * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value cannot - * be converted to BigInteger. - */ - public BigInteger getBigInteger(String key) throws JSONException { - Object object = this.get(key); - BigInteger ret = objectToBigInteger(object, null); - if (ret != null) { - return ret; - } - throw wrongValueFormatException(key, "BigInteger", object, null); - } - - /** - * Get the BigDecimal value associated with a key. If the value is float or - * double, the the {@link BigDecimal#BigDecimal(double)} constructor will - * be used. See notes on the constructor for conversion issues that may - * arise. - * - * @param key - * A key string. - * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value - * cannot be converted to BigDecimal. - */ - public BigDecimal getBigDecimal(String key) throws JSONException { - Object object = this.get(key); - BigDecimal ret = objectToBigDecimal(object, null); - if (ret != null) { - return ret; - } - throw wrongValueFormatException(key, "BigDecimal", object, null); - } - - /** - * Get the double value associated with a key. - * - * @param key - * A key string. - * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value is not a Number - * object and cannot be converted to a number. - */ - public double getDouble(String key) throws JSONException { - final Object object = this.get(key); - if(object instanceof Number) { - return ((Number)object).doubleValue(); - } - try { - return Double.parseDouble(object.toString()); - } catch (Exception e) { - throw wrongValueFormatException(key, "double", e); - } - } - - /** - * Get the float value associated with a key. - * - * @param key - * A key string. - * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value is not a Number - * object and cannot be converted to a number. - */ - public float getFloat(String key) throws JSONException { - final Object object = this.get(key); - if(object instanceof Number) { - return ((Number)object).floatValue(); - } - try { - return Float.parseFloat(object.toString()); - } catch (Exception e) { - throw wrongValueFormatException(key, "float", e); - } - } - - /** - * Get the Number value associated with a key. - * - * @param key - * A key string. - * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value is not a Number - * object and cannot be converted to a number. - */ - public Number getNumber(String key) throws JSONException { - Object object = this.get(key); - try { - if (object instanceof Number) { - return (Number)object; - } - return stringToNumber(object.toString()); - } catch (Exception e) { - throw wrongValueFormatException(key, "number", e); - } - } - - /** - * Get the int value associated with a key. - * - * @param key - * A key string. - * @return The integer value. - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to an integer. - */ - public int getInt(String key) throws JSONException { - final Object object = this.get(key); - if(object instanceof Number) { - return ((Number)object).intValue(); - } - try { - return Integer.parseInt(object.toString()); - } catch (Exception e) { - throw wrongValueFormatException(key, "int", e); - } - } - - /** - * Get the JSONArray value associated with a key. - * - * @param key - * A key string. - * @return A JSONArray which is the value. - * @throws JSONException - * if the key is not found or if the value is not a JSONArray. - */ - public JSONArray getJSONArray(String key) throws JSONException { - Object object = this.get(key); - if (object instanceof JSONArray) { - return (JSONArray) object; - } - throw wrongValueFormatException(key, "JSONArray", null); - } - - /** - * Get the JSONObject value associated with a key. - * - * @param key - * A key string. - * @return A JSONObject which is the value. - * @throws JSONException - * if the key is not found or if the value is not a JSONObject. - */ - public JSONObject getJSONObject(String key) throws JSONException { - Object object = this.get(key); - if (object instanceof JSONObject) { - return (JSONObject) object; - } - throw wrongValueFormatException(key, "JSONObject", null); - } - - /** - * Get the long value associated with a key. - * - * @param key - * A key string. - * @return The long value. - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to a long. - */ - public long getLong(String key) throws JSONException { - final Object object = this.get(key); - if(object instanceof Number) { - return ((Number)object).longValue(); - } - try { - return Long.parseLong(object.toString()); - } catch (Exception e) { - throw wrongValueFormatException(key, "long", e); - } - } - - public UUID getUUID(String key) throws JSONException { - Object object = this.get(key); - if (object instanceof UUID) { - return (UUID) object; - } else if (object instanceof String) { - return UUID.fromString(String.valueOf(object)); - } - throw wrongValueFormatException(key, "UUID", null); - } - /** * Get an array of field names from a JSONObject. * - * @param jo - * JSON object + * @param jo JSON object * @return An array of field names, or null if there are no names. */ public static String[] getNames(JSONObject jo) { @@ -827,8 +428,7 @@ public class JSONObject { /** * Get an array of public field names from an Object. * - * @param object - * object to read + * @param object object to read * @return An array of field names, or null if there are no names. */ public static String[] getNames(Object object) { @@ -848,188 +448,12 @@ public class JSONObject { return names; } - /** - * Get the string associated with a key. - * - * @param key - * A key string. - * @return A string which is the value. - * @throws JSONException - * if there is no string value for the key. - */ - public String getString(String key) throws JSONException { - Object object = this.get(key); - if (object instanceof String) { - return (String) object; - } - throw wrongValueFormatException(key, "string", null); - } - - public byte getByte(String key) throws JSONException { - Object object = this.get(key); - if (object instanceof Byte) { - return (byte) object; - } - throw wrongValueFormatException(key, "byte", null); - } - - public byte[] getByteArray(String key) throws JSONException { - Object object = this.get(key); - if (object instanceof JSONArray) { - JSONArray jsonArray = (JSONArray) object; - byte[] array = new byte[jsonArray.length()]; - for (int k = 0; k < jsonArray.length(); k++) { - array[k] = Byte.valueOf(String.valueOf(jsonArray.get(k))); - } - return array; - } - if (object instanceof byte[]) { - return (byte[]) object; - } - throw wrongValueFormatException(key, "byteArray", null); - } - - /** - * Determine if the JSONObject contains a specific key. - * - * @param key - * A key string. - * @return true if the key exists in the JSONObject. - */ - public boolean has(String key) { - return this.map.containsKey(key); - } - - /** - * Increment a property of a JSONObject. If there is no such property, - * create one with a value of 1 (Integer). If there is such a property, and if it is - * an Integer, Long, Double, Float, BigInteger, or BigDecimal then add one to it. - * No overflow bounds checking is performed, so callers should initialize the key - * prior to this call with an appropriate type that can handle the maximum expected - * value. - * - * @param key - * A key string. - * @return this. - * @throws JSONException - * If there is already a property with this name that is not an - * Integer, Long, Double, or Float. - */ - public JSONObject increment(String key) throws JSONException { - 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() + 1L); - } else if (value instanceof BigInteger) { - this.put(key, ((BigInteger)value).add(BigInteger.ONE)); - } else if (value instanceof Float) { - this.put(key, ((Float) value).floatValue() + 1.0f); - } else if (value instanceof Double) { - this.put(key, ((Double) value).doubleValue() + 1.0d); - } else if (value instanceof BigDecimal) { - this.put(key, ((BigDecimal)value).add(BigDecimal.ONE)); - } else { - throw new JSONException("Unable to increment [" + quote(key) + "]."); - } - return this; - } - - /** - * Determine if the value associated with the key is null or if there is no - * value. - * - * @param key - * A key string. - * @return true if there is no value associated with the key or if the value - * is the JSONObject.NULL object. - */ - public boolean isNull(String key) { - return JSONObject.NULL.equals(this.opt(key)); - } - - /** - * Get an enumeration of the keys of the JSONObject. Modifying this key Set will also - * modify the JSONObject. Use with caution. - * - * @see Set#iterator() - * - * @return An iterator of the keys. - */ - public Iterator keys() { - return this.keySet().iterator(); - } - - /** - * Get a set of keys of the JSONObject. Modifying this key Set will also modify the - * JSONObject. Use with caution. - * - * @see Map#keySet() - * - * @return A keySet. - */ - public Set keySet() { - return this.map.keySet(); - } - - /** - * Get a set of entries of the JSONObject. These are raw values and may not - * match what is returned by the JSONObject get* and opt* functions. Modifying - * the returned EntrySet or the Entry objects contained therein will modify the - * backing JSONObject. This does not return a clone or a read-only view. - * - * Use with caution. - * - * @see Map#entrySet() - * - * @return An Entry Set - */ - protected Set> entrySet() { - return this.map.entrySet(); - } - - /** - * Get the number of keys stored in the JSONObject. - * - * @return The number of keys in the JSONObject. - */ - public int length() { - return this.map.size(); - } - - /** - * Check if JSONObject is empty. - * - * @return true if JSONObject is empty, otherwise false. - */ - public boolean isEmpty() { - return this.map.isEmpty(); - } - - /** - * Produce a JSONArray containing the names of the elements of this - * JSONObject. - * - * @return A JSONArray containing the key strings, or null if the JSONObject - * is empty. - */ - public JSONArray names() { - if(this.map.isEmpty()) { - return null; - } - return new JSONArray(this.map.keySet()); - } - /** * Produce a string from a Number. * - * @param number - * A Number + * @param number A Number * @return A String. - * @throws JSONException - * If n is a non-finite number. + * @throws JSONException If n is a non-finite number. */ public static String numberToString(Number number) throws JSONException { if (number == null) { @@ -1053,148 +477,30 @@ public class JSONObject { } /** - * Get an optional value associated with a key. - * - * @param key - * A key string. - * @return An object which is the value, or null if there is no value. - */ - public Object opt(String key) { - return key == null ? null : this.map.get(key); - } - - /** - * Get the enum value associated with a key. - * - * @param - * Enum Type - * @param clazz - * The type of enum to retrieve. - * @param key - * A key string. - * @return The enum value associated with the key or null if not found - */ - public > E optEnum(Class clazz, String key) { - return this.optEnum(clazz, key, null); - } - - /** - * Get the enum value associated with a key. - * - * @param - * Enum Type - * @param clazz - * The type of enum to retrieve. - * @param key - * A key string. - * @param defaultValue - * The default in case the value is not found - * @return The enum value associated with the key or defaultValue - * if the value is not found or cannot be assigned to clazz - */ - public > E optEnum(Class clazz, String key, E defaultValue) { - try { - Object val = this.opt(key); - if (NULL.equals(val)) { - return defaultValue; - } - if (clazz.isAssignableFrom(val.getClass())) { - // we just checked it! - @SuppressWarnings("unchecked") - E myE = (E) val; - return myE; - } - return Enum.valueOf(clazz, val.toString()); - } catch (IllegalArgumentException e) { - return defaultValue; - } catch (NullPointerException e) { - return defaultValue; - } - } - - /** - * Get an optional boolean associated with a key. It returns false if there - * is no such key, or if the value is not Boolean.TRUE or the String "true". - * - * @param key - * A key string. - * @return The truth. - */ - public boolean optBoolean(String key) { - return this.optBoolean(key, false); - } - - /** - * Get an optional boolean associated with a key. It returns the - * defaultValue if there is no such key, or if it is not a Boolean or the - * String "true" or "false" (case insensitive). - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return The truth. - */ - public boolean optBoolean(String key, boolean defaultValue) { - Object val = this.opt(key); - if (NULL.equals(val)) { - return defaultValue; - } - if (val instanceof Boolean){ - return ((Boolean) val).booleanValue(); - } - try { - // we'll use the get anyway because it does string conversion. - return this.getBoolean(key); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * Get an optional BigDecimal associated with a key, or the defaultValue if - * there is no such key or if its value is not a number. If the value is a - * string, an attempt will be made to evaluate it as a number. If the value - * is float or double, then the {@link BigDecimal#BigDecimal(double)} - * constructor will be used. See notes on the constructor for conversion - * issues that may arise. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) { - Object val = this.opt(key); - return objectToBigDecimal(val, defaultValue); - } - - /** - * @param val value to convert + * @param val value to convert * @param defaultValue default value to return is the conversion doesn't work or is null. * @return BigDecimal conversion of the original value, or the defaultValue if unable - * to convert. + * to convert. */ static BigDecimal objectToBigDecimal(Object val, BigDecimal defaultValue) { if (NULL.equals(val)) { return defaultValue; } - if (val instanceof BigDecimal){ + if (val instanceof BigDecimal) { return (BigDecimal) val; } - if (val instanceof BigInteger){ + if (val instanceof BigInteger) { return new BigDecimal((BigInteger) val); } - if (val instanceof Double || val instanceof Float){ + if (val instanceof Double || val instanceof Float) { final double d = ((Number) val).doubleValue(); - if(Double.isNaN(d)) { + if (Double.isNaN(d)) { return defaultValue; } return new BigDecimal(((Number) val).doubleValue()); } if (val instanceof Long || val instanceof Integer - || val instanceof Short || val instanceof Byte){ + || val instanceof Short || val instanceof Byte) { return new BigDecimal(((Number) val).longValue()); } // don't check if it's a string in case of unchecked Number subclasses @@ -1206,57 +512,41 @@ public class JSONObject { } /** - * Get an optional BigInteger associated with a key, or the defaultValue if - * there is no such key or if its value is not a number. If the value is a - * string, an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public BigInteger optBigInteger(String key, BigInteger defaultValue) { - Object val = this.opt(key); - return objectToBigInteger(val, defaultValue); - } - - /** - * @param val value to convert + * @param val value to convert * @param defaultValue default value to return is the conversion doesn't work or is null. * @return BigInteger conversion of the original value, or the defaultValue if unable - * to convert. + * to convert. */ static BigInteger objectToBigInteger(Object val, BigInteger defaultValue) { if (NULL.equals(val)) { return defaultValue; } - if (val instanceof BigInteger){ + if (val instanceof BigInteger) { return (BigInteger) val; } - if (val instanceof BigDecimal){ + if (val instanceof BigDecimal) { return ((BigDecimal) val).toBigInteger(); } - if (val instanceof Double || val instanceof Float){ + if (val instanceof Double || val instanceof Float) { final double d = ((Number) val).doubleValue(); - if(Double.isNaN(d)) { + if (Double.isNaN(d)) { return defaultValue; } return new BigDecimal(d).toBigInteger(); } if (val instanceof Long || val instanceof Integer - || val instanceof Short || val instanceof Byte){ + || val instanceof Short || val instanceof Byte) { return BigInteger.valueOf(((Number) val).longValue()); } // don't check if it's a string in case of unchecked Number subclasses try { - // the other opt functions handle implicit conversions, i.e. + // the other opt functions handle implicit conversions, i.e. // jo.put("double",1.1d); // jo.optInt("double"); -- will return 1, not an error // this conversion to BigDecimal then to BigInteger is to maintain // that type cast support that may truncate the decimal. final String valStr = val.toString(); - if(isDecimalNotation(valStr)) { + if (isDecimalNotation(valStr)) { return new BigDecimal(valStr).toBigInteger(); } return new BigInteger(valStr); @@ -1265,289 +555,6 @@ public class JSONObject { } } - /** - * Get an optional double associated with a key, or NaN if there is no such - * key or if its value is not a number. If the value is a string, an attempt - * will be made to evaluate it as a number. - * - * @param key - * A string which is the key. - * @return An object which is the value. - */ - public double optDouble(String key) { - return this.optDouble(key, Double.NaN); - } - - /** - * Get an optional double associated with a key, or the defaultValue if - * there is no such key or if its value is not a number. If the value is a - * string, an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public double optDouble(String key, double defaultValue) { - Number val = this.optNumber(key); - if (val == null) { - return defaultValue; - } - final double doubleValue = val.doubleValue(); - // if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) { - // return defaultValue; - // } - return doubleValue; - } - - /** - * Get the optional double value associated with an index. NaN is returned - * if there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param key - * A key string. - * @return The value. - */ - public float optFloat(String key) { - return this.optFloat(key, Float.NaN); - } - - /** - * Get the optional double value associated with an index. The defaultValue - * is returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param key - * A key string. - * @param defaultValue - * The default value. - * @return The value. - */ - public float optFloat(String key, float defaultValue) { - Number val = this.optNumber(key); - if (val == null) { - return defaultValue; - } - final float floatValue = val.floatValue(); - // if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) { - // return defaultValue; - // } - return floatValue; - } - - /** - * Get an optional int value associated with a key, or zero if there is no - * such key or if the value is not a number. If the value is a string, an - * attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @return An object which is the value. - */ - public int optInt(String key) { - return this.optInt(key, 0); - } - - /** - * Get an optional int value associated with a key, or the default if there - * is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public int optInt(String key, int defaultValue) { - final Number val = this.optNumber(key, null); - if (val == null) { - return defaultValue; - } - return val.intValue(); - } - - /** - * Get an optional JSONArray associated with a key. It returns null if there - * is no such key, or if its value is not a JSONArray. - * - * @param key - * A key string. - * @return A JSONArray which is the value. - */ - public JSONArray optJSONArray(String key) { - Object o = this.opt(key); - return o instanceof JSONArray ? (JSONArray) o : null; - } - - /** - * Get an optional JSONObject associated with a key. It returns null if - * there is no such key, or if its value is not a JSONObject. - * - * @param key - * A key string. - * @return A JSONObject which is the value. - */ - public JSONObject optJSONObject(String key) { - Object object = this.opt(key); - return object instanceof JSONObject ? (JSONObject) object : null; - } - - /** - * Get an optional long value associated with a key, or zero if there is no - * such key or if the value is not a number. If the value is a string, an - * attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @return An object which is the value. - */ - public long optLong(String key) { - return this.optLong(key, 0); - } - - /** - * Get an optional long value associated with a key, or the default if there - * is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public long optLong(String key, long defaultValue) { - final Number val = this.optNumber(key, null); - if (val == null) { - return defaultValue; - } - - return val.longValue(); - } - - /** - * Get an optional {@link Number} value associated with a key, or null - * if there is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number ({@link BigDecimal}). This method - * would be used in cases where type coercion of the number value is unwanted. - * - * @param key - * A key string. - * @return An object which is the value. - */ - public Number optNumber(String key) { - return this.optNumber(key, null); - } - - /** - * Get an optional {@link Number} value associated with a key, or the default if there - * is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number. This method - * would be used in cases where type coercion of the number value is unwanted. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public Number optNumber(String key, Number defaultValue) { - Object val = this.opt(key); - if (NULL.equals(val)) { - return defaultValue; - } - if (val instanceof Number){ - return (Number) val; - } - - try { - return stringToNumber(val.toString()); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * Get an optional string associated with a key. It returns an empty string - * if there is no such key. If the value is not a string and is not null, - * then it is converted to a string. - * - * @param key - * A key string. - * @return A string which is the value. - */ - public String optString(String key) { - return this.optString(key, ""); - } - - /** - * Get an optional string associated with a key. It returns the defaultValue - * if there is no such key. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return A string which is the value. - */ - public String optString(String key, String defaultValue) { - Object object = this.opt(key); - return NULL.equals(object) ? defaultValue : object.toString(); - } - - /** - * Populates the internal map of the JSONObject with the bean properties. The - * bean can not be recursive. - * - * @see JSONObject#JSONObject(Object) - * - * @param bean - * the bean - */ - private void populateMap(Object bean) { - Class klass = bean.getClass(); - - // If klass is a System class then set includeSuperClass to false. - - boolean includeSuperClass = klass.getClassLoader() != null; - - Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods(); - for (final Method method : methods) { - final int modifiers = method.getModifiers(); - if (Modifier.isPublic(modifiers) - && !Modifier.isStatic(modifiers) - && method.getParameterTypes().length == 0 - && !method.isBridge() - && method.getReturnType() != Void.TYPE - && isValidMethodName(method.getName())) { - final String key = getKeyNameFromMethod(method); - if (key != null && !key.isEmpty()) { - try { - final Object result = method.invoke(bean); - if (result != null) { - this.map.put(key, wrap(result)); - // we don't use the result anywhere outside of wrap - // if it's a resource we should be sure to close it - // after calling toString - if (result instanceof Closeable) { - try { - ((Closeable) result).close(); - } catch (IOException ignore) { - } - } - } - } catch (IllegalAccessException ignore) { - } catch (IllegalArgumentException ignore) { - } catch (InvocationTargetException ignore) { - } - } - } - } - } - private static boolean isValidMethodName(String name) { return !"getClass".equals(name) && !"getDeclaringClass".equals(name); } @@ -1593,15 +600,11 @@ public class JSONObject { * Searches the class hierarchy to see if the method or it's super * implementations and interfaces has the annotation. * - * @param - * type of the annotation - * - * @param m - * method to check - * @param annotationClass - * annotation to look for + * @param type of the annotation + * @param m method to check + * @param annotationClass annotation to look for * @return the {@link Annotation} if the annotation exists on the current method - * or one of it's super class definitions + * or one of it's super class definitions */ private static A getAnnotation(final Method m, final Class annotationClass) { // if we have invalid data the result is null @@ -1646,13 +649,11 @@ public class JSONObject { * Searches the class hierarchy to see if the method or it's super * implementations and interfaces has the annotation. Returns the depth of the * annotation in the hierarchy. + *

+ * type of the annotation * - * type of the annotation - * - * @param m - * method to check - * @param annotationClass - * annotation to look for + * @param m method to check + * @param annotationClass annotation to look for * @return Depth of the annotation or -1 if the annotation is not on the method. */ private static int getAnnotationDepth(final Method m, final Class annotationClass) { @@ -1703,285 +704,6 @@ public class JSONObject { } } - /** - * Put a key/boolean pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * A boolean which is the value. - * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject put(String key, boolean value) throws JSONException { - return this.put(key, value ? Boolean.TRUE : Boolean.FALSE); - } - - public JSONObject put(String key, byte value) throws JSONException { - return this.put(key, Byte.valueOf(value)); - } - - /** - * Put a key/value pair in the JSONObject, where the value will be a - * JSONArray which is produced from a Collection. - * - * @param key - * A key string. - * @param value - * A Collection value. - * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject put(String key, Collection value) throws JSONException { - return this.put(key, new JSONArray(value)); - } - - /** - * Put a key/double pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * A double which is the value. - * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject put(String key, double value) throws JSONException { - return this.put(key, Double.valueOf(value)); - } - - /** - * Put a key/float pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * A float which is the value. - * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject put(String key, float value) throws JSONException { - return this.put(key, Float.valueOf(value)); - } - - /** - * Put a key/int pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * An int which is the value. - * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject put(String key, int value) throws JSONException { - return this.put(key, Integer.valueOf(value)); - } - - /** - * Put a key/long pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * A long which is the value. - * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject put(String key, long value) throws JSONException { - return this.put(key, Long.valueOf(value)); - } - - /** - * Put a key/value pair in the JSONObject, where the value will be a - * JSONObject which is produced from a Map. - * - * @param key - * A key string. - * @param value - * A Map value. - * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject put(String key, Map value) throws JSONException { - return this.put(key, new JSONObject(value)); - } - - /** - * Put a key/value pair in the JSONObject. If the value is null, then the - * key will be removed from the JSONObject if it is present. - * - * @param key - * A key string. - * @param value - * An object which is the value. It should be of one of these - * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, - * String, or the JSONObject.NULL object. - * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject put(String key, Object value) throws JSONException { - if (key == null) { - throw new NullPointerException("Null key."); - } - if (value != null) { - testValidity(value); - this.map.put(key, value); - } else { - this.remove(key); - } - return this; - } - - public JSONObject put(String key, byte[] bytes) throws JSONException { - return this.put(key, (Object) bytes); - } - - public JSONObject put(String key, UUID uuid) throws JSONException { - return this.put(key, uuid.toString()); - } - - /** - * Put a key/value pair in the JSONObject, but only if the key and the value - * are both non-null, and only if there is not already a member with that - * name. - * - * @param key - * key to insert into - * @param value - * value to insert - * @return this. - * @throws JSONException - * if the key is a duplicate - */ - public JSONObject putOnce(String key, Object value) throws JSONException { - if (key != null && value != null) { - if (this.opt(key) != null) { - throw new JSONException("Duplicate key \"" + key + "\""); - } - return this.put(key, value); - } - return this; - } - - /** - * Put a key/value pair in the JSONObject, but only if the key and the value - * are both non-null. - * - * @param key - * A key string. - * @param value - * An object which is the value. It should be of one of these - * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, - * String, or the JSONObject.NULL object. - * @return this. - * @throws JSONException - * If the value is a non-finite number. - */ - public JSONObject putOpt(String key, Object value) throws JSONException { - if (key != null && value != null) { - return this.put(key, value); - } - return this; - } - - /** - * Creates a JSONPointer using an initialization string and tries to - * match it to an item within this JSONObject. For example, given a - * JSONObject initialized with this document: - *

-     * {
-     *     "a":{"b":"c"}
-     * }
-     * 
- * and this JSONPointer string: - *
-     * "/a/b"
-     * 
- * Then this method will return the String "c". - * A JSONPointerException may be thrown from code called by this method. - * - * @param jsonPointer string that can be used to create a JSONPointer - * @return the item matched by the JSONPointer, otherwise null - */ - public Object query(String jsonPointer) { - return query(new JSONPointer(jsonPointer)); - } - /** - * Uses a user initialized JSONPointer and tries to - * match it to an item within this JSONObject. For example, given a - * JSONObject initialized with this document: - *
-     * {
-     *     "a":{"b":"c"}
-     * }
-     * 
- * and this JSONPointer: - *
-     * "/a/b"
-     * 
- * Then this method will return the String "c". - * A JSONPointerException may be thrown from code called by this method. - * - * @param jsonPointer string that can be used to create a JSONPointer - * @return the item matched by the JSONPointer, otherwise null - */ - public Object query(JSONPointer jsonPointer) { - return jsonPointer.queryFrom(this); - } - - /** - * Queries and returns a value from this object using {@code jsonPointer}, or - * returns null if the query fails due to a missing key. - * - * @param jsonPointer the string representation of the JSON pointer - * @return the queried value or {@code null} - * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax - */ - public Object optQuery(String jsonPointer) { - return optQuery(new JSONPointer(jsonPointer)); - } - - /** - * Queries and returns a value from this object using {@code jsonPointer}, or - * returns null if the query fails due to a missing key. - * - * @param jsonPointer The JSON pointer - * @return the queried value or {@code null} - * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax - */ - public Object optQuery(JSONPointer jsonPointer) { - try { - return jsonPointer.queryFrom(this); - } catch (JSONPointerException e) { - return null; - } - } - /** * Produce a string in double quotes with backslash sequences in all the * right places. A backslash will be inserted within </, producing @@ -1989,8 +711,7 @@ public class JSONObject { * string cannot contain a control character or an unescaped quote or * backslash. * - * @param string - * A String + * @param string A String * @return A String correctly formatted for insertion in a JSON text. */ public static String quote(String string) { @@ -2022,107 +743,51 @@ public class JSONObject { b = c; c = string.charAt(i); switch (c) { - case '\\': - case '"': - w.write('\\'); - w.write(c); - break; - case '/': - if (b == '<') { + case '\\': + case '"': 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); - } + 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; } - /** - * Remove a name and its value, if present. - * - * @param key - * The name to be removed. - * @return The value that was associated with the name, or null if there was - * no value. - */ - public Object remove(String key) { - return this.map.remove(key); - } - - /** - * Determine if two JSONObjects are similar. - * They must contain the same set of names which must be associated with - * similar values. - * - * @param other The other JSONObject - * @return true if they are equal - */ - public boolean similar(Object other) { - try { - if (!(other instanceof JSONObject)) { - return false; - } - if (!this.keySet().equals(((JSONObject)other).keySet())) { - return false; - } - for (final Entry entry : this.entrySet()) { - String name = entry.getKey(); - Object valueThis = entry.getValue(); - Object valueOther = ((JSONObject)other).get(name); - if(valueThis == valueOther) { - continue; - } - if(valueThis == null) { - return false; - } - if (valueThis instanceof JSONObject) { - if (!((JSONObject)valueThis).similar(valueOther)) { - return false; - } - } else if (valueThis instanceof JSONArray) { - if (!((JSONArray)valueThis).similar(valueOther)) { - return false; - } - } else if (!valueThis.equals(valueOther)) { - return false; - } - } - return true; - } catch (Throwable exception) { - return false; - } - } - /** * Tests if the value should be tried as a decimal. It makes no test if there are actual digits. - * + * * @param val value to test * @return true if the string is "-0" or if it contains '.', 'e', or 'E', false otherwise. */ @@ -2130,16 +795,16 @@ public class JSONObject { return val.indexOf('.') > -1 || val.indexOf('e') > -1 || val.indexOf('E') > -1 || "-0".equals(val); } - + /** - * Converts a string to a number using the narrowest possible type. Possible + * Converts a string to a number using the narrowest possible type. Possible * returns for this function are BigDecimal, Double, BigInteger, Long, and Integer. * When a Double is returned, it should always be a valid Double and not NaN or +-infinity. - * + * * @param val value to convert * @return Number representation of the value. * @throws NumberFormatException thrown if the value is not a valid number. A public - * caller should catch this and wrap it in a {@link JSONException} if applicable. + * caller should catch this and wrap it in a {@link JSONException} if applicable. */ protected static Number stringToNumber(final String val) throws NumberFormatException { char initial = val.charAt(0); @@ -2148,7 +813,7 @@ public class JSONObject { if (isDecimalNotation(val)) { // quick dirty way to see if we need a BigDecimal instead of a Double // this only handles some cases of overflow or underflow - if (val.length()>14) { + if (val.length() > 14) { return new BigDecimal(val); } final Double d = Double.valueOf(val); @@ -2164,7 +829,7 @@ public class JSONObject { // integer representation. // This will narrow any values to the smallest reasonable Object representation // (Integer, Long, or BigInteger) - + // string version // The compare string length method reduces GC, // but leads to smaller integers being placed in larger wrappers even though not @@ -2177,33 +842,31 @@ public class JSONObject { // return Long.valueOf(val); //} //return new BigInteger(val); - + // BigInteger version: We use a similar bitLength compare as // BigInteger#intValueExact uses. Increases GC, but objects hold // only what they need. i.e. Less runtime overhead if the value is // long lived. Which is the better tradeoff? This is closer to what's // in stringToValue. BigInteger bi = new BigInteger(val); - if(bi.bitLength()<=31){ + if (bi.bitLength() <= 31) { return Integer.valueOf(bi.intValue()); } - if(bi.bitLength()<=63){ + if (bi.bitLength() <= 63) { return Long.valueOf(bi.longValue()); } return bi; } - throw new NumberFormatException("val ["+val+"] is not a valid number."); + throw new NumberFormatException("val [" + val + "] is not a valid number."); } /** * Try to convert a string into a number, boolean, or null. If the string * can't be converted, return the string. * - * @param string - * A String. can not be null. + * @param string A String. can not be null. * @return A simple JSON value. - * @throws NullPointerException - * Thrown if the string is null. + * @throws NullPointerException Thrown if the string is null. */ // Changes to this method must be copied to the corresponding method in // the XML class to keep full support for Android @@ -2257,10 +920,8 @@ public class JSONObject { /** * Throw an exception if the object is a NaN or infinite number. * - * @param o - * The object to test. - * @throws JSONException - * If o is a non-finite number. + * @param o The object to test. + * @throws JSONException If o is a non-finite number. */ public static void testValidity(Object o) throws JSONException { if (o != null) { @@ -2278,83 +939,6 @@ public class JSONObject { } } - /** - * Produce a JSONArray containing the values of the members of this - * JSONObject. - * - * @param names - * A JSONArray containing a list of key strings. This determines - * the sequence of the values in the result. - * @return A JSONArray of values. - * @throws JSONException - * If any of the values are non-finite numbers. - */ - public JSONArray toJSONArray(JSONArray names) throws JSONException { - if (names == null || names.isEmpty()) { - return null; - } - JSONArray ja = new JSONArray(); - for (int i = 0; i < names.length(); i += 1) { - ja.put(this.opt(names.getString(i))); - } - return ja; - } - - /** - * Make a JSON text of this JSONObject. For compactness, no whitespace is - * added. If this would not result in a syntactically correct JSON text, - * then null will be returned instead. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * - * @return a printable, displayable, portable, transmittable representation - * of the object, beginning with { (left - * brace) and ending with } (right - * brace). - */ - @Override - public String toString() { - try { - return this.toString(0); - } catch (Exception e) { - return null; - } - } - - /** - * Make a pretty-printed JSON text of this JSONObject. - * - *

If indentFactor > 0 and the {@link JSONObject} - * has only one key, then the object will be output on a single line: - *

{@code {"key": 1}}
- * - *

If an object has 2 or more keys, then it will be output across - * multiple lines:

{
-     *  "key1": 1,
-     *  "key2": "value 2",
-     *  "key3": 3
-     * }
- *

- * Warning: This method assumes that the data structure is acyclical. - * - * - * @param indentFactor - * The number of spaces to add to each level of indentation. - * @return a printable, displayable, portable, transmittable representation - * of the object, beginning with { (left - * brace) and ending with } (right - * brace). - * @throws JSONException - * If the object contains an invalid number. - */ - public String toString(int indentFactor) throws JSONException { - StringWriter w = new StringWriter(); - synchronized (w.getBuffer()) { - return this.write(w, indentFactor, 0).toString(); - } - } - /** * Make a JSON text of an Object value. If the object has an * value.toJSONString() method, then that method will be used to produce the @@ -2370,20 +954,18 @@ public class JSONObject { *

* Warning: This method assumes that the data structure is acyclical. * - * @param value - * The value to be serialized. + * @param value The value to be serialized. * @return a printable, displayable, transmittable representation of the - * object, beginning with { (left - * brace) and ending with } (right - * brace). - * @throws JSONException - * If the value is or contains an invalid number. + * object, beginning with { (left + * brace) and ending with } (right + * brace). + * @throws JSONException If the value is or contains an invalid number. */ public static String valueToString(Object value) throws JSONException { - // moves the implementation to JSONWriter as: - // 1. It makes more sense to be part of the writer class - // 2. For Android support this method is not available. By implementing it in the Writer - // Android users can use the writer with the built in Android JSONObject implementation. + // moves the implementation to JSONWriter as: + // 1. It makes more sense to be part of the writer class + // 2. For Android support this method is not available. By implementing it in the Writer + // Android users can use the writer with the built in Android JSONObject implementation. return JSONWriter.valueToString(value); } @@ -2395,8 +977,7 @@ public class JSONObject { * one of the java packages, turn it into a string. And if it doesn't, try * to wrap it in a JSONObject. If the wrapping fails, then null is returned. * - * @param object - * The object to wrap + * @param object The object to wrap * @return The wrapped value */ public static Object wrap(Object object) { @@ -2440,22 +1021,8 @@ public class JSONObject { } } - /** - * Write the contents of the JSONObject as JSON text to a writer. For - * compactness, no whitespace is added. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * - * @return The writer. - * @throws JSONException - */ - public Writer write(Writer writer) throws JSONException { - return this.write(writer, 0, 0); - } - static final Writer writeValue(Writer writer, Object value, - int indentFactor, int indent) throws JSONException, IOException { + int indentFactor, int indent) throws JSONException, IOException { if (value == null || value.equals(null)) { writer.write("null"); } else if (value instanceof JSONString) { @@ -2469,7 +1036,7 @@ public class JSONObject { } else if (value instanceof Number) { // not all Numbers may match actual JSON Numbers. i.e. fractions or Imaginary final String numberAsString = numberToString((Number) value); - if(NUMBER_PATTERN.matcher(numberAsString).matches()) { + if (NUMBER_PATTERN.matcher(numberAsString).matches()) { writer.write(numberAsString); } else { // The Number value is not a valid JSON number. @@ -2479,7 +1046,7 @@ public class JSONObject { } else if (value instanceof Boolean) { writer.write(value.toString()); } else if (value instanceof Enum) { - writer.write(quote(((Enum)value).name())); + writer.write(quote(((Enum) value).name())); } else if (value instanceof JSONObject) { ((JSONObject) value).write(writer, indentFactor, indent); } else if (value instanceof JSONArray) { @@ -2505,12 +1072,1227 @@ public class JSONObject { } /** - * Write the contents of the JSONObject as JSON text to a writer. - * + * Create a new JSONException in a common format for incorrect conversions. + * + * @param key name of the key + * @param valueType the type of value being coerced to + * @param cause optional cause of the coercion failure + * @return JSONException that can be thrown. + */ + private static JSONException wrongValueFormatException( + String key, + String valueType, + Throwable cause) { + return new JSONException( + "JSONObject[" + quote(key) + "] is not a " + valueType + "." + , cause); + } + + /** + * Create a new JSONException in a common format for incorrect conversions. + * + * @param key name of the key + * @param valueType the type of value being coerced to + * @param cause optional cause of the coercion failure + * @return JSONException that can be thrown. + */ + private static JSONException wrongValueFormatException( + String key, + String valueType, + Object value, + Throwable cause) { + return new JSONException( + "JSONObject[" + quote(key) + "] is not a " + valueType + " (" + value + ")." + , cause); + } + + /** + * Accumulate values under a key. It is similar to the put method except + * that if there is already an object stored under the key then a JSONArray + * is stored under the key to hold all of the accumulated values. If there + * is already a JSONArray, then the new value is appended to it. In + * contrast, the put method replaces the previous value. + *

+ * If only one value is accumulated that is not a JSONArray, then the result + * will be the same as using put. But if multiple values are accumulated, + * then the result will be like append. + * + * @param key A key string. + * @param value An object to be accumulated under the key. + * @return this. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. + */ + public JSONObject accumulate(String key, Object value) throws JSONException { + testValidity(value); + 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; + } + + /** + * Append values to the array under a key. If the key does not exist in the + * JSONObject, then the key is put in the JSONObject with its value being a + * JSONArray containing the value parameter. If the key was already + * associated with a JSONArray, then the value parameter is appended to it. + * + * @param key A key string. + * @param value An object to be accumulated under the key. + * @return this. + * @throws JSONException If the value is non-finite number or if the current value associated with + * the key is not a JSONArray. + * @throws NullPointerException If the key is null. + */ + public JSONObject append(String key, Object value) throws JSONException { + testValidity(value); + 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 wrongValueFormatException(key, "JSONArray", null, null); + } + return this; + } + + /** + * Get the value object associated with a key. + * + * @param key A key string. + * @return The object associated with the key. + * @throws JSONException if the key is not found. + */ + public Object get(String key) throws JSONException { + if (key == null) { + throw new JSONException("Null key."); + } + Object object = this.opt(key); + if (object == null) { + throw new JSONException("JSONObject[" + quote(key) + "] not found."); + } + return object; + } + + /** + * Get the enum value associated with a key. + * + * @param Enum Type + * @param clazz The type of enum to retrieve. + * @param key A key string. + * @return The enum value associated with the key + * @throws JSONException if the key is not found or if the value cannot be converted + * to an enum. + */ + public > E getEnum(Class clazz, String key) throws JSONException { + E val = optEnum(clazz, key); + if (val == null) { + // JSONException should really take a throwable argument. + // If it did, I would re-implement this with the Enum.valueOf + // method and place any thrown exception in the JSONException + throw wrongValueFormatException(key, "enum of type " + quote(clazz.getSimpleName()), null); + } + return val; + } + + /** + * Get the boolean value associated with a key. + * + * @param key A key string. + * @return The truth. + * @throws JSONException if the value is not a Boolean or the String "true" or + * "false". + */ + public boolean getBoolean(String key) throws JSONException { + 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 wrongValueFormatException(key, "Boolean", null); + } + + /** + * Get the BigInteger value associated with a key. + * + * @param key A key string. + * @return The numeric value. + * @throws JSONException if the key is not found or if the value cannot + * be converted to BigInteger. + */ + public BigInteger getBigInteger(String key) throws JSONException { + Object object = this.get(key); + BigInteger ret = objectToBigInteger(object, null); + if (ret != null) { + return ret; + } + throw wrongValueFormatException(key, "BigInteger", object, null); + } + + /** + * Get the BigDecimal value associated with a key. If the value is float or + * double, the the {@link BigDecimal#BigDecimal(double)} constructor will + * be used. See notes on the constructor for conversion issues that may + * arise. + * + * @param key A key string. + * @return The numeric value. + * @throws JSONException if the key is not found or if the value + * cannot be converted to BigDecimal. + */ + public BigDecimal getBigDecimal(String key) throws JSONException { + Object object = this.get(key); + BigDecimal ret = objectToBigDecimal(object, null); + if (ret != null) { + return ret; + } + throw wrongValueFormatException(key, "BigDecimal", object, null); + } + + /** + * Get the double value associated with a key. + * + * @param key A key string. + * @return The numeric value. + * @throws JSONException if the key is not found or if the value is not a Number + * object and cannot be converted to a number. + */ + public double getDouble(String key) throws JSONException { + final Object object = this.get(key); + if (object instanceof Number) { + return ((Number) object).doubleValue(); + } + try { + return Double.parseDouble(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(key, "double", e); + } + } + + /** + * Get the float value associated with a key. + * + * @param key A key string. + * @return The numeric value. + * @throws JSONException if the key is not found or if the value is not a Number + * object and cannot be converted to a number. + */ + public float getFloat(String key) throws JSONException { + final Object object = this.get(key); + if (object instanceof Number) { + return ((Number) object).floatValue(); + } + try { + return Float.parseFloat(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(key, "float", e); + } + } + + /** + * Get the Number value associated with a key. + * + * @param key A key string. + * @return The numeric value. + * @throws JSONException if the key is not found or if the value is not a Number + * object and cannot be converted to a number. + */ + public Number getNumber(String key) throws JSONException { + Object object = this.get(key); + try { + if (object instanceof Number) { + return (Number) object; + } + return stringToNumber(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(key, "number", e); + } + } + + /** + * Get the int value associated with a key. + * + * @param key A key string. + * @return The integer value. + * @throws JSONException if the key is not found or if the value cannot be converted + * to an integer. + */ + public int getInt(String key) throws JSONException { + final Object object = this.get(key); + if (object instanceof Number) { + return ((Number) object).intValue(); + } + try { + return Integer.parseInt(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(key, "int", e); + } + } + + /** + * Get the JSONArray value associated with a key. + * + * @param key A key string. + * @return A JSONArray which is the value. + * @throws JSONException if the key is not found or if the value is not a JSONArray. + */ + public JSONArray getJSONArray(String key) throws JSONException { + Object object = this.get(key); + if (object instanceof JSONArray) { + return (JSONArray) object; + } + throw wrongValueFormatException(key, "JSONArray", null); + } + + /** + * Get the JSONObject value associated with a key. + * + * @param key A key string. + * @return A JSONObject which is the value. + * @throws JSONException if the key is not found or if the value is not a JSONObject. + */ + public JSONObject getJSONObject(String key) throws JSONException { + Object object = this.get(key); + if (object instanceof JSONObject) { + return (JSONObject) object; + } + throw wrongValueFormatException(key, "JSONObject", null); + } + + /** + * Get the long value associated with a key. + * + * @param key A key string. + * @return The long value. + * @throws JSONException if the key is not found or if the value cannot be converted + * to a long. + */ + public long getLong(String key) throws JSONException { + final Object object = this.get(key); + if (object instanceof Number) { + return ((Number) object).longValue(); + } + try { + return Long.parseLong(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(key, "long", e); + } + } + + public UUID getUUID(String key) throws JSONException { + Object object = this.get(key); + if (object instanceof UUID) { + return (UUID) object; + } else if (object instanceof String) { + return UUID.fromString(String.valueOf(object)); + } + throw wrongValueFormatException(key, "UUID", null); + } + + /** + * Get the string associated with a key. + * + * @param key A key string. + * @return A string which is the value. + * @throws JSONException if there is no string value for the key. + */ + public String getString(String key) throws JSONException { + Object object = this.get(key); + if (object instanceof String) { + return (String) object; + } + throw wrongValueFormatException(key, "string", null); + } + + public byte getByte(String key) throws JSONException { + Object object = this.get(key); + if (object instanceof Byte) { + return (byte) object; + } + throw wrongValueFormatException(key, "byte", null); + } + + public byte[] getByteArray(String key) throws JSONException { + Object object = this.get(key); + if (object instanceof JSONArray) { + JSONArray jsonArray = (JSONArray) object; + byte[] array = new byte[jsonArray.length()]; + for (int k = 0; k < jsonArray.length(); k++) { + array[k] = Byte.valueOf(String.valueOf(jsonArray.get(k))); + } + return array; + } + if (object instanceof byte[]) { + return (byte[]) object; + } + throw wrongValueFormatException(key, "byteArray", null); + } + + /** + * Determine if the JSONObject contains a specific key. + * + * @param key A key string. + * @return true if the key exists in the JSONObject. + */ + public boolean has(String key) { + return this.map.containsKey(key); + } + + /** + * Increment a property of a JSONObject. If there is no such property, + * create one with a value of 1 (Integer). If there is such a property, and if it is + * an Integer, Long, Double, Float, BigInteger, or BigDecimal then add one to it. + * No overflow bounds checking is performed, so callers should initialize the key + * prior to this call with an appropriate type that can handle the maximum expected + * value. + * + * @param key A key string. + * @return this. + * @throws JSONException If there is already a property with this name that is not an + * Integer, Long, Double, or Float. + */ + public JSONObject increment(String key) throws JSONException { + 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() + 1L); + } else if (value instanceof BigInteger) { + this.put(key, ((BigInteger) value).add(BigInteger.ONE)); + } else if (value instanceof Float) { + this.put(key, ((Float) value).floatValue() + 1.0f); + } else if (value instanceof Double) { + this.put(key, ((Double) value).doubleValue() + 1.0d); + } else if (value instanceof BigDecimal) { + this.put(key, ((BigDecimal) value).add(BigDecimal.ONE)); + } else { + throw new JSONException("Unable to increment [" + quote(key) + "]."); + } + return this; + } + + /** + * Determine if the value associated with the key is null or if there is no + * value. + * + * @param key A key string. + * @return true if there is no value associated with the key or if the value + * is the JSONObject.NULL object. + */ + public boolean isNull(String key) { + return JSONObject.NULL.equals(this.opt(key)); + } + + /** + * Get an enumeration of the keys of the JSONObject. Modifying this key Set will also + * modify the JSONObject. Use with caution. + * + * @return An iterator of the keys. + * @see Set#iterator() + */ + public Iterator keys() { + return this.keySet().iterator(); + } + + /** + * Get a set of keys of the JSONObject. Modifying this key Set will also modify the + * JSONObject. Use with caution. + * + * @return A keySet. + * @see Map#keySet() + */ + public Set keySet() { + return this.map.keySet(); + } + + /** + * Get a set of entries of the JSONObject. These are raw values and may not + * match what is returned by the JSONObject get* and opt* functions. Modifying + * the returned EntrySet or the Entry objects contained therein will modify the + * backing JSONObject. This does not return a clone or a read-only view. + *

+ * Use with caution. + * + * @return An Entry Set + * @see Map#entrySet() + */ + protected Set> entrySet() { + return this.map.entrySet(); + } + + /** + * Get the number of keys stored in the JSONObject. + * + * @return The number of keys in the JSONObject. + */ + public int length() { + return this.map.size(); + } + + /** + * Check if JSONObject is empty. + * + * @return true if JSONObject is empty, otherwise false. + */ + public boolean isEmpty() { + return this.map.isEmpty(); + } + + /** + * Produce a JSONArray containing the names of the elements of this + * JSONObject. + * + * @return A JSONArray containing the key strings, or null if the JSONObject + * is empty. + */ + public JSONArray names() { + if (this.map.isEmpty()) { + return null; + } + return new JSONArray(this.map.keySet()); + } + + /** + * Get an optional value associated with a key. + * + * @param key A key string. + * @return An object which is the value, or null if there is no value. + */ + public Object opt(String key) { + return key == null ? null : this.map.get(key); + } + + /** + * Get the enum value associated with a key. + * + * @param Enum Type + * @param clazz The type of enum to retrieve. + * @param key A key string. + * @return The enum value associated with the key or null if not found + */ + public > E optEnum(Class clazz, String key) { + return this.optEnum(clazz, key, null); + } + + /** + * Get the enum value associated with a key. + * + * @param Enum Type + * @param clazz The type of enum to retrieve. + * @param key A key string. + * @param defaultValue The default in case the value is not found + * @return The enum value associated with the key or defaultValue + * if the value is not found or cannot be assigned to clazz + */ + public > E optEnum(Class clazz, String key, E defaultValue) { + try { + Object val = this.opt(key); + if (NULL.equals(val)) { + return defaultValue; + } + if (clazz.isAssignableFrom(val.getClass())) { + // we just checked it! + @SuppressWarnings("unchecked") + E myE = (E) val; + return myE; + } + return Enum.valueOf(clazz, val.toString()); + } catch (IllegalArgumentException e) { + return defaultValue; + } catch (NullPointerException e) { + return defaultValue; + } + } + + /** + * Get an optional boolean associated with a key. It returns false if there + * is no such key, or if the value is not Boolean.TRUE or the String "true". + * + * @param key A key string. + * @return The truth. + */ + public boolean optBoolean(String key) { + return this.optBoolean(key, false); + } + + /** + * Get an optional boolean associated with a key. It returns the + * defaultValue if there is no such key, or if it is not a Boolean or the + * String "true" or "false" (case insensitive). + * + * @param key A key string. + * @param defaultValue The default. + * @return The truth. + */ + public boolean optBoolean(String key, boolean defaultValue) { + Object val = this.opt(key); + if (NULL.equals(val)) { + return defaultValue; + } + if (val instanceof Boolean) { + return ((Boolean) val).booleanValue(); + } + try { + // we'll use the get anyway because it does string conversion. + return this.getBoolean(key); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get an optional BigDecimal associated with a key, or the defaultValue if + * there is no such key or if its value is not a number. If the value is a + * string, an attempt will be made to evaluate it as a number. If the value + * is float or double, then the {@link BigDecimal#BigDecimal(double)} + * constructor will be used. See notes on the constructor for conversion + * issues that may arise. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) { + Object val = this.opt(key); + return objectToBigDecimal(val, defaultValue); + } + + /** + * Get an optional BigInteger associated with a key, or the defaultValue if + * there is no such key or if its value is not a number. If the value is a + * string, an attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public BigInteger optBigInteger(String key, BigInteger defaultValue) { + Object val = this.opt(key); + return objectToBigInteger(val, defaultValue); + } + + /** + * Get an optional double associated with a key, or NaN if there is no such + * key or if its value is not a number. If the value is a string, an attempt + * will be made to evaluate it as a number. + * + * @param key A string which is the key. + * @return An object which is the value. + */ + public double optDouble(String key) { + return this.optDouble(key, Double.NaN); + } + + /** + * Get an optional double associated with a key, or the defaultValue if + * there is no such key or if its value is not a number. If the value is a + * string, an attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public double optDouble(String key, double defaultValue) { + Number val = this.optNumber(key); + if (val == null) { + return defaultValue; + } + final double doubleValue = val.doubleValue(); + // if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) { + // return defaultValue; + // } + return doubleValue; + } + + /** + * Get the optional double value associated with an index. NaN is returned + * if there is no value for the index, or if the value is not a number and + * cannot be converted to a number. + * + * @param key A key string. + * @return The value. + */ + public float optFloat(String key) { + return this.optFloat(key, Float.NaN); + } + + /** + * Get the optional double value associated with an index. The defaultValue + * is returned if there is no value for the index, or if the value is not a + * number and cannot be converted to a number. + * + * @param key A key string. + * @param defaultValue The default value. + * @return The value. + */ + public float optFloat(String key, float defaultValue) { + Number val = this.optNumber(key); + if (val == null) { + return defaultValue; + } + final float floatValue = val.floatValue(); + // if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) { + // return defaultValue; + // } + return floatValue; + } + + /** + * Get an optional int value associated with a key, or zero if there is no + * such key or if the value is not a number. If the value is a string, an + * attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @return An object which is the value. + */ + public int optInt(String key) { + return this.optInt(key, 0); + } + + /** + * Get an optional int value associated with a key, or the default if there + * is no such key or if the value is not a number. If the value is a string, + * an attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public int optInt(String key, int defaultValue) { + final Number val = this.optNumber(key, null); + if (val == null) { + return defaultValue; + } + return val.intValue(); + } + + /** + * Get an optional JSONArray associated with a key. It returns null if there + * is no such key, or if its value is not a JSONArray. + * + * @param key A key string. + * @return A JSONArray which is the value. + */ + public JSONArray optJSONArray(String key) { + Object o = this.opt(key); + return o instanceof JSONArray ? (JSONArray) o : null; + } + + /** + * Get an optional JSONObject associated with a key. It returns null if + * there is no such key, or if its value is not a JSONObject. + * + * @param key A key string. + * @return A JSONObject which is the value. + */ + public JSONObject optJSONObject(String key) { + Object object = this.opt(key); + return object instanceof JSONObject ? (JSONObject) object : null; + } + + /** + * Get an optional long value associated with a key, or zero if there is no + * such key or if the value is not a number. If the value is a string, an + * attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @return An object which is the value. + */ + public long optLong(String key) { + return this.optLong(key, 0); + } + + /** + * Get an optional long value associated with a key, or the default if there + * is no such key or if the value is not a number. If the value is a string, + * an attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public long optLong(String key, long defaultValue) { + final Number val = this.optNumber(key, null); + if (val == null) { + return defaultValue; + } + + return val.longValue(); + } + + /** + * Get an optional {@link Number} value associated with a key, or null + * if there is no such key or if the value is not a number. If the value is a string, + * an attempt will be made to evaluate it as a number ({@link BigDecimal}). This method + * would be used in cases where type coercion of the number value is unwanted. + * + * @param key A key string. + * @return An object which is the value. + */ + public Number optNumber(String key) { + return this.optNumber(key, null); + } + + /** + * Get an optional {@link Number} value associated with a key, or the default if there + * is no such key or if the value is not a number. If the value is a string, + * an attempt will be made to evaluate it as a number. This method + * would be used in cases where type coercion of the number value is unwanted. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public Number optNumber(String key, Number defaultValue) { + Object val = this.opt(key); + if (NULL.equals(val)) { + return defaultValue; + } + if (val instanceof Number) { + return (Number) val; + } + + try { + return stringToNumber(val.toString()); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get an optional string associated with a key. It returns an empty string + * if there is no such key. If the value is not a string and is not null, + * then it is converted to a string. + * + * @param key A key string. + * @return A string which is the value. + */ + public String optString(String key) { + return this.optString(key, ""); + } + + /** + * Get an optional string associated with a key. It returns the defaultValue + * if there is no such key. + * + * @param key A key string. + * @param defaultValue The default. + * @return A string which is the value. + */ + public String optString(String key, String defaultValue) { + Object object = this.opt(key); + return NULL.equals(object) ? defaultValue : object.toString(); + } + + /** + * Populates the internal map of the JSONObject with the bean properties. The + * bean can not be recursive. + * + * @param bean the bean + * @see JSONObject#JSONObject(Object) + */ + private void populateMap(Object bean) { + Class klass = bean.getClass(); + + // If klass is a System class then set includeSuperClass to false. + + boolean includeSuperClass = klass.getClassLoader() != null; + + Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods(); + for (final Method method : methods) { + final int modifiers = method.getModifiers(); + if (Modifier.isPublic(modifiers) + && !Modifier.isStatic(modifiers) + && method.getParameterTypes().length == 0 + && !method.isBridge() + && method.getReturnType() != Void.TYPE + && isValidMethodName(method.getName())) { + final String key = getKeyNameFromMethod(method); + if (key != null && !key.isEmpty()) { + try { + final Object result = method.invoke(bean); + if (result != null) { + this.map.put(key, wrap(result)); + // we don't use the result anywhere outside of wrap + // if it's a resource we should be sure to close it + // after calling toString + if (result instanceof Closeable) { + try { + ((Closeable) result).close(); + } catch (IOException ignore) { + } + } + } + } catch (IllegalAccessException ignore) { + } catch (IllegalArgumentException ignore) { + } catch (InvocationTargetException ignore) { + } + } + } + } + } + + /** + * Put a key/boolean pair in the JSONObject. + * + * @param key A key string. + * @param value A boolean which is the value. + * @return this. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. + */ + public JSONObject put(String key, boolean value) throws JSONException { + return this.put(key, value ? Boolean.TRUE : Boolean.FALSE); + } + + public JSONObject put(String key, byte value) throws JSONException { + return this.put(key, Byte.valueOf(value)); + } + + /** + * Put a key/value pair in the JSONObject, where the value will be a + * JSONArray which is produced from a Collection. + * + * @param key A key string. + * @param value A Collection value. + * @return this. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. + */ + public JSONObject put(String key, Collection value) throws JSONException { + return this.put(key, new JSONArray(value)); + } + + /** + * Put a key/double pair in the JSONObject. + * + * @param key A key string. + * @param value A double which is the value. + * @return this. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. + */ + public JSONObject put(String key, double value) throws JSONException { + return this.put(key, Double.valueOf(value)); + } + + /** + * Put a key/float pair in the JSONObject. + * + * @param key A key string. + * @param value A float which is the value. + * @return this. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. + */ + public JSONObject put(String key, float value) throws JSONException { + return this.put(key, Float.valueOf(value)); + } + + /** + * Put a key/int pair in the JSONObject. + * + * @param key A key string. + * @param value An int which is the value. + * @return this. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. + */ + public JSONObject put(String key, int value) throws JSONException { + return this.put(key, Integer.valueOf(value)); + } + + /** + * Put a key/long pair in the JSONObject. + * + * @param key A key string. + * @param value A long which is the value. + * @return this. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. + */ + public JSONObject put(String key, long value) throws JSONException { + return this.put(key, Long.valueOf(value)); + } + + /** + * Put a key/value pair in the JSONObject, where the value will be a + * JSONObject which is produced from a Map. + * + * @param key A key string. + * @param value A Map value. + * @return this. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. + */ + public JSONObject put(String key, Map value) throws JSONException { + return this.put(key, new JSONObject(value)); + } + + /** + * Put a key/value pair in the JSONObject. If the value is null, then the + * key will be removed from the JSONObject if it is present. + * + * @param key A key string. + * @param value An object which is the value. It should be of one of these + * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, + * String, or the JSONObject.NULL object. + * @return this. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. + */ + public JSONObject put(String key, Object value) throws JSONException { + if (key == null) { + throw new NullPointerException("Null key."); + } + if (value != null) { + testValidity(value); + this.map.put(key, value); + } else { + this.remove(key); + } + return this; + } + + public JSONObject put(String key, byte[] bytes) throws JSONException { + return this.put(key, (Object) bytes); + } + + public JSONObject put(String key, UUID uuid) throws JSONException { + return this.put(key, uuid.toString()); + } + + /** + * Put a key/value pair in the JSONObject, but only if the key and the value + * are both non-null, and only if there is not already a member with that + * name. + * + * @param key key to insert into + * @param value value to insert + * @return this. + * @throws JSONException if the key is a duplicate + */ + public JSONObject putOnce(String key, Object value) throws JSONException { + if (key != null && value != null) { + if (this.opt(key) != null) { + throw new JSONException("Duplicate key \"" + key + "\""); + } + return this.put(key, value); + } + return this; + } + + /** + * Put a key/value pair in the JSONObject, but only if the key and the value + * are both non-null. + * + * @param key A key string. + * @param value An object which is the value. It should be of one of these + * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, + * String, or the JSONObject.NULL object. + * @return this. + * @throws JSONException If the value is a non-finite number. + */ + public JSONObject putOpt(String key, Object value) throws JSONException { + if (key != null && value != null) { + return this.put(key, value); + } + return this; + } + + /** + * Creates a JSONPointer using an initialization string and tries to + * match it to an item within this JSONObject. For example, given a + * JSONObject initialized with this document: + *

+     * {
+     *     "a":{"b":"c"}
+     * }
+     * 
+ * and this JSONPointer string: + *
+     * "/a/b"
+     * 
+ * Then this method will return the String "c". + * A JSONPointerException may be thrown from code called by this method. + * + * @param jsonPointer string that can be used to create a JSONPointer + * @return the item matched by the JSONPointer, otherwise null + */ + public Object query(String jsonPointer) { + return query(new JSONPointer(jsonPointer)); + } + + /** + * Uses a user initialized JSONPointer and tries to + * match it to an item within this JSONObject. For example, given a + * JSONObject initialized with this document: + *
+     * {
+     *     "a":{"b":"c"}
+     * }
+     * 
+ * and this JSONPointer: + *
+     * "/a/b"
+     * 
+ * Then this method will return the String "c". + * A JSONPointerException may be thrown from code called by this method. + * + * @param jsonPointer string that can be used to create a JSONPointer + * @return the item matched by the JSONPointer, otherwise null + */ + public Object query(JSONPointer jsonPointer) { + return jsonPointer.queryFrom(this); + } + + /** + * Queries and returns a value from this object using {@code jsonPointer}, or + * returns null if the query fails due to a missing key. + * + * @param jsonPointer the string representation of the JSON pointer + * @return the queried value or {@code null} + * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax + */ + public Object optQuery(String jsonPointer) { + return optQuery(new JSONPointer(jsonPointer)); + } + + /** + * Queries and returns a value from this object using {@code jsonPointer}, or + * returns null if the query fails due to a missing key. + * + * @param jsonPointer The JSON pointer + * @return the queried value or {@code null} + * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax + */ + public Object optQuery(JSONPointer jsonPointer) { + try { + return jsonPointer.queryFrom(this); + } catch (JSONPointerException e) { + return null; + } + } + + /** + * Remove a name and its value, if present. + * + * @param key The name to be removed. + * @return The value that was associated with the name, or null if there was + * no value. + */ + public Object remove(String key) { + return this.map.remove(key); + } + + /** + * Determine if two JSONObjects are similar. + * They must contain the same set of names which must be associated with + * similar values. + * + * @param other The other JSONObject + * @return true if they are equal + */ + public boolean similar(Object other) { + try { + if (!(other instanceof JSONObject)) { + return false; + } + if (!this.keySet().equals(((JSONObject) other).keySet())) { + return false; + } + for (final Entry entry : this.entrySet()) { + String name = entry.getKey(); + Object valueThis = entry.getValue(); + Object valueOther = ((JSONObject) other).get(name); + if (valueThis == valueOther) { + continue; + } + if (valueThis == null) { + return false; + } + if (valueThis instanceof JSONObject) { + if (!((JSONObject) valueThis).similar(valueOther)) { + return false; + } + } else if (valueThis instanceof JSONArray) { + if (!((JSONArray) valueThis).similar(valueOther)) { + return false; + } + } else if (!valueThis.equals(valueOther)) { + return false; + } + } + return true; + } catch (Throwable exception) { + return false; + } + } + + /** + * Produce a JSONArray containing the values of the members of this + * JSONObject. + * + * @param names A JSONArray containing a list of key strings. This determines + * the sequence of the values in the result. + * @return A JSONArray of values. + * @throws JSONException If any of the values are non-finite numbers. + */ + public JSONArray toJSONArray(JSONArray names) throws JSONException { + if (names == null || names.isEmpty()) { + return null; + } + JSONArray ja = new JSONArray(); + for (int i = 0; i < names.length(); i += 1) { + ja.put(this.opt(names.getString(i))); + } + return ja; + } + + /** + * Make a JSON text of this JSONObject. For compactness, no whitespace is + * added. If this would not result in a syntactically correct JSON text, + * then null will be returned instead. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * + * @return a printable, displayable, portable, transmittable representation + * of the object, beginning with { (left + * brace) and ending with } (right + * brace). + */ + @Override + public String toString() { + try { + return this.toString(0); + } catch (Exception e) { + return null; + } + } + + /** + * Make a pretty-printed JSON text of this JSONObject. + * *

If indentFactor > 0 and the {@link JSONObject} * has only one key, then the object will be output on a single line: *

{@code {"key": 1}}
- * + * *

If an object has 2 or more keys, then it will be output across * multiple lines:

{
      *  "key1": 1,
@@ -2521,12 +2303,54 @@ public class JSONObject {
      * Warning: This method assumes that the data structure is acyclical.
      * 
      *
-     * @param writer
-     *            Writes the serialized JSON
-     * @param indentFactor
-     *            The number of spaces to add to each level of indentation.
-     * @param indent
-     *            The indentation of the top level.
+     * @param indentFactor The number of spaces to add to each level of indentation.
+     * @return a printable, displayable, portable, transmittable representation
+     * of the object, beginning with { (left
+     * brace) and ending with } (right
+     * brace).
+     * @throws JSONException If the object contains an invalid number.
+     */
+    public String toString(int indentFactor) throws JSONException {
+        StringWriter w = new StringWriter();
+        synchronized (w.getBuffer()) {
+            return this.write(w, indentFactor, 0).toString();
+        }
+    }
+
+    /**
+     * Write the contents of the JSONObject as JSON text to a writer. For
+     * compactness, no whitespace is added.
+     * 

+ * Warning: This method assumes that the data structure is acyclical. + * + * + * @return The writer. + * @throws JSONException + */ + public Writer write(Writer writer) throws JSONException { + return this.write(writer, 0, 0); + } + + /** + * Write the contents of the JSONObject as JSON text to a writer. + * + *

If indentFactor > 0 and the {@link JSONObject} + * has only one key, then the object will be output on a single line: + *

{@code {"key": 1}}
+ * + *

If an object has 2 or more keys, then it will be output across + * multiple lines:

{
+     *  "key1": 1,
+     *  "key2": "value 2",
+     *  "key3": 3
+     * }
+ *

+ * Warning: This method assumes that the data structure is acyclical. + * + * + * @param writer Writes the serialized JSON + * @param indentFactor The number of spaces to add to each level of indentation. + * @param indent The indentation of the top level. * @return The writer. * @throws JSONException */ @@ -2538,21 +2362,21 @@ public class JSONObject { writer.write('{'); if (length == 1) { - final Entry entry = this.entrySet().iterator().next(); + final Entry entry = this.entrySet().iterator().next(); final String key = entry.getKey(); writer.write(quote(key)); writer.write(':'); if (indentFactor > 0) { writer.write(' '); } - try{ + try { writeValue(writer, entry.getValue(), indentFactor, indent); } catch (Exception e) { throw new JSONException("Unable to write JSONObject value for key: " + key, e); } } else if (length != 0) { final int newIndent = indent + indentFactor; - for (final Entry entry : this.entrySet()) { + for (final Entry entry : this.entrySet()) { if (needsComma) { writer.write(','); } @@ -2611,37 +2435,55 @@ public class JSONObject { } return results; } - + /** - * Create a new JSONException in a common format for incorrect conversions. - * @param key name of the key - * @param valueType the type of value being coerced to - * @param cause optional cause of the coercion failure - * @return JSONException that can be thrown. + * JSONObject.NULL is equivalent to the value that JavaScript calls null, + * whilst Java's null is equivalent to the value that JavaScript calls + * undefined. */ - private static JSONException wrongValueFormatException( - String key, - String valueType, - Throwable cause) { - return new JSONException( - "JSONObject[" + quote(key) + "] is not a " + valueType + "." - , cause); - } - - /** - * Create a new JSONException in a common format for incorrect conversions. - * @param key name of the key - * @param valueType the type of value being coerced to - * @param cause optional cause of the coercion failure - * @return JSONException that can be thrown. - */ - private static JSONException wrongValueFormatException( - String key, - String valueType, - Object value, - Throwable cause) { - return new JSONException( - "JSONObject[" + quote(key) + "] is not a " + valueType + " (" + value + ")." - , cause); + private static final class Null { + + /** + * There is only intended to be a single instance of the NULL object, + * so the clone method returns itself. + * + * @return NULL. + */ + @Override + protected final Object clone() { + return this; + } + + /** + * A Null object is equal to the null value and to itself. + * + * @param object An object to test for nullness. + * @return true if the object parameter is the JSONObject.NULL object or + * null. + */ + @Override + public boolean equals(Object object) { + return object == null || object == this; + } + + /** + * A Null object is equal to the null value and to itself. + * + * @return always returns 0. + */ + @Override + public int hashCode() { + return 0; + } + + /** + * Get the "null" string value. + * + * @return The string "null". + */ + @Override + public String toString() { + return "null"; + } } } diff --git a/src/main/java/json/JSONPointer.java b/src/main/java/json/JSONPointer.java index bef1ee0..28a8a31 100644 --- a/src/main/java/json/JSONPointer.java +++ b/src/main/java/json/JSONPointer.java @@ -36,18 +36,18 @@ SOFTWARE. /** * A JSON Pointer is a simple query language defined for JSON documents by * RFC 6901. - * + *

* In a nutshell, JSONPointer allows the user to navigate into a JSON document * using strings, and retrieve targeted objects, like a simple form of XPATH. * Path segments are separated by the '/' char, which signifies the root of - * the document when it appears as the first char of the string. Array + * the document when it appears as the first char of the string. Array * elements are navigated using ordinals, counting from 0. JSONPointer strings * may be extended to any arbitrary number of segments. If the navigation * is successful, the matched item is returned. A matched item may be a - * JSONObject, a JSONArray, or a JSON value. If the JSONPointer string building + * JSONObject, a JSONArray, or a JSON value. If the JSONPointer string building * fails, an appropriate exception is thrown. If the navigation fails to find - * a match, a JSONPointerException is thrown. - * + * a match, a JSONPointerException is thrown. + * * @author JSON.org * @version 2016-05-14 */ @@ -55,76 +55,6 @@ public class JSONPointer { // used for URL encoding and decoding private static final String ENCODING = "utf-8"; - - /** - * This class allows the user to build a JSONPointer in steps, using - * exactly one segment in each step. - */ - public static class Builder { - - // Segments for the eventual JSONPointer string - private final List refTokens = new ArrayList(); - - /** - * Creates a {@code JSONPointer} instance using the tokens previously set using the - * {@link #append(String)} method calls. - */ - public JSONPointer build() { - return new JSONPointer(this.refTokens); - } - - /** - * Adds an arbitrary token to the list of reference tokens. It can be any non-null value. - * - * Unlike in the case of JSON string or URI fragment representation of JSON pointers, the - * argument of this method MUST NOT be escaped. If you want to query the property called - * {@code "a~b"} then you should simply pass the {@code "a~b"} string as-is, there is no - * need to escape it as {@code "a~0b"}. - * - * @param token the new token to be appended to the list - * @return {@code this} - * @throws NullPointerException if {@code token} is null - */ - public Builder append(String token) { - if (token == null) { - throw new NullPointerException("token cannot be null"); - } - this.refTokens.add(token); - return this; - } - - /** - * Adds an integer to the reference token list. Although not necessarily, mostly this token will - * denote an array index. - * - * @param arrayIndex the array index to be added to the token list - * @return {@code this} - */ - public Builder append(int arrayIndex) { - this.refTokens.add(String.valueOf(arrayIndex)); - return this; - } - } - - /** - * Static factory method for {@link Builder}. Example usage: - * - *


-     * JSONPointer pointer = JSONPointer.builder()
-     *       .append("obj")
-     *       .append("other~key").append("another/key")
-     *       .append("\"")
-     *       .append(0)
-     *       .build();
-     * 
- * - * @return a builder instance which can be used to construct a {@code JSONPointer} instance by chained - * {@link Builder#append(String)} calls. - */ - public static Builder builder() { - return new Builder(); - } - // Segments for the JSONPointer string private final List refTokens; @@ -132,7 +62,7 @@ public class JSONPointer { * Pre-parses and initializes a new {@code JSONPointer} instance. If you want to * evaluate the same JSON Pointer on different JSON documents then it is recommended * to keep the {@code JSONPointer} instances due to performance considerations. - * + * * @param pointer the JSON String or URI Fragment representation of the JSON pointer. * @throws IllegalArgumentException if {@code pointer} is not a valid JSON pointer */ @@ -163,7 +93,7 @@ public class JSONPointer { do { prevSlashIdx = slashIdx + 1; slashIdx = refs.indexOf('/', prevSlashIdx); - if(prevSlashIdx == slashIdx || prevSlashIdx == refs.length()) { + if (prevSlashIdx == slashIdx || prevSlashIdx == refs.length()) { // found 2 slashes in a row ( obj//next ) // or single slash at the end of a string ( obj/test/ ) this.refTokens.add(""); @@ -186,18 +116,79 @@ public class JSONPointer { this.refTokens = new ArrayList(refTokens); } + /** + * Static factory method for {@link Builder}. Example usage: + * + *

+     * JSONPointer pointer = JSONPointer.builder()
+     *       .append("obj")
+     *       .append("other~key").append("another/key")
+     *       .append("\"")
+     *       .append(0)
+     *       .build();
+     * 
+ * + * @return a builder instance which can be used to construct a {@code JSONPointer} instance by chained + * {@link Builder#append(String)} calls. + */ + public static Builder builder() { + return new Builder(); + } + private static String unescape(String token) { return token.replace("~1", "/").replace("~0", "~") .replace("\\\"", "\"") .replace("\\\\", "\\"); } + /** + * Matches a JSONArray element by ordinal position + * + * @param current the JSONArray to be evaluated + * @param indexToken the array index in string form + * @return the matched object. If no matching item is found a + * @throws JSONPointerException is thrown if the index is out of bounds + */ + private static Object readByIndexToken(Object current, String indexToken) throws JSONPointerException { + try { + int index = Integer.parseInt(indexToken); + JSONArray currentArr = (JSONArray) current; + if (index >= currentArr.length()) { + throw new JSONPointerException(format("index %s is out of bounds - the array has %d elements", indexToken, + Integer.valueOf(currentArr.length()))); + } + try { + return currentArr.get(index); + } catch (JSONException e) { + throw new JSONPointerException("Error reading value at index position " + index, e); + } + } catch (NumberFormatException e) { + throw new JSONPointerException(format("%s is not an array index", indexToken), e); + } + } + + /** + * Escapes path segment values to an unambiguous form. + * The escape char to be inserted is '~'. The chars to be escaped + * are ~, which maps to ~0, and /, which maps to ~1. Backslashes + * and double quote chars are also escaped. + * + * @param token the JSONPointer segment value to be escaped + * @return the escaped value for the token + */ + private static String escape(String token) { + return token.replace("~", "~0") + .replace("/", "~1") + .replace("\\", "\\\\") + .replace("\"", "\\\""); + } + /** * Evaluates this JSON Pointer on the given {@code document}. The {@code document} * is usually a {@link JSONObject} or a {@link JSONArray} instance, but the empty * JSON Pointer ({@code ""}) can be evaluated on any JSON values and in such case the - * returned value will be {@code document} itself. - * + * returned value will be {@code document} itself. + * * @param document the JSON document which should be the subject of querying. * @return the result of the evaluation * @throws JSONPointerException if an error occurs during evaluation @@ -221,31 +212,6 @@ public class JSONPointer { return current; } - /** - * Matches a JSONArray element by ordinal position - * @param current the JSONArray to be evaluated - * @param indexToken the array index in string form - * @return the matched object. If no matching item is found a - * @throws JSONPointerException is thrown if the index is out of bounds - */ - private static Object readByIndexToken(Object current, String indexToken) throws JSONPointerException { - try { - int index = Integer.parseInt(indexToken); - JSONArray currentArr = (JSONArray) current; - if (index >= currentArr.length()) { - throw new JSONPointerException(format("index %s is out of bounds - the array has %d elements", indexToken, - Integer.valueOf(currentArr.length()))); - } - try { - return currentArr.get(index); - } catch (JSONException e) { - throw new JSONPointerException("Error reading value at index position " + index, e); - } - } catch (NumberFormatException e) { - throw new JSONPointerException(format("%s is not an array index", indexToken), e); - } - } - /** * Returns a string representing the JSONPointer path value using string * representation @@ -253,27 +219,12 @@ public class JSONPointer { @Override public String toString() { StringBuilder rval = new StringBuilder(""); - for (String token: this.refTokens) { + for (String token : this.refTokens) { rval.append('/').append(escape(token)); } return rval.toString(); } - /** - * Escapes path segment values to an unambiguous form. - * The escape char to be inserted is '~'. The chars to be escaped - * are ~, which maps to ~0, and /, which maps to ~1. Backslashes - * and double quote chars are also escaped. - * @param token the JSONPointer segment value to be escaped - * @return the escaped value for the token - */ - private static String escape(String token) { - return token.replace("~", "~0") - .replace("/", "~1") - .replace("\\", "\\\\") - .replace("\"", "\\\""); - } - /** * Returns a string representing the JSONPointer path value using URI * fragment identifier representation @@ -289,5 +240,55 @@ public class JSONPointer { throw new RuntimeException(e); } } - + + /** + * This class allows the user to build a JSONPointer in steps, using + * exactly one segment in each step. + */ + public static class Builder { + + // Segments for the eventual JSONPointer string + private final List refTokens = new ArrayList(); + + /** + * Creates a {@code JSONPointer} instance using the tokens previously set using the + * {@link #append(String)} method calls. + */ + public JSONPointer build() { + return new JSONPointer(this.refTokens); + } + + /** + * Adds an arbitrary token to the list of reference tokens. It can be any non-null value. + *

+ * Unlike in the case of JSON string or URI fragment representation of JSON pointers, the + * argument of this method MUST NOT be escaped. If you want to query the property called + * {@code "a~b"} then you should simply pass the {@code "a~b"} string as-is, there is no + * need to escape it as {@code "a~0b"}. + * + * @param token the new token to be appended to the list + * @return {@code this} + * @throws NullPointerException if {@code token} is null + */ + public Builder append(String token) { + if (token == null) { + throw new NullPointerException("token cannot be null"); + } + this.refTokens.add(token); + return this; + } + + /** + * Adds an integer to the reference token list. Although not necessarily, mostly this token will + * denote an array index. + * + * @param arrayIndex the array index to be added to the token list + * @return {@code this} + */ + public Builder append(int arrayIndex) { + this.refTokens.add(String.valueOf(arrayIndex)); + return this; + } + } + } diff --git a/src/main/java/json/JSONPointerException.java b/src/main/java/json/JSONPointerException.java index 294d4e3..68eafee 100644 --- a/src/main/java/json/JSONPointerException.java +++ b/src/main/java/json/JSONPointerException.java @@ -27,7 +27,7 @@ SOFTWARE. /** * The JSONPointerException is thrown by {@link JSONPointer} if an error occurs * during evaluating a pointer. - * + * * @author JSON.org * @version 2016-05-13 */ diff --git a/src/main/java/json/JSONPropertyIgnore.java b/src/main/java/json/JSONPropertyIgnore.java index c2b18bd..dd81c36 100644 --- a/src/main/java/json/JSONPropertyIgnore.java +++ b/src/main/java/json/JSONPropertyIgnore.java @@ -40,4 +40,5 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; * present at any level in the class hierarchy, then the method will * not be serialized from the bean into the JSONObject. */ -public @interface JSONPropertyIgnore { } +public @interface JSONPropertyIgnore { +} diff --git a/src/main/java/json/JSONString.java b/src/main/java/json/JSONString.java index dbf7fb2..0a75428 100644 --- a/src/main/java/json/JSONString.java +++ b/src/main/java/json/JSONString.java @@ -1,4 +1,5 @@ package json; + /** * The JSONString interface allows a toJSONString() * method so that a class can change the behavior of diff --git a/src/main/java/json/JSONStringer.java b/src/main/java/json/JSONStringer.java index 46979bb..5b7b0be 100644 --- a/src/main/java/json/JSONStringer.java +++ b/src/main/java/json/JSONStringer.java @@ -53,6 +53,7 @@ import java.io.StringWriter; * you. Objects and arrays can be nested up to 20 levels deep. *

* This can sometimes be easier than using a JSONObject to build a string. + * * @author JSON.org * @version 2015-12-09 */ @@ -70,6 +71,7 @@ public class JSONStringer extends JSONWriter { * problem in the construction of the JSON text (such as the calls to * array were not properly balanced with calls to * endArray). + * * @return The JSON text. */ @Override diff --git a/src/main/java/json/JSONTokener.java b/src/main/java/json/JSONTokener.java index f7f450e..632d1cf 100644 --- a/src/main/java/json/JSONTokener.java +++ b/src/main/java/json/JSONTokener.java @@ -30,37 +30,54 @@ SOFTWARE. * A JSONTokener takes a source string and extracts characters and tokens from * it. It is used by the JSONObject and JSONArray constructors to parse * JSON source strings. + * * @author JSON.org * @version 2014-05-03 */ public class JSONTokener { - /** current read character position on the current line. */ - private long character; - /** flag to indicate if the end of the input has been found. */ - private boolean eof; - /** current read index of the input. */ - private long index; - /** current line of the input. */ - private long line; - /** previous character read from the input. */ - private char previous; - /** Reader for the input. */ + /** + * Reader for the input. + */ private final Reader reader; - /** flag to indicate that a previous character was requested. */ + /** + * current read character position on the current line. + */ + private long character; + /** + * flag to indicate if the end of the input has been found. + */ + private boolean eof; + /** + * current read index of the input. + */ + private long index; + /** + * current line of the input. + */ + private long line; + /** + * previous character read from the input. + */ + private char previous; + /** + * flag to indicate that a previous character was requested. + */ private boolean usePrevious; - /** the number of characters read in the previous line. */ + /** + * the number of characters read in the previous line. + */ private long characterPreviousLine; /** * Construct a JSONTokener from a Reader. The caller must close the Reader. * - * @param reader A reader. + * @param reader A reader. */ public JSONTokener(Reader reader) { this.reader = reader.markSupported() ? reader - : new BufferedReader(reader); + : new BufferedReader(reader); this.eof = false; this.usePrevious = false; this.previous = 0; @@ -73,6 +90,7 @@ public class JSONTokener { /** * Construct a JSONTokener from an InputStream. The caller must close the input stream. + * * @param inputStream The source. */ public JSONTokener(InputStream inputStream) { @@ -83,47 +101,18 @@ public class JSONTokener { /** * Construct a JSONTokener from a string. * - * @param s A source string. + * @param s A source string. */ public JSONTokener(String s) { this(new StringReader(s)); } - - /** - * Back up one character. This provides a sort of lookahead capability, - * so that you can test for a digit or letter before attempting to parse - * the next number or identifier. - * @throws JSONException Thrown if trying to step back more than 1 step - * or if already at the start of the string - */ - public void back() throws JSONException { - if (this.usePrevious || this.index <= 0) { - throw new JSONException("Stepping back two steps is not supported"); - } - this.decrementIndexes(); - this.usePrevious = true; - this.eof = false; - } - - /** - * Decrements the indexes for the {@link #back()} method based on the previous character read. - */ - private void decrementIndexes() { - this.index--; - if(this.previous=='\r' || this.previous == '\n') { - this.line--; - this.character=this.characterPreviousLine ; - } else if(this.character > 0){ - this.character--; - } - } - /** * Get the hex value of a character (base16). + * * @param c A character between '0' and '9' or between 'A' and 'F' or - * between 'a' and 'f'. - * @return An int between 0 and 15, or -1 if c was not a hex digit. + * between 'a' and 'f'. + * @return An int between 0 and 15, or -1 if c was not a hex digit. */ public static int dehexchar(char c) { if (c >= '0' && c <= '9') { @@ -138,9 +127,39 @@ public class JSONTokener { return -1; } + /** + * Back up one character. This provides a sort of lookahead capability, + * so that you can test for a digit or letter before attempting to parse + * the next number or identifier. + * + * @throws JSONException Thrown if trying to step back more than 1 step + * or if already at the start of the string + */ + public void back() throws JSONException { + if (this.usePrevious || this.index <= 0) { + throw new JSONException("Stepping back two steps is not supported"); + } + this.decrementIndexes(); + this.usePrevious = true; + this.eof = false; + } + + /** + * Decrements the indexes for the {@link #back()} method based on the previous character read. + */ + private void decrementIndexes() { + this.index--; + if (this.previous == '\r' || this.previous == '\n') { + this.line--; + this.character = this.characterPreviousLine; + } else if (this.character > 0) { + this.character--; + } + } + /** * Checks if the end of the input has been reached. - * + * * @return true if at the end of the file and we didn't step back */ public boolean end() { @@ -151,12 +170,13 @@ public class JSONTokener { /** * Determine if the source string still contains characters that next() * can consume. + * * @return true if not yet at the end of the source. * @throws JSONException thrown if there is an error stepping forward - * or backward while checking for more data. + * or backward while checking for more data. */ public boolean more() throws JSONException { - if(this.usePrevious) { + if (this.usePrevious) { return true; } try { @@ -166,7 +186,7 @@ public class JSONTokener { } try { // -1 is EOF, but next() can not consume the null character '\0' - if(this.reader.read() <= 0) { + if (this.reader.read() <= 0) { this.eof = true; return false; } @@ -208,21 +228,22 @@ public class JSONTokener { /** * Increments the internal indexes according to the previous character * read and the character passed as the current character. + * * @param c the current character read. */ private void incrementIndexes(int c) { - if(c > 0) { + if (c > 0) { this.index++; - if(c=='\r') { + if (c == '\r') { this.line++; this.characterPreviousLine = this.character; - this.character=0; - }else if (c=='\n') { - if(this.previous != '\r') { + this.character = 0; + } else if (c == '\n') { + if (this.previous != '\r') { this.line++; this.characterPreviousLine = this.character; } - this.character=0; + this.character = 0; } else { this.character++; } @@ -232,6 +253,7 @@ public class JSONTokener { /** * Consume the next character, and check that it matches a specified * character. + * * @param c The character to match. * @return The character. * @throws JSONException if the character does not match. @@ -239,7 +261,7 @@ public class JSONTokener { public char next(char c) throws JSONException { char n = this.next(); if (n != c) { - if(n > 0) { + if (n > 0) { throw this.syntaxError("Expected '" + c + "' and instead saw '" + n + "'"); } @@ -252,11 +274,10 @@ public class JSONTokener { /** * Get the next n characters. * - * @param n The number of characters to take. - * @return A string of n characters. - * @throws JSONException - * Substring bounds error if there are not - * n characters remaining in the source string. + * @param n The number of characters to take. + * @return A string of n characters. + * @throws JSONException Substring bounds error if there are not + * n characters remaining in the source string. */ public String next(int n) throws JSONException { if (n == 0) { @@ -279,11 +300,12 @@ public class JSONTokener { /** * Get the next char in the string, skipping whitespace. + * + * @return A character, or 0 if there are no more characters. * @throws JSONException Thrown if there is an error reading the source string. - * @return A character, or 0 if there are no more characters. */ public char nextClean() throws JSONException { - for (;;) { + for (; ; ) { char c = this.next(); if (c == 0 || c > ' ') { return c; @@ -297,62 +319,63 @@ public class JSONTokener { * Backslash processing is done. The formal JSON format does not * allow strings in single quotes, but an implementation is allowed to * accept them. + * * @param quote The quoting character, either - * " (double quote) or - * ' (single quote). - * @return A String. + * " (double quote) or + * ' (single quote). + * @return A String. * @throws JSONException Unterminated string. */ public String nextString(char quote) throws JSONException { char c; StringBuilder sb = new StringBuilder(); - for (;;) { + 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': - try { - sb.append((char)Integer.parseInt(this.next(4), 16)); - } catch (NumberFormatException e) { - throw this.syntaxError("Illegal escape.", e); + 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': + try { + sb.append((char) Integer.parseInt(this.next(4), 16)); + } catch (NumberFormatException e) { + throw this.syntaxError("Illegal escape.", e); + } + break; + case '"': + case '\'': + case '\\': + case '/': + sb.append(c); + break; + default: + throw this.syntaxError("Illegal escape."); } 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); + if (c == quote) { + return sb.toString(); + } + sb.append(c); } } } @@ -361,14 +384,15 @@ public class JSONTokener { /** * Get the text up but not including the specified character or the * end of line, whichever comes first. - * @param delimiter A delimiter character. - * @return A string. + * + * @param delimiter A delimiter character. + * @return A string. * @throws JSONException Thrown if there is an error while searching - * for the delimiter + * for the delimiter */ public String nextTo(char delimiter) throws JSONException { StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { char c = this.next(); if (c == delimiter || c == 0 || c == '\n' || c == '\r') { if (c != 0) { @@ -384,15 +408,16 @@ public class JSONTokener { /** * Get the text up but not including one of the specified delimiter * characters or the end of line, whichever comes first. + * * @param delimiters A set of delimiter characters. * @return A string, trimmed. * @throws JSONException Thrown if there is an error while searching - * for the delimiter + * for the delimiter */ public String nextTo(String delimiters) throws JSONException { char c; StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { c = this.next(); if (delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r') { @@ -409,24 +434,24 @@ public class JSONTokener { /** * Get the next value. The value can be a Boolean, Double, Integer, * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. - * @throws JSONException If syntax error. * * @return An object. + * @throws JSONException If syntax error. */ 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); + case '"': + case '\'': + return this.nextString(c); + case '{': + this.back(); + return new JSONObject(this); + case '[': + this.back(); + return new JSONArray(this); } /* @@ -458,11 +483,12 @@ public class JSONTokener { /** * Skip characters until the next character is the requested character. * If the requested character is not found, no characters are skipped. + * * @param to A character to skip to. * @return The requested character, or zero if the requested character * is not found. * @throws JSONException Thrown if there is an error while searching - * for the to character + * for the to character */ public char skipTo(char to) throws JSONException { char c; @@ -496,7 +522,7 @@ public class JSONTokener { * Make a JSONException to signal a syntax error. * * @param message The error message. - * @return A JSONException object, suitable for throwing + * @return A JSONException object, suitable for throwing */ public JSONException syntaxError(String message) { return new JSONException(message + this.toString()); @@ -505,9 +531,9 @@ public class JSONTokener { /** * Make a JSONException to signal a syntax error. * - * @param message The error message. + * @param message The error message. * @param causedBy The throwable that caused the error. - * @return A JSONException object, suitable for throwing + * @return A JSONException object, suitable for throwing */ public JSONException syntaxError(String message, Throwable causedBy) { return new JSONException(message + this.toString(), causedBy); diff --git a/src/main/java/json/JSONWriter.java b/src/main/java/json/JSONWriter.java index 1576383..044b4ed 100644 --- a/src/main/java/json/JSONWriter.java +++ b/src/main/java/json/JSONWriter.java @@ -54,18 +54,16 @@ SOFTWARE. * you. Objects and arrays can be nested up to 200 levels deep. *

* This can sometimes be easier than using a JSONObject to build a string. + * * @author JSON.org * @version 2016-08-08 */ public class JSONWriter { private static final int maxdepth = 200; - /** - * The comma flag determines if a comma should be output before the next - * value. + * The object/array stack. */ - private boolean comma; - + private final JSONObject stack[]; /** * The current mode. Values: * 'a' (array), @@ -75,21 +73,19 @@ public class JSONWriter { * 'o' (object). */ protected char mode; - - /** - * The object/array stack. - */ - private final JSONObject stack[]; - - /** - * The stack top index. A value of 0 indicates that the stack is empty. - */ - private int top; - /** * The writer that will receive the output. */ protected Appendable writer; + /** + * The comma flag determines if a comma should be output before the next + * value. + */ + private boolean comma; + /** + * The stack top index. A value of 0 indicates that the stack is empty. + */ + private int top; /** * Make a fresh JSONWriter. It can be used to build one JSON text. @@ -102,200 +98,6 @@ public class JSONWriter { this.writer = w; } - /** - * Append a value. - * @param string A string value. - * @return this - * @throws JSONException If the value is out of sequence. - */ - private JSONWriter append(String string) throws JSONException { - if (string == null) { - throw new JSONException("Null pointer"); - } - if (this.mode == 'o' || this.mode == 'a') { - try { - if (this.comma && this.mode == 'a') { - this.writer.append(','); - } - this.writer.append(string); - } catch (IOException e) { - // Android as of API 25 does not support this exception constructor - // however we won't worry about it. If an exception is happening here - // it will just throw a "Method not found" exception instead. - throw new JSONException(e); - } - if (this.mode == 'o') { - this.mode = 'k'; - } - this.comma = true; - return this; - } - throw new JSONException("Value out of sequence."); - } - - /** - * Begin appending a new array. All values until the balancing - * endArray will be appended to this array. The - * endArray method must be called to mark the array's end. - * @return this - * @throws JSONException If the nesting is too deep, or if the object is - * started in the wrong place (for example as a key or after the end of the - * outermost array or object). - */ - public JSONWriter array() throws JSONException { - if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { - this.push(null); - this.append("["); - this.comma = false; - return this; - } - throw new JSONException("Misplaced array."); - } - - /** - * End something. - * @param m Mode - * @param c Closing character - * @return this - * @throws JSONException If unbalanced. - */ - private JSONWriter end(char m, char c) throws JSONException { - if (this.mode != m) { - throw new JSONException(m == 'a' - ? "Misplaced endArray." - : "Misplaced endObject."); - } - this.pop(m); - try { - this.writer.append(c); - } catch (IOException e) { - // Android as of API 25 does not support this exception constructor - // however we won't worry about it. If an exception is happening here - // it will just throw a "Method not found" exception instead. - throw new JSONException(e); - } - this.comma = true; - return this; - } - - /** - * End an array. This method most be called to balance calls to - * array. - * @return this - * @throws JSONException If incorrectly nested. - */ - public JSONWriter endArray() throws JSONException { - return this.end('a', ']'); - } - - /** - * End an object. This method most be called to balance calls to - * object. - * @return this - * @throws JSONException If incorrectly nested. - */ - public JSONWriter endObject() throws JSONException { - return this.end('k', '}'); - } - - /** - * Append a key. The key will be associated with the next value. In an - * object, every value must be preceded by a key. - * @param string A key string. - * @return this - * @throws JSONException If the key is out of place. For example, keys - * do not belong in arrays or if the key is null. - */ - public JSONWriter key(String string) throws JSONException { - if (string == null) { - throw new JSONException("Null key."); - } - if (this.mode == 'k') { - try { - JSONObject topObject = this.stack[this.top - 1]; - // don't use the built in putOnce method to maintain Android support - if(topObject.has(string)) { - throw new JSONException("Duplicate key \"" + string + "\""); - } - topObject.put(string, true); - if (this.comma) { - this.writer.append(','); - } - this.writer.append(JSONObject.quote(string)); - this.writer.append(':'); - this.comma = false; - this.mode = 'o'; - return this; - } catch (IOException e) { - // Android as of API 25 does not support this exception constructor - // however we won't worry about it. If an exception is happening here - // it will just throw a "Method not found" exception instead. - throw new JSONException(e); - } - } - throw new JSONException("Misplaced key."); - } - - - /** - * Begin appending a new object. All keys and values until the balancing - * endObject will be appended to this object. The - * endObject method must be called to mark the object's end. - * @return this - * @throws JSONException If the nesting is too deep, or if the object is - * started in the wrong place (for example as a key or after the end of the - * outermost array or object). - */ - public JSONWriter object() throws JSONException { - if (this.mode == 'i') { - this.mode = 'o'; - } - if (this.mode == 'o' || this.mode == 'a') { - this.append("{"); - this.push(new JSONObject()); - this.comma = false; - return this; - } - throw new JSONException("Misplaced object."); - - } - - - /** - * Pop an array or object scope. - * @param c The scope to close. - * @throws JSONException If nesting is wrong. - */ - private void pop(char c) throws JSONException { - if (this.top <= 0) { - throw new JSONException("Nesting error."); - } - char m = this.stack[this.top - 1] == null ? 'a' : 'k'; - if (m != c) { - throw new JSONException("Nesting error."); - } - this.top -= 1; - this.mode = this.top == 0 - ? 'd' - : this.stack[this.top - 1] == null - ? 'a' - : 'k'; - } - - /** - * Push an array or object scope. - * @param jo The scope to open. - * @throws JSONException If nesting is too deep. - */ - private void push(JSONObject jo) throws JSONException { - if (this.top >= maxdepth) { - throw new JSONException("Nesting too deep."); - } - this.stack[this.top] = jo; - this.mode = jo == null ? 'a' : 'k'; - this.top += 1; - } - /** * Make a JSON text of an Object value. If the object has an * value.toJSONString() method, then that method will be used to produce the @@ -311,14 +113,12 @@ public class JSONWriter { *

* Warning: This method assumes that the data structure is acyclical. * - * @param value - * The value to be serialized. + * @param value The value to be serialized. * @return a printable, displayable, transmittable representation of the - * object, beginning with { (left - * brace) and ending with } (right - * brace). - * @throws JSONException - * If the value is or contains an invalid number. + * object, beginning with { (left + * brace) and ending with } (right + * brace). + * @throws JSONException If the value is or contains an invalid number. */ public static String valueToString(Object value) throws JSONException { if (value == null || value.equals(null)) { @@ -339,7 +139,7 @@ public class JSONWriter { if (value instanceof Number) { // not all Numbers may match actual JSON Numbers. i.e. Fractions or Complex final String numberAsString = JSONObject.numberToString((Number) value); - if(JSONObject.NUMBER_PATTERN.matcher(numberAsString).matches()) { + if (JSONObject.NUMBER_PATTERN.matcher(numberAsString).matches()) { // Close enough to a JSON number that we will return it unquoted return numberAsString; } @@ -362,15 +162,217 @@ public class JSONWriter { if (value.getClass().isArray()) { return new JSONArray(value).toString(); } - if(value instanceof Enum){ - return JSONObject.quote(((Enum)value).name()); + if (value instanceof Enum) { + return JSONObject.quote(((Enum) value).name()); } return JSONObject.quote(value.toString()); } + /** + * Append a value. + * + * @param string A string value. + * @return this + * @throws JSONException If the value is out of sequence. + */ + private JSONWriter append(String string) throws JSONException { + if (string == null) { + throw new JSONException("Null pointer"); + } + if (this.mode == 'o' || this.mode == 'a') { + try { + if (this.comma && this.mode == 'a') { + this.writer.append(','); + } + this.writer.append(string); + } catch (IOException e) { + // Android as of API 25 does not support this exception constructor + // however we won't worry about it. If an exception is happening here + // it will just throw a "Method not found" exception instead. + throw new JSONException(e); + } + if (this.mode == 'o') { + this.mode = 'k'; + } + this.comma = true; + return this; + } + throw new JSONException("Value out of sequence."); + } + + /** + * Begin appending a new array. All values until the balancing + * endArray will be appended to this array. The + * endArray method must be called to mark the array's end. + * + * @return this + * @throws JSONException If the nesting is too deep, or if the object is + * started in the wrong place (for example as a key or after the end of the + * outermost array or object). + */ + public JSONWriter array() throws JSONException { + if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { + this.push(null); + this.append("["); + this.comma = false; + return this; + } + throw new JSONException("Misplaced array."); + } + + /** + * End something. + * + * @param m Mode + * @param c Closing character + * @return this + * @throws JSONException If unbalanced. + */ + private JSONWriter end(char m, char c) throws JSONException { + if (this.mode != m) { + throw new JSONException(m == 'a' + ? "Misplaced endArray." + : "Misplaced endObject."); + } + this.pop(m); + try { + this.writer.append(c); + } catch (IOException e) { + // Android as of API 25 does not support this exception constructor + // however we won't worry about it. If an exception is happening here + // it will just throw a "Method not found" exception instead. + throw new JSONException(e); + } + this.comma = true; + return this; + } + + /** + * End an array. This method most be called to balance calls to + * array. + * + * @return this + * @throws JSONException If incorrectly nested. + */ + public JSONWriter endArray() throws JSONException { + return this.end('a', ']'); + } + + /** + * End an object. This method most be called to balance calls to + * object. + * + * @return this + * @throws JSONException If incorrectly nested. + */ + public JSONWriter endObject() throws JSONException { + return this.end('k', '}'); + } + + /** + * Append a key. The key will be associated with the next value. In an + * object, every value must be preceded by a key. + * + * @param string A key string. + * @return this + * @throws JSONException If the key is out of place. For example, keys + * do not belong in arrays or if the key is null. + */ + public JSONWriter key(String string) throws JSONException { + if (string == null) { + throw new JSONException("Null key."); + } + if (this.mode == 'k') { + try { + JSONObject topObject = this.stack[this.top - 1]; + // don't use the built in putOnce method to maintain Android support + if (topObject.has(string)) { + throw new JSONException("Duplicate key \"" + string + "\""); + } + topObject.put(string, true); + if (this.comma) { + this.writer.append(','); + } + this.writer.append(JSONObject.quote(string)); + this.writer.append(':'); + this.comma = false; + this.mode = 'o'; + return this; + } catch (IOException e) { + // Android as of API 25 does not support this exception constructor + // however we won't worry about it. If an exception is happening here + // it will just throw a "Method not found" exception instead. + throw new JSONException(e); + } + } + throw new JSONException("Misplaced key."); + } + + /** + * Begin appending a new object. All keys and values until the balancing + * endObject will be appended to this object. The + * endObject method must be called to mark the object's end. + * + * @return this + * @throws JSONException If the nesting is too deep, or if the object is + * started in the wrong place (for example as a key or after the end of the + * outermost array or object). + */ + public JSONWriter object() throws JSONException { + if (this.mode == 'i') { + this.mode = 'o'; + } + if (this.mode == 'o' || this.mode == 'a') { + this.append("{"); + this.push(new JSONObject()); + this.comma = false; + return this; + } + throw new JSONException("Misplaced object."); + + } + + /** + * Pop an array or object scope. + * + * @param c The scope to close. + * @throws JSONException If nesting is wrong. + */ + private void pop(char c) throws JSONException { + if (this.top <= 0) { + throw new JSONException("Nesting error."); + } + char m = this.stack[this.top - 1] == null ? 'a' : 'k'; + if (m != c) { + throw new JSONException("Nesting error."); + } + this.top -= 1; + this.mode = this.top == 0 + ? 'd' + : this.stack[this.top - 1] == null + ? 'a' + : 'k'; + } + + /** + * Push an array or object scope. + * + * @param jo The scope to open. + * @throws JSONException If nesting is too deep. + */ + private void push(JSONObject jo) throws JSONException { + if (this.top >= maxdepth) { + throw new JSONException("Nesting too deep."); + } + this.stack[this.top] = jo; + this.mode = jo == null ? 'a' : 'k'; + this.top += 1; + } + /** * Append either the value true or the value * false. + * * @param b A boolean. * @return this * @throws JSONException @@ -381,6 +383,7 @@ public class JSONWriter { /** * Append a double value. + * * @param d A double. * @return this * @throws JSONException If the number is not finite. @@ -391,6 +394,7 @@ public class JSONWriter { /** * Append a long value. + * * @param l A long. * @return this * @throws JSONException @@ -402,8 +406,9 @@ public class JSONWriter { /** * Append an object value. + * * @param object The object to append. It can be null, or a Boolean, Number, - * String, JSONObject, or JSONArray, or an object that implements JSONString. + * String, JSONObject, or JSONArray, or an object that implements JSONString. * @return this * @throws JSONException If the value is out of sequence. */ diff --git a/target/classes/com/io/yutian/livemutually/liveroom/Chat.class b/target/classes/com/io/yutian/livemutually/liveroom/Chat.class index 4ea9b4d..e7ce687 100644 Binary files a/target/classes/com/io/yutian/livemutually/liveroom/Chat.class and b/target/classes/com/io/yutian/livemutually/liveroom/Chat.class differ diff --git a/target/classes/com/io/yutian/livemutually/liveroom/Follow.class b/target/classes/com/io/yutian/livemutually/liveroom/Follow.class index c1def0c..c553d24 100644 Binary files a/target/classes/com/io/yutian/livemutually/liveroom/Follow.class and b/target/classes/com/io/yutian/livemutually/liveroom/Follow.class differ diff --git a/target/classes/com/io/yutian/livemutually/liveroom/Like.class b/target/classes/com/io/yutian/livemutually/liveroom/Like.class index 9bad31e..f5ae478 100644 Binary files a/target/classes/com/io/yutian/livemutually/liveroom/Like.class and b/target/classes/com/io/yutian/livemutually/liveroom/Like.class differ diff --git a/target/classes/com/io/yutian/livemutually/liveroom/LiveRoomWatcher.class b/target/classes/com/io/yutian/livemutually/liveroom/LiveRoomWatcher.class index e8b3ff2..de12657 100644 Binary files a/target/classes/com/io/yutian/livemutually/liveroom/LiveRoomWatcher.class and b/target/classes/com/io/yutian/livemutually/liveroom/LiveRoomWatcher.class differ diff --git a/target/classes/com/io/yutian/livemutually/liveroom/User.class b/target/classes/com/io/yutian/livemutually/liveroom/User.class index 40bccba..7623357 100644 Binary files a/target/classes/com/io/yutian/livemutually/liveroom/User.class and b/target/classes/com/io/yutian/livemutually/liveroom/User.class differ diff --git a/target/classes/com/io/yutian/livemutually/manager/KSLiveRoomManager.class b/target/classes/com/io/yutian/livemutually/manager/KSLiveRoomManager.class index 86ac787..dfb5f8a 100644 Binary files a/target/classes/com/io/yutian/livemutually/manager/KSLiveRoomManager.class and b/target/classes/com/io/yutian/livemutually/manager/KSLiveRoomManager.class differ diff --git a/target/classes/com/io/yutian/livemutually/wss/KSAPILiveRoomWatcher.class b/target/classes/com/io/yutian/livemutually/wss/KSAPILiveRoomWatcher.class index 01fe355..f8819cb 100644 Binary files a/target/classes/com/io/yutian/livemutually/wss/KSAPILiveRoomWatcher.class and b/target/classes/com/io/yutian/livemutually/wss/KSAPILiveRoomWatcher.class differ diff --git a/target/classes/com/io/yutian/livemutually/wss/KuaiShouChat.class b/target/classes/com/io/yutian/livemutually/wss/KuaiShouChat.class index afb66a6..07e8d9d 100644 Binary files a/target/classes/com/io/yutian/livemutually/wss/KuaiShouChat.class and b/target/classes/com/io/yutian/livemutually/wss/KuaiShouChat.class differ diff --git a/target/classes/com/io/yutian/livemutually/wss/KuaiShouLike.class b/target/classes/com/io/yutian/livemutually/wss/KuaiShouLike.class index aca5146..01e8038 100644 Binary files a/target/classes/com/io/yutian/livemutually/wss/KuaiShouLike.class and b/target/classes/com/io/yutian/livemutually/wss/KuaiShouLike.class differ diff --git a/target/classes/com/io/yutian/livemutually/wss/KuaiShouUser.class b/target/classes/com/io/yutian/livemutually/wss/KuaiShouUser.class index 2fcee99..4646905 100644 Binary files a/target/classes/com/io/yutian/livemutually/wss/KuaiShouUser.class and b/target/classes/com/io/yutian/livemutually/wss/KuaiShouUser.class differ diff --git a/target/classes/com/io/yutian/mclive/Main.class b/target/classes/com/io/yutian/mclive/Main.class index b1cea0e..0173846 100644 Binary files a/target/classes/com/io/yutian/mclive/Main.class and b/target/classes/com/io/yutian/mclive/Main.class differ diff --git a/target/classes/com/io/yutian/mclive/event/LiveChatEvents.class b/target/classes/com/io/yutian/mclive/event/LiveChatEvents.class index 8f9fa30..fffe719 100644 Binary files a/target/classes/com/io/yutian/mclive/event/LiveChatEvents.class and b/target/classes/com/io/yutian/mclive/event/LiveChatEvents.class differ diff --git a/target/classes/com/io/yutian/mclive/event/LiveEnterEvents.class b/target/classes/com/io/yutian/mclive/event/LiveEnterEvents.class index 8577bd3..2b22494 100644 Binary files a/target/classes/com/io/yutian/mclive/event/LiveEnterEvents.class and b/target/classes/com/io/yutian/mclive/event/LiveEnterEvents.class differ diff --git a/target/classes/com/io/yutian/mclive/event/LiveFollowEvents.class b/target/classes/com/io/yutian/mclive/event/LiveFollowEvents.class index 4421290..963ecb2 100644 Binary files a/target/classes/com/io/yutian/mclive/event/LiveFollowEvents.class and b/target/classes/com/io/yutian/mclive/event/LiveFollowEvents.class differ diff --git a/target/classes/com/io/yutian/mclive/event/LiveGiftEvents.class b/target/classes/com/io/yutian/mclive/event/LiveGiftEvents.class index fb71780..9e27727 100644 Binary files a/target/classes/com/io/yutian/mclive/event/LiveGiftEvents.class and b/target/classes/com/io/yutian/mclive/event/LiveGiftEvents.class differ diff --git a/target/classes/com/io/yutian/mclive/event/LiveLikeEvents.class b/target/classes/com/io/yutian/mclive/event/LiveLikeEvents.class index 6e5bfdc..111588d 100644 Binary files a/target/classes/com/io/yutian/mclive/event/LiveLikeEvents.class and b/target/classes/com/io/yutian/mclive/event/LiveLikeEvents.class differ diff --git a/target/classes/com/io/yutian/mclive/event/ZhuboAPI.class b/target/classes/com/io/yutian/mclive/event/ZhuboAPI.class index 8c67c76..e98bc97 100644 Binary files a/target/classes/com/io/yutian/mclive/event/ZhuboAPI.class and b/target/classes/com/io/yutian/mclive/event/ZhuboAPI.class differ diff --git a/target/classes/com/io/yutian/verify/AESUtil.class b/target/classes/com/io/yutian/verify/AESUtil.class index 9ce7a3a..f5c58ae 100644 Binary files a/target/classes/com/io/yutian/verify/AESUtil.class and b/target/classes/com/io/yutian/verify/AESUtil.class differ diff --git a/target/classes/com/io/yutian/verify/PluginVerifyResult.class b/target/classes/com/io/yutian/verify/PluginVerifyResult.class index d483c3d..61010ce 100644 Binary files a/target/classes/com/io/yutian/verify/PluginVerifyResult.class and b/target/classes/com/io/yutian/verify/PluginVerifyResult.class differ diff --git a/target/classes/com/io/yutian/verify/VerifyHandler.class b/target/classes/com/io/yutian/verify/VerifyHandler.class index a20f5e7..0562ac7 100644 Binary files a/target/classes/com/io/yutian/verify/VerifyHandler.class and b/target/classes/com/io/yutian/verify/VerifyHandler.class differ diff --git a/target/classes/json/JSONArray.class b/target/classes/json/JSONArray.class index 1564b0f..248b38a 100644 Binary files a/target/classes/json/JSONArray.class and b/target/classes/json/JSONArray.class differ diff --git a/target/classes/json/JSONException.class b/target/classes/json/JSONException.class index a12d327..0e19e22 100644 Binary files a/target/classes/json/JSONException.class and b/target/classes/json/JSONException.class differ diff --git a/target/classes/json/JSONObject$Null.class b/target/classes/json/JSONObject$Null.class index 2a408e7..9c6a784 100644 Binary files a/target/classes/json/JSONObject$Null.class and b/target/classes/json/JSONObject$Null.class differ diff --git a/target/classes/json/JSONObject.class b/target/classes/json/JSONObject.class index 246e34d..eeaf6c3 100644 Binary files a/target/classes/json/JSONObject.class and b/target/classes/json/JSONObject.class differ diff --git a/target/classes/json/JSONPointer$Builder.class b/target/classes/json/JSONPointer$Builder.class index 8c00583..c5621b7 100644 Binary files a/target/classes/json/JSONPointer$Builder.class and b/target/classes/json/JSONPointer$Builder.class differ diff --git a/target/classes/json/JSONPointer.class b/target/classes/json/JSONPointer.class index 6852361..73e5045 100644 Binary files a/target/classes/json/JSONPointer.class and b/target/classes/json/JSONPointer.class differ diff --git a/target/classes/json/JSONPointerException.class b/target/classes/json/JSONPointerException.class index f7d9c66..9d0242e 100644 Binary files a/target/classes/json/JSONPointerException.class and b/target/classes/json/JSONPointerException.class differ diff --git a/target/classes/json/JSONPropertyIgnore.class b/target/classes/json/JSONPropertyIgnore.class index 5e092d5..5e2afb6 100644 Binary files a/target/classes/json/JSONPropertyIgnore.class and b/target/classes/json/JSONPropertyIgnore.class differ diff --git a/target/classes/json/JSONPropertyName.class b/target/classes/json/JSONPropertyName.class index 6fae440..fad21d5 100644 Binary files a/target/classes/json/JSONPropertyName.class and b/target/classes/json/JSONPropertyName.class differ diff --git a/target/classes/json/JSONString.class b/target/classes/json/JSONString.class index 2ca4132..45cd76d 100644 Binary files a/target/classes/json/JSONString.class and b/target/classes/json/JSONString.class differ diff --git a/target/classes/json/JSONStringer.class b/target/classes/json/JSONStringer.class index ab5b7d5..f797072 100644 Binary files a/target/classes/json/JSONStringer.class and b/target/classes/json/JSONStringer.class differ diff --git a/target/classes/json/JSONTokener.class b/target/classes/json/JSONTokener.class index 5ca4c55..5b426bf 100644 Binary files a/target/classes/json/JSONTokener.class and b/target/classes/json/JSONTokener.class differ diff --git a/target/classes/json/JSONWriter.class b/target/classes/json/JSONWriter.class index ffb752b..9afad21 100644 Binary files a/target/classes/json/JSONWriter.class and b/target/classes/json/JSONWriter.class differ