diff --git a/pom.xml b/pom.xml index 92b9015..3ef792c 100644 --- a/pom.xml +++ b/pom.xml @@ -102,12 +102,6 @@ 1.8.8 provided - - com.h2database - h2 - 2.1.214 - provided - org.github.spigot 1.7.10 diff --git a/src/main/java/dev/brighten/ac/Anticheat.java b/src/main/java/dev/brighten/ac/Anticheat.java index 8f33cc5..7bed4d6 100644 --- a/src/main/java/dev/brighten/ac/Anticheat.java +++ b/src/main/java/dev/brighten/ac/Anticheat.java @@ -45,7 +45,6 @@ import java.util.concurrent.atomic.AtomicLong; @Init //@MavenLibrary(groupId = "co.aikar", artifactId = "acf-bukkit", version = "0.5.1", repo = @Repository(url = "https://nexus.funkemunky.cc/content/repositories/releases/")) @MavenLibrary(groupId = "com.google.guava", artifactId = "guava", version = "21.0", repo = @Repository(url = "https://repo1.maven.org/maven2")) -@MavenLibrary(groupId = "com.h2database", artifactId = "h2", version = "2.1.214", repo = @Repository(url = "https://repo1.maven.org/maven2")) @MavenLibrary(groupId = "it.unimi.dsi", artifactId = "fastutil", version = "8.5.6", repo = @Repository(url = "https://repo1.maven.org/maven2")) @MavenLibrary(groupId = "org.ow2.asm", artifactId = "asm", version = "9.2", repo = @Repository(url = "https://repo1.maven.org/maven2")) @MavenLibrary(groupId = "org.ow2.asm", artifactId = "asm-tree", version = "9.2", repo = @Repository(url = "https://repo1.maven.org/maven2")) diff --git a/src/main/java/dev/brighten/ac/check/Check.java b/src/main/java/dev/brighten/ac/check/Check.java index cea811b..03cf531 100644 --- a/src/main/java/dev/brighten/ac/check/Check.java +++ b/src/main/java/dev/brighten/ac/check/Check.java @@ -128,6 +128,26 @@ public class Check implements ECheck { } } + static List devComponents = new ArrayList<>(), components = new ArrayList<>(); + static { + + for (BaseComponent dev : new ComponentBuilder("[").color(ChatColor.DARK_GRAY).append("Dev") + .color(ChatColor.RED).append("]").color(ChatColor.DARK_GRAY).create()) { + devComponents.add((TextComponent)dev); + } + + BaseComponent[] textComp = new ComponentBuilder("[").color(ChatColor.DARK_GRAY).append("!") + .color(ChatColor.DARK_RED).append("]").color(ChatColor.DARK_GRAY).append(" %player%") + .color(ChatColor.WHITE).append(" flagged").color(ChatColor.GRAY).append(" %check%") + .color(ChatColor.WHITE).append(" (").color(ChatColor.DARK_GRAY).append("x%vl%") + .color(ChatColor.YELLOW).append(")").color(ChatColor.DARK_GRAY).create(); + + for (BaseComponent bc : textComp) { + devComponents.add(new TextComponent((TextComponent)bc)); + components.add(new TextComponent((TextComponent)bc)); + } + } + public void flag(String information, Object... variables) { flag(true, information, variables); } @@ -135,11 +155,11 @@ public class Check implements ECheck { public void flag(boolean punish, String information, Object... variables) { vl++; if(System.currentTimeMillis() - lastFlagRun < 50L) return; + lastFlagRun = System.currentTimeMillis(); Anticheat.INSTANCE.getScheduler().execute(() -> { if(Anticheat.INSTANCE.getTps() < 18) vl = 0; - lastFlagRun = System.currentTimeMillis(); final String info = String.format(information, variables); @@ -156,38 +176,41 @@ public class Check implements ECheck { .execute(() -> Anticheat.INSTANCE.getLogManager() .insertLog(player, checkData, vl, System.currentTimeMillis(), info)); - boolean dev = Anticheat.INSTANCE.getTps() < 18; - //if(vl > 0) Anticheat.INSTANCE.loggerManager.addLog(player, this, info); + if(lastAlert.isPassed(200L)) { + boolean dev = Anticheat.INSTANCE.getTps() < 18; + //if(vl > 0) Anticheat.INSTANCE.loggerManager.addLog(player, this, info); - //Sending Discord webhook alert + //Sending Discord webhook alert - List components = new ArrayList<>(); + List toSend = new ArrayList<>(); - if(dev) { - components.add(new TextComponent(createTxt("&8[&cDev&8] "))); - } - val text = createTxt("&8[&4!&8] &f%player% &7flagged &f%check%" + - " &8(&ex%vl%&8)", info); + for (TextComponent tc : components) { + TextComponent ntc = new TextComponent(tc); + ntc.setText(formatAlert(tc.getText(), info)); - text.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[] { - createTxt("&eDescription&8: &f%desc%" + - "\n&eInfo: &f%info%\n&r\n&7&oClick to teleport to player.", info)})); + ntc.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder("Description:") + .color(ChatColor.YELLOW) + .append(formatAlert(" %desc%\n", info)).color(ChatColor.WHITE).append("Info:") + .color(ChatColor.YELLOW) + .append(formatAlert(" %info%\n", info)).color(ChatColor.WHITE) + .append("\n").append("Click to teleport to player") + .create())); + ntc.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, + addPlaceHolders(CheckConfig.clickCommand))); - text.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, CheckConfig.clickCommand)); + toSend.add(ntc); + } - components.add(text); - - TextComponent[] toSend = components.toArray(new TextComponent[0]); - - for (UUID uuid : alertsEnabled) { - Anticheat.INSTANCE.getPlayerRegistry().getPlayer(uuid) - .ifPresent(apl -> apl.getBukkitPlayer().spigot().sendMessage(toSend)); - } - - if(punish && vl > punishVl) { - punish(); - } - lastAlert.reset(); + for (UUID uuid : alertsEnabled) { + Anticheat.INSTANCE.getPlayerRegistry().getPlayer(uuid) + .ifPresent(apl -> apl.getBukkitPlayer().spigot().sendMessage(toSend + .toArray(new BaseComponent[0]))); + } + lastAlert.reset(); + } + if(punish && vl > punishVl) { + punish(); + } }); } diff --git a/src/main/java/dev/brighten/ac/check/impl/movement/nofall/NoFallA.java b/src/main/java/dev/brighten/ac/check/impl/movement/nofall/NoFallA.java index 8a6201d..2a6589d 100644 --- a/src/main/java/dev/brighten/ac/check/impl/movement/nofall/NoFallA.java +++ b/src/main/java/dev/brighten/ac/check/impl/movement/nofall/NoFallA.java @@ -1,12 +1,11 @@ package dev.brighten.ac.check.impl.movement.nofall; -import dev.brighten.ac.check.WAction; +import dev.brighten.ac.api.check.CheckType; import dev.brighten.ac.check.Check; import dev.brighten.ac.check.CheckData; -import dev.brighten.ac.api.check.CheckType; +import dev.brighten.ac.check.WAction; import dev.brighten.ac.data.APlayer; import dev.brighten.ac.packet.wrapper.in.WPacketPlayInFlying; -import dev.brighten.ac.utils.annotation.Async; @CheckData(name = "NoFall (A)", checkId = "nofalla", type = CheckType.MOVEMENT) public class NoFallA extends Check { @@ -18,14 +17,13 @@ public class NoFallA extends Check { private static double divisor = 1. / 64.; private float buffer; - @Async WAction flying = packet -> { - if(player.getInfo().isGeneralCancel() + if(!packet.isMoved() + || player.getInfo().isGeneralCancel() || (player.getMovement().getDeltaXZ() == 0 && player.getMovement().getDeltaY() == 0) || player.getBlockInfo().inLiquid || player.getInfo().velocity.isNotPassed(1) - || player.getMovement().getLastTeleport().isNotPassed(1) - || !packet.isMoved()) { + || player.getMovement().getLastTeleport().isNotPassed(1)) { if(buffer > 0) buffer-= 0.5f; return; } diff --git a/src/main/java/dev/brighten/ac/check/impl/movement/speed/Horizontal.java b/src/main/java/dev/brighten/ac/check/impl/movement/speed/Horizontal.java index e9a3c3a..f6e7544 100644 --- a/src/main/java/dev/brighten/ac/check/impl/movement/speed/Horizontal.java +++ b/src/main/java/dev/brighten/ac/check/impl/movement/speed/Horizontal.java @@ -258,7 +258,6 @@ public class Horizontal extends Check { buffer = Math.min(3.5f, buffer); //Ensuring we don't have a run-away buffer flag("smallest=%s b=%.1f to=%s dxz=%.2f", smallestDelta, buffer, player.getMovement().getTo().getLoc(), player.getMovement().getDeltaXZ()); - cancel(); } else debug("bad movement"); } else if (buffer > 0) buffer -= 0.05f; diff --git a/src/main/java/dev/brighten/ac/check/impl/movement/speed/Speed.java b/src/main/java/dev/brighten/ac/check/impl/movement/speed/Speed.java deleted file mode 100644 index 82b3c8e..0000000 --- a/src/main/java/dev/brighten/ac/check/impl/movement/speed/Speed.java +++ /dev/null @@ -1,153 +0,0 @@ -package dev.brighten.ac.check.impl.movement.speed; - -import dev.brighten.ac.api.check.CheckType; -import dev.brighten.ac.check.Check; -import dev.brighten.ac.check.CheckData; -import dev.brighten.ac.check.WAction; -import dev.brighten.ac.data.APlayer; -import dev.brighten.ac.packet.ProtocolVersion; -import dev.brighten.ac.packet.wrapper.in.WPacketPlayInFlying; -import dev.brighten.ac.utils.*; -import dev.brighten.ac.utils.math.IntVector; -import dev.brighten.ac.utils.wrapper.Wrapper; -import org.bukkit.potion.PotionEffectType; - -import java.util.Comparator; -import java.util.List; -import java.util.stream.Collectors; - -@CheckData(name = "Speed", checkId = "speed", type = CheckType.MOVEMENT) -public class Speed extends Check { - - public Speed(APlayer player) { - super(player); - } - private float buffer; - private boolean previousFromGround; - - WAction flyingPacket = packet -> { - if(player.getMovement().isExcuseNextFlying()) return; - checkProccesing: - { - if (!packet.isMoved()) - break checkProccesing; - - IntVector belowLoc = new IntVector(MathHelper.floor_double(player.getMovement().getFrom().getX()), - MathHelper.floor_double(player.getMovement().getFrom().getY() - 1), - MathHelper.floor_double(player.getMovement().getFrom().getZ())); - List frictions = player.getBlockUpdateHandler().getPossibleMaterials(belowLoc).stream() - .map(Wrapper.getInstance()::getFriction).collect(Collectors.toList()); - - Tuple ratio = frictions.stream().map(friction -> { - float drag = 0.91f; - double ldxz = player.getMovement().getDeltaXZ(); - - if(previousFromGround) { - drag*= friction; - } - - TagsBuilder tags = new TagsBuilder(); - double moveFactor = player.getBukkitPlayer().getWalkSpeed() / 2f; - - moveFactor+= moveFactor * 0.3f; - - if(player.getPotionHandler().hasPotionEffect(PotionEffectType.SPEED)) - moveFactor += (PlayerUtils.getPotionEffectLevel(player.getBukkitPlayer(), PotionEffectType.SPEED) - * (0.20000000298023224D)) * moveFactor; - - if(player.getPotionHandler().hasPotionEffect(PotionEffectType.SLOW)) - moveFactor += (PlayerUtils.getPotionEffectLevel(player.getBukkitPlayer(), PotionEffectType.SLOW) - * (-0.15000000596046448D)) * moveFactor; - - if (player.getMovement().getFrom().isOnGround()) { - tags.addTag("ground"); - drag *= 0.91f; - moveFactor *= 0.16277136 / (drag * drag * drag); - - if (player.getMovement().isJumped()) { - tags.addTag("jumped"); - moveFactor += 0.2; - } - } else { - tags.addTag("air"); - drag = 0.91f; - moveFactor = 0.026f; - } - - if(player.getBlockInfo().inWater) { - tags.addTag("water"); - - drag = player.getPlayerVersion().isOrAbove(ProtocolVersion.V1_13) ? 0.9f : 0.8f; - moveFactor = 0.034; - - if(player.getInfo().lastLiquid.getResetStreak() < 3) { - tags.addTag("water-enter"); - moveFactor*= 1.35; - } - } else if(player.getInfo().lastLiquid.isNotPassed(3)) { - moveFactor*= 1.35; - tags.addTag("water-leave"); - } - - if(player.getMovement().getLastTeleport().isNotPassed(6) - || player.getInfo().getLastRespawn().isNotPassed(6)) { - tags.addTag("teleport"); - moveFactor+= 0.1; - moveFactor*= 5; - } - - //In 1.9+, entity collisions add acceleration to their movement. - if(player.getInfo().lastEntityCollision.isNotPassed(2)) { - tags.addTag("entity-collision"); - moveFactor+= 0.05; - } - - //Pistons have the ability to move players 1 whole block - if(player.getBlockInfo().pistonNear) { - tags.addTag("piston"); - moveFactor+= 1; - } - - if(player.getBlockInfo().onSlime && player.getMovement().getFrom().isOnGround()) { - if (Math.abs(player.getMovement().getDeltaY()) < 0.1D && !player.getInfo().isSneaking()) { - moveFactor*= 0.5; - } - } - - if(player.getBlockInfo().inWeb - //Ensuring they aren't just entering or leaving web - && player.getInfo().getLastWeb().getResetStreak() > 1) { - tags.addTag("web"); - moveFactor*= 0.4; - } - - if(player.getBlockInfo().onSoulSand && player.getMovement().getFrom().isOnGround() - //Ensuring the player is actually standing on the block and recieving slow - && packet.getY() % (1) == 0.875) { - tags.addTag("soulsand"); - moveFactor*= 0.88; - } - - return new Tuple<>((player.getMovement().getDeltaXZ() - ldxz) / moveFactor * 100D, tags); - }).min(Comparator.comparing(r -> MathUtils.getDelta(r.one, 100))).orElse(new Tuple<>(100D, new TagsBuilder())); - - if (ratio.one > 100.8 - && !player.getBlockInfo().inHoney - && !player.getBlockInfo().inScaffolding - && player.getInfo().velocity.isPassed(2) - && player.getInfo().lastLiquid.isPassed(2) - && !player.getInfo().generalCancel) { - if(++buffer > 2) { - vl++; - flag("p=%.1f%% dxz=%.3f a/g=%s,%s tags=%s", - ratio.one, player.getMovement().getDeltaXZ(), player.getMovement().getAirTicks(), player.getMovement().getGroundTicks(), - ratio.two.build()); - buffer = Math.min(5, buffer); //Preventing runaway flagging - } - } else if(buffer > 0) buffer-= 0.2f; - debug("ratio=%.1f deltaY=%.3f tags=%s tp=%s buffer=%.1f", ratio.one, player.getMovement().getDeltaY(), - ratio.two.build(), player.getInfo().getLastLiquid().getPassed(), buffer); - } - previousFromGround = player.getMovement().getFrom().isOnGround(); - }; -} diff --git a/src/main/java/dev/brighten/ac/command/AnticheatCommand.java b/src/main/java/dev/brighten/ac/command/AnticheatCommand.java index 5bee5aa..932cc6e 100644 --- a/src/main/java/dev/brighten/ac/command/AnticheatCommand.java +++ b/src/main/java/dev/brighten/ac/command/AnticheatCommand.java @@ -212,48 +212,66 @@ public class AnticheatCommand extends BaseCommand { @CommandCompletion("@players @checkIds") @CommandPermission("anticheat.command.logs") @Description("Get player logs") - public void onLogs(CommandSender sender, @Single String playername, @Single @Optional @Default("none") String check) { + public void onLogs(CommandSender sender, @Single String playername, + @Single @Optional @Default("none") String check) { UUID uuid = Bukkit.getOfflinePlayer(playername).getUniqueId(); sender.sendMessage(Color.Red + "Getting logs for " + playername + "..."); - Anticheat.INSTANCE.getScheduler().execute(() -> { - List logs = new ArrayList<>(); + List logs = new ArrayList<>(); - if(check.equals("none")) { - Anticheat.INSTANCE.getLogManager().getLogs(uuid, logsList -> { - logsList.forEach(log -> { - logs.add("[" + new Timestamp(log.getTime()).toLocalDateTime() - .format(DateTimeFormatter.ISO_DATE_TIME) + "] funkemunky failed " - + Anticheat.INSTANCE.getCheckManager().getIdToName().get(log.getCheckId()) + "(VL: " + log.getVl() + ") {" + log.getData() + "}"); - }); - if(logs.size() == 0) { - if(check.equals("none")) { - sender.sendMessage(Color.Gray + "There are no logs for player \"" + playername + "\""); - } else { - sender.sendMessage(Color.Gray + " does not have any violations for check \"" + check + "\""); - } - } else { - String url = null; - try { - url = Pastebin.makePaste(String.join("\n", logs), playername + "'s Logs", Pastebin.Privacy.UNLISTED); - - sender.sendMessage(Color.Green + "Logs for " + playername + ": " + Color.White + url); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - } + if(check.equals("none")) { + Anticheat.INSTANCE.getLogManager().getLogs(uuid, logsList -> { + logsList.forEach(log -> { + logs.add("[" + new Timestamp(log.getTime()).toLocalDateTime() + .format(DateTimeFormatter.ISO_DATE_TIME) + "] funkemunky failed " + + Anticheat.INSTANCE.getCheckManager().getIdToName().get(log.getCheckId()) + "(VL: " + + log.getVl() + ") {" + log.getData() + "}"); }); - } else { + if(logs.size() == 0) { + sender.sendMessage(Color.Gray + "There are no logs for player \"" + playername + "\""); + } else { + String url = null; + try { + url = Pastebin.makePaste(String.join("\n", logs), playername + "'s Logs", + Pastebin.Privacy.UNLISTED); - } - }); + sender.sendMessage(Color.Green + "Logs for " + playername + ": " + Color.White + url); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } + }); + } else { + Anticheat.INSTANCE.getLogManager().getLogs(uuid, check, logsList -> { + logsList.forEach(log -> { + logs.add("[" + new Timestamp(log.getTime()).toLocalDateTime() + .format(DateTimeFormatter.ISO_DATE_TIME) + "] funkemunky failed " + + Anticheat.INSTANCE.getCheckManager().getIdToName().get(log.getCheckId()) + + "(VL: " + log.getVl() + ") {" + log.getData() + "}"); + }); + if(logs.size() == 0) { + sender.sendMessage(Color.Gray + " does not have any violations for check \"" + check + "\""); + } else { + String url = null; + try { + url = Pastebin.makePaste(String.join("\n", logs), playername + "'s Logs", + Pastebin.Privacy.UNLISTED); + + sender.sendMessage(Color.Green + "Logs for " + playername + ": " + Color.White + url); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } + }); + } } @Subcommand("title") @Private public void onTitle(CommandSender sender, OnlinePlayer target, String title) { - PacketPlayOutTitle packetSubtitle = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.TITLE, CraftChatMessage.fromString(Color.translate(title))[0]); + PacketPlayOutTitle packetSubtitle = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.TITLE, + CraftChatMessage.fromString(Color.translate(title))[0]); HandlerAbstract.getHandler().sendPacket(target.getPlayer(), packetSubtitle); sender.sendMessage(Color.Green + "Sent title!"); } diff --git a/src/main/java/dev/brighten/ac/data/info/CheckHandler.java b/src/main/java/dev/brighten/ac/data/info/CheckHandler.java index 666aeb7..5b41641 100644 --- a/src/main/java/dev/brighten/ac/data/info/CheckHandler.java +++ b/src/main/java/dev/brighten/ac/data/info/CheckHandler.java @@ -6,8 +6,6 @@ import dev.brighten.ac.data.APlayer; import dev.brighten.ac.data.obj.ActionStore; import dev.brighten.ac.data.obj.CancellableActionStore; import dev.brighten.ac.data.obj.TimedActionStore; -import dev.brighten.ac.handler.thread.ThreadHandler; -import dev.brighten.ac.utils.annotation.Async; import dev.brighten.ac.utils.Tuple; import dev.brighten.ac.utils.reflections.types.WrappedField; import lombok.RequiredArgsConstructor; @@ -21,9 +19,6 @@ public class CheckHandler { private final Map, TimedActionStore[]> eventsWithTimestamp = new HashMap<>(); private final Map, CancellableActionStore[]> cancellableEvents = new HashMap<>(); - private final Map, ActionStore[]> async_events = new HashMap<>(); - private final Map, TimedActionStore[]> async_eventsWithTimestamp = new HashMap<>(); - private final Map, Check> checkCache = new HashMap<>(); private final List checks = new ArrayList<>(); @@ -74,87 +69,45 @@ public class CheckHandler { for (Tuple> tuple : checkClass.getActions()) { WAction action = tuple.one.get(check); - if(!tuple.one.getField().isAnnotationPresent(Async.class)) { - events.compute(tuple.two, (packetClass, array) -> { - if (array == null) { - return new ActionStore[] {new ActionStore(action, checkClass.getCheckClass().getParent())}; - } else { - ActionStore[] newArray = Arrays.copyOf(array, array.length + 1); - newArray[array.length] = new ActionStore(action, checkClass.getCheckClass().getParent()); - return newArray; - } - }); - } - } - } - synchronized (async_events) { - for (Tuple> tuple : checkClass.getActions()) { - WAction action = tuple.one.get(check); - - if(tuple.one.getField().isAnnotationPresent(Async.class)) { - async_events.compute(tuple.two, (packetClass, array) -> { - if (array == null) { - return new ActionStore[] {new ActionStore(action, checkClass.getCheckClass().getParent())}; - } else { - ActionStore[] newArray = Arrays.copyOf(array, array.length + 1); - newArray[array.length] = new ActionStore(action, checkClass.getCheckClass().getParent()); - return newArray; - } - }); - } + events.compute(tuple.two, (packetClass, array) -> { + if (array == null) { + return new ActionStore[] {new ActionStore(action, checkClass.getCheckClass().getParent())}; + } else { + ActionStore[] newArray = Arrays.copyOf(array, array.length + 1); + newArray[array.length] = new ActionStore(action, checkClass.getCheckClass().getParent()); + return newArray; + } + }); } } synchronized (eventsWithTimestamp) { for (Tuple> tuple : checkClass.getTimedActions()) { WTimedAction action = tuple.one.get(check); - if(!tuple.one.getField().isAnnotationPresent(Async.class)) { - eventsWithTimestamp.compute(tuple.two, (packetClass, array) -> { - if (array == null) { - return new TimedActionStore[] {new TimedActionStore(action, checkClass.getCheckClass().getParent())}; - } else { - TimedActionStore[] newArray = Arrays.copyOf(array, array.length + 1); - newArray[array.length] = new TimedActionStore(action, checkClass.getCheckClass().getParent()); - return newArray; - } - }); - } - } - } - synchronized (async_eventsWithTimestamp) { - for (Tuple> tuple : checkClass.getTimedActions()) { - WTimedAction action = tuple.one.get(check); - - if(tuple.one.getField().isAnnotationPresent(Async.class)) { - async_eventsWithTimestamp.compute(tuple.two, (packetClass, array) -> { - if (array == null) { - return new TimedActionStore[] {new TimedActionStore(action, checkClass.getCheckClass().getParent())}; - } else { - TimedActionStore[] newArray = Arrays.copyOf(array, array.length + 1); - newArray[array.length] = new TimedActionStore(action, checkClass.getCheckClass().getParent()); - return newArray; - } - }); - } + eventsWithTimestamp.compute(tuple.two, (packetClass, array) -> { + if (array == null) { + return new TimedActionStore[] {new TimedActionStore(action, checkClass.getCheckClass().getParent())}; + } else { + TimedActionStore[] newArray = Arrays.copyOf(array, array.length + 1); + newArray[array.length] = new TimedActionStore(action, checkClass.getCheckClass().getParent()); + return newArray; + } + }); } } synchronized (cancellableEvents) { for (Tuple> tuple : checkClass.getCancellableActions()) { WCancellable action = tuple.one.get(check); - if(!tuple.one.getField().isAnnotationPresent(Async.class)) { - cancellableEvents.compute(tuple.two, (packetClass, array) -> { - if (array == null) { - return new CancellableActionStore[] {new CancellableActionStore(action, checkClass.getCheckClass().getParent())}; - } else { - CancellableActionStore[] newArray = Arrays.copyOf(array, array.length + 1); - newArray[array.length] = new CancellableActionStore(action, checkClass.getCheckClass().getParent()); - return newArray; - } - }); - } else { - Anticheat.INSTANCE.alog("WARNING: Async action " + action.getClass().getSimpleName() + " is not cancellable"); - } + cancellableEvents.compute(tuple.two, (packetClass, array) -> { + if (array == null) { + return new CancellableActionStore[] {new CancellableActionStore(action, checkClass.getCheckClass().getParent())}; + } else { + CancellableActionStore[] newArray = Arrays.copyOf(array, array.length + 1); + newArray[array.length] = new CancellableActionStore(action, checkClass.getCheckClass().getParent()); + return newArray; + } + }); } } } @@ -165,8 +118,6 @@ public class CheckHandler { events.clear(); eventsWithTimestamp.clear(); cancellableEvents.clear(); - async_events.clear(); - async_eventsWithTimestamp.clear(); } public void disableCheck(String checkName) { @@ -185,30 +136,6 @@ public class CheckHandler { } //TODO When using WPacket wrappers only, make this strictly WPacket param based only - public void callPacket(Object packet, long timestamp) { - ThreadHandler.INSTANCE.getThread(player).getThread().execute(() -> { - if(async_events.containsKey(packet.getClass())) { - synchronized (async_events) { - ActionStore[] actions = async_events.get(packet.getClass()); - for (ActionStore action : actions) { - if(!Anticheat.INSTANCE.getCheckManager().getCheckSettings(action.getCheckClass()).isEnabled()) - continue; - action.getAction().invoke(packet); - } - } - } - if(async_eventsWithTimestamp.containsKey(packet.getClass())) { - synchronized (async_eventsWithTimestamp) { - TimedActionStore[] actions = async_eventsWithTimestamp.get(packet.getClass()); - for (TimedActionStore action : actions) { - if(!Anticheat.INSTANCE.getCheckManager().getCheckSettings(action.getCheckClass()).isEnabled()) - continue; - action.getAction().invoke(packet, timestamp); - } - } - } - }); - } public boolean callSyncPacket(Object packet, long timestamp) { if(events.containsKey(packet.getClass())) { diff --git a/src/main/java/dev/brighten/ac/handler/MovementHandler.java b/src/main/java/dev/brighten/ac/handler/MovementHandler.java index 0b221fb..0e817cb 100644 --- a/src/main/java/dev/brighten/ac/handler/MovementHandler.java +++ b/src/main/java/dev/brighten/ac/handler/MovementHandler.java @@ -19,10 +19,7 @@ import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.potion.PotionEffectType; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; +import java.util.*; @RequiredArgsConstructor public class MovementHandler { @@ -81,6 +78,10 @@ public class MovementHandler { } else moveTicks = 0; updateLocations(packet); + + if(packet.isMoved()) { + player.getBlockInfo().runCollisionCheck(); + } if (moveTicks > 0) { // Updating block locations @@ -106,8 +107,6 @@ public class MovementHandler { } } - player.getBlockInfo().runCollisionCheck(); - if(player.getBlockInfo().blocksAbove) { player.getInfo().getBlockAbove().reset(); } @@ -209,6 +208,7 @@ public class MovementHandler { airTicks = 0; player.getInfo().groundJumpBoost = player.getPotionHandler().getEffectByType(PotionEffectType.JUMP); } else { + player.getInfo().groundJumpBoost = Optional.empty(); airTicks++; groundTicks = 0; } diff --git a/src/main/java/dev/brighten/ac/handler/PacketHandler.java b/src/main/java/dev/brighten/ac/handler/PacketHandler.java index 6aa0614..eee79b0 100644 --- a/src/main/java/dev/brighten/ac/handler/PacketHandler.java +++ b/src/main/java/dev/brighten/ac/handler/PacketHandler.java @@ -309,7 +309,6 @@ public class PacketHandler { } boolean cancelled = player.getCheckHandler().callSyncPacket(packetObject, timestamp); - player.getCheckHandler().callPacket(packetObject, timestamp); // Post flying settings if(type.equals(PacketType.FLYING)) { diff --git a/src/main/java/dev/brighten/ac/handler/block/BlockUpdateHandler.java b/src/main/java/dev/brighten/ac/handler/block/BlockUpdateHandler.java index 06050d1..e665bff 100644 --- a/src/main/java/dev/brighten/ac/handler/block/BlockUpdateHandler.java +++ b/src/main/java/dev/brighten/ac/handler/block/BlockUpdateHandler.java @@ -18,11 +18,10 @@ import org.bukkit.Material; import org.bukkit.block.Block; import java.util.*; -import java.util.concurrent.ConcurrentHashMap; @RequiredArgsConstructor public class BlockUpdateHandler { - private final Map> blockInformation = new ConcurrentHashMap<>(); + private final Map> blockInformation = new Hashtable<>(100, 0.1f); private final APlayer player; @@ -61,7 +60,7 @@ public class BlockUpdateHandler { player.getInfo().getLastPlace().reset(); - Deque possible = getDirectPossibleMaterials(pos); + Deque possible = getPossibleMaterials(pos); possible.add(place.getItemStack().getType()); } @@ -72,7 +71,7 @@ public class BlockUpdateHandler { public void onDig(WPacketPlayInBlockDig dig) { player.getInfo().lastBlockUpdate.reset(); if(dig.getDigType() == WPacketPlayInBlockDig.EnumPlayerDigType.STOP_DESTROY_BLOCK) { - Deque possible = getDirectPossibleMaterials(dig.getBlockPos()); + Deque possible = getPossibleMaterials(dig.getBlockPos()); possible.clear(); possible.add(Material.AIR); } @@ -80,44 +79,13 @@ public class BlockUpdateHandler { public void runUpdate(WPacketPlayOutBlockChange packet) { player.getInfo().lastBlockUpdate.reset(); - Deque blockInfo = blockInformation.compute(packet.getBlockLocation(), (blockLoc, blockI) -> { - if(blockI == null) { - blockI = new LinkedList<>(); - - val optional = BlockUtils - .getBlockAsync(packet.getBlockLocation().toBukkitVector() - .toLocation(player.getBukkitPlayer().getWorld())); - - if(optional.isPresent()) { - Block block = optional.get(); - - blockI.add(block.getType()); - } - } - - return blockI; - }); - - // Updating block information - player.runInstantAction(k -> { - if(!k.isEnd()) { - blockInfo.add(packet.getMaterial()); - } else if(blockInfo.size() > 1) { - blockInfo.removeFirst(); - } - }); - } - - public void runUpdate(WPacketPlayOutMultiBlockChange packet) { - player.getInfo().lastBlockUpdate.reset(); - List, Material>> changes = new ArrayList<>(); - for (WPacketPlayOutMultiBlockChange.BlockChange change : packet.getChanges()) { - Deque blockInfo = blockInformation.compute(change.getLocation(), (blockLoc, blockI) -> { + synchronized (blockInformation) { + Deque blockInfo = blockInformation.compute(packet.getBlockLocation(), (blockLoc, blockI) -> { if(blockI == null) { blockI = new LinkedList<>(); val optional = BlockUtils - .getBlockAsync(change.getLocation().toBukkitVector() + .getBlockAsync(packet.getBlockLocation().toBukkitVector() .toLocation(player.getBukkitPlayer().getWorld())); if(optional.isPresent()) { @@ -129,10 +97,44 @@ public class BlockUpdateHandler { return blockI; }); - - changes.add(new Tuple<>(blockInfo, change.getMaterial())); + // Updating block information + player.runInstantAction(k -> { + if (!k.isEnd()) { + blockInfo.add(packet.getMaterial()); + } else if (blockInfo.size() > 1) { + blockInfo.removeFirst(); + } + }); } + } + public void runUpdate(WPacketPlayOutMultiBlockChange packet) { + player.getInfo().lastBlockUpdate.reset(); + List, Material>> changes = new ArrayList<>(); + synchronized (blockInformation) { + for (WPacketPlayOutMultiBlockChange.BlockChange change : packet.getChanges()) { + Deque blockInfo = blockInformation.compute(change.getLocation(), (blockLoc, blockI) -> { + if(blockI == null) { + blockI = new LinkedList<>(); + + val optional = BlockUtils + .getBlockAsync(change.getLocation().toBukkitVector() + .toLocation(player.getBukkitPlayer().getWorld())); + + if(optional.isPresent()) { + Block block = optional.get(); + + blockI.add(block.getType()); + } + } + + return blockI; + }); + + changes.add(new Tuple<>(blockInfo, change.getMaterial())); + } + + } player.runInstantAction(k -> { if(!k.isEnd()) { for (Tuple, Material> tuple : changes) { @@ -149,21 +151,22 @@ public class BlockUpdateHandler { } public Deque getPossibleMaterials(IntVector loc) { - return new LinkedList<>(getDirectPossibleMaterials(loc)); - } + synchronized (blockInformation) { + + Deque blockI = blockInformation.get(loc); - private Deque getDirectPossibleMaterials(IntVector loc) { - return blockInformation.compute(loc, (blockLoc, blockI) -> { if(blockI == null) { blockI = new LinkedList<>(); - Material type = Wrapper.getInstance().getType(player.getBukkitPlayer().getWorld(), - loc.getX(), loc.getY(), loc.getZ()); + Material type = Wrapper.getInstance().getType(player.getBukkitPlayer().getWorld(), + loc.getX(), loc.getY(), loc.getZ()); blockI.add(type); + + blockInformation.put(loc, blockI); } return blockI; - }); + } } } diff --git a/src/main/java/dev/brighten/ac/handler/keepalive/KeepAlive.java b/src/main/java/dev/brighten/ac/handler/keepalive/KeepAlive.java index 885f743..591eacd 100644 --- a/src/main/java/dev/brighten/ac/handler/keepalive/KeepAlive.java +++ b/src/main/java/dev/brighten/ac/handler/keepalive/KeepAlive.java @@ -20,7 +20,7 @@ public class KeepAlive { this.id = id; } - public final Int2ObjectMap receivedKeepalive = new Int2ObjectOpenHashMap<>(); + public final Int2ObjectMap receivedKeepalive = new Int2ObjectOpenHashMap<>(400); public void received(APlayer player) { receivedKeepalive.put(player.getBukkitPlayer().getUniqueId().hashCode(), diff --git a/src/main/java/dev/brighten/ac/logging/Log.java b/src/main/java/dev/brighten/ac/logging/Log.java index 3cfe808..2f5d82b 100644 --- a/src/main/java/dev/brighten/ac/logging/Log.java +++ b/src/main/java/dev/brighten/ac/logging/Log.java @@ -2,8 +2,8 @@ package dev.brighten.ac.logging; import lombok.Builder; import lombok.Getter; -import me.mat1337.loader.utils.json.JSONException; -import me.mat1337.loader.utils.json.JSONObject; +import dev.brighten.ac.utils.json.JSONException; +import dev.brighten.ac.utils.json.JSONObject; import java.util.UUID; diff --git a/src/main/java/dev/brighten/ac/logging/LoggerManager.java b/src/main/java/dev/brighten/ac/logging/LoggerManager.java index 6a555d7..d037cfe 100644 --- a/src/main/java/dev/brighten/ac/logging/LoggerManager.java +++ b/src/main/java/dev/brighten/ac/logging/LoggerManager.java @@ -7,11 +7,12 @@ import com.neovisionaries.ws.client.WebSocketFactory; import dev.brighten.ac.Anticheat; import dev.brighten.ac.check.CheckData; import dev.brighten.ac.data.APlayer; -import me.mat1337.loader.utils.json.JSONObject; +import dev.brighten.ac.utils.json.JSONObject; import java.io.*; import java.util.*; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; @@ -28,8 +29,10 @@ public class LoggerManager { // Starting up H2 license = Anticheat.INSTANCE.getPluginInstance().getConfig().getString("license"); + AtomicLong lastWrite = new AtomicLong(); Anticheat.INSTANCE.getScheduler().scheduleAtFixedRate(() -> { - if(logList.size() > 0) { + long now = System.currentTimeMillis(); + if(logList.size() > 0 && (now - lastWrite.get() > 2000L || logList.size() > 600)) { try { WebSocket socket = new WebSocketFactory().createSocket("ws://port.funkemunky.cc/chat").connect(); @@ -42,11 +45,16 @@ public class LoggerManager { oos.writeUTF(license()); int i = 0; - while((log = logList.poll()) != null && i++ < 100) { + while((log = logList.poll()) != null && i++ < 400) { oos.writeUTF(log.toJson()); } - System.out.println("Wrote " + i + " logs"); + if(i == 0) { + logList.clear(); + } + + System.out.println("Wrote " + i + " logs;" + logList.size()); + lastWrite.set(now); oos.close(); socket.sendBinary(baos.toByteArray()); baos.close(); @@ -56,7 +64,7 @@ public class LoggerManager { throw new RuntimeException(e); } } - }, 10, 10, TimeUnit.SECONDS); + }, 100, 100, TimeUnit.MILLISECONDS); } private String license() { @@ -73,54 +81,146 @@ public class LoggerManager { .build()); } - public void getLogs(UUID uuid, Consumer> logsConsumer) { - try { - WebSocket socket = new WebSocketFactory().createSocket("ws://port.funkemunky.cc/chat").connect(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); + public void getLogs(UUID uuid, Consumer> logConsumer) { + getLogs(uuid, 500, 0, logConsumer); + } + public void getLogs(UUID uuid, int limit, int skip, Consumer> logsConsumer) { + Anticheat.INSTANCE.getScheduler().execute(() -> { + try { + WebSocket socket = createSocket(logsConsumer).connect(); - oos.writeUTF("LOG_REQ_UUID"); - oos.writeUTF(license()); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeUTF(uuid.toString()); - oos.close(); - System.out.println("Sending binary"); - socket.sendBinary(baos.toByteArray()).addListener(new WebSocketAdapter() { + oos.writeUTF("LOG_REQ_UUID"); + oos.writeUTF(license()); - @Override - public void onBinaryMessage(WebSocket websocket, byte[] data) throws Exception { - ByteArrayInputStream bais = new ByteArrayInputStream(data); - ObjectInputStream ois = new ObjectInputStream(bais); - - List logs = new ArrayList<>(); - while(ois.available() > 0) { - String logString = ois.readUTF(); - JSONObject logObject = new JSONObject(logString); - - logs.add(Log.builder() - .vl((float)logObject.getDouble("vl")) - .checkId(logObject.getString("checkId")) - .data(logObject.getString("data")) - .time(logObject.getLong("time")) - .uuid(UUID.fromString(logObject.getString("uuid"))).build()); - } - - logsConsumer.accept(logs); - websocket.disconnect(); - } - }); - - if(socket.isOpen()) System.out.println("Open"); - else System.out.println("Not open!"); - } catch(WebSocketException e) { - e.printStackTrace(); - } catch (IOException e) { - throw new RuntimeException(e); - } + oos.writeUTF(uuid.toString()); + oos.writeInt(skip); + oos.writeInt(limit); + oos.close(); + socket.sendBinary(baos.toByteArray()); + } catch(WebSocketException e) { + e.printStackTrace(); + } catch (IOException e) { + throw new RuntimeException(e); + } + }); } + public void getLogs(UUID uuid, String checkId, Consumer> logConsumer) { + getLogs(uuid, checkId, 500, 0, logConsumer); + } + + public void getLogs(UUID uuid, String checkId, int limit, int skip, Consumer> logsConsumer) { + Anticheat.INSTANCE.getScheduler().execute(() -> { + try { + WebSocket socket = createSocket(logsConsumer).connect(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + + oos.writeUTF("LOG_REQ_UUID_CHECK"); + oos.writeUTF(license()); + oos.writeUTF(uuid.toString()); + oos.writeUTF(checkId); + oos.writeInt(skip); + oos.writeInt(limit); + + + oos.close(); + socket.sendBinary(baos.toByteArray()); + } catch(WebSocketException e) { + e.printStackTrace(); + } catch (IOException e) { + throw new RuntimeException(e); + } + }); + } + + public void getLogs(UUID uuid, String checkId, long timeBefore, long timeAfter, + Consumer> logsConsumer) { + getLogs(uuid, checkId, timeBefore, timeAfter, 500, 0, logsConsumer); + } + public void getLogs(UUID uuid, String checkId, long timeBefore, long timeAfter, int limit, int skip, + Consumer> logsConsumer) { + Anticheat.INSTANCE.getScheduler().execute(() -> { + try { + WebSocket socket = createSocket(logsConsumer).connect(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + + oos.writeUTF("LOG_REQ_UUID_CHECK_TIME"); + oos.writeUTF(license()); + oos.writeUTF(checkId); + oos.writeLong(timeBefore); + oos.writeLong(timeAfter); + oos.writeInt(skip); + oos.writeInt(limit); + + + oos.writeUTF(uuid.toString()); + oos.close(); + socket.sendBinary(baos.toByteArray()); + } catch(WebSocketException e) { + e.printStackTrace(); + } catch (IOException e) { + throw new RuntimeException(e); + } + }); + } + + public void getRecentLogs(int limit, Consumer> logsConsumer) { + Anticheat.INSTANCE.getScheduler().execute(() -> { + try { + WebSocket socket = createSocket(logsConsumer).connect(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + + oos.writeUTF("LOG_REQ_UUID_CHECK"); + oos.writeUTF(license()); + oos.writeInt(limit); + + oos.close(); + socket.sendBinary(baos.toByteArray()); + } catch (WebSocketException | IOException e) { + throw new RuntimeException(e); + } + }); + } + + private WebSocket createSocket(Consumer> logsConsumer) throws IOException { + return new WebSocketFactory().createSocket("ws://port.funkemunky.cc/chat") + .addListener(new WebSocketAdapter() { + + @Override + public void onBinaryMessage(WebSocket websocket, byte[] data) throws Exception { + ByteArrayInputStream bais = new ByteArrayInputStream(data); + ObjectInputStream ois = new ObjectInputStream(bais); + + System.out.println("Received!: " + ois.available()); + List logs = new ArrayList<>(); + while(ois.available() > 0) { + String logString = ois.readUTF(); + JSONObject logObject = new JSONObject(logString); + + logs.add(Log.builder() + .vl((float)logObject.getDouble("vl")) + .checkId(logObject.getString("checkId")) + .data(logObject.getString("data")) + .time(logObject.getLong("time")) + .uuid(UUID.fromString(logObject.getString("uuid"))).build()); + } + + logsConsumer.accept(logs); + websocket.disconnect(); + } + }); + } public void shutDown() { } diff --git a/src/main/java/dev/brighten/ac/logging/sql/ExecutableStatement.java b/src/main/java/dev/brighten/ac/logging/sql/ExecutableStatement.java deleted file mode 100644 index 92f875f..0000000 --- a/src/main/java/dev/brighten/ac/logging/sql/ExecutableStatement.java +++ /dev/null @@ -1,146 +0,0 @@ -package dev.brighten.ac.logging.sql; - -import dev.brighten.ac.utils.MiscUtils; -import lombok.SneakyThrows; - -import java.sql.*; -import java.util.UUID; - -public class ExecutableStatement { - private PreparedStatement statement; - private int pos = 1; - - public ExecutableStatement(PreparedStatement statement) { - this.statement = statement; - } - - @SneakyThrows - public Integer execute() { - try { - return statement.executeUpdate(); - } finally { - MiscUtils.close(statement); - } - } - - @SneakyThrows - public void execute(ResultSetIterator iterator) { - ResultSet rs = null; - try { - rs = statement.executeQuery(); - while (rs.next()) iterator.next(rs); - } finally { - MiscUtils.close(statement, rs); - } - } - - @SneakyThrows - public void executeSingle(ResultSetIterator iterator) { - ResultSet rs = null; - try { - rs = statement.executeQuery(); - if (rs.next()) iterator.next(rs); - else iterator.next(null); - } finally { - MiscUtils.close(statement, rs); - } - } - - @SneakyThrows - public ResultSet executeQuery() { - return statement.executeQuery(); - } - - @SneakyThrows - public ExecutableStatement append(Object obj) { - statement.setObject(pos++, obj); - return this; - } - - @SneakyThrows - public ExecutableStatement append(Object... objects) { - for (Object obj : objects) { - statement.setObject(pos++, obj); - } - return this; - } - - @SneakyThrows - public ExecutableStatement append(String obj) { - statement.setString(pos++, obj); - return this; - } - - @SneakyThrows - public ExecutableStatement append(UUID uuid) { - if (uuid != null) statement.setString(pos++, uuid.toString().replace("-", "")); - else statement.setString(pos++, null); - return this; - } - - @SneakyThrows - public ExecutableStatement append(Array obj) { - statement.setArray(pos++, obj); - return this; - } - - @SneakyThrows - public ExecutableStatement append(Integer obj) { - statement.setInt(pos++, obj); - return this; - } - - @SneakyThrows - public ExecutableStatement append(Short obj) { - statement.setShort(pos++, obj); - return this; - } - - @SneakyThrows - public ExecutableStatement append(Long obj) { - statement.setLong(pos++, obj); - return this; - } - - @SneakyThrows - public ExecutableStatement append(Float obj) { - statement.setFloat(pos++, obj); - return this; - } - - @SneakyThrows - public ExecutableStatement append(Double obj) { - statement.setDouble(pos++, obj); - return this; - } - - @SneakyThrows - public ExecutableStatement append(Date obj) { - statement.setDate(pos++, obj); - return this; - } - - @SneakyThrows - public ExecutableStatement append(Timestamp obj) { - statement.setTimestamp(pos++, obj); - return this; - } - - @SneakyThrows - public ExecutableStatement append(Time obj) { - statement.setTime(pos++, obj); - return this; - } - - @SneakyThrows - public ExecutableStatement append(Blob obj) { - statement.setBlob(pos++, obj); - return this; - } - - @SneakyThrows - public ExecutableStatement append(byte[] obj) { - statement.setBytes(pos++, obj); - return this; - } -} diff --git a/src/main/java/dev/brighten/ac/logging/sql/MySQL.java b/src/main/java/dev/brighten/ac/logging/sql/MySQL.java deleted file mode 100644 index 9701141..0000000 --- a/src/main/java/dev/brighten/ac/logging/sql/MySQL.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.brighten.ac.logging.sql; - -import dev.brighten.ac.Anticheat; -import lombok.SneakyThrows; -import org.bukkit.Bukkit; -import org.h2.jdbc.JdbcConnection; - -import java.io.File; -import java.io.IOException; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.Properties; -import java.util.logging.Level; - -public class MySQL { - private static Connection conn; - - @SneakyThrows - public static void initH2() { - File dataFolder = new File(Anticheat.INSTANCE.getDataFolder(), "database.db"); - try {//https://nexus.funkemunky.cc/service/local/repositories/releases/content/com/h2database/h2/1.4.199/h2-1.4.199.jar - if(dataFolder.createNewFile()) { - Anticheat.INSTANCE.getLogger().info("Successfully created database.db in Anticheat folder!"); - } - } catch (IOException e) { - Anticheat.INSTANCE.getLogger().log(Level.SEVERE, "File write error: database.db"); - } - try { - conn = new NonClosableConnection(new JdbcConnection("jdbc:h2:file:" + - dataFolder.getAbsolutePath(), - new Properties(), "root", "erc5gmv-xvg5CZQ0nzw", false)); - conn.setAutoCommit(true); - Query.use(conn); - Bukkit.getLogger().info("Connection to H2 SQlLite has been established."); - } catch (SQLException ex) { - Anticheat.INSTANCE.getLogger().log(Level.SEVERE,"SQLite exception on initialize", ex); - } - } - - public static void shutdown() { - try { - if(conn != null && !conn.isClosed()) { - if(conn instanceof NonClosableConnection) { - ((NonClosableConnection)conn).shutdown(); - } else conn.close(); - conn = null; - } - } catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/src/main/java/dev/brighten/ac/logging/sql/NonClosableConnection.java b/src/main/java/dev/brighten/ac/logging/sql/NonClosableConnection.java deleted file mode 100644 index 5a7cfa0..0000000 --- a/src/main/java/dev/brighten/ac/logging/sql/NonClosableConnection.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * This file is part of LuckPerms, licensed under the MIT License. - * - * Copyright (c) lucko (Luck) - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package dev.brighten.ac.logging.sql; - -import java.sql.*; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.Executor; - -/** - * A wrapper around a {@link Connection} which blocks usage of the default {@link #close()} method. - */ -public class NonClosableConnection implements Connection { - private final Connection delegate; - - public NonClosableConnection(Connection delegate) { - this.delegate = delegate; - } - - /** - * Actually {@link #close() closes} the underlying connection. - */ - public final void shutdown() throws SQLException { - this.delegate.close(); - } - - @Override - public final void close() throws SQLException { - // do nothing - } - - @Override - public final boolean isWrapperFor(Class iface) throws SQLException { - return iface.isInstance(this.delegate) || this.delegate.isWrapperFor(iface); - } - - @SuppressWarnings("unchecked") - @Override - public final T unwrap(Class iface) throws SQLException { - if (iface.isInstance(this.delegate)) { - return (T) this.delegate; - } - return this.delegate.unwrap(iface); - } - - // Forward to the delegate connection - @Override public Statement createStatement() throws SQLException { return this.delegate.createStatement(); } - @Override public PreparedStatement prepareStatement(String sql) throws SQLException { return this.delegate.prepareStatement(sql); } - @Override public CallableStatement prepareCall(String sql) throws SQLException { return this.delegate.prepareCall(sql); } - @Override public String nativeSQL(String sql) throws SQLException { return this.delegate.nativeSQL(sql); } - @Override public void setAutoCommit(boolean autoCommit) throws SQLException { this.delegate.setAutoCommit(autoCommit); } - @Override public boolean getAutoCommit() throws SQLException { return this.delegate.getAutoCommit(); } - @Override public void commit() throws SQLException { this.delegate.commit(); } - @Override public void rollback() throws SQLException { this.delegate.rollback(); } - @Override public boolean isClosed() throws SQLException { return this.delegate.isClosed(); } - @Override public DatabaseMetaData getMetaData() throws SQLException { return this.delegate.getMetaData(); } - @Override public void setReadOnly(boolean readOnly) throws SQLException { this.delegate.setReadOnly(readOnly); } - @Override public boolean isReadOnly() throws SQLException { return this.delegate.isReadOnly(); } - @Override public void setCatalog(String catalog) throws SQLException { this.delegate.setCatalog(catalog); } - @Override public String getCatalog() throws SQLException { return this.delegate.getCatalog(); } - @Override public void setTransactionIsolation(int level) throws SQLException { this.delegate.setTransactionIsolation(level); } - @Override public int getTransactionIsolation() throws SQLException { return this.delegate.getTransactionIsolation(); } - @Override public SQLWarning getWarnings() throws SQLException { return this.delegate.getWarnings(); } - @Override public void clearWarnings() throws SQLException { this.delegate.clearWarnings(); } - @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { return this.delegate.createStatement(resultSetType, resultSetConcurrency); } - @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return this.delegate.prepareStatement(sql, resultSetType, resultSetConcurrency); } - @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return this.delegate.prepareCall(sql, resultSetType, resultSetConcurrency); } - @Override public Map> getTypeMap() throws SQLException { return this.delegate.getTypeMap(); } - @Override public void setTypeMap(Map> map) throws SQLException { this.delegate.setTypeMap(map); } - @Override public void setHoldability(int holdability) throws SQLException { this.delegate.setHoldability(holdability); } - @Override public int getHoldability() throws SQLException { return this.delegate.getHoldability(); } - @Override public Savepoint setSavepoint() throws SQLException { return this.delegate.setSavepoint(); } - @Override public Savepoint setSavepoint(String name) throws SQLException { return this.delegate.setSavepoint(name); } - @Override public void rollback(Savepoint savepoint) throws SQLException { this.delegate.rollback(savepoint); } - @Override public void releaseSavepoint(Savepoint savepoint) throws SQLException { this.delegate.releaseSavepoint(savepoint); } - @Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return this.delegate.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); } - @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return this.delegate.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } - @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return this.delegate.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } - @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { return this.delegate.prepareStatement(sql, autoGeneratedKeys); } - @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { return this.delegate.prepareStatement(sql, columnIndexes); } - @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { return this.delegate.prepareStatement(sql, columnNames); } - @Override public Clob createClob() throws SQLException { return this.delegate.createClob(); } - @Override public Blob createBlob() throws SQLException { return this.delegate.createBlob(); } - @Override public NClob createNClob() throws SQLException { return this.delegate.createNClob(); } - @Override public SQLXML createSQLXML() throws SQLException { return this.delegate.createSQLXML(); } - @Override public boolean isValid(int timeout) throws SQLException { return this.delegate.isValid(timeout); } - @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { this.delegate.setClientInfo(name, value); } - @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { this.delegate.setClientInfo(properties); } - @Override public String getClientInfo(String name) throws SQLException { return this.delegate.getClientInfo(name); } - @Override public Properties getClientInfo() throws SQLException { return this.delegate.getClientInfo(); } - @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { return this.delegate.createArrayOf(typeName, elements); } - @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { return this.delegate.createStruct(typeName, attributes); } - @Override public void setSchema(String schema) throws SQLException { this.delegate.setSchema(schema); } - @Override public String getSchema() throws SQLException { return this.delegate.getSchema(); } - @Override public void abort(Executor executor) throws SQLException { this.delegate.abort(executor); } - @Override public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { this.delegate.setNetworkTimeout(executor, milliseconds); } - @Override public int getNetworkTimeout() throws SQLException { return this.delegate.getNetworkTimeout(); } - -} diff --git a/src/main/java/dev/brighten/ac/logging/sql/Query.java b/src/main/java/dev/brighten/ac/logging/sql/Query.java deleted file mode 100644 index fa94eca..0000000 --- a/src/main/java/dev/brighten/ac/logging/sql/Query.java +++ /dev/null @@ -1,23 +0,0 @@ -package dev.brighten.ac.logging.sql; - -import lombok.SneakyThrows; - -import java.sql.Connection; - -public class Query { - private static Connection conn; - - public static void use(Connection conn) { - Query.conn = conn; - } - - @SneakyThrows - public static ExecutableStatement prepare(String query) { - return new ExecutableStatement(conn.prepareStatement(query)); - } - - @SneakyThrows - public static ExecutableStatement prepare(String query, Connection con) { - return new ExecutableStatement(con.prepareStatement(query)); - } -} diff --git a/src/main/java/dev/brighten/ac/logging/sql/ResultSetIterator.java b/src/main/java/dev/brighten/ac/logging/sql/ResultSetIterator.java deleted file mode 100644 index 56e5858..0000000 --- a/src/main/java/dev/brighten/ac/logging/sql/ResultSetIterator.java +++ /dev/null @@ -1,7 +0,0 @@ -package dev.brighten.ac.logging.sql; - -import java.sql.ResultSet; - -public interface ResultSetIterator { - void next(ResultSet rs) throws Exception; -} diff --git a/src/main/java/dev/brighten/ac/utils/json/CDL.java b/src/main/java/dev/brighten/ac/utils/json/CDL.java new file mode 100644 index 0000000..0330d63 --- /dev/null +++ b/src/main/java/dev/brighten/ac/utils/json/CDL.java @@ -0,0 +1,295 @@ +package dev.brighten.ac.utils.json; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import dev.brighten.ac.utils.json.JSONArray; +import dev.brighten.ac.utils.json.JSONException; +import dev.brighten.ac.utils.json.JSONObject; +import dev.brighten.ac.utils.json.JSONTokener; + +/** + * This provides static methods to convert comma delimited text into a + * JSONArray, and to covert a JSONArray into comma delimited text. Comma + * delimited text is a very popular format for data interchange. It is + * understood by most database, spreadsheet, and organizer programs. + *

+ * Each row of text represents a row in a table or a data record. Each row + * ends with a NEWLINE character. Each row contains one or more values. + * Values are separated by commas. A value can contain any character except + * for comma, unless is is wrapped in single quotes or double quotes. + *

+ * The first row usually contains the names of the columns. + *

+ * A comma delimited list can be converted into a JSONArray of JSONObjects. + * The names for the elements in the JSONObjects can be taken from the names + * in the first row. + * + * @author JSON.org + * @version 2010-12-24 + */ +public class CDL { + + /** + * Get the next value. The value can be wrapped in quotes. The value can + * be empty. + * + * @param x A JSONTokener of the source text. + * @return The value string, or null if empty. + * @throws dev.brighten.ac.utils.json.JSONException if the quoted string is badly formed. + */ + private static String getValue(dev.brighten.ac.utils.json.JSONTokener x) throws dev.brighten.ac.utils.json.JSONException { + char c; + char q; + StringBuffer sb; + do { + c = x.next(); + } while (c == ' ' || c == '\t'); + switch (c) { + case 0: + return null; + case '"': + case '\'': + q = c; + sb = new StringBuffer(); + for (; ; ) { + c = x.next(); + if (c == q) { + break; + } + if (c == 0 || c == '\n' || c == '\r') { + throw x.syntaxError("Missing close quote '" + q + "'."); + } + sb.append(c); + } + return sb.toString(); + case ',': + x.back(); + return ""; + default: + x.back(); + return x.nextTo(','); + } + } + + /** + * Produce a JSONArray of strings from a row of comma delimited values. + * + * @param x A JSONTokener of the source text. + * @return A JSONArray of strings. + * @throws dev.brighten.ac.utils.json.JSONException + */ + public static dev.brighten.ac.utils.json.JSONArray rowToJSONArray(dev.brighten.ac.utils.json.JSONTokener x) throws dev.brighten.ac.utils.json.JSONException { + dev.brighten.ac.utils.json.JSONArray ja = new dev.brighten.ac.utils.json.JSONArray(); + for (; ; ) { + String value = getValue(x); + char c = x.next(); + if (value == null || + (ja.length() == 0 && value.length() == 0 && c != ',')) { + return null; + } + ja.put(value); + for (; ; ) { + if (c == ',') { + break; + } + if (c != ' ') { + if (c == '\n' || c == '\r' || c == 0) { + return ja; + } + throw x.syntaxError("Bad character '" + c + "' (" + + (int) c + ")."); + } + c = x.next(); + } + } + } + + /** + * Produce a JSONObject from a row of comma delimited text, using a + * parallel JSONArray of strings to provides the names of the elements. + * + * @param names A JSONArray of names. This is commonly obtained from the + * first row of a comma delimited text file using the rowToJSONArray + * method. + * @param x A JSONTokener of the source text. + * @return A JSONObject combining the names and values. + * @throws dev.brighten.ac.utils.json.JSONException + */ + public static dev.brighten.ac.utils.json.JSONObject rowToJSONObject(dev.brighten.ac.utils.json.JSONArray names, dev.brighten.ac.utils.json.JSONTokener x) + throws dev.brighten.ac.utils.json.JSONException { + dev.brighten.ac.utils.json.JSONArray ja = rowToJSONArray(x); + return ja != null ? ja.toJSONObject(names) : null; + } + + /** + * Produce a comma delimited text row from a JSONArray. Values containing + * the comma character will be quoted. Troublesome characters may be + * removed. + * + * @param ja A JSONArray of strings. + * @return A string ending in NEWLINE. + */ + public static String rowToString(dev.brighten.ac.utils.json.JSONArray ja) { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < ja.length(); i += 1) { + if (i > 0) { + sb.append(','); + } + Object object = ja.opt(i); + if (object != null) { + String string = object.toString(); + if (string.length() > 0 && (string.indexOf(',') >= 0 || + string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 || + string.indexOf(0) >= 0 || string.charAt(0) == '"')) { + sb.append('"'); + int length = string.length(); + for (int j = 0; j < length; j += 1) { + char c = string.charAt(j); + if (c >= ' ' && c != '"') { + sb.append(c); + } + } + sb.append('"'); + } else { + sb.append(string); + } + } + } + sb.append('\n'); + return sb.toString(); + } + + /** + * Produce a JSONArray of JSONObjects from a comma delimited text string, + * using the first row as a source of names. + * + * @param string The comma delimited text. + * @return A JSONArray of JSONObjects. + * @throws dev.brighten.ac.utils.json.JSONException + */ + public static dev.brighten.ac.utils.json.JSONArray toJSONArray(String string) throws dev.brighten.ac.utils.json.JSONException { + return toJSONArray(new dev.brighten.ac.utils.json.JSONTokener(string)); + } + + /** + * Produce a JSONArray of JSONObjects from a comma delimited text string, + * using the first row as a source of names. + * + * @param x The JSONTokener containing the comma delimited text. + * @return A JSONArray of JSONObjects. + * @throws dev.brighten.ac.utils.json.JSONException + */ + public static dev.brighten.ac.utils.json.JSONArray toJSONArray(dev.brighten.ac.utils.json.JSONTokener x) throws dev.brighten.ac.utils.json.JSONException { + return toJSONArray(rowToJSONArray(x), x); + } + + /** + * Produce a JSONArray of JSONObjects from a comma delimited text string + * using a supplied JSONArray as the source of element names. + * + * @param names A JSONArray of strings. + * @param string The comma delimited text. + * @return A JSONArray of JSONObjects. + * @throws dev.brighten.ac.utils.json.JSONException + */ + public static dev.brighten.ac.utils.json.JSONArray toJSONArray(dev.brighten.ac.utils.json.JSONArray names, String string) + throws dev.brighten.ac.utils.json.JSONException { + return toJSONArray(names, new dev.brighten.ac.utils.json.JSONTokener(string)); + } + + /** + * Produce a JSONArray of JSONObjects from a comma delimited text string + * using a supplied JSONArray as the source of element names. + * + * @param names A JSONArray of strings. + * @param x A JSONTokener of the source text. + * @return A JSONArray of JSONObjects. + * @throws dev.brighten.ac.utils.json.JSONException + */ + public static dev.brighten.ac.utils.json.JSONArray toJSONArray(dev.brighten.ac.utils.json.JSONArray names, JSONTokener x) + throws dev.brighten.ac.utils.json.JSONException { + if (names == null || names.length() == 0) { + return null; + } + dev.brighten.ac.utils.json.JSONArray ja = new dev.brighten.ac.utils.json.JSONArray(); + for (; ; ) { + dev.brighten.ac.utils.json.JSONObject jo = rowToJSONObject(names, x); + if (jo == null) { + break; + } + ja.put(jo); + } + if (ja.length() == 0) { + return null; + } + return ja; + } + + + /** + * Produce a comma delimited text from a JSONArray of JSONObjects. The + * first row will be a list of names obtained by inspecting the first + * JSONObject. + * + * @param ja A JSONArray of JSONObjects. + * @return A comma delimited text. + * @throws dev.brighten.ac.utils.json.JSONException + */ + public static String toString(dev.brighten.ac.utils.json.JSONArray ja) throws dev.brighten.ac.utils.json.JSONException { + dev.brighten.ac.utils.json.JSONObject jo = ja.optJSONObject(0); + if (jo != null) { + dev.brighten.ac.utils.json.JSONArray names = jo.names(); + if (names != null) { + return rowToString(names) + toString(names, ja); + } + } + return null; + } + + /** + * Produce a comma delimited text from a JSONArray of JSONObjects using + * a provided list of names. The list of names is not included in the + * output. + * + * @param names A JSONArray of strings. + * @param ja A JSONArray of JSONObjects. + * @return A comma delimited text. + * @throws dev.brighten.ac.utils.json.JSONException + */ + public static String toString(dev.brighten.ac.utils.json.JSONArray names, JSONArray ja) + throws JSONException { + if (names == null || names.length() == 0) { + return null; + } + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < ja.length(); i += 1) { + JSONObject jo = ja.optJSONObject(i); + if (jo != null) { + sb.append(rowToString(jo.toJSONArray(names))); + } + } + return sb.toString(); + } +} diff --git a/src/main/java/dev/brighten/ac/utils/json/Cookie.java b/src/main/java/dev/brighten/ac/utils/json/Cookie.java new file mode 100644 index 0000000..2594f68 --- /dev/null +++ b/src/main/java/dev/brighten/ac/utils/json/Cookie.java @@ -0,0 +1,178 @@ +package dev.brighten.ac.utils.json; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import dev.brighten.ac.utils.json.JSONException; +import dev.brighten.ac.utils.json.JSONObject; +import dev.brighten.ac.utils.json.JSONTokener; + +/** + * Convert a web browser cookie specification to a JSONObject and back. + * JSON and Cookies are both notations for name/value pairs. + * + * @author JSON.org + * @version 2010-12-24 + */ +public class Cookie { + + /** + * Produce a copy of a string in which the characters '+', '%', '=', ';' + * and control characters are replaced with "%hh". This is a gentle form + * of URL encoding, attempting to cause as little distortion to the + * string as possible. The characters '=' and ';' are meta characters in + * cookies. By convention, they are escaped using the URL-encoding. This is + * only a convention, not a standard. Often, cookies are expected to have + * encoded values. We encode '=' and ';' because we must. We encode '%' and + * '+' because they are meta characters in URL encoding. + * + * @param string The source string. + * @return The escaped result. + */ + public static String escape(String string) { + char c; + String s = string.trim(); + StringBuffer sb = new StringBuffer(); + int length = s.length(); + for (int i = 0; i < length; i += 1) { + c = s.charAt(i); + if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') { + sb.append('%'); + sb.append(Character.forDigit((char) ((c >>> 4) & 0x0f), 16)); + sb.append(Character.forDigit((char) (c & 0x0f), 16)); + } else { + sb.append(c); + } + } + return sb.toString(); + } + + + /** + * Convert a cookie specification string into a JSONObject. The string + * will contain a name value pair separated by '='. The name and the value + * will be unescaped, possibly converting '+' and '%' sequences. The + * cookie properties may follow, separated by ';', also represented as + * name=value (except the secure property, which does not have a value). + * The name will be stored under the key "name", and the value will be + * stored under the key "value". This method does not do checking or + * validation of the parameters. It only converts the cookie string into + * a JSONObject. + * + * @param string The cookie specification string. + * @return A JSONObject containing "name", "value", and possibly other + * members. + * @throws JSONException + */ + public static JSONObject toJSONObject(String string) throws JSONException { + String name; + JSONObject jo = new JSONObject(); + Object value; + JSONTokener x = new JSONTokener(string); + jo.put("name", x.nextTo('=')); + x.next('='); + jo.put("value", x.nextTo(';')); + x.next(); + while (x.more()) { + name = unescape(x.nextTo("=;")); + if (x.next() != '=') { + if (name.equals("secure")) { + value = Boolean.TRUE; + } else { + throw x.syntaxError("Missing '=' in cookie parameter."); + } + } else { + value = unescape(x.nextTo(';')); + x.next(); + } + jo.put(name, value); + } + return jo; + } + + + /** + * Convert a JSONObject into a cookie specification string. The JSONObject + * must contain "name" and "value" members. + * If the JSONObject contains "expires", "domain", "path", or "secure" + * members, they will be appended to the cookie specification string. + * All other members are ignored. + * + * @param jo A JSONObject + * @return A cookie specification string + * @throws JSONException + */ + public static String toString(JSONObject jo) throws JSONException { + StringBuffer sb = new StringBuffer(); + + sb.append(escape(jo.getString("name"))); + sb.append("="); + sb.append(escape(jo.getString("value"))); + if (jo.has("expires")) { + sb.append(";expires="); + sb.append(jo.getString("expires")); + } + if (jo.has("domain")) { + sb.append(";domain="); + sb.append(escape(jo.getString("domain"))); + } + if (jo.has("path")) { + sb.append(";path="); + sb.append(escape(jo.getString("path"))); + } + if (jo.optBoolean("secure")) { + sb.append(";secure"); + } + return sb.toString(); + } + + /** + * Convert %hh sequences to single characters, and + * convert plus to space. + * + * @param string A string that may contain + * + (plus) and + * %hh sequences. + * @return The unescaped string. + */ + public static String unescape(String string) { + int length = string.length(); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < length; ++i) { + char c = string.charAt(i); + if (c == '+') { + c = ' '; + } else if (c == '%' && i + 2 < length) { + int d = JSONTokener.dehexchar(string.charAt(i + 1)); + int e = JSONTokener.dehexchar(string.charAt(i + 2)); + if (d >= 0 && e >= 0) { + c = (char) (d * 16 + e); + i += 2; + } + } + sb.append(c); + } + return sb.toString(); + } +} diff --git a/src/main/java/dev/brighten/ac/utils/json/CookieList.java b/src/main/java/dev/brighten/ac/utils/json/CookieList.java new file mode 100644 index 0000000..28f0b80 --- /dev/null +++ b/src/main/java/dev/brighten/ac/utils/json/CookieList.java @@ -0,0 +1,98 @@ +package dev.brighten.ac.utils.json; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import dev.brighten.ac.utils.json.Cookie; +import dev.brighten.ac.utils.json.JSONException; +import dev.brighten.ac.utils.json.JSONObject; +import dev.brighten.ac.utils.json.JSONTokener; + +import java.util.Iterator; + +/** + * Convert a web browser cookie list string to a JSONObject and back. + * + * @author JSON.org + * @version 2010-12-24 + */ +public class CookieList { + + /** + * Convert a cookie list into a JSONObject. A cookie list is a sequence + * of name/value pairs. The names are separated from the values by '='. + * The pairs are separated by ';'. The names and the values + * will be unescaped, possibly converting '+' and '%' sequences. + *

+ * To add a cookie to a cooklist, + * cookielistJSONObject.put(cookieJSONObject.getString("name"), + * cookieJSONObject.getString("value")); + * + * @param string A cookie list string + * @return A JSONObject + * @throws JSONException + */ + public static JSONObject toJSONObject(String string) throws JSONException { + JSONObject jo = new JSONObject(); + dev.brighten.ac.utils.json.JSONTokener x = new JSONTokener(string); + while (x.more()) { + String name = dev.brighten.ac.utils.json.Cookie.unescape(x.nextTo('=')); + x.next('='); + jo.put(name, dev.brighten.ac.utils.json.Cookie.unescape(x.nextTo(';'))); + x.next(); + } + return jo; + } + + + /** + * Convert a JSONObject into a cookie list. A cookie list is a sequence + * of name/value pairs. The names are separated from the values by '='. + * The pairs are separated by ';'. The characters '%', '+', '=', and ';' + * in the names and values are replaced by "%hh". + * + * @param jo A JSONObject + * @return A cookie list string + * @throws JSONException + */ + public static String toString(JSONObject jo) throws JSONException { + boolean b = false; + Iterator keys = jo.keys(); + String string; + StringBuffer sb = new StringBuffer(); + while (keys.hasNext()) { + string = keys.next().toString(); + if (!jo.isNull(string)) { + if (b) { + sb.append(';'); + } + sb.append(dev.brighten.ac.utils.json.Cookie.escape(string)); + sb.append("="); + sb.append(Cookie.escape(jo.getString(string))); + b = true; + } + } + return sb.toString(); + } +} diff --git a/src/main/java/dev/brighten/ac/utils/json/HTTP.java b/src/main/java/dev/brighten/ac/utils/json/HTTP.java new file mode 100644 index 0000000..fd29d05 --- /dev/null +++ b/src/main/java/dev/brighten/ac/utils/json/HTTP.java @@ -0,0 +1,172 @@ +package dev.brighten.ac.utils.json; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import dev.brighten.ac.utils.json.HTTPTokener; +import dev.brighten.ac.utils.json.JSONException; +import dev.brighten.ac.utils.json.JSONObject; + +import java.util.Iterator; + +/** + * Convert an HTTP header to a JSONObject and back. + * + * @author JSON.org + * @version 2010-12-24 + */ +public class HTTP { + + /** + * Carriage return/line feed. + */ + public static final String CRLF = "\r\n"; + + /** + * Convert an HTTP header string into a JSONObject. It can be a request + * header or a response header. A request header will contain + *

{
+     *    Method: "POST" (for example),
+     *    "Request-URI": "/" (for example),
+     *    "HTTP-Version": "HTTP/1.1" (for example)
+     * }
+ * A response header will contain + *
{
+     *    "HTTP-Version": "HTTP/1.1" (for example),
+     *    "Fixes-Code": "200" (for example),
+     *    "Reason-Phrase": "OK" (for example)
+     * }
+ * In addition, the other parameters in the header will be captured, using + * the HTTP field names as JSON names, so that
+     *    Date: Sun, 26 May 2002 18:06:04 GMT
+     *    Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s
+     *    Cache-Control: no-cache
+ * become + *
{...
+     *    Date: "Sun, 26 May 2002 18:06:04 GMT",
+     *    Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s",
+     *    "Cache-Control": "no-cache",
+     * ...}
+ * It does no further checking or conversion. It does not parse dates. + * It does not do '%' transforms on URLs. + * + * @param string An HTTP header string. + * @return A JSONObject containing the elements and attributes + * of the XML string. + * @throws dev.brighten.ac.utils.json.JSONException + */ + public static JSONObject toJSONObject(String string) throws dev.brighten.ac.utils.json.JSONException { + JSONObject jo = new JSONObject(); + HTTPTokener x = new HTTPTokener(string); + String token; + + token = x.nextToken(); + if (token.toUpperCase().startsWith("HTTP")) { + +// Response + + jo.put("HTTP-Version", token); + jo.put("Fixes-Code", x.nextToken()); + jo.put("Reason-Phrase", x.nextTo('\0')); + x.next(); + + } else { + +// Request + + jo.put("Method", token); + jo.put("Request-URI", x.nextToken()); + jo.put("HTTP-Version", x.nextToken()); + } + +// Fields + + while (x.more()) { + String name = x.nextTo(':'); + x.next(':'); + jo.put(name, x.nextTo('\0')); + x.next(); + } + return jo; + } + + + /** + * Convert a JSONObject into an HTTP header. A request header must contain + *
{
+     *    Method: "POST" (for example),
+     *    "Request-URI": "/" (for example),
+     *    "HTTP-Version": "HTTP/1.1" (for example)
+     * }
+ * A response header must contain + *
{
+     *    "HTTP-Version": "HTTP/1.1" (for example),
+     *    "Fixes-Code": "200" (for example),
+     *    "Reason-Phrase": "OK" (for example)
+     * }
+ * Any other members of the JSONObject will be output as HTTP fields. + * The result will end with two CRLF pairs. + * + * @param jo A JSONObject + * @return An HTTP header string. + * @throws dev.brighten.ac.utils.json.JSONException if the object does not contain enough + * information. + */ + public static String toString(JSONObject jo) throws dev.brighten.ac.utils.json.JSONException { + Iterator keys = jo.keys(); + String string; + StringBuffer sb = new StringBuffer(); + if (jo.has("Fixes-Code") && jo.has("Reason-Phrase")) { + sb.append(jo.getString("HTTP-Version")); + sb.append(' '); + sb.append(jo.getString("Fixes-Code")); + sb.append(' '); + sb.append(jo.getString("Reason-Phrase")); + } else if (jo.has("Method") && jo.has("Request-URI")) { + sb.append(jo.getString("Method")); + sb.append(' '); + sb.append('"'); + sb.append(jo.getString("Request-URI")); + sb.append('"'); + sb.append(' '); + sb.append(jo.getString("HTTP-Version")); + } else { + throw new JSONException("Not enough material for an HTTP header."); + } + sb.append(CRLF); + while (keys.hasNext()) { + string = keys.next().toString(); + if (!string.equals("HTTP-Version") && !string.equals("Fixes-Code") && + !string.equals("Reason-Phrase") && !string.equals("Method") && + !string.equals("Request-URI") && !jo.isNull(string)) { + sb.append(string); + sb.append(": "); + sb.append(jo.getString(string)); + sb.append(CRLF); + } + } + sb.append(CRLF); + return sb.toString(); + } +} diff --git a/src/main/java/dev/brighten/ac/utils/json/HTTPTokener.java b/src/main/java/dev/brighten/ac/utils/json/HTTPTokener.java new file mode 100644 index 0000000..6796c7a --- /dev/null +++ b/src/main/java/dev/brighten/ac/utils/json/HTTPTokener.java @@ -0,0 +1,83 @@ +package dev.brighten.ac.utils.json; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import dev.brighten.ac.utils.json.JSONException; +import dev.brighten.ac.utils.json.JSONTokener; + +/** + * The HTTPTokener extends the JSONTokener to provide additional methods + * for the parsing of HTTP headers. + * + * @author JSON.org + * @version 2010-12-24 + */ +public class HTTPTokener extends JSONTokener { + + /** + * Construct an HTTPTokener from a string. + * + * @param string A source string. + */ + public HTTPTokener(String string) { + super(string); + } + + + /** + * Get the next token or string. This is used in parsing HTTP headers. + * + * @return A String. + * @throws dev.brighten.ac.utils.json.JSONException + */ + public String nextToken() throws JSONException { + char c; + char q; + StringBuffer sb = new StringBuffer(); + do { + c = next(); + } while (Character.isWhitespace(c)); + if (c == '"' || c == '\'') { + q = c; + for (; ; ) { + c = next(); + if (c < ' ') { + throw syntaxError("Unterminated string."); + } + if (c == q) { + return sb.toString(); + } + sb.append(c); + } + } + for (; ; ) { + if (c == 0 || Character.isWhitespace(c)) { + return sb.toString(); + } + sb.append(c); + c = next(); + } + } +} diff --git a/src/main/java/dev/brighten/ac/utils/json/JSONArray.java b/src/main/java/dev/brighten/ac/utils/json/JSONArray.java new file mode 100644 index 0000000..ebe680d --- /dev/null +++ b/src/main/java/dev/brighten/ac/utils/json/JSONArray.java @@ -0,0 +1,950 @@ +package dev.brighten.ac.utils.json; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import dev.brighten.ac.utils.json.JSONException; +import dev.brighten.ac.utils.json.JSONObject; +import dev.brighten.ac.utils.json.JSONTokener; + +import java.io.IOException; +import java.io.Writer; +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.Map; + +/** + * A JSONArray is an ordered sequence of values. Its external text form is a + * string wrapped in square brackets with commas separating the values. The + * internal form is an object having get and opt + * methods for accessing the values by index, and put methods for + * adding or replacing values. The values can be any of these types: + * Boolean, JSONArray, JSONObject, + * Number, String, or the + * JSONObject.NULL object. + *

+ * The constructor can convert a JSON text into a Java object. The + * toString method converts to JSON text. + *

+ * A get method returns a value if one can be found, and throws an + * exception if one cannot be found. An opt method returns a + * default value instead of throwing an exception, and so is useful for + * obtaining optional values. + *

+ * The generic get() and opt() methods return an + * object which you can cast or query for type. There are also typed + * get and opt methods that do type checking and type + * coercion for you. + *

+ * The texts produced by the toString methods strictly conform to + * JSON syntax rules. The constructors are more forgiving in the texts they will + * accept: + *

    + *
  • An extra , (comma) may appear just + * before the closing bracket.
  • + *
  • The null value will be inserted when there + * is , (comma) elision.
  • + *
  • Strings may be quoted with ' (single + * quote).
  • + *
  • Strings do not need to be quoted at all if they do not begin with a quote + * or single quote, and if they do not contain leading or trailing spaces, + * and if they do not contain any of these characters: + * { } [ ] / \ : , = ; # and if they do not look like numbers + * and if they are not the reserved words true, + * false, or null.
  • + *
  • Values can be separated by ; (semicolon) as + * well as by , (comma).
  • + *
  • Numbers may have the + * 0x- (hex) prefix.
  • + *
+ * + * @author JSON.org + * @version 2011-05-04 + */ +public class JSONArray { + + + /** + * The arrayList where the JSONArray's properties are kept. + */ + private ArrayList myArrayList; + + + /** + * Construct an empty JSONArray. + */ + public JSONArray() { + this.myArrayList = new ArrayList(); + } + + /** + * Construct a JSONArray from a JSONTokener. + * + * @param x A JSONTokener + * @throws JSONException If there is a syntax error. + */ + public JSONArray(dev.brighten.ac.utils.json.JSONTokener x) throws JSONException { + this(); + if (x.nextClean() != '[') { + throw x.syntaxError("A JSONArray text must start with '['"); + } + if (x.nextClean() != ']') { + x.back(); + for (; ; ) { + if (x.nextClean() == ',') { + x.back(); + this.myArrayList.add(JSONObject.NULL); + } else { + x.back(); + this.myArrayList.add(x.nextValue()); + } + switch (x.nextClean()) { + case ';': + case ',': + if (x.nextClean() == ']') { + return; + } + x.back(); + break; + case ']': + return; + default: + throw x.syntaxError("Expected a ',' or ']'"); + } + } + } + } + + + /** + * 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. + */ + public JSONArray(String source) throws JSONException { + this(new JSONTokener(source)); + } + + + /** + * Construct a JSONArray from a Collection. + * + * @param collection A Collection. + */ + public JSONArray(Collection collection) { + this.myArrayList = new ArrayList(); + if (collection != null) { + Iterator iter = collection.iterator(); + while (iter.hasNext()) { + this.myArrayList.add(JSONObject.wrap(iter.next())); + } + } + } + + + /** + * Construct a JSONArray from an array + * + * @throws JSONException If not an array. + */ + public JSONArray(Object array) throws JSONException { + this(); + if (array.getClass().isArray()) { + int length = Array.getLength(array); + for (int i = 0; i < length; i += 1) { + this.put(JSONObject.wrap(Array.get(array, i))); + } + } else { + throw new JSONException( + "JSONArray initial value should be a string or collection or array."); + } + } + + + /** + * Get the object value associated with an index. + * + * @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. + */ + public Object get(int index) throws JSONException { + Object object = opt(index); + if (object == null) { + throw new JSONException("JSONArray[" + index + "] not found."); + } + return object; + } + + + /** + * 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. + * @return The truth. + * @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 = get(index); + if (object.equals(Boolean.FALSE) || + (object instanceof String && + ((String) object).equalsIgnoreCase("false"))) { + return false; + } else if (object.equals(Boolean.TRUE) || + (object instanceof String && + ((String) object).equalsIgnoreCase("true"))) { + return true; + } + throw new JSONException("JSONArray[" + index + "] is not a boolean."); + } + + + /** + * Get the double value associated with an index. + * + * @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. + */ + public double getDouble(int index) throws JSONException { + Object object = get(index); + try { + return object instanceof Number ? + ((Number) object).doubleValue() : + Double.parseDouble((String) object); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + + "] is not a number."); + } + } + + + /** + * Get the int value associated with an index. + * + * @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. + */ + public int getInt(int index) throws JSONException { + Object object = get(index); + try { + return object instanceof Number ? + ((Number) object).intValue() : + Integer.parseInt((String) object); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + + "] is not a number."); + } + } + + + /** + * Get the JSONArray associated with an index. + * + * @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 + */ + public dev.brighten.ac.utils.json.JSONArray getJSONArray(int index) throws JSONException { + Object object = get(index); + if (object instanceof dev.brighten.ac.utils.json.JSONArray) { + return (dev.brighten.ac.utils.json.JSONArray) object; + } + throw new JSONException("JSONArray[" + index + + "] is not a JSONArray."); + } + + + /** + * Get the JSONObject associated with an index. + * + * @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 + */ + public JSONObject getJSONObject(int index) throws JSONException { + Object object = get(index); + if (object instanceof JSONObject) { + return (JSONObject) object; + } + throw new JSONException("JSONArray[" + index + + "] is not a JSONObject."); + } + + + /** + * Get the long value associated with an index. + * + * @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. + */ + public long getLong(int index) throws JSONException { + Object object = get(index); + try { + return object instanceof Number ? + ((Number) object).longValue() : + Long.parseLong((String) object); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + + "] is not a number."); + } + } + + + /** + * Get the string associated with an index. + * + * @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. + */ + public String getString(int index) throws JSONException { + Object object = get(index); + if (object instanceof String) { + return (String) object; + } + throw new JSONException("JSONArray[" + index + "] not a string."); + } + + + /** + * Determine if the value is null. + * + * @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) { + return JSONObject.NULL.equals(opt(index)); + } + + + /** + * Make a string from the contents of this JSONArray. The + * 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. + * @return a string. + * @throws JSONException If the array contains an invalid number. + */ + public String join(String separator) throws JSONException { + int len = length(); + StringBuffer sb = new StringBuffer(); + + for (int i = 0; i < len; i += 1) { + if (i > 0) { + sb.append(separator); + } + sb.append(JSONObject.valueToString(this.myArrayList.get(i))); + } + return sb.toString(); + } + + + /** + * Get the number of elements in the JSONArray, included nulls. + * + * @return The length (or size). + */ + public int length() { + return this.myArrayList.size(); + } + + + /** + * Get the optional object value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return An object value, or null if there is no + * object at that index. + */ + public Object opt(int index) { + return (index < 0 || index >= length()) ? + null : this.myArrayList.get(index); + } + + + /** + * Get the optional boolean value associated with an index. + * It returns false 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. + * @return The truth. + */ + public boolean optBoolean(int index) { + return optBoolean(index, false); + } + + + /** + * Get the optional boolean value associated with an index. + * It returns the 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. + * @return The truth. + */ + public boolean optBoolean(int index, boolean defaultValue) { + try { + return getBoolean(index); + } catch (Exception e) { + return defaultValue; + } + } + + + /** + * 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 index The index must be between 0 and length() - 1. + * @return The value. + */ + public double optDouble(int index) { + return optDouble(index, Double.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 index subscript + * @param defaultValue The default value. + * @return The value. + */ + public double optDouble(int index, double defaultValue) { + try { + return getDouble(index); + } catch (Exception e) { + return defaultValue; + } + } + + + /** + * Get the optional int value associated with an index. + * Zero 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. + * @return The value. + */ + public int optInt(int index) { + return optInt(index, 0); + } + + + /** + * Get the optional int 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. + * @return The value. + */ + public int optInt(int index, int defaultValue) { + try { + return getInt(index); + } catch (Exception e) { + return defaultValue; + } + } + + + /** + * Get the optional JSONArray associated with an index. + * + * @param index subscript + * @return A JSONArray value, or null if the index has no value, + * or if the value is not a JSONArray. + */ + public dev.brighten.ac.utils.json.JSONArray optJSONArray(int index) { + Object o = opt(index); + return o instanceof dev.brighten.ac.utils.json.JSONArray ? (dev.brighten.ac.utils.json.JSONArray) o : null; + } + + + /** + * Get the optional JSONObject associated with an index. + * Null is returned if 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. + * @return A JSONObject value. + */ + public JSONObject optJSONObject(int index) { + Object o = opt(index); + return o instanceof JSONObject ? (JSONObject) o : null; + } + + + /** + * Get the optional long value associated with an index. + * Zero 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. + * @return The value. + */ + public long optLong(int index) { + return optLong(index, 0); + } + + + /** + * Get the optional long 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. + * @return The value. + */ + public long optLong(int index, long defaultValue) { + try { + return getLong(index); + } catch (Exception e) { + return defaultValue; + } + } + + + /** + * Get the optional string value associated with an index. It returns an + * empty string if there is no value at that index. If the value + * is not a string and is not null, then it is coverted to a string. + * + * @param index The index must be between 0 and length() - 1. + * @return A String value. + */ + public String optString(int index) { + return optString(index, ""); + } + + + /** + * 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. + * @return A String value. + */ + public String optString(int index, String defaultValue) { + Object object = opt(index); + return object != null ? object.toString() : defaultValue; + } + + + /** + * Append a boolean value. This increases the array's length by one. + * + * @param value A boolean value. + * @return this. + */ + public dev.brighten.ac.utils.json.JSONArray put(boolean value) { + put(value ? Boolean.TRUE : Boolean.FALSE); + return this; + } + + + /** + * Put a value in the JSONArray, where the value will be a + * JSONArray which is produced from a Collection. + * + * @param value A Collection value. + * @return this. + */ + public dev.brighten.ac.utils.json.JSONArray put(Collection value) { + put(new dev.brighten.ac.utils.json.JSONArray(value)); + return this; + } + + + /** + * Append a double value. This increases the array's length by one. + * + * @param value A double value. + * @return this. + * @throws JSONException if the value is not finite. + */ + public dev.brighten.ac.utils.json.JSONArray put(double value) throws JSONException { + Double d = new Double(value); + JSONObject.testValidity(d); + put(d); + return this; + } + + + /** + * Append an int value. This increases the array's length by one. + * + * @param value An int value. + * @return this. + */ + public dev.brighten.ac.utils.json.JSONArray put(int value) { + put(new Integer(value)); + return this; + } + + + /** + * Append an long value. This increases the array's length by one. + * + * @param value A long value. + * @return this. + */ + public dev.brighten.ac.utils.json.JSONArray put(long value) { + put(new Long(value)); + return this; + } + + + /** + * Put a value in the JSONArray, where the value will be a + * JSONObject which is produced from a Map. + * + * @param value A Map value. + * @return this. + */ + public dev.brighten.ac.utils.json.JSONArray put(Map value) { + put(new JSONObject(value)); + return this; + } + + + /** + * 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. + * @return this. + */ + public dev.brighten.ac.utils.json.JSONArray put(Object value) { + this.myArrayList.add(value); + return this; + } + + + /** + * Put or replace a boolean value in the JSONArray. If the index is greater + * 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. + * @return this. + * @throws JSONException If the index is negative. + */ + public dev.brighten.ac.utils.json.JSONArray put(int index, boolean value) throws JSONException { + put(index, value ? Boolean.TRUE : Boolean.FALSE); + return this; + } + + + /** + * 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. + * @return this. + * @throws JSONException If the index is negative or if the value is + * not finite. + */ + public dev.brighten.ac.utils.json.JSONArray put(int index, Collection value) throws JSONException { + put(index, new dev.brighten.ac.utils.json.JSONArray(value)); + return this; + } + + + /** + * Put or replace a double value. If the index is greater 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 double value. + * @return this. + * @throws JSONException If the index is negative or if the value is + * not finite. + */ + public dev.brighten.ac.utils.json.JSONArray put(int index, double value) throws JSONException { + put(index, new Double(value)); + return this; + } + + + /** + * Put or replace an int value. If the index is greater than the length of + * the JSONArray, then null elements will be added as necessary to pad + * it out. + * + * @param index The subscript. + * @param value An int value. + * @return this. + * @throws JSONException If the index is negative. + */ + public dev.brighten.ac.utils.json.JSONArray put(int index, int value) throws JSONException { + put(index, new Integer(value)); + return this; + } + + + /** + * Put or replace a long value. If the index is greater 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 long value. + * @return this. + * @throws JSONException If the index is negative. + */ + public dev.brighten.ac.utils.json.JSONArray put(int index, long value) throws JSONException { + put(index, new Long(value)); + return this; + } + + + /** + * 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. + * @return this. + * @throws JSONException If the index is negative or if the the value is + * an invalid number. + */ + public dev.brighten.ac.utils.json.JSONArray put(int index, Map value) throws JSONException { + put(index, new JSONObject(value)); + return this; + } + + + /** + * Put or replace an object value in the JSONArray. If the index is greater + * 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. + * @return this. + * @throws JSONException If the index is negative or if the the value is + * an invalid number. + */ + public dev.brighten.ac.utils.json.JSONArray put(int index, Object value) throws JSONException { + JSONObject.testValidity(value); + if (index < 0) { + throw new JSONException("JSONArray[" + index + "] not found."); + } + if (index < length()) { + this.myArrayList.set(index, value); + } else { + while (index != length()) { + put(JSONObject.NULL); + } + put(value); + } + return this; + } + + + /** + * Remove an index and close the hole. + * + * @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. + */ + public Object remove(int index) { + Object o = opt(index); + this.myArrayList.remove(index); + return o; + } + + + /** + * 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. + * @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. + */ + public JSONObject toJSONObject(dev.brighten.ac.utils.json.JSONArray names) throws JSONException { + if (names == null || names.length() == 0 || length() == 0) { + return null; + } + JSONObject jo = new JSONObject(); + for (int i = 0; i < names.length(); i += 1) { + jo.put(names.getString(i), this.opt(i)); + } + return jo; + } + + + /** + * Make a JSON text of this JSONArray. For compactness, no + * unnecessary whitespace is added. If it is not possible to produce a + * syntactically correct JSON text then null will be returned instead. This + * could occur if the array contains an invalid number. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @return a printable, displayable, transmittable + * representation of the array. + */ + public String toString() { + try { + return '[' + join(",") + ']'; + } catch (Exception e) { + return null; + } + } + + + /** + * Make a prettyprinted JSON text of this JSONArray. + * 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, transmittable + * representation of the object, beginning + * with [ (left bracket) and ending + * with ] (right bracket). + * @throws JSONException + */ + public String toString(int indentFactor) throws JSONException { + return toString(indentFactor, 0); + } + + + /** + * Make a prettyprinted JSON text of this JSONArray. + * Warning: This method assumes that the data structure is acyclical. + * + * @param indentFactor The number of spaces to add to each level of + * indentation. + * @param indent The indention of the top level. + * @return a printable, displayable, transmittable + * representation of the array. + * @throws JSONException + */ + String toString(int indentFactor, int indent) throws JSONException { + int len = length(); + if (len == 0) { + return "[]"; + } + int i; + StringBuffer sb = new StringBuffer("["); + if (len == 1) { + sb.append(JSONObject.valueToString(this.myArrayList.get(0), + indentFactor, indent)); + } else { + int newindent = indent + indentFactor; + sb.append('\n'); + for (i = 0; i < len; i += 1) { + if (i > 0) { + sb.append(",\n"); + } + for (int j = 0; j < newindent; j += 1) { + sb.append(' '); + } + sb.append(JSONObject.valueToString(this.myArrayList.get(i), + indentFactor, newindent)); + } + sb.append('\n'); + for (i = 0; i < indent; i += 1) { + sb.append(' '); + } + } + sb.append(']'); + return sb.toString(); + } + + + /** + * Write the contents of the JSONArray 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 { + try { + boolean b = false; + int len = length(); + + writer.write('['); + + for (int i = 0; i < len; i += 1) { + if (b) { + writer.write(','); + } + Object v = this.myArrayList.get(i); + if (v instanceof JSONObject) { + ((JSONObject) v).write(writer); + } else if (v instanceof dev.brighten.ac.utils.json.JSONArray) { + ((dev.brighten.ac.utils.json.JSONArray) v).write(writer); + } else { + writer.write(JSONObject.valueToString(v)); + } + b = true; + } + writer.write(']'); + return writer; + } catch (IOException e) { + throw new JSONException(e); + } + } +} \ No newline at end of file diff --git a/src/main/java/dev/brighten/ac/utils/json/JSONException.java b/src/main/java/dev/brighten/ac/utils/json/JSONException.java new file mode 100644 index 0000000..5478eb8 --- /dev/null +++ b/src/main/java/dev/brighten/ac/utils/json/JSONException.java @@ -0,0 +1,30 @@ +package dev.brighten.ac.utils.json; + +/** + * The JSONException is thrown by the JSON.org classes when things are amiss. + * + * @author JSON.org + * @version 2010-12-24 + */ +public class JSONException extends Exception { + private static final long serialVersionUID = 0; + private Throwable cause; + + /** + * Constructs a JSONException with an explanatory message. + * + * @param message Detail about the reason for the exception. + */ + public JSONException(String message) { + super(message); + } + + public JSONException(Throwable cause) { + super(cause.getMessage()); + this.cause = cause; + } + + public Throwable getCause() { + return this.cause; + } +} diff --git a/src/main/java/dev/brighten/ac/utils/json/JSONML.java b/src/main/java/dev/brighten/ac/utils/json/JSONML.java new file mode 100644 index 0000000..1f7a2ba --- /dev/null +++ b/src/main/java/dev/brighten/ac/utils/json/JSONML.java @@ -0,0 +1,470 @@ +package dev.brighten.ac.utils.json; + +/* +Copyright (c) 2008 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import dev.brighten.ac.utils.json.JSONArray; +import dev.brighten.ac.utils.json.JSONException; +import dev.brighten.ac.utils.json.JSONObject; +import dev.brighten.ac.utils.json.XML; +import dev.brighten.ac.utils.json.XMLTokener; + +import java.util.Iterator; + + +/** + * This provides static methods to convert an XML text into a JSONArray or + * JSONObject, and to covert a JSONArray or JSONObject into an XML text using + * the JsonML transform. + * + * @author JSON.org + * @version 2010-12-23 + */ +public class JSONML { + + /** + * Parse XML values and store them in a JSONArray. + * + * @param x The XMLTokener containing the source string. + * @param arrayForm true if array form, false if object form. + * @param ja The JSONArray that is containing the current tag or null + * if we are at the outermost level. + * @return A JSONArray if the value is the outermost tag, otherwise null. + * @throws dev.brighten.ac.utils.json.JSONException + */ + private static Object parse(dev.brighten.ac.utils.json.XMLTokener x, boolean arrayForm, + dev.brighten.ac.utils.json.JSONArray ja) throws dev.brighten.ac.utils.json.JSONException { + String attribute; + char c; + String closeTag = null; + int i; + dev.brighten.ac.utils.json.JSONArray newja = null; + dev.brighten.ac.utils.json.JSONObject newjo = null; + Object token; + String tagName = null; + +// Test for and skip past these forms: +// +// +// +// + + while (true) { + token = x.nextContent(); + if (token == dev.brighten.ac.utils.json.XML.LT) { + token = x.nextToken(); + if (token instanceof Character) { + if (token == dev.brighten.ac.utils.json.XML.SLASH) { + +// Close tag "); + } + x.back(); + } else if (c == '[') { + token = x.nextToken(); + if (token.equals("CDATA") && x.next() == '[') { + if (ja != null) { + ja.put(x.nextCDATA()); + } + } else { + throw x.syntaxError("Expected 'CDATA['"); + } + } else { + i = 1; + do { + token = x.nextMeta(); + if (token == null) { + throw x.syntaxError("Missing '>' after ' 0); + } + } else if (token == dev.brighten.ac.utils.json.XML.QUEST) { + +// "); + } else { + throw x.syntaxError("Misshaped tag"); + } + +// Open tag < + + } else { + if (!(token instanceof String)) { + throw x.syntaxError("Bad tagName '" + token + "'."); + } + tagName = (String) token; + newja = new dev.brighten.ac.utils.json.JSONArray(); + newjo = new dev.brighten.ac.utils.json.JSONObject(); + if (arrayForm) { + newja.put(tagName); + if (ja != null) { + ja.put(newja); + } + } else { + newjo.put("tagName", tagName); + if (ja != null) { + ja.put(newjo); + } + } + token = null; + for (; ; ) { + if (token == null) { + token = x.nextToken(); + } + if (token == null) { + throw x.syntaxError("Misshaped tag"); + } + if (!(token instanceof String)) { + break; + } + +// attribute = value + + attribute = (String) token; + if (!arrayForm && (attribute == "tagName" || attribute == "childNode")) { + throw x.syntaxError("Reserved attribute."); + } + token = x.nextToken(); + if (token == dev.brighten.ac.utils.json.XML.EQ) { + token = x.nextToken(); + if (!(token instanceof String)) { + throw x.syntaxError("Missing value"); + } + newjo.accumulate(attribute, dev.brighten.ac.utils.json.XML.stringToValue((String) token)); + token = null; + } else { + newjo.accumulate(attribute, ""); + } + } + if (arrayForm && newjo.length() > 0) { + newja.put(newjo); + } + +// Empty tag <.../> + + if (token == dev.brighten.ac.utils.json.XML.SLASH) { + if (x.nextToken() != dev.brighten.ac.utils.json.XML.GT) { + throw x.syntaxError("Misshaped tag"); + } + if (ja == null) { + if (arrayForm) { + return newja; + } else { + return newjo; + } + } + +// Content, between <...> and + + } else { + if (token != dev.brighten.ac.utils.json.XML.GT) { + throw x.syntaxError("Misshaped tag"); + } + closeTag = (String) parse(x, arrayForm, newja); + if (closeTag != null) { + if (!closeTag.equals(tagName)) { + throw x.syntaxError("Mismatched '" + tagName + + "' and '" + closeTag + "'"); + } + tagName = null; + if (!arrayForm && newja.length() > 0) { + newjo.put("childNodes", newja); + } + if (ja == null) { + if (arrayForm) { + return newja; + } else { + return newjo; + } + } + } + } + } + } else { + if (ja != null) { + ja.put(token instanceof String ? + dev.brighten.ac.utils.json.XML.stringToValue((String) token) : token); + } + } + } + } + + + /** + * Convert a well-formed (but not necessarily valid) XML string into a + * JSONArray using the JsonML transform. Each XML tag is represented as + * a JSONArray in which the first element is the tag name. If the tag has + * attributes, then the second element will be JSONObject containing the + * name/value pairs. If the tag contains children, then strings and + * JSONArrays will represent the child tags. + * Comments, prologs, DTDs, and <[ [ ]]> are ignored. + * + * @param string The source string. + * @return A JSONArray containing the structured data from the XML string. + * @throws dev.brighten.ac.utils.json.JSONException + */ + public static dev.brighten.ac.utils.json.JSONArray toJSONArray(String string) throws dev.brighten.ac.utils.json.JSONException { + return toJSONArray(new dev.brighten.ac.utils.json.XMLTokener(string)); + } + + + /** + * Convert a well-formed (but not necessarily valid) XML string into a + * JSONArray using the JsonML transform. Each XML tag is represented as + * a JSONArray in which the first element is the tag name. If the tag has + * attributes, then the second element will be JSONObject containing the + * name/value pairs. If the tag contains children, then strings and + * JSONArrays will represent the child content and tags. + * Comments, prologs, DTDs, and <[ [ ]]> are ignored. + * + * @param x An XMLTokener. + * @return A JSONArray containing the structured data from the XML string. + * @throws dev.brighten.ac.utils.json.JSONException + */ + public static dev.brighten.ac.utils.json.JSONArray toJSONArray(dev.brighten.ac.utils.json.XMLTokener x) throws dev.brighten.ac.utils.json.JSONException { + return (dev.brighten.ac.utils.json.JSONArray) parse(x, true, null); + } + + + /** + * Convert a well-formed (but not necessarily valid) XML string into a + * JSONObject using the JsonML transform. Each XML tag is represented as + * a JSONObject with a "tagName" property. If the tag has attributes, then + * the attributes will be in the JSONObject as properties. If the tag + * contains children, the object will have a "childNodes" property which + * will be an array of strings and JsonML JSONObjects. + *

+ * Comments, prologs, DTDs, and <[ [ ]]> are ignored. + * + * @param x An XMLTokener of the XML source text. + * @return A JSONObject containing the structured data from the XML string. + * @throws dev.brighten.ac.utils.json.JSONException + */ + public static dev.brighten.ac.utils.json.JSONObject toJSONObject(dev.brighten.ac.utils.json.XMLTokener x) throws dev.brighten.ac.utils.json.JSONException { + return (dev.brighten.ac.utils.json.JSONObject) parse(x, false, null); + } + + + /** + * Convert a well-formed (but not necessarily valid) XML string into a + * JSONObject using the JsonML transform. Each XML tag is represented as + * a JSONObject with a "tagName" property. If the tag has attributes, then + * the attributes will be in the JSONObject as properties. If the tag + * contains children, the object will have a "childNodes" property which + * will be an array of strings and JsonML JSONObjects. + *

+ * Comments, prologs, DTDs, and <[ [ ]]> are ignored. + * + * @param string The XML source text. + * @return A JSONObject containing the structured data from the XML string. + * @throws dev.brighten.ac.utils.json.JSONException + */ + public static dev.brighten.ac.utils.json.JSONObject toJSONObject(String string) throws dev.brighten.ac.utils.json.JSONException { + return toJSONObject(new XMLTokener(string)); + } + + + /** + * Reverse the JSONML transformation, making an XML text from a JSONArray. + * + * @param ja A JSONArray. + * @return An XML string. + * @throws dev.brighten.ac.utils.json.JSONException + */ + public static String toString(dev.brighten.ac.utils.json.JSONArray ja) throws dev.brighten.ac.utils.json.JSONException { + int i; + dev.brighten.ac.utils.json.JSONObject jo; + String key; + Iterator keys; + int length; + Object object; + StringBuffer sb = new StringBuffer(); + String tagName; + String value; + +// Emit = length) { + sb.append('/'); + sb.append('>'); + } else { + sb.append('>'); + do { + object = ja.get(i); + i += 1; + if (object != null) { + if (object instanceof String) { + sb.append(dev.brighten.ac.utils.json.XML.escape(object.toString())); + } else if (object instanceof dev.brighten.ac.utils.json.JSONObject) { + sb.append(toString((dev.brighten.ac.utils.json.JSONObject) object)); + } else if (object instanceof dev.brighten.ac.utils.json.JSONArray) { + sb.append(toString((dev.brighten.ac.utils.json.JSONArray) object)); + } + } + } while (i < length); + sb.append('<'); + sb.append('/'); + sb.append(tagName); + sb.append('>'); + } + return sb.toString(); + } + + /** + * Reverse the JSONML transformation, making an XML text from a JSONObject. + * The JSONObject must contain a "tagName" property. If it has children, + * then it must have a "childNodes" property containing an array of objects. + * The other properties are attributes with string values. + * + * @param jo A JSONObject. + * @return An XML string. + * @throws dev.brighten.ac.utils.json.JSONException + */ + public static String toString(dev.brighten.ac.utils.json.JSONObject jo) throws JSONException { + StringBuffer sb = new StringBuffer(); + int i; + dev.brighten.ac.utils.json.JSONArray ja; + String key; + Iterator keys; + int length; + Object object; + String tagName; + String value; + +//Emit '); + } else { + sb.append('>'); + length = ja.length(); + for (i = 0; i < length; i += 1) { + object = ja.get(i); + if (object != null) { + if (object instanceof String) { + sb.append(XML.escape(object.toString())); + } else if (object instanceof dev.brighten.ac.utils.json.JSONObject) { + sb.append(toString((JSONObject) object)); + } else if (object instanceof dev.brighten.ac.utils.json.JSONArray) { + sb.append(toString((JSONArray) object)); + } + } + } + sb.append('<'); + sb.append('/'); + sb.append(tagName); + sb.append('>'); + } + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/dev/brighten/ac/utils/json/JSONObject.java b/src/main/java/dev/brighten/ac/utils/json/JSONObject.java new file mode 100644 index 0000000..67e4856 --- /dev/null +++ b/src/main/java/dev/brighten/ac/utils/json/JSONObject.java @@ -0,0 +1,1601 @@ +package dev.brighten.ac.utils.json; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import java.io.IOException; +import java.io.Writer; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.*; + +/** + * A JSONObject is an unordered collection of name/value pairs. Its + * external form is a string wrapped in curly braces with colons between the + * names and values, and commas between the values and names. The internal form + * is an object having get and opt methods for + * accessing the values by name, and put methods for adding or + * replacing values by name. The values can be any of these types: + * Boolean, JSONArray, JSONObject, + * Number, String, or the JSONObject.NULL + * object. A JSONObject constructor can be used to convert an external form + * JSON text into an internal form whose values can be retrieved with the + * get and opt methods, or to convert values into a + * JSON text using the put and toString methods. + * A get method returns a value if one can be found, and throws an + * exception if one cannot be found. An opt method returns a + * default value instead of throwing an exception, and so is useful for + * obtaining optional values. + *

+ * The generic get() and opt() methods return an + * object, which you can cast or query for type. There are also typed + * get and opt methods that do type checking and type + * coercion for you. The opt methods differ from the get methods in that they + * do not throw. Instead, they return a specified value, such as null. + *

+ * The put methods add or replace values in an object. For example, + *

myString = new JSONObject().put("JSON", "Hello, World!").toString();
+ * produces the string {"JSON": "Hello, World"}. + *

+ * The texts produced by the toString methods strictly conform to + * the JSON syntax rules. + * The constructors are more forgiving in the texts they will accept: + *

    + *
  • An extra , (comma) may appear just + * before the closing brace.
  • + *
  • Strings may be quoted with ' (single + * quote).
  • + *
  • Strings do not need to be quoted at all if they do not begin with a quote + * or single quote, and if they do not contain leading or trailing spaces, + * and if they do not contain any of these characters: + * { } [ ] / \ : , = ; # and if they do not look like numbers + * and if they are not the reserved words true, + * false, or null.
  • + *
  • Keys can be followed by = or => as well as + * by :.
  • + *
  • Values can be followed by ; (semicolon) as + * well as by , (comma).
  • + *
  • Numbers may have the 0x- (hex) prefix.
  • + *
+ * + * @author JSON.org + * @version 2011-04-05 + */ +public class JSONObject { + + /** + * 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(); + /** + * The map where the JSONObject's properties are kept. + */ + private Map map; + + + /** + * Construct an empty JSONObject. + */ + public JSONObject() { + this.map = new HashMap(); + } + + + /** + * Construct a JSONObject from a subset of another JSONObject. + * An array of 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. + */ + public JSONObject(dev.brighten.ac.utils.json.JSONObject jo, String[] names) { + this(); + for (int i = 0; i < names.length; i += 1) { + try { + putOnce(names[i], jo.opt(names[i])); + } catch (Exception ignore) { + } + } + } + + + /** + * Construct a JSONObject from a JSONTokener. + * + * @param x A JSONTokener object containing the source string. + * @throws dev.brighten.ac.utils.json.JSONException If there is a syntax error in the source string + * or a duplicated key. + */ + public JSONObject(dev.brighten.ac.utils.json.JSONTokener x) throws dev.brighten.ac.utils.json.JSONException { + this(); + char c; + String key; + + if (x.nextClean() != '{') { + throw x.syntaxError("A JSONObject text must begin with '{'"); + } + for (; ; ) { + c = x.nextClean(); + switch (c) { + case 0: + throw x.syntaxError("A JSONObject text must end with '}'"); + case '}': + return; + default: + x.back(); + key = x.nextValue().toString(); + } + +// The key is followed by ':'. We will also tolerate '=' or '=>'. + + c = x.nextClean(); + if (c == '=') { + if (x.next() != '>') { + x.back(); + } + } else if (c != ':') { + throw x.syntaxError("Expected a ':' after a key"); + } + putOnce(key, x.nextValue()); + +// Pairs are separated by ','. We will also tolerate ';'. + + switch (x.nextClean()) { + case ';': + case ',': + if (x.nextClean() == '}') { + return; + } + x.back(); + break; + case '}': + return; + default: + throw x.syntaxError("Expected a ',' or '}'"); + } + } + } + + + /** + * Construct a JSONObject from a Map. + * + * @param map A map object that can be used to initialize the contents of + * the JSONObject. + */ + public JSONObject(Map map) { + this.map = new HashMap(); + if (map != null) { + Iterator i = map.entrySet().iterator(); + while (i.hasNext()) { + Map.Entry e = (Map.Entry) i.next(); + Object value = e.getValue(); + if (value != null) { + this.map.put(e.getKey(), wrap(value)); + } + } + } + } + + + /** + * Construct a JSONObject from an Object using bean getters. + * It reflects on all of the public methods of the object. + * For each of the methods with no parameters and a name starting + * with "get" or "is" followed by an uppercase letter, + * the method is invoked, and a key and the value returned from the getter method + * are put into the new JSONObject. + *

+ * The key is formed by removing the "get" or "is" prefix. + * If the second remaining character is not upper case, then the first + * character is converted to lower case. + *

+ * For example, if an object has a method named "getName", and + * if the result of calling object.getName() is "Larry Fine", + * then the JSONObject will contain "name": "Larry Fine". + * + * @param bean An object that has getter methods that should be used + * to make a JSONObject. + */ + public JSONObject(Object bean) { + this(); + populateMap(bean); + } + + + /** + * Construct a JSONObject from an Object, using reflection to find the + * public members. The resulting JSONObject's keys will be the strings + * from the names array, and the values will be the field values associated + * with 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. + */ + public JSONObject(Object object, String names[]) { + this(); + Class c = object.getClass(); + for (int i = 0; i < names.length; i += 1) { + String name = names[i]; + try { + putOpt(name, c.getField(name).get(object)); + } catch (Exception ignore) { + } + } + } + + + /** + * 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). + * @throws dev.brighten.ac.utils.json.JSONException If there is a syntax error in the source + * string or a duplicated key. + */ + public JSONObject(String source) throws dev.brighten.ac.utils.json.JSONException { + this(new JSONTokener(source)); + } + + + /** + * Construct a JSONObject from a ResourceBundle. + * + * @param baseName The ResourceBundle base name. + * @param locale The Locale to load the ResourceBundle for. + * @throws dev.brighten.ac.utils.json.JSONException If any JSONExceptions are detected. + */ + public JSONObject(String baseName, Locale locale) throws dev.brighten.ac.utils.json.JSONException { + this(); + ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, + Thread.currentThread().getContextClassLoader()); + +// Iterate through the keys in the bundle. + + Enumeration keys = bundle.getKeys(); + while (keys.hasMoreElements()) { + Object key = keys.nextElement(); + if (key instanceof String) { + +// Go through the path, ensuring that there is a nested JSONObject for each +// segment except the last. Add the value using the last segment's name into +// the deepest nested JSONObject. + + String[] path = ((String) key).split("\\."); + int last = path.length - 1; + dev.brighten.ac.utils.json.JSONObject target = this; + for (int i = 0; i < last; i += 1) { + String segment = path[i]; + dev.brighten.ac.utils.json.JSONObject nextTarget = target.optJSONObject(segment); + if (nextTarget == null) { + nextTarget = new dev.brighten.ac.utils.json.JSONObject(); + target.put(segment, nextTarget); + } + target = nextTarget; + } + target.put(path[last], bundle.getString((String) key)); + } + } + } + + /** + * Produce a string from a double. The string "null" will be returned if + * the number is not finite. + * + * @param d A double. + * @return A String. + */ + public static String doubleToString(double d) { + if (Double.isInfinite(d) || Double.isNaN(d)) { + return "null"; + } + +// Shave off trailing zeros and decimal point, if possible. + + String string = Double.toString(d); + if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && + string.indexOf('E') < 0) { + while (string.endsWith("0")) { + string = string.substring(0, string.length() - 1); + } + if (string.endsWith(".")) { + string = string.substring(0, string.length() - 1); + } + } + return string; + } + + /** + * Get an array of field names from a JSONObject. + * + * @return An array of field names, or null if there are no names. + */ + public static String[] getNames(dev.brighten.ac.utils.json.JSONObject jo) { + int length = jo.length(); + if (length == 0) { + return null; + } + Iterator iterator = jo.keys(); + String[] names = new String[length]; + int i = 0; + while (iterator.hasNext()) { + names[i] = (String) iterator.next(); + i += 1; + } + return names; + } + + /** + * Get an array of field names from an Object. + * + * @return An array of field names, or null if there are no names. + */ + public static String[] getNames(Object object) { + if (object == null) { + return null; + } + Class klass = object.getClass(); + Field[] fields = klass.getFields(); + int length = fields.length; + if (length == 0) { + return null; + } + String[] names = new String[length]; + for (int i = 0; i < length; i += 1) { + names[i] = fields[i].getName(); + } + return names; + } + + /** + * Produce a string from a Number. + * + * @param number A Number + * @return A String. + * @throws dev.brighten.ac.utils.json.JSONException If n is a non-finite number. + */ + public static String numberToString(Number number) + throws dev.brighten.ac.utils.json.JSONException { + if (number == null) { + throw new dev.brighten.ac.utils.json.JSONException("Null pointer"); + } + testValidity(number); + +// Shave off trailing zeros and decimal point, if possible. + + String string = number.toString(); + if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && + string.indexOf('E') < 0) { + while (string.endsWith("0")) { + string = string.substring(0, string.length() - 1); + } + if (string.endsWith(".")) { + string = string.substring(0, string.length() - 1); + } + } + return string; + } + + /** + * Produce a string in double quotes with backslash sequences in all the + * right places. A backslash will be inserted within = '\u0080' && c < '\u00a0') || + (c >= '\u2000' && c < '\u2100')) { + hhhh = "000" + Integer.toHexString(c); + sb.append("\\u" + hhhh.substring(hhhh.length() - 4)); + } else { + sb.append(c); + } + } + } + sb.append('"'); + return sb.toString(); + } + + /** + * 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. + * @return A simple JSON value. + */ + public static Object stringToValue(String string) { + if (string.equals("")) { + return string; + } + if (string.equalsIgnoreCase("true")) { + return Boolean.TRUE; + } + if (string.equalsIgnoreCase("false")) { + return Boolean.FALSE; + } + if (string.equalsIgnoreCase("null")) { + return dev.brighten.ac.utils.json.JSONObject.NULL; + } + + /* + * If it might be a number, try converting it. + * We support the non-standard 0x- convention. + * If a number cannot be produced, then the value will just + * be a string. Note that the 0x-, plus, and implied string + * conventions are non-standard. A JSON parser may accept + * non-JSON forms as long as it accepts all correct JSON forms. + */ + + char b = string.charAt(0); + if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') { + if (b == '0' && string.length() > 2 && + (string.charAt(1) == 'x' || string.charAt(1) == 'X')) { + try { + return new Integer(Integer.parseInt(string.substring(2), 16)); + } catch (Exception ignore) { + } + } + try { + if (string.indexOf('.') > -1 || + string.indexOf('e') > -1 || string.indexOf('E') > -1) { + return Double.valueOf(string); + } else { + Long myLong = new Long(string); + if (myLong.longValue() == myLong.intValue()) { + return new Integer(myLong.intValue()); + } else { + return myLong; + } + } + } catch (Exception ignore) { + } + } + return string; + } + + /** + * Throw an exception if the object is a NaN or infinite number. + * + * @param o The object to test. + * @throws dev.brighten.ac.utils.json.JSONException If o is a non-finite number. + */ + public static void testValidity(Object o) throws dev.brighten.ac.utils.json.JSONException { + if (o != null) { + if (o instanceof Double) { + if (((Double) o).isInfinite() || ((Double) o).isNaN()) { + throw new dev.brighten.ac.utils.json.JSONException( + "JSON does not allow non-finite numbers."); + } + } else if (o instanceof Float) { + if (((Float) o).isInfinite() || ((Float) o).isNaN()) { + throw new dev.brighten.ac.utils.json.JSONException( + "JSON does not allow non-finite numbers."); + } + } + } + } + + /** + * 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 JSON text. The method is required to produce a strictly + * conforming text. If the object does not contain a toJSONString + * method (which is the most common case), then a text will be + * produced by other means. If the value is an array or Collection, + * then a JSONArray will be made from it and its toJSONString method + * will be called. If the value is a MAP, then a JSONObject will be made + * from it and its toJSONString method will be called. Otherwise, the + * value's toString method will be called, and the result will be quoted. + * + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @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 dev.brighten.ac.utils.json.JSONException If the value is or contains an invalid number. + */ + public static String valueToString(Object value) throws dev.brighten.ac.utils.json.JSONException { + if (value == null || value.equals(null)) { + return "null"; + } + if (value instanceof JSONString) { + Object object; + try { + object = ((JSONString) value).toJSONString(); + } catch (Exception e) { + throw new dev.brighten.ac.utils.json.JSONException(e); + } + if (object instanceof String) { + return (String) object; + } + throw new dev.brighten.ac.utils.json.JSONException("Bad value from toJSONString: " + object); + } + if (value instanceof Number) { + return numberToString((Number) value); + } + if (value instanceof Boolean || value instanceof dev.brighten.ac.utils.json.JSONObject || + value instanceof dev.brighten.ac.utils.json.JSONArray) { + return value.toString(); + } + if (value instanceof Map) { + return new dev.brighten.ac.utils.json.JSONObject((Map) value).toString(); + } + if (value instanceof Collection) { + return new dev.brighten.ac.utils.json.JSONArray((Collection) value).toString(); + } + if (value.getClass().isArray()) { + return new dev.brighten.ac.utils.json.JSONArray(value).toString(); + } + return quote(value.toString()); + } + + /** + * Make a prettyprinted JSON text of an object value. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @param value The value to be serialized. + * @param indentFactor The number of spaces to add to each level of + * indentation. + * @param indent The indentation of the top level. + * @return a printable, displayable, transmittable + * representation of the object, beginning + * with { (left brace) and ending + * with } (right brace). + * @throws dev.brighten.ac.utils.json.JSONException If the object contains an invalid number. + */ + static String valueToString( + Object value, + int indentFactor, + int indent + ) throws dev.brighten.ac.utils.json.JSONException { + if (value == null || value.equals(null)) { + return "null"; + } + try { + if (value instanceof JSONString) { + Object o = ((JSONString) value).toJSONString(); + if (o instanceof String) { + return (String) o; + } + } + } catch (Exception ignore) { + } + if (value instanceof Number) { + return numberToString((Number) value); + } + if (value instanceof Boolean) { + return value.toString(); + } + if (value instanceof dev.brighten.ac.utils.json.JSONObject) { + return ((dev.brighten.ac.utils.json.JSONObject) value).toString(indentFactor, indent); + } + if (value instanceof dev.brighten.ac.utils.json.JSONArray) { + return ((dev.brighten.ac.utils.json.JSONArray) value).toString(indentFactor, indent); + } + if (value instanceof Map) { + return new dev.brighten.ac.utils.json.JSONObject((Map) value).toString(indentFactor, indent); + } + if (value instanceof Collection) { + return new dev.brighten.ac.utils.json.JSONArray((Collection) value).toString(indentFactor, indent); + } + if (value.getClass().isArray()) { + return new dev.brighten.ac.utils.json.JSONArray(value).toString(indentFactor, indent); + } + return quote(value.toString()); + } + + /** + * Wrap an object, if necessary. If the object is null, return the NULL + * object. If it is an array or collection, wrap it in a JSONArray. If + * it is a map, wrap it in a JSONObject. If it is a standard property + * (Double, String, et al) then it is already wrapped. Otherwise, if it + * comes from 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 + * @return The wrapped value + */ + public static Object wrap(Object object) { + try { + if (object == null) { + return NULL; + } + if (object instanceof dev.brighten.ac.utils.json.JSONObject || object instanceof dev.brighten.ac.utils.json.JSONArray || + NULL.equals(object) || object instanceof JSONString || + object instanceof Byte || object instanceof Character || + object instanceof Short || object instanceof Integer || + object instanceof Long || object instanceof Boolean || + object instanceof Float || object instanceof Double || + object instanceof String) { + return object; + } + + if (object instanceof Collection) { + return new dev.brighten.ac.utils.json.JSONArray((Collection) object); + } + if (object.getClass().isArray()) { + return new dev.brighten.ac.utils.json.JSONArray(object); + } + if (object instanceof Map) { + return new dev.brighten.ac.utils.json.JSONObject((Map) object); + } + Package objectPackage = object.getClass().getPackage(); + String objectPackageName = objectPackage != null ? + objectPackage.getName() : ""; + if ( + objectPackageName.startsWith("java.") || + objectPackageName.startsWith("javax.") || + object.getClass().getClassLoader() == null + ) { + return object.toString(); + } + return new dev.brighten.ac.utils.json.JSONObject(object); + } catch (Exception exception) { + return null; + } + } + + /** + * 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 dev.brighten.ac.utils.json.JSONException If the value is an invalid number + * or if the key is null. + */ + public dev.brighten.ac.utils.json.JSONObject accumulate( + String key, + Object value + ) throws dev.brighten.ac.utils.json.JSONException { + testValidity(value); + Object object = opt(key); + if (object == null) { + put(key, value instanceof dev.brighten.ac.utils.json.JSONArray ? + new dev.brighten.ac.utils.json.JSONArray().put(value) : value); + } else if (object instanceof dev.brighten.ac.utils.json.JSONArray) { + ((dev.brighten.ac.utils.json.JSONArray) object).put(value); + } else { + put(key, new dev.brighten.ac.utils.json.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 dev.brighten.ac.utils.json.JSONException If the key is null or if the current value + * associated with the key is not a JSONArray. + */ + public dev.brighten.ac.utils.json.JSONObject append(String key, Object value) throws dev.brighten.ac.utils.json.JSONException { + testValidity(value); + Object object = opt(key); + if (object == null) { + put(key, new dev.brighten.ac.utils.json.JSONArray().put(value)); + } else if (object instanceof dev.brighten.ac.utils.json.JSONArray) { + put(key, ((dev.brighten.ac.utils.json.JSONArray) object).put(value)); + } else { + throw new dev.brighten.ac.utils.json.JSONException("JSONObject[" + key + + "] is not a JSONArray."); + } + return this; + } + + /** + * Get the value object associated with a key. + * + * @param key A key string. + * @return The object associated with the key. + * @throws dev.brighten.ac.utils.json.JSONException if the key is not found. + */ + public Object get(String key) throws dev.brighten.ac.utils.json.JSONException { + if (key == null) { + throw new dev.brighten.ac.utils.json.JSONException("Null key."); + } + Object object = opt(key); + if (object == null) { + throw new dev.brighten.ac.utils.json.JSONException("JSONObject[" + quote(key) + + "] not found."); + } + return object; + } + + /** + * Get the boolean value associated with a key. + * + * @param key A key string. + * @return The truth. + * @throws dev.brighten.ac.utils.json.JSONException if the value is not a Boolean or the String "true" or "false". + */ + public boolean getBoolean(String key) throws dev.brighten.ac.utils.json.JSONException { + Object object = get(key); + if (object.equals(Boolean.FALSE) || + (object instanceof String && + ((String) object).equalsIgnoreCase("false"))) { + return false; + } else if (object.equals(Boolean.TRUE) || + (object instanceof String && + ((String) object).equalsIgnoreCase("true"))) { + return true; + } + throw new dev.brighten.ac.utils.json.JSONException("JSONObject[" + quote(key) + + "] is not a Boolean."); + } + + /** + * Get the double value associated with a key. + * + * @param key A key string. + * @return The numeric value. + * @throws dev.brighten.ac.utils.json.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 dev.brighten.ac.utils.json.JSONException { + Object object = get(key); + try { + return object instanceof Number ? + ((Number) object).doubleValue() : + Double.parseDouble((String) object); + } catch (Exception e) { + throw new dev.brighten.ac.utils.json.JSONException("JSONObject[" + quote(key) + + "] is not a number."); + } + } + + /** + * Get the int value associated with a key. + * + * @param key A key string. + * @return The integer value. + * @throws dev.brighten.ac.utils.json.JSONException if the key is not found or if the value cannot + * be converted to an integer. + */ + public int getInt(String key) throws dev.brighten.ac.utils.json.JSONException { + Object object = get(key); + try { + return object instanceof Number ? + ((Number) object).intValue() : + Integer.parseInt((String) object); + } catch (Exception e) { + throw new dev.brighten.ac.utils.json.JSONException("JSONObject[" + quote(key) + + "] is not an int."); + } + } + + /** + * Get the JSONArray value associated with a key. + * + * @param key A key string. + * @return A JSONArray which is the value. + * @throws dev.brighten.ac.utils.json.JSONException if the key is not found or + * if the value is not a JSONArray. + */ + public dev.brighten.ac.utils.json.JSONArray getJSONArray(String key) throws dev.brighten.ac.utils.json.JSONException { + Object object = get(key); + if (object instanceof dev.brighten.ac.utils.json.JSONArray) { + return (dev.brighten.ac.utils.json.JSONArray) object; + } + throw new dev.brighten.ac.utils.json.JSONException("JSONObject[" + quote(key) + + "] is not a JSONArray."); + } + + /** + * Get the JSONObject value associated with a key. + * + * @param key A key string. + * @return A JSONObject which is the value. + * @throws dev.brighten.ac.utils.json.JSONException if the key is not found or + * if the value is not a JSONObject. + */ + public dev.brighten.ac.utils.json.JSONObject getJSONObject(String key) throws dev.brighten.ac.utils.json.JSONException { + Object object = get(key); + if (object instanceof dev.brighten.ac.utils.json.JSONObject) { + return (dev.brighten.ac.utils.json.JSONObject) object; + } + throw new dev.brighten.ac.utils.json.JSONException("JSONObject[" + quote(key) + + "] is not a JSONObject."); + } + + /** + * Get the long value associated with a key. + * + * @param key A key string. + * @return The long value. + * @throws dev.brighten.ac.utils.json.JSONException if the key is not found or if the value cannot + * be converted to a long. + */ + public long getLong(String key) throws dev.brighten.ac.utils.json.JSONException { + Object object = get(key); + try { + return object instanceof Number ? + ((Number) object).longValue() : + Long.parseLong((String) object); + } catch (Exception e) { + throw new dev.brighten.ac.utils.json.JSONException("JSONObject[" + quote(key) + + "] is not a long."); + } + } + + /** + * Get the string associated with a key. + * + * @param key A key string. + * @return A string which is the value. + * @throws dev.brighten.ac.utils.json.JSONException if there is no string value for the key. + */ + public String getString(String key) throws dev.brighten.ac.utils.json.JSONException { + Object object = get(key); + if (object instanceof String) { + return (String) object; + } + throw new dev.brighten.ac.utils.json.JSONException("JSONObject[" + quote(key) + + "] not a string."); + } + + /** + * 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. If there is such a property, and if + * it is an Integer, Long, Double, or Float, then add one to it. + * + * @param key A key string. + * @return this. + * @throws dev.brighten.ac.utils.json.JSONException If there is already a property with this name + * that is not an Integer, Long, Double, or Float. + */ + public dev.brighten.ac.utils.json.JSONObject increment(String key) throws dev.brighten.ac.utils.json.JSONException { + Object value = opt(key); + if (value == null) { + put(key, 1); + } else if (value instanceof Integer) { + put(key, ((Integer) value).intValue() + 1); + } else if (value instanceof Long) { + put(key, ((Long) value).longValue() + 1); + } else if (value instanceof Double) { + put(key, ((Double) value).doubleValue() + 1); + } else if (value instanceof Float) { + put(key, ((Float) value).floatValue() + 1); + } else { + throw new dev.brighten.ac.utils.json.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 dev.brighten.ac.utils.json.JSONObject.NULL.equals(opt(key)); + } + + /** + * Get an enumeration of the keys of the JSONObject. + * + * @return An iterator of the keys. + */ + public Iterator keys() { + return this.map.keySet().iterator(); + } + + /** + * Get the number of keys stored in the JSONObject. + * + * @return The number of keys in the JSONObject. + */ + public int length() { + return this.map.size(); + } + + /** + * 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 dev.brighten.ac.utils.json.JSONArray names() { + dev.brighten.ac.utils.json.JSONArray ja = new dev.brighten.ac.utils.json.JSONArray(); + Iterator keys = this.keys(); + while (keys.hasNext()) { + ja.put(keys.next()); + } + return ja.length() == 0 ? null : ja; + } + + /** + * 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 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 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) { + try { + return getBoolean(key); + } catch (Exception e) { + return 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 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) { + try { + return getDouble(key); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 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 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) { + try { + return getInt(key); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 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 dev.brighten.ac.utils.json.JSONArray optJSONArray(String key) { + Object o = opt(key); + return o instanceof dev.brighten.ac.utils.json.JSONArray ? (dev.brighten.ac.utils.json.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 dev.brighten.ac.utils.json.JSONObject optJSONObject(String key) { + Object object = opt(key); + return object instanceof dev.brighten.ac.utils.json.JSONObject ? (dev.brighten.ac.utils.json.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 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) { + try { + return getLong(key); + } 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 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 = opt(key); + return NULL.equals(object) ? defaultValue : object.toString(); + } + + 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 (int i = 0; i < methods.length; i += 1) { + try { + Method method = methods[i]; + if (Modifier.isPublic(method.getModifiers())) { + String name = method.getName(); + String key = ""; + if (name.startsWith("get")) { + if (name.equals("getClass") || + name.equals("getDeclaringClass")) { + key = ""; + } else { + key = name.substring(3); + } + } else if (name.startsWith("is")) { + key = name.substring(2); + } + if (key.length() > 0 && + Character.isUpperCase(key.charAt(0)) && + method.getParameterTypes().length == 0) { + if (key.length() == 1) { + key = key.toLowerCase(); + } else if (!Character.isUpperCase(key.charAt(1))) { + key = key.substring(0, 1).toLowerCase() + + key.substring(1); + } + + Object result = method.invoke(bean, (Object[]) null); + if (result != null) { + map.put(key, wrap(result)); + } + } + } + } catch (Exception 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 dev.brighten.ac.utils.json.JSONException If the key is null. + */ + public dev.brighten.ac.utils.json.JSONObject put(String key, boolean value) throws dev.brighten.ac.utils.json.JSONException { + put(key, value ? Boolean.TRUE : Boolean.FALSE); + return this; + } + + /** + * 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 dev.brighten.ac.utils.json.JSONException + */ + public dev.brighten.ac.utils.json.JSONObject put(String key, Collection value) throws dev.brighten.ac.utils.json.JSONException { + put(key, new dev.brighten.ac.utils.json.JSONArray(value)); + return this; + } + + /** + * Put a key/double pair in the JSONObject. + * + * @param key A key string. + * @param value A double which is the value. + * @return this. + * @throws dev.brighten.ac.utils.json.JSONException If the key is null or if the number is invalid. + */ + public dev.brighten.ac.utils.json.JSONObject put(String key, double value) throws dev.brighten.ac.utils.json.JSONException { + put(key, new Double(value)); + return this; + } + + /** + * Put a key/int pair in the JSONObject. + * + * @param key A key string. + * @param value An int which is the value. + * @return this. + * @throws dev.brighten.ac.utils.json.JSONException If the key is null. + */ + public dev.brighten.ac.utils.json.JSONObject put(String key, int value) throws dev.brighten.ac.utils.json.JSONException { + put(key, new Integer(value)); + return this; + } + + /** + * Put a key/long pair in the JSONObject. + * + * @param key A key string. + * @param value A long which is the value. + * @return this. + * @throws dev.brighten.ac.utils.json.JSONException If the key is null. + */ + public dev.brighten.ac.utils.json.JSONObject put(String key, long value) throws dev.brighten.ac.utils.json.JSONException { + put(key, new Long(value)); + return this; + } + + /** + * 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 dev.brighten.ac.utils.json.JSONException + */ + public dev.brighten.ac.utils.json.JSONObject put(String key, Map value) throws dev.brighten.ac.utils.json.JSONException { + put(key, new dev.brighten.ac.utils.json.JSONObject(value)); + return this; + } + + /** + * 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 dev.brighten.ac.utils.json.JSONException If the value is non-finite number + * or if the key is null. + */ + public dev.brighten.ac.utils.json.JSONObject put(String key, Object value) throws dev.brighten.ac.utils.json.JSONException { + if (key == null) { + throw new dev.brighten.ac.utils.json.JSONException("Null key."); + } + if (value != null) { + testValidity(value); + this.map.put(key, value); + } else { + remove(key); + } + return this; + } + + /** + * 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 + * @param value + * @return his. + * @throws dev.brighten.ac.utils.json.JSONException if the key is a duplicate + */ + public dev.brighten.ac.utils.json.JSONObject putOnce(String key, Object value) throws dev.brighten.ac.utils.json.JSONException { + if (key != null && value != null) { + if (opt(key) != null) { + throw new dev.brighten.ac.utils.json.JSONException("Duplicate key \"" + key + "\""); + } + 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 dev.brighten.ac.utils.json.JSONException If the value is a non-finite number. + */ + public dev.brighten.ac.utils.json.JSONObject putOpt(String key, Object value) throws dev.brighten.ac.utils.json.JSONException { + if (key != null && value != null) { + put(key, value); + } + return this; + } + + /** + * 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); + } + + /** + * 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 dev.brighten.ac.utils.json.JSONException If any of the values are non-finite numbers. + */ + public dev.brighten.ac.utils.json.JSONArray toJSONArray(dev.brighten.ac.utils.json.JSONArray names) throws dev.brighten.ac.utils.json.JSONException { + if (names == null || names.length() == 0) { + return null; + } + dev.brighten.ac.utils.json.JSONArray ja = new dev.brighten.ac.utils.json.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). + */ + public String toString() { + try { + Iterator keys = this.keys(); + StringBuffer sb = new StringBuffer("{"); + + while (keys.hasNext()) { + if (sb.length() > 1) { + sb.append(','); + } + Object o = keys.next(); + sb.append(quote(o.toString())); + sb.append(':'); + sb.append(valueToString(this.map.get(o))); + } + sb.append('}'); + return sb.toString(); + } catch (Exception e) { + return null; + } + } + + /** + * Make a prettyprinted JSON text of this JSONObject. + *

+ * 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 dev.brighten.ac.utils.json.JSONException If the object contains an invalid number. + */ + public String toString(int indentFactor) throws dev.brighten.ac.utils.json.JSONException { + return toString(indentFactor, 0); + } + + /** + * Make a prettyprinted JSON text of this JSONObject. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @param indentFactor The number of spaces to add to each level of + * indentation. + * @param indent The indentation of the top level. + * @return a printable, displayable, transmittable + * representation of the object, beginning + * with { (left brace) and ending + * with } (right brace). + * @throws dev.brighten.ac.utils.json.JSONException If the object contains an invalid number. + */ + String toString(int indentFactor, int indent) throws dev.brighten.ac.utils.json.JSONException { + int i; + int length = this.length(); + if (length == 0) { + return "{}"; + } + Iterator keys = this.keys(); + int newindent = indent + indentFactor; + Object object; + StringBuffer sb = new StringBuffer("{"); + if (length == 1) { + object = keys.next(); + sb.append(quote(object.toString())); + sb.append(": "); + sb.append(valueToString(this.map.get(object), indentFactor, + indent)); + } else { + while (keys.hasNext()) { + object = keys.next(); + if (sb.length() > 1) { + sb.append(",\n"); + } else { + sb.append('\n'); + } + for (i = 0; i < newindent; i += 1) { + sb.append(' '); + } + sb.append(quote(object.toString())); + sb.append(": "); + sb.append(valueToString(this.map.get(object), indentFactor, + newindent)); + } + if (sb.length() > 1) { + sb.append('\n'); + for (i = 0; i < indent; i += 1) { + sb.append(' '); + } + } + } + sb.append('}'); + return sb.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 dev.brighten.ac.utils.json.JSONException + */ + public Writer write(Writer writer) throws dev.brighten.ac.utils.json.JSONException { + try { + boolean commanate = false; + Iterator keys = this.keys(); + writer.write('{'); + + while (keys.hasNext()) { + if (commanate) { + writer.write(','); + } + Object key = keys.next(); + writer.write(quote(key.toString())); + writer.write(':'); + Object value = this.map.get(key); + if (value instanceof dev.brighten.ac.utils.json.JSONObject) { + ((dev.brighten.ac.utils.json.JSONObject) value).write(writer); + } else if (value instanceof dev.brighten.ac.utils.json.JSONArray) { + ((JSONArray) value).write(writer); + } else { + writer.write(valueToString(value)); + } + commanate = true; + } + writer.write('}'); + return writer; + } catch (IOException exception) { + throw new JSONException(exception); + } + } + + /** + * 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 final class Null { + + /** + * There is only intended to be a single instance of the NULL object, + * so the clone method returns itself. + * + * @return NULL. + */ + 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. + */ + public boolean equals(Object object) { + return object == null || object == this; + } + + /** + * Get the "null" string value. + * + * @return The string "null". + */ + public String toString() { + return "null"; + } + } +} \ No newline at end of file diff --git a/src/main/java/dev/brighten/ac/utils/json/JSONString.java b/src/main/java/dev/brighten/ac/utils/json/JSONString.java new file mode 100644 index 0000000..bc977ba --- /dev/null +++ b/src/main/java/dev/brighten/ac/utils/json/JSONString.java @@ -0,0 +1,19 @@ +package dev.brighten.ac.utils.json; + +/** + * The JSONString interface allows a toJSONString() + * method so that a class can change the behavior of + * JSONObject.toString(), JSONArray.toString(), + * and JSONWriter.value(Object). The + * toJSONString method will be used instead of the default behavior + * of using the Object's toString() method and quoting the result. + */ +public interface JSONString { + /** + * The toJSONString method allows a class to produce its own JSON + * serialization. + * + * @return A strictly syntactically correct JSON text. + */ + public String toJSONString(); +} diff --git a/src/main/java/dev/brighten/ac/utils/json/JSONStringer.java b/src/main/java/dev/brighten/ac/utils/json/JSONStringer.java new file mode 100644 index 0000000..17200bf --- /dev/null +++ b/src/main/java/dev/brighten/ac/utils/json/JSONStringer.java @@ -0,0 +1,82 @@ +package dev.brighten.ac.utils.json; + +/* +Copyright (c) 2006 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import dev.brighten.ac.utils.json.JSONWriter; + +import java.io.StringWriter; + +/** + * JSONStringer provides a quick and convenient way of producing JSON text. + * The texts produced strictly conform to JSON syntax rules. No whitespace is + * added, so the results are ready for transmission or storage. Each instance of + * JSONStringer can produce one JSON text. + *

+ * A JSONStringer instance provides a value method for appending + * values to the + * text, and a key + * method for adding keys before values in objects. There are array + * and endArray methods that make and bound array values, and + * object and endObject methods which make and bound + * object values. All of these methods return the JSONWriter instance, + * permitting cascade style. For example,

+ * myString = new JSONStringer()
+ *     .object()
+ *         .key("JSON")
+ *         .value("Hello, World!")
+ *     .endObject()
+ *     .toString();
which produces the string
+ * {"JSON":"Hello, World!"}
+ *

+ * The first method called must be array or object. + * There are no methods for adding commas or colons. JSONStringer adds them for + * 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 2008-09-18 + */ +public class JSONStringer extends JSONWriter { + /** + * Make a fresh JSONStringer. It can be used to build one JSON text. + */ + public JSONStringer() { + super(new StringWriter()); + } + + /** + * Return the JSON text. This method is used to obtain the product of the + * JSONStringer instance. It will return null if there was a + * 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. + */ + public String toString() { + return this.mode == 'd' ? this.writer.toString() : null; + } +} diff --git a/src/main/java/dev/brighten/ac/utils/json/JSONTokener.java b/src/main/java/dev/brighten/ac/utils/json/JSONTokener.java new file mode 100644 index 0000000..c775c78 --- /dev/null +++ b/src/main/java/dev/brighten/ac/utils/json/JSONTokener.java @@ -0,0 +1,450 @@ +package dev.brighten.ac.utils.json; + +import dev.brighten.ac.utils.json.JSONArray; +import dev.brighten.ac.utils.json.JSONException; +import dev.brighten.ac.utils.json.JSONObject; + +import java.io.*; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +/** + * 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 2010-12-24 + */ +public class JSONTokener { + + private int character; + private boolean eof; + private int index; + private int line; + private char previous; + private Reader reader; + private boolean usePrevious; + + + /** + * Construct a JSONTokener from a Reader. + * + * @param reader A reader. + */ + public JSONTokener(Reader reader) { + this.reader = reader.markSupported() ? + reader : new BufferedReader(reader); + this.eof = false; + this.usePrevious = false; + this.previous = 0; + this.index = 0; + this.character = 1; + this.line = 1; + } + + + /** + * Construct a JSONTokener from an InputStream. + */ + public JSONTokener(InputStream inputStream) throws JSONException { + this(new InputStreamReader(inputStream)); + } + + + /** + * Construct a JSONTokener from a string. + * + * @param s A source string. + */ + public JSONTokener(String s) { + this(new StringReader(s)); + } + + /** + * 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. + */ + public static int dehexchar(char c) { + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'A' && c <= 'F') { + return c - ('A' - 10); + } + if (c >= 'a' && c <= 'f') { + return c - ('a' - 10); + } + return -1; + } + + /** + * 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. + */ + public void back() throws JSONException { + if (usePrevious || index <= 0) { + throw new JSONException("Stepping back two steps is not supported"); + } + this.index -= 1; + this.character -= 1; + this.usePrevious = true; + this.eof = false; + } + + public boolean end() { + return eof && !usePrevious; + } + + + /** + * Determine if the source string still contains characters that next() + * can consume. + * + * @return true if not yet at the end of the source. + */ + public boolean more() throws JSONException { + next(); + if (end()) { + return false; + } + back(); + return true; + } + + + /** + * Get the next character in the source string. + * + * @return The next character, or 0 if past the end of the source string. + */ + public char next() throws JSONException { + int c; + if (this.usePrevious) { + this.usePrevious = false; + c = this.previous; + } else { + try { + c = this.reader.read(); + } catch (IOException exception) { + throw new JSONException(exception); + } + + if (c <= 0) { // End of stream + this.eof = true; + c = 0; + } + } + this.index += 1; + if (this.previous == '\r') { + this.line += 1; + this.character = c == '\n' ? 0 : 1; + } else if (c == '\n') { + this.line += 1; + this.character = 0; + } else { + this.character += 1; + } + this.previous = (char) c; + return this.previous; + } + + + /** + * 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. + */ + public char next(char c) throws JSONException { + char n = next(); + if (n != c) { + throw syntaxError("Expected '" + c + "' and instead saw '" + + n + "'"); + } + return n; + } + + + /** + * 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. + */ + public String next(int n) throws JSONException { + if (n == 0) { + return ""; + } + + char[] chars = new char[n]; + int pos = 0; + + while (pos < n) { + chars[pos] = next(); + if (end()) { + throw syntaxError("Substring bounds error"); + } + pos += 1; + } + return new String(chars); + } + + + /** + * Get the next char in the string, skipping whitespace. + * + * @return A character, or 0 if there are no more characters. + * @throws JSONException + */ + public char nextClean() throws JSONException { + for (; ; ) { + char c = next(); + if (c == 0 || c > ' ') { + return c; + } + } + } + + + /** + * Return the characters up to the next close quote character. + * 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. + * @throws JSONException Unterminated string. + */ + public String nextString(char quote) throws JSONException { + char c; + StringBuffer sb = new StringBuffer(); + for (; ; ) { + c = next(); + switch (c) { + case 0: + case '\n': + case '\r': + throw syntaxError("Unterminated string"); + case '\\': + c = next(); + switch (c) { + case 'b': + sb.append('\b'); + break; + case 't': + sb.append('\t'); + break; + case 'n': + sb.append('\n'); + break; + case 'f': + sb.append('\f'); + break; + case 'r': + sb.append('\r'); + break; + case 'u': + sb.append((char) Integer.parseInt(next(4), 16)); + break; + case '"': + case '\'': + case '\\': + case '/': + sb.append(c); + break; + default: + throw syntaxError("Illegal escape."); + } + break; + default: + if (c == quote) { + return sb.toString(); + } + sb.append(c); + } + } + } + + + /** + * 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. + */ + public String nextTo(char delimiter) throws JSONException { + StringBuffer sb = new StringBuffer(); + for (; ; ) { + char c = next(); + if (c == delimiter || c == 0 || c == '\n' || c == '\r') { + if (c != 0) { + back(); + } + return sb.toString().trim(); + } + sb.append(c); + } + } + + + /** + * 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. + */ + public String nextTo(String delimiters) throws JSONException { + char c; + StringBuffer sb = new StringBuffer(); + for (; ; ) { + c = next(); + if (delimiters.indexOf(c) >= 0 || c == 0 || + c == '\n' || c == '\r') { + if (c != 0) { + back(); + } + return sb.toString().trim(); + } + sb.append(c); + } + } + + + /** + * Get the next value. The value can be a Boolean, Double, Integer, + * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. + * + * @return An object. + * @throws JSONException If syntax error. + */ + public Object nextValue() throws JSONException { + char c = nextClean(); + String string; + + switch (c) { + case '"': + case '\'': + return nextString(c); + case '{': + back(); + return new JSONObject(this); + case '[': + back(); + return new JSONArray(this); + } + + /* + * Handle unquoted text. This could be the values true, false, or + * null, or it can be a number. An implementation (such as this one) + * is allowed to also accept non-standard forms. + * + * Accumulate characters until we reach the end of the text or a + * formatting character. + */ + + StringBuffer sb = new StringBuffer(); + while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { + sb.append(c); + c = next(); + } + back(); + + string = sb.toString().trim(); + if (string.equals("")) { + throw syntaxError("Missing value"); + } + return JSONObject.stringToValue(string); + } + + + /** + * 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. + */ + public char skipTo(char to) throws JSONException { + char c; + try { + int startIndex = this.index; + int startCharacter = this.character; + int startLine = this.line; + reader.mark(Integer.MAX_VALUE); + do { + c = next(); + if (c == 0) { + reader.reset(); + this.index = startIndex; + this.character = startCharacter; + this.line = startLine; + return c; + } + } while (c != to); + } catch (IOException exc) { + throw new JSONException(exc); + } + + back(); + return c; + } + + + /** + * Make a JSONException to signal a syntax error. + * + * @param message The error message. + * @return A JSONException object, suitable for throwing + */ + public JSONException syntaxError(String message) { + return new JSONException(message + toString()); + } + + + /** + * Make a printable string of this JSONTokener. + * + * @return " at {index} [character {character} line {line}]" + */ + public String toString() { + return " at " + index + " [character " + this.character + " line " + + this.line + "]"; + } +} \ No newline at end of file diff --git a/src/main/java/dev/brighten/ac/utils/json/JSONWriter.java b/src/main/java/dev/brighten/ac/utils/json/JSONWriter.java new file mode 100644 index 0000000..5247718 --- /dev/null +++ b/src/main/java/dev/brighten/ac/utils/json/JSONWriter.java @@ -0,0 +1,335 @@ +package dev.brighten.ac.utils.json; + +import dev.brighten.ac.utils.json.JSONException; +import dev.brighten.ac.utils.json.JSONObject; + +import java.io.IOException; +import java.io.Writer; + +/* +Copyright (c) 2006 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +/** + * JSONWriter provides a quick and convenient way of producing JSON text. + * The texts produced strictly conform to JSON syntax rules. No whitespace is + * added, so the results are ready for transmission or storage. Each instance of + * JSONWriter can produce one JSON text. + *

+ * A JSONWriter instance provides a value method for appending + * values to the + * text, and a key + * method for adding keys before values in objects. There are array + * and endArray methods that make and bound array values, and + * object and endObject methods which make and bound + * object values. All of these methods return the JSONWriter instance, + * permitting a cascade style. For example,

+ * new JSONWriter(myWriter)
+ *     .object()
+ *         .key("JSON")
+ *         .value("Hello, World!")
+ *     .endObject();
which writes
+ * {"JSON":"Hello, World!"}
+ *

+ * The first method called must be array or object. + * There are no methods for adding commas or colons. JSONWriter adds them for + * 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 2010-12-24 + */ +public class JSONWriter { + private static final int maxdepth = 20; + /** + * The current mode. Values: + * 'a' (array), + * 'd' (done), + * 'i' (initial), + * 'k' (key), + * 'o' (object). + */ + protected char mode; + /** + * The writer that will receive the output. + */ + protected Writer writer; + /** + * The comma flag determines if a comma should be output before the next + * value. + */ + private boolean comma; + /** + * The object/array stack. + */ + private JSONObject stack[]; + /** + * 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. + */ + public JSONWriter(Writer w) { + this.comma = false; + this.mode = 'i'; + this.stack = new JSONObject[maxdepth]; + this.top = 0; + this.writer = w; + } + + /** + * Append a value. + * + * @param string A string value. + * @return this + * @throws dev.brighten.ac.utils.json.JSONException If the value is out of sequence. + */ + private dev.brighten.ac.utils.json.JSONWriter append(String string) throws dev.brighten.ac.utils.json.JSONException { + if (string == null) { + throw new dev.brighten.ac.utils.json.JSONException("Null pointer"); + } + if (this.mode == 'o' || this.mode == 'a') { + try { + if (this.comma && this.mode == 'a') { + this.writer.write(','); + } + this.writer.write(string); + } catch (IOException e) { + throw new dev.brighten.ac.utils.json.JSONException(e); + } + if (this.mode == 'o') { + this.mode = 'k'; + } + this.comma = true; + return this; + } + throw new dev.brighten.ac.utils.json.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 dev.brighten.ac.utils.json.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 dev.brighten.ac.utils.json.JSONWriter array() throws dev.brighten.ac.utils.json.JSONException { + if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { + this.push(null); + this.append("["); + this.comma = false; + return this; + } + throw new dev.brighten.ac.utils.json.JSONException("Misplaced array."); + } + + /** + * End something. + * + * @param mode Mode + * @param c Closing character + * @return this + * @throws dev.brighten.ac.utils.json.JSONException If unbalanced. + */ + private dev.brighten.ac.utils.json.JSONWriter end(char mode, char c) throws dev.brighten.ac.utils.json.JSONException { + if (this.mode != mode) { + throw new dev.brighten.ac.utils.json.JSONException(mode == 'a' ? "Misplaced endArray." : + "Misplaced endObject."); + } + this.pop(mode); + try { + this.writer.write(c); + } catch (IOException e) { + throw new dev.brighten.ac.utils.json.JSONException(e); + } + this.comma = true; + return this; + } + + /** + * End an array. This method most be called to balance calls to + * array. + * + * @return this + * @throws dev.brighten.ac.utils.json.JSONException If incorrectly nested. + */ + public dev.brighten.ac.utils.json.JSONWriter endArray() throws dev.brighten.ac.utils.json.JSONException { + return this.end('a', ']'); + } + + /** + * End an object. This method most be called to balance calls to + * object. + * + * @return this + * @throws dev.brighten.ac.utils.json.JSONException If incorrectly nested. + */ + public dev.brighten.ac.utils.json.JSONWriter endObject() throws dev.brighten.ac.utils.json.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 dev.brighten.ac.utils.json.JSONException If the key is out of place. For example, keys + * do not belong in arrays or if the key is null. + */ + public dev.brighten.ac.utils.json.JSONWriter key(String string) throws dev.brighten.ac.utils.json.JSONException { + if (string == null) { + throw new dev.brighten.ac.utils.json.JSONException("Null key."); + } + if (this.mode == 'k') { + try { + stack[top - 1].putOnce(string, Boolean.TRUE); + if (this.comma) { + this.writer.write(','); + } + this.writer.write(JSONObject.quote(string)); + this.writer.write(':'); + this.comma = false; + this.mode = 'o'; + return this; + } catch (IOException e) { + throw new dev.brighten.ac.utils.json.JSONException(e); + } + } + throw new dev.brighten.ac.utils.json.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 dev.brighten.ac.utils.json.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 dev.brighten.ac.utils.json.JSONWriter object() throws dev.brighten.ac.utils.json.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 dev.brighten.ac.utils.json.JSONException("Misplaced object."); + + } + + + /** + * Pop an array or object scope. + * + * @param c The scope to close. + * @throws dev.brighten.ac.utils.json.JSONException If nesting is wrong. + */ + private void pop(char c) throws dev.brighten.ac.utils.json.JSONException { + if (this.top <= 0) { + throw new dev.brighten.ac.utils.json.JSONException("Nesting error."); + } + char m = this.stack[this.top - 1] == null ? 'a' : 'k'; + if (m != c) { + throw new dev.brighten.ac.utils.json.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 c The scope to open. + * @throws dev.brighten.ac.utils.json.JSONException If nesting is too deep. + */ + private void push(JSONObject jo) throws dev.brighten.ac.utils.json.JSONException { + if (this.top >= maxdepth) { + throw new dev.brighten.ac.utils.json.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 dev.brighten.ac.utils.json.JSONException + */ + public dev.brighten.ac.utils.json.JSONWriter value(boolean b) throws dev.brighten.ac.utils.json.JSONException { + return this.append(b ? "true" : "false"); + } + + /** + * Append a double value. + * + * @param d A double. + * @return this + * @throws dev.brighten.ac.utils.json.JSONException If the number is not finite. + */ + public dev.brighten.ac.utils.json.JSONWriter value(double d) throws dev.brighten.ac.utils.json.JSONException { + return this.value(new Double(d)); + } + + /** + * Append a long value. + * + * @param l A long. + * @return this + * @throws dev.brighten.ac.utils.json.JSONException + */ + public dev.brighten.ac.utils.json.JSONWriter value(long l) throws dev.brighten.ac.utils.json.JSONException { + return this.append(Long.toString(l)); + } + + + /** + * 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. + * @return this + * @throws dev.brighten.ac.utils.json.JSONException If the value is out of sequence. + */ + public dev.brighten.ac.utils.json.JSONWriter value(Object object) throws JSONException { + return this.append(JSONObject.valueToString(object)); + } +} diff --git a/src/main/java/dev/brighten/ac/utils/json/XML.java b/src/main/java/dev/brighten/ac/utils/json/XML.java new file mode 100644 index 0000000..b63f3a1 --- /dev/null +++ b/src/main/java/dev/brighten/ac/utils/json/XML.java @@ -0,0 +1,539 @@ +package dev.brighten.ac.utils.json; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import dev.brighten.ac.utils.json.JSONArray; +import dev.brighten.ac.utils.json.JSONException; +import dev.brighten.ac.utils.json.JSONObject; +import dev.brighten.ac.utils.json.XMLTokener; + +import java.util.Iterator; + + +/** + * This provides static methods to convert an XML text into a JSONObject, + * and to covert a JSONObject into an XML text. + * + * @author JSON.org + * @version 2011-02-11 + */ +public class XML { + + /** + * The Character '&'. + */ + public static final Character AMP = new Character('&'); + + /** + * The Character '''. + */ + public static final Character APOS = new Character('\''); + + /** + * The Character '!'. + */ + public static final Character BANG = new Character('!'); + + /** + * The Character '='. + */ + public static final Character EQ = new Character('='); + + /** + * The Character '>'. + */ + public static final Character GT = new Character('>'); + + /** + * The Character '<'. + */ + public static final Character LT = new Character('<'); + + /** + * The Character '?'. + */ + public static final Character QUEST = new Character('?'); + + /** + * The Character '"'. + */ + public static final Character QUOT = new Character('"'); + + /** + * The Character '/'. + */ + public static final Character SLASH = new Character('/'); + + /** + * Replace special characters with XML escapes: + *

+     * & (ampersand) is replaced by &amp;
+     * < (less than) is replaced by &lt;
+     * > (greater than) is replaced by &gt;
+     * " (double quote) is replaced by &quot;
+     * 
+ * + * @param string The string to be escaped. + * @return The escaped string. + */ + public static String escape(String string) { + StringBuffer sb = new StringBuffer(); + for (int i = 0, length = string.length(); i < length; i++) { + char c = string.charAt(i); + switch (c) { + case '&': + sb.append("&"); + break; + case '<': + sb.append("<"); + break; + case '>': + sb.append(">"); + break; + case '"': + sb.append("""); + break; + case '\'': + sb.append("'"); + break; + default: + sb.append(c); + } + } + return sb.toString(); + } + + /** + * Throw an exception if the string contains whitespace. + * Whitespace is not allowed in tagNames and attributes. + * + * @param string + * @throws JSONException + */ + public static void noSpace(String string) throws JSONException { + int i, length = string.length(); + if (length == 0) { + throw new JSONException("Empty string."); + } + for (i = 0; i < length; i += 1) { + if (Character.isWhitespace(string.charAt(i))) { + throw new JSONException("'" + string + + "' contains a space character."); + } + } + } + + /** + * Scan the content following the named tag, attaching it to the context. + * + * @param x The XMLTokener containing the source string. + * @param context The JSONObject that will include the new material. + * @param name The tag name. + * @return true if the close tag is processed. + * @throws JSONException + */ + private static boolean parse(dev.brighten.ac.utils.json.XMLTokener x, JSONObject context, + String name) throws JSONException { + char c; + int i; + JSONObject jsonobject = null; + String string; + String tagName; + Object token; + +// Test for and skip past these forms: +// +// +// +// +// Report errors for these forms: +// <> +// <= +// << + + token = x.nextToken(); + +// "); + return false; + } + x.back(); + } else if (c == '[') { + token = x.nextToken(); + if (token.equals("CDATA")) { + if (x.next() == '[') { + string = x.nextCDATA(); + if (string.length() > 0) { + context.accumulate("content", string); + } + return false; + } + } + throw x.syntaxError("Expected 'CDATA['"); + } + i = 1; + do { + token = x.nextMeta(); + if (token == null) { + throw x.syntaxError("Missing '>' after ' 0); + return false; + } else if (token == QUEST) { + +// "); + return false; + } else if (token == SLASH) { + +// Close tag + + } else if (token == SLASH) { + if (x.nextToken() != GT) { + throw x.syntaxError("Misshaped tag"); + } + if (jsonobject.length() > 0) { + context.accumulate(tagName, jsonobject); + } else { + context.accumulate(tagName, ""); + } + return false; + +// Content, between <...> and + + } else if (token == GT) { + for (; ; ) { + token = x.nextContent(); + if (token == null) { + if (tagName != null) { + throw x.syntaxError("Unclosed tag " + tagName); + } + return false; + } else if (token instanceof String) { + string = (String) token; + if (string.length() > 0) { + jsonobject.accumulate("content", + dev.brighten.ac.utils.json.XML.stringToValue(string)); + } + +// Nested element + + } else if (token == LT) { + if (parse(x, jsonobject, tagName)) { + if (jsonobject.length() == 0) { + context.accumulate(tagName, ""); + } else if (jsonobject.length() == 1 && + jsonobject.opt("content") != null) { + context.accumulate(tagName, + jsonobject.opt("content")); + } else { + context.accumulate(tagName, jsonobject); + } + return false; + } + } + } + } else { + throw x.syntaxError("Misshaped tag"); + } + } + } + } + + + /** + * Try to convert a string into a number, boolean, or null. If the string + * can't be converted, return the string. This is much less ambitious than + * JSONObject.stringToValue, especially because it does not attempt to + * convert plus forms, octal forms, hex forms, or E forms lacking decimal + * points. + * + * @param string A String. + * @return A simple JSON value. + */ + public static Object stringToValue(String string) { + if (string.equals("")) { + return string; + } + if (string.equalsIgnoreCase("true")) { + return Boolean.TRUE; + } + if (string.equalsIgnoreCase("false")) { + return Boolean.FALSE; + } + if (string.equalsIgnoreCase("null")) { + return JSONObject.NULL; + } + if (string.equals("0")) { + return new Integer(0); + } + +// If it might be a number, try converting it. If that doesn't work, +// return the string. + + try { + char initial = string.charAt(0); + boolean negative = false; + if (initial == '-') { + initial = string.charAt(1); + negative = true; + } + if (initial == '0' && string.charAt(negative ? 2 : 1) == '0') { + return string; + } + if ((initial >= '0' && initial <= '9')) { + if (string.indexOf('.') >= 0) { + return Double.valueOf(string); + } else if (string.indexOf('e') < 0 && string.indexOf('E') < 0) { + Long myLong = new Long(string); + if (myLong.longValue() == myLong.intValue()) { + return new Integer(myLong.intValue()); + } else { + return myLong; + } + } + } + } catch (Exception ignore) { + } + return string; + } + + + /** + * Convert a well-formed (but not necessarily valid) XML string into a + * JSONObject. Some information may be lost in this transformation + * because JSON is a data format and XML is a document format. XML uses + * elements, attributes, and content text, while JSON uses unordered + * collections of name/value pairs and arrays of values. JSON does not + * does not like to distinguish between elements and attributes. + * Sequences of similar elements are represented as JSONArrays. Content + * text may be placed in a "content" member. Comments, prologs, DTDs, and + * <[ [ ]]> are ignored. + * + * @param string The source string. + * @return A JSONObject containing the structured data from the XML string. + * @throws JSONException + */ + public static JSONObject toJSONObject(String string) throws JSONException { + JSONObject jo = new JSONObject(); + dev.brighten.ac.utils.json.XMLTokener x = new XMLTokener(string); + while (x.more() && x.skipPast("<")) { + parse(x, jo, null); + } + return jo; + } + + + /** + * Convert a JSONObject into a well-formed, element-normal XML string. + * + * @param object A JSONObject. + * @return A string. + * @throws JSONException + */ + public static String toString(Object object) throws JSONException { + return toString(object, null); + } + + + /** + * Convert a JSONObject into a well-formed, element-normal XML string. + * + * @param object A JSONObject. + * @param tagName The optional name of the enclosing tag. + * @return A string. + * @throws JSONException + */ + public static String toString(Object object, String tagName) + throws JSONException { + StringBuffer sb = new StringBuffer(); + int i; + JSONArray ja; + JSONObject jo; + String key; + Iterator keys; + int length; + String string; + Object value; + if (object instanceof JSONObject) { + +// Emit + + if (tagName != null) { + sb.append('<'); + sb.append(tagName); + sb.append('>'); + } + +// Loop thru the keys. + + jo = (JSONObject) object; + keys = jo.keys(); + while (keys.hasNext()) { + key = keys.next().toString(); + value = jo.opt(key); + if (value == null) { + value = ""; + } + if (value instanceof String) { + string = (String) value; + } else { + string = null; + } + +// Emit content in body + + if (key.equals("content")) { + if (value instanceof JSONArray) { + ja = (JSONArray) value; + length = ja.length(); + for (i = 0; i < length; i += 1) { + if (i > 0) { + sb.append('\n'); + } + sb.append(escape(ja.get(i).toString())); + } + } else { + sb.append(escape(value.toString())); + } + +// Emit an array of similar keys + + } else if (value instanceof JSONArray) { + ja = (JSONArray) value; + length = ja.length(); + for (i = 0; i < length; i += 1) { + value = ja.get(i); + if (value instanceof JSONArray) { + sb.append('<'); + sb.append(key); + sb.append('>'); + sb.append(toString(value)); + sb.append("'); + } else { + sb.append(toString(value, key)); + } + } + } else if (value.equals("")) { + sb.append('<'); + sb.append(key); + sb.append("/>"); + +// Emit a new tag + + } else { + sb.append(toString(value, key)); + } + } + if (tagName != null) { + +// Emit the close tag + + sb.append("'); + } + return sb.toString(); + +// XML does not have good support for arrays. If an array appears in a place +// where XML is lacking, synthesize an element. + + } else { + if (object.getClass().isArray()) { + object = new JSONArray(object); + } + if (object instanceof JSONArray) { + ja = (JSONArray) object; + length = ja.length(); + for (i = 0; i < length; i += 1) { + sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName)); + } + return sb.toString(); + } else { + string = (object == null) ? "null" : escape(object.toString()); + return (tagName == null) ? "\"" + string + "\"" : + (string.length() == 0) ? "<" + tagName + "/>" : + "<" + tagName + ">" + string + ""; + } + } + } +} \ No newline at end of file diff --git a/src/main/java/dev/brighten/ac/utils/json/XMLTokener.java b/src/main/java/dev/brighten/ac/utils/json/XMLTokener.java new file mode 100644 index 0000000..2646f8f --- /dev/null +++ b/src/main/java/dev/brighten/ac/utils/json/XMLTokener.java @@ -0,0 +1,377 @@ +package dev.brighten.ac.utils.json; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import dev.brighten.ac.utils.json.JSONException; +import dev.brighten.ac.utils.json.JSONTokener; +import dev.brighten.ac.utils.json.XML; + +/** + * The XMLTokener extends the JSONTokener to provide additional methods + * for the parsing of XML texts. + * + * @author JSON.org + * @version 2010-12-24 + */ +public class XMLTokener extends JSONTokener { + + + /** + * The table of entity values. It initially contains Character values for + * amp, apos, gt, lt, quot. + */ + public static final java.util.HashMap entity; + + static { + entity = new java.util.HashMap(8); + entity.put("amp", XML.AMP); + entity.put("apos", XML.APOS); + entity.put("gt", XML.GT); + entity.put("lt", XML.LT); + entity.put("quot", XML.QUOT); + } + + /** + * Construct an XMLTokener from a string. + * + * @param s A source string. + */ + public XMLTokener(String s) { + super(s); + } + + /** + * Get the text in the CDATA block. + * + * @return The string up to the ]]>. + * @throws JSONException If the ]]> is not found. + */ + public String nextCDATA() throws JSONException { + char c; + int i; + StringBuffer sb = new StringBuffer(); + for (; ; ) { + c = next(); + if (end()) { + throw syntaxError("Unclosed CDATA"); + } + sb.append(c); + i = sb.length() - 3; + if (i >= 0 && sb.charAt(i) == ']' && + sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { + sb.setLength(i); + return sb.toString(); + } + } + } + + + /** + * Get the next XML outer token, trimming whitespace. There are two kinds + * of tokens: the '<' character which begins a markup tag, and the content + * text between markup tags. + * + * @return A string, or a '<' Character, or null if there is no more + * source text. + * @throws JSONException + */ + public Object nextContent() throws JSONException { + char c; + StringBuffer sb; + do { + c = next(); + } while (Character.isWhitespace(c)); + if (c == 0) { + return null; + } + if (c == '<') { + return XML.LT; + } + sb = new StringBuffer(); + for (; ; ) { + if (c == '<' || c == 0) { + back(); + return sb.toString().trim(); + } + if (c == '&') { + sb.append(nextEntity(c)); + } else { + sb.append(c); + } + c = next(); + } + } + + + /** + * Return the next entity. These entities are translated to Characters: + * & ' > < ". + * + * @param ampersand An ampersand character. + * @return A Character or an entity String if the entity is not recognized. + * @throws JSONException If missing ';' in XML entity. + */ + public Object nextEntity(char ampersand) throws JSONException { + StringBuffer sb = new StringBuffer(); + for (; ; ) { + char c = next(); + if (Character.isLetterOrDigit(c) || c == '#') { + sb.append(Character.toLowerCase(c)); + } else if (c == ';') { + break; + } else { + throw syntaxError("Missing ';' in XML entity: &" + sb); + } + } + String string = sb.toString(); + Object object = entity.get(string); + return object != null ? object : ampersand + string + ";"; + } + + + /** + * Returns the next XML meta token. This is used for skipping over + * and structures. + * + * @return Syntax characters (< > / = ! ?) are returned as + * Character, and strings and names are returned as Boolean. We don't care + * what the values actually are. + * @throws JSONException If a string is not properly closed or if the XML + * is badly structured. + */ + public Object nextMeta() throws JSONException { + char c; + char q; + do { + c = next(); + } while (Character.isWhitespace(c)); + switch (c) { + case 0: + throw syntaxError("Misshaped meta tag"); + case '<': + return XML.LT; + case '>': + return XML.GT; + case '/': + return XML.SLASH; + case '=': + return XML.EQ; + case '!': + return XML.BANG; + case '?': + return XML.QUEST; + case '"': + case '\'': + q = c; + for (; ; ) { + c = next(); + if (c == 0) { + throw syntaxError("Unterminated string"); + } + if (c == q) { + return Boolean.TRUE; + } + } + default: + for (; ; ) { + c = next(); + if (Character.isWhitespace(c)) { + return Boolean.TRUE; + } + switch (c) { + case 0: + case '<': + case '>': + case '/': + case '=': + case '!': + case '?': + case '"': + case '\'': + back(); + return Boolean.TRUE; + } + } + } + } + + + /** + * Get the next XML Token. These tokens are found inside of angle + * brackets. It may be one of these characters: / > = ! ? or it + * may be a string wrapped in single quotes or double quotes, or it may be a + * name. + * + * @return a String or a Character. + * @throws JSONException If the XML is not well formed. + */ + public Object nextToken() throws JSONException { + char c; + char q; + StringBuffer sb; + do { + c = next(); + } while (Character.isWhitespace(c)); + switch (c) { + case 0: + throw syntaxError("Misshaped element"); + case '<': + throw syntaxError("Misplaced '<'"); + case '>': + return XML.GT; + case '/': + return XML.SLASH; + case '=': + return XML.EQ; + case '!': + return XML.BANG; + case '?': + return XML.QUEST; + +// Quoted string + + case '"': + case '\'': + q = c; + sb = new StringBuffer(); + for (; ; ) { + c = next(); + if (c == 0) { + throw syntaxError("Unterminated string"); + } + if (c == q) { + return sb.toString(); + } + if (c == '&') { + sb.append(nextEntity(c)); + } else { + sb.append(c); + } + } + default: + +// Name + + sb = new StringBuffer(); + for (; ; ) { + sb.append(c); + c = next(); + if (Character.isWhitespace(c)) { + return sb.toString(); + } + switch (c) { + case 0: + return sb.toString(); + case '>': + case '/': + case '=': + case '!': + case '?': + case '[': + case ']': + back(); + return sb.toString(); + case '<': + case '"': + case '\'': + throw syntaxError("Bad character in a name"); + } + } + } + } + + + /** + * Skip characters until past the requested string. + * If it is not found, we are left at the end of the source with a result of false. + * + * @param to A string to skip past. + * @throws JSONException + */ + public boolean skipPast(String to) throws JSONException { + boolean b; + char c; + int i; + int j; + int offset = 0; + int length = to.length(); + char[] circle = new char[length]; + + /* + * First fill the circle buffer with as many characters as are in the + * to string. If we reach an early end, bail. + */ + + for (i = 0; i < length; i += 1) { + c = next(); + if (c == 0) { + return false; + } + circle[i] = c; + } + /* + * We will loop, possibly for all of the remaining characters. + */ + for (; ; ) { + j = offset; + b = true; + /* + * Compare the circle buffer with the to string. + */ + for (i = 0; i < length; i += 1) { + if (circle[j] != to.charAt(i)) { + b = false; + break; + } + j += 1; + if (j >= length) { + j -= length; + } + } + /* + * If we exit the loop with b intact, then victory is ours. + */ + if (b) { + return true; + } + /* + * Get the next character. If there isn't one, then defeat is ours. + */ + c = next(); + if (c == 0) { + return false; + } + /* + * Shove the character in the circle buffer and advance the + * circle offset. The offset is mod n. + */ + circle[offset] = c; + offset += 1; + if (offset >= length) { + offset -= length; + } + } + } +} diff --git a/src/main/java/dev/brighten/ac/utils/math/IntVector.java b/src/main/java/dev/brighten/ac/utils/math/IntVector.java index 916eca7..97d88a4 100644 --- a/src/main/java/dev/brighten/ac/utils/math/IntVector.java +++ b/src/main/java/dev/brighten/ac/utils/math/IntVector.java @@ -6,8 +6,6 @@ import lombok.NoArgsConstructor; import lombok.Setter; import org.bukkit.util.Vector; -import java.util.Objects; - @AllArgsConstructor @NoArgsConstructor public class IntVector { @@ -30,14 +28,18 @@ public class IntVector { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if(!(o instanceof IntVector)) return false; + IntVector intVector = (IntVector) o; return x == intVector.x && y == intVector.y && z == intVector.z; } @Override public int hashCode() { - return Objects.hash(x, y, z); + int hash = 7; + hash = 79 * hash + (int)(Double.doubleToLongBits(this.x) ^ Double.doubleToLongBits(this.x) >>> 32); + hash = 79 * hash + (int)(Double.doubleToLongBits(this.y) ^ Double.doubleToLongBits(this.y) >>> 32); + hash = 79 * hash + (int)(Double.doubleToLongBits(this.z) ^ Double.doubleToLongBits(this.z) >>> 32); + return hash; } }