file_id
int64
1
215k
content
stringlengths
7
454k
repo
stringlengths
6
113
path
stringlengths
6
251
213,265
package com.worldcretornica.plotme; import com.worldcretornica.plotme.utils.MinecraftFontWidthCalculator; import net.milkbowl.vault.economy.EconomyResponse; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.OfflinePlayer; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.*; public class PMCommand implements CommandExecutor { private PlotMe plugin; private final ChatColor BLUE = ChatColor.BLUE; private final ChatColor RED = ChatColor.RED; private final ChatColor RESET = ChatColor.RESET; private final ChatColor AQUA = ChatColor.AQUA; private final ChatColor GREEN = ChatColor.GREEN; private final ChatColor ITALIC = ChatColor.ITALIC; private final String PREFIX = PlotMe.PREFIX; private final String LOG = "[" + PlotMe.NAME + " Event] "; private final boolean isAdv = PlotMe.advancedlogging; public PMCommand(PlotMe instance) { plugin = instance; } private String C(String caption) { return PlotMe.caption(caption); } public boolean onCommand(CommandSender s, Command c, String l, String[] args) { if (l.equalsIgnoreCase("plotme") || l.equalsIgnoreCase("plot") || l.equalsIgnoreCase("p")) { if (!(s instanceof Player)) { if (args.length == 0 || args[0].equalsIgnoreCase("1")) { s.sendMessage(C("ConsoleHelpMain")); s.sendMessage(" - /plotme reload"); s.sendMessage(C("ConsoleHelpReload")); return true; } else { String a0 = args[0]; if (a0.equalsIgnoreCase("reload")) { return reload(s, args); } if (a0.equalsIgnoreCase(C("CommandResetExpired"))) { return resetexpired(s, args); } } } else { Player p = (Player) s; if (args.length == 0) { return showhelp(p, 1); } else { String a0 = args[0]; int ipage = -1; try { ipage = Integer.parseInt(a0); } catch (NumberFormatException ignored) { } if (ipage != -1) { return showhelp(p, ipage); } else { if (a0.equalsIgnoreCase(C("CommandHelp"))) { ipage = -1; if (args.length > 1) { String a1 = args[1]; ipage = -1; try { ipage = Integer.parseInt(a1); } catch (NumberFormatException e) { } } if (ipage != -1) { return showhelp(p, ipage); } else { return showhelp(p, 1); } } if (a0.equalsIgnoreCase(C("CommandClaim"))) { return claim(p, args); } if (a0.equalsIgnoreCase(C("CommandAuto"))) { return auto(p, args); } if (a0.equalsIgnoreCase(C("CommandInfo")) || a0.equalsIgnoreCase("i")) { return info(p, args); } if (a0.equalsIgnoreCase(C("CommandComment"))) { return comment(p, args); } if (a0.equalsIgnoreCase(C("CommandComments")) || a0.equalsIgnoreCase("c")) { return comments(p, args); } if (a0.equalsIgnoreCase(C("CommandBiome")) || a0.equalsIgnoreCase("b")) { return biome(p, args); } if (a0.equalsIgnoreCase(C("CommandBiomelist"))) { return biomelist(p, args); } if (a0.equalsIgnoreCase(C("CommandId"))) { return id(p, args); } if (a0.equalsIgnoreCase(C("CommandTp"))) { return tp(p, args); } if (a0.equalsIgnoreCase(C("CommandClear"))) { return clear(p, args); } if (a0.equalsIgnoreCase(C("CommandReset"))) { return reset(p, args); } if (a0.equalsIgnoreCase(C("CommandAdd")) || a0.equalsIgnoreCase("+")) { return add(p, args); } if (PlotMe.allowToDeny) { if (a0.equalsIgnoreCase(C("CommandDeny"))) { return deny(p, args); } if (a0.equalsIgnoreCase(C("CommandUndeny"))) { return undeny(p, args); } } if (a0.equalsIgnoreCase(C("CommandRemove")) || a0.equalsIgnoreCase("-")) { return remove(p, args); } if (a0.equalsIgnoreCase(C("CommandSetowner")) || a0.equalsIgnoreCase("o")) { return setowner(p, args); } if (a0.equalsIgnoreCase(C("CommandMove")) || a0.equalsIgnoreCase("m")) { return move(p, args); } if (a0.equalsIgnoreCase("reload")) { return reload(s, args); } if (a0.equalsIgnoreCase(C("CommandWEAnywhere"))) { return weanywhere(p, args); } if (a0.equalsIgnoreCase(C("CommandList"))) { return plotlist(p, args); } if (a0.equalsIgnoreCase(C("CommandExpired"))) { return expired(p, args); } if (a0.equalsIgnoreCase(C("CommandAddtime"))) { return addtime(p, args); } if (a0.equalsIgnoreCase(C("CommandDone"))) { return done(p, args); } if (a0.equalsIgnoreCase(C("CommandDoneList"))) { return donelist(p, args); } if (a0.equalsIgnoreCase(C("CommandProtect"))) { return protect(p, args); } if (a0.equalsIgnoreCase(C("CommandSell"))) { return sell(p, args); } if (a0.equalsIgnoreCase(C("CommandDispose"))) { return dispose(p, args); } if (a0.equalsIgnoreCase(C("CommandAuction"))) { return auction(p, args); } if (a0.equalsIgnoreCase(C("CommandBuy"))) { return buy(p, args); } if (a0.equalsIgnoreCase(C("CommandBid"))) { return bid(p, args); } if (a0.startsWith(C("CommandHome")) || a0.startsWith("h")) { return home(p, args); } if (a0.equalsIgnoreCase(C("CommandResetExpired"))) { return resetexpired(p, args); } } } } } return false; } private boolean resetexpired(CommandSender s, String[] args) { if (PlotMe.cPerms(s, "PlotMe.admin.resetexpired")) { if (args.length <= 1) { Send(s, C("WordUsage") + ": " + RED + "/plotme " + C("CommandResetExpired") + " <" + C("WordWorld") + "> " + RESET + "Example: " + RED + "/plotme " + C("CommandResetExpired") + " plotworld "); } else if (PlotMe.worldcurrentlyprocessingexpired != null) { Send(s, PlotMe.cscurrentlyprocessingexpired.getName() + " " + C("MsgAlreadyProcessingPlots")); } else { World w = s.getServer().getWorld(args[1]); if (w == null) { Send(s, RED + C("WordWorld") + " '" + args[1] + "' " + C("MsgDoesNotExistOrNotLoaded")); return true; } else if (!PlotManager.isPlotWorld(w)) { Send(s, RED + C("MsgNotPlotWorld")); return true; } else { PlotMe.worldcurrentlyprocessingexpired = w; PlotMe.cscurrentlyprocessingexpired = s; PlotMe.counterexpired = 50; PlotMe.nbperdeletionprocessingexpired = 5; plugin.scheduleTask(new PlotRunnableDeleteExpire(), 5, 50); } } } else { Send(s, RED + C("MsgPermissionDenied")); } return true; } private boolean bid(Player p, String[] args) { if (PlotManager.isEconomyEnabled(p)) { if (PlotMe.cPerms(p, "PlotMe.use.bid")) { String id = PlotManager.getPlotId(p.getLocation()); if (id.equals("")) { Send(p, RED + C("MsgNoPlotFound")); } else if (!PlotManager.isPlotAvailable(id, p)) { Plot plot = PlotManager.getPlotById(p, id); if (plot.auctionned) { String bidder = p.getName(); OfflinePlayer playerbidder = p; if (plot.owner.equalsIgnoreCase(bidder)) { Send(p, RED + C("MsgCannotBidOwnPlot")); } else if (args.length == 2) { double bid = 0; double currentbid = plot.currentbid; String currentbidder = plot.currentbidder; OfflinePlayer playercurrentbidder = Bukkit.getOfflinePlayer(plot.currentbidderId); try { bid = Double.parseDouble(args[1]); } catch (NumberFormatException ignored) { } boolean equals = currentbidder.equals(""); if (bid < currentbid) { Send(p, RED + C("MsgInvalidBidMustBeAbove") + " " + RESET + f(plot.currentbid, false)); } else if (bid == currentbid) { if (!equals) { Send(p, RED + C("MsgInvalidBidMustBeAbove") + " " + RESET + f(plot.currentbid, false)); } else { double balance = PlotMe.economy.getBalance(playerbidder); if (bid >= balance && !currentbidder.equals(bidder) || currentbidder.equals(bidder) && bid > (balance + currentbid)) { Send(p, RED + C("MsgNotEnoughBid")); } else { EconomyResponse er = PlotMe.economy.withdrawPlayer(playerbidder, bid); if (er.transactionSuccess()) { plot.currentbidder = bidder; plot.currentbid = bid; plot.updateField("currentbidder", bidder); plot.updateField("currentbid", bid); PlotManager.setSellSign(p.getWorld(), plot); Send(p, C("MsgBidAccepted") + " " + f(-bid)); if (isAdv) { PlotMe.logger.info(LOG + bidder + " bid " + bid + " on plot " + id); } } else { Send(p, er.errorMessage); warn(er.errorMessage); } } } } else { double balance = PlotMe.economy.getBalance(playerbidder); if (bid >= balance && !currentbidder.equals(bidder) || currentbidder.equals(bidder) && bid > (balance + currentbid)) { Send(p, RED + C("MsgNotEnoughBid")); } else { EconomyResponse er = PlotMe.economy.withdrawPlayer(playerbidder, bid); if (er.transactionSuccess()) { if (!equals) { EconomyResponse er2 = PlotMe.economy.depositPlayer(playercurrentbidder, currentbid); if (!er2.transactionSuccess()) { Send(p, er2.errorMessage); warn(er2.errorMessage); } else { for (Player player : Bukkit.getServer().getOnlinePlayers()) { if (player.getName().equalsIgnoreCase(currentbidder)) { Send(player, C("MsgOutbidOnPlot") + " " + id + " " + C("MsgOwnedBy") + " " + plot.owner + ". " + f(bid)); break; } } } } plot.currentbidder = bidder; plot.currentbid = bid; plot.updateField("currentbidder", bidder); plot.updateField("currentbid", bid); PlotManager.setSellSign(p.getWorld(), plot); Send(p, C("MsgBidAccepted") + " " + f(-bid)); if (isAdv) { PlotMe.logger.info(LOG + bidder + " bid " + bid + " on plot " + id); } } else { Send(p, er.errorMessage); warn(er.errorMessage); } } } } else { Send(p, C("WordUsage") + ": " + RED + "/plotme " + C("CommandBid") + " <" + C("WordAmount") + "> " + RESET + C("WordExample") + ": " + RED + "/plotme " + C("CommandBid") + " 100"); } } else { Send(p, RED + C("MsgPlotNotAuctionned")); } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgHasNoOwner")); } } else { Send(p, RED + C("MsgPermissionDenied")); } } else { Send(p, RED + C("MsgEconomyDisabledWorld")); } return true; } private boolean buy(Player p, String[] args) { if (PlotManager.isEconomyEnabled(p)) { if (PlotMe.cPerms(p, "PlotMe.use.buy") || PlotMe.cPerms(p, "PlotMe.admin.buy")) { Location l = p.getLocation(); String id = PlotManager.getPlotId(l); if (id.equals("")) { Send(p, RED + C("MsgNoPlotFound")); } else if (!PlotManager.isPlotAvailable(id, p)) { Plot plot = PlotManager.getPlotById(p, id); if (!plot.forsale) { Send(p, RED + C("MsgPlotNotForSale")); } else { String buyer = p.getName(); if (plot.owner.equalsIgnoreCase(buyer)) { Send(p, RED + C("MsgCannotBuyOwnPlot")); } else { int plotlimit = PlotMe.getPlotLimit(p); if (plotlimit != -1 && PlotManager.getNbOwnedPlot(p) >= plotlimit) { Send(p, C("MsgAlreadyReachedMaxPlots") + " (" + PlotManager.getNbOwnedPlot(p) + "/" + PlotMe.getPlotLimit(p) + "). " + C("WordUse") + " " + RED + "/plotme " + C("CommandHome") + RESET + " " + C("MsgToGetToIt")); } else { World w = p.getWorld(); double cost = plot.customprice; if (PlotMe.economy.getBalance(p) < cost) { Send(p, RED + C("MsgNotEnoughBuy")); } else { EconomyResponse er = PlotMe.economy.withdrawPlayer(p, cost); if (er.transactionSuccess()) { String oldowner = plot.owner; OfflinePlayer playercurrentbidder = Bukkit.getOfflinePlayer(plot.ownerId); if (!oldowner.equalsIgnoreCase("$Bank$")) { EconomyResponse er2 = PlotMe.economy.depositPlayer(playercurrentbidder, cost); if (!er2.transactionSuccess()) { Send(p, RED + er2.errorMessage); warn(er2.errorMessage); } else { for (Player player : Bukkit.getServer().getOnlinePlayers()) { if (player.getName().equalsIgnoreCase(oldowner)) { Send(player, C("WordPlot") + " " + id + " " + C("MsgSoldTo") + " " + buyer + ". " + f(cost)); break; } } } } plot.owner = buyer; plot.customprice = 0; plot.forsale = false; plot.updateField("owner", buyer); plot.updateField("customprice", 0); plot.updateField("forsale", false); PlotManager.adjustWall(l); PlotManager.setSellSign(w, plot); PlotManager.setOwnerSign(w, plot); Send(p, C("MsgPlotBought") + " " + f(-cost)); if (isAdv) { PlotMe.logger.info(LOG + buyer + " " + C("MsgBoughtPlot") + " " + id + " " + C("WordFor") + " " + cost); } } else { Send(p, RED + er.errorMessage); warn(er.errorMessage); } } } } } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgHasNoOwner")); } } else { Send(p, RED + C("MsgPermissionDenied")); } } else { Send(p, RED + C("MsgEconomyDisabledWorld")); } return true; } private boolean auction(Player p, String[] args) { if (PlotManager.isEconomyEnabled(p)) { PlotMapInfo pmi = PlotManager.getMap(p); if (pmi.CanPutOnSale) { if (PlotMe.cPerms(p, "PlotMe.use.auction") || PlotMe.cPerms(p, "PlotMe.admin.auction")) { String id = PlotManager.getPlotId(p.getLocation()); if (id.equals("")) { Send(p, RED + C("MsgNoPlotFound")); } else if (!PlotManager.isPlotAvailable(id, p)) { Plot plot = PlotManager.getPlotById(p, id); String name = p.getName(); if (plot.owner.equalsIgnoreCase(name) || PlotMe.cPerms(p, "PlotMe.admin.auction")) { World w = p.getWorld(); if (plot.auctionned) { if (plot.currentbidder != null) { if (!plot.currentbidder.equalsIgnoreCase("")) { if (!PlotMe.cPerms(p, "PlotMe.admin.auction")) { Send(p, RED + C("MsgPlotHasBidsAskAdmin")); } else { if (plot.currentbidder != null) { OfflinePlayer playercurrentbidder = Bukkit.getOfflinePlayer(plot.currentbidderId); EconomyResponse er = PlotMe.economy.depositPlayer(playercurrentbidder, plot.currentbid); if (!er.transactionSuccess()) { Send(p, RED + er.errorMessage); warn(er.errorMessage); } else { for (Player player : Bukkit.getServer().getOnlinePlayers()) { if (plot.currentbidder != null && player.getName().equalsIgnoreCase(plot.currentbidder)) { Send(player, C("MsgAuctionCancelledOnPlot") + " " + id + " " + C("MsgOwnedBy") + " " + plot.owner + ". " + f(plot.currentbid)); break; } } } } plot.auctionned = false; PlotManager.adjustWall(p.getLocation()); PlotManager.setSellSign(w, plot); plot.currentbid = 0; plot.currentbidder = ""; plot.updateField("currentbid", 0); plot.updateField("currentbidder", ""); plot.updateField("auctionned", false); Send(p, C("MsgAuctionCancelled")); if (isAdv) { PlotMe.logger.info(LOG + name + " " + C("MsgStoppedTheAuctionOnPlot") + " " + id); } } } else { plot.auctionned = false; PlotManager.adjustWall(p.getLocation()); PlotManager.setSellSign(w, plot); plot.currentbid = 0; plot.currentbidder = ""; plot.updateField("currentbid", 0); plot.updateField("currentbidder", ""); plot.updateField("auctionned", false); Send(p, C("MsgAuctionCancelled")); if (isAdv) { PlotMe.logger.info(LOG + name + " " + C("MsgStoppedTheAuctionOnPlot") + " " + id); } } } else { plot.auctionned = false; PlotManager.adjustWall(p.getLocation()); PlotManager.setSellSign(w, plot); plot.currentbid = 0; plot.currentbidder = ""; plot.updateField("currentbid", 0); plot.updateField("currentbidder", ""); plot.updateField("auctionned", false); Send(p, C("MsgAuctionCancelled")); if (isAdv) { PlotMe.logger.info(LOG + name + " " + C("MsgStoppedTheAuctionOnPlot") + " " + id); } } } else { double bid = 1; if (args.length == 2) { try { bid = Double.parseDouble(args[1]); } catch (NumberFormatException ignored) { } } if (bid < 0) { Send(p, RED + C("MsgInvalidAmount")); } else { plot.currentbid = bid; plot.auctionned = true; PlotManager.adjustWall(p.getLocation()); PlotManager.setSellSign(w, plot); plot.updateField("currentbid", bid); plot.updateField("auctionned", true); Send(p, C("MsgAuctionStarted")); if (isAdv) { PlotMe.logger.info(LOG + name + " " + C("MsgStartedAuctionOnPlot") + " " + id + " " + C("WordAt") + " " + bid); } } } } else { Send(p, RED + C("MsgDoNotOwnPlot")); } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgHasNoOwner")); } } else { Send(p, RED + C("MsgPermissionDenied")); } } else { Send(p, RED + C("MsgSellingPlotsIsDisabledWorld")); } } else { Send(p, RED + C("MsgEconomyDisabledWorld")); } return true; } private boolean dispose(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.admin.dispose") || PlotMe.cPerms(p, "PlotMe.use.dispose")) { if (!PlotManager.isPlotWorld(p)) { Send(p, RED + C("MsgNotPlotWorld")); } else { String id = PlotManager.getPlotId(p.getLocation()); if (id.equals("")) { Send(p, RED + C("MsgNoPlotFound")); } else if (!PlotManager.isPlotAvailable(id, p)) { Plot plot = PlotManager.getPlotById(p, id); if (plot.protect) { Send(p, RED + C("MsgPlotProtectedNotDisposed")); } else { String name = p.getName(); if (plot.owner.equalsIgnoreCase(name) || PlotMe.cPerms(p, "PlotMe.admin.dispose")) { PlotMapInfo pmi = PlotManager.getMap(p); double cost = pmi.DisposePrice; if (PlotManager.isEconomyEnabled(p)) { if (cost != 0 && PlotMe.economy.getBalance(p) < cost) { Send(p, RED + C("MsgNotEnoughDispose")); return true; } EconomyResponse er = PlotMe.economy.withdrawPlayer(p, cost); if (!er.transactionSuccess()) { Send(p, RED + er.errorMessage); warn(er.errorMessage); return true; } if (plot.auctionned) { String currentbidder = plot.currentbidder; OfflinePlayer playercurrentbidder = Bukkit.getOfflinePlayer(plot.currentbidderId); if (!currentbidder.equals("")) { EconomyResponse er2 = PlotMe.economy.depositPlayer(playercurrentbidder, plot.currentbid); if (!er2.transactionSuccess()) { Send(p, RED + er2.errorMessage); warn(er2.errorMessage); } else { for (Player player : Bukkit.getServer().getOnlinePlayers()) { if (player.getName().equalsIgnoreCase(currentbidder)) { Send(player, C("WordPlot") + " " + id + " " + C("MsgOwnedBy") + " " + plot.owner + " " + C("MsgWasDisposed") + " " + f(cost)); break; } } } } } } World w = p.getWorld(); if (!PlotManager.isPlotAvailable(id, p)) { PlotManager.getPlots(p).remove(id); } PlotManager.removeOwnerSign(w, id); PlotManager.removeSellSign(w, id); SqlManager.deletePlot(PlotManager.getIdX(id), PlotManager.getIdZ(id), w.getName().toLowerCase()); Send(p, C("MsgPlotDisposedAnyoneClaim")); if (isAdv) { PlotMe.logger.info(LOG + name + " " + C("MsgDisposedPlot") + " " + id); } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgNotYoursCannotDispose")); } } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgHasNoOwner")); } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean sell(Player p, String[] args) { if (PlotManager.isEconomyEnabled(p)) { PlotMapInfo pmi = PlotManager.getMap(p); if (pmi.CanSellToBank || pmi.CanPutOnSale) { if (PlotMe.cPerms(p, "PlotMe.use.sell") || PlotMe.cPerms(p, "PlotMe.admin.sell")) { Location l = p.getLocation(); String id = PlotManager.getPlotId(l); if (id.equals("")) { Send(p, RED + C("MsgNoPlotFound")); } else if (!PlotManager.isPlotAvailable(id, p)) { Plot plot = PlotManager.getPlotById(p, id); if (plot.owner.equalsIgnoreCase(p.getName()) || PlotMe.cPerms(p, "PlotMe.admin.sell")) { World w = p.getWorld(); String name = p.getName(); if (plot.forsale) { plot.customprice = 0; plot.forsale = false; plot.updateField("customprice", 0); plot.updateField("forsale", false); PlotManager.adjustWall(l); PlotManager.setSellSign(w, plot); Send(p, C("MsgPlotNoLongerSale")); if (isAdv) { PlotMe.logger.info(LOG + name + " " + C("MsgRemovedPlot") + " " + id + " " + C("MsgFromBeingSold")); } } else { double price = pmi.SellToPlayerPrice; boolean bank = false; if (args.length == 2) { if (args[1].equalsIgnoreCase("bank")) { bank = true; } else if (pmi.CanCustomizeSellPrice) { try { price = Double.parseDouble(args[1]); } catch (Exception e) { if (pmi.CanSellToBank) { Send(p, C("WordUsage") + ": " + RED + " /plotme " + C("CommandSellBank") + "|<" + C("WordAmount") + ">"); p.sendMessage(" " + C("WordExample") + ": " + RED + "/plotme " + C("CommandSellBank") + " " + RESET + " or " + RED + " /plotme " + C("CommandSell") + " 200"); } else { Send(p, C("WordUsage") + ": " + RED + " /plotme " + C("CommandSell") + " <" + C("WordAmount") + ">" + RESET + " " + C("WordExample") + ": " + RED + "/plotme " + C("CommandSell") + " 200"); } } } else { Send(p, RED + C("MsgCannotCustomPriceDefault") + " " + price); return true; } } if (bank) { if (!pmi.CanSellToBank) { Send(p, RED + C("MsgCannotSellToBank")); } else { String currentbidder = plot.currentbidder; if (!currentbidder.equals("")) { double bid = plot.currentbid; OfflinePlayer playercurrentbidder = Bukkit.getOfflinePlayer(plot.currentbidderId); EconomyResponse er = PlotMe.economy.depositPlayer(playercurrentbidder, bid); if (!er.transactionSuccess()) { Send(p, RED + er.errorMessage); warn(er.errorMessage); } else { for (Player player : Bukkit.getServer().getOnlinePlayers()) { if (player.getName().equalsIgnoreCase(currentbidder)) { Send(player, C("WordPlot") + " " + id + " " + C("MsgOwnedBy") + " " + plot.owner + " " + C("MsgSoldToBank") + " " + f(bid)); break; } } } } double sellprice = pmi.SellToBankPrice; EconomyResponse er = PlotMe.economy.depositPlayer(p, sellprice); if (er.transactionSuccess()) { plot.owner = "$Bank$"; plot.forsale = true; plot.customprice = pmi.BuyFromBankPrice; plot.auctionned = false; plot.currentbidder = ""; plot.currentbid = 0; plot.removeAllAllowed(); PlotManager.setOwnerSign(w, plot); PlotManager.setSellSign(w, plot); plot.updateField("owner", plot.owner); plot.updateField("forsale", true); plot.updateField("auctionned", true); plot.updateField("customprice", plot.customprice); plot.updateField("currentbidder", ""); plot.updateField("currentbid", 0); Send(p, C("MsgPlotSold") + " " + f(sellprice)); if (isAdv) { PlotMe.logger.info(LOG + name + " " + C("MsgSoldToBankPlot") + " " + id + " " + C("WordFor") + " " + sellprice); } } else { Send(p, " " + er.errorMessage); warn(er.errorMessage); } } } else if (price < 0) { Send(p, RED + C("MsgInvalidAmount")); } else { plot.customprice = price; plot.forsale = true; plot.updateField("customprice", price); plot.updateField("forsale", true); PlotManager.adjustWall(l); PlotManager.setSellSign(w, plot); Send(p, C("MsgPlotForSale")); if (isAdv) { PlotMe.logger.info(LOG + name + " " + C("MsgPutOnSalePlot") + " " + id + " " + C("WordFor") + " " + price); } } } } else { Send(p, RED + C("MsgDoNotOwnPlot")); } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgHasNoOwner")); } } else { Send(p, RED + C("MsgPermissionDenied")); } } else { Send(p, RED + C("MsgSellingPlotsIsDisabledWorld")); } } else { Send(p, RED + C("MsgEconomyDisabledWorld")); } return true; } private boolean protect(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.admin.protect") || PlotMe.cPerms(p, "PlotMe.use.protect")) { if (!PlotManager.isPlotWorld(p)) { Send(p, RED + C("MsgNotPlotWorld")); return true; } else { String id = PlotManager.getPlotId(p.getLocation()); if (id.equals("")) { Send(p, RED + C("MsgNoPlotFound")); } else if (!PlotManager.isPlotAvailable(id, p)) { Plot plot = PlotManager.getPlotById(p, id); String name = p.getName(); if (plot.owner.equalsIgnoreCase(name) || PlotMe.cPerms(p, "PlotMe.admin.protect")) { if (plot.protect) { plot.protect = false; PlotManager.adjustWall(p.getLocation()); plot.updateField("protected", false); Send(p, C("MsgPlotNoLongerProtected")); if (isAdv) { PlotMe.logger.info(LOG + name + " " + C("MsgUnprotectedPlot") + " " + id); } } else { PlotMapInfo pmi = PlotManager.getMap(p); double cost = 0; if (PlotManager.isEconomyEnabled(p)) { cost = pmi.ProtectPrice; if (PlotMe.economy.getBalance(p) < cost) { Send(p, RED + C("MsgNotEnoughProtectPlot")); return true; } else { EconomyResponse er = PlotMe.economy.withdrawPlayer(p, cost); if (!er.transactionSuccess()) { Send(p, RED + er.errorMessage); warn(er.errorMessage); return true; } } } plot.protect = true; PlotManager.adjustWall(p.getLocation()); plot.updateField("protected", true); Send(p, C("MsgPlotNowProtected") + " " + f(-cost)); if (isAdv) { PlotMe.logger.info(LOG + name + " " + C("MsgProtectedPlot") + " " + id); } } } else { Send(p, RED + C("MsgDoNotOwnPlot")); } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgHasNoOwner")); } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean donelist(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.admin.done")) { PlotMapInfo pmi = PlotManager.getMap(p); if (pmi == null) { Send(p, RED + C("MsgNotPlotWorld")); return true; } else { HashMap<String, Plot> plots = pmi.plots; List<Plot> finishedplots = new ArrayList<>(); int nbfinished = 0; int maxpage; int pagesize = 8; int page = 1; if (args.length == 2) { try { page = Integer.parseInt(args[1]); } catch (NumberFormatException ignored) { } } for (String id : plots.keySet()) { Plot plot = plots.get(id); if (plot.finished) { finishedplots.add(plot); nbfinished++; } } Collections.sort(finishedplots, new PlotFinishedComparator()); maxpage = (int) Math.ceil(((double) nbfinished / (double) pagesize)); if (finishedplots.size() == 0) { Send(p, C("MsgNoPlotsFinished")); } else { Send(p, C("MsgFinishedPlotsPage") + " " + page + "/" + maxpage); for (int i = (page - 1) * pagesize; i < finishedplots.size() && i < (page * pagesize); i++) { Plot plot = finishedplots.get(i); String starttext = " " + BLUE + plot.id + RESET + " -> " + plot.owner; int textLength = MinecraftFontWidthCalculator.getStringWidth(starttext); String line = starttext + whitespace(550 - textLength) + "@" + plot.finisheddate; p.sendMessage(line); } } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean done(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.use.done") || PlotMe.cPerms(p, "PlotMe.admin.done")) { if (!PlotManager.isPlotWorld(p)) { Send(p, RED + C("MsgNotPlotWorld")); return true; } else { String id = PlotManager.getPlotId(p.getLocation()); if (id.equals("")) { Send(p, RED + C("MsgNoPlotFound")); } else { if (!PlotManager.isPlotAvailable(id, p)) { Plot plot = PlotManager.getPlotById(p, id); String name = p.getName(); if (plot.owner.equalsIgnoreCase(name) || PlotMe.cPerms(p, "PlotMe.admin.done")) { if (plot.finished) { plot.setUnfinished(); Send(p, C("MsgUnmarkFinished")); if (isAdv) { PlotMe.logger.info(LOG + name + " " + C("WordMarked") + " " + id + " " + C("WordFinished")); } } else { plot.setFinished(); Send(p, C("MsgMarkFinished")); if (isAdv) { PlotMe.logger.info(LOG + name + " " + C("WordMarked") + " " + id + " " + C("WordUnfinished")); } } } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgHasNoOwner")); } } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean addtime(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.admin.addtime")) { if (!PlotManager.isPlotWorld(p)) { Send(p, RED + C("MsgNotPlotWorld")); return true; } else { String id = PlotManager.getPlotId(p.getLocation()); if (id.equals("")) { Send(p, RED + C("MsgNoPlotFound")); } else if (!PlotManager.isPlotAvailable(id, p)) { Plot plot = PlotManager.getPlotById(p, id); if (plot != null) { String name = p.getName(); plot.resetExpire(PlotManager.getMap(p).DaysToExpiration); Send(p, C("MsgPlotExpirationReset")); if (isAdv) { PlotMe.logger.info(LOG + name + " reset expiration on plot " + id); } } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgHasNoOwner")); } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean expired(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.admin.expired")) { if (!PlotManager.isPlotWorld(p)) { Send(p, RED + C("MsgNotPlotWorld")); return true; } else { int pagesize = 8; int page = 1; int maxpage; int nbexpiredplots = 0; World w = p.getWorld(); List<Plot> expiredplots = new ArrayList<>(); HashMap<String, Plot> plots = PlotManager.getPlots(w); String date = PlotMe.getDate(); if (args.length == 2) { try { page = Integer.parseInt(args[1]); } catch (NumberFormatException ignored) { } } for (String id : plots.keySet()) { Plot plot = plots.get(id); if (!plot.protect && plot.expireddate != null && PlotMe.getDate(plot.expireddate).compareTo(date) < 0) { nbexpiredplots++; expiredplots.add(plot); } } Collections.sort(expiredplots); maxpage = (int) Math.ceil(((double) nbexpiredplots / (double) pagesize)); if (expiredplots.size() == 0) { Send(p, C("MsgNoPlotExpired")); } else { Send(p, C("MsgExpiredPlotsPage") + " " + page + "/" + maxpage); for (int i = (page - 1) * pagesize; i < expiredplots.size() && i < (page * pagesize); i++) { Plot plot = expiredplots.get(i); String starttext = " " + BLUE + plot.id + RESET + " -> " + plot.owner; int textLength = MinecraftFontWidthCalculator.getStringWidth(starttext); String line = starttext + whitespace(550 - textLength) + "@" + plot.expireddate.toString(); p.sendMessage(line); } } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean plotlist(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.use.list")) { if (!PlotManager.isPlotWorld(p)) { Send(p, RED + C("MsgNotPlotWorld")); return true; } else { String name; String pname = p.getName(); if (PlotMe.cPerms(p, "PlotMe.admin.list") && args.length == 2) { name = args[1]; Send(p, C("MsgListOfPlotsWhere") + " " + BLUE + name + RESET + " " + C("MsgCanBuild")); } else { name = p.getName(); Send(p, C("MsgListOfPlotsWhereYou")); } for (Plot plot : PlotManager.getPlots(p).values()) { StringBuilder addition = new StringBuilder(); if (plot.expireddate != null) { java.util.Date tempdate = plot.expireddate; if (tempdate.compareTo(Calendar.getInstance().getTime()) < 0) { addition.append(RED + " @" + plot.expireddate.toString() + RESET); } else { addition.append(" @" + plot.expireddate.toString()); } } if (plot.auctionned) { addition.append(" " + C("WordAuction") + ": " + GREEN + round(plot.currentbid) + RESET + ((plot.currentbidder != null && !plot.currentbidder.equals("")) ? " " + plot.currentbidder : "")); } if (plot.forsale) { addition.append(" " + C("WordSell") + ": " + GREEN + round(plot.customprice) + RESET); } if (plot.owner.equalsIgnoreCase(name)) { if (plot.allowedcount() == 0) { if (name.equalsIgnoreCase(pname)) { p.sendMessage(" " + plot.id + " -> " + BLUE + ITALIC + C("WordYours") + RESET + addition); } else { p.sendMessage(" " + plot.id + " -> " + BLUE + ITALIC + plot.owner + RESET + addition); } } else { StringBuilder helpers = new StringBuilder(); for (int i = 0; i < plot.allowedcount(); i++) { helpers.append(BLUE).append(plot.allowed().toArray()[i]).append(RESET).append(", "); } if (helpers.length() > 2) { helpers.delete(helpers.length() - 2, helpers.length()); } if (name.equalsIgnoreCase(pname)) { p.sendMessage(" " + plot.id + " -> " + BLUE + ITALIC + C("WordYours") + RESET + addition + ", " + C("WordHelpers") + ": " + helpers); } else { p.sendMessage(" " + plot.id + " -> " + BLUE + ITALIC + plot.owner + RESET + addition + ", " + C("WordHelpers") + ": " + helpers); } } } else if (plot.isAllowedConsulting(name)) { StringBuilder helpers = new StringBuilder(); for (int i = 0; i < plot.allowedcount(); i++) { if (p.getName().equalsIgnoreCase((String) plot.allowed().toArray()[i])) { if (name.equalsIgnoreCase(pname)) { helpers.append(BLUE).append(ITALIC).append("You").append(RESET).append(", "); } else { helpers.append(BLUE).append(ITALIC).append(args[1]).append(RESET).append(", "); } } else { helpers.append(BLUE).append(plot.allowed().toArray()[i]).append(RESET).append(", "); } } if (helpers.length() > 2) { helpers.delete(helpers.length() - 2, helpers.length()); } if (plot.owner.equalsIgnoreCase(pname)) { p.sendMessage(" " + plot.id + " -> " + BLUE + C("WordYours") + RESET + addition + ", " + C("WordHelpers") + ": " + helpers); } else { p.sendMessage(" " + plot.id + " -> " + BLUE + plot.owner + C("WordPossessive") + RESET + addition + ", " + C("WordHelpers") + ": " + helpers); } } } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean weanywhere(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.admin.weanywhere")) { String name = p.getName(); if (PlotMe.isIgnoringWELimit(p) && !PlotMe.defaultWEAnywhere || !PlotMe.isIgnoringWELimit(p) && PlotMe.defaultWEAnywhere) { PlotMe.removeIgnoreWELimit(p); } else { PlotMe.addIgnoreWELimit(p); } if (PlotMe.isIgnoringWELimit(p)) { Send(p, C("MsgWorldEditAnywhere")); if (isAdv) { PlotMe.logger.info(LOG + name + " enabled WorldEdit anywhere"); } } else { Send(p, C("MsgWorldEditInYourPlots")); if (isAdv) { PlotMe.logger.info(LOG + name + " disabled WorldEdit anywhere"); } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean showhelp(Player p, int page) { int max = 4; int maxpage = 0; boolean ecoon = PlotManager.isEconomyEnabled(p); List<String> allowed_commands = new ArrayList<>(); allowed_commands.add("limit"); if (PlotMe.cPerms(p, "PlotMe.use.claim")) { allowed_commands.add("claim"); } if (PlotMe.cPerms(p, "PlotMe.use.claim.other")) { allowed_commands.add("claim.other"); } if (PlotMe.cPerms(p, "PlotMe.use.auto")) { allowed_commands.add("auto"); } if (PlotMe.cPerms(p, "PlotMe.use.home")) { allowed_commands.add("home"); } if (PlotMe.cPerms(p, "PlotMe.use.home.other")) { allowed_commands.add("home.other"); } if (PlotMe.cPerms(p, "PlotMe.use.info")) { allowed_commands.add("info"); allowed_commands.add("biomeinfo"); } if (PlotMe.cPerms(p, "PlotMe.use.comment")) { allowed_commands.add("comment"); } if (PlotMe.cPerms(p, "PlotMe.use.comments")) { allowed_commands.add("comments"); } if (PlotMe.cPerms(p, "PlotMe.use.list")) { allowed_commands.add("list"); } if (PlotMe.cPerms(p, "PlotMe.use.biome")) { allowed_commands.add("biome"); allowed_commands.add("biomelist"); } if (PlotMe.cPerms(p, "PlotMe.use.done") || PlotMe.cPerms(p, "PlotMe.admin.done")) { allowed_commands.add("done"); } if (PlotMe.cPerms(p, "PlotMe.admin.done")) { allowed_commands.add("donelist"); } if (PlotMe.cPerms(p, "PlotMe.admin.tp")) { allowed_commands.add("tp"); } if (PlotMe.cPerms(p, "PlotMe.admin.id")) { allowed_commands.add("id"); } if (PlotMe.cPerms(p, "PlotMe.use.clear") || PlotMe.cPerms(p, "PlotMe.admin.clear")) { allowed_commands.add("clear"); } if (PlotMe.cPerms(p, "PlotMe.admin.dispose") || PlotMe.cPerms(p, "PlotMe.use.dispose")) { allowed_commands.add("dispose"); } if (PlotMe.cPerms(p, "PlotMe.admin.reset")) { allowed_commands.add("reset"); } if (PlotMe.cPerms(p, "PlotMe.use.add") || PlotMe.cPerms(p, "PlotMe.admin.add")) { allowed_commands.add("add"); } if (PlotMe.cPerms(p, "PlotMe.use.remove") || PlotMe.cPerms(p, "PlotMe.admin.remove")) { allowed_commands.add("remove"); } if (PlotMe.allowToDeny) { if (PlotMe.cPerms(p, "PlotMe.use.deny") || PlotMe.cPerms(p, "PlotMe.admin.deny")) { allowed_commands.add("deny"); } if (PlotMe.cPerms(p, "PlotMe.use.undeny") || PlotMe.cPerms(p, "PlotMe.admin.undeny")) { allowed_commands.add("undeny"); } } if (PlotMe.cPerms(p, "PlotMe.admin.setowner")) { allowed_commands.add("setowner"); } if (PlotMe.cPerms(p, "PlotMe.admin.move")) { allowed_commands.add("move"); } if (PlotMe.cPerms(p, "PlotMe.admin.weanywhere")) { allowed_commands.add("weanywhere"); } if (PlotMe.cPerms(p, "PlotMe.admin.reload")) { allowed_commands.add("reload"); } if (PlotMe.cPerms(p, "PlotMe.admin.list")) { allowed_commands.add("listother"); } if (PlotMe.cPerms(p, "PlotMe.admin.expired")) { allowed_commands.add("expired"); } if (PlotMe.cPerms(p, "PlotMe.admin.addtime")) { allowed_commands.add("addtime"); } if (PlotMe.cPerms(p, "PlotMe.admin.resetexpired")) { allowed_commands.add("resetexpired"); } PlotMapInfo pmi = PlotManager.getMap(p); if (PlotManager.isPlotWorld(p) && ecoon) { if (PlotMe.cPerms(p, "PlotMe.use.buy")) { allowed_commands.add("buy"); } if (PlotMe.cPerms(p, "PlotMe.use.sell")) { allowed_commands.add("sell"); if (pmi.CanSellToBank) { allowed_commands.add("sellbank"); } } if (PlotMe.cPerms(p, "PlotMe.use.auction")) { allowed_commands.add("auction"); } if (PlotMe.cPerms(p, "PlotMe.use.bid")) { allowed_commands.add("bid"); } } maxpage = (int) Math.ceil((double) allowed_commands.size() / max); if (page > maxpage) { page = 1; } p.sendMessage(RED + " ---==" + BLUE + C("HelpTitle") + " " + page + "/" + maxpage + RED + "==--- "); for (int ctr = (page - 1) * max; ctr < (page * max) && ctr < allowed_commands.size(); ctr++) { String allowedcmd = allowed_commands.get(ctr); if (allowedcmd.equalsIgnoreCase("limit")) { if (PlotManager.isPlotWorld(p) || PlotMe.allowWorldTeleport) { World w = null; if (PlotManager.isPlotWorld(p)) { w = p.getWorld(); } else if (PlotMe.allowWorldTeleport) { w = PlotManager.getFirstWorld(); } int maxplots = PlotMe.getPlotLimit(p); int ownedplots = PlotManager.getNbOwnedPlot(p, w); if (maxplots == -1) { p.sendMessage(GREEN + C("HelpYourPlotLimitWorld") + " : " + AQUA + ownedplots + GREEN + " " + C("HelpUsedOf") + " " + AQUA + C("WordInfinite")); } else { p.sendMessage(GREEN + C("HelpYourPlotLimitWorld") + " : " + AQUA + ownedplots + GREEN + " " + C("HelpUsedOf") + " " + AQUA + maxplots); } } else { p.sendMessage(GREEN + C("HelpYourPlotLimitWorld") + " : " + AQUA + C("MsgNotPlotWorld")); } } else if (allowedcmd.equalsIgnoreCase("claim")) { p.sendMessage(GREEN + " /plotme " + C("CommandClaim")); if (ecoon && pmi != null && pmi.ClaimPrice != 0) { p.sendMessage(AQUA + " " + C("HelpClaim") + " " + C("WordPrice") + " : " + RESET + round(pmi.ClaimPrice)); } else { p.sendMessage(AQUA + " " + C("HelpClaim")); } } else if (allowedcmd.equalsIgnoreCase("claim.other")) { p.sendMessage(GREEN + " /plotme " + C("CommandClaim") + " <" + C("WordPlayer") + ">"); if (ecoon && pmi != null && pmi.ClaimPrice != 0) { p.sendMessage(AQUA + " " + C("HelpClaimOther") + " " + C("WordPrice") + " : " + RESET + round(pmi.ClaimPrice)); } else { p.sendMessage(AQUA + " " + C("HelpClaimOther")); } } else if (allowedcmd.equalsIgnoreCase("auto")) { if (PlotMe.allowWorldTeleport) { p.sendMessage(GREEN + " /plotme " + C("CommandAuto") + " [" + C("WordWorld") + "]"); } else { p.sendMessage(GREEN + " /plotme " + C("CommandAuto")); } if (ecoon && pmi != null && pmi.ClaimPrice != 0) { p.sendMessage(AQUA + " " + C("HelpAuto") + " " + C("WordPrice") + " : " + RESET + round(pmi.ClaimPrice)); } else { p.sendMessage(AQUA + " " + C("HelpAuto")); } } else if (allowedcmd.equalsIgnoreCase("home")) { if (PlotMe.allowWorldTeleport) { p.sendMessage(GREEN + " /plotme " + C("CommandHome") + "[:#] [" + C("WordWorld") + "]"); } else { p.sendMessage(GREEN + " /plotme " + C("CommandHome") + "[:#]"); } if (ecoon && pmi != null && pmi.PlotHomePrice != 0) { p.sendMessage(AQUA + " " + C("HelpHome") + " " + C("WordPrice") + " : " + RESET + round(pmi.PlotHomePrice)); } else { p.sendMessage(AQUA + " " + C("HelpHome")); } } else if (allowedcmd.equalsIgnoreCase("home.other")) { if (PlotMe.allowWorldTeleport) { p.sendMessage(GREEN + " /plotme " + C("CommandHome") + "[:#] <" + C("WordPlayer") + "> [" + C("WordWorld") + "]"); } else { p.sendMessage(GREEN + " /plotme " + C("CommandHome") + "[:#] <" + C("WordPlayer") + ">"); } if (ecoon && pmi != null && pmi.PlotHomePrice != 0) { p.sendMessage(AQUA + " " + C("HelpHomeOther") + " " + C("WordPrice") + " : " + RESET + round(pmi.PlotHomePrice)); } else { p.sendMessage(AQUA + " " + C("HelpHomeOther")); } } else if (allowedcmd.equalsIgnoreCase("info")) { p.sendMessage(GREEN + " /plotme " + C("CommandInfo")); p.sendMessage(AQUA + " " + C("HelpInfo")); } else if (allowedcmd.equalsIgnoreCase("comment")) { p.sendMessage(GREEN + " /plotme " + C("CommandComment") + " <" + C("WordComment") + ">"); if (ecoon && pmi != null && pmi.AddCommentPrice != 0) { p.sendMessage(AQUA + " " + C("HelpComment") + " " + C("WordPrice") + " : " + RESET + round(pmi.AddCommentPrice)); } else { p.sendMessage(AQUA + " " + C("HelpComment")); } } else if (allowedcmd.equalsIgnoreCase("comments")) { p.sendMessage(GREEN + " /plotme " + C("CommandComments")); p.sendMessage(AQUA + " " + C("HelpComments")); } else if (allowedcmd.equalsIgnoreCase("list")) { p.sendMessage(GREEN + " /plotme " + C("CommandList")); p.sendMessage(AQUA + " " + C("HelpList")); } else if (allowedcmd.equalsIgnoreCase("listother")) { p.sendMessage(GREEN + " /plotme " + C("CommandList") + " <" + C("WordPlayer") + ">"); p.sendMessage(AQUA + " " + C("HelpListOther")); } else if (allowedcmd.equalsIgnoreCase("biomeinfo")) { p.sendMessage(GREEN + " /plotme " + C("CommandBiome")); p.sendMessage(AQUA + " " + C("HelpBiomeInfo")); } else if (allowedcmd.equalsIgnoreCase("biome")) { p.sendMessage(GREEN + " /plotme " + C("CommandBiome") + " <" + C("WordBiome") + ">"); if (ecoon && pmi != null && pmi.BiomeChangePrice != 0) { p.sendMessage(AQUA + " " + C("HelpBiome") + " " + C("WordPrice") + " : " + RESET + round(pmi.BiomeChangePrice)); } else { p.sendMessage(AQUA + " " + C("HelpBiome")); } } else if (allowedcmd.equalsIgnoreCase("biomelist")) { p.sendMessage(GREEN + " /plotme " + C("CommandBiomelist")); p.sendMessage(AQUA + " " + C("HelpBiomeList")); } else if (allowedcmd.equalsIgnoreCase("done")) { p.sendMessage(GREEN + " /plotme " + C("CommandDone")); p.sendMessage(AQUA + " " + C("HelpDone")); } else if (allowedcmd.equalsIgnoreCase("tp")) { if (PlotMe.allowWorldTeleport) { p.sendMessage(GREEN + " /plotme " + C("CommandTp") + " <" + C("WordId") + "> [" + C("WordWorld") + "]"); } else { p.sendMessage(GREEN + " /plotme " + C("CommandTp") + " <" + C("WordId") + ">"); } p.sendMessage(AQUA + " " + C("HelpTp")); } else if (allowedcmd.equalsIgnoreCase("id")) { p.sendMessage(GREEN + " /plotme " + C("CommandId")); p.sendMessage(AQUA + " " + C("HelpId")); } else if (allowedcmd.equalsIgnoreCase("clear")) { p.sendMessage(GREEN + " /plotme " + C("CommandClear")); if (ecoon && pmi != null && pmi.ClearPrice != 0) { p.sendMessage(AQUA + " " + C("HelpId") + " " + C("WordPrice") + " : " + RESET + round(pmi.ClearPrice)); } else { p.sendMessage(AQUA + " " + C("HelpClear")); } } else if (allowedcmd.equalsIgnoreCase("reset")) { p.sendMessage(GREEN + " /plotme " + C("CommandReset")); p.sendMessage(AQUA + " " + C("HelpReset")); } else if (allowedcmd.equalsIgnoreCase("add")) { p.sendMessage(GREEN + " /plotme " + C("CommandAdd") + " <" + C("WordPlayer") + ">"); if (ecoon && pmi != null && pmi.AddPlayerPrice != 0) { p.sendMessage(AQUA + " " + C("HelpAdd") + " " + C("WordPrice") + " : " + RESET + round(pmi.AddPlayerPrice)); } else { p.sendMessage(AQUA + " " + C("HelpAdd")); } } else if (allowedcmd.equalsIgnoreCase("deny")) { p.sendMessage(GREEN + " /plotme " + C("CommandDeny") + " <" + C("WordPlayer") + ">"); if (ecoon && pmi != null && pmi.DenyPlayerPrice != 0) { p.sendMessage(AQUA + " " + C("HelpDeny") + " " + C("WordPrice") + " : " + RESET + round(pmi.DenyPlayerPrice)); } else { p.sendMessage(AQUA + " " + C("HelpDeny")); } } else if (allowedcmd.equalsIgnoreCase("remove")) { p.sendMessage(GREEN + " /plotme " + C("CommandRemove") + " <" + C("WordPlayer") + ">"); if (ecoon && pmi != null && pmi.RemovePlayerPrice != 0) { p.sendMessage(AQUA + " " + C("HelpRemove") + " " + C("WordPrice") + " : " + RESET + round(pmi.RemovePlayerPrice)); } else { p.sendMessage(AQUA + " " + C("HelpRemove")); } } else if (allowedcmd.equalsIgnoreCase("undeny")) { p.sendMessage(GREEN + " /plotme " + C("CommandUndeny") + " <" + C("WordPlayer") + ">"); if (ecoon && pmi != null && pmi.UndenyPlayerPrice != 0) { p.sendMessage(AQUA + " " + C("HelpUndeny") + " " + C("WordPrice") + " : " + RESET + round(pmi.UndenyPlayerPrice)); } else { p.sendMessage(AQUA + " " + C("HelpUndeny")); } } else if (allowedcmd.equalsIgnoreCase("setowner")) { p.sendMessage(GREEN + " /plotme " + C("CommandSetowner") + " <" + C("WordPlayer") + ">"); p.sendMessage(AQUA + " " + C("HelpSetowner")); } else if (allowedcmd.equalsIgnoreCase("move")) { p.sendMessage(GREEN + " /plotme " + C("CommandMove") + " <" + C("WordIdFrom") + "> <" + C("WordIdTo") + ">"); p.sendMessage(AQUA + " " + C("HelpMove")); } else if (allowedcmd.equalsIgnoreCase("weanywhere")) { p.sendMessage(GREEN + " /plotme " + C("CommandWEAnywhere")); p.sendMessage(AQUA + " " + C("HelpWEAnywhere")); } else if (allowedcmd.equalsIgnoreCase("expired")) { p.sendMessage(GREEN + " /plotme " + C("CommandExpired") + " [page]"); p.sendMessage(AQUA + " " + C("HelpExpired")); } else if (allowedcmd.equalsIgnoreCase("donelist")) { p.sendMessage(GREEN + " /plotme " + C("CommandDoneList") + " [page]"); p.sendMessage(AQUA + " " + C("HelpDoneList")); } else if (allowedcmd.equalsIgnoreCase("addtime")) { p.sendMessage(GREEN + " /plotme " + C("CommandAddtime")); int days = (pmi == null) ? 0 : pmi.DaysToExpiration; if (days == 0) { p.sendMessage(AQUA + " " + C("HelpAddTime1") + " " + RESET + C("WordNever")); } else { p.sendMessage(AQUA + " " + C("HelpAddTime1") + " " + RESET + days + AQUA + " " + C("HelpAddTime2")); } } else if (allowedcmd.equalsIgnoreCase("reload")) { p.sendMessage(GREEN + " /plotme reload"); p.sendMessage(AQUA + " " + C("HelpReload")); } else if (allowedcmd.equalsIgnoreCase("dispose")) { p.sendMessage(GREEN + " /plotme " + C("CommandDispose")); if (ecoon && pmi != null && pmi.DisposePrice != 0) { p.sendMessage(AQUA + " " + C("HelpDispose") + " " + C("WordPrice") + " : " + RESET + round(pmi.DisposePrice)); } else { p.sendMessage(AQUA + " " + C("HelpDispose")); } } else if (allowedcmd.equalsIgnoreCase("buy")) { p.sendMessage(GREEN + " /plotme " + C("CommandBuy")); p.sendMessage(AQUA + " " + C("HelpBuy")); } else if (allowedcmd.equalsIgnoreCase("sell")) { p.sendMessage(GREEN + " /plotme " + C("CommandSell") + " [" + C("WordAmount") + "]"); p.sendMessage(AQUA + " " + C("HelpSell") + " " + C("WordDefault") + " : " + RESET + round(pmi.SellToPlayerPrice)); } else if (allowedcmd.equalsIgnoreCase("sellbank")) { p.sendMessage(GREEN + " /plotme " + C("CommandSellBank")); p.sendMessage(AQUA + " " + C("HelpSellBank") + " " + RESET + round(pmi.SellToBankPrice)); } else if (allowedcmd.equalsIgnoreCase("auction")) { p.sendMessage(GREEN + " /plotme " + C("CommandAuction") + " [" + C("WordAmount") + "]"); p.sendMessage(AQUA + " " + C("HelpAuction") + " " + C("WordDefault") + " : " + RESET + "1"); } else if (allowedcmd.equalsIgnoreCase("resetexpired")) { p.sendMessage(GREEN + " /plotme " + C("CommandResetExpired") + " <" + C("WordWorld") + ">"); p.sendMessage(AQUA + " " + C("HelpResetExpired")); } else if (allowedcmd.equalsIgnoreCase("bid")) { p.sendMessage(GREEN + " /plotme " + C("CommandBid") + " <" + C("WordAmount") + ">"); p.sendMessage(AQUA + " " + C("HelpBid")); } } return true; } private boolean tp(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.admin.tp")) { if (!PlotManager.isPlotWorld(p)) { if (!PlotMe.allowWorldTeleport) { Send(p, RED + C("MsgNotPlotWorld")); } else if (args.length == 2 || (args.length == 3)) { String id = args[1]; if (!PlotManager.isValidId(id)) { Send(p, C("WordUsage") + ": " + RED + "/plotme " + C("CommandTp") + " <" + C("WordId") + "> [" + C("WordWorld") + "] " + RESET + C("WordExample") + ": " + RED + "/plotme " + C("CommandTp") + " 5;-1 "); return true; } else { World w; if (args.length == 3) { String world = args[2]; w = Bukkit.getWorld(world); } else if (!PlotManager.isPlotWorld(p)) { w = PlotManager.getFirstWorld(); } else { w = p.getWorld(); } if (w == null || !PlotManager.isPlotWorld(w)) { Send(p, RED + C("MsgNoPlotworldFound")); } else { Location bottom = PlotManager.getPlotBottomLoc(w, id); Location top = PlotManager.getPlotTopLoc(w, id); p.teleport(new Location(w, bottom.getX() + (top.getBlockX() - bottom.getBlockX()) / 2, PlotManager.getMap(w).RoadHeight + 2, bottom.getZ() - 2)); } } } else { Send(p, C("WordUsage") + ": " + RED + "/plotme " + C("CommandTp") + " <" + C("WordId") + "> [" + C("WordWorld") + "] " + RESET + C("WordExample") + ": " + RED + "/plotme " + C("CommandTp") + " 5;-1 "); } } else if (args.length == 2 || (args.length == 3 && PlotMe.allowWorldTeleport)) { String id = args[1]; if (!PlotManager.isValidId(id)) { if (PlotMe.allowWorldTeleport) { Send(p, C("WordUsage") + ": " + RED + "/plotme " + C("CommandTp") + " <" + C("WordId") + "> [" + C("WordWorld") + "] " + RESET + C("WordExample") + ": " + RED + "/plotme " + C("CommandTp") + " 5;-1 "); } else { Send(p, C("WordUsage") + ": " + RED + "/plotme " + C("CommandTp") + " <" + C("WordId") + "> " + RESET + C("WordExample") + ": " + RED + "/plotme " + C("CommandTp") + " 5;-1 "); } return true; } else { World w; if (args.length == 3) { String world = args[2]; w = Bukkit.getWorld(world); } else if (!PlotManager.isPlotWorld(p)) { w = PlotManager.getFirstWorld(); } else { w = p.getWorld(); } if (w == null || !PlotManager.isPlotWorld(w)) { Send(p, RED + C("MsgNoPlotworldFound")); } else { Location bottom = PlotManager.getPlotBottomLoc(w, id); Location top = PlotManager.getPlotTopLoc(w, id); p.teleport(new Location(w, bottom.getX() + (top.getBlockX() - bottom.getBlockX()) / 2, PlotManager.getMap(w).RoadHeight + 2, bottom.getZ() - 2)); } } } else if (PlotMe.allowWorldTeleport) { Send(p, C("WordUsage") + ": " + RED + "/plotme " + C("CommandTp") + " <" + C("WordId") + "> [" + C("WordWorld") + "] " + RESET + C("WordExample") + ": " + RED + "/plotme " + C("CommandTp") + " 5;-1 "); } else { Send(p, C("WordUsage") + ": " + RED + "/plotme " + C("CommandTp") + " <" + C("WordId") + "> " + RESET + C("WordExample") + ": " + RED + "/plotme " + C("CommandTp") + " 5;-1 "); } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean auto(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.use.auto")) { if (!PlotManager.isPlotWorld(p)) { if (!PlotMe.allowWorldTeleport) { Send(p, RED + C("MsgNotPlotWorld")); } else { World w; if (!PlotManager.isPlotWorld(p)) { if (args.length == 2) { w = Bukkit.getWorld(args[1]); } else { w = PlotManager.getFirstWorld(); } if (w == null || !PlotManager.isPlotWorld(w)) { Send(p, RED + args[1] + " " + C("MsgWorldNotPlot")); return true; } } else { w = p.getWorld(); } if (w == null) { Send(p, RED + C("MsgNoPlotworldFound")); } else if (PlotManager.getNbOwnedPlot(p, w) >= PlotMe.getPlotLimit(p) && !PlotMe.cPerms(p, "PlotMe.admin")) { Send(p, RED + C("MsgAlreadyReachedMaxPlots") + " (" + PlotManager.getNbOwnedPlot(p, w) + "/" + PlotMe.getPlotLimit(p) + "). " + C("WordUse") + " " + "/plotme " + C("CommandHome") + " " + C("MsgToGetToIt")); } else { PlotMapInfo pmi = PlotManager.getMap(w); int limit = pmi.PlotAutoLimit; for (int i = 0; i < limit; i++) { for (int x = -i; x <= i; x++) { for (int z = -i; z <= i; z++) { String id = "" + x + ";" + z; if (PlotManager.isPlotAvailable(id, w)) { String name = p.getName(); UUID uuid = p.getUniqueId(); double price = 0; if (PlotManager.isEconomyEnabled(w)) { price = pmi.ClaimPrice; double balance = PlotMe.economy.getBalance(p); if (balance >= price) { EconomyResponse er = PlotMe.economy.withdrawPlayer(p, price); if (!er.transactionSuccess()) { Send(p, RED + er.errorMessage); warn(er.errorMessage); return true; } } else { Send(p, RED + C("MsgNotEnoughAuto") + " " + C("WordMissing") + " " + RESET + f(price - balance, false)); return true; } } Plot plot = PlotManager.createPlot(w, id, name, uuid); //PlotManager.adjustLinkedPlots(id, w); p.teleport(new Location(w, PlotManager.bottomX(plot.id, w) + (PlotManager.topX(plot.id, w) - PlotManager.bottomX(plot.id, w)) / 2, pmi.RoadHeight + 2, PlotManager.bottomZ(plot.id, w) - 2)); Send(p, C("MsgThisPlotYours") + " " + C("WordUse") + " " + RED + "/plotme " + C("CommandHome") + RESET + " " + C("MsgToGetToIt") + " " + f(-price)); if (isAdv) { PlotMe.logger.info(LOG + name + " " + C("MsgClaimedPlot") + " " + id + ((price != 0) ? " " + C("WordFor") + " " + price : "")); } return true; } } } } Send(p, RED + C("MsgNoPlotFound1") + " " + (limit ^ 2) + " " + C("MsgNoPlotFound2")); } } } else { World w; if (!PlotManager.isPlotWorld(p)) { if (PlotMe.allowWorldTeleport) { if (args.length == 2) { w = Bukkit.getWorld(args[1]); } else { w = PlotManager.getFirstWorld(); } if (w == null || !PlotManager.isPlotWorld(w)) { Send(p, RED + args[1] + " " + C("MsgWorldNotPlot")); return true; } } else { w = p.getWorld(); } } else { w = p.getWorld(); } if (w == null) { Send(p, RED + C("MsgNoPlotworldFound")); } else if (PlotManager.getNbOwnedPlot(p, w) >= PlotMe.getPlotLimit(p) && !PlotMe.cPerms(p, "PlotMe.admin")) { Send(p, RED + C("MsgAlreadyReachedMaxPlots") + " (" + PlotManager.getNbOwnedPlot(p, w) + "/" + PlotMe.getPlotLimit(p) + "). " + C("WordUse") + " " + "/plotme " + C("CommandHome") + " " + C("MsgToGetToIt")); } else { PlotMapInfo pmi = PlotManager.getMap(w); int limit = pmi.PlotAutoLimit; for (int i = 0; i < limit; i++) { for (int x = -i; x <= i; x++) { for (int z = -i; z <= i; z++) { String id = "" + x + ";" + z; if (PlotManager.isPlotAvailable(id, w)) { String name = p.getName(); UUID uuid = p.getUniqueId(); double price = 0; if (PlotManager.isEconomyEnabled(w)) { price = pmi.ClaimPrice; double balance = PlotMe.economy.getBalance(p); if (balance >= price) { EconomyResponse er = PlotMe.economy.withdrawPlayer(p, price); if (!er.transactionSuccess()) { Send(p, RED + er.errorMessage); warn(er.errorMessage); return true; } } else { Send(p, RED + C("MsgNotEnoughAuto") + " " + C("WordMissing") + " " + RESET + f(price - balance, false)); return true; } } Plot plot = PlotManager.createPlot(w, id, name, uuid); //PlotManager.adjustLinkedPlots(id, w); p.teleport(new Location(w, PlotManager.bottomX(plot.id, w) + (PlotManager.topX(plot.id, w) - PlotManager.bottomX(plot.id, w)) / 2, pmi.RoadHeight + 2, PlotManager.bottomZ(plot.id, w) - 2)); Send(p, C("MsgThisPlotYours") + " " + C("WordUse") + " " + RED + "/plotme " + C("CommandHome") + RESET + " " + C("MsgToGetToIt") + " " + f(-price)); if (isAdv) { PlotMe.logger.info(LOG + name + " " + C("MsgClaimedPlot") + " " + id + ((price != 0) ? " " + C("WordFor") + " " + price : "")); } return true; } } } } Send(p, RED + C("MsgNoPlotFound1") + " " + (limit ^ 2) + " " + C("MsgNoPlotFound2")); } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean claim(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.use.claim") || PlotMe.cPerms(p, "PlotMe.admin.claim.other")) { if (!PlotManager.isPlotWorld(p)) { Send(p, RED + C("MsgNotPlotWorld")); } else { String id = PlotManager.getPlotId(p.getLocation()); if (id.equals("")) { Send(p, RED + C("MsgCannotClaimRoad")); } else if (!PlotManager.isPlotAvailable(id, p)) { Send(p, RED + C("MsgThisPlotOwned")); } else { String playername = p.getName(); UUID uuid = p.getUniqueId(); if (args.length == 2) { if (PlotMe.cPerms(p, "PlotMe.admin.claim.other")) { playername = args[1]; uuid = null; } } int plotlimit = PlotMe.getPlotLimit(p); if (playername.equals(p.getName()) && plotlimit != -1 && PlotManager.getNbOwnedPlot(p) >= plotlimit) { Send(p, RED + C("MsgAlreadyReachedMaxPlots") + " (" + PlotManager.getNbOwnedPlot(p) + "/" + PlotMe.getPlotLimit(p) + "). " + C("WordUse") + " " + RED + "/plotme " + C("CommandHome") + RESET + " " + C("MsgToGetToIt")); } else { World w = p.getWorld(); PlotMapInfo pmi = PlotManager.getMap(w); double price = 0; if (PlotManager.isEconomyEnabled(w)) { price = pmi.ClaimPrice; double balance = PlotMe.economy.getBalance(p); if (balance >= price) { EconomyResponse er = PlotMe.economy.withdrawPlayer(p, price); if (!er.transactionSuccess()) { Send(p, RED + er.errorMessage); warn(er.errorMessage); return true; } } else { Send(p, RED + C("MsgNotEnoughBuy") + " " + C("WordMissing") + " " + RESET + (price - balance) + RED + " " + PlotMe.economy.currencyNamePlural()); return true; } } Plot plot = PlotManager.createPlot(w, id, playername, uuid); //PlotManager.adjustLinkedPlots(id, w); if (plot == null) { Send(p, RED + C("ErrCreatingPlotAt") + " " + id); } else { if (playername.equalsIgnoreCase(p.getName())) { Send(p, C("MsgThisPlotYours") + " " + C("WordUse") + " " + RED + "/plotme " + C("CommandHome") + RESET + " " + C("MsgToGetToIt") + " " + f(-price)); } else { Send(p, C("MsgThisPlotIsNow") + " " + playername + C("WordPossessive") + ". " + C("WordUse") + " " + RED + "/plotme " + C("CommandHome") + RESET + " " + C("MsgToGetToIt") + " " + f(-price)); } if (isAdv) { PlotMe.logger.info(LOG + playername + " " + C("MsgClaimedPlot") + " " + id + ((price != 0) ? " " + C("WordFor") + " " + price : "")); } } } } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean home(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.use.home") || PlotMe.cPerms(p, "PlotMe.admin.home.other")) { if (!PlotManager.isPlotWorld(p)) { if (!PlotMe.allowWorldTeleport) { Send(p, RED + C("MsgNotPlotWorld")); } else { String playername = p.getName(); UUID uuid = p.getUniqueId(); int nb = 1; World w; String worldname = ""; if (!PlotManager.isPlotWorld(p)) { w = PlotManager.getFirstWorld(); } else { w = p.getWorld(); } if (w != null) { worldname = w.getName(); } if (args[0].contains(":")) { try { if (args[0].split(":").length == 1 || args[0].split(":")[1].equals("")) { Send(p, C("WordUsage") + ": " + RED + "/plotme " + C("CommandHome") + ":# " + RESET + C("WordExample") + ": " + RED + "/plotme " + C("CommandHome") + ":1"); return true; } else { nb = Integer.parseInt(args[0].split(":")[1]); } } catch (NumberFormatException ex) { Send(p, C("WordUsage") + ": " + RED + "/plotme " + C("CommandHome") + ":# " + RESET + C("WordExample") + ": " + RED + "/plotme " + C("CommandHome") + ":1"); return true; } } if (args.length == 2) { if (Bukkit.getWorld(args[1]) == null) { if (PlotMe.cPerms(p, "PlotMe.admin.home.other")) { playername = args[1]; uuid = null; } } else { w = Bukkit.getWorld(args[1]); worldname = args[1]; } } if (args.length == 3) { if (Bukkit.getWorld(args[2]) == null) { Send(p, RED + args[2] + " " + C("MsgWorldNotPlot")); return true; } else { w = Bukkit.getWorld(args[2]); worldname = args[2]; } } if (!PlotManager.isPlotWorld(w)) { Send(p, RED + worldname + " " + C("MsgWorldNotPlot")); } else { int i = nb - 1; for (Plot plot : PlotManager.getPlots(w).values()) { if (uuid == null && plot.owner.equalsIgnoreCase(playername) || uuid != null && plot.ownerId != null && plot.ownerId.equals(uuid)) { if (i == 0) { PlotMapInfo pmi = PlotManager.getMap(w); double price = 0; if (PlotManager.isEconomyEnabled(w)) { price = pmi.PlotHomePrice; double balance = PlotMe.economy.getBalance(p); if (balance >= price) { EconomyResponse er = PlotMe.economy.withdrawPlayer(p, price); if (!er.transactionSuccess()) { Send(p, RED + er.errorMessage); return true; } } else { Send(p, RED + C("MsgNotEnoughTp") + " " + C("WordMissing") + " " + RESET + f(price - balance, false)); return true; } } p.teleport(PlotManager.getPlotHome(w, plot)); if (price != 0) { Send(p, f(-price)); } return true; } else { i--; } } } if (nb > 0) { if (!playername.equalsIgnoreCase(p.getName())) { Send(p, RED + playername + " " + C("MsgDoesNotHavePlot") + " #" + nb); } else { Send(p, RED + C("MsgPlotNotFound") + " #" + nb); } } else if (!playername.equalsIgnoreCase(p.getName())) { Send(p, RED + playername + " " + C("MsgDoesNotHavePlot")); } else { Send(p, RED + C("MsgYouHaveNoPlot")); } } } } else { String playername = p.getName(); UUID uuid = p.getUniqueId(); int nb = 1; World w; String worldname = ""; if (!PlotManager.isPlotWorld(p) && PlotMe.allowWorldTeleport) { w = PlotManager.getFirstWorld(); } else { w = p.getWorld(); } if (w != null) { worldname = w.getName(); } if (args[0].contains(":")) { try { if (args[0].split(":").length == 1 || args[0].split(":")[1].equals("")) { Send(p, C("WordUsage") + ": " + RED + "/plotme " + C("CommandHome") + ":# " + RESET + C("WordExample") + ": " + RED + "/plotme " + C("CommandHome") + ":1"); return true; } else { nb = Integer.parseInt(args[0].split(":")[1]); } } catch (Exception ex) { Send(p, C("WordUsage") + ": " + RED + "/plotme " + C("CommandHome") + ":# " + RESET + C("WordExample") + ": " + RED + "/plotme " + C("CommandHome") + ":1"); return true; } } if (args.length == 2) { if (Bukkit.getWorld(args[1]) == null) { if (PlotMe.cPerms(p, "PlotMe.admin.home.other")) { playername = args[1]; uuid = null; } } else { w = Bukkit.getWorld(args[1]); worldname = args[1]; } } if (args.length == 3) { if (Bukkit.getWorld(args[2]) == null) { Send(p, RED + args[2] + " " + C("MsgWorldNotPlot")); return true; } else { w = Bukkit.getWorld(args[2]); worldname = args[2]; } } if (!PlotManager.isPlotWorld(w)) { Send(p, RED + worldname + " " + C("MsgWorldNotPlot")); } else { int i = nb - 1; for (Plot plot : PlotManager.getPlots(w).values()) { if (uuid == null && plot.owner.equalsIgnoreCase(playername) || uuid != null && plot.ownerId != null && plot.ownerId.equals(uuid)) { if (i == 0) { PlotMapInfo pmi = PlotManager.getMap(w); double price = 0; if (PlotManager.isEconomyEnabled(w)) { price = pmi.PlotHomePrice; double balance = PlotMe.economy.getBalance(p); if (balance >= price) { EconomyResponse er = PlotMe.economy.withdrawPlayer(p, price); if (!er.transactionSuccess()) { Send(p, RED + er.errorMessage); return true; } } else { Send(p, RED + C("MsgNotEnoughTp") + " " + C("WordMissing") + " " + RESET + f(price - balance, false)); return true; } } p.teleport(PlotManager.getPlotHome(w, plot)); if (price != 0) { Send(p, f(-price)); } return true; } else { i--; } } } if (nb > 0) { if (!playername.equalsIgnoreCase(p.getName())) { Send(p, RED + playername + " " + C("MsgDoesNotHavePlot") + " #" + nb); } else { Send(p, RED + C("MsgPlotNotFound") + " #" + nb); } } else if (!playername.equalsIgnoreCase(p.getName())) { Send(p, RED + playername + " " + C("MsgDoesNotHavePlot")); } else { Send(p, RED + C("MsgYouHaveNoPlot")); } } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean info(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.use.info")) { if (!PlotManager.isPlotWorld(p)) { Send(p, RED + C("MsgNotPlotWorld")); } else { String id = PlotManager.getPlotId(p.getLocation()); if (id.equals("")) { Send(p, RED + C("MsgNoPlotFound")); } else if (!PlotManager.isPlotAvailable(id, p)) { Plot plot = PlotManager.getPlotById(p, id); p.sendMessage(GREEN + C("InfoId") + ": " + AQUA + id + GREEN + " " + C("InfoOwner") + ": " + AQUA + plot.owner + GREEN + " " + C("InfoBiome") + ": " + AQUA + FormatBiome(plot.biome.name())); p.sendMessage(GREEN + C("InfoExpire") + ": " + AQUA + ((plot.expireddate == null) ? C("WordNever") : plot.expireddate.toString()) + GREEN + " " + C("InfoFinished") + ": " + AQUA + ((plot.finished) ? C("WordYes") : C("WordNo")) + GREEN + " " + C("InfoProtected") + ": " + AQUA + ((plot.protect) ? C("WordYes") : C("WordNo"))); if (plot.allowedcount() > 0) { p.sendMessage(GREEN + C("InfoHelpers") + ": " + AQUA + plot.getAllowed()); } if (PlotMe.allowToDeny && plot.deniedcount() > 0) { p.sendMessage(GREEN + C("InfoDenied") + ": " + AQUA + plot.getDenied()); } if (PlotManager.isEconomyEnabled(p)) { if (plot.currentbidder == null || plot.currentbidder.equalsIgnoreCase("")) { p.sendMessage(GREEN + C("InfoAuctionned") + ": " + AQUA + ((plot.auctionned) ? C("WordYes") + GREEN + " " + C("InfoMinimumBid") + ": " + AQUA + round(plot.currentbid) : C("WordNo")) + GREEN + " " + C("InfoForSale") + ": " + AQUA + ((plot.forsale) ? AQUA + round(plot.customprice) : C("WordNo"))); } else { p.sendMessage(GREEN + C("InfoAuctionned") + ": " + AQUA + ((plot.auctionned) ? C("WordYes") + GREEN + " " + C("InfoBidder") + ": " + AQUA + plot.currentbidder + GREEN + " " + C("InfoBid") + ": " + AQUA + round(plot.currentbid) : C("WordNo")) + GREEN + " " + C("InfoForSale") + ": " + AQUA + ((plot.forsale) ? AQUA + round(plot.customprice) : C("WordNo"))); } } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgHasNoOwner")); } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean comment(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.use.comment")) { if (!PlotManager.isPlotWorld(p)) { Send(p, RED + C("MsgNotPlotWorld")); } else if (args.length < 2) { Send(p, C("WordUsage") + ": " + RED + "/plotme " + C("CommandComment") + " <" + C("WordText") + ">"); } else { String id = PlotManager.getPlotId(p.getLocation()); if (id.equals("")) { Send(p, RED + C("MsgNoPlotFound")); } else if (!PlotManager.isPlotAvailable(id, p)) { World w = p.getWorld(); PlotMapInfo pmi = PlotManager.getMap(w); String playername = p.getName(); UUID uuid = p.getUniqueId(); double price = 0; if (PlotManager.isEconomyEnabled(w)) { price = pmi.AddCommentPrice; double balance = PlotMe.economy.getBalance(p); if (balance >= price) { EconomyResponse er = PlotMe.economy.withdrawPlayer(p, price); if (!er.transactionSuccess()) { Send(p, RED + er.errorMessage); warn(er.errorMessage); return true; } } else { Send(p, RED + C("MsgNotEnoughComment") + " " + C("WordMissing") + " " + RESET + f(price - balance, false)); return true; } } Plot plot = PlotManager.getPlotById(p, id); String text = StringUtils.join(args, " "); text = text.substring(text.indexOf(" ")); String[] comment = new String[3]; comment[0] = playername; comment[1] = text; comment[2] = uuid.toString(); plot.comments.add(comment); SqlManager.addPlotComment(comment, plot.comments.size(), PlotManager.getIdX(id), PlotManager.getIdZ(id), plot.world, uuid); Send(p, C("MsgCommentAdded") + " " + f(-price)); if (isAdv) { PlotMe.logger.info(LOG + playername + " " + C("MsgCommentedPlot") + " " + id + ((price != 0) ? " " + C("WordFor") + " " + price : "")); } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgHasNoOwner")); } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean comments(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.use.comments")) { if (!PlotManager.isPlotWorld(p)) { Send(p, RED + C("MsgNotPlotWorld")); } else if (args.length < 2) { String id = PlotManager.getPlotId(p.getLocation()); if (id.equals("")) { Send(p, RED + C("MsgNoPlotFound")); } else if (!PlotManager.isPlotAvailable(id, p)) { Plot plot = PlotManager.getPlotById(p, id); if (plot.ownerId.equals(p.getUniqueId()) || plot.isAllowed(p.getUniqueId()) || PlotMe.cPerms(p, "PlotMe.admin")) { if (plot.comments.size() == 0) { Send(p, C("MsgNoComments")); } else { Send(p, C("MsgYouHave") + " " + BLUE + plot.comments.size() + RESET + " " + C("MsgComments")); for (String[] comment : plot.comments) { p.sendMessage(ChatColor.BLUE + C("WordFrom") + " : " + RED + comment[0]); p.sendMessage("" + RESET + ChatColor.ITALIC + comment[1]); } } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgNotYoursNotAllowedViewComments")); } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgHasNoOwner")); } } } else { p.sendMessage(BLUE + PREFIX + RED + C("MsgPermissionDenied")); } return true; } private boolean biome(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.use.biome")) { if (!PlotManager.isPlotWorld(p)) { Send(p, RED + C("MsgNotPlotWorld")); } else { String id = PlotManager.getPlotId(p.getLocation()); if (id.equals("")) { p.sendMessage(BLUE + PREFIX + RED + C("MsgNoPlotFound")); } else if (!PlotManager.isPlotAvailable(id, p)) { World w = p.getWorld(); if (args.length == 2) { Biome biome = null; for (Biome bio : Biome.values()) { if (bio.name().equalsIgnoreCase(args[1])) { biome = bio; } } if (biome == null) { Send(p, RED + args[1] + RESET + " " + C("MsgIsInvalidBiome")); } else { Plot plot = PlotManager.getPlotById(p, id); String playername = p.getName(); if (plot.owner.equalsIgnoreCase(playername) || PlotMe.cPerms(p, "PlotMe.admin")) { PlotMapInfo pmi = PlotManager.getMap(w); double price = 0; if (PlotManager.isEconomyEnabled(w)) { price = pmi.BiomeChangePrice; double balance = PlotMe.economy.getBalance(p); if (balance >= price) { EconomyResponse er = PlotMe.economy.withdrawPlayer(p, price); if (!er.transactionSuccess()) { Send(p, RED + er.errorMessage); warn(er.errorMessage); return true; } } else { Send(p, RED + C("MsgNotEnoughBiome") + " " + C("WordMissing") + " " + RESET + f(price - balance, false)); return true; } } PlotManager.setBiome(w, id, plot, biome); Send(p, C("MsgBiomeSet") + " " + ChatColor.BLUE + FormatBiome(biome.name()) + " " + f(-price)); if (isAdv) { PlotMe.logger.info(LOG + playername + " " + C("MsgChangedBiome") + " " + id + " " + C("WordTo") + " " + FormatBiome(biome.name()) + ((price != 0) ? " " + C("WordFor") + " " + price : "")); } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgNotYoursNotAllowedBiome")); } } } else { Plot plot = PlotMe.plotmaps.get(w.getName().toLowerCase()).plots.get(id); Send(p, C("MsgPlotUsingBiome") + " " + ChatColor.BLUE + FormatBiome(plot.biome.name())); } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgHasNoOwner")); } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean biomelist(Player player, String[] args) { if (PlotMe.cPerms(player, "PlotMe.use.biome")) { Send(player, C("WordBiomes") + " : "); //int i = 0; StringBuilder line = new StringBuilder(); List<String> biomes = new ArrayList<>(); for (Biome b : Biome.values()) { biomes.add(b.name()); } Collections.sort(biomes); List<String> column1 = new ArrayList<>(); List<String> column2 = new ArrayList<>(); List<String> column3 = new ArrayList<>(); for (int ctr = 0; ctr < biomes.size(); ctr++) { if (ctr < biomes.size() / 3) { column1.add(biomes.get(ctr)); } else if (ctr < biomes.size() * 2 / 3) { column2.add(biomes.get(ctr)); } else { column3.add(biomes.get(ctr)); } } for (int ctr = 0; ctr < column1.size(); ctr++) { String b; int nameLength; b = FormatBiome(column1.get(ctr)); nameLength = MinecraftFontWidthCalculator.getStringWidth(b); line.append(b).append(whitespace(432 - nameLength)); if (ctr < column2.size()) { b = FormatBiome(column2.get(ctr)); nameLength = MinecraftFontWidthCalculator.getStringWidth(b); line.append(b).append(whitespace(432 - nameLength)); } if (ctr < column3.size()) { b = FormatBiome(column3.get(ctr)); line.append(b); } player.sendMessage("" + BLUE + line); //i = 0; line = new StringBuilder(); /*int nameLength = MinecraftFontWidthCalculator.getStringWidth(b); i += 1; if(i == 3) { line.append(b); player.sendMessage("" + BLUE + line); i = 0; line = new StringBuilder(); } else { line.append(b).append(whitespace(318 - nameLength)); }*/ } } else { Send(player, RED + C("MsgPermissionDenied")); } return true; } private boolean reset(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.admin.reset")) { if (!PlotManager.isPlotWorld(p)) { Send(p, RED + C("MsgNotPlotWorld")); } else { Plot plot = PlotManager.getPlotById(p.getLocation()); if (plot == null) { Send(p, RED + C("MsgNoPlotFound")); } else if (plot.protect) { Send(p, RED + C("MsgPlotProtectedCannotReset")); } else { String id = plot.id; World w = p.getWorld(); PlotManager.setBiome(w, id, plot, Biome.PLAINS); PlotManager.clear(w, plot); //RemoveLWC(w, plot); if (PlotManager.isEconomyEnabled(p)) { if (plot.auctionned) { String currentbidder = plot.currentbidder; if (!currentbidder.equals("")) { OfflinePlayer playercurrentbidder = Bukkit.getOfflinePlayer(plot.currentbidderId); EconomyResponse er = PlotMe.economy.depositPlayer(playercurrentbidder, plot.currentbid); if (!er.transactionSuccess()) { Send(p, er.errorMessage); warn(er.errorMessage); } else { for (Player player : Bukkit.getServer().getOnlinePlayers()) { if (player.getName().equalsIgnoreCase(currentbidder)) { Send(player, C("WordPlot") + " " + id + " " + C("MsgOwnedBy") + " " + plot.owner + " " + C("MsgWasReset") + " " + f(plot.currentbid)); break; } } } } } PlotMapInfo pmi = PlotManager.getMap(p); if (pmi.RefundClaimPriceOnReset) { OfflinePlayer playerowner = Bukkit.getOfflinePlayer(plot.ownerId); EconomyResponse er = PlotMe.economy.depositPlayer(playerowner, pmi.ClaimPrice); if (!er.transactionSuccess()) { Send(p, RED + er.errorMessage); warn(er.errorMessage); return true; } else { for (Player player : Bukkit.getServer().getOnlinePlayers()) { if (player.getName().equalsIgnoreCase(plot.owner)) { Send(player, C("WordPlot") + " " + id + " " + C("MsgOwnedBy") + " " + plot.owner + " " + C("MsgWasReset") + " " + f(pmi.ClaimPrice)); break; } } } } } if (!PlotManager.isPlotAvailable(id, p)) { PlotManager.getPlots(p).remove(id); } String name = p.getName(); PlotManager.removeOwnerSign(w, id); PlotManager.removeSellSign(w, id); SqlManager.deletePlot(PlotManager.getIdX(id), PlotManager.getIdZ(id), w.getName().toLowerCase()); Send(p, C("MsgPlotReset")); if (isAdv) { PlotMe.logger.info(LOG + name + " " + C("MsgResetPlot") + " " + id); } } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean clear(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.admin.clear") || PlotMe.cPerms(p, "PlotMe.use.clear")) { if (!PlotManager.isPlotWorld(p)) { Send(p, RED + C("MsgNotPlotWorld")); } else { String id = PlotManager.getPlotId(p.getLocation()); if (id.equals("")) { Send(p, RED + C("MsgNoPlotFound")); } else if (!PlotManager.isPlotAvailable(id, p)) { Plot plot = PlotManager.getPlotById(p, id); if (plot.protect) { Send(p, RED + C("MsgPlotProtectedCannotClear")); } else { String playername = p.getName(); if (plot.owner.equalsIgnoreCase(playername) || PlotMe.cPerms(p, "PlotMe.admin.clear")) { World w = p.getWorld(); PlotMapInfo pmi = PlotManager.getMap(w); double price = 0; if (PlotManager.isEconomyEnabled(w)) { price = pmi.ClearPrice; double balance = PlotMe.economy.getBalance(p); if (balance >= price) { EconomyResponse er = PlotMe.economy.withdrawPlayer(p, price); if (!er.transactionSuccess()) { Send(p, RED + er.errorMessage); warn(er.errorMessage); return true; } } else { Send(p, RED + C("MsgNotEnoughClear") + " " + C("WordMissing") + " " + RESET + (price - balance) + RED + " " + PlotMe.economy.currencyNamePlural()); return true; } } PlotManager.clear(w, plot); //RemoveLWC(w, plot, p); //PlotManager.regen(w, plot); Send(p, C("MsgPlotCleared") + " " + f(-price)); if (isAdv) { PlotMe.logger.info(LOG + playername + " " + C("MsgClearedPlot") + " " + id + ((price != 0) ? " " + C("WordFor") + " " + price : "")); } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgNotYoursNotAllowedClear")); } } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgHasNoOwner")); } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean add(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.admin.add") || PlotMe.cPerms(p, "PlotMe.use.add")) { if (!PlotManager.isPlotWorld(p)) { Send(p, RED + C("MsgNotPlotWorld")); } else { String id = PlotManager.getPlotId(p.getLocation()); if (id.equals("")) { Send(p, RED + C("MsgNoPlotFound")); } else if (!PlotManager.isPlotAvailable(id, p)) { if (args.length < 2 || args[1].equalsIgnoreCase("")) { Send(p, C("WordUsage") + " " + RED + "/plotme " + C("CommandAdd") + " <" + C("WordPlayer") + ">"); } else { Plot plot = PlotManager.getPlotById(p, id); String playername = p.getName(); String allowed = args[1]; if (plot.owner.equalsIgnoreCase(playername) || PlotMe.cPerms(p, "PlotMe.admin.add")) { if (plot.isAllowedConsulting(allowed) || plot.isGroupAllowed(allowed)) { Send(p, C("WordPlayer") + " " + RED + args[1] + RESET + " " + C("MsgAlreadyAllowed")); } else { World w = p.getWorld(); PlotMapInfo pmi = PlotManager.getMap(w); double price = 0; if (PlotManager.isEconomyEnabled(w)) { price = pmi.AddPlayerPrice; double balance = PlotMe.economy.getBalance(p); if (balance >= price) { EconomyResponse er = PlotMe.economy.withdrawPlayer(p, price); if (!er.transactionSuccess()) { Send(p, RED + er.errorMessage); warn(er.errorMessage); return true; } } else { Send(p, RED + C("MsgNotEnoughAdd") + " " + C("WordMissing") + " " + RESET + f(price - balance, false)); return true; } } plot.addAllowed(allowed); plot.removeDenied(allowed); Send(p, C("WordPlayer") + " " + RED + allowed + RESET + " " + C("MsgNowAllowed") + " " + f(-price)); if (isAdv) { PlotMe.logger.info(LOG + playername + " " + C("MsgAddedPlayer") + " " + allowed + " " + C("MsgToPlot") + " " + id + ((price != 0) ? " " + C("WordFor") + " " + price : "")); } } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgNotYoursNotAllowedAdd")); } } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgHasNoOwner")); } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean deny(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.admin.deny") || PlotMe.cPerms(p, "PlotMe.use.deny")) { if (!PlotManager.isPlotWorld(p)) { Send(p, RED + C("MsgNotPlotWorld")); } else { String id = PlotManager.getPlotId(p.getLocation()); if (id.equals("")) { Send(p, RED + C("MsgNoPlotFound")); } else if (!PlotManager.isPlotAvailable(id, p)) { if (args.length < 2 || args[1].equalsIgnoreCase("")) { Send(p, C("WordUsage") + " " + RED + "/plotme " + C("CommandDeny") + " <" + C("WordPlayer") + ">"); } else { Plot plot = PlotManager.getPlotById(p, id); String playername = p.getName(); String denied = args[1]; if (plot.owner.equalsIgnoreCase(playername) || PlotMe.cPerms(p, "PlotMe.admin.deny")) { if (plot.isDeniedConsulting(denied) || plot.isGroupDenied(denied)) { Send(p, C("WordPlayer") + " " + RED + args[1] + RESET + " " + C("MsgAlreadyDenied")); } else { World w = p.getWorld(); PlotMapInfo pmi = PlotManager.getMap(w); double price = 0; if (PlotManager.isEconomyEnabled(w)) { price = pmi.DenyPlayerPrice; double balance = PlotMe.economy.getBalance(p); if (balance >= price) { EconomyResponse er = PlotMe.economy.withdrawPlayer(p, price); if (!er.transactionSuccess()) { Send(p, RED + er.errorMessage); warn(er.errorMessage); return true; } } else { Send(p, RED + C("MsgNotEnoughDeny") + " " + C("WordMissing") + " " + RESET + f(price - balance, false)); return true; } } plot.addDenied(denied); plot.removeAllowed(denied); if (denied.equals("*")) { List<Player> deniedplayers = PlotManager.getPlayersInPlot(w, id); for (Player deniedplayer : deniedplayers) { if (!plot.isAllowed(deniedplayer.getUniqueId())) { deniedplayer.teleport(PlotManager.getPlotHome(w, plot)); } } } else { @SuppressWarnings("deprecation") Player deniedplayer = Bukkit.getPlayerExact(denied); if (deniedplayer != null) { if (deniedplayer.getWorld().equals(w)) { String deniedid = PlotManager.getPlotId(deniedplayer); if (deniedid.equalsIgnoreCase(id)) { deniedplayer.teleport(PlotManager.getPlotHome(w, plot)); } } } } Send(p, C("WordPlayer") + " " + RED + denied + RESET + " " + C("MsgNowDenied") + " " + f(-price)); if (isAdv) { PlotMe.logger.info(LOG + playername + " " + C("MsgDeniedPlayer") + " " + denied + " " + C("MsgToPlot") + " " + id + ((price != 0) ? " " + C("WordFor") + " " + price : "")); } } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgNotYoursNotAllowedDeny")); } } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgHasNoOwner")); } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean remove(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.admin.remove") || PlotMe.cPerms(p, "PlotMe.use.remove")) { if (!PlotManager.isPlotWorld(p)) { Send(p, RED + C("MsgNotPlotWorld")); } else { String id = PlotManager.getPlotId(p.getLocation()); if (id.equals("")) { Send(p, RED + C("MsgNoPlotFound")); } else if (!PlotManager.isPlotAvailable(id, p)) { if (args.length < 2 || args[1].equalsIgnoreCase("")) { Send(p, C("WordUsage") + ": " + RED + "/plotme " + C("CommandRemove") + " <" + C("WordPlayer") + ">"); } else { Plot plot = PlotManager.getPlotById(p, id); UUID playeruuid = p.getUniqueId(); String allowed = args[1]; if (plot.ownerId.equals(playeruuid) || PlotMe.cPerms(p, "PlotMe.admin.remove")) { if (plot.isAllowedConsulting(allowed) || plot.isGroupAllowed(allowed)) { World w = p.getWorld(); PlotMapInfo pmi = PlotManager.getMap(w); double price = 0; if (PlotManager.isEconomyEnabled(w)) { price = pmi.RemovePlayerPrice; double balance = PlotMe.economy.getBalance(p); if (balance >= price) { EconomyResponse er = PlotMe.economy.withdrawPlayer(p, price); if (!er.transactionSuccess()) { Send(p, RED + er.errorMessage); warn(er.errorMessage); return true; } } else { Send(p, RED + C("MsgNotEnoughRemove") + " " + C("WordMissing") + " " + RESET + f(price - balance, false)); return true; } } if (allowed.startsWith("group:")) { plot.removeAllowedGroup(allowed); } else { plot.removeAllowed(allowed); } Send(p, C("WordPlayer") + " " + RED + allowed + RESET + " " + C("WordRemoved") + ". " + f(-price)); if (isAdv) { PlotMe.logger.info(LOG + p.getName() + " " + C("MsgRemovedPlayer") + " " + allowed + " " + C("MsgFromPlot") + " " + id + ((price != 0) ? " " + C("WordFor") + " " + price : "")); } } else { Send(p, C("WordPlayer") + " " + RED + args[1] + RESET + " " + C("MsgWasNotAllowed")); } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgNotYoursNotAllowedRemove")); } } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgHasNoOwner")); } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean undeny(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.admin.undeny") || PlotMe.cPerms(p, "PlotMe.use.undeny")) { if (!PlotManager.isPlotWorld(p)) { Send(p, RED + C("MsgNotPlotWorld")); } else { String id = PlotManager.getPlotId(p.getLocation()); if (id.equals("")) { Send(p, RED + C("MsgNoPlotFound")); } else if (!PlotManager.isPlotAvailable(id, p)) { if (args.length < 2 || args[1].equalsIgnoreCase("")) { Send(p, C("WordUsage") + ": " + RED + "/plotme " + C("CommandUndeny") + " <" + C("WordPlayer") + ">"); } else { Plot plot = PlotManager.getPlotById(p, id); String playername = p.getName(); UUID playeruuid = p.getUniqueId(); String denied = args[1]; if (plot.ownerId.equals(playeruuid) || PlotMe.cPerms(p, "PlotMe.admin.undeny")) { if (plot.isDeniedConsulting(denied) || plot.isGroupDenied(denied)) { World w = p.getWorld(); PlotMapInfo pmi = PlotManager.getMap(w); double price = 0; if (PlotManager.isEconomyEnabled(w)) { price = pmi.UndenyPlayerPrice; double balance = PlotMe.economy.getBalance(p); if (balance >= price) { EconomyResponse er = PlotMe.economy.withdrawPlayer(p, price); if (!er.transactionSuccess()) { Send(p, RED + er.errorMessage); warn(er.errorMessage); return true; } } else { Send(p, RED + C("MsgNotEnoughUndeny") + " " + C("WordMissing") + " " + RESET + f(price - balance, false)); return true; } } if (denied.startsWith("group:")) { plot.removeDeniedGroup(denied); } else { plot.removeDenied(denied); } Send(p, C("WordPlayer") + " " + RED + denied + RESET + " " + C("MsgNowUndenied") + " " + f(-price)); if (isAdv) { PlotMe.logger.info(LOG + playername + " " + C("MsgUndeniedPlayer") + " " + denied + " " + C("MsgFromPlot") + " " + id + ((price != 0) ? " " + C("WordFor") + " " + price : "")); } } else { Send(p, C("WordPlayer") + " " + RED + args[1] + RESET + " " + C("MsgWasNotDenied")); } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgNotYoursNotAllowedUndeny")); } } } else { Send(p, RED + C("MsgThisPlot") + "(" + id + ") " + C("MsgHasNoOwner")); } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean setowner(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.admin.setowner")) { if (!PlotManager.isPlotWorld(p)) { Send(p, RED + C("MsgNotPlotWorld")); } else { String id = PlotManager.getPlotId(p.getLocation()); if (id.equals("")) { Send(p, RED + C("MsgNoPlotFound")); } else if (args.length < 2 || args[1].equals("")) { Send(p, C("WordUsage") + ": " + RED + "/plotme " + C("CommandSetowner") + " <" + C("WordPlayer") + ">"); } else { String newowner = args[1]; String oldowner = "<" + C("WordNotApplicable") + ">"; String playername = p.getName(); if (!PlotManager.isPlotAvailable(id, p)) { Plot plot = PlotManager.getPlotById(p, id); PlotMapInfo pmi = PlotManager.getMap(p); oldowner = plot.owner; OfflinePlayer playeroldowner = Bukkit.getOfflinePlayer(plot.ownerId); if (PlotManager.isEconomyEnabled(p)) { if (pmi.RefundClaimPriceOnSetOwner && newowner != oldowner) { EconomyResponse er = PlotMe.economy.depositPlayer(playeroldowner, pmi.ClaimPrice); if (!er.transactionSuccess()) { Send(p, RED + er.errorMessage); warn(er.errorMessage); return true; } else { for (Player player : Bukkit.getServer().getOnlinePlayers()) { if (player.getName().equalsIgnoreCase(oldowner)) { Send(player, C("MsgYourPlot") + " " + id + " " + C("MsgNowOwnedBy") + " " + newowner + ". " + f(pmi.ClaimPrice)); break; } } } } if (plot.currentbidder != null && !plot.currentbidder.equals("")) { OfflinePlayer playercurrentbidder = Bukkit.getOfflinePlayer(plot.currentbidderId); EconomyResponse er = PlotMe.economy.depositPlayer(playercurrentbidder, plot.currentbid); if (!er.transactionSuccess()) { Send(p, er.errorMessage); warn(er.errorMessage); } else { for (Player player : Bukkit.getServer().getOnlinePlayers()) { if (player.getName().equalsIgnoreCase(plot.currentbidder)) { Send(player, C("WordPlot") + " " + id + " " + C("MsgChangedOwnerFrom") + " " + oldowner + " " + C("WordTo") + " " + newowner + ". " + f(plot.currentbid)); break; } } } } } plot.currentbidder = ""; plot.currentbidderId = null; plot.currentbid = 0; plot.auctionned = false; plot.forsale = false; PlotManager.setSellSign(p.getWorld(), plot); plot.updateField("currentbidder", ""); plot.updateField("currentbid", 0); plot.updateField("auctionned", false); plot.updateField("forsale", false); plot.updateField("currentbidderid", null); plot.owner = newowner; PlotManager.setOwnerSign(p.getWorld(), plot); plot.updateField("owner", newowner); } else { PlotManager.createPlot(p.getWorld(), id, newowner, null); } Send(p, C("MsgOwnerChangedTo") + " " + RED + newowner); if (isAdv) { PlotMe.logger.info(LOG + playername + " " + C("MsgChangedOwnerOf") + " " + id + " " + C("WordFrom") + " " + oldowner + " " + C("WordTo") + " " + newowner); } } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean id(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.admin.id")) { if (!PlotManager.isPlotWorld(p)) { Send(p, RED + C("MsgNotPlotWorld")); } else { String plotid = PlotManager.getPlotId(p.getLocation()); if (plotid.equals("")) { Send(p, RED + C("MsgNoPlotFound")); } else { p.sendMessage(BLUE + C("WordPlot") + " " + C("WordId") + ": " + RESET + plotid); Location bottom = PlotManager.getPlotBottomLoc(p.getWorld(), plotid); Location top = PlotManager.getPlotTopLoc(p.getWorld(), plotid); p.sendMessage(BLUE + C("WordBottom") + ": " + RESET + bottom.getBlockX() + ChatColor.BLUE + "," + RESET + bottom.getBlockZ()); p.sendMessage(BLUE + C("WordTop") + ": " + RESET + top.getBlockX() + ChatColor.BLUE + "," + RESET + top.getBlockZ()); } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean move(Player p, String[] args) { if (PlotMe.cPerms(p, "PlotMe.admin.move")) { if (!PlotManager.isPlotWorld(p)) { Send(p, RED + C("MsgNotPlotWorld")); } else if (args.length < 3 || args[1].equalsIgnoreCase("") || args[2].equalsIgnoreCase("")) { Send(p, C("WordUsage") + ": " + RED + "/plotme " + C("CommandMove") + " <" + C("WordIdFrom") + "> <" + C("WordIdTo") + "> " + RESET + C("WordExample") + ": " + RED + "/plotme " + C("CommandMove") + " 0;1 2;-1"); } else { String plot1 = args[1]; String plot2 = args[2]; if (!PlotManager.isValidId(plot1) || !PlotManager.isValidId(plot2)) { Send(p, C("WordUsage") + ": " + RED + "/plotme " + C("CommandMove") + " <" + C("WordIdFrom") + "> <" + C("WordIdTo") + "> " + RESET + C("WordExample") + ": " + RED + "/plotme " + C("CommandMove") + " 0;1 2;-1"); return true; } else if (PlotManager.movePlot(p.getWorld(), plot1, plot2)) { Send(p, C("MsgPlotMovedSuccess")); if (isAdv) { PlotMe.logger.info(LOG + p.getName() + " " + C("MsgExchangedPlot") + " " + plot1 + " " + C("MsgAndPlot") + " " + plot2); } } else { Send(p, RED + C("ErrMovingPlot")); } } } else { Send(p, RED + C("MsgPermissionDenied")); } return true; } private boolean reload(CommandSender s, String[] args) { if (!(s instanceof Player) || PlotMe.cPerms(s, "PlotMe.admin.reload")) { plugin.initialize(); Send(s, C("MsgReloadedSuccess")); if (isAdv) { PlotMe.logger.info(LOG + s.getName() + " " + C("MsgReloadedConfigurations")); } } else { Send(s, RED + C("MsgPermissionDenied")); } return true; } private StringBuilder whitespace(int length) { int spaceWidth = MinecraftFontWidthCalculator.getStringWidth(" "); StringBuilder ret = new StringBuilder(); for (int i = 0; (i + spaceWidth) < length; i += spaceWidth) { ret.append(" "); } return ret; } private String round(double money) { return (money % 1 == 0) ? "" + Math.round(money) : "" + money; } private void warn(String msg) { PlotMe.logger.warning(LOG + msg); } private String f(double price) { return f(price, true); } private String f(double price, boolean showsign) { if (price == 0) { return ""; } String format = round(Math.abs(price)); if (PlotMe.economy != null) { format = (price <= 1 && price >= -1) ? format + " " + PlotMe.economy.currencyNameSingular() : format + " " + PlotMe.economy.currencyNamePlural(); } if (showsign) { return GREEN + ((price > 0) ? "+" + format : "-" + format); } else { return GREEN + format; } } private void Send(CommandSender cs, String text) { cs.sendMessage(PREFIX + text); } private String FormatBiome(String biome) { biome = biome.toLowerCase(); String[] tokens = biome.split("_"); biome = ""; for (String token : tokens) { token = token.substring(0, 1).toUpperCase() + token.substring(1); if (biome.equalsIgnoreCase("")) { biome = token; } else { biome = biome + "_" + token; } } return biome; } }
Frostcast/PlotMe
src/com/worldcretornica/plotme/PMCommand.java
213,266
package com.worldcretornica.plotme_core.commands; import com.worldcretornica.plotme_core.PermissionNames; import com.worldcretornica.plotme_core.Plot; import com.worldcretornica.plotme_core.PlotId; import com.worldcretornica.plotme_core.PlotMapInfo; import com.worldcretornica.plotme_core.PlotMe_Core; import com.worldcretornica.plotme_core.api.IPlayer; import com.worldcretornica.plotme_core.api.IWorld; import com.worldcretornica.plotme_core.api.event.InternalPlotAddDeniedEvent; import net.milkbowl.vault.economy.EconomyResponse; import java.util.List; public class CmdDeny extends PlotCommand { public CmdDeny(PlotMe_Core instance) { super(instance); } public boolean exec(IPlayer player, String[] args) { if (player.hasPermission(PermissionNames.ADMIN_DENY) || player.hasPermission(PermissionNames.USER_DENY)) { IWorld world = player.getWorld(); PlotMapInfo pmi = manager.getMap(world); if (manager.isPlotWorld(world)) { PlotId id = manager.getPlotId(player); if (id == null) { player.sendMessage("§c" + C("MsgNoPlotFound")); } else if (!manager.isPlotAvailable(id, pmi)) { if (args.length < 2 || args[1].isEmpty()) { player.sendMessage(C("WordUsage") + " §c/plotme deny <" + C("WordPlayer") + ">"); } else { Plot plot = manager.getPlotById(id, pmi); String denied = args[1]; if (player.getUniqueId().equals(plot.getOwnerId()) || player.hasPermission(PermissionNames.ADMIN_DENY)) { if (plot.getOwner().equalsIgnoreCase(denied)) { player.sendMessage(C("MsgCannotDenyOwner")); return true; } if (plot.isDeniedConsulting(denied) || plot.isGroupDenied(denied)) { player.sendMessage(C("WordPlayer") + " §c" + args[1] + "§r " + C("MsgAlreadyDenied")); } else { double price = 0.0; InternalPlotAddDeniedEvent event; if (manager.isEconomyEnabled(pmi)) { price = pmi.getDenyPlayerPrice(); double balance = serverBridge.getBalance(player); if (balance >= price) { event = serverBridge.getEventFactory().callPlotAddDeniedEvent(plugin, world, plot, player, denied); if (event.isCancelled()) { return true; } else { EconomyResponse er = serverBridge.withdrawPlayer(player, price); if (!er.transactionSuccess()) { player.sendMessage("§c" + er.errorMessage); serverBridge.getLogger().warning(er.errorMessage); return true; } } } else { player.sendMessage("§c" + C("MsgNotEnoughDeny") + " " + C("WordMissing") + " §r" + Util() .moneyFormat(price - balance, false)); return true; } } else { event = serverBridge.getEventFactory().callPlotAddDeniedEvent(plugin, world, plot, player, denied); } if (!event.isCancelled()) { plot.addDenied(denied); plot.removeAllowed(denied); if ("*".equals(denied)) { List<IPlayer> playersInPlot = manager.getPlayersInPlot(world, id); for (IPlayer iPlayer : playersInPlot) { if (!plot.isAllowed(iPlayer.getName(), iPlayer.getUniqueId())) { iPlayer.setLocation(manager.getPlotHome(world, plot.getId())); } } } else { IPlayer deniedPlayer = serverBridge.getPlayerExact(denied); if (deniedPlayer != null) { if (deniedPlayer.getWorld().equals(world)) { PlotId plotId = manager.getPlotId(deniedPlayer); if (plotId.equals(id)) { deniedPlayer.setLocation(manager.getPlotHome(world, plot.getId())); } } } } player.sendMessage( C("WordPlayer") + " §c" + denied + "§r " + C("MsgNowDenied") + " " + Util().moneyFormat(-price, true)); if (isAdvancedLogging()) { if (price == 0) { serverBridge.getLogger() .info(player.getName() + " " + C("MsgDeniedPlayer") + " " + denied + " " + C("MsgToPlot") + " " + id); } else { serverBridge.getLogger() .info(player.getName() + " " + C("MsgDeniedPlayer") + " " + denied + " " + C("MsgToPlot") + " " + id + (" " + C("WordFor") + " " + price)); } } } } } else { player.sendMessage("§c" + C("MsgThisPlot") + "(" + id + ") " + C("MsgNotYoursNotAllowedDeny")); } } } else { player.sendMessage("§c" + C("MsgThisPlot") + "(" + id + ") " + C("MsgHasNoOwner")); } } else { player.sendMessage("§c" + C("MsgNotPlotWorld")); } } else { player.sendMessage("§c" + C("MsgPermissionDenied")); return false; } return true; } }
Maescool/PlotMe-Core
src/main/java/com/worldcretornica/plotme_core/commands/CmdDeny.java
213,267
404: Not Found
skmedix/LittleTiles
src/main/java/com/creativemd/littletiles/LittleTilesConfig.java
213,268
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.document.json; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.io.JsonStringEncoder; import com.google.common.base.Joiner; import com.yahoo.collections.Tuple2; import com.yahoo.document.ArrayDataType; import com.yahoo.document.DataType; import com.yahoo.document.Document; import com.yahoo.document.DocumentId; import com.yahoo.document.DocumentOperation; import com.yahoo.document.DocumentPut; import com.yahoo.document.DocumentRemove; import com.yahoo.document.DocumentType; import com.yahoo.document.DocumentTypeManager; import com.yahoo.document.DocumentUpdate; import com.yahoo.document.Field; import com.yahoo.document.MapDataType; import com.yahoo.document.PositionDataType; import com.yahoo.document.StructDataType; import com.yahoo.document.TensorDataType; import com.yahoo.document.WeightedSetDataType; import com.yahoo.document.datatypes.Array; import com.yahoo.document.datatypes.BoolFieldValue; import com.yahoo.document.datatypes.FieldValue; import com.yahoo.document.datatypes.IntegerFieldValue; import com.yahoo.document.datatypes.MapFieldValue; import com.yahoo.document.datatypes.Raw; import com.yahoo.document.datatypes.StringFieldValue; import com.yahoo.document.datatypes.Struct; import com.yahoo.document.datatypes.TensorFieldValue; import com.yahoo.document.datatypes.WeightedSet; import com.yahoo.document.internal.GeoPosType; import com.yahoo.document.json.readers.DocumentParseInfo; import com.yahoo.document.json.readers.VespaJsonDocumentReader; import com.yahoo.document.serialization.DocumentSerializer; import com.yahoo.document.serialization.DocumentSerializerFactory; import com.yahoo.document.update.AddValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate.Operator; import com.yahoo.document.update.AssignValueUpdate; import com.yahoo.document.update.ClearValueUpdate; import com.yahoo.document.update.FieldUpdate; import com.yahoo.document.update.MapValueUpdate; import com.yahoo.document.update.TensorAddUpdate; import com.yahoo.document.update.TensorModifyUpdate; import com.yahoo.document.update.TensorRemoveUpdate; import com.yahoo.document.update.ValueUpdate; import com.yahoo.io.GrowableByteBuffer; import com.yahoo.tensor.IndexedTensor; import com.yahoo.tensor.MappedTensor; import com.yahoo.tensor.MixedTensor; import com.yahoo.tensor.Tensor; import com.yahoo.tensor.TensorType; import com.yahoo.text.Utf8; import com.yahoo.yolean.Exceptions; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DECREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DIVIDE; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_INCREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_MULTIPLY; import static com.yahoo.test.json.JsonTestHelper.inputJson; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Basic test of JSON streams to Vespa document instances. * * @author Steinar Knutsen * @author bratseth */ public class JsonReaderTestCase { private DocumentTypeManager types; private JsonFactory parserFactory; @Before public void setUp() throws Exception { parserFactory = new JsonFactory(); types = new DocumentTypeManager(); { DocumentType x = new DocumentType("smoke"); x.addField(new Field("something", DataType.STRING)); x.addField(new Field("nalle", DataType.STRING)); x.addField(new Field("field1", DataType.STRING)); x.addField(new Field("field2", DataType.STRING)); x.addField(new Field("int1", DataType.INT)); x.addField(new Field("flag", DataType.BOOL)); x.addField(new Field("tensor1", DataType.getTensor(TensorType.fromSpec("tensor(x{})")))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("mirrors"); StructDataType woo = new StructDataType("woo"); woo.addField(new Field("sandra", DataType.STRING)); woo.addField(new Field("cloud", DataType.STRING)); x.addField(new Field("skuggsjaa", woo)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testarray"); DataType d = new ArrayDataType(DataType.STRING); x.addField(new Field("actualarray", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testset"); DataType d = new WeightedSetDataType(DataType.STRING, true, true); x.addField(new Field("actualset", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testmap"); DataType d = new MapDataType(DataType.STRING, DataType.STRING); x.addField(new Field("actualmap", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testraw"); DataType d = DataType.RAW; x.addField(new Field("actualraw", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testMapStringToArrayOfInt"); DataType value = new ArrayDataType(DataType.INT); DataType d = new MapDataType(DataType.STRING, value); x.addField(new Field("actualMapStringToArrayOfInt", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testArrayOfArrayOfInt"); DataType inner = new ArrayDataType(DataType.INT); DataType outer = new ArrayDataType(inner); x.addField(new Field("arrayOfArrayOfInt", outer)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testsinglepos"); DataType d = PositionDataType.INSTANCE; x.addField(new Field("singlepos", d)); x.addField(new Field("geopos", new GeoPosType(8))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testtensor"); x.addField(new Field("sparse_single_dimension_tensor", new TensorDataType(new TensorType.Builder().mapped("x").build()))); x.addField(new Field("sparse_tensor", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").build()))); x.addField(new Field("dense_tensor", new TensorDataType(new TensorType.Builder().indexed("x", 2).indexed("y", 3).build()))); x.addField(new Field("dense_int8_tensor", new TensorDataType(TensorType.fromSpec("tensor<int8>(x[2],y[3])")))); x.addField(new Field("dense_unbound_tensor", new TensorDataType(new TensorType.Builder().indexed("x").indexed("y").build()))); x.addField(new Field("mixed_tensor", new TensorDataType(new TensorType.Builder().mapped("x").indexed("y", 3).build()))); x.addField(new Field("mixed_bfloat16_tensor", new TensorDataType(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")))); x.addField(new Field("mixed_tensor_adv", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").mapped("z").indexed("a", 3).build()))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testpredicate"); x.addField(new Field("boolean", DataType.PREDICATE)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testint"); x.addField(new Field("integerfield", DataType.INT)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testnull"); x.addField(new Field("intfield", DataType.INT)); x.addField(new Field("stringfield", DataType.STRING)); x.addField(new Field("arrayfield", new ArrayDataType(DataType.STRING))); x.addField(new Field("weightedsetfield", new WeightedSetDataType(DataType.STRING, true, true))); x.addField(new Field("mapfield", new MapDataType(DataType.STRING, DataType.STRING))); x.addField(new Field("tensorfield", new TensorDataType(new TensorType.Builder().indexed("x").build()))); types.registerDocumentType(x); } } @After public void tearDown() throws Exception { types = null; parserFactory = null; } private JsonReader createReader(String jsonInput) { InputStream input = new ByteArrayInputStream(Utf8.toBytes(jsonInput)); return new JsonReader(types, input, parserFactory); } @Test public void readDocumentWithMissingFieldsField() { assertEquals("document is missing the required \"fields\" field", assertThrows(IllegalArgumentException.class, () -> createReader("{ }").readSingleDocumentStreaming(DocumentOperationType.PUT, "id:unittest:testnull::whee")) .getMessage()); } @Test public void readSingleDocumentsPutStreaming() throws IOException { String json = """ { "remove": "id:unittest:smoke::ignored", "ignored-extra-array": [{ "foo": null }, { }], "ignored-extra-object": { "foo": [null, { }], "bar": { } }, "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" }, "id": "id:unittest:smoke::ignored", "create": false, "condition": "true" } """; ParsedDocumentOperation operation = createReader(json).readSingleDocumentStreaming(DocumentOperationType.PUT,"id:unittest:smoke::doc1"); DocumentPut put = ((DocumentPut) operation.operation()); assertFalse(put.getCreateIfNonExistent()); assertEquals("true", put.getCondition().getSelection()); smokeTestDoc(put.getDocument()); } @Test public void readSingleDocumentsUpdateStreaming() throws IOException { String json = """ { "remove": "id:unittest:smoke::ignored", "ignored-extra-array": [{ "foo": null }, { }], "ignored-extra-object": { "foo": [null, { }], "bar": { } }, "fields": { "something": { "assign": "smoketest" }, "flag": { "assign": true }, "nalle": { "assign": "bamse" } }, "id": "id:unittest:smoke::ignored", "create": true, "condition": "false" } """; ParsedDocumentOperation operation = createReader(json).readSingleDocumentStreaming(DocumentOperationType.UPDATE,"id:unittest:smoke::doc1"); Document doc = new Document(types.getDocumentType("smoke"), new DocumentId("id:unittest:smoke::doc1")); DocumentUpdate update = ((DocumentUpdate) operation.operation()); update.applyTo(doc); smokeTestDoc(doc); assertTrue(update.getCreateIfNonExistent()); assertEquals("false", update.getCondition().getSelection()); } @Test public void readSingleDocumentPut() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:smoke::doc1", "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" } } """); smokeTestDoc(doc); } @Test public final void readSingleDocumentUpdate() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:smoke::whee", "fields": { "something": { "assign": "orOther" } } } """); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof AssignValueUpdate); assertEquals(new StringFieldValue("orOther"), f.getValueUpdate(0).getValue()); } @Test public void readClearField() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:smoke::whee", "fields": { "int1": { "assign": null } } } """); FieldUpdate f = doc.getFieldUpdate("int1"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof ClearValueUpdate); assertNull(f.getValueUpdate(0).getValue()); } @Test public void smokeTest() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:smoke::doc1", "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" } } """); smokeTestDoc(doc); } @Test public void docIdLookaheadTest() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:smoke::doc1", "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" } } """); smokeTestDoc(doc); } @Test public void emptyDocTest() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:smoke::whee", "fields": { } }"""); assertEquals(new Document(types.getDocumentType("smoke"), new DocumentId("id:unittest:smoke::whee")), doc); } @Test public void testStruct() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:mirrors::whee", "fields": { "skuggsjaa": { "sandra": "person", "cloud": "another person" } } } """); FieldValue f = doc.getFieldValue(doc.getField("skuggsjaa")); assertSame(Struct.class, f.getClass()); Struct s = (Struct) f; assertEquals("person", ((StringFieldValue) s.getFieldValue("sandra")).getString()); } private DocumentUpdate parseUpdate(String json) throws IOException { InputStream rawDoc = new ByteArrayInputStream(Utf8.toBytes(json)); JsonReader r = new JsonReader(types, rawDoc, parserFactory); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentUpdate update = new DocumentUpdate(docType, parseInfo.documentId); new VespaJsonDocumentReader(false).readUpdate(parseInfo.fieldsBuffer, update); return update; } @Test public void testStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(""" { "update": "id:unittest:mirrors:g=test:whee", "create": true, "fields": { "skuggsjaa": { "assign": { "sandra": "person", "cloud": "another person" } } } } """); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(2, s.getFieldCount()); assertEquals(new StringFieldValue("person"), s.getFieldValue(s.getField("sandra"))); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(107, buf.position()); } @Test public final void testEmptyStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(""" { "update": "id:unittest:mirrors:g=test:whee", "create": true, "fields": { "skuggsjaa": { "assign": { } } } } """); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(0, s.getFieldCount()); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(69, buf.position()); } @Test public void testUpdateArray() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testarray::whee", "fields": { "actualarray": { "add": [ "person", "another person" ] } } } """); checkSimpleArrayAdd(doc); } @Test public void testUpdateWeighted() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testset::whee", "fields": { "actualset": { "add": { "person": 37, "another person": 41 } } } } """); Map<String, Integer> weights = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; final String s = ((StringFieldValue) adder.getValue()).getString(); weights.put(s, adder.getWeight()); } assertEquals(2, weights.size()); final String o = "person"; final String o2 = "another person"; assertTrue(weights.containsKey(o)); assertTrue(weights.containsKey(o2)); assertEquals(Integer.valueOf(37), weights.get(o)); assertEquals(Integer.valueOf(41), weights.get(o2)); } @Test public void testUpdateMatch() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testset::whee", "fields": { "actualset": { "match": { "element": "person", "increment": 13 } } } } """); DocumentUpdate otherDoc = parseUpdate(""" { "update": "id:unittest:testset::whee", "fields": { "actualset": { "match": { "increment": 13, "element": "person" } } } }"""); assertEquals(doc, otherDoc); Map<String, Tuple2<Number, String>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); String op = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperator().toString(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()).getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertEquals("ADD", matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } @SuppressWarnings({ "cast", "unchecked", "rawtypes" }) @Test public void testArithmeticOperators() throws IOException { Tuple2[] operations = new Tuple2[] { new Tuple2<>(UPDATE_DECREMENT, ArithmeticValueUpdate.Operator.SUB), new Tuple2<>(UPDATE_DIVIDE, ArithmeticValueUpdate.Operator.DIV), new Tuple2<>(UPDATE_INCREMENT, ArithmeticValueUpdate.Operator.ADD), new Tuple2<>(UPDATE_MULTIPLY, ArithmeticValueUpdate.Operator.MUL) }; for (Tuple2<String, Operator> operator : operations) { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testset::whee", "fields": { "actualset": { "match": { "element": "person", "%s": 13 } } } } """.formatted(operator.first)); Map<String, Tuple2<Number, Operator>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); Operator op = ((ArithmeticValueUpdate) adder .getUpdate()).getOperator(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertSame(operator.second, matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } } @SuppressWarnings("rawtypes") @Test public void testArrayIndexing() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testarray::whee", "fields": { "actualarray": { "match": { "element": 3, "assign": "nalle" } } } } """); Map<Number, String> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualarray"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final Number key = ((IntegerFieldValue) adder.getValue()) .getNumber(); String op = ((StringFieldValue) adder.getUpdate() .getValue()).getString(); matches.put(key, op); } assertEquals(1, matches.size()); Number n = Integer.valueOf(3); assertEquals("nalle", matches.get(n)); } @Test public void testDocumentRemove() { JsonReader r = createReader(inputJson("{'remove': 'id:unittest:smoke::whee'}")); DocumentType docType = r.readDocumentType(new DocumentId("id:unittest:smoke::whee")); assertEquals("smoke", docType.getName()); } private Document docFromJson(String json) throws IOException { JsonReader r = createReader(json); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); return put.getDocument(); } @Test public void testWeightedSet() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testset::whee", "fields": { "actualset": { "nalle": 2, "tralle": 7 } } } """); FieldValue f = doc.getFieldValue(doc.getField("actualset")); assertSame(WeightedSet.class, f.getClass()); WeightedSet<?> w = (WeightedSet<?>) f; assertEquals(2, w.size()); assertEquals(Integer.valueOf(2), w.get(new StringFieldValue("nalle"))); assertEquals(Integer.valueOf(7), w.get(new StringFieldValue("tralle"))); } @Test public void testArray() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testarray::whee", "fields": { "actualarray": [ "nalle", "tralle" ] } } """); FieldValue f = doc.getFieldValue(doc.getField("actualarray")); assertSame(Array.class, f.getClass()); Array<?> a = (Array<?>) f; assertEquals(2, a.size()); assertEquals(new StringFieldValue("nalle"), a.get(0)); assertEquals(new StringFieldValue("tralle"), a.get(1)); } @Test public void testMap() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testmap::whee", "fields": { "actualmap": { "nalle": "kalle", "tralle": "skalle" } } } """); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testOldMap() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testmap::whee", "fields": { "actualmap": [ { "key": "nalle", "value": "kalle" }, { "key": "tralle", "value": "skalle" } ] } } """); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testPositionPositive() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "singlepos": "N63.429722;E10.393333" } } """); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionOld() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "singlepos": { "x": 10393333, "y": 63429722 } } } """); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testGeoPosition() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "singlepos": { "lat": 63.429722, "lng": 10.393333 } } } """); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testGeoPositionNoAbbreviations() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "singlepos": { "latitude": 63.429722, "longitude": 10.393333 } } } """); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionGeoPos() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "geopos": "N63.429722;E10.393333" } } """); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); } @Test public void testPositionOldGeoPos() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "geopos": { "x": 10393333, "y": 63429722 } } } """); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); } @Test public void testGeoPositionGeoPos() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "geopos": { "lat": 63.429722, "lng": 10.393333 } } } """); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); assertEquals(PositionDataType.INSTANCE, f.getDataType()); } @Test public void testPositionNegative() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "singlepos": "W46.63;S23.55" } } """); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(-46630000, PositionDataType.getXValue(f).getInteger()); assertEquals(-23550000, PositionDataType.getYValue(f).getInteger()); } @Test public void testRaw() throws IOException { String base64 = new String(new JsonStringEncoder().quoteAsString( Base64.getEncoder().withoutPadding().encodeToString(Utf8.toBytes("smoketest")))); String s = fieldStringFromBase64RawContent(base64); assertEquals("smoketest", s); } @Test public void can_read_legacy_chunked_base64_raw_field_encoding() throws IOException { String expected = "this is a string with an impressive length. it's long enough to reach the end of the line, wow!"; String base64withDelims = "dGhpcyBpcyBhIHN0cmluZyB3aXRoIGFuIGltcHJlc3NpdmUgbGVuZ3RoLiBpdCdzIGxvbmcgZW5v\\r\\n" + "dWdoIHRvIHJlYWNoIHRoZSBlbmQgb2YgdGhlIGxpbmUsIHdvdyE=\\r\\n"; assertEquals(expected, fieldStringFromBase64RawContent(base64withDelims)); } private String fieldStringFromBase64RawContent(String base64data) throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testraw::whee", "fields": { "actualraw": "%s" } } """.formatted(base64data)); FieldValue f = doc.getFieldValue(doc.getField("actualraw")); assertSame(Raw.class, f.getClass()); Raw s = (Raw) f; return Utf8.toString(s.getByteBuffer()); } @Test public void testMapStringToArrayOfInt() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt": { "bamse": [1, 2, 3] } } } """); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldMapStringToArrayOfInt() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt": [ { "key": "bamse", "value": [1, 2, 3] } ] } } """); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToString() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:smoke::whee", "fields": { "something": { "assign": "orOther" } } } """); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); AssignValueUpdate a = (AssignValueUpdate) f.getValueUpdate(0); assertEquals(new StringFieldValue("orOther"), a.getValue()); } @Test public void testNestedArrayMatch() throws IOException { DocumentUpdate nested = parseUpdate(""" { "update": "id:unittest:testArrayOfArrayOfInt::whee", "fields": { "arrayOfArrayOfInt": { "match": { "element": 1, "match": { "element": 2, "assign": 3 } } } } } """); DocumentUpdate equivalent = parseUpdate(""" { "update": "id:unittest:testArrayOfArrayOfInt::whee", "fields": { "arrayOfArrayOfInt": { "match": { "match": { "assign": 3, "element": 2 }, "element": 1 } } } } """); assertEquals(nested, equivalent); assertEquals(1, nested.fieldUpdates().size()); FieldUpdate fu = nested.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); MapValueUpdate mvu = (MapValueUpdate) fu.getValueUpdate(0); assertEquals(new IntegerFieldValue(1), mvu.getValue()); MapValueUpdate nvu = (MapValueUpdate) mvu.getUpdate(); assertEquals(new IntegerFieldValue(2), nvu.getValue()); AssignValueUpdate avu = (AssignValueUpdate) nvu.getUpdate(); assertEquals(new IntegerFieldValue(3), avu.getValue()); Document doc = docFromJson(""" { "put": "id:unittest:testArrayOfArrayOfInt::whee", "fields": { "arrayOfArrayOfInt": [ [1, 2, 3], [4, 5, 6] ] } } """); nested.applyTo(doc); Document expected = docFromJson(""" { "put": "id:unittest:testArrayOfArrayOfInt::whee", "fields": { "arrayOfArrayOfInt": [ [1, 2, 3], [4, 5, 3] ] } } """); assertEquals(expected, doc); } @Test public void testMatchCannotUpdateNestedFields() { // Should this work? It doesn't. assertEquals("Field type Map<string,Array<int>> not supported.", assertThrows(UnsupportedOperationException.class, () -> parseUpdate(""" { "update": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt": { "match": { "element": "bamse", "match": { "element": 1, "assign": 4 } } } } } """)).getMessage()); } @Test public void testMatchCannotAssignToNestedMap() { // Unsupported value type for map value assign. assertEquals("Field type Map<string,Array<int>> not supported.", assertThrows(UnsupportedOperationException.class, () -> parseUpdate(""" { "update": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt": { "match": { "element": "bamse", "assign": [1, 3, 4] } } } } """)).getMessage()); } @Test public void testMatchCannotAssignToMap() { // Unsupported value type for map value assign. assertEquals("Field type Map<string,string> not supported.", assertThrows(UnsupportedOperationException.class, () -> parseUpdate(""" { "update": "id:unittest:testmap::whee", "fields": { "actualmap": { "match": { "element": "bamse", "assign": "bar" } } } } """)).getMessage()); } @Test public void testAssignInsideArrayInMap() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt": { "bamse": [1, 2, 3] } } }"""); assertEquals(2, ((MapFieldValue<StringFieldValue, Array<IntegerFieldValue>>) doc.getFieldValue("actualMapStringToArrayOfInt")) .get(StringFieldValue.getFactory().create("bamse")).get(1).getInteger()); DocumentUpdate update = parseUpdate(""" { "update": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt{bamse}[1]": { "assign": 4 } } } """); assertEquals(1, update.fieldPathUpdates().size()); update.applyTo(doc); assertEquals(4, ((MapFieldValue<StringFieldValue, Array<IntegerFieldValue>>) doc.getFieldValue("actualMapStringToArrayOfInt")) .get(StringFieldValue.getFactory().create("bamse")).get(1).getInteger()); } @Test public void testAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt": { "assign": { "bamse": [1, 2, 3] } } } } """); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt": { "assign": [ { "key": "bamse", "value": [1, 2, 3] } ] } } } """); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToWeightedSet() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testset::whee", "fields": { "actualset": { "assign": { "person": 37, "another person": 41 } } } } """); FieldUpdate x = doc.getFieldUpdate("actualset"); assertEquals(1, x.size()); AssignValueUpdate assign = (AssignValueUpdate) x.getValueUpdate(0); WeightedSet<?> w = (WeightedSet<?>) assign.getValue(); assertEquals(2, w.size()); assertEquals(Integer.valueOf(37), w.get(new StringFieldValue("person"))); assertEquals(Integer.valueOf(41), w.get(new StringFieldValue("another person"))); } @Test public void testCompleteFeed() { JsonReader r = createReader(""" [ { "put": "id:unittest:smoke::whee", "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" } }, { "update": "id:unittest:testarray::whee", "fields": { "actualarray": { "add": [ "person", "another person" ] } } }, { "remove": "id:unittest:smoke::whee" } ] """); controlBasicFeed(r); } @Test public void testCompleteFeedWithCreateAndCondition() { JsonReader r = createReader(""" [ { "put": "id:unittest:smoke::whee", "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" } }, { "condition":"bla", "update": "id:unittest:testarray::whee", "create":true, "fields": { "actualarray": { "add": [ "person", "another person" ] } } }, { "remove": "id:unittest:smoke::whee" } ] """); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testUpdateWithConditionAndCreateInDifferentOrdering() { int documentsCreated = 106; List<String> parts = Arrays.asList( "\"condition\":\"bla\"", "\"update\": \"id:unittest:testarray::whee\"", " \"fields\": { " + "\"actualarray\": { \"add\": [" + " \"person\",\"another person\"]}}", " \"create\":true"); Random random = new Random(42); StringBuilder documents = new StringBuilder("["); for (int x = 0; x < documentsCreated; x++) { Collections.shuffle(parts, random); documents.append("{").append(Joiner.on(",").join(parts)).append("}"); if (x < documentsCreated -1) { documents.append(","); } } documents.append("]"); InputStream rawDoc = new ByteArrayInputStream(Utf8.toBytes(documents.toString())); JsonReader r = new JsonReader(types, rawDoc, parserFactory); for (int x = 0; x < documentsCreated; x++) { DocumentUpdate update = (DocumentUpdate) r.next(); checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); } assertNull(r.next()); } @Test public void testCreateIfNonExistentInPut() { JsonReader r = createReader(""" [ { "create":true, "fields": { "something": "smoketest", "nalle": "bamse" }, "put": "id:unittest:smoke::whee" } ] """); var op = r.next(); var put = (DocumentPut) op; assertTrue(put.getCreateIfNonExistent()); } @Test public void testCompleteFeedWithIdAfterFields() { JsonReader r = createReader(""" [ { "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" }, "put": "id:unittest:smoke::whee" }, { "fields": { "actualarray": { "add": [ "person", "another person" ] } }, "update": "id:unittest:testarray::whee" }, { "remove": "id:unittest:smoke::whee" } ] """); controlBasicFeed(r); } protected void controlBasicFeed(JsonReader r) { DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testCompleteFeedWithEmptyDoc() { JsonReader r = createReader(""" [ { "put": "id:unittest:smoke::whee", "fields": {} }, { "update": "id:unittest:testarray::whee", "fields": {} }, { "remove": "id:unittest:smoke::whee" } ] """); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); assertEquals("smoke", doc.getId().getDocType()); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; assertEquals("testarray", update.getId().getDocType()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } private void checkSimpleArrayAdd(DocumentUpdate update) { Set<String> toAdd = new HashSet<>(); FieldUpdate x = update.getFieldUpdate("actualarray"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; toAdd.add(((StringFieldValue) adder.getValue()).getString()); } assertEquals(2, toAdd.size()); assertTrue(toAdd.contains("person")); assertTrue(toAdd.contains("another person")); } private void smokeTestDoc(Document doc) { FieldValue boolField = doc.getFieldValue(doc.getField("flag")); assertSame(BoolFieldValue.class, boolField.getClass()); assertTrue((Boolean)boolField.getWrappedValue()); FieldValue stringField = doc.getFieldValue(doc.getField("nalle")); assertSame(StringFieldValue.class, stringField.getClass()); assertEquals("bamse", ((StringFieldValue) stringField).getString()); } @Test public void nonExistingFieldCausesException() throws IOException { Exception expected = assertThrows(IllegalArgumentException.class, () -> docFromJson(""" { "put": "id:unittest:smoke::whee", "fields": { "smething": "smoketest", "nalle": "bamse" } } """)); assertTrue(expected.getMessage().startsWith("No field 'smething' in the structure of type 'smoke'")); } @Test public void nonExistingFieldsCanBeIgnoredInPut() throws IOException { JsonReader r = createReader(""" { "put": "id:unittest:smoke::doc1", "fields": { "nonexisting1": "ignored value", "field1": "value1", "nonexisting2": { "blocks": { "a": [2.0, 3.0], "b": [4.0, 5.0] } }, "field2": "value2", "nonexisting3": { "cells": [ { "address": { "x": "x1" }, "value": 1.0 } ] }, "tensor1": { "cells": { "x1": 1.0 } }, "nonexisting4": "ignored value" } } """); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); boolean fullyApplied = new VespaJsonDocumentReader(true).readPut(parseInfo.fieldsBuffer, put); assertFalse(fullyApplied); assertNull(put.getDocument().getField("nonexisting1")); assertEquals("value1", put.getDocument().getFieldValue("field1").toString()); assertNull(put.getDocument().getField("nonexisting2")); assertEquals("value2", put.getDocument().getFieldValue("field2").toString()); assertNull(put.getDocument().getField("nonexisting3")); assertEquals(Tensor.from("tensor(x{}):{{x:x1}:1.0}"), put.getDocument().getFieldValue("tensor1").getWrappedValue()); assertNull(put.getDocument().getField("nonexisting4")); } @Test public void nonExistingFieldsCanBeIgnoredInUpdate() throws IOException{ JsonReader r = createReader(""" { "update": "id:unittest:smoke::doc1", "fields": { "nonexisting1": { "assign": "ignored value" }, "field1": { "assign": "value1" }, "nonexisting2": { "assign": { "blocks": { "a":[2.0,3.0], "b":[4.0,5.0] } } }, "field2": { "assign": "value2" }, "nonexisting3": { "assign" : { "cells": [{"address": {"x": "x1"}, "value": 1.0}] } }, "tensor1": {"assign": { "cells": {"x1": 1.0} } }, "nonexisting4": { "assign": "ignored value" } } } """); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentUpdate update = new DocumentUpdate(docType, parseInfo.documentId); boolean fullyApplied = new VespaJsonDocumentReader(true).readUpdate(parseInfo.fieldsBuffer, update); assertFalse(fullyApplied); assertNull(update.getFieldUpdate("nonexisting1")); assertEquals("value1", update.getFieldUpdate("field1").getValueUpdates().get(0).getValue().getWrappedValue().toString()); assertNull(update.getFieldUpdate("nonexisting2")); assertEquals("value2", update.getFieldUpdate("field2").getValueUpdates().get(0).getValue().getWrappedValue().toString()); assertNull(update.getFieldUpdate("nonexisting3")); assertEquals(Tensor.from("tensor(x{}):{{x:x1}:1.0}"), update.getFieldUpdate("tensor1").getValueUpdates().get(0).getValue().getWrappedValue()); assertNull(update.getFieldUpdate("nonexisting4")); } @Test public void feedWithBasicErrorTest() { JsonReader r = createReader(""" [ { "put": "id:test:smoke::0", "fields": { "something": "foo" } }, { "put": "id:test:smoke::1", "fields": { "something": "foo" } }, { "put": "id:test:smoke::2", "fields": { "something": "foo" } }, ]"""); // Trailing comma in array ... assertTrue(assertThrows(RuntimeException.class, () -> { while (r.next() != null); }) .getMessage().contains("JsonParseException")); } @Test public void idAsAliasForPutTest() throws IOException{ JsonReader r = createReader(""" { "id": "id:unittest:smoke::doc1", "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" } } """); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); boolean fullyApplied = new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); assertTrue(fullyApplied); smokeTestDoc(put.getDocument()); } private void testFeedWithTestAndSetCondition(String jsonDoc) { ByteArrayInputStream parseInfoDoc = new ByteArrayInputStream(Utf8.toBytes(jsonDoc)); JsonReader reader = new JsonReader(types, parseInfoDoc, parserFactory); int NUM_OPERATIONS_IN_FEED = 3; for (int i = 0; i < NUM_OPERATIONS_IN_FEED; i++) { DocumentOperation operation = reader.next(); assertTrue("A test and set condition should be present", operation.getCondition().isPresent()); assertEquals("DocumentOperation's test and set condition should be equal to the one in the JSON feed", "smoke.something == \"smoketest\"", operation.getCondition().getSelection()); } assertNull(reader.next()); } @Test public void testFeedWithTestAndSetConditionOrderingOne() { testFeedWithTestAndSetCondition(""" [ { "put": "id:unittest:smoke::whee", "condition": "smoke.something == \\"smoketest\\"", "fields": { "something": "smoketest", "nalle": "bamse" } }, { "update": "id:unittest:testarray::whee", "condition": "smoke.something == \\"smoketest\\"", "fields": { "actualarray": { "add": [ "person", "another person" ] } } }, { "remove": "id:unittest:smoke::whee", "condition": "smoke.something == \\"smoketest\\"" } ] """); } @Test public void testFeedWithTestAndSetConditionOrderingTwo() { testFeedWithTestAndSetCondition(""" [ { "condition": "smoke.something == \\"smoketest\\"", "put": "id:unittest:smoke::whee", "fields": { "something": "smoketest", "nalle": "bamse" } }, { "condition": "smoke.something == \\"smoketest\\"", "update": "id:unittest:testarray::whee", "fields": { "actualarray": { "add": [ "person", "another person" ] } } }, { "condition": "smoke.something == \\"smoketest\\"", "remove": "id:unittest:smoke::whee" } ] """); } @Test public void testFeedWithTestAndSetConditionOrderingThree() { testFeedWithTestAndSetCondition(""" [ { "put": "id:unittest:smoke::whee", "fields": { "something": "smoketest", "nalle": "bamse" }, "condition": "smoke.something == \\"smoketest\\"" }, { "update": "id:unittest:testarray::whee", "fields": { "actualarray": { "add": [ "person", "another person" ] } }, "condition": "smoke.something == \\"smoketest\\"" }, { "remove": "id:unittest:smoke::whee", "condition": "smoke.something == \\"smoketest\\"" } ] """); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldAfterFieldsFieldShouldFailParse() { String jsonData = """ [ { "put": "id:unittest:smoke::whee", "fields": { "something": "smoketest", "nalle": "bamse" }, "bjarne": "stroustrup" } ]"""; new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldBeforeFieldsFieldShouldFailParse() { String jsonData = """ [ { "update": "id:unittest:testarray::whee", "what is this": "nothing to see here", "fields": { "actualarray": { "add": [ "person", "another person" ] } } } ]"""; new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldWithoutFieldsFieldShouldFailParse() { String jsonData = """ [ { "remove": "id:unittest:smoke::whee", "what is love": "baby, do not hurt me... much } ]"""; new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test public void testMissingOperation() { try { String jsonData = """ [ { "fields": { "actualarray": { "add": [ "person", "another person" ] } } } ]"""; new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Missing a document operation ('put', 'update' or 'remove')", e.getMessage()); } } @Test public void testMissingFieldsMapInPut() { try { String jsonData = """ [ { "put": "id:unittest:smoke::whee" } ]"""; new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("put of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testMissingFieldsMapInUpdate() { try { String jsonData = """ [ { "update": "id:unittest:smoke::whee" } ]"""; new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Update of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testNullValues() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testnull::doc1", "fields": { "intfield": null, "stringfield": null, "arrayfield": null, "weightedsetfield": null, "mapfield": null, "tensorfield": null } } """); assertFieldValueNull(doc, "intfield"); assertFieldValueNull(doc, "stringfield"); assertFieldValueNull(doc, "arrayfield"); assertFieldValueNull(doc, "weightedsetfield"); assertFieldValueNull(doc, "mapfield"); assertFieldValueNull(doc, "tensorfield"); } @Test(expected=JsonReaderException.class) public void testNullArrayElement() throws IOException { docFromJson(""" { "put": "id:unittest:testnull::doc1", "fields": { "arrayfield": [ null ] } } """); fail(); } private void assertFieldValueNull(Document doc, String fieldName) { Field field = doc.getField(fieldName); assertNotNull(field); FieldValue fieldValue = doc.getFieldValue(field); assertNull(fieldValue); } static ByteArrayInputStream jsonToInputStream(String json) { return new ByteArrayInputStream(Utf8.toBytes(json)); } @Test public void testParsingWithoutTensorField() { Document doc = createPutWithoutTensor().getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals("id:unittest:testtensor::0", doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField("sparse_tensor")); assertNull(fieldValue); } @Test public void testParsingOfEmptyTensor() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor("{}")); } @Test public void testParsingOfTensorWithEmptyCells() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor(inputJson("{ 'cells': [] }"))); } @Test public void testDisallowedDenseTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{ 'values': [] }"), "dense_tensor", "The 'values' array does not contain any values"); assertCreatePutFails(inputJson("{ 'values': '' }"), "dense_tensor", "The 'values' string does not contain any values"); } @Test public void testDisallowedMixedTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{\"blocks\":{ \"a\": [] } }"), "mixed_tensor", "Expected 3 values, but got 0"); assertCreatePutFails(inputJson("{\"blocks\":[ {\"address\":{\"x\":\"a\"}, \"values\": [] } ] }"), "mixed_tensor", "Expected 3 values, but got 0"); } @Test public void testParsingOfSparseTensorWithCells() { Tensor tensor = assertSparseTensorField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createPutWithSparseTensor(""" { "type": "tensor(x{},y{})", "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 }, { "address": { "x": "c", "y": "b" }, "value": 3.0 } ] } """)); assertTrue(tensor instanceof MappedTensor); // any functional instance is fine } @Test public void testParsingOfDenseTensorWithCells() { Tensor tensor = assertTensorField("{{x:0,y:0}:2.0,{x:1,y:0}:3.0}}", createPutWithTensor(""" { "cells": [ { "address": { "x": 0, "y": 0 }, "value": 2.0 }, { "address": { "x": 1, "y": 0 }, "value": 3.0 } ] } """, "dense_unbound_tensor"), "dense_unbound_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorOnDenseForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(Double.POSITIVE_INFINITY); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(""" { "values": [2.0, 3.0, 4.0, "inf", 6.0, 7.0] }""", "dense_tensor"), "dense_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<int8>(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(""" { "values": "020304050607" }""", "dense_int8_tensor"), "dense_int8_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfMixedTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")); builder.cell().label("x", "foo").label("y", 0).value(2.0); builder.cell().label("x", "foo").label("y", 1).value(3.0); builder.cell().label("x", "foo").label("y", 2).value(4.0); builder.cell().label("x", "bar").label("y", 0).value(5.0); builder.cell().label("x", "bar").label("y", 1).value(6.0); builder.cell().label("x", "bar").label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = """ { "blocks":[ {"address":{"x":"foo"},"values":"400040404080"}, {"address":{"x":"bar"},"values":"40A040C040E0"} ] } """; var put = createPutWithTensor(inputJson(mixedJson), "mixed_bfloat16_tensor"); Tensor tensor = assertTensorField(expected, put, "mixed_bfloat16_tensor"); } /** Tests parsing of various tensor values set at the root, i.e. no 'cells', 'blocks' or 'values' */ @Test public void testDirectValue() { assertTensorField("tensor(x{}):{a:2, b:3}", "sparse_single_dimension_tensor", "{'a':2.0, 'b':3.0}"); assertTensorField("tensor(x[2],y[3]):[2, 3, 4, 5, 6, 7]]", "dense_tensor", "[2, 3, 4, 5, 6, 7]"); assertTensorField("tensor(x[2],y[3]):[2, 3, 4, 5, 6, 7]]", "dense_tensor", "[[2, 3, 4], [5, 6, 7]]"); assertTensorField("tensor(x{},y[3]):{a:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'a':[2, 3, 4], 'b':[4, 5, 6]}"); assertTensorField("tensor(x{},y{}):{{x:a,y:0}:2, {x:b,y:1}:3}", "sparse_tensor", "[{'address':{'x':'a','y':'0'},'value':2}, {'address':{'x':'b','y':'1'},'value':3}]"); } @Test public void testDirectValueReservedNameKeys() { // Single-valued assertTensorField("tensor(x{}):{cells:2, b:3}", "sparse_single_dimension_tensor", "{'cells':2.0, 'b':3.0}"); assertTensorField("tensor(x{}):{values:2, b:3}", "sparse_single_dimension_tensor", "{'values':2.0, 'b':3.0}"); assertTensorField("tensor(x{}):{block:2, b:3}", "sparse_single_dimension_tensor", "{'block':2.0, 'b':3.0}"); // Multi-valued assertTensorField("tensor(x{},y[3]):{cells:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'cells':[2, 3, 4], 'b':[4, 5, 6]}"); assertTensorField("tensor(x{},y[3]):{values:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'values':[2, 3, 4], 'b':[4, 5, 6]}"); assertTensorField("tensor(x{},y[3]):{block:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'block':[2, 3, 4], 'b':[4, 5, 6]}"); } @Test public void testParsingOfMixedTensorOnMixedForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = """ { "blocks":[ {"address":{"x":"0"},"values":[2.0,3.0,4.0]}, {"address":{"x":"1"},"values":[5.0,6.0,7.0]} ] } """; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance String mixedJsonDirect = """ [ {"address":{"x":"0","y":"0"},"value":2.0}, {"address":{"x":"0","y":"1"},"value":3.0}, {"address":{"x":"0","y":"2"},"value":4.0}, {"address":{"x":"1","y":"0"},"value":5.0}, {"address":{"x":"1","y":"1"},"value":6.0}, {"address":{"x":"1","y":"2"},"value":7.0} ] """; Tensor tensorDirect = assertTensorField(expected, createPutWithTensor(inputJson(mixedJsonDirect), "mixed_tensor"), "mixed_tensor"); assertTrue(tensorDirect instanceof MixedTensor); // this matters for performance } @Test public void testMixedTensorInMixedFormWithSingleSparseDimensionShortForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = """ { "blocks":{ "0":[2.0,3.0,4.0], "1":[5.0,6.0,7.0] } } """; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance } @Test public void testParsingOfTensorWithSingleCellInDifferentJsonOrder() { assertSparseTensorField("{{x:a,y:b}:2.0}", createPutWithSparseTensor(""" { "cells": [ { "value": 2.0, "address": { "x": "a", "y": "b" } } ] } """)); } @Test public void testAssignUpdateOfEmptySparseTensor() { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithSparseTensor("{}")); } @Test public void testAssignUpdateOfEmptyDenseTensor() { try { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithTensor("{}", "dense_unbound_tensor")); } catch (IllegalArgumentException e) { assertEquals("An indexed tensor must have a value", "Error in 'dense_unbound_tensor': Tensor of type tensor(x[],y[]) has no values", Exceptions.toMessageString(e)); } } @Test public void testAssignUpdateOfNullTensor() { ClearValueUpdate clearUpdate = (ClearValueUpdate) getTensorField(createAssignUpdateWithSparseTensor(null)).getValueUpdate(0); assertNotNull(clearUpdate); assertNull(clearUpdate.getValue()); } @Test public void testAssignUpdateOfTensorWithCells() { assertTensorAssignUpdateSparseField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createAssignUpdateWithSparseTensor(""" { "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 }, { "address": { "x": "c", "y": "b" }, "value": 3.0 } ] } """)); } @Test public void testAssignUpdateOfTensorDenseShortForm() { assertTensorAssignUpdateDenseField("tensor(x[2],y[3]):[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]", createAssignUpdateWithTensor(""" { "values": [1,2,3,4,5,6] } """, "dense_tensor")); } @Test public void tensor_modify_update_with_replace_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_tensor", """ { "operation": "replace", "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_add_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, "sparse_tensor", """ { "operation": "add", "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_multiply_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "sparse_tensor", """ { "operation": "multiply", "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_create_non_existing_cells_true() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, true, "sparse_tensor", """ { "operation": "add", "create": true, "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_create_non_existing_cells_false() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, false, "sparse_tensor", """ { "operation": "add", "create": false, "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_treats_the_input_tensor_as_sparse() { // Note that the type of the tensor in the modify update is sparse (it only has mapped dimensions). assertTensorModifyUpdate("tensor(x{},y{}):{{x:0,y:0}:2.0, {x:1,y:2}:3.0}", TensorModifyUpdate.Operation.REPLACE, "dense_tensor", """ { "operation": "replace", "cells": [ { "address": { "x": "0", "y": "0" }, "value": 2.0 }, { "address": { "x": "1", "y": "2" }, "value": 3.0 } ] }"""); } @Test public void tensor_modify_update_on_non_tensor_field_throws() { try { JsonReader reader = createReader(""" { "update": "id:unittest:smoke::doc1", "fields": { "something": { "modify": {} } } } """); reader.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::doc1"); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Error in 'something': A modify update can only be applied to tensor fields. Field 'something' is of type 'string'", Exceptions.toMessageString(e)); } } @Test public void tensor_modify_update_on_dense_unbound_tensor_throws() { illegalTensorModifyUpdate("Error in 'dense_unbound_tensor': A modify update cannot be applied to tensor types with indexed unbound dimensions. Field 'dense_unbound_tensor' has unsupported tensor type 'tensor(x[],y[])'", "dense_unbound_tensor", """ { "operation": "replace", "cells": [ { "address": { "x": "0", "y": "0" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorModifyUpdate("{{x:a}:2.0, {x:c}: 3.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_single_dimension_tensor", """ { "operation": "replace", "cells": { "a": 2.0, "c": 3.0 } }"""); } @Test public void tensor_modify_update_with_replace_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", """ { "operation": "replace", "cells": [ { "address": { "x": "a", "y": "0" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_array() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", """ { "operation": "replace", "blocks": [ { "address": { "x": "a" }, "values": [1,2,3] } ] }"""); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_must_specify_full_subspace() { illegalTensorModifyUpdate("Error in 'mixed_tensor': At {x:a}: Expected 3 values, but got 2", "mixed_tensor", """ { "operation": "replace", "blocks": { "a": [2,3] } }"""); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_map() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", """ { "operation": "replace", "blocks": { "a": [1,2,3] } }"""); } @Test public void tensor_modify_update_with_add_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.ADD, "mixed_tensor", """ { "operation": "add", "cells": [ { "address": { "x": "a", "y": "0" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_multiply_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "mixed_tensor", """ { "operation": "multiply", "cells": [ { "address": { "x": "a", "y": "0" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws() { illegalTensorModifyUpdate("Error in 'dense_tensor': Dimension 'y' has label '3' but type is tensor(x[2],y[3])", "dense_tensor", """ { "operation": "replace", "cells": [ { "address": { "x": "0", "y": "3" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws_mixed() { illegalTensorModifyUpdate("Error in 'mixed_tensor': Dimension 'y' has label '3' but type is tensor(x{},y[3])", "mixed_tensor", """ { "operation": "replace", "cells": [ { "address": { "x": "0", "y": "3" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_unknown_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown operation 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", """ { "operation": "unknown", "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_without_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain an operation", "sparse_tensor", """ { "cells": [] }"""); } @Test public void tensor_modify_update_without_cells_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", """ { "operation": "replace" }"""); } @Test public void tensor_modify_update_with_unknown_content_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown JSON string 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", """ { "unknown": "here" }"""); } @Test public void tensor_add_update_on_sparse_tensor() { assertTensorAddUpdate("{{x:a,y:b}:2.0, {x:c,y:d}: 3.0}", "sparse_tensor", """ { "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 }, { "address": { "x": "c", "y": "d" }, "value": 3.0 } ] }"""); } @Test public void tensor_add_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorAddUpdate("{{x:a}:2.0, {x:c}: 3.0}", "sparse_single_dimension_tensor", """ { "cells": { "a": 2.0, "c": 3.0 } }"""); } @Test public void tensor_add_update_on_mixed_tensor() { assertTensorAddUpdate("{{x:a,y:0}:2.0, {x:a,y:1}:3.0, {x:a,y:2}:0.0}", "mixed_tensor", """ { "cells": [ { "address": { "x": "a", "y": "0" }, "value": 2.0 }, { "address": { "x": "a", "y": "1" }, "value": 3.0 } ] }"""); } @Test public void tensor_add_update_on_mixed_with_out_of_bound_dense_cells_throws() { illegalTensorAddUpdate("Error in 'mixed_tensor': Index 3 out of bounds for length 3", "mixed_tensor", """ { "cells": [ { "address": { "x": "0", "y": "3" }, "value": 2.0 } ] }"""); } @Test public void tensor_add_update_on_dense_tensor_throws() { illegalTensorAddUpdate("Error in 'dense_tensor': An add update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", """ { "cells": [ ] }"""); } @Test public void tensor_add_update_on_not_fully_specified_cell_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Missing a label for dimension 'y' for tensor(x{},y{})", "sparse_tensor", """ { "cells": [ { "address": { "x": "a" }, "value": 2.0 } ] }"""); } @Test public void tensor_add_update_without_cells_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Add update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", "{}"); illegalTensorAddUpdate("Error in 'mixed_tensor': Add update for field 'mixed_tensor' does not contain tensor cells", "mixed_tensor", "{}"); } @Test public void tensor_remove_update_on_sparse_tensor() { assertTensorRemoveUpdate("{{x:a,y:b}:1.0,{x:c,y:d}:1.0}", "sparse_tensor", """ { "addresses": [ { "x": "a", "y": "b" }, { "x": "c", "y": "d" } ] }"""); } @Test public void tensor_remove_update_on_mixed_tensor() { assertTensorRemoveUpdate("{{x:1}:1.0,{x:2}:1.0}", "mixed_tensor", """ { "addresses": [ { "x": "1" }, { "x": "2" } ] }"""); } @Test public void tensor_remove_update_on_sparse_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{y:b}:1.0,{y:d}:1.0}", "sparse_tensor", """ { "addresses": [ { "y": "b" }, { "y": "d" } ] }"""); } @Test public void tensor_remove_update_on_mixed_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{x:1,z:a}:1.0,{x:2,z:b}:1.0}", "mixed_tensor_adv", """ { "addresses": [ { "x": "1", "z": "a" }, { "x": "2", "z": "b" } ] }"""); } @Test public void tensor_remove_update_on_mixed_tensor_with_dense_addresses_throws() { illegalTensorRemoveUpdate("Error in 'mixed_tensor': Indexed dimension address 'y' should not be specified in remove update", "mixed_tensor", """ { "addresses": [ { "x": "1", "y": "0" }, { "x": "2", "y": "0" } ] }"""); } @Test public void tensor_remove_update_on_dense_tensor_throws() { illegalTensorRemoveUpdate("Error in 'dense_tensor': A remove update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", """ { "addresses": [] }"""); } @Test public void tensor_remove_update_with_stray_dimension_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{},y{}) does not contain dimension 'foo'", "sparse_tensor", """ { "addresses": [ { "x": "a", "foo": "b" } ] }"""); illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{}) does not contain dimension 'foo'", "sparse_tensor", """ { "addresses": [ { "x": "c" }, { "x": "a", "foo": "b" } ] }"""); } @Test public void tensor_remove_update_without_cells_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': Remove update for field 'sparse_tensor' does not contain tensor addresses", "sparse_tensor", """ { "addresses": [] }"""); illegalTensorRemoveUpdate("Error in 'mixed_tensor': Remove update for field 'mixed_tensor' does not contain tensor addresses", "mixed_tensor", """ { "addresses": [] }"""); } @Test public void require_that_parser_propagates_datatype_parser_errors_predicate() { assertParserErrorMatches( "Error in document 'id:unittest:testpredicate::0' - could not parse field 'boolean' of type 'predicate': " + "line 1:10 no viable alternative at character '>'", """ [ { "fields": { "boolean": "timestamp > 9000" }, "put": "id:unittest:testpredicate::0" } ] """); } @Test public void require_that_parser_propagates_datatype_parser_errors_string_as_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \" 1\"", """ [ { "fields": { "integerfield": " 1" }, "put": "id:unittest:testint::0" } ] """); } @Test public void require_that_parser_propagates_datatype_parser_errors_overflowing_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \"281474976710656\"", """ [ { "fields": { "integerfield": 281474976710656 }, "put": "id:unittest:testint::0" } ] """); } @Test public void requireThatUnknownDocTypeThrowsIllegalArgumentException() { String jsonData = """ [ { "put": "id:ns:walrus::walrus1", "fields": { "aField": 42 } } ] """; try { new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail(); } catch (IllegalArgumentException e) { assertEquals("Document type walrus does not exist", e.getMessage()); } } private static final String TENSOR_DOC_ID = "id:unittest:testtensor::0"; private void illegalTensorModifyUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorModifyUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorAddUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorAddUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorRemoveUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorRemoveUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private DocumentPut createPutWithoutTensor() { JsonReader reader = createReader(inputJson("[ { 'put': '" + TENSOR_DOC_ID + "', 'fields': { } } ]")); return (DocumentPut) reader.next(); } private DocumentPut createPutWithSparseTensor(String inputTensor) { return createPutWithTensor(inputTensor, "sparse_tensor"); } private DocumentPut createPutWithTensor(String inputTensor, String tensorFieldName) { JsonReader streaming = createReader(""" { "fields": { "%s": %s } } """.formatted(tensorFieldName, inputTensor)); DocumentPut lazyParsed = (DocumentPut) streaming.readSingleDocumentStreaming(DocumentOperationType.PUT, TENSOR_DOC_ID).operation(); JsonReader reader = createReader(""" [ { "put": "%s", "fields": { "%s": %s } } ]""".formatted(TENSOR_DOC_ID, tensorFieldName, inputTensor)); DocumentPut bufferParsed = (DocumentPut) reader.next(); assertEquals(lazyParsed, bufferParsed); return bufferParsed; } private DocumentUpdate createAssignUpdateWithSparseTensor(String inputTensor) { return createAssignUpdateWithTensor(inputTensor, "sparse_tensor"); } private DocumentUpdate createAssignUpdateWithTensor(String inputTensor, String tensorFieldName) { return createTensorUpdate("assign", inputTensor, tensorFieldName); } private static Tensor assertSparseTensorField(String expectedTensor, DocumentPut put) { return assertTensorField(expectedTensor, put, "sparse_tensor"); } private Tensor assertTensorField(String expectedTensor, String fieldName, String inputJson) { return assertTensorField(expectedTensor, createPutWithTensor(inputJson(inputJson), fieldName), fieldName); } private static Tensor assertTensorField(String expectedTensor, DocumentPut put, String tensorFieldName) { return assertTensorField(Tensor.from(expectedTensor), put, tensorFieldName); } private static Tensor assertTensorField(Tensor expectedTensor, DocumentPut put, String tensorFieldName) { Document doc = put.getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals(TENSOR_DOC_ID, doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField(tensorFieldName)); assertEquals(expectedTensor, fieldValue.getTensor().get()); return fieldValue.getTensor().get(); } private static void assertTensorFieldUpdate(DocumentUpdate update, String tensorFieldName) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); assertEquals(1, update.fieldUpdates().size()); assertEquals(1, update.getFieldUpdate(tensorFieldName).size()); } private static void assertTensorAssignUpdateSparseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "sparse_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private static void assertTensorAssignUpdateDenseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "dense_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, String tensorFieldName, String modifyJson) { assertTensorModifyUpdate(expectedTensor, expectedOperation, false, tensorFieldName, createTensorModifyUpdate(modifyJson, tensorFieldName)); } private void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, boolean expectedCreateNonExistingCells, String tensorFieldName, String modifyJson) { assertTensorModifyUpdate(expectedTensor, expectedOperation, expectedCreateNonExistingCells, tensorFieldName, createTensorModifyUpdate(modifyJson, tensorFieldName)); } private static void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, boolean expectedCreateNonExistingCells, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorModifyUpdate modifyUpdate = (TensorModifyUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(expectedOperation, modifyUpdate.getOperation()); assertEquals(Tensor.from(expectedTensor), modifyUpdate.getValue().getTensor().get()); assertEquals(expectedCreateNonExistingCells, modifyUpdate.getCreateNonExistingCells()); } private DocumentUpdate createTensorModifyUpdate(String modifyJson, String tensorFieldName) { return createTensorUpdate("modify", modifyJson, tensorFieldName); } private DocumentUpdate createTensorAddUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("add", tensorJson, tensorFieldName); } private DocumentUpdate createTensorRemoveUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("remove", tensorJson, tensorFieldName); } private DocumentUpdate createTensorUpdate(String operation, String tensorJson, String tensorFieldName) { JsonReader streaming = createReader(""" { "fields": { "%s": { "%s": %s } } }""".formatted(tensorFieldName, operation, tensorJson)); DocumentUpdate lazyParsed = (DocumentUpdate) streaming.readSingleDocumentStreaming(DocumentOperationType.UPDATE, TENSOR_DOC_ID).operation(); JsonReader reader = createReader(""" [ { "update": "%s", "fields": { "%s": { "%s": %s } } } ]""".formatted(TENSOR_DOC_ID, tensorFieldName, operation, tensorJson)); DocumentUpdate bufferParsed = (DocumentUpdate) reader.next(); assertEquals(lazyParsed, bufferParsed); return bufferParsed; } private void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorAddUpdate(expectedTensor, tensorFieldName, createTensorAddUpdate(tensorJson, tensorFieldName)); } private static void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorAddUpdate addUpdate = (TensorAddUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), addUpdate.getValue().getTensor().get()); } private void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorRemoveUpdate(expectedTensor, tensorFieldName, createTensorRemoveUpdate(tensorJson, tensorFieldName)); } private static void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorRemoveUpdate removeUpdate = (TensorRemoveUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), removeUpdate.getValue().getTensor().get()); } private static FieldUpdate getTensorField(DocumentUpdate update) { return getTensorField(update, "sparse_tensor"); } private static FieldUpdate getTensorField(DocumentUpdate update, String fieldName) { FieldUpdate fieldUpdate = update.getFieldUpdate(fieldName); assertEquals(1, fieldUpdate.size()); return fieldUpdate; } // NOTE: Do not call this method multiple times from a test method as it's using the ExpectedException rule private void assertParserErrorMatches(String expectedError, String... json) { String jsonData = inputJson(json); try { new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail(); } catch (JsonReaderException e) { assertEquals(expectedError, e.getMessage()); } } private void assertCreatePutFails(String tensor, String name, String msg) { try { createPutWithTensor(inputJson(tensor), name); fail("Expected exception"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains(msg)); } } }
vespa-engine/vespa
document/src/test/java/com/yahoo/document/json/JsonReaderTestCase.java
213,269
/* * Copyright (c) 2018, 2021 Oracle and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.helidon.security.abac.role; import java.util.ArrayList; import java.util.List; import java.util.Optional; import io.helidon.common.Errors; import io.helidon.config.Config; import io.helidon.security.EndpointConfig; import io.helidon.security.Principal; import io.helidon.security.ProviderRequest; import io.helidon.security.Role; import io.helidon.security.SecurityLevel; import io.helidon.security.Subject; import io.helidon.security.SubjectType; import jakarta.annotation.security.DenyAll; import jakarta.annotation.security.PermitAll; import jakarta.annotation.security.RolesAllowed; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Unit test for {@link RoleValidator}. */ class RoleValidatorTest { static Config config; @BeforeAll static void beforeAll() { config = Config.create(); } @Test void testRolesAllowedPermit() { RoleValidator validator = RoleValidator.create(); RolesAllowed annot = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(RolesAllowed.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testRolesAllowedDeny() { RoleValidator validator = RoleValidator.create(); RolesAllowed annot = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(RolesAllowed.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("User is not in admin role, should have failed"); } } @Test void testUserRoles() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); when(annot.subjectType()).thenReturn(SubjectType.USER); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(RoleValidator.Roles.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testUserRolesDeny() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.subjectType()).thenReturn(SubjectType.USER); when(annot.value()).thenReturn(roleArray); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(RoleValidator.Roles.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("User is not in admin role, should have failed"); } } @Test void testServiceRoles() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); when(annot.subjectType()).thenReturn(SubjectType.SERVICE); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(RoleValidator.Roles.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.service()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("service")) .addGrant(Role.create("admin")) .build())); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testServiceRolesDeny() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); when(annot.subjectType()).thenReturn(SubjectType.SERVICE); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(RoleValidator.Roles.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("service")) .addGrant(Role.create("user")) .build())); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("Service is not in admin role, should have failed"); } } @Test void testDenyAll() { RoleValidator validator = RoleValidator.create(); DenyAll annot = mock(DenyAll.class); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(DenyAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("DenyAll is set on this method, this should have failed"); } } @Test void testPermitAll() { RoleValidator validator = RoleValidator.create(); PermitAll annot = mock(PermitAll.class); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(PermitAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testDenyAllAndPermitAll() { RoleValidator validator = RoleValidator.create(); PermitAll permitAll = mock(PermitAll.class); DenyAll denyAll = mock(DenyAll.class); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(DenyAll.class, EndpointConfig.AnnotationScope.CLASS)) .thenReturn(List.of(denyAll)); when(classSecurityLevel.filterAnnotations(PermitAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(permitAll)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testDenyAllAndRoles() { RoleValidator validator = RoleValidator.create(); DenyAll denyAll = mock(DenyAll.class); RolesAllowed rolesAllowed = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(rolesAllowed.value()).thenReturn(roleArray); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(DenyAll.class, EndpointConfig.AnnotationScope.CLASS)) .thenReturn(List.of(denyAll)); when(classSecurityLevel.filterAnnotations(RolesAllowed.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(rolesAllowed)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testPermitAllAndRolesAndDenyAll() { RoleValidator validator = RoleValidator.create(); PermitAll permitAll = mock(PermitAll.class); DenyAll denyAll = mock(DenyAll.class); RolesAllowed rolesAllowed = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(rolesAllowed.value()).thenReturn(roleArray); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(PermitAll.class, EndpointConfig.AnnotationScope.CLASS)) .thenReturn(List.of(permitAll)); when(classSecurityLevel.filterAnnotations(DenyAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(denyAll)); when(classSecurityLevel.filterAnnotations(RolesAllowed.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(rolesAllowed)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("DenyAll is set on this method, this should have failed"); } } @Test void testAllAccessAnnotationsOnTheSameLevel() { RoleValidator validator = RoleValidator.create(); PermitAll permitAll = mock(PermitAll.class); DenyAll denyAll = mock(DenyAll.class); RolesAllowed rolesAllowed = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(rolesAllowed.value()).thenReturn(roleArray); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(PermitAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(permitAll)); when(classSecurityLevel.filterAnnotations(DenyAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(denyAll)); when(classSecurityLevel.filterAnnotations(RolesAllowed.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(rolesAllowed)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("DenyAll is set on this method, this should have failed"); } } @Test void testRolesFromConfig() { RoleValidator roleValidator = RoleValidator.create(); RoleValidator.RoleConfig roleConfig = roleValidator.fromConfig(config.get("test1")); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); roleValidator.validate(roleConfig, collector, request); collector.collect().checkValid(); } @Test void testRolesAndPermitAllFromConfig() { RoleValidator roleValidator = RoleValidator.create(); RoleValidator.RoleConfig roleConfig = roleValidator.fromConfig(config.get("test2")); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("test")) .build())); roleValidator.validate(roleConfig, collector, request); collector.collect().checkValid(); } @Test void testRolesAndDenyAllFromConfig() { RoleValidator roleValidator = RoleValidator.create(); RoleValidator.RoleConfig roleConfig = roleValidator.fromConfig(config.get("test3")); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("test")) .build())); roleValidator.validate(roleConfig, collector, request); if (collector.collect().isValid()) { fail("DenyAll is set on this method, this should have failed"); } } @Test void testAllAccessModificationsOnTheSameLevelFromConfig() { RoleValidator roleValidator = RoleValidator.create(); RoleValidator.RoleConfig roleConfig = roleValidator.fromConfig(config.get("test4")); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("test")) .build())); roleValidator.validate(roleConfig, collector, request); if (collector.collect().isValid()) { fail("DenyAll is set on this method, this should have failed"); } } }
helidon-io/helidon
security/abac/role/src/test/java/io/helidon/security/abac/role/RoleValidatorTest.java
213,270
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sling.feature.extension.apiregions.api.artifacts; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import jakarta.json.Json; import org.apache.sling.feature.ArtifactId; import org.apache.sling.feature.Extension; import org.apache.sling.feature.ExtensionState; import org.apache.sling.feature.ExtensionType; import org.junit.Test; import org.osgi.framework.Version; import org.osgi.framework.VersionRange; public class VersionRuleTest { @Test public void testClear() { final VersionRule entity = new VersionRule(); entity.getAttributes().put("a", Json.createValue(5)); entity.setAllowedVersionRanges(new VersionRange[] {new VersionRange("1.0")}); entity.setDeniedVersionRanges(new VersionRange[] {new VersionRange("3.0")}); entity.setMode(Mode.LENIENT); entity.setMessage("msg"); entity.setArtifactId(ArtifactId.parse("g:a:1")); entity.clear(); assertTrue(entity.getAttributes().isEmpty()); assertNull(entity.getAllowedVersionRanges()); assertNull(entity.getDeniedVersionRanges()); assertNull(entity.getMessage()); assertNull(entity.getArtifactId()); assertNull(entity.getMode()); } @Test public void testFromJSONObject() throws IOException { final Extension ext = new Extension(ExtensionType.JSON, "a", ExtensionState.OPTIONAL); ext.setJSON("{ \"mode\" : \"LENIENT\", \"message\" : \"msg\", \"artifact-id\":\"g:a:1\"," + "\"allowed-version-ranges\":[\"1.0\"],\"denied-version-ranges\":[\"2.0\"]}"); final VersionRule entity = new VersionRule(); entity.fromJSONObject(ext.getJSONStructure().asJsonObject()); assertEquals(Mode.LENIENT, entity.getMode()); assertEquals("msg", entity.getMessage()); assertEquals(ArtifactId.parse("g:a:1"), entity.getArtifactId()); assertEquals(1, entity.getAllowedVersionRanges().length); assertEquals(new VersionRange("1.0"), entity.getAllowedVersionRanges()[0]); assertEquals(1, entity.getDeniedVersionRanges().length); assertEquals(new VersionRange("2.0"), entity.getDeniedVersionRanges()[0]); } @Test public void testToJSONObject() throws IOException { final VersionRule entity = new VersionRule(); entity.setMode(Mode.LENIENT); entity.setMessage("msg"); entity.setArtifactId(ArtifactId.parse("g:a:1")); entity.setAllowedVersionRanges(new VersionRange[] {new VersionRange("1.0.0")}); entity.setDeniedVersionRanges(new VersionRange[] {new VersionRange("2.0.0")}); final Extension ext = new Extension(ExtensionType.JSON, "a", ExtensionState.OPTIONAL); ext.setJSON("{ \"mode\" : \"LENIENT\", \"artifact-id\":\"g:a:1\", \"message\" : \"msg\"," + "\"allowed-version-ranges\":[\"1.0.0\"],\"denied-version-ranges\":[\"2.0.0\"]}"); assertEquals(ext.getJSONStructure().asJsonObject(), entity.toJSONObject()); } @Test public void testIsAllowedNoRanges() { final VersionRule entity = new VersionRule(); assertFalse(entity.isAllowed(new Version("1.0"))); assertFalse(entity.isAllowed(new Version("1.3"))); assertFalse(entity.isAllowed(new Version("2.1"))); } @Test public void testIsAllowedAllowedRange() { final VersionRule entity = new VersionRule(); entity.setAllowedVersionRanges(new VersionRange[] {new VersionRange("[1.2, 2)")}); assertFalse(entity.isAllowed(new Version("1.0"))); assertTrue(entity.isAllowed(new Version("1.3"))); assertFalse(entity.isAllowed(new Version("2.1"))); } @Test public void testIsAllowedAllowedDenied() { final VersionRule entity = new VersionRule(); entity.setAllowedVersionRanges(new VersionRange[] {new VersionRange("[1.2, 2)")}); entity.setDeniedVersionRanges(new VersionRange[] {new VersionRange("[1.3.1,1.3.1]")}); assertFalse(entity.isAllowed(new Version("1.0"))); assertTrue(entity.isAllowed(new Version("1.3"))); assertFalse(entity.isAllowed(new Version("1.3.1"))); assertTrue(entity.isAllowed(new Version("1.3.2"))); assertFalse(entity.isAllowed(new Version("2.1"))); } }
apache/sling-org-apache-sling-feature-extension-apiregions
src/test/java/org/apache/sling/feature/extension/apiregions/api/artifacts/VersionRuleTest.java
213,271
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.qpid.systest.rest.acl; import java.io.File; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.qpid.server.logging.VirtualHostFileLogger; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.model.VirtualHostLogger; import org.apache.qpid.server.model.VirtualHostNode; import org.apache.qpid.server.security.acl.AbstractACLTestCase; import org.apache.qpid.server.virtualhost.ProvidedStoreVirtualHostImpl; import org.apache.qpid.server.virtualhostnode.JsonVirtualHostNode; import org.apache.qpid.systest.rest.QpidRestTestCase; import org.apache.qpid.test.utils.TestBrokerConfiguration; public class VirtualHostACLTest extends QpidRestTestCase { private static final String VHN_WITHOUT_VH = "myVhnWithoutVh"; private static final String ALLOWED_USER = "user1"; private static final String DENIED_USER = "user2"; @Override protected void customizeConfiguration() throws Exception { super.customizeConfiguration(); final TestBrokerConfiguration defaultBrokerConfiguration = getDefaultBrokerConfiguration(); defaultBrokerConfiguration.configureTemporaryPasswordFile(ALLOWED_USER, DENIED_USER); AbstractACLTestCase.writeACLFileUtil(this, "ACL ALLOW-LOG ALL ACCESS MANAGEMENT", "ACL ALLOW-LOG " + ALLOWED_USER + " ALL VIRTUALHOST", "ACL DENY-LOG " + DENIED_USER + " ALL VIRTUALHOST", "ACL DENY-LOG ALL ALL"); Map<String, Object> virtualHostNodeAttributes = new HashMap<>(); virtualHostNodeAttributes.put(VirtualHostNode.NAME, VHN_WITHOUT_VH); virtualHostNodeAttributes.put(VirtualHostNode.TYPE, getTestProfileVirtualHostNodeType()); // TODO need better way to determine the VHN's optional attributes virtualHostNodeAttributes.put(JsonVirtualHostNode.STORE_PATH, getStoreLocation(VHN_WITHOUT_VH)); defaultBrokerConfiguration.addObjectConfiguration(VirtualHostNode.class, virtualHostNodeAttributes); } public void testCreateVirtualHostAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String hostName = getTestName(); int responseCode = createVirtualHost(VHN_WITHOUT_VH, hostName); assertEquals("Virtual host creation should be allowed", HttpServletResponse.SC_CREATED, responseCode); assertVirtualHostExists(VHN_WITHOUT_VH, hostName); } public void testCreateVirtualHostDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String hostName = getTestName(); int responseCode = createVirtualHost(VHN_WITHOUT_VH, hostName); assertEquals("Virtual host creation should be denied", HttpServletResponse.SC_FORBIDDEN, responseCode); assertVirtualHostDoesNotExist(VHN_WITHOUT_VH, hostName); } public void testDeleteVirtualHostDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest("virtualhost/" + TEST2_VIRTUALHOST + "/" + TEST2_VIRTUALHOST, "DELETE", HttpServletResponse.SC_FORBIDDEN); assertVirtualHostExists(TEST2_VIRTUALHOST, TEST2_VIRTUALHOST); } public void testUpdateVirtualHostDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(VirtualHost.NAME, TEST2_VIRTUALHOST); attributes.put(VirtualHost.DESCRIPTION, "new description"); getRestTestHelper().submitRequest("virtualhost/" + TEST2_VIRTUALHOST + "/" + TEST2_VIRTUALHOST, "PUT", attributes, HttpServletResponse.SC_FORBIDDEN); } public void testDownloadVirtualHostLoggerFileAllowedDenied() throws Exception { final String virtualHostName = "testVirtualHost"; final String loggerName = "testFileLogger"; final String loggerPath = "virtualhostlogger/" + VHN_WITHOUT_VH + "/" + virtualHostName + "/" + loggerName; getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); createVirtualHost(VHN_WITHOUT_VH, virtualHostName); Map<String, Object> attributes = new HashMap<>(); attributes.put(VirtualHostLogger.NAME, loggerName); attributes.put(ConfiguredObject.TYPE, VirtualHostFileLogger.TYPE); getRestTestHelper().submitRequest("virtualhostlogger/" + VHN_WITHOUT_VH + "/" + virtualHostName, "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_OK); getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_OK); getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_FORBIDDEN); } /* === Utility Methods === */ private int createVirtualHost(final String testVirtualHostNode, String virtualHostName) throws Exception { Map<String, Object> data = new HashMap<>(); data.put(VirtualHost.NAME, virtualHostName); data.put(VirtualHost.TYPE, ProvidedStoreVirtualHostImpl.VIRTUAL_HOST_TYPE); return getRestTestHelper().submitRequest("virtualhost/" + testVirtualHostNode + "/" + virtualHostName, "PUT", data); } private void assertVirtualHostDoesNotExist(final String virtualHostNodeName, String virtualHostName) throws Exception { assertVirtualHostExistence(virtualHostNodeName, virtualHostName, false); } private void assertVirtualHostExists(final String virtualHostNodeName, String virtualHostName) throws Exception { assertVirtualHostExistence(virtualHostNodeName, virtualHostName, true); } private void assertVirtualHostExistence(final String virtualHostNodeName, String virtualHostName, boolean exists) throws Exception { String path = "virtualhost/" + virtualHostNodeName + "/" + virtualHostName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private String getStoreLocation(String hostName) { return new File(TMP_FOLDER, "store-" + hostName + "-" + System.currentTimeMillis()).getAbsolutePath(); } }
pamod/qpid-java
systests/src/test/java/org/apache/qpid/systest/rest/acl/VirtualHostACLTest.java
213,272
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.qpid.systest.rest.acl; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.qpid.server.logging.VirtualHostFileLogger; import org.apache.qpid.server.management.plugin.HttpManagement; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.Plugin; import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.model.VirtualHostLogger; import org.apache.qpid.server.model.VirtualHostNode; import org.apache.qpid.server.security.acl.AbstractACLTestCase; import org.apache.qpid.server.virtualhost.ProvidedStoreVirtualHostImpl; import org.apache.qpid.server.virtualhostnode.JsonVirtualHostNode; import org.apache.qpid.systest.rest.QpidRestTestCase; import org.apache.qpid.test.utils.TestBrokerConfiguration; public class VirtualHostACLTest extends QpidRestTestCase { private static final String VHN_WITHOUT_VH = "myVhnWithoutVh"; private static final String ALLOWED_USER = "user1"; private static final String DENIED_USER = "user2"; @Override protected void customizeConfiguration() throws IOException { super.customizeConfiguration(); getRestTestHelper().configureTemporaryPasswordFile(this, ALLOWED_USER, DENIED_USER); AbstractACLTestCase.writeACLFileUtil(this, "ACL ALLOW-LOG ALL ACCESS MANAGEMENT", "ACL ALLOW-LOG " + ALLOWED_USER + " ALL VIRTUALHOST", "ACL DENY-LOG " + DENIED_USER + " ALL VIRTUALHOST", "ACL DENY-LOG ALL ALL"); getBrokerConfiguration().setObjectAttribute(Plugin.class, TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT, HttpManagement.HTTP_BASIC_AUTHENTICATION_ENABLED, true); Map<String, Object> virtualHostNodeAttributes = new HashMap<>(); virtualHostNodeAttributes.put(VirtualHostNode.NAME, VHN_WITHOUT_VH); virtualHostNodeAttributes.put(VirtualHostNode.TYPE, getTestProfileVirtualHostNodeType()); // TODO need better way to determine the VHN's optional attributes virtualHostNodeAttributes.put(JsonVirtualHostNode.STORE_PATH, getStoreLocation(VHN_WITHOUT_VH)); getBrokerConfiguration().addObjectConfiguration(VirtualHostNode.class, virtualHostNodeAttributes); } public void testCreateVirtualHostAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String hostName = getTestName(); int responseCode = createVirtualHost(VHN_WITHOUT_VH, hostName); assertEquals("Virtual host creation should be allowed", HttpServletResponse.SC_CREATED, responseCode); assertVirtualHostExists(VHN_WITHOUT_VH, hostName); } public void testCreateVirtualHostDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String hostName = getTestName(); int responseCode = createVirtualHost(VHN_WITHOUT_VH, hostName); assertEquals("Virtual host creation should be denied", HttpServletResponse.SC_FORBIDDEN, responseCode); assertVirtualHostDoesNotExist(VHN_WITHOUT_VH, hostName); } public void testDeleteVirtualHostDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest("virtualhost/" + TEST2_VIRTUALHOST + "/" + TEST2_VIRTUALHOST, "DELETE", HttpServletResponse.SC_FORBIDDEN); assertVirtualHostExists(TEST2_VIRTUALHOST, TEST2_VIRTUALHOST); } public void testUpdateVirtualHostDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(VirtualHost.NAME, TEST2_VIRTUALHOST); attributes.put(VirtualHost.DESCRIPTION, "new description"); getRestTestHelper().submitRequest("virtualhost/" + TEST2_VIRTUALHOST + "/" + TEST2_VIRTUALHOST, "PUT", attributes, HttpServletResponse.SC_FORBIDDEN); } public void testDownloadVirtualHostLoggerFileAllowedDenied() throws Exception { final String virtualHostName = "testVirtualHost"; final String loggerName = "testFileLogger"; final String loggerPath = "virtualhostlogger/" + VHN_WITHOUT_VH + "/" + virtualHostName + "/" + loggerName; getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); createVirtualHost(VHN_WITHOUT_VH, virtualHostName); Map<String, Object> attributes = new HashMap<>(); attributes.put(VirtualHostLogger.NAME, loggerName); attributes.put(ConfiguredObject.TYPE, VirtualHostFileLogger.TYPE); getRestTestHelper().submitRequest("virtualhostlogger/" + VHN_WITHOUT_VH + "/" + virtualHostName, "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_OK); getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_OK); getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_FORBIDDEN); } /* === Utility Methods === */ private int createVirtualHost(final String testVirtualHostNode, String virtualHostName) throws Exception { Map<String, Object> data = new HashMap<>(); data.put(VirtualHost.NAME, virtualHostName); data.put(VirtualHost.TYPE, ProvidedStoreVirtualHostImpl.VIRTUAL_HOST_TYPE); return getRestTestHelper().submitRequest("virtualhost/" + testVirtualHostNode + "/" + virtualHostName, "PUT", data); } private void assertVirtualHostDoesNotExist(final String virtualHostNodeName, String virtualHostName) throws Exception { assertVirtualHostExistence(virtualHostNodeName, virtualHostName, false); } private void assertVirtualHostExists(final String virtualHostNodeName, String virtualHostName) throws Exception { assertVirtualHostExistence(virtualHostNodeName, virtualHostName, true); } private void assertVirtualHostExistence(final String virtualHostNodeName, String virtualHostName, boolean exists) throws Exception { String path = "virtualhost/" + virtualHostNodeName + "/" + virtualHostName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private String getStoreLocation(String hostName) { return new File(TMP_FOLDER, "store-" + hostName + "-" + System.currentTimeMillis()).getAbsolutePath(); } }
pkdevbox/qpid-java
systests/src/test/java/org/apache/qpid/systest/rest/acl/VirtualHostACLTest.java
213,273
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sling.feature.extension.apiregions.api.artifacts; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import javax.json.Json; import org.apache.sling.feature.ArtifactId; import org.apache.sling.feature.Extension; import org.apache.sling.feature.ExtensionState; import org.apache.sling.feature.ExtensionType; import org.junit.Test; import org.osgi.framework.Version; import org.osgi.framework.VersionRange; public class VersionRuleTest { @Test public void testClear() { final VersionRule entity = new VersionRule(); entity.getAttributes().put("a", Json.createValue(5)); entity.setAllowedVersionRanges(new VersionRange[] {new VersionRange("1.0")}); entity.setDeniedVersionRanges(new VersionRange[] {new VersionRange("3.0")}); entity.setMode(Mode.LENIENT); entity.setMessage("msg"); entity.setArtifactId(ArtifactId.parse("g:a:1")); entity.clear(); assertTrue(entity.getAttributes().isEmpty()); assertNull(entity.getAllowedVersionRanges()); assertNull(entity.getDeniedVersionRanges()); assertNull(entity.getMessage()); assertNull(entity.getArtifactId()); assertNull(entity.getMode()); } @Test public void testFromJSONObject() throws IOException { final Extension ext = new Extension(ExtensionType.JSON, "a", ExtensionState.OPTIONAL); ext.setJSON("{ \"mode\" : \"LENIENT\", \"message\" : \"msg\", \"artifact-id\":\"g:a:1\"," + "\"allowed-version-ranges\":[\"1.0\"],\"denied-version-ranges\":[\"2.0\"]}"); final VersionRule entity = new VersionRule(); entity.fromJSONObject(ext.getJSONStructure().asJsonObject()); assertEquals(Mode.LENIENT, entity.getMode()); assertEquals("msg", entity.getMessage()); assertEquals(ArtifactId.parse("g:a:1"), entity.getArtifactId()); assertEquals(1, entity.getAllowedVersionRanges().length); assertEquals(new VersionRange("1.0"), entity.getAllowedVersionRanges()[0]); assertEquals(1, entity.getDeniedVersionRanges().length); assertEquals(new VersionRange("2.0"), entity.getDeniedVersionRanges()[0]); } @Test public void testToJSONObject() throws IOException { final VersionRule entity = new VersionRule(); entity.setMode(Mode.LENIENT); entity.setMessage("msg"); entity.setArtifactId(ArtifactId.parse("g:a:1")); entity.setAllowedVersionRanges(new VersionRange[] {new VersionRange("1.0.0")}); entity.setDeniedVersionRanges(new VersionRange[] {new VersionRange("2.0.0")}); final Extension ext = new Extension(ExtensionType.JSON, "a", ExtensionState.OPTIONAL); ext.setJSON("{ \"mode\" : \"LENIENT\", \"artifact-id\":\"g:a:1\", \"message\" : \"msg\"," + "\"allowed-version-ranges\":[\"1.0.0\"],\"denied-version-ranges\":[\"2.0.0\"]}"); assertEquals(ext.getJSONStructure().asJsonObject(), entity.toJSONObject()); } @Test public void testIsAllowedNoRanges() { final VersionRule entity = new VersionRule(); assertFalse(entity.isAllowed(new Version("1.0"))); assertFalse(entity.isAllowed(new Version("1.3"))); assertFalse(entity.isAllowed(new Version("2.1"))); } @Test public void testIsAllowedAllowedRange() { final VersionRule entity = new VersionRule(); entity.setAllowedVersionRanges(new VersionRange[] {new VersionRange("[1.2, 2)")}); assertFalse(entity.isAllowed(new Version("1.0"))); assertTrue(entity.isAllowed(new Version("1.3"))); assertFalse(entity.isAllowed(new Version("2.1"))); } @Test public void testIsAllowedAllowedDenied() { final VersionRule entity = new VersionRule(); entity.setAllowedVersionRanges(new VersionRange[] {new VersionRange("[1.2, 2)")}); entity.setDeniedVersionRanges(new VersionRange[] {new VersionRange("[1.3.1,1.3.1]")}); assertFalse(entity.isAllowed(new Version("1.0"))); assertTrue(entity.isAllowed(new Version("1.3"))); assertFalse(entity.isAllowed(new Version("1.3.1"))); assertTrue(entity.isAllowed(new Version("1.3.2"))); assertFalse(entity.isAllowed(new Version("2.1"))); } }
JLLeitschuh/apache__sling-org-apache-sling-feature-extension-apiregions
src/test/java/org/apache/sling/feature/extension/apiregions/api/artifacts/VersionRuleTest.java
213,274
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.qpid.systest.rest.acl; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.qpid.server.logging.logback.BrokerFileLogger; import org.apache.qpid.server.logging.logback.BrokerMemoryLogger; import org.apache.qpid.server.logging.logback.BrokerNameAndLevelLogInclusionRule; import org.apache.qpid.server.management.plugin.HttpManagement; import org.apache.qpid.server.management.plugin.servlet.rest.AbstractServlet; import org.apache.qpid.server.model.AccessControlProvider; import org.apache.qpid.server.model.AuthenticationProvider; import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.BrokerLogger; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.ExternalFileBasedAuthenticationManager; import org.apache.qpid.server.model.GroupProvider; import org.apache.qpid.server.model.KeyStore; import org.apache.qpid.server.model.Port; import org.apache.qpid.server.model.Protocol; import org.apache.qpid.server.model.State; import org.apache.qpid.server.model.TrustStore; import org.apache.qpid.server.model.adapter.FileBasedGroupProvider; import org.apache.qpid.server.model.adapter.FileBasedGroupProviderImpl; import org.apache.qpid.server.security.AllowAllAccessControlProvider; import org.apache.qpid.server.security.FileKeyStore; import org.apache.qpid.server.security.FileTrustStore; import org.apache.qpid.server.security.access.plugins.AclFileAccessControlProvider; import org.apache.qpid.server.security.acl.AbstractACLTestCase; import org.apache.qpid.server.security.auth.manager.AnonymousAuthenticationManager; import org.apache.qpid.server.security.auth.manager.PlainPasswordDatabaseAuthenticationManager; import org.apache.qpid.systest.rest.QpidRestTestCase; import org.apache.qpid.test.utils.TestBrokerConfiguration; import org.apache.qpid.test.utils.TestFileUtils; import org.apache.qpid.test.utils.TestSSLConstants; public class BrokerACLTest extends QpidRestTestCase { private static final String ALLOWED_USER = "user1"; private static final String DENIED_USER = "user2"; private String _secondaryAclFileContent = ""; @Override protected void customizeConfiguration() throws Exception { super.customizeConfiguration(); final TestBrokerConfiguration defaultBrokerConfiguration = getDefaultBrokerConfiguration(); defaultBrokerConfiguration.configureTemporaryPasswordFile(ALLOWED_USER, DENIED_USER); AbstractACLTestCase.writeACLFileUtil(this, "ACL ALLOW-LOG ALL ACCESS MANAGEMENT", "ACL ALLOW-LOG " + ALLOWED_USER + " CONFIGURE BROKER", "ACL DENY-LOG " + DENIED_USER + " CONFIGURE BROKER", "ACL ALLOW-LOG " + ALLOWED_USER + " ACCESS_LOGS BROKER", "ACL DENY-LOG " + DENIED_USER + " ACCESS_LOGS BROKER", "ACL DENY-LOG ALL ALL"); _secondaryAclFileContent = "ACL ALLOW-LOG ALL ACCESS MANAGEMENT\n" + "ACL ALLOW-LOG " + ALLOWED_USER + " CONFIGURE BROKER\n" + "ACL DENY-LOG " + DENIED_USER + " CONFIGURE BROKER\n" + "ACL DENY-LOG ALL ALL"; } /* === AuthenticationProvider === */ public void testCreateAuthenticationProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String authenticationProviderName = getTestName(); int responseCode = createAuthenticationProvider(authenticationProviderName); assertEquals("Provider creation should be allowed", 201, responseCode); assertAuthenticationProviderExists(authenticationProviderName); } public void testCreateAuthenticationProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String authenticationProviderName = getTestName(); int responseCode = createAuthenticationProvider(authenticationProviderName); assertEquals("Provider creation should be denied", 403, responseCode); assertAuthenticationProviderDoesNotExist(authenticationProviderName); } public void testDeleteAuthenticationProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String providerName = getTestName(); int responseCode = createAuthenticationProvider(providerName); assertEquals("Provider creation should be allowed", 201, responseCode); assertAuthenticationProviderExists(providerName); responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "DELETE"); assertEquals("Provider deletion should be allowed", 200, responseCode); assertAuthenticationProviderDoesNotExist(TEST2_VIRTUALHOST); } public void testDeleteAuthenticationProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String providerName = getTestName(); int responseCode = createAuthenticationProvider(providerName); assertEquals("Provider creation should be allowed", 201, responseCode); assertAuthenticationProviderExists(providerName); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "DELETE"); assertEquals("Provider deletion should be denied", 403, responseCode); assertAuthenticationProviderExists(providerName); } public void testSetAuthenticationProviderAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String providerName = TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER; assertAuthenticationProviderExists(providerName); Map<String, Object> attributes = new HashMap<>(); attributes.put(AuthenticationProvider.NAME, providerName); attributes.put(AuthenticationProvider.TYPE, PlainPasswordDatabaseAuthenticationManager.PROVIDER_TYPE); attributes.put(AuthenticationProvider.STATE, State.DELETED.name()); int responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "PUT", attributes); assertEquals("Setting of provider attribites should be allowed", 200, responseCode); } public void testSetAuthenticationProviderAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String providerName = TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER; Map<String, Object> providerData = getRestTestHelper().getJsonAsMap("authenticationprovider/" + providerName); File file = TestFileUtils.createTempFile(this, ".users", "guest:guest\n" + ALLOWED_USER + ":" + ALLOWED_USER + "\n" + DENIED_USER + ":" + DENIED_USER); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AuthenticationProvider.NAME, providerName); attributes.put(AuthenticationProvider.TYPE, AnonymousAuthenticationManager.PROVIDER_TYPE); attributes.put(ExternalFileBasedAuthenticationManager.PATH, file.getAbsolutePath()); int responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "PUT", attributes); assertEquals("Setting of provider attribites should be allowed", 403, responseCode); Map<String, Object> provider = getRestTestHelper().getJsonAsMap("authenticationprovider/" + providerName); assertEquals("Unexpected STORE_URL attribute value", providerData.get(ExternalFileBasedAuthenticationManager.PATH), provider.get(ExternalFileBasedAuthenticationManager.PATH)); } /* === Port === */ public void testCreatePortAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String portName = getTestName(); int responseCode = createPort(portName); assertEquals("Port creation should be allowed", 201, responseCode); assertPortExists(portName); } public void testCreatePortDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String portName = getTestName(); int responseCode = createPort(portName); assertEquals("Port creation should be denied", 403, responseCode); assertPortDoesNotExist(portName); } public void testDeletePortDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String portName = TestBrokerConfiguration.ENTRY_NAME_AMQP_PORT; assertPortExists(portName); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); int responseCode = getRestTestHelper().submitRequest("port/" + portName, "DELETE"); assertEquals("Port deletion should be denied", 403, responseCode); assertPortExists(portName); } public void testDeletePortAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String portName = TestBrokerConfiguration.ENTRY_NAME_AMQP_PORT; assertPortExists(portName); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); int responseCode = getRestTestHelper().submitRequest("port/" + portName, "DELETE"); assertEquals("Port deletion should be allowed", 200, responseCode); assertPortDoesNotExist(portName); } public void testSetPortAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String portName = getTestName(); int responseCode = createPort(portName); assertEquals("Port creation should be allowed", 201, responseCode); assertPortExists(portName); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(Port.NAME, portName); attributes.put(Port.PROTOCOLS, Arrays.asList(Protocol.AMQP_0_9)); attributes.put(Port.AUTHENTICATION_PROVIDER, TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER); responseCode = getRestTestHelper().submitRequest("port/" + portName, "PUT", attributes); assertEquals("Setting of port attribites should be denied", 403, responseCode); Map<String, Object> port = getRestTestHelper().getJsonAsMap("port/" + portName); assertEquals("Unexpected authentication provider attribute value", TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER, port.get(Port.AUTHENTICATION_PROVIDER)); } /* === KeyStore === */ public void testCreateKeyStoreAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, TestSSLConstants.CERT_ALIAS_APP1); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); } public void testCreateKeyStoreDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String keyStoreName = getTestName(); assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, TestSSLConstants.CERT_ALIAS_APP1); assertEquals("keyStore creation should be allowed", 403, responseCode); assertKeyStoreExistence(keyStoreName, false); } public void testDeleteKeyStoreDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, TestSSLConstants.CERT_ALIAS_APP1); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "DELETE"); assertEquals("keystore deletion should be denied", 403, responseCode); assertKeyStoreExistence(keyStoreName, true); } public void testDeleteKeyStoreAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, TestSSLConstants.CERT_ALIAS_APP1); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "DELETE"); assertEquals("keystore deletion should be allowed", 200, responseCode); assertKeyStoreExistence(keyStoreName, false); } public void testSetKeyStoreAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); String initialCertAlias = TestSSLConstants.CERT_ALIAS_APP1; String updatedCertAlias = TestSSLConstants.CERT_ALIAS_APP2; assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, initialCertAlias); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); Map<String, Object> keyStore = getRestTestHelper().getJsonAsMap("keystore/" + keyStoreName); assertEquals("Unexpected certificateAlias attribute value", initialCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS)); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(KeyStore.NAME, keyStoreName); attributes.put(FileKeyStore.CERTIFICATE_ALIAS, updatedCertAlias); responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "PUT", attributes); assertEquals("Setting of keystore attributes should be allowed", 200, responseCode); keyStore = getRestTestHelper().getJsonAsMap("keystore/" + keyStoreName); assertEquals("Unexpected certificateAlias attribute value", updatedCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS)); } public void testSetKeyStoreAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); String initialCertAlias = TestSSLConstants.CERT_ALIAS_APP1; String updatedCertAlias = TestSSLConstants.CERT_ALIAS_APP2; assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, initialCertAlias); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); Map<String, Object> keyStore = getRestTestHelper().getJsonAsMap("keystore/" + keyStoreName); assertEquals("Unexpected certificateAlias attribute value", initialCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS)); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(KeyStore.NAME, keyStoreName); attributes.put(FileKeyStore.CERTIFICATE_ALIAS, updatedCertAlias); responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "PUT", attributes); assertEquals("Setting of keystore attributes should be denied", 403, responseCode); keyStore = getRestTestHelper().getJsonAsMap("keystore/" + keyStoreName); assertEquals("Unexpected certificateAlias attribute value", initialCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS)); } /* === TrustStore === */ public void testCreateTrustStoreAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, false); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); } public void testCreateTrustStoreDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String trustStoreName = getTestName(); assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, false); assertEquals("trustStore creation should be allowed", 403, responseCode); assertTrustStoreExistence(trustStoreName, false); } public void testDeleteTrustStoreDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, false); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "DELETE"); assertEquals("truststore deletion should be denied", 403, responseCode); assertTrustStoreExistence(trustStoreName, true); } public void testDeleteTrustStoreAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, false); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "DELETE"); assertEquals("truststore deletion should be allowed", 200, responseCode); assertTrustStoreExistence(trustStoreName, false); } public void testSetTrustStoreAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); boolean initialPeersOnly = false; boolean updatedPeersOnly = true; assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, initialPeersOnly); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); Map<String, Object> trustStore = getRestTestHelper().getJsonAsMap("truststore/" + trustStoreName); assertEquals("Unexpected peersOnly attribute value", initialPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY)); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(TrustStore.NAME, trustStoreName); attributes.put(FileTrustStore.PEERS_ONLY, updatedPeersOnly); responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "PUT", attributes); assertEquals("Setting of truststore attributes should be allowed", 200, responseCode); trustStore = getRestTestHelper().getJsonAsMap("truststore/" + trustStoreName); assertEquals("Unexpected peersOnly attribute value", updatedPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY)); } public void testSetTrustStoreAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); boolean initialPeersOnly = false; boolean updatedPeersOnly = true; assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, initialPeersOnly); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); Map<String, Object> trustStore = getRestTestHelper().getJsonAsMap("truststore/" + trustStoreName); assertEquals("Unexpected peersOnly attribute value", initialPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY)); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(TrustStore.NAME, trustStoreName); attributes.put(FileTrustStore.PEERS_ONLY, updatedPeersOnly); responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "PUT", attributes); assertEquals("Setting of truststore attributes should be denied", 403, responseCode); trustStore = getRestTestHelper().getJsonAsMap("truststore/" + trustStoreName); assertEquals("Unexpected peersOnly attribute value", initialPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY)); } /* === Broker === */ public void testSetBrokerAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> brokerAttributes = getRestTestHelper().getJsonAsMap("broker"); assertEquals("Unexpected description", null, brokerAttributes.get(Broker.DESCRIPTION)); String descriptionValue = "test description"; getRestTestHelper().submitRequest("broker", "PUT", Collections.singletonMap(Broker.DESCRIPTION, descriptionValue), 200); brokerAttributes = getRestTestHelper().getJsonAsMap("broker"); assertEquals("Unexpected description", descriptionValue, brokerAttributes.get(Broker.DESCRIPTION)); } public void testSetBrokerAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> brokerAttributes = getRestTestHelper().getJsonAsMap("broker"); assertEquals("Unexpected description", null, brokerAttributes.get(Broker.DESCRIPTION)); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest("broker", "PUT", Collections.singletonMap(Broker.DESCRIPTION, "test description"), 403); brokerAttributes = getRestTestHelper().getJsonAsMap("broker"); assertEquals("Unexpected description", null, brokerAttributes.get(Broker.DESCRIPTION)); } /* === GroupProvider === */ public void testCreateGroupProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); } public void testCreateGroupProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be denied", 403, responseCode); assertGroupProviderExistence(groupProviderName, false); } public void testDeleteGroupProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "DELETE"); assertEquals("Group provider deletion should be denied", 403, responseCode); assertGroupProviderExistence(groupProviderName, true); } public void testDeleteGroupProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "DELETE"); assertEquals("Group provider deletion should be allowed", 200, responseCode); assertGroupProviderExistence(groupProviderName, false); } public void testSetGroupProviderAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(GroupProvider.NAME, groupProviderName); attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); attributes.put(FileBasedGroupProvider.PATH, "/path/to/file"); responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "PUT", attributes); assertEquals("Setting of group provider attributes should be allowed but not supported", AbstractServlet.SC_UNPROCESSABLE_ENTITY, responseCode); } public void testSetGroupProviderAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(GroupProvider.NAME, groupProviderName); attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); attributes.put(FileBasedGroupProvider.PATH, "/path/to/file"); responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "PUT", attributes); assertEquals("Setting of group provider attributes should be denied", 403, responseCode); } /* === AccessControlProvider === */ public void testCreateAccessControlProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String accessControlProviderName = getTestName(); assertAccessControlProviderExistence(accessControlProviderName, false); int responseCode = createAccessControlProvider(accessControlProviderName); assertEquals("Access control provider creation should be denied", 403, responseCode); assertAccessControlProviderExistence(accessControlProviderName, false); } public void testDeleteAccessControlProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "DELETE"); assertEquals("Access control provider deletion should be denied", 403, responseCode); assertAccessControlProviderExistence(accessControlProviderName, true); } public void testDeleteAccessControlProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); // add a second, low priority AllowAll provider Map<String,Object> attributes = new HashMap<>(); final String secondProviderName = "AllowAll"; attributes.put(ConfiguredObject.NAME, secondProviderName); attributes.put(ConfiguredObject.TYPE, AllowAllAccessControlProvider.ALLOW_ALL); attributes.put(AccessControlProvider.PRIORITY, 9999); int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + secondProviderName, "PUT", attributes); assertEquals("Access control provider creation should be allowed", 201, responseCode); responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "DELETE"); assertEquals("Access control provider deletion should be allowed", 200, responseCode); assertAccessControlProviderExistence(accessControlProviderName, false); } public void testSetAccessControlProviderAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); File aclFile = TestFileUtils.createTempFile(this, ".acl", "ACL ALLOW all all"); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AccessControlProvider.NAME, accessControlProviderName); attributes.put(FileBasedGroupProvider.PATH, aclFile.getAbsolutePath()); int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes); assertEquals("Setting of access control provider attributes should be allowed", 200, responseCode); } public void testSetAccessControlProviderAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(GroupProvider.NAME, accessControlProviderName); attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); attributes.put(FileBasedGroupProvider.PATH, "/path/to/file"); int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes); assertEquals("Setting of access control provider attributes should be denied", 403, responseCode); } /* === HTTP management === */ public void testSetHttpManagementAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(HttpManagement.NAME, TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT); attributes.put(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.TIME_OUT, 10000); int responseCode = getRestTestHelper().submitRequest( "plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT, "PUT", attributes); assertEquals("Setting of http management should be allowed", 200, responseCode); Map<String, Object> details = getRestTestHelper().getJsonAsMap("plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT); assertEquals("Unexpected session timeout", 10000, details.get(HttpManagement.TIME_OUT)); assertEquals("Unexpected http basic auth enabled", true, details.get(HttpManagement.HTTP_BASIC_AUTHENTICATION_ENABLED)); assertEquals("Unexpected https basic auth enabled", false, details.get(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED)); assertEquals("Unexpected http sasl auth enabled", false, details.get(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED)); assertEquals("Unexpected https sasl auth enabled", false, details.get(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED)); } public void testSetHttpManagementAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(HttpManagement.NAME, TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT); attributes.put(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.TIME_OUT, 10000); int responseCode = getRestTestHelper().submitRequest( "plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT, "PUT", attributes); assertEquals("Setting of http management should be denied", 403, responseCode); Map<String, Object> details = getRestTestHelper().getJsonAsMap("plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT); assertEquals("Unexpected session timeout", HttpManagement.DEFAULT_TIMEOUT_IN_SECONDS, details.get(HttpManagement.TIME_OUT)); assertEquals("Unexpected http basic auth enabled", true, details.get(HttpManagement.HTTP_BASIC_AUTHENTICATION_ENABLED)); assertEquals("Unexpected https basic auth enabled", true, details.get(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED)); assertEquals("Unexpected http sasl auth enabled", true, details.get(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED)); assertEquals("Unexpected https sasl auth enabled", true, details.get(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED)); } /* === Broker Logger === */ public void testCreateBrokerLoggerAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerLogger.NAME, "testLogger1"); attributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "testLogger2"); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest("brokerlogger/testLogger2", "GET", HttpServletResponse.SC_NOT_FOUND); } public void testDeleteBrokerLoggerAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerLogger.NAME, "testLogger1"); attributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "DELETE", null, HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "DELETE", null, HttpServletResponse.SC_OK); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_NOT_FOUND); } public void testDownloadBrokerLoggerFileAllowedDenied() throws Exception { final String loggerName = "testFileLogger"; final String loggerPath = "brokerlogger/" + loggerName; getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerLogger.NAME, loggerName); attributes.put(ConfiguredObject.TYPE, BrokerFileLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_OK); getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_OK); getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_FORBIDDEN); } public void testViewMemoryLoggerEntriesAllowedDenied() throws Exception { final String loggerName = "testMemoryLogger"; final String loggerPath = "brokerlogger/" + loggerName; getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerLogger.NAME, loggerName); attributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest(loggerPath + "/getLogEntries?lastLogId=0", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest(loggerPath + "/getLogEntries?lastLogId=0", "GET", HttpServletResponse.SC_FORBIDDEN); } /* === Broker Log Inclusion Rules === */ public void testCreateBrokerLoggerRuleAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> loggerAttributes = new HashMap<>(); loggerAttributes.put(BrokerLogger.NAME, "testLogger1"); loggerAttributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", loggerAttributes, HttpServletResponse.SC_CREATED); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1"); attributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "DEBUG"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule2"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", attributes, HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule2", "GET", HttpServletResponse.SC_NOT_FOUND); } public void testUpdateBrokerLoggerRuleAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> loggerAttributes = new HashMap<>(); loggerAttributes.put(BrokerLogger.NAME, "testLogger1"); loggerAttributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", loggerAttributes, HttpServletResponse.SC_CREATED); Map<String, Object> ruleAttributes = new HashMap<>(); ruleAttributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1"); ruleAttributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); ruleAttributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "INFO"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", ruleAttributes, HttpServletResponse.SC_CREATED); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1"); attributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "DEBUG"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "PUT", attributes, HttpServletResponse.SC_OK); Map<String,Object> resultAfterUpdate = getRestTestHelper().getJsonAsMap("brokerloginclusionrule/testLogger1/rule1"); assertEquals("Log level was not changed", "DEBUG", resultAfterUpdate.get(BrokerNameAndLevelLogInclusionRule.LEVEL)); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "INFO"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "PUT", attributes, HttpServletResponse.SC_FORBIDDEN); Map<String,Object> resultAfterDeniedUpdate = getRestTestHelper().getJsonAsMap("brokerloginclusionrule/testLogger1/rule1"); assertEquals("Log level was changed by not allowed user", "DEBUG", resultAfterDeniedUpdate.get(BrokerNameAndLevelLogInclusionRule.LEVEL)); } public void testDeleteBrokerLoggerRuleAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> loggerAttributes = new HashMap<>(); loggerAttributes.put(BrokerLogger.NAME, "testLogger1"); loggerAttributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", loggerAttributes, HttpServletResponse.SC_CREATED); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1"); attributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "DEBUG"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "DELETE", null, HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "DELETE", null, HttpServletResponse.SC_OK); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_NOT_FOUND); } /* === Utility Methods === */ private int createPort(String portName) throws Exception { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(Port.NAME, portName); attributes.put(Port.PORT, 0); attributes.put(Port.AUTHENTICATION_PROVIDER, TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER); return getRestTestHelper().submitRequest("port/" + portName, "PUT", attributes); } private void assertPortExists(String portName) throws Exception { assertPortExistence(portName, true); } private void assertPortDoesNotExist(String portName) throws Exception { assertPortExistence(portName, false); } private void assertPortExistence(String portName, boolean exists) throws Exception { String path = "port/" + portName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private void assertKeyStoreExistence(String keyStoreName, boolean exists) throws Exception { String path = "keystore/" + keyStoreName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private void assertTrustStoreExistence(String trustStoreName, boolean exists) throws Exception { String path = "truststore/" + trustStoreName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private int createAuthenticationProvider(String authenticationProviderName) throws Exception { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AuthenticationProvider.NAME, authenticationProviderName); attributes.put(AuthenticationProvider.TYPE, AnonymousAuthenticationManager.PROVIDER_TYPE); return getRestTestHelper().submitRequest("authenticationprovider/" + authenticationProviderName, "PUT", attributes); } private void assertAuthenticationProviderDoesNotExist(String authenticationProviderName) throws Exception { assertAuthenticationProviderExistence(authenticationProviderName, false); } private void assertAuthenticationProviderExists(String authenticationProviderName) throws Exception { assertAuthenticationProviderExistence(authenticationProviderName, true); } private void assertAuthenticationProviderExistence(String authenticationProviderName, boolean exists) throws Exception { String path = "authenticationprovider/" + authenticationProviderName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private int createKeyStore(String name, String certAlias) throws IOException { Map<String, Object> keyStoreAttributes = new HashMap<String, Object>(); keyStoreAttributes.put(KeyStore.NAME, name); keyStoreAttributes.put(FileKeyStore.STORE_URL, TestSSLConstants.KEYSTORE); keyStoreAttributes.put(FileKeyStore.PASSWORD, TestSSLConstants.KEYSTORE_PASSWORD); keyStoreAttributes.put(FileKeyStore.CERTIFICATE_ALIAS, certAlias); return getRestTestHelper().submitRequest("keystore/" + name, "PUT", keyStoreAttributes); } private int createTrustStore(String name, boolean peersOnly) throws IOException { Map<String, Object> trustStoreAttributes = new HashMap<String, Object>(); trustStoreAttributes.put(TrustStore.NAME, name); trustStoreAttributes.put(FileTrustStore.STORE_URL, TestSSLConstants.KEYSTORE); trustStoreAttributes.put(FileTrustStore.PASSWORD, TestSSLConstants.KEYSTORE_PASSWORD); trustStoreAttributes.put(FileTrustStore.PEERS_ONLY, peersOnly); return getRestTestHelper().submitRequest("truststore/" + name, "PUT", trustStoreAttributes); } private void assertGroupProviderExistence(String groupProviderName, boolean exists) throws Exception { String path = "groupprovider/" + groupProviderName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private int createGroupProvider(String groupProviderName) throws Exception { File file = TestFileUtils.createTempFile(this, ".groups"); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(GroupProvider.NAME, groupProviderName); attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); attributes.put(FileBasedGroupProvider.PATH, file.getAbsoluteFile()); return getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "PUT", attributes); } private void assertAccessControlProviderExistence(String accessControlProviderName, boolean exists) throws Exception { String path = "accesscontrolprovider/" + accessControlProviderName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private int createAccessControlProvider(String accessControlProviderName) throws Exception { File file = TestFileUtils.createTempFile(this, ".acl", _secondaryAclFileContent); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AccessControlProvider.NAME, accessControlProviderName); attributes.put(AccessControlProvider.TYPE, AclFileAccessControlProvider.ACL_FILE_PROVIDER_TYPE); attributes.put(AclFileAccessControlProvider.PATH, file.getAbsoluteFile()); return getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes); } }
acidburn0zzz/qpid-broker-j
systests/src/test/java/org/apache/qpid/systest/rest/acl/BrokerACLTest.java
213,275
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.qpid.systest.rest.acl; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.qpid.server.logging.BrokerFileLogger; import org.apache.qpid.server.logging.BrokerMemoryLogger; import org.apache.qpid.server.logging.BrokerNameAndLevelLogInclusionRule; import org.apache.qpid.server.management.plugin.servlet.rest.RestServlet; import org.apache.qpid.server.model.BrokerLogger; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.management.plugin.HttpManagement; import org.apache.qpid.server.model.AccessControlProvider; import org.apache.qpid.server.model.AuthenticationProvider; import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.ExternalFileBasedAuthenticationManager; import org.apache.qpid.server.model.GroupProvider; import org.apache.qpid.server.model.KeyStore; import org.apache.qpid.server.model.Plugin; import org.apache.qpid.server.model.Port; import org.apache.qpid.server.model.Protocol; import org.apache.qpid.server.model.TrustStore; import org.apache.qpid.server.model.adapter.FileBasedGroupProvider; import org.apache.qpid.server.model.adapter.FileBasedGroupProviderImpl; import org.apache.qpid.server.security.FileKeyStore; import org.apache.qpid.server.security.FileTrustStore; import org.apache.qpid.server.security.access.FileAccessControlProviderConstants; import org.apache.qpid.server.security.acl.AbstractACLTestCase; import org.apache.qpid.server.security.auth.manager.AnonymousAuthenticationManager; import org.apache.qpid.server.security.auth.manager.PlainPasswordDatabaseAuthenticationManager; import org.apache.qpid.systest.rest.QpidRestTestCase; import org.apache.qpid.test.utils.TestBrokerConfiguration; import org.apache.qpid.test.utils.TestFileUtils; import org.apache.qpid.test.utils.TestSSLConstants; public class BrokerACLTest extends QpidRestTestCase { private static final String ALLOWED_USER = "user1"; private static final String DENIED_USER = "user2"; private String _secondaryAclFileContent = ""; @Override protected void customizeConfiguration() throws IOException { super.customizeConfiguration(); getRestTestHelper().configureTemporaryPasswordFile(this, ALLOWED_USER, DENIED_USER); AbstractACLTestCase.writeACLFileUtil(this, "ACL ALLOW-LOG ALL ACCESS MANAGEMENT", "ACL ALLOW-LOG " + ALLOWED_USER + " CONFIGURE BROKER", "ACL DENY-LOG " + DENIED_USER + " CONFIGURE BROKER", "ACL ALLOW-LOG " + ALLOWED_USER + " ACCESS_LOGS BROKER", "ACL DENY-LOG " + DENIED_USER + " ACCESS_LOGS BROKER", "ACL DENY-LOG ALL ALL"); _secondaryAclFileContent = "ACL ALLOW-LOG ALL ACCESS MANAGEMENT\n" + "ACL ALLOW-LOG " + ALLOWED_USER + " CONFIGURE BROKER\n" + "ACL DENY-LOG " + DENIED_USER + " CONFIGURE BROKER\n" + "ACL DENY-LOG ALL ALL"; getBrokerConfiguration().setObjectAttribute(Plugin.class, TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT, HttpManagement.HTTP_BASIC_AUTHENTICATION_ENABLED, true); } /* === AuthenticationProvider === */ public void testCreateAuthenticationProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String authenticationProviderName = getTestName(); int responseCode = createAuthenticationProvider(authenticationProviderName); assertEquals("Provider creation should be allowed", 201, responseCode); assertAuthenticationProviderExists(authenticationProviderName); } public void testCreateAuthenticationProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String authenticationProviderName = getTestName(); int responseCode = createAuthenticationProvider(authenticationProviderName); assertEquals("Provider creation should be denied", 403, responseCode); assertAuthenticationProviderDoesNotExist(authenticationProviderName); } public void testDeleteAuthenticationProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String providerName = getTestName(); int responseCode = createAuthenticationProvider(providerName); assertEquals("Provider creation should be allowed", 201, responseCode); assertAuthenticationProviderExists(providerName); responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "DELETE"); assertEquals("Provider deletion should be allowed", 200, responseCode); assertAuthenticationProviderDoesNotExist(TEST2_VIRTUALHOST); } public void testDeleteAuthenticationProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String providerName = getTestName(); int responseCode = createAuthenticationProvider(providerName); assertEquals("Provider creation should be allowed", 201, responseCode); assertAuthenticationProviderExists(providerName); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "DELETE"); assertEquals("Provider deletion should be denied", 403, responseCode); assertAuthenticationProviderExists(providerName); } public void testSetAuthenticationProviderAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String providerName = TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER; assertAuthenticationProviderExists(providerName); File file = TestFileUtils.createTempFile(this, ".users", "guest:guest\n" + ALLOWED_USER + ":" + ALLOWED_USER + "\n" + DENIED_USER + ":" + DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AuthenticationProvider.NAME, providerName); attributes.put(AuthenticationProvider.TYPE, PlainPasswordDatabaseAuthenticationManager.PROVIDER_TYPE); attributes.put(ExternalFileBasedAuthenticationManager.PATH, file.getAbsolutePath()); int responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "PUT", attributes); assertEquals("Setting of provider attribites should be allowed", 200, responseCode); } public void testSetAuthenticationProviderAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String providerName = TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER; Map<String, Object> providerData = getRestTestHelper().getJsonAsSingletonList("authenticationprovider/" + providerName); File file = TestFileUtils.createTempFile(this, ".users", "guest:guest\n" + ALLOWED_USER + ":" + ALLOWED_USER + "\n" + DENIED_USER + ":" + DENIED_USER); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AuthenticationProvider.NAME, providerName); attributes.put(AuthenticationProvider.TYPE, AnonymousAuthenticationManager.PROVIDER_TYPE); attributes.put(ExternalFileBasedAuthenticationManager.PATH, file.getAbsolutePath()); int responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "PUT", attributes); assertEquals("Setting of provider attribites should be allowed", 403, responseCode); Map<String, Object> provider = getRestTestHelper().getJsonAsSingletonList("authenticationprovider/" + providerName); assertEquals("Unexpected STORE_URL attribute value", providerData.get(ExternalFileBasedAuthenticationManager.PATH), provider.get(ExternalFileBasedAuthenticationManager.PATH)); } /* === Port === */ public void testCreatePortAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String portName = getTestName(); int responseCode = createPort(portName); assertEquals("Port creation should be allowed", 201, responseCode); assertPortExists(portName); } public void testCreatePortDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String portName = getTestName(); int responseCode = createPort(portName); assertEquals("Port creation should be denied", 403, responseCode); assertPortDoesNotExist(portName); } public void testDeletePortDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String portName = TestBrokerConfiguration.ENTRY_NAME_AMQP_PORT; assertPortExists(portName); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); int responseCode = getRestTestHelper().submitRequest("port/" + portName, "DELETE"); assertEquals("Port deletion should be denied", 403, responseCode); assertPortExists(portName); } public void testDeletePortAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String portName = TestBrokerConfiguration.ENTRY_NAME_AMQP_PORT; assertPortExists(portName); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); int responseCode = getRestTestHelper().submitRequest("port/" + portName, "DELETE"); assertEquals("Port deletion should be allowed", 200, responseCode); assertPortDoesNotExist(portName); } public void testSetPortAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String portName = getTestName(); int responseCode = createPort(portName); assertEquals("Port creation should be allowed", 201, responseCode); assertPortExists(portName); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(Port.NAME, portName); attributes.put(Port.PROTOCOLS, Arrays.asList(Protocol.AMQP_0_9)); attributes.put(Port.AUTHENTICATION_PROVIDER, TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER); responseCode = getRestTestHelper().submitRequest("port/" + portName, "PUT", attributes); assertEquals("Setting of port attribites should be denied", 403, responseCode); Map<String, Object> port = getRestTestHelper().getJsonAsSingletonList("port/" + portName); assertEquals("Unexpected authentication provider attribute value", TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER, port.get(Port.AUTHENTICATION_PROVIDER)); } /* === KeyStore === */ public void testCreateKeyStoreAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, "app1"); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); } public void testCreateKeyStoreDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String keyStoreName = getTestName(); assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, "app1"); assertEquals("keyStore creation should be allowed", 403, responseCode); assertKeyStoreExistence(keyStoreName, false); } public void testDeleteKeyStoreDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, "app1"); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "DELETE"); assertEquals("keystore deletion should be denied", 403, responseCode); assertKeyStoreExistence(keyStoreName, true); } public void testDeleteKeyStoreAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, "app1"); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "DELETE"); assertEquals("keystore deletion should be allowed", 200, responseCode); assertKeyStoreExistence(keyStoreName, false); } public void testSetKeyStoreAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); String initialCertAlias = "app1"; String updatedCertAlias = "app2"; assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, initialCertAlias); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); Map<String, Object> keyStore = getRestTestHelper().getJsonAsSingletonList("keystore/" + keyStoreName); assertEquals("Unexpected certificateAlias attribute value", initialCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS)); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(KeyStore.NAME, keyStoreName); attributes.put(FileKeyStore.CERTIFICATE_ALIAS, updatedCertAlias); responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "PUT", attributes); assertEquals("Setting of keystore attributes should be allowed", 200, responseCode); keyStore = getRestTestHelper().getJsonAsSingletonList("keystore/" + keyStoreName); assertEquals("Unexpected certificateAlias attribute value", updatedCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS)); } public void testSetKeyStoreAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); String initialCertAlias = "app1"; String updatedCertAlias = "app2"; assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, initialCertAlias); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); Map<String, Object> keyStore = getRestTestHelper().getJsonAsSingletonList("keystore/" + keyStoreName); assertEquals("Unexpected certificateAlias attribute value", initialCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS)); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(KeyStore.NAME, keyStoreName); attributes.put(FileKeyStore.CERTIFICATE_ALIAS, updatedCertAlias); responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "PUT", attributes); assertEquals("Setting of keystore attributes should be denied", 403, responseCode); keyStore = getRestTestHelper().getJsonAsSingletonList("keystore/" + keyStoreName); assertEquals("Unexpected certificateAlias attribute value", initialCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS)); } /* === TrustStore === */ public void testCreateTrustStoreAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, false); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); } public void testCreateTrustStoreDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String trustStoreName = getTestName(); assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, false); assertEquals("trustStore creation should be allowed", 403, responseCode); assertTrustStoreExistence(trustStoreName, false); } public void testDeleteTrustStoreDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, false); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "DELETE"); assertEquals("truststore deletion should be denied", 403, responseCode); assertTrustStoreExistence(trustStoreName, true); } public void testDeleteTrustStoreAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, false); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "DELETE"); assertEquals("truststore deletion should be allowed", 200, responseCode); assertTrustStoreExistence(trustStoreName, false); } public void testSetTrustStoreAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); boolean initialPeersOnly = false; boolean updatedPeersOnly = true; assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, initialPeersOnly); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); Map<String, Object> trustStore = getRestTestHelper().getJsonAsSingletonList("truststore/" + trustStoreName); assertEquals("Unexpected peersOnly attribute value", initialPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY)); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(TrustStore.NAME, trustStoreName); attributes.put(FileTrustStore.PEERS_ONLY, updatedPeersOnly); responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "PUT", attributes); assertEquals("Setting of truststore attributes should be allowed", 200, responseCode); trustStore = getRestTestHelper().getJsonAsSingletonList("truststore/" + trustStoreName); assertEquals("Unexpected peersOnly attribute value", updatedPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY)); } public void testSetTrustStoreAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); boolean initialPeersOnly = false; boolean updatedPeersOnly = true; assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, initialPeersOnly); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); Map<String, Object> trustStore = getRestTestHelper().getJsonAsSingletonList("truststore/" + trustStoreName); assertEquals("Unexpected peersOnly attribute value", initialPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY)); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(TrustStore.NAME, trustStoreName); attributes.put(FileTrustStore.PEERS_ONLY, updatedPeersOnly); responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "PUT", attributes); assertEquals("Setting of truststore attributes should be denied", 403, responseCode); trustStore = getRestTestHelper().getJsonAsSingletonList("truststore/" + trustStoreName); assertEquals("Unexpected peersOnly attribute value", initialPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY)); } /* === Broker === */ public void testSetBrokerAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); int initialSessionCountLimit = 256; int updatedSessionCountLimit = 299; Map<String, Object> brokerAttributes = getRestTestHelper().getJsonAsSingletonList("broker"); assertEquals("Unexpected alert repeat gap", initialSessionCountLimit, brokerAttributes.get(Broker.CONNECTION_SESSION_COUNT_LIMIT)); Map<String, Object> newAttributes = new HashMap<String, Object>(); newAttributes.put(Broker.CONNECTION_SESSION_COUNT_LIMIT, updatedSessionCountLimit); int responseCode = getRestTestHelper().submitRequest("broker", "PUT", newAttributes); assertEquals("Setting of port attribites should be allowed", 200, responseCode); brokerAttributes = getRestTestHelper().getJsonAsSingletonList("broker"); assertEquals("Unexpected default alert repeat gap", updatedSessionCountLimit, brokerAttributes.get(Broker.CONNECTION_SESSION_COUNT_LIMIT)); } public void testSetBrokerAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); int initialSessionCountLimit = 256; int updatedSessionCountLimit = 299; Map<String, Object> brokerAttributes = getRestTestHelper().getJsonAsSingletonList("broker"); assertEquals("Unexpected alert repeat gap", initialSessionCountLimit, brokerAttributes.get(Broker.CONNECTION_SESSION_COUNT_LIMIT)); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> newAttributes = new HashMap<String, Object>(); newAttributes.put(Broker.CONNECTION_SESSION_COUNT_LIMIT, updatedSessionCountLimit); int responseCode = getRestTestHelper().submitRequest("broker", "PUT", newAttributes); assertEquals("Setting of port attribites should be allowed", 403, responseCode); brokerAttributes = getRestTestHelper().getJsonAsSingletonList("broker"); assertEquals("Unexpected default alert repeat gap", initialSessionCountLimit, brokerAttributes.get(Broker.CONNECTION_SESSION_COUNT_LIMIT)); } /* === GroupProvider === */ public void testCreateGroupProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); } public void testCreateGroupProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be denied", 403, responseCode); assertGroupProviderExistence(groupProviderName, false); } public void testDeleteGroupProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "DELETE"); assertEquals("Group provider deletion should be denied", 403, responseCode); assertGroupProviderExistence(groupProviderName, true); } public void testDeleteGroupProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "DELETE"); assertEquals("Group provider deletion should be allowed", 200, responseCode); assertGroupProviderExistence(groupProviderName, false); } public void testSetGroupProviderAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(GroupProvider.NAME, groupProviderName); attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); attributes.put(FileBasedGroupProvider.PATH, "/path/to/file"); responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "PUT", attributes); assertEquals("Setting of group provider attributes should be allowed but not supported", RestServlet.SC_UNPROCESSABLE_ENTITY, responseCode); } public void testSetGroupProviderAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(GroupProvider.NAME, groupProviderName); attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); attributes.put(FileBasedGroupProvider.PATH, "/path/to/file"); responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "PUT", attributes); assertEquals("Setting of group provider attributes should be denied", 403, responseCode); } /* === AccessControlProvider === */ public void testCreateAccessControlProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String accessControlProviderName = getTestName(); assertAccessControlProviderExistence(accessControlProviderName, false); int responseCode = createAccessControlProvider(accessControlProviderName); assertEquals("Access control provider creation should be denied", 403, responseCode); assertAccessControlProviderExistence(accessControlProviderName, false); } public void testDeleteAccessControlProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "DELETE"); assertEquals("Access control provider deletion should be denied", 403, responseCode); assertAccessControlProviderExistence(accessControlProviderName, true); } public void testDeleteAccessControlProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "DELETE"); assertEquals("Access control provider deletion should be allowed", 200, responseCode); assertAccessControlProviderExistence(accessControlProviderName, false); } public void testSetAccessControlProviderAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); File aclFile = TestFileUtils.createTempFile(this, ".acl", "ACL ALLOW all all"); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AccessControlProvider.NAME, accessControlProviderName); attributes.put(FileBasedGroupProvider.PATH, aclFile.getAbsolutePath()); int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes); assertEquals("Setting of access control provider attributes should be allowed", 200, responseCode); } public void testSetAccessControlProviderAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(GroupProvider.NAME, accessControlProviderName); attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); attributes.put(FileBasedGroupProvider.PATH, "/path/to/file"); int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes); assertEquals("Setting of access control provider attributes should be denied", 403, responseCode); } /* === HTTP management === */ public void testSetHttpManagementAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(HttpManagement.NAME, TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT); attributes.put(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.TIME_OUT, 10000); int responseCode = getRestTestHelper().submitRequest( "plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT, "PUT", attributes); assertEquals("Setting of http management should be allowed", 200, responseCode); Map<String, Object> details = getRestTestHelper().getJsonAsSingletonList( "plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT); assertEquals("Unexpected session timeout", 10000, details.get(HttpManagement.TIME_OUT)); assertEquals("Unexpected http basic auth enabled", true, details.get(HttpManagement.HTTP_BASIC_AUTHENTICATION_ENABLED)); assertEquals("Unexpected https basic auth enabled", false, details.get(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED)); assertEquals("Unexpected http sasl auth enabled", false, details.get(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED)); assertEquals("Unexpected https sasl auth enabled", false, details.get(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED)); } public void testSetHttpManagementAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(HttpManagement.NAME, TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT); attributes.put(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.TIME_OUT, 10000); int responseCode = getRestTestHelper().submitRequest( "plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT, "PUT", attributes); assertEquals("Setting of http management should be denied", 403, responseCode); Map<String, Object> details = getRestTestHelper().getJsonAsSingletonList( "plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT); assertEquals("Unexpected session timeout", HttpManagement.DEFAULT_TIMEOUT_IN_SECONDS, details.get(HttpManagement.TIME_OUT)); assertEquals("Unexpected http basic auth enabled", true, details.get(HttpManagement.HTTP_BASIC_AUTHENTICATION_ENABLED)); assertEquals("Unexpected https basic auth enabled", true, details.get(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED)); assertEquals("Unexpected http sasl auth enabled", true, details.get(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED)); assertEquals("Unexpected https sasl auth enabled", true, details.get(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED)); } /* === Broker Logger === */ public void testCreateBrokerLoggerAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerLogger.NAME, "testLogger1"); attributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "testLogger2"); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest("brokerlogger/testLogger2", "GET", HttpServletResponse.SC_NOT_FOUND); } public void testDeleteBrokerLoggerAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerLogger.NAME, "testLogger1"); attributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "DELETE", null, HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "DELETE", null, HttpServletResponse.SC_OK); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_NOT_FOUND); } public void testDownloadBrokerLoggerFileAllowedDenied() throws Exception { final String loggerName = "testFileLogger"; final String loggerPath = "brokerlogger/" + loggerName; getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerLogger.NAME, loggerName); attributes.put(ConfiguredObject.TYPE, BrokerFileLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_OK); getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_OK); getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_FORBIDDEN); } public void testViewMemoryLoggerEntriesAllowedDenied() throws Exception { final String loggerName = "testMemoryLogger"; final String loggerPath = "brokerlogger/" + loggerName; getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerLogger.NAME, loggerName); attributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest(loggerPath + "/getLogEntries?lastLogId=0", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest(loggerPath + "/getLogEntries?lastLogId=0", "GET", HttpServletResponse.SC_FORBIDDEN); } /* === Broker Log Inclusion Rules === */ public void testCreateBrokerLoggerRuleAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> loggerAttributes = new HashMap<>(); loggerAttributes.put(BrokerLogger.NAME, "testLogger1"); loggerAttributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", loggerAttributes, HttpServletResponse.SC_CREATED); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1"); attributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "DEBUG"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule2"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", attributes, HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule2", "GET", HttpServletResponse.SC_NOT_FOUND); } public void testUpdateBrokerLoggerRuleAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> loggerAttributes = new HashMap<>(); loggerAttributes.put(BrokerLogger.NAME, "testLogger1"); loggerAttributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", loggerAttributes, HttpServletResponse.SC_CREATED); Map<String, Object> ruleAttributes = new HashMap<>(); ruleAttributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1"); ruleAttributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); ruleAttributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "INFO"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", ruleAttributes, HttpServletResponse.SC_CREATED); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1"); attributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "DEBUG"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "PUT", attributes, HttpServletResponse.SC_OK); Map<String,Object> resultAfterUpdate = getRestTestHelper().getJsonAsSingletonList("brokerloginclusionrule/testLogger1/rule1"); assertEquals("Log level was not changed", "DEBUG", resultAfterUpdate.get(BrokerNameAndLevelLogInclusionRule.LEVEL)); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "INFO"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "PUT", attributes, HttpServletResponse.SC_FORBIDDEN); Map<String,Object> resultAfterDeniedUpdate = getRestTestHelper().getJsonAsSingletonList("brokerloginclusionrule/testLogger1/rule1"); assertEquals("Log level was changed by not allowed user", "DEBUG", resultAfterDeniedUpdate.get(BrokerNameAndLevelLogInclusionRule.LEVEL)); } public void testDeleteBrokerLoggerRuleAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> loggerAttributes = new HashMap<>(); loggerAttributes.put(BrokerLogger.NAME, "testLogger1"); loggerAttributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", loggerAttributes, HttpServletResponse.SC_CREATED); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1"); attributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "DEBUG"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "DELETE", null, HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "DELETE", null, HttpServletResponse.SC_OK); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_NOT_FOUND); } /* === Utility Methods === */ private int createPort(String portName) throws Exception { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(Port.NAME, portName); attributes.put(Port.PORT, findFreePort()); attributes.put(Port.AUTHENTICATION_PROVIDER, TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER); return getRestTestHelper().submitRequest("port/" + portName, "PUT", attributes); } private void assertPortExists(String portName) throws Exception { assertPortExistence(portName, true); } private void assertPortDoesNotExist(String portName) throws Exception { assertPortExistence(portName, false); } private void assertPortExistence(String portName, boolean exists) throws Exception { String path = "port/" + portName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private void assertKeyStoreExistence(String keyStoreName, boolean exists) throws Exception { String path = "keystore/" + keyStoreName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private void assertTrustStoreExistence(String trustStoreName, boolean exists) throws Exception { String path = "truststore/" + trustStoreName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private int createAuthenticationProvider(String authenticationProviderName) throws Exception { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AuthenticationProvider.NAME, authenticationProviderName); attributes.put(AuthenticationProvider.TYPE, AnonymousAuthenticationManager.PROVIDER_TYPE); return getRestTestHelper().submitRequest("authenticationprovider/" + authenticationProviderName, "PUT", attributes); } private void assertAuthenticationProviderDoesNotExist(String authenticationProviderName) throws Exception { assertAuthenticationProviderExistence(authenticationProviderName, false); } private void assertAuthenticationProviderExists(String authenticationProviderName) throws Exception { assertAuthenticationProviderExistence(authenticationProviderName, true); } private void assertAuthenticationProviderExistence(String authenticationProviderName, boolean exists) throws Exception { String path = "authenticationprovider/" + authenticationProviderName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private int createKeyStore(String name, String certAlias) throws IOException { Map<String, Object> keyStoreAttributes = new HashMap<String, Object>(); keyStoreAttributes.put(KeyStore.NAME, name); keyStoreAttributes.put(FileKeyStore.STORE_URL, TestSSLConstants.KEYSTORE); keyStoreAttributes.put(FileKeyStore.PASSWORD, TestSSLConstants.KEYSTORE_PASSWORD); keyStoreAttributes.put(FileKeyStore.CERTIFICATE_ALIAS, certAlias); return getRestTestHelper().submitRequest("keystore/" + name, "PUT", keyStoreAttributes); } private int createTrustStore(String name, boolean peersOnly) throws IOException { Map<String, Object> trustStoreAttributes = new HashMap<String, Object>(); trustStoreAttributes.put(TrustStore.NAME, name); trustStoreAttributes.put(FileTrustStore.STORE_URL, TestSSLConstants.KEYSTORE); trustStoreAttributes.put(FileTrustStore.PASSWORD, TestSSLConstants.KEYSTORE_PASSWORD); trustStoreAttributes.put(FileTrustStore.PEERS_ONLY, peersOnly); return getRestTestHelper().submitRequest("truststore/" + name, "PUT", trustStoreAttributes); } private void assertGroupProviderExistence(String groupProviderName, boolean exists) throws Exception { String path = "groupprovider/" + groupProviderName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private int createGroupProvider(String groupProviderName) throws Exception { File file = TestFileUtils.createTempFile(this, ".groups"); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(GroupProvider.NAME, groupProviderName); attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); attributes.put(FileBasedGroupProvider.PATH, file.getAbsoluteFile()); return getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "PUT", attributes); } private void assertAccessControlProviderExistence(String accessControlProviderName, boolean exists) throws Exception { String path = "accesscontrolprovider/" + accessControlProviderName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private int createAccessControlProvider(String accessControlProviderName) throws Exception { File file = TestFileUtils.createTempFile(this, ".acl", _secondaryAclFileContent); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AccessControlProvider.NAME, accessControlProviderName); attributes.put(AccessControlProvider.TYPE, FileAccessControlProviderConstants.ACL_FILE_PROVIDER_TYPE); attributes.put(FileAccessControlProviderConstants.PATH, file.getAbsoluteFile()); return getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes); } }
pkdevbox/qpid-java
systests/src/test/java/org/apache/qpid/systest/rest/acl/BrokerACLTest.java
213,276
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.qpid.systest.rest.acl; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.qpid.server.logging.BrokerFileLogger; import org.apache.qpid.server.logging.BrokerMemoryLogger; import org.apache.qpid.server.logging.BrokerNameAndLevelLogInclusionRule; import org.apache.qpid.server.management.plugin.HttpManagement; import org.apache.qpid.server.management.plugin.servlet.rest.RestServlet; import org.apache.qpid.server.model.AccessControlProvider; import org.apache.qpid.server.model.AuthenticationProvider; import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.BrokerLogger; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.ExternalFileBasedAuthenticationManager; import org.apache.qpid.server.model.GroupProvider; import org.apache.qpid.server.model.KeyStore; import org.apache.qpid.server.model.Port; import org.apache.qpid.server.model.Protocol; import org.apache.qpid.server.model.TrustStore; import org.apache.qpid.server.model.adapter.FileBasedGroupProvider; import org.apache.qpid.server.model.adapter.FileBasedGroupProviderImpl; import org.apache.qpid.server.security.FileKeyStore; import org.apache.qpid.server.security.FileTrustStore; import org.apache.qpid.server.security.access.FileAccessControlProviderConstants; import org.apache.qpid.server.security.acl.AbstractACLTestCase; import org.apache.qpid.server.security.auth.manager.AnonymousAuthenticationManager; import org.apache.qpid.server.security.auth.manager.PlainPasswordDatabaseAuthenticationManager; import org.apache.qpid.systest.rest.QpidRestTestCase; import org.apache.qpid.test.utils.TestBrokerConfiguration; import org.apache.qpid.test.utils.TestFileUtils; import org.apache.qpid.test.utils.TestSSLConstants; public class BrokerACLTest extends QpidRestTestCase { private static final String ALLOWED_USER = "user1"; private static final String DENIED_USER = "user2"; private String _secondaryAclFileContent = ""; @Override protected void customizeConfiguration() throws Exception { super.customizeConfiguration(); final TestBrokerConfiguration defaultBrokerConfiguration = getDefaultBrokerConfiguration(); defaultBrokerConfiguration.configureTemporaryPasswordFile(ALLOWED_USER, DENIED_USER); AbstractACLTestCase.writeACLFileUtil(this, "ACL ALLOW-LOG ALL ACCESS MANAGEMENT", "ACL ALLOW-LOG " + ALLOWED_USER + " CONFIGURE BROKER", "ACL DENY-LOG " + DENIED_USER + " CONFIGURE BROKER", "ACL ALLOW-LOG " + ALLOWED_USER + " ACCESS_LOGS BROKER", "ACL DENY-LOG " + DENIED_USER + " ACCESS_LOGS BROKER", "ACL DENY-LOG ALL ALL"); _secondaryAclFileContent = "ACL ALLOW-LOG ALL ACCESS MANAGEMENT\n" + "ACL ALLOW-LOG " + ALLOWED_USER + " CONFIGURE BROKER\n" + "ACL DENY-LOG " + DENIED_USER + " CONFIGURE BROKER\n" + "ACL DENY-LOG ALL ALL"; } /* === AuthenticationProvider === */ public void testCreateAuthenticationProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String authenticationProviderName = getTestName(); int responseCode = createAuthenticationProvider(authenticationProviderName); assertEquals("Provider creation should be allowed", 201, responseCode); assertAuthenticationProviderExists(authenticationProviderName); } public void testCreateAuthenticationProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String authenticationProviderName = getTestName(); int responseCode = createAuthenticationProvider(authenticationProviderName); assertEquals("Provider creation should be denied", 403, responseCode); assertAuthenticationProviderDoesNotExist(authenticationProviderName); } public void testDeleteAuthenticationProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String providerName = getTestName(); int responseCode = createAuthenticationProvider(providerName); assertEquals("Provider creation should be allowed", 201, responseCode); assertAuthenticationProviderExists(providerName); responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "DELETE"); assertEquals("Provider deletion should be allowed", 200, responseCode); assertAuthenticationProviderDoesNotExist(TEST2_VIRTUALHOST); } public void testDeleteAuthenticationProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String providerName = getTestName(); int responseCode = createAuthenticationProvider(providerName); assertEquals("Provider creation should be allowed", 201, responseCode); assertAuthenticationProviderExists(providerName); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "DELETE"); assertEquals("Provider deletion should be denied", 403, responseCode); assertAuthenticationProviderExists(providerName); } public void testSetAuthenticationProviderAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String providerName = TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER; assertAuthenticationProviderExists(providerName); File file = TestFileUtils.createTempFile(this, ".users", "guest:guest\n" + ALLOWED_USER + ":" + ALLOWED_USER + "\n" + DENIED_USER + ":" + DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AuthenticationProvider.NAME, providerName); attributes.put(AuthenticationProvider.TYPE, PlainPasswordDatabaseAuthenticationManager.PROVIDER_TYPE); attributes.put(ExternalFileBasedAuthenticationManager.PATH, file.getAbsolutePath()); int responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "PUT", attributes); assertEquals("Setting of provider attribites should be allowed", 200, responseCode); } public void testSetAuthenticationProviderAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String providerName = TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER; Map<String, Object> providerData = getRestTestHelper().getJsonAsSingletonList("authenticationprovider/" + providerName); File file = TestFileUtils.createTempFile(this, ".users", "guest:guest\n" + ALLOWED_USER + ":" + ALLOWED_USER + "\n" + DENIED_USER + ":" + DENIED_USER); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AuthenticationProvider.NAME, providerName); attributes.put(AuthenticationProvider.TYPE, AnonymousAuthenticationManager.PROVIDER_TYPE); attributes.put(ExternalFileBasedAuthenticationManager.PATH, file.getAbsolutePath()); int responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "PUT", attributes); assertEquals("Setting of provider attribites should be allowed", 403, responseCode); Map<String, Object> provider = getRestTestHelper().getJsonAsSingletonList("authenticationprovider/" + providerName); assertEquals("Unexpected STORE_URL attribute value", providerData.get(ExternalFileBasedAuthenticationManager.PATH), provider.get(ExternalFileBasedAuthenticationManager.PATH)); } /* === Port === */ public void testCreatePortAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String portName = getTestName(); int responseCode = createPort(portName); assertEquals("Port creation should be allowed", 201, responseCode); assertPortExists(portName); } public void testCreatePortDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String portName = getTestName(); int responseCode = createPort(portName); assertEquals("Port creation should be denied", 403, responseCode); assertPortDoesNotExist(portName); } public void testDeletePortDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String portName = TestBrokerConfiguration.ENTRY_NAME_AMQP_PORT; assertPortExists(portName); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); int responseCode = getRestTestHelper().submitRequest("port/" + portName, "DELETE"); assertEquals("Port deletion should be denied", 403, responseCode); assertPortExists(portName); } public void testDeletePortAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String portName = TestBrokerConfiguration.ENTRY_NAME_AMQP_PORT; assertPortExists(portName); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); int responseCode = getRestTestHelper().submitRequest("port/" + portName, "DELETE"); assertEquals("Port deletion should be allowed", 200, responseCode); assertPortDoesNotExist(portName); } public void testSetPortAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String portName = getTestName(); int responseCode = createPort(portName); assertEquals("Port creation should be allowed", 201, responseCode); assertPortExists(portName); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(Port.NAME, portName); attributes.put(Port.PROTOCOLS, Arrays.asList(Protocol.AMQP_0_9)); attributes.put(Port.AUTHENTICATION_PROVIDER, TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER); responseCode = getRestTestHelper().submitRequest("port/" + portName, "PUT", attributes); assertEquals("Setting of port attribites should be denied", 403, responseCode); Map<String, Object> port = getRestTestHelper().getJsonAsSingletonList("port/" + portName); assertEquals("Unexpected authentication provider attribute value", TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER, port.get(Port.AUTHENTICATION_PROVIDER)); } /* === KeyStore === */ public void testCreateKeyStoreAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, TestSSLConstants.CERT_ALIAS_APP1); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); } public void testCreateKeyStoreDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String keyStoreName = getTestName(); assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, TestSSLConstants.CERT_ALIAS_APP1); assertEquals("keyStore creation should be allowed", 403, responseCode); assertKeyStoreExistence(keyStoreName, false); } public void testDeleteKeyStoreDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, TestSSLConstants.CERT_ALIAS_APP1); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "DELETE"); assertEquals("keystore deletion should be denied", 403, responseCode); assertKeyStoreExistence(keyStoreName, true); } public void testDeleteKeyStoreAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, TestSSLConstants.CERT_ALIAS_APP1); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "DELETE"); assertEquals("keystore deletion should be allowed", 200, responseCode); assertKeyStoreExistence(keyStoreName, false); } public void testSetKeyStoreAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); String initialCertAlias = TestSSLConstants.CERT_ALIAS_APP1; String updatedCertAlias = TestSSLConstants.CERT_ALIAS_APP2; assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, initialCertAlias); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); Map<String, Object> keyStore = getRestTestHelper().getJsonAsSingletonList("keystore/" + keyStoreName); assertEquals("Unexpected certificateAlias attribute value", initialCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS)); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(KeyStore.NAME, keyStoreName); attributes.put(FileKeyStore.CERTIFICATE_ALIAS, updatedCertAlias); responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "PUT", attributes); assertEquals("Setting of keystore attributes should be allowed", 200, responseCode); keyStore = getRestTestHelper().getJsonAsSingletonList("keystore/" + keyStoreName); assertEquals("Unexpected certificateAlias attribute value", updatedCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS)); } public void testSetKeyStoreAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); String initialCertAlias = TestSSLConstants.CERT_ALIAS_APP1; String updatedCertAlias = TestSSLConstants.CERT_ALIAS_APP2; assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, initialCertAlias); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); Map<String, Object> keyStore = getRestTestHelper().getJsonAsSingletonList("keystore/" + keyStoreName); assertEquals("Unexpected certificateAlias attribute value", initialCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS)); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(KeyStore.NAME, keyStoreName); attributes.put(FileKeyStore.CERTIFICATE_ALIAS, updatedCertAlias); responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "PUT", attributes); assertEquals("Setting of keystore attributes should be denied", 403, responseCode); keyStore = getRestTestHelper().getJsonAsSingletonList("keystore/" + keyStoreName); assertEquals("Unexpected certificateAlias attribute value", initialCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS)); } /* === TrustStore === */ public void testCreateTrustStoreAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, false); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); } public void testCreateTrustStoreDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String trustStoreName = getTestName(); assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, false); assertEquals("trustStore creation should be allowed", 403, responseCode); assertTrustStoreExistence(trustStoreName, false); } public void testDeleteTrustStoreDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, false); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "DELETE"); assertEquals("truststore deletion should be denied", 403, responseCode); assertTrustStoreExistence(trustStoreName, true); } public void testDeleteTrustStoreAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, false); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "DELETE"); assertEquals("truststore deletion should be allowed", 200, responseCode); assertTrustStoreExistence(trustStoreName, false); } public void testSetTrustStoreAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); boolean initialPeersOnly = false; boolean updatedPeersOnly = true; assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, initialPeersOnly); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); Map<String, Object> trustStore = getRestTestHelper().getJsonAsSingletonList("truststore/" + trustStoreName); assertEquals("Unexpected peersOnly attribute value", initialPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY)); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(TrustStore.NAME, trustStoreName); attributes.put(FileTrustStore.PEERS_ONLY, updatedPeersOnly); responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "PUT", attributes); assertEquals("Setting of truststore attributes should be allowed", 200, responseCode); trustStore = getRestTestHelper().getJsonAsSingletonList("truststore/" + trustStoreName); assertEquals("Unexpected peersOnly attribute value", updatedPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY)); } public void testSetTrustStoreAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); boolean initialPeersOnly = false; boolean updatedPeersOnly = true; assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, initialPeersOnly); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); Map<String, Object> trustStore = getRestTestHelper().getJsonAsSingletonList("truststore/" + trustStoreName); assertEquals("Unexpected peersOnly attribute value", initialPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY)); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(TrustStore.NAME, trustStoreName); attributes.put(FileTrustStore.PEERS_ONLY, updatedPeersOnly); responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "PUT", attributes); assertEquals("Setting of truststore attributes should be denied", 403, responseCode); trustStore = getRestTestHelper().getJsonAsSingletonList("truststore/" + trustStoreName); assertEquals("Unexpected peersOnly attribute value", initialPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY)); } /* === Broker === */ public void testSetBrokerAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); int initialSessionCountLimit = 256; int updatedSessionCountLimit = 299; Map<String, Object> brokerAttributes = getRestTestHelper().getJsonAsSingletonList("broker"); assertEquals("Unexpected alert repeat gap", initialSessionCountLimit, brokerAttributes.get(Broker.CONNECTION_SESSION_COUNT_LIMIT)); Map<String, Object> newAttributes = new HashMap<String, Object>(); newAttributes.put(Broker.CONNECTION_SESSION_COUNT_LIMIT, updatedSessionCountLimit); int responseCode = getRestTestHelper().submitRequest("broker", "PUT", newAttributes); assertEquals("Setting of port attribites should be allowed", 200, responseCode); brokerAttributes = getRestTestHelper().getJsonAsSingletonList("broker"); assertEquals("Unexpected default alert repeat gap", updatedSessionCountLimit, brokerAttributes.get(Broker.CONNECTION_SESSION_COUNT_LIMIT)); } public void testSetBrokerAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); int initialSessionCountLimit = 256; int updatedSessionCountLimit = 299; Map<String, Object> brokerAttributes = getRestTestHelper().getJsonAsSingletonList("broker"); assertEquals("Unexpected alert repeat gap", initialSessionCountLimit, brokerAttributes.get(Broker.CONNECTION_SESSION_COUNT_LIMIT)); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> newAttributes = new HashMap<String, Object>(); newAttributes.put(Broker.CONNECTION_SESSION_COUNT_LIMIT, updatedSessionCountLimit); int responseCode = getRestTestHelper().submitRequest("broker", "PUT", newAttributes); assertEquals("Setting of port attribites should be allowed", 403, responseCode); brokerAttributes = getRestTestHelper().getJsonAsSingletonList("broker"); assertEquals("Unexpected default alert repeat gap", initialSessionCountLimit, brokerAttributes.get(Broker.CONNECTION_SESSION_COUNT_LIMIT)); } /* === GroupProvider === */ public void testCreateGroupProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); } public void testCreateGroupProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be denied", 403, responseCode); assertGroupProviderExistence(groupProviderName, false); } public void testDeleteGroupProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "DELETE"); assertEquals("Group provider deletion should be denied", 403, responseCode); assertGroupProviderExistence(groupProviderName, true); } public void testDeleteGroupProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "DELETE"); assertEquals("Group provider deletion should be allowed", 200, responseCode); assertGroupProviderExistence(groupProviderName, false); } public void testSetGroupProviderAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(GroupProvider.NAME, groupProviderName); attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); attributes.put(FileBasedGroupProvider.PATH, "/path/to/file"); responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "PUT", attributes); assertEquals("Setting of group provider attributes should be allowed but not supported", RestServlet.SC_UNPROCESSABLE_ENTITY, responseCode); } public void testSetGroupProviderAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(GroupProvider.NAME, groupProviderName); attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); attributes.put(FileBasedGroupProvider.PATH, "/path/to/file"); responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "PUT", attributes); assertEquals("Setting of group provider attributes should be denied", 403, responseCode); } /* === AccessControlProvider === */ public void testCreateAccessControlProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String accessControlProviderName = getTestName(); assertAccessControlProviderExistence(accessControlProviderName, false); int responseCode = createAccessControlProvider(accessControlProviderName); assertEquals("Access control provider creation should be denied", 403, responseCode); assertAccessControlProviderExistence(accessControlProviderName, false); } public void testDeleteAccessControlProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "DELETE"); assertEquals("Access control provider deletion should be denied", 403, responseCode); assertAccessControlProviderExistence(accessControlProviderName, true); } public void testDeleteAccessControlProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "DELETE"); assertEquals("Access control provider deletion should be allowed", 200, responseCode); assertAccessControlProviderExistence(accessControlProviderName, false); } public void testSetAccessControlProviderAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); File aclFile = TestFileUtils.createTempFile(this, ".acl", "ACL ALLOW all all"); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AccessControlProvider.NAME, accessControlProviderName); attributes.put(FileBasedGroupProvider.PATH, aclFile.getAbsolutePath()); int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes); assertEquals("Setting of access control provider attributes should be allowed", 200, responseCode); } public void testSetAccessControlProviderAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(GroupProvider.NAME, accessControlProviderName); attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); attributes.put(FileBasedGroupProvider.PATH, "/path/to/file"); int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes); assertEquals("Setting of access control provider attributes should be denied", 403, responseCode); } /* === HTTP management === */ public void testSetHttpManagementAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(HttpManagement.NAME, TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT); attributes.put(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.TIME_OUT, 10000); int responseCode = getRestTestHelper().submitRequest( "plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT, "PUT", attributes); assertEquals("Setting of http management should be allowed", 200, responseCode); Map<String, Object> details = getRestTestHelper().getJsonAsSingletonList( "plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT); assertEquals("Unexpected session timeout", 10000, details.get(HttpManagement.TIME_OUT)); assertEquals("Unexpected http basic auth enabled", true, details.get(HttpManagement.HTTP_BASIC_AUTHENTICATION_ENABLED)); assertEquals("Unexpected https basic auth enabled", false, details.get(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED)); assertEquals("Unexpected http sasl auth enabled", false, details.get(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED)); assertEquals("Unexpected https sasl auth enabled", false, details.get(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED)); } public void testSetHttpManagementAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(HttpManagement.NAME, TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT); attributes.put(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.TIME_OUT, 10000); int responseCode = getRestTestHelper().submitRequest( "plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT, "PUT", attributes); assertEquals("Setting of http management should be denied", 403, responseCode); Map<String, Object> details = getRestTestHelper().getJsonAsSingletonList( "plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT); assertEquals("Unexpected session timeout", HttpManagement.DEFAULT_TIMEOUT_IN_SECONDS, details.get(HttpManagement.TIME_OUT)); assertEquals("Unexpected http basic auth enabled", true, details.get(HttpManagement.HTTP_BASIC_AUTHENTICATION_ENABLED)); assertEquals("Unexpected https basic auth enabled", true, details.get(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED)); assertEquals("Unexpected http sasl auth enabled", true, details.get(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED)); assertEquals("Unexpected https sasl auth enabled", true, details.get(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED)); } /* === Broker Logger === */ public void testCreateBrokerLoggerAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerLogger.NAME, "testLogger1"); attributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "testLogger2"); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest("brokerlogger/testLogger2", "GET", HttpServletResponse.SC_NOT_FOUND); } public void testDeleteBrokerLoggerAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerLogger.NAME, "testLogger1"); attributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "DELETE", null, HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "DELETE", null, HttpServletResponse.SC_OK); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_NOT_FOUND); } public void testDownloadBrokerLoggerFileAllowedDenied() throws Exception { final String loggerName = "testFileLogger"; final String loggerPath = "brokerlogger/" + loggerName; getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerLogger.NAME, loggerName); attributes.put(ConfiguredObject.TYPE, BrokerFileLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_OK); getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_OK); getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_FORBIDDEN); } public void testViewMemoryLoggerEntriesAllowedDenied() throws Exception { final String loggerName = "testMemoryLogger"; final String loggerPath = "brokerlogger/" + loggerName; getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerLogger.NAME, loggerName); attributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest(loggerPath + "/getLogEntries?lastLogId=0", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest(loggerPath + "/getLogEntries?lastLogId=0", "GET", HttpServletResponse.SC_FORBIDDEN); } /* === Broker Log Inclusion Rules === */ public void testCreateBrokerLoggerRuleAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> loggerAttributes = new HashMap<>(); loggerAttributes.put(BrokerLogger.NAME, "testLogger1"); loggerAttributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", loggerAttributes, HttpServletResponse.SC_CREATED); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1"); attributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "DEBUG"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule2"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", attributes, HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule2", "GET", HttpServletResponse.SC_NOT_FOUND); } public void testUpdateBrokerLoggerRuleAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> loggerAttributes = new HashMap<>(); loggerAttributes.put(BrokerLogger.NAME, "testLogger1"); loggerAttributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", loggerAttributes, HttpServletResponse.SC_CREATED); Map<String, Object> ruleAttributes = new HashMap<>(); ruleAttributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1"); ruleAttributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); ruleAttributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "INFO"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", ruleAttributes, HttpServletResponse.SC_CREATED); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1"); attributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "DEBUG"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "PUT", attributes, HttpServletResponse.SC_OK); Map<String,Object> resultAfterUpdate = getRestTestHelper().getJsonAsSingletonList("brokerloginclusionrule/testLogger1/rule1"); assertEquals("Log level was not changed", "DEBUG", resultAfterUpdate.get(BrokerNameAndLevelLogInclusionRule.LEVEL)); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "INFO"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "PUT", attributes, HttpServletResponse.SC_FORBIDDEN); Map<String,Object> resultAfterDeniedUpdate = getRestTestHelper().getJsonAsSingletonList("brokerloginclusionrule/testLogger1/rule1"); assertEquals("Log level was changed by not allowed user", "DEBUG", resultAfterDeniedUpdate.get(BrokerNameAndLevelLogInclusionRule.LEVEL)); } public void testDeleteBrokerLoggerRuleAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> loggerAttributes = new HashMap<>(); loggerAttributes.put(BrokerLogger.NAME, "testLogger1"); loggerAttributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", loggerAttributes, HttpServletResponse.SC_CREATED); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1"); attributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "DEBUG"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "DELETE", null, HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "DELETE", null, HttpServletResponse.SC_OK); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_NOT_FOUND); } /* === Utility Methods === */ private int createPort(String portName) throws Exception { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(Port.NAME, portName); attributes.put(Port.PORT, 0); attributes.put(Port.AUTHENTICATION_PROVIDER, TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER); return getRestTestHelper().submitRequest("port/" + portName, "PUT", attributes); } private void assertPortExists(String portName) throws Exception { assertPortExistence(portName, true); } private void assertPortDoesNotExist(String portName) throws Exception { assertPortExistence(portName, false); } private void assertPortExistence(String portName, boolean exists) throws Exception { String path = "port/" + portName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private void assertKeyStoreExistence(String keyStoreName, boolean exists) throws Exception { String path = "keystore/" + keyStoreName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private void assertTrustStoreExistence(String trustStoreName, boolean exists) throws Exception { String path = "truststore/" + trustStoreName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private int createAuthenticationProvider(String authenticationProviderName) throws Exception { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AuthenticationProvider.NAME, authenticationProviderName); attributes.put(AuthenticationProvider.TYPE, AnonymousAuthenticationManager.PROVIDER_TYPE); return getRestTestHelper().submitRequest("authenticationprovider/" + authenticationProviderName, "PUT", attributes); } private void assertAuthenticationProviderDoesNotExist(String authenticationProviderName) throws Exception { assertAuthenticationProviderExistence(authenticationProviderName, false); } private void assertAuthenticationProviderExists(String authenticationProviderName) throws Exception { assertAuthenticationProviderExistence(authenticationProviderName, true); } private void assertAuthenticationProviderExistence(String authenticationProviderName, boolean exists) throws Exception { String path = "authenticationprovider/" + authenticationProviderName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private int createKeyStore(String name, String certAlias) throws IOException { Map<String, Object> keyStoreAttributes = new HashMap<String, Object>(); keyStoreAttributes.put(KeyStore.NAME, name); keyStoreAttributes.put(FileKeyStore.STORE_URL, TestSSLConstants.KEYSTORE); keyStoreAttributes.put(FileKeyStore.PASSWORD, TestSSLConstants.KEYSTORE_PASSWORD); keyStoreAttributes.put(FileKeyStore.CERTIFICATE_ALIAS, certAlias); return getRestTestHelper().submitRequest("keystore/" + name, "PUT", keyStoreAttributes); } private int createTrustStore(String name, boolean peersOnly) throws IOException { Map<String, Object> trustStoreAttributes = new HashMap<String, Object>(); trustStoreAttributes.put(TrustStore.NAME, name); trustStoreAttributes.put(FileTrustStore.STORE_URL, TestSSLConstants.KEYSTORE); trustStoreAttributes.put(FileTrustStore.PASSWORD, TestSSLConstants.KEYSTORE_PASSWORD); trustStoreAttributes.put(FileTrustStore.PEERS_ONLY, peersOnly); return getRestTestHelper().submitRequest("truststore/" + name, "PUT", trustStoreAttributes); } private void assertGroupProviderExistence(String groupProviderName, boolean exists) throws Exception { String path = "groupprovider/" + groupProviderName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private int createGroupProvider(String groupProviderName) throws Exception { File file = TestFileUtils.createTempFile(this, ".groups"); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(GroupProvider.NAME, groupProviderName); attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); attributes.put(FileBasedGroupProvider.PATH, file.getAbsoluteFile()); return getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "PUT", attributes); } private void assertAccessControlProviderExistence(String accessControlProviderName, boolean exists) throws Exception { String path = "accesscontrolprovider/" + accessControlProviderName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private int createAccessControlProvider(String accessControlProviderName) throws Exception { File file = TestFileUtils.createTempFile(this, ".acl", _secondaryAclFileContent); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AccessControlProvider.NAME, accessControlProviderName); attributes.put(AccessControlProvider.TYPE, FileAccessControlProviderConstants.ACL_FILE_PROVIDER_TYPE); attributes.put(FileAccessControlProviderConstants.PATH, file.getAbsoluteFile()); return getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes); } }
pamod/qpid-java
systests/src/test/java/org/apache/qpid/systest/rest/acl/BrokerACLTest.java
213,277
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.qpid.systest.rest.acl; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.qpid.server.logging.BrokerFileLogger; import org.apache.qpid.server.logging.BrokerMemoryLogger; import org.apache.qpid.server.logging.BrokerNameAndLevelLogInclusionRule; import org.apache.qpid.server.management.plugin.HttpManagement; import org.apache.qpid.server.management.plugin.servlet.rest.AbstractServlet; import org.apache.qpid.server.model.AccessControlProvider; import org.apache.qpid.server.model.AuthenticationProvider; import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.BrokerLogger; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.ExternalFileBasedAuthenticationManager; import org.apache.qpid.server.model.GroupProvider; import org.apache.qpid.server.model.KeyStore; import org.apache.qpid.server.model.Port; import org.apache.qpid.server.model.Protocol; import org.apache.qpid.server.model.TrustStore; import org.apache.qpid.server.model.adapter.FileBasedGroupProvider; import org.apache.qpid.server.model.adapter.FileBasedGroupProviderImpl; import org.apache.qpid.server.security.FileKeyStore; import org.apache.qpid.server.security.FileTrustStore; import org.apache.qpid.server.security.access.FileAccessControlProviderConstants; import org.apache.qpid.server.security.acl.AbstractACLTestCase; import org.apache.qpid.server.security.auth.manager.AnonymousAuthenticationManager; import org.apache.qpid.server.security.auth.manager.PlainPasswordDatabaseAuthenticationManager; import org.apache.qpid.systest.rest.QpidRestTestCase; import org.apache.qpid.test.utils.TestBrokerConfiguration; import org.apache.qpid.test.utils.TestFileUtils; import org.apache.qpid.test.utils.TestSSLConstants; public class BrokerACLTest extends QpidRestTestCase { private static final String ALLOWED_USER = "user1"; private static final String DENIED_USER = "user2"; private String _secondaryAclFileContent = ""; @Override protected void customizeConfiguration() throws Exception { super.customizeConfiguration(); final TestBrokerConfiguration defaultBrokerConfiguration = getDefaultBrokerConfiguration(); defaultBrokerConfiguration.configureTemporaryPasswordFile(ALLOWED_USER, DENIED_USER); AbstractACLTestCase.writeACLFileUtil(this, "ACL ALLOW-LOG ALL ACCESS MANAGEMENT", "ACL ALLOW-LOG " + ALLOWED_USER + " CONFIGURE BROKER", "ACL DENY-LOG " + DENIED_USER + " CONFIGURE BROKER", "ACL ALLOW-LOG " + ALLOWED_USER + " ACCESS_LOGS BROKER", "ACL DENY-LOG " + DENIED_USER + " ACCESS_LOGS BROKER", "ACL DENY-LOG ALL ALL"); _secondaryAclFileContent = "ACL ALLOW-LOG ALL ACCESS MANAGEMENT\n" + "ACL ALLOW-LOG " + ALLOWED_USER + " CONFIGURE BROKER\n" + "ACL DENY-LOG " + DENIED_USER + " CONFIGURE BROKER\n" + "ACL DENY-LOG ALL ALL"; } /* === AuthenticationProvider === */ public void testCreateAuthenticationProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String authenticationProviderName = getTestName(); int responseCode = createAuthenticationProvider(authenticationProviderName); assertEquals("Provider creation should be allowed", 201, responseCode); assertAuthenticationProviderExists(authenticationProviderName); } public void testCreateAuthenticationProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String authenticationProviderName = getTestName(); int responseCode = createAuthenticationProvider(authenticationProviderName); assertEquals("Provider creation should be denied", 403, responseCode); assertAuthenticationProviderDoesNotExist(authenticationProviderName); } public void testDeleteAuthenticationProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String providerName = getTestName(); int responseCode = createAuthenticationProvider(providerName); assertEquals("Provider creation should be allowed", 201, responseCode); assertAuthenticationProviderExists(providerName); responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "DELETE"); assertEquals("Provider deletion should be allowed", 200, responseCode); assertAuthenticationProviderDoesNotExist(TEST2_VIRTUALHOST); } public void testDeleteAuthenticationProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String providerName = getTestName(); int responseCode = createAuthenticationProvider(providerName); assertEquals("Provider creation should be allowed", 201, responseCode); assertAuthenticationProviderExists(providerName); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "DELETE"); assertEquals("Provider deletion should be denied", 403, responseCode); assertAuthenticationProviderExists(providerName); } public void testSetAuthenticationProviderAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String providerName = TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER; assertAuthenticationProviderExists(providerName); File file = TestFileUtils.createTempFile(this, ".users", "guest:guest\n" + ALLOWED_USER + ":" + ALLOWED_USER + "\n" + DENIED_USER + ":" + DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AuthenticationProvider.NAME, providerName); attributes.put(AuthenticationProvider.TYPE, PlainPasswordDatabaseAuthenticationManager.PROVIDER_TYPE); attributes.put(ExternalFileBasedAuthenticationManager.PATH, file.getAbsolutePath()); int responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "PUT", attributes); assertEquals("Setting of provider attribites should be allowed", 200, responseCode); } public void testSetAuthenticationProviderAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String providerName = TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER; Map<String, Object> providerData = getRestTestHelper().getJsonAsSingletonList("authenticationprovider/" + providerName); File file = TestFileUtils.createTempFile(this, ".users", "guest:guest\n" + ALLOWED_USER + ":" + ALLOWED_USER + "\n" + DENIED_USER + ":" + DENIED_USER); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AuthenticationProvider.NAME, providerName); attributes.put(AuthenticationProvider.TYPE, AnonymousAuthenticationManager.PROVIDER_TYPE); attributes.put(ExternalFileBasedAuthenticationManager.PATH, file.getAbsolutePath()); int responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "PUT", attributes); assertEquals("Setting of provider attribites should be allowed", 403, responseCode); Map<String, Object> provider = getRestTestHelper().getJsonAsSingletonList("authenticationprovider/" + providerName); assertEquals("Unexpected STORE_URL attribute value", providerData.get(ExternalFileBasedAuthenticationManager.PATH), provider.get(ExternalFileBasedAuthenticationManager.PATH)); } /* === Port === */ public void testCreatePortAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String portName = getTestName(); int responseCode = createPort(portName); assertEquals("Port creation should be allowed", 201, responseCode); assertPortExists(portName); } public void testCreatePortDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String portName = getTestName(); int responseCode = createPort(portName); assertEquals("Port creation should be denied", 403, responseCode); assertPortDoesNotExist(portName); } public void testDeletePortDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String portName = TestBrokerConfiguration.ENTRY_NAME_AMQP_PORT; assertPortExists(portName); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); int responseCode = getRestTestHelper().submitRequest("port/" + portName, "DELETE"); assertEquals("Port deletion should be denied", 403, responseCode); assertPortExists(portName); } public void testDeletePortAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String portName = TestBrokerConfiguration.ENTRY_NAME_AMQP_PORT; assertPortExists(portName); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); int responseCode = getRestTestHelper().submitRequest("port/" + portName, "DELETE"); assertEquals("Port deletion should be allowed", 200, responseCode); assertPortDoesNotExist(portName); } public void testSetPortAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String portName = getTestName(); int responseCode = createPort(portName); assertEquals("Port creation should be allowed", 201, responseCode); assertPortExists(portName); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(Port.NAME, portName); attributes.put(Port.PROTOCOLS, Arrays.asList(Protocol.AMQP_0_9)); attributes.put(Port.AUTHENTICATION_PROVIDER, TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER); responseCode = getRestTestHelper().submitRequest("port/" + portName, "PUT", attributes); assertEquals("Setting of port attribites should be denied", 403, responseCode); Map<String, Object> port = getRestTestHelper().getJsonAsSingletonList("port/" + portName); assertEquals("Unexpected authentication provider attribute value", TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER, port.get(Port.AUTHENTICATION_PROVIDER)); } /* === KeyStore === */ public void testCreateKeyStoreAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, TestSSLConstants.CERT_ALIAS_APP1); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); } public void testCreateKeyStoreDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String keyStoreName = getTestName(); assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, TestSSLConstants.CERT_ALIAS_APP1); assertEquals("keyStore creation should be allowed", 403, responseCode); assertKeyStoreExistence(keyStoreName, false); } public void testDeleteKeyStoreDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, TestSSLConstants.CERT_ALIAS_APP1); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "DELETE"); assertEquals("keystore deletion should be denied", 403, responseCode); assertKeyStoreExistence(keyStoreName, true); } public void testDeleteKeyStoreAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, TestSSLConstants.CERT_ALIAS_APP1); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "DELETE"); assertEquals("keystore deletion should be allowed", 200, responseCode); assertKeyStoreExistence(keyStoreName, false); } public void testSetKeyStoreAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); String initialCertAlias = TestSSLConstants.CERT_ALIAS_APP1; String updatedCertAlias = TestSSLConstants.CERT_ALIAS_APP2; assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, initialCertAlias); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); Map<String, Object> keyStore = getRestTestHelper().getJsonAsSingletonList("keystore/" + keyStoreName); assertEquals("Unexpected certificateAlias attribute value", initialCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS)); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(KeyStore.NAME, keyStoreName); attributes.put(FileKeyStore.CERTIFICATE_ALIAS, updatedCertAlias); responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "PUT", attributes); assertEquals("Setting of keystore attributes should be allowed", 200, responseCode); keyStore = getRestTestHelper().getJsonAsSingletonList("keystore/" + keyStoreName); assertEquals("Unexpected certificateAlias attribute value", updatedCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS)); } public void testSetKeyStoreAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); String initialCertAlias = TestSSLConstants.CERT_ALIAS_APP1; String updatedCertAlias = TestSSLConstants.CERT_ALIAS_APP2; assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, initialCertAlias); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); Map<String, Object> keyStore = getRestTestHelper().getJsonAsSingletonList("keystore/" + keyStoreName); assertEquals("Unexpected certificateAlias attribute value", initialCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS)); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(KeyStore.NAME, keyStoreName); attributes.put(FileKeyStore.CERTIFICATE_ALIAS, updatedCertAlias); responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "PUT", attributes); assertEquals("Setting of keystore attributes should be denied", 403, responseCode); keyStore = getRestTestHelper().getJsonAsSingletonList("keystore/" + keyStoreName); assertEquals("Unexpected certificateAlias attribute value", initialCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS)); } /* === TrustStore === */ public void testCreateTrustStoreAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, false); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); } public void testCreateTrustStoreDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String trustStoreName = getTestName(); assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, false); assertEquals("trustStore creation should be allowed", 403, responseCode); assertTrustStoreExistence(trustStoreName, false); } public void testDeleteTrustStoreDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, false); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "DELETE"); assertEquals("truststore deletion should be denied", 403, responseCode); assertTrustStoreExistence(trustStoreName, true); } public void testDeleteTrustStoreAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, false); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "DELETE"); assertEquals("truststore deletion should be allowed", 200, responseCode); assertTrustStoreExistence(trustStoreName, false); } public void testSetTrustStoreAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); boolean initialPeersOnly = false; boolean updatedPeersOnly = true; assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, initialPeersOnly); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); Map<String, Object> trustStore = getRestTestHelper().getJsonAsSingletonList("truststore/" + trustStoreName); assertEquals("Unexpected peersOnly attribute value", initialPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY)); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(TrustStore.NAME, trustStoreName); attributes.put(FileTrustStore.PEERS_ONLY, updatedPeersOnly); responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "PUT", attributes); assertEquals("Setting of truststore attributes should be allowed", 200, responseCode); trustStore = getRestTestHelper().getJsonAsSingletonList("truststore/" + trustStoreName); assertEquals("Unexpected peersOnly attribute value", updatedPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY)); } public void testSetTrustStoreAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); boolean initialPeersOnly = false; boolean updatedPeersOnly = true; assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, initialPeersOnly); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); Map<String, Object> trustStore = getRestTestHelper().getJsonAsSingletonList("truststore/" + trustStoreName); assertEquals("Unexpected peersOnly attribute value", initialPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY)); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(TrustStore.NAME, trustStoreName); attributes.put(FileTrustStore.PEERS_ONLY, updatedPeersOnly); responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "PUT", attributes); assertEquals("Setting of truststore attributes should be denied", 403, responseCode); trustStore = getRestTestHelper().getJsonAsSingletonList("truststore/" + trustStoreName); assertEquals("Unexpected peersOnly attribute value", initialPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY)); } /* === Broker === */ public void testSetBrokerAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); int initialSessionCountLimit = 256; int updatedSessionCountLimit = 299; Map<String, Object> brokerAttributes = getRestTestHelper().getJsonAsSingletonList("broker"); assertEquals("Unexpected alert repeat gap", initialSessionCountLimit, brokerAttributes.get(Broker.CONNECTION_SESSION_COUNT_LIMIT)); Map<String, Object> newAttributes = new HashMap<String, Object>(); newAttributes.put(Broker.CONNECTION_SESSION_COUNT_LIMIT, updatedSessionCountLimit); int responseCode = getRestTestHelper().submitRequest("broker", "PUT", newAttributes); assertEquals("Setting of port attribites should be allowed", 200, responseCode); brokerAttributes = getRestTestHelper().getJsonAsSingletonList("broker"); assertEquals("Unexpected default alert repeat gap", updatedSessionCountLimit, brokerAttributes.get(Broker.CONNECTION_SESSION_COUNT_LIMIT)); } public void testSetBrokerAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); int initialSessionCountLimit = 256; int updatedSessionCountLimit = 299; Map<String, Object> brokerAttributes = getRestTestHelper().getJsonAsSingletonList("broker"); assertEquals("Unexpected alert repeat gap", initialSessionCountLimit, brokerAttributes.get(Broker.CONNECTION_SESSION_COUNT_LIMIT)); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> newAttributes = new HashMap<String, Object>(); newAttributes.put(Broker.CONNECTION_SESSION_COUNT_LIMIT, updatedSessionCountLimit); int responseCode = getRestTestHelper().submitRequest("broker", "PUT", newAttributes); assertEquals("Setting of port attribites should be allowed", 403, responseCode); brokerAttributes = getRestTestHelper().getJsonAsSingletonList("broker"); assertEquals("Unexpected default alert repeat gap", initialSessionCountLimit, brokerAttributes.get(Broker.CONNECTION_SESSION_COUNT_LIMIT)); } /* === GroupProvider === */ public void testCreateGroupProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); } public void testCreateGroupProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be denied", 403, responseCode); assertGroupProviderExistence(groupProviderName, false); } public void testDeleteGroupProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "DELETE"); assertEquals("Group provider deletion should be denied", 403, responseCode); assertGroupProviderExistence(groupProviderName, true); } public void testDeleteGroupProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "DELETE"); assertEquals("Group provider deletion should be allowed", 200, responseCode); assertGroupProviderExistence(groupProviderName, false); } public void testSetGroupProviderAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(GroupProvider.NAME, groupProviderName); attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); attributes.put(FileBasedGroupProvider.PATH, "/path/to/file"); responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "PUT", attributes); assertEquals("Setting of group provider attributes should be allowed but not supported", AbstractServlet.SC_UNPROCESSABLE_ENTITY, responseCode); } public void testSetGroupProviderAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(GroupProvider.NAME, groupProviderName); attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); attributes.put(FileBasedGroupProvider.PATH, "/path/to/file"); responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "PUT", attributes); assertEquals("Setting of group provider attributes should be denied", 403, responseCode); } /* === AccessControlProvider === */ public void testCreateAccessControlProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String accessControlProviderName = getTestName(); assertAccessControlProviderExistence(accessControlProviderName, false); int responseCode = createAccessControlProvider(accessControlProviderName); assertEquals("Access control provider creation should be denied", 403, responseCode); assertAccessControlProviderExistence(accessControlProviderName, false); } public void testDeleteAccessControlProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "DELETE"); assertEquals("Access control provider deletion should be denied", 403, responseCode); assertAccessControlProviderExistence(accessControlProviderName, true); } public void testDeleteAccessControlProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "DELETE"); assertEquals("Access control provider deletion should be allowed", 200, responseCode); assertAccessControlProviderExistence(accessControlProviderName, false); } public void testSetAccessControlProviderAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); File aclFile = TestFileUtils.createTempFile(this, ".acl", "ACL ALLOW all all"); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AccessControlProvider.NAME, accessControlProviderName); attributes.put(FileBasedGroupProvider.PATH, aclFile.getAbsolutePath()); int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes); assertEquals("Setting of access control provider attributes should be allowed", 200, responseCode); } public void testSetAccessControlProviderAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(GroupProvider.NAME, accessControlProviderName); attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); attributes.put(FileBasedGroupProvider.PATH, "/path/to/file"); int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes); assertEquals("Setting of access control provider attributes should be denied", 403, responseCode); } /* === HTTP management === */ public void testSetHttpManagementAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(HttpManagement.NAME, TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT); attributes.put(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.TIME_OUT, 10000); int responseCode = getRestTestHelper().submitRequest( "plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT, "PUT", attributes); assertEquals("Setting of http management should be allowed", 200, responseCode); Map<String, Object> details = getRestTestHelper().getJsonAsSingletonList( "plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT); assertEquals("Unexpected session timeout", 10000, details.get(HttpManagement.TIME_OUT)); assertEquals("Unexpected http basic auth enabled", true, details.get(HttpManagement.HTTP_BASIC_AUTHENTICATION_ENABLED)); assertEquals("Unexpected https basic auth enabled", false, details.get(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED)); assertEquals("Unexpected http sasl auth enabled", false, details.get(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED)); assertEquals("Unexpected https sasl auth enabled", false, details.get(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED)); } public void testSetHttpManagementAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(HttpManagement.NAME, TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT); attributes.put(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.TIME_OUT, 10000); int responseCode = getRestTestHelper().submitRequest( "plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT, "PUT", attributes); assertEquals("Setting of http management should be denied", 403, responseCode); Map<String, Object> details = getRestTestHelper().getJsonAsSingletonList( "plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT); assertEquals("Unexpected session timeout", HttpManagement.DEFAULT_TIMEOUT_IN_SECONDS, details.get(HttpManagement.TIME_OUT)); assertEquals("Unexpected http basic auth enabled", true, details.get(HttpManagement.HTTP_BASIC_AUTHENTICATION_ENABLED)); assertEquals("Unexpected https basic auth enabled", true, details.get(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED)); assertEquals("Unexpected http sasl auth enabled", true, details.get(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED)); assertEquals("Unexpected https sasl auth enabled", true, details.get(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED)); } /* === Broker Logger === */ public void testCreateBrokerLoggerAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerLogger.NAME, "testLogger1"); attributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "testLogger2"); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest("brokerlogger/testLogger2", "GET", HttpServletResponse.SC_NOT_FOUND); } public void testDeleteBrokerLoggerAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerLogger.NAME, "testLogger1"); attributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "DELETE", null, HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "DELETE", null, HttpServletResponse.SC_OK); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_NOT_FOUND); } public void testDownloadBrokerLoggerFileAllowedDenied() throws Exception { final String loggerName = "testFileLogger"; final String loggerPath = "brokerlogger/" + loggerName; getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerLogger.NAME, loggerName); attributes.put(ConfiguredObject.TYPE, BrokerFileLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_OK); getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_OK); getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_FORBIDDEN); } public void testViewMemoryLoggerEntriesAllowedDenied() throws Exception { final String loggerName = "testMemoryLogger"; final String loggerPath = "brokerlogger/" + loggerName; getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerLogger.NAME, loggerName); attributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest(loggerPath + "/getLogEntries?lastLogId=0", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest(loggerPath + "/getLogEntries?lastLogId=0", "GET", HttpServletResponse.SC_FORBIDDEN); } /* === Broker Log Inclusion Rules === */ public void testCreateBrokerLoggerRuleAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> loggerAttributes = new HashMap<>(); loggerAttributes.put(BrokerLogger.NAME, "testLogger1"); loggerAttributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", loggerAttributes, HttpServletResponse.SC_CREATED); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1"); attributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "DEBUG"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule2"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", attributes, HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule2", "GET", HttpServletResponse.SC_NOT_FOUND); } public void testUpdateBrokerLoggerRuleAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> loggerAttributes = new HashMap<>(); loggerAttributes.put(BrokerLogger.NAME, "testLogger1"); loggerAttributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", loggerAttributes, HttpServletResponse.SC_CREATED); Map<String, Object> ruleAttributes = new HashMap<>(); ruleAttributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1"); ruleAttributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); ruleAttributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "INFO"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", ruleAttributes, HttpServletResponse.SC_CREATED); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1"); attributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "DEBUG"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "PUT", attributes, HttpServletResponse.SC_OK); Map<String,Object> resultAfterUpdate = getRestTestHelper().getJsonAsSingletonList("brokerloginclusionrule/testLogger1/rule1"); assertEquals("Log level was not changed", "DEBUG", resultAfterUpdate.get(BrokerNameAndLevelLogInclusionRule.LEVEL)); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "INFO"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "PUT", attributes, HttpServletResponse.SC_FORBIDDEN); Map<String,Object> resultAfterDeniedUpdate = getRestTestHelper().getJsonAsSingletonList("brokerloginclusionrule/testLogger1/rule1"); assertEquals("Log level was changed by not allowed user", "DEBUG", resultAfterDeniedUpdate.get(BrokerNameAndLevelLogInclusionRule.LEVEL)); } public void testDeleteBrokerLoggerRuleAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> loggerAttributes = new HashMap<>(); loggerAttributes.put(BrokerLogger.NAME, "testLogger1"); loggerAttributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", loggerAttributes, HttpServletResponse.SC_CREATED); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1"); attributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "DEBUG"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "DELETE", null, HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "DELETE", null, HttpServletResponse.SC_OK); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_NOT_FOUND); } /* === Utility Methods === */ private int createPort(String portName) throws Exception { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(Port.NAME, portName); attributes.put(Port.PORT, 0); attributes.put(Port.AUTHENTICATION_PROVIDER, TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER); return getRestTestHelper().submitRequest("port/" + portName, "PUT", attributes); } private void assertPortExists(String portName) throws Exception { assertPortExistence(portName, true); } private void assertPortDoesNotExist(String portName) throws Exception { assertPortExistence(portName, false); } private void assertPortExistence(String portName, boolean exists) throws Exception { String path = "port/" + portName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private void assertKeyStoreExistence(String keyStoreName, boolean exists) throws Exception { String path = "keystore/" + keyStoreName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private void assertTrustStoreExistence(String trustStoreName, boolean exists) throws Exception { String path = "truststore/" + trustStoreName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private int createAuthenticationProvider(String authenticationProviderName) throws Exception { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AuthenticationProvider.NAME, authenticationProviderName); attributes.put(AuthenticationProvider.TYPE, AnonymousAuthenticationManager.PROVIDER_TYPE); return getRestTestHelper().submitRequest("authenticationprovider/" + authenticationProviderName, "PUT", attributes); } private void assertAuthenticationProviderDoesNotExist(String authenticationProviderName) throws Exception { assertAuthenticationProviderExistence(authenticationProviderName, false); } private void assertAuthenticationProviderExists(String authenticationProviderName) throws Exception { assertAuthenticationProviderExistence(authenticationProviderName, true); } private void assertAuthenticationProviderExistence(String authenticationProviderName, boolean exists) throws Exception { String path = "authenticationprovider/" + authenticationProviderName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private int createKeyStore(String name, String certAlias) throws IOException { Map<String, Object> keyStoreAttributes = new HashMap<String, Object>(); keyStoreAttributes.put(KeyStore.NAME, name); keyStoreAttributes.put(FileKeyStore.STORE_URL, TestSSLConstants.KEYSTORE); keyStoreAttributes.put(FileKeyStore.PASSWORD, TestSSLConstants.KEYSTORE_PASSWORD); keyStoreAttributes.put(FileKeyStore.CERTIFICATE_ALIAS, certAlias); return getRestTestHelper().submitRequest("keystore/" + name, "PUT", keyStoreAttributes); } private int createTrustStore(String name, boolean peersOnly) throws IOException { Map<String, Object> trustStoreAttributes = new HashMap<String, Object>(); trustStoreAttributes.put(TrustStore.NAME, name); trustStoreAttributes.put(FileTrustStore.STORE_URL, TestSSLConstants.KEYSTORE); trustStoreAttributes.put(FileTrustStore.PASSWORD, TestSSLConstants.KEYSTORE_PASSWORD); trustStoreAttributes.put(FileTrustStore.PEERS_ONLY, peersOnly); return getRestTestHelper().submitRequest("truststore/" + name, "PUT", trustStoreAttributes); } private void assertGroupProviderExistence(String groupProviderName, boolean exists) throws Exception { String path = "groupprovider/" + groupProviderName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private int createGroupProvider(String groupProviderName) throws Exception { File file = TestFileUtils.createTempFile(this, ".groups"); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(GroupProvider.NAME, groupProviderName); attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); attributes.put(FileBasedGroupProvider.PATH, file.getAbsoluteFile()); return getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "PUT", attributes); } private void assertAccessControlProviderExistence(String accessControlProviderName, boolean exists) throws Exception { String path = "accesscontrolprovider/" + accessControlProviderName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private int createAccessControlProvider(String accessControlProviderName) throws Exception { File file = TestFileUtils.createTempFile(this, ".acl", _secondaryAclFileContent); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AccessControlProvider.NAME, accessControlProviderName); attributes.put(AccessControlProvider.TYPE, FileAccessControlProviderConstants.ACL_FILE_PROVIDER_TYPE); attributes.put(FileAccessControlProviderConstants.PATH, file.getAbsoluteFile()); return getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes); } }
pkt1583/qpid-java
systests/src/test/java/org/apache/qpid/systest/rest/acl/BrokerACLTest.java
213,278
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.qpid.systest.rest.acl; import java.io.File; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.qpid.server.logging.logback.VirtualHostFileLogger; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.model.VirtualHostLogger; import org.apache.qpid.server.model.VirtualHostNode; import org.apache.qpid.server.security.acl.AbstractACLTestCase; import org.apache.qpid.server.virtualhost.ProvidedStoreVirtualHostImpl; import org.apache.qpid.server.virtualhostnode.JsonVirtualHostNode; import org.apache.qpid.systest.rest.QpidRestTestCase; import org.apache.qpid.test.utils.TestBrokerConfiguration; public class VirtualHostACLTest extends QpidRestTestCase { private static final String VHN_WITHOUT_VH = "myVhnWithoutVh"; private static final String ALLOWED_USER = "user1"; private static final String DENIED_USER = "user2"; private static final String RESTRICTED_USER = "restricted"; @Override protected void customizeConfiguration() throws Exception { super.customizeConfiguration(); final TestBrokerConfiguration defaultBrokerConfiguration = getDefaultBrokerConfiguration(); defaultBrokerConfiguration.configureTemporaryPasswordFile(ALLOWED_USER, DENIED_USER, RESTRICTED_USER); AbstractACLTestCase.writeACLFileUtil(this, "ACL ALLOW-LOG ALL ACCESS MANAGEMENT", "ACL ALLOW-LOG " + ALLOWED_USER + " ALL VIRTUALHOST", "ACL ALLOW-LOG " + RESTRICTED_USER + " ALL VIRTUALHOST attributes=\"description\"", "ACL DENY-LOG " + DENIED_USER + " ALL VIRTUALHOST", "ACL DENY-LOG ALL ALL"); Map<String, Object> virtualHostNodeAttributes = new HashMap<>(); virtualHostNodeAttributes.put(VirtualHostNode.NAME, VHN_WITHOUT_VH); virtualHostNodeAttributes.put(VirtualHostNode.TYPE, getTestProfileVirtualHostNodeType()); // TODO need better way to determine the VHN's optional attributes virtualHostNodeAttributes.put(JsonVirtualHostNode.STORE_PATH, getStoreLocation(VHN_WITHOUT_VH)); defaultBrokerConfiguration.addObjectConfiguration(VirtualHostNode.class, virtualHostNodeAttributes); } public void testCreateVirtualHostAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String hostName = getTestName(); int responseCode = createVirtualHost(VHN_WITHOUT_VH, hostName); assertEquals("Virtual host creation should be allowed", HttpServletResponse.SC_CREATED, responseCode); assertVirtualHostExists(VHN_WITHOUT_VH, hostName); } public void testCreateVirtualHostDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String hostName = getTestName(); int responseCode = createVirtualHost(VHN_WITHOUT_VH, hostName); assertEquals("Virtual host creation should be denied", HttpServletResponse.SC_FORBIDDEN, responseCode); assertVirtualHostDoesNotExist(VHN_WITHOUT_VH, hostName); } public void testDeleteVirtualHostDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest("virtualhost/" + TEST2_VIRTUALHOST + "/" + TEST2_VIRTUALHOST, "DELETE", HttpServletResponse.SC_FORBIDDEN); assertVirtualHostExists(TEST2_VIRTUALHOST, TEST2_VIRTUALHOST); } public void testUpdateRestrictedAttributes() throws Exception { getRestTestHelper().setUsernameAndPassword(RESTRICTED_USER, RESTRICTED_USER); String virtualHostUrl = "virtualhost/" + TEST2_VIRTUALHOST + "/" + TEST2_VIRTUALHOST; getRestTestHelper().submitRequest(virtualHostUrl, "PUT", Collections.singletonMap(VirtualHost.CONTEXT, Collections.singletonMap("test1", "test2")), HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest(virtualHostUrl, "PUT", Collections.singletonMap(VirtualHost.DESCRIPTION, "Test Description"), HttpServletResponse.SC_OK); } public void testUpdateVirtualHostDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(VirtualHost.NAME, TEST2_VIRTUALHOST); attributes.put(VirtualHost.DESCRIPTION, "new description"); getRestTestHelper().submitRequest("virtualhost/" + TEST2_VIRTUALHOST + "/" + TEST2_VIRTUALHOST, "PUT", attributes, HttpServletResponse.SC_FORBIDDEN); } public void testDownloadVirtualHostLoggerFileAllowedDenied() throws Exception { final String virtualHostName = "testVirtualHost"; final String loggerName = "testFileLogger"; final String loggerPath = "virtualhostlogger/" + VHN_WITHOUT_VH + "/" + virtualHostName + "/" + loggerName; getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); createVirtualHost(VHN_WITHOUT_VH, virtualHostName); Map<String, Object> attributes = new HashMap<>(); attributes.put(VirtualHostLogger.NAME, loggerName); attributes.put(ConfiguredObject.TYPE, VirtualHostFileLogger.TYPE); getRestTestHelper().submitRequest("virtualhostlogger/" + VHN_WITHOUT_VH + "/" + virtualHostName, "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_OK); getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_OK); getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_FORBIDDEN); } /* === Utility Methods === */ private int createVirtualHost(final String testVirtualHostNode, String virtualHostName) throws Exception { Map<String, Object> data = new HashMap<>(); data.put(VirtualHost.NAME, virtualHostName); data.put(VirtualHost.TYPE, ProvidedStoreVirtualHostImpl.VIRTUAL_HOST_TYPE); return getRestTestHelper().submitRequest("virtualhost/" + testVirtualHostNode + "/" + virtualHostName, "PUT", data); } private void assertVirtualHostDoesNotExist(final String virtualHostNodeName, String virtualHostName) throws Exception { assertVirtualHostExistence(virtualHostNodeName, virtualHostName, false); } private void assertVirtualHostExists(final String virtualHostNodeName, String virtualHostName) throws Exception { assertVirtualHostExistence(virtualHostNodeName, virtualHostName, true); } private void assertVirtualHostExistence(final String virtualHostNodeName, String virtualHostName, boolean exists) throws Exception { String path = "virtualhost/" + virtualHostNodeName + "/" + virtualHostName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private String getStoreLocation(String hostName) { return new File(TMP_FOLDER, "store-" + hostName + "-" + System.currentTimeMillis()).getAbsolutePath(); } }
acidburn0zzz/qpid-broker-j
systests/src/test/java/org/apache/qpid/systest/rest/acl/VirtualHostACLTest.java
213,279
/* * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.helidon.security.abac.role; import java.util.Optional; import javax.annotation.security.RolesAllowed; import io.helidon.common.CollectionsHelper; import io.helidon.common.Errors; import io.helidon.security.Principal; import io.helidon.security.ProviderRequest; import io.helidon.security.Role; import io.helidon.security.Subject; import io.helidon.security.SubjectType; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Unit test for {@link RoleValidator}. */ class RoleValidatorTest { @Test void testRolesAllowedPermit() { RoleValidator validator = RoleValidator.create(); RolesAllowed annot = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(CollectionsHelper.listOf(annot)); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testRolesAllowedDeny() { RoleValidator validator = RoleValidator.create(); RolesAllowed annot = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(CollectionsHelper.listOf(annot)); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("User is not in admin role, should have failed"); } } @Test void testUserRoles() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); when(annot.subjectType()).thenReturn(SubjectType.USER); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(CollectionsHelper.listOf(annot)); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testUserRolesDeny() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.subjectType()).thenReturn(SubjectType.USER); when(annot.value()).thenReturn(roleArray); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(CollectionsHelper.listOf(annot)); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("User is not in admin role, should have failed"); } } @Test void testServiceRoles() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); when(annot.subjectType()).thenReturn(SubjectType.SERVICE); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(CollectionsHelper.listOf(annot)); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.service()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("service")) .addGrant(Role.create("admin")) .build())); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testServiceRolesDeny() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); when(annot.subjectType()).thenReturn(SubjectType.SERVICE); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(CollectionsHelper.listOf(annot)); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("service")) .addGrant(Role.create("user")) .build())); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("Service is not in admin role, should have failed"); } } }
monad-one/helidon
security/abac/role/src/test/java/io/helidon/security/abac/role/RoleValidatorTest.java
213,280
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.qpid.systest.rest.acl; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.qpid.server.logging.BrokerFileLogger; import org.apache.qpid.server.logging.BrokerMemoryLogger; import org.apache.qpid.server.logging.BrokerNameAndLevelLogInclusionRule; import org.apache.qpid.server.management.plugin.HttpManagement; import org.apache.qpid.server.management.plugin.servlet.rest.AbstractServlet; import org.apache.qpid.server.model.AccessControlProvider; import org.apache.qpid.server.model.AuthenticationProvider; import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.BrokerLogger; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.ExternalFileBasedAuthenticationManager; import org.apache.qpid.server.model.GroupProvider; import org.apache.qpid.server.model.KeyStore; import org.apache.qpid.server.model.Port; import org.apache.qpid.server.model.Protocol; import org.apache.qpid.server.model.TrustStore; import org.apache.qpid.server.model.adapter.FileBasedGroupProvider; import org.apache.qpid.server.model.adapter.FileBasedGroupProviderImpl; import org.apache.qpid.server.security.AllowAllAccessControlProvider; import org.apache.qpid.server.security.FileKeyStore; import org.apache.qpid.server.security.FileTrustStore; import org.apache.qpid.server.security.access.plugins.ACLFileAccessControlProvider; import org.apache.qpid.server.security.acl.AbstractACLTestCase; import org.apache.qpid.server.security.auth.manager.AnonymousAuthenticationManager; import org.apache.qpid.server.security.auth.manager.PlainPasswordDatabaseAuthenticationManager; import org.apache.qpid.systest.rest.QpidRestTestCase; import org.apache.qpid.test.utils.TestBrokerConfiguration; import org.apache.qpid.test.utils.TestFileUtils; import org.apache.qpid.test.utils.TestSSLConstants; public class BrokerACLTest extends QpidRestTestCase { private static final String ALLOWED_USER = "user1"; private static final String DENIED_USER = "user2"; private String _secondaryAclFileContent = ""; @Override protected void customizeConfiguration() throws Exception { super.customizeConfiguration(); final TestBrokerConfiguration defaultBrokerConfiguration = getDefaultBrokerConfiguration(); defaultBrokerConfiguration.configureTemporaryPasswordFile(ALLOWED_USER, DENIED_USER); AbstractACLTestCase.writeACLFileUtil(this, "ACL ALLOW-LOG ALL ACCESS MANAGEMENT", "ACL ALLOW-LOG " + ALLOWED_USER + " CONFIGURE BROKER", "ACL DENY-LOG " + DENIED_USER + " CONFIGURE BROKER", "ACL ALLOW-LOG " + ALLOWED_USER + " ACCESS_LOGS BROKER", "ACL DENY-LOG " + DENIED_USER + " ACCESS_LOGS BROKER", "ACL DENY-LOG ALL ALL"); _secondaryAclFileContent = "ACL ALLOW-LOG ALL ACCESS MANAGEMENT\n" + "ACL ALLOW-LOG " + ALLOWED_USER + " CONFIGURE BROKER\n" + "ACL DENY-LOG " + DENIED_USER + " CONFIGURE BROKER\n" + "ACL DENY-LOG ALL ALL"; } /* === AuthenticationProvider === */ public void testCreateAuthenticationProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String authenticationProviderName = getTestName(); int responseCode = createAuthenticationProvider(authenticationProviderName); assertEquals("Provider creation should be allowed", 201, responseCode); assertAuthenticationProviderExists(authenticationProviderName); } public void testCreateAuthenticationProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String authenticationProviderName = getTestName(); int responseCode = createAuthenticationProvider(authenticationProviderName); assertEquals("Provider creation should be denied", 403, responseCode); assertAuthenticationProviderDoesNotExist(authenticationProviderName); } public void testDeleteAuthenticationProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String providerName = getTestName(); int responseCode = createAuthenticationProvider(providerName); assertEquals("Provider creation should be allowed", 201, responseCode); assertAuthenticationProviderExists(providerName); responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "DELETE"); assertEquals("Provider deletion should be allowed", 200, responseCode); assertAuthenticationProviderDoesNotExist(TEST2_VIRTUALHOST); } public void testDeleteAuthenticationProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String providerName = getTestName(); int responseCode = createAuthenticationProvider(providerName); assertEquals("Provider creation should be allowed", 201, responseCode); assertAuthenticationProviderExists(providerName); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "DELETE"); assertEquals("Provider deletion should be denied", 403, responseCode); assertAuthenticationProviderExists(providerName); } public void testSetAuthenticationProviderAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String providerName = TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER; assertAuthenticationProviderExists(providerName); File file = TestFileUtils.createTempFile(this, ".users", "guest:guest\n" + ALLOWED_USER + ":" + ALLOWED_USER + "\n" + DENIED_USER + ":" + DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AuthenticationProvider.NAME, providerName); attributes.put(AuthenticationProvider.TYPE, PlainPasswordDatabaseAuthenticationManager.PROVIDER_TYPE); attributes.put(ExternalFileBasedAuthenticationManager.PATH, file.getAbsolutePath()); int responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "PUT", attributes); assertEquals("Setting of provider attribites should be allowed", 200, responseCode); } public void testSetAuthenticationProviderAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String providerName = TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER; Map<String, Object> providerData = getRestTestHelper().getJsonAsSingletonList("authenticationprovider/" + providerName); File file = TestFileUtils.createTempFile(this, ".users", "guest:guest\n" + ALLOWED_USER + ":" + ALLOWED_USER + "\n" + DENIED_USER + ":" + DENIED_USER); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AuthenticationProvider.NAME, providerName); attributes.put(AuthenticationProvider.TYPE, AnonymousAuthenticationManager.PROVIDER_TYPE); attributes.put(ExternalFileBasedAuthenticationManager.PATH, file.getAbsolutePath()); int responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "PUT", attributes); assertEquals("Setting of provider attribites should be allowed", 403, responseCode); Map<String, Object> provider = getRestTestHelper().getJsonAsSingletonList("authenticationprovider/" + providerName); assertEquals("Unexpected STORE_URL attribute value", providerData.get(ExternalFileBasedAuthenticationManager.PATH), provider.get(ExternalFileBasedAuthenticationManager.PATH)); } /* === Port === */ public void testCreatePortAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String portName = getTestName(); int responseCode = createPort(portName); assertEquals("Port creation should be allowed", 201, responseCode); assertPortExists(portName); } public void testCreatePortDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String portName = getTestName(); int responseCode = createPort(portName); assertEquals("Port creation should be denied", 403, responseCode); assertPortDoesNotExist(portName); } public void testDeletePortDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String portName = TestBrokerConfiguration.ENTRY_NAME_AMQP_PORT; assertPortExists(portName); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); int responseCode = getRestTestHelper().submitRequest("port/" + portName, "DELETE"); assertEquals("Port deletion should be denied", 403, responseCode); assertPortExists(portName); } public void testDeletePortAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String portName = TestBrokerConfiguration.ENTRY_NAME_AMQP_PORT; assertPortExists(portName); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); int responseCode = getRestTestHelper().submitRequest("port/" + portName, "DELETE"); assertEquals("Port deletion should be allowed", 200, responseCode); assertPortDoesNotExist(portName); } public void testSetPortAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String portName = getTestName(); int responseCode = createPort(portName); assertEquals("Port creation should be allowed", 201, responseCode); assertPortExists(portName); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(Port.NAME, portName); attributes.put(Port.PROTOCOLS, Arrays.asList(Protocol.AMQP_0_9)); attributes.put(Port.AUTHENTICATION_PROVIDER, TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER); responseCode = getRestTestHelper().submitRequest("port/" + portName, "PUT", attributes); assertEquals("Setting of port attribites should be denied", 403, responseCode); Map<String, Object> port = getRestTestHelper().getJsonAsSingletonList("port/" + portName); assertEquals("Unexpected authentication provider attribute value", TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER, port.get(Port.AUTHENTICATION_PROVIDER)); } /* === KeyStore === */ public void testCreateKeyStoreAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, TestSSLConstants.CERT_ALIAS_APP1); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); } public void testCreateKeyStoreDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String keyStoreName = getTestName(); assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, TestSSLConstants.CERT_ALIAS_APP1); assertEquals("keyStore creation should be allowed", 403, responseCode); assertKeyStoreExistence(keyStoreName, false); } public void testDeleteKeyStoreDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, TestSSLConstants.CERT_ALIAS_APP1); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "DELETE"); assertEquals("keystore deletion should be denied", 403, responseCode); assertKeyStoreExistence(keyStoreName, true); } public void testDeleteKeyStoreAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, TestSSLConstants.CERT_ALIAS_APP1); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "DELETE"); assertEquals("keystore deletion should be allowed", 200, responseCode); assertKeyStoreExistence(keyStoreName, false); } public void testSetKeyStoreAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); String initialCertAlias = TestSSLConstants.CERT_ALIAS_APP1; String updatedCertAlias = TestSSLConstants.CERT_ALIAS_APP2; assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, initialCertAlias); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); Map<String, Object> keyStore = getRestTestHelper().getJsonAsSingletonList("keystore/" + keyStoreName); assertEquals("Unexpected certificateAlias attribute value", initialCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS)); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(KeyStore.NAME, keyStoreName); attributes.put(FileKeyStore.CERTIFICATE_ALIAS, updatedCertAlias); responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "PUT", attributes); assertEquals("Setting of keystore attributes should be allowed", 200, responseCode); keyStore = getRestTestHelper().getJsonAsSingletonList("keystore/" + keyStoreName); assertEquals("Unexpected certificateAlias attribute value", updatedCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS)); } public void testSetKeyStoreAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String keyStoreName = getTestName(); String initialCertAlias = TestSSLConstants.CERT_ALIAS_APP1; String updatedCertAlias = TestSSLConstants.CERT_ALIAS_APP2; assertKeyStoreExistence(keyStoreName, false); int responseCode = createKeyStore(keyStoreName, initialCertAlias); assertEquals("keyStore creation should be allowed", 201, responseCode); assertKeyStoreExistence(keyStoreName, true); Map<String, Object> keyStore = getRestTestHelper().getJsonAsSingletonList("keystore/" + keyStoreName); assertEquals("Unexpected certificateAlias attribute value", initialCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS)); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(KeyStore.NAME, keyStoreName); attributes.put(FileKeyStore.CERTIFICATE_ALIAS, updatedCertAlias); responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "PUT", attributes); assertEquals("Setting of keystore attributes should be denied", 403, responseCode); keyStore = getRestTestHelper().getJsonAsSingletonList("keystore/" + keyStoreName); assertEquals("Unexpected certificateAlias attribute value", initialCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS)); } /* === TrustStore === */ public void testCreateTrustStoreAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, false); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); } public void testCreateTrustStoreDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String trustStoreName = getTestName(); assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, false); assertEquals("trustStore creation should be allowed", 403, responseCode); assertTrustStoreExistence(trustStoreName, false); } public void testDeleteTrustStoreDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, false); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "DELETE"); assertEquals("truststore deletion should be denied", 403, responseCode); assertTrustStoreExistence(trustStoreName, true); } public void testDeleteTrustStoreAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, false); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "DELETE"); assertEquals("truststore deletion should be allowed", 200, responseCode); assertTrustStoreExistence(trustStoreName, false); } public void testSetTrustStoreAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); boolean initialPeersOnly = false; boolean updatedPeersOnly = true; assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, initialPeersOnly); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); Map<String, Object> trustStore = getRestTestHelper().getJsonAsSingletonList("truststore/" + trustStoreName); assertEquals("Unexpected peersOnly attribute value", initialPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY)); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(TrustStore.NAME, trustStoreName); attributes.put(FileTrustStore.PEERS_ONLY, updatedPeersOnly); responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "PUT", attributes); assertEquals("Setting of truststore attributes should be allowed", 200, responseCode); trustStore = getRestTestHelper().getJsonAsSingletonList("truststore/" + trustStoreName); assertEquals("Unexpected peersOnly attribute value", updatedPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY)); } public void testSetTrustStoreAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String trustStoreName = getTestName(); boolean initialPeersOnly = false; boolean updatedPeersOnly = true; assertTrustStoreExistence(trustStoreName, false); int responseCode = createTrustStore(trustStoreName, initialPeersOnly); assertEquals("trustStore creation should be allowed", 201, responseCode); assertTrustStoreExistence(trustStoreName, true); Map<String, Object> trustStore = getRestTestHelper().getJsonAsSingletonList("truststore/" + trustStoreName); assertEquals("Unexpected peersOnly attribute value", initialPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY)); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(TrustStore.NAME, trustStoreName); attributes.put(FileTrustStore.PEERS_ONLY, updatedPeersOnly); responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "PUT", attributes); assertEquals("Setting of truststore attributes should be denied", 403, responseCode); trustStore = getRestTestHelper().getJsonAsSingletonList("truststore/" + trustStoreName); assertEquals("Unexpected peersOnly attribute value", initialPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY)); } /* === Broker === */ public void testSetBrokerAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); int initialSessionCountLimit = 256; int updatedSessionCountLimit = 299; Map<String, Object> brokerAttributes = getRestTestHelper().getJsonAsSingletonList("broker"); assertEquals("Unexpected alert repeat gap", initialSessionCountLimit, brokerAttributes.get(Broker.CONNECTION_SESSION_COUNT_LIMIT)); Map<String, Object> newAttributes = new HashMap<String, Object>(); newAttributes.put(Broker.CONNECTION_SESSION_COUNT_LIMIT, updatedSessionCountLimit); int responseCode = getRestTestHelper().submitRequest("broker", "PUT", newAttributes); assertEquals("Setting of port attribites should be allowed", 200, responseCode); brokerAttributes = getRestTestHelper().getJsonAsSingletonList("broker"); assertEquals("Unexpected default alert repeat gap", updatedSessionCountLimit, brokerAttributes.get(Broker.CONNECTION_SESSION_COUNT_LIMIT)); } public void testSetBrokerAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); int initialSessionCountLimit = 256; int updatedSessionCountLimit = 299; Map<String, Object> brokerAttributes = getRestTestHelper().getJsonAsSingletonList("broker"); assertEquals("Unexpected alert repeat gap", initialSessionCountLimit, brokerAttributes.get(Broker.CONNECTION_SESSION_COUNT_LIMIT)); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> newAttributes = new HashMap<String, Object>(); newAttributes.put(Broker.CONNECTION_SESSION_COUNT_LIMIT, updatedSessionCountLimit); int responseCode = getRestTestHelper().submitRequest("broker", "PUT", newAttributes); assertEquals("Setting of port attribites should be allowed", 403, responseCode); brokerAttributes = getRestTestHelper().getJsonAsSingletonList("broker"); assertEquals("Unexpected default alert repeat gap", initialSessionCountLimit, brokerAttributes.get(Broker.CONNECTION_SESSION_COUNT_LIMIT)); } /* === GroupProvider === */ public void testCreateGroupProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); } public void testCreateGroupProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be denied", 403, responseCode); assertGroupProviderExistence(groupProviderName, false); } public void testDeleteGroupProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "DELETE"); assertEquals("Group provider deletion should be denied", 403, responseCode); assertGroupProviderExistence(groupProviderName, true); } public void testDeleteGroupProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "DELETE"); assertEquals("Group provider deletion should be allowed", 200, responseCode); assertGroupProviderExistence(groupProviderName, false); } public void testSetGroupProviderAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(GroupProvider.NAME, groupProviderName); attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); attributes.put(FileBasedGroupProvider.PATH, "/path/to/file"); responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "PUT", attributes); assertEquals("Setting of group provider attributes should be allowed but not supported", AbstractServlet.SC_UNPROCESSABLE_ENTITY, responseCode); } public void testSetGroupProviderAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String groupProviderName = getTestName(); assertGroupProviderExistence(groupProviderName, false); int responseCode = createGroupProvider(groupProviderName); assertEquals("Group provider creation should be allowed", 201, responseCode); assertGroupProviderExistence(groupProviderName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(GroupProvider.NAME, groupProviderName); attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); attributes.put(FileBasedGroupProvider.PATH, "/path/to/file"); responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "PUT", attributes); assertEquals("Setting of group provider attributes should be denied", 403, responseCode); } /* === AccessControlProvider === */ public void testCreateAccessControlProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); String accessControlProviderName = getTestName(); assertAccessControlProviderExistence(accessControlProviderName, false); int responseCode = createAccessControlProvider(accessControlProviderName); assertEquals("Access control provider creation should be denied", 403, responseCode); assertAccessControlProviderExistence(accessControlProviderName, false); } public void testDeleteAccessControlProviderDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "DELETE"); assertEquals("Access control provider deletion should be denied", 403, responseCode); assertAccessControlProviderExistence(accessControlProviderName, true); } public void testDeleteAccessControlProviderAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); // add a second, low priority AllowAll provider Map<String,Object> attributes = new HashMap<>(); final String secondProviderName = "AllowAll"; attributes.put(ConfiguredObject.NAME, secondProviderName); attributes.put(ConfiguredObject.TYPE, AllowAllAccessControlProvider.ALLOW_ALL); attributes.put(AccessControlProvider.PRIORITY, 9999); int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + secondProviderName, "PUT", attributes); assertEquals("Access control provider creation should be allowed", 201, responseCode); responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "DELETE"); assertEquals("Access control provider deletion should be allowed", 200, responseCode); assertAccessControlProviderExistence(accessControlProviderName, false); } public void testSetAccessControlProviderAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); File aclFile = TestFileUtils.createTempFile(this, ".acl", "ACL ALLOW all all"); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AccessControlProvider.NAME, accessControlProviderName); attributes.put(FileBasedGroupProvider.PATH, aclFile.getAbsolutePath()); int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes); assertEquals("Setting of access control provider attributes should be allowed", 200, responseCode); } public void testSetAccessControlProviderAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(GroupProvider.NAME, accessControlProviderName); attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); attributes.put(FileBasedGroupProvider.PATH, "/path/to/file"); int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes); assertEquals("Setting of access control provider attributes should be denied", 403, responseCode); } /* === HTTP management === */ public void testSetHttpManagementAttributesAllowed() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(HttpManagement.NAME, TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT); attributes.put(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.TIME_OUT, 10000); int responseCode = getRestTestHelper().submitRequest( "plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT, "PUT", attributes); assertEquals("Setting of http management should be allowed", 200, responseCode); Map<String, Object> details = getRestTestHelper().getJsonAsSingletonList( "plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT); assertEquals("Unexpected session timeout", 10000, details.get(HttpManagement.TIME_OUT)); assertEquals("Unexpected http basic auth enabled", true, details.get(HttpManagement.HTTP_BASIC_AUTHENTICATION_ENABLED)); assertEquals("Unexpected https basic auth enabled", false, details.get(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED)); assertEquals("Unexpected http sasl auth enabled", false, details.get(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED)); assertEquals("Unexpected https sasl auth enabled", false, details.get(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED)); } public void testSetHttpManagementAttributesDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(HttpManagement.NAME, TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT); attributes.put(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED, false); attributes.put(HttpManagement.TIME_OUT, 10000); int responseCode = getRestTestHelper().submitRequest( "plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT, "PUT", attributes); assertEquals("Setting of http management should be denied", 403, responseCode); Map<String, Object> details = getRestTestHelper().getJsonAsSingletonList( "plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT); assertEquals("Unexpected session timeout", HttpManagement.DEFAULT_TIMEOUT_IN_SECONDS, details.get(HttpManagement.TIME_OUT)); assertEquals("Unexpected http basic auth enabled", true, details.get(HttpManagement.HTTP_BASIC_AUTHENTICATION_ENABLED)); assertEquals("Unexpected https basic auth enabled", true, details.get(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED)); assertEquals("Unexpected http sasl auth enabled", true, details.get(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED)); assertEquals("Unexpected https sasl auth enabled", true, details.get(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED)); } /* === Broker Logger === */ public void testCreateBrokerLoggerAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerLogger.NAME, "testLogger1"); attributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "testLogger2"); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest("brokerlogger/testLogger2", "GET", HttpServletResponse.SC_NOT_FOUND); } public void testDeleteBrokerLoggerAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerLogger.NAME, "testLogger1"); attributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "DELETE", null, HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "DELETE", null, HttpServletResponse.SC_OK); getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_NOT_FOUND); } public void testDownloadBrokerLoggerFileAllowedDenied() throws Exception { final String loggerName = "testFileLogger"; final String loggerPath = "brokerlogger/" + loggerName; getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerLogger.NAME, loggerName); attributes.put(ConfiguredObject.TYPE, BrokerFileLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_OK); getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_OK); getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_FORBIDDEN); } public void testViewMemoryLoggerEntriesAllowedDenied() throws Exception { final String loggerName = "testMemoryLogger"; final String loggerPath = "brokerlogger/" + loggerName; getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerLogger.NAME, loggerName); attributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest(loggerPath + "/getLogEntries?lastLogId=0", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest(loggerPath + "/getLogEntries?lastLogId=0", "GET", HttpServletResponse.SC_FORBIDDEN); } /* === Broker Log Inclusion Rules === */ public void testCreateBrokerLoggerRuleAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> loggerAttributes = new HashMap<>(); loggerAttributes.put(BrokerLogger.NAME, "testLogger1"); loggerAttributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", loggerAttributes, HttpServletResponse.SC_CREATED); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1"); attributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "DEBUG"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule2"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", attributes, HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule2", "GET", HttpServletResponse.SC_NOT_FOUND); } public void testUpdateBrokerLoggerRuleAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> loggerAttributes = new HashMap<>(); loggerAttributes.put(BrokerLogger.NAME, "testLogger1"); loggerAttributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", loggerAttributes, HttpServletResponse.SC_CREATED); Map<String, Object> ruleAttributes = new HashMap<>(); ruleAttributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1"); ruleAttributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); ruleAttributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "INFO"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", ruleAttributes, HttpServletResponse.SC_CREATED); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1"); attributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "DEBUG"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "PUT", attributes, HttpServletResponse.SC_OK); Map<String,Object> resultAfterUpdate = getRestTestHelper().getJsonAsSingletonList("brokerloginclusionrule/testLogger1/rule1"); assertEquals("Log level was not changed", "DEBUG", resultAfterUpdate.get(BrokerNameAndLevelLogInclusionRule.LEVEL)); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "INFO"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "PUT", attributes, HttpServletResponse.SC_FORBIDDEN); Map<String,Object> resultAfterDeniedUpdate = getRestTestHelper().getJsonAsSingletonList("brokerloginclusionrule/testLogger1/rule1"); assertEquals("Log level was changed by not allowed user", "DEBUG", resultAfterDeniedUpdate.get(BrokerNameAndLevelLogInclusionRule.LEVEL)); } public void testDeleteBrokerLoggerRuleAllowedDenied() throws Exception { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); Map<String, Object> loggerAttributes = new HashMap<>(); loggerAttributes.put(BrokerLogger.NAME, "testLogger1"); loggerAttributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE); getRestTestHelper().submitRequest("brokerlogger", "PUT", loggerAttributes, HttpServletResponse.SC_CREATED); Map<String, Object> attributes = new HashMap<>(); attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1"); attributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "DEBUG"); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", attributes, HttpServletResponse.SC_CREATED); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "DELETE", null, HttpServletResponse.SC_FORBIDDEN); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_OK); getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "DELETE", null, HttpServletResponse.SC_OK); getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_NOT_FOUND); } /* === Utility Methods === */ private int createPort(String portName) throws Exception { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(Port.NAME, portName); attributes.put(Port.PORT, 0); attributes.put(Port.AUTHENTICATION_PROVIDER, TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER); return getRestTestHelper().submitRequest("port/" + portName, "PUT", attributes); } private void assertPortExists(String portName) throws Exception { assertPortExistence(portName, true); } private void assertPortDoesNotExist(String portName) throws Exception { assertPortExistence(portName, false); } private void assertPortExistence(String portName, boolean exists) throws Exception { String path = "port/" + portName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private void assertKeyStoreExistence(String keyStoreName, boolean exists) throws Exception { String path = "keystore/" + keyStoreName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private void assertTrustStoreExistence(String trustStoreName, boolean exists) throws Exception { String path = "truststore/" + trustStoreName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private int createAuthenticationProvider(String authenticationProviderName) throws Exception { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AuthenticationProvider.NAME, authenticationProviderName); attributes.put(AuthenticationProvider.TYPE, AnonymousAuthenticationManager.PROVIDER_TYPE); return getRestTestHelper().submitRequest("authenticationprovider/" + authenticationProviderName, "PUT", attributes); } private void assertAuthenticationProviderDoesNotExist(String authenticationProviderName) throws Exception { assertAuthenticationProviderExistence(authenticationProviderName, false); } private void assertAuthenticationProviderExists(String authenticationProviderName) throws Exception { assertAuthenticationProviderExistence(authenticationProviderName, true); } private void assertAuthenticationProviderExistence(String authenticationProviderName, boolean exists) throws Exception { String path = "authenticationprovider/" + authenticationProviderName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private int createKeyStore(String name, String certAlias) throws IOException { Map<String, Object> keyStoreAttributes = new HashMap<String, Object>(); keyStoreAttributes.put(KeyStore.NAME, name); keyStoreAttributes.put(FileKeyStore.STORE_URL, TestSSLConstants.KEYSTORE); keyStoreAttributes.put(FileKeyStore.PASSWORD, TestSSLConstants.KEYSTORE_PASSWORD); keyStoreAttributes.put(FileKeyStore.CERTIFICATE_ALIAS, certAlias); return getRestTestHelper().submitRequest("keystore/" + name, "PUT", keyStoreAttributes); } private int createTrustStore(String name, boolean peersOnly) throws IOException { Map<String, Object> trustStoreAttributes = new HashMap<String, Object>(); trustStoreAttributes.put(TrustStore.NAME, name); trustStoreAttributes.put(FileTrustStore.STORE_URL, TestSSLConstants.KEYSTORE); trustStoreAttributes.put(FileTrustStore.PASSWORD, TestSSLConstants.KEYSTORE_PASSWORD); trustStoreAttributes.put(FileTrustStore.PEERS_ONLY, peersOnly); return getRestTestHelper().submitRequest("truststore/" + name, "PUT", trustStoreAttributes); } private void assertGroupProviderExistence(String groupProviderName, boolean exists) throws Exception { String path = "groupprovider/" + groupProviderName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private int createGroupProvider(String groupProviderName) throws Exception { File file = TestFileUtils.createTempFile(this, ".groups"); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(GroupProvider.NAME, groupProviderName); attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); attributes.put(FileBasedGroupProvider.PATH, file.getAbsoluteFile()); return getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "PUT", attributes); } private void assertAccessControlProviderExistence(String accessControlProviderName, boolean exists) throws Exception { String path = "accesscontrolprovider/" + accessControlProviderName; int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND; getRestTestHelper().submitRequest(path, "GET", expectedResponseCode); } private int createAccessControlProvider(String accessControlProviderName) throws Exception { File file = TestFileUtils.createTempFile(this, ".acl", _secondaryAclFileContent); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(AccessControlProvider.NAME, accessControlProviderName); attributes.put(AccessControlProvider.TYPE, ACLFileAccessControlProvider.ACL_FILE_PROVIDER_TYPE); attributes.put(ACLFileAccessControlProvider.PATH, file.getAbsoluteFile()); return getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes); } }
ChugR/qpid-java
systests/src/test/java/org/apache/qpid/systest/rest/acl/BrokerACLTest.java
213,281
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.document.json; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.io.JsonStringEncoder; import com.google.common.base.Joiner; import com.yahoo.collections.Tuple2; import com.yahoo.document.ArrayDataType; import com.yahoo.document.DataType; import com.yahoo.document.Document; import com.yahoo.document.DocumentId; import com.yahoo.document.DocumentOperation; import com.yahoo.document.DocumentPut; import com.yahoo.document.DocumentRemove; import com.yahoo.document.DocumentType; import com.yahoo.document.DocumentTypeManager; import com.yahoo.document.DocumentUpdate; import com.yahoo.document.Field; import com.yahoo.document.MapDataType; import com.yahoo.document.PositionDataType; import com.yahoo.document.StructDataType; import com.yahoo.document.TensorDataType; import com.yahoo.document.WeightedSetDataType; import com.yahoo.document.datatypes.Array; import com.yahoo.document.datatypes.BoolFieldValue; import com.yahoo.document.datatypes.FieldValue; import com.yahoo.document.datatypes.IntegerFieldValue; import com.yahoo.document.datatypes.MapFieldValue; import com.yahoo.document.datatypes.Raw; import com.yahoo.document.datatypes.StringFieldValue; import com.yahoo.document.datatypes.Struct; import com.yahoo.document.datatypes.TensorFieldValue; import com.yahoo.document.datatypes.WeightedSet; import com.yahoo.document.json.readers.DocumentParseInfo; import com.yahoo.document.json.readers.VespaJsonDocumentReader; import com.yahoo.document.serialization.DocumentSerializer; import com.yahoo.document.serialization.DocumentSerializerFactory; import com.yahoo.document.update.AddValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate.Operator; import com.yahoo.document.update.AssignValueUpdate; import com.yahoo.document.update.ClearValueUpdate; import com.yahoo.document.update.FieldUpdate; import com.yahoo.document.update.MapValueUpdate; import com.yahoo.document.update.TensorAddUpdate; import com.yahoo.document.update.TensorModifyUpdate; import com.yahoo.document.update.TensorRemoveUpdate; import com.yahoo.document.update.ValueUpdate; import com.yahoo.io.GrowableByteBuffer; import com.yahoo.tensor.IndexedTensor; import com.yahoo.tensor.MappedTensor; import com.yahoo.tensor.MixedTensor; import com.yahoo.tensor.Tensor; import com.yahoo.tensor.TensorType; import com.yahoo.text.Utf8; import com.yahoo.yolean.Exceptions; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DECREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DIVIDE; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_INCREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_MULTIPLY; import static com.yahoo.test.json.JsonTestHelper.inputJson; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Basic test of JSON streams to Vespa document instances. * * @author Steinar Knutsen * @author bratseth */ public class JsonReaderTestCase { private DocumentTypeManager types; private JsonFactory parserFactory; @Rule public ExpectedException exception = ExpectedException.none(); @Before public void setUp() throws Exception { parserFactory = new JsonFactory(); types = new DocumentTypeManager(); { DocumentType x = new DocumentType("smoke"); x.addField(new Field("something", DataType.STRING)); x.addField(new Field("nalle", DataType.STRING)); x.addField(new Field("int1", DataType.INT)); x.addField(new Field("flag", DataType.BOOL)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("mirrors"); StructDataType woo = new StructDataType("woo"); woo.addField(new Field("sandra", DataType.STRING)); woo.addField(new Field("cloud", DataType.STRING)); x.addField(new Field("skuggsjaa", woo)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testarray"); DataType d = new ArrayDataType(DataType.STRING); x.addField(new Field("actualarray", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testset"); DataType d = new WeightedSetDataType(DataType.STRING, true, true); x.addField(new Field("actualset", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testmap"); DataType d = new MapDataType(DataType.STRING, DataType.STRING); x.addField(new Field("actualmap", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testraw"); DataType d = DataType.RAW; x.addField(new Field("actualraw", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testMapStringToArrayOfInt"); DataType value = new ArrayDataType(DataType.INT); DataType d = new MapDataType(DataType.STRING, value); x.addField(new Field("actualMapStringToArrayOfInt", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testsinglepos"); DataType d = PositionDataType.INSTANCE; x.addField(new Field("singlepos", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testtensor"); x.addField(new Field("sparse_single_dimension_tensor", new TensorDataType(new TensorType.Builder().mapped("x").build()))); x.addField(new Field("sparse_tensor", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").build()))); x.addField(new Field("dense_tensor", new TensorDataType(new TensorType.Builder().indexed("x", 2).indexed("y", 3).build()))); x.addField(new Field("dense_int8_tensor", new TensorDataType(TensorType.fromSpec("tensor<int8>(x[2],y[3])")))); x.addField(new Field("dense_unbound_tensor", new TensorDataType(new TensorType.Builder().indexed("x").indexed("y").build()))); x.addField(new Field("mixed_tensor", new TensorDataType(new TensorType.Builder().mapped("x").indexed("y", 3).build()))); x.addField(new Field("mixed_bfloat16_tensor", new TensorDataType(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")))); x.addField(new Field("mixed_tensor_adv", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").mapped("z").indexed("a", 3).build()))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testpredicate"); x.addField(new Field("boolean", DataType.PREDICATE)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testint"); x.addField(new Field("integerfield", DataType.INT)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testnull"); x.addField(new Field("intfield", DataType.INT)); x.addField(new Field("stringfield", DataType.STRING)); x.addField(new Field("arrayfield", new ArrayDataType(DataType.STRING))); x.addField(new Field("weightedsetfield", new WeightedSetDataType(DataType.STRING, true, true))); x.addField(new Field("mapfield", new MapDataType(DataType.STRING, DataType.STRING))); x.addField(new Field("tensorfield", new TensorDataType(new TensorType.Builder().indexed("x").build()))); types.registerDocumentType(x); } } @After public void tearDown() throws Exception { types = null; parserFactory = null; exception = ExpectedException.none(); } private JsonReader createReader(String jsonInput) { InputStream input = new ByteArrayInputStream(Utf8.toBytes(jsonInput)); return new JsonReader(types, input, parserFactory); } @Test public void readSingleDocumentPut() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " }", "}")); DocumentPut put = (DocumentPut) r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:smoke::doc1"); smokeTestDoc(put.getDocument()); } @Test public final void readSingleDocumentUpdate() { JsonReader r = createReader(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': {", " 'assign': 'orOther' }}}")); DocumentUpdate doc = (DocumentUpdate) r.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::whee"); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof AssignValueUpdate); } @Test public void readClearField() { JsonReader r = createReader(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'int1': {", " 'assign': null }}}")); DocumentUpdate doc = (DocumentUpdate) r.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::whee"); FieldUpdate f = doc.getFieldUpdate("int1"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof ClearValueUpdate); assertNull(f.getValueUpdate(0).getValue()); } @Test public void smokeTest() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } @Test public void docIdLookaheadTest() throws IOException { JsonReader r = createReader(inputJson( "{ 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " },", " 'put': 'id:unittest:smoke::doc1'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } @Test public void emptyDocTest() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::whee', 'fields': {}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); assertEquals("id:unittest:smoke::whee", parseInfo.documentId.toString()); } @Test public void testStruct() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:mirrors::whee',", " 'fields': {", " 'skuggsjaa': {", " 'sandra': 'person',", " 'cloud': 'another person' }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("skuggsjaa")); assertSame(Struct.class, f.getClass()); Struct s = (Struct) f; assertEquals("person", ((StringFieldValue) s.getFieldValue("sandra")).getString()); } private DocumentUpdate parseUpdate(String json) throws IOException { InputStream rawDoc = new ByteArrayInputStream(Utf8.toBytes(json)); JsonReader r = new JsonReader(types, rawDoc, parserFactory); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentUpdate update = new DocumentUpdate(docType, parseInfo.documentId); new VespaJsonDocumentReader().readUpdate(parseInfo.fieldsBuffer, update); return update; } @Test public void testStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(inputJson("{ 'update': 'id:unittest:mirrors:g=test:whee',", " 'create': true,", " 'fields': {", " 'skuggsjaa': {", " 'assign': {", " 'sandra': 'person',", " 'cloud': 'another person' }}}}")); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(2, s.getFieldCount()); assertEquals(new StringFieldValue("person"), s.getFieldValue(s.getField("sandra"))); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(107, buf.position()); } @Test public final void testEmptyStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(inputJson("{ 'update': 'id:unittest:mirrors:g=test:whee',", " 'create': true,", " 'fields': { ", " 'skuggsjaa': {", " 'assign': { } }}}")); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(0, s.getFieldCount()); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(69, buf.position()); } @Test public void testUpdateArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}}")); checkSimpleArrayAdd(doc); } @Test public void testUpdateWeighted() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'add': {", " 'person': 37,", " 'another person': 41 }}}}")); Map<String, Integer> weights = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; final String s = ((StringFieldValue) adder.getValue()).getString(); weights.put(s, adder.getWeight()); } assertEquals(2, weights.size()); final String o = "person"; final String o2 = "another person"; assertTrue(weights.containsKey(o)); assertTrue(weights.containsKey(o2)); assertEquals(Integer.valueOf(37), weights.get(o)); assertEquals(Integer.valueOf(41), weights.get(o2)); } @Test public void testUpdateMatch() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'match': {", " 'element': 'person',", " 'increment': 13 }}}}")); Map<String, Tuple2<Number, String>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); String op = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperator().toString(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()).getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertEquals("ADD", matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } @SuppressWarnings({ "cast", "unchecked", "rawtypes" }) @Test public void testArithmeticOperators() throws IOException { Tuple2[] operations = new Tuple2[] { new Tuple2<String, Operator>(UPDATE_DECREMENT, ArithmeticValueUpdate.Operator.SUB), new Tuple2<String, Operator>(UPDATE_DIVIDE, ArithmeticValueUpdate.Operator.DIV), new Tuple2<String, Operator>(UPDATE_INCREMENT, ArithmeticValueUpdate.Operator.ADD), new Tuple2<String, Operator>(UPDATE_MULTIPLY, ArithmeticValueUpdate.Operator.MUL) }; for (Tuple2<String, Operator> operator : operations) { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'match': {", " 'element': 'person',", " '" + (String) operator.first + "': 13 }}}}")); Map<String, Tuple2<Number, Operator>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); Operator op = ((ArithmeticValueUpdate) adder .getUpdate()).getOperator(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertSame(operator.second, matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } } @SuppressWarnings("rawtypes") @Test public void testArrayIndexing() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'match': {", " 'element': 3,", " 'assign': 'nalle' }}}}")); Map<Number, String> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualarray"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final Number key = ((IntegerFieldValue) adder.getValue()) .getNumber(); String op = ((StringFieldValue) ((AssignValueUpdate) adder.getUpdate()) .getValue()).getString(); matches.put(key, op); } assertEquals(1, matches.size()); Number n = Integer.valueOf(3); assertEquals("nalle", matches.get(n)); } @Test public void testDocumentRemove() { JsonReader r = createReader(inputJson("{'remove': 'id:unittest:smoke::whee'}")); DocumentType docType = r.readDocumentType(new DocumentId("id:unittest:smoke::whee")); assertEquals("smoke", docType.getName()); } @Test public void testWeightedSet() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'nalle': 2,", " 'tralle': 7 }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("actualset")); assertSame(WeightedSet.class, f.getClass()); WeightedSet<?> w = (WeightedSet<?>) f; assertEquals(2, w.size()); assertEquals(Integer.valueOf(2), w.get(new StringFieldValue("nalle"))); assertEquals(Integer.valueOf(7), w.get(new StringFieldValue("tralle"))); } @Test public void testArray() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': [", " 'nalle',", " 'tralle' ]}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("actualarray")); assertSame(Array.class, f.getClass()); Array<?> a = (Array<?>) f; assertEquals(2, a.size()); assertEquals(new StringFieldValue("nalle"), a.get(0)); assertEquals(new StringFieldValue("tralle"), a.get(1)); } @Test public void testMap() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testmap::whee',", " 'fields': {", " 'actualmap': {", " 'nalle': 'kalle',", " 'tralle': 'skalle' }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testOldMap() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testmap::whee',", " 'fields': {", " 'actualmap': [", " { 'key': 'nalle', 'value': 'kalle'},", " { 'key': 'tralle', 'value': 'skalle'} ]}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testPositionPositive() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': 'N63.429722;E10.393333' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionNegative() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': 'W46.63;S23.55' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(-46630000, PositionDataType.getXValue(f).getInteger()); assertEquals(-23550000, PositionDataType.getYValue(f).getInteger()); } @Test public void testRaw() throws IOException { String base64 = new String(new JsonStringEncoder().quoteAsString( Base64.getEncoder().encodeToString(Utf8.toBytes("smoketest")))); String s = fieldStringFromBase64RawContent(base64); assertEquals("smoketest", s); } @Test public void can_read_legacy_chunked_base64_raw_field_encoding() throws IOException { String expected = "this is a string with an impressive length. it's long enough to reach the end of the line, wow!"; String base64withDelims = "dGhpcyBpcyBhIHN0cmluZyB3aXRoIGFuIGltcHJlc3NpdmUgbGVuZ3RoLiBpdCdzIGxvbmcgZW5v\\r\\n" + "dWdoIHRvIHJlYWNoIHRoZSBlbmQgb2YgdGhlIGxpbmUsIHdvdyE=\\r\\n"; assertEquals(expected, fieldStringFromBase64RawContent(base64withDelims)); } private String fieldStringFromBase64RawContent(String base64data) throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testraw::whee',", " 'fields': {", " 'actualraw': '" + base64data + "' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("actualraw")); assertSame(Raw.class, f.getClass()); Raw s = (Raw) f; return Utf8.toString(s.getByteBuffer()); } @Test public void testMapStringToArrayOfInt() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'bamse': [1, 2, 3] }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldMapStringToArrayOfInt() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': [", " { 'key': 'bamse', 'value': [1, 2, 3] } ]}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToString() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': {", " 'assign': 'orOther' }}}")); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); AssignValueUpdate a = (AssignValueUpdate) f.getValueUpdate(0); assertEquals(new StringFieldValue("orOther"), a.getValue()); } @Test public void testAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'assign': { 'bamse': [1, 2, 3] }}}}")); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'assign': [", " { 'key': 'bamse', 'value': [1, 2, 3] } ]}}}")); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToWeightedSet() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'assign': {", " 'person': 37,", " 'another person': 41 }}}}")); FieldUpdate x = doc.getFieldUpdate("actualset"); assertEquals(1, x.size()); AssignValueUpdate assign = (AssignValueUpdate) x.getValueUpdate(0); WeightedSet<?> w = (WeightedSet<?>) assign.getValue(); assertEquals(2, w.size()); assertEquals(Integer.valueOf(37), w.get(new StringFieldValue("person"))); assertEquals(Integer.valueOf(41), w.get(new StringFieldValue("another person"))); } @Test public void testCompleteFeed() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }},", "{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}},", "{ 'remove': 'id:unittest:smoke::whee' }]")); controlBasicFeed(r); } @Test public void testCompleteFeedWithCreateAndCondition() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }},", "{", " 'condition':'bla',", " 'update': 'id:unittest:testarray::whee',", " 'create':true,", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}},", "{ 'remove': 'id:unittest:smoke::whee' }]")); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testUpdateWithConditionAndCreateInDifferentOrdering() { int documentsCreated = 106; List<String> parts = Arrays.asList( "\"condition\":\"bla\"", "\"update\": \"id:unittest:testarray::whee\"", " \"fields\": { " + "\"actualarray\": { \"add\": [" + " \"person\",\"another person\"]}}", " \"create\":true"); Random random = new Random(42); StringBuilder documents = new StringBuilder("["); for (int x = 0; x < documentsCreated; x++) { Collections.shuffle(parts, random); documents.append("{").append(Joiner.on(",").join(parts)).append("}"); if (x < documentsCreated -1) { documents.append(","); } } documents.append("]"); InputStream rawDoc = new ByteArrayInputStream( Utf8.toBytes(documents.toString())); JsonReader r = new JsonReader(types, rawDoc, parserFactory); for (int x = 0; x < documentsCreated; x++) { DocumentUpdate update = (DocumentUpdate) r.next(); checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); } assertNull(r.next()); } @Test(expected=RuntimeException.class) public void testCreateIfNonExistentInPut() { JsonReader r = createReader(inputJson("[{", " 'create':true,", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse' },", " 'put': 'id:unittest:smoke::whee'", "}]")); r.next(); } @Test public void testCompleteFeedWithIdAfterFields() { JsonReader r = createReader(inputJson("[", "{", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' },", " 'put': 'id:unittest:smoke::whee'", "},", "{", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}},", " 'update': 'id:unittest:testarray::whee'", "},", "{ 'remove': 'id:unittest:smoke::whee' }]")); controlBasicFeed(r); } protected void controlBasicFeed(JsonReader r) { DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testCompleteFeedWithEmptyDoc() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee', 'fields': {} },", "{ 'update': 'id:unittest:testarray::whee', 'fields': {} },", "{ 'remove': 'id:unittest:smoke::whee' }]")); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); assertEquals("smoke", doc.getId().getDocType()); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; assertEquals("testarray", update.getId().getDocType()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } private void checkSimpleArrayAdd(DocumentUpdate update) { Set<String> toAdd = new HashSet<>(); FieldUpdate x = update.getFieldUpdate("actualarray"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; toAdd.add(((StringFieldValue) adder.getValue()).getString()); } assertEquals(2, toAdd.size()); assertTrue(toAdd.contains("person")); assertTrue(toAdd.contains("another person")); } private void smokeTestDoc(Document doc) { FieldValue boolField = doc.getFieldValue(doc.getField("flag")); assertSame(BoolFieldValue.class, boolField.getClass()); assertTrue((Boolean)boolField.getWrappedValue()); FieldValue stringField = doc.getFieldValue(doc.getField("nalle")); assertSame(StringFieldValue.class, stringField.getClass()); assertEquals("bamse", ((StringFieldValue) stringField).getString()); } @Test public void misspelledFieldTest() throws IOException{ JsonReader r = createReader(inputJson( "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'smething': 'smoketest',", " 'nalle': 'bamse' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); exception.expect(IllegalArgumentException.class); exception.expectMessage("No field 'smething' in the structure of type 'smoke'"); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); } @Test public void feedWithBasicErrorTest() { JsonReader r = createReader(inputJson("[", " { 'put': 'id:test:smoke::0', 'fields': { 'something': 'foo' } },", " { 'put': 'id:test:smoke::1', 'fields': { 'something': 'foo' } },", " { 'put': 'id:test:smoke::2', 'fields': { 'something': 'foo' } },", "]")); exception.expect(RuntimeException.class); exception.expectMessage("JsonParseException"); while (r.next() != null); } @Test public void idAsAliasForPutTest() throws IOException{ JsonReader r = createReader(inputJson("{ 'id': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } private void testFeedWithTestAndSetCondition(String jsonDoc) { ByteArrayInputStream parseInfoDoc = new ByteArrayInputStream(Utf8.toBytes(jsonDoc)); JsonReader reader = new JsonReader(types, parseInfoDoc, parserFactory); int NUM_OPERATIONS_IN_FEED = 3; for (int i = 0; i < NUM_OPERATIONS_IN_FEED; i++) { DocumentOperation operation = reader.next(); assertTrue("A test and set condition should be present", operation.getCondition().isPresent()); assertEquals("DocumentOperation's test and set condition should be equal to the one in the JSON feed", "smoke.something == \"smoketest\"", operation.getCondition().getSelection()); } assertNull(reader.next()); } @Test public void testFeedWithTestAndSetConditionOrderingOne() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'put': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " }", " },", " {", " 'update': 'id:unittest:testarray::whee',", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " },", " {", " 'remove': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\''", " }", "]" )); } @Test public void testFeedWithTestAndSetConditionOrderingTwo() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " }", " },", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " },", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'remove': 'id:unittest:smoke::whee'", " }", "]" )); } @Test public void testFeedWithTestAndSetConditionOrderingThree() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " },", " 'condition': 'smoke.something == \\'smoketest\\''", " },", " {", " 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " },", " 'condition': 'smoke.something == \\'smoketest\\''", " },", " {", " 'remove': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\''", " }", "]" )); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldAfterFieldsFieldShouldFailParse() { final String jsonData = inputJson( "[", " {", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " },", " 'bjarne': 'stroustrup'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldBeforeFieldsFieldShouldFailParse() { final String jsonData = inputJson( "[", " {", " 'update': 'id:unittest:testarray::whee',", " 'what is this': 'nothing to see here',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldWithoutFieldsFieldShouldFailParse() { String jsonData = inputJson( "[", " {", " 'remove': 'id:unittest:smoke::whee',", " 'what is love': 'baby, do not hurt me... much'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test public void testMissingOperation() { try { String jsonData = inputJson( "[", " {", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Missing a document operation ('put', 'update' or 'remove')", e.getMessage()); } } @Test public void testMissingFieldsMapInPut() { try { String jsonData = inputJson( "[", " {", " 'put': 'id:unittest:smoke::whee'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("put of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testMissingFieldsMapInUpdate() { try { String jsonData = inputJson( "[", " {", " 'update': 'id:unittest:smoke::whee'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("update of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testNullValues() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testnull::doc1',", " 'fields': {", " 'intfield': null,", " 'stringfield': null,", " 'arrayfield': null,", " 'weightedsetfield': null,", " 'mapfield': null,", " 'tensorfield': null", " }", "}")); DocumentPut put = (DocumentPut) r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:testnull::doc1"); Document doc = put.getDocument(); assertFieldValueNull(doc, "intfield"); assertFieldValueNull(doc, "stringfield"); assertFieldValueNull(doc, "arrayfield"); assertFieldValueNull(doc, "weightedsetfield"); assertFieldValueNull(doc, "mapfield"); assertFieldValueNull(doc, "tensorfield"); } @Test(expected=JsonReaderException.class) public void testNullArrayElement() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testnull::doc1',", " 'fields': {", " 'arrayfield': [ null ]", " }", "}")); r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:testnull::doc1"); fail(); } private void assertFieldValueNull(Document doc, String fieldName) { Field field = doc.getField(fieldName); assertNotNull(field); FieldValue fieldValue = doc.getFieldValue(field); assertNull(fieldValue); } static ByteArrayInputStream jsonToInputStream(String json) { return new ByteArrayInputStream(Utf8.toBytes(json)); } @Test public void testParsingWithoutTensorField() { Document doc = createPutWithoutTensor().getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals("id:unittest:testtensor::0", doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField("sparse_tensor")); assertNull(fieldValue); } @Test public void testParsingOfEmptyTensor() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor("{}")); } @Test public void testParsingOfTensorWithEmptyDimensions() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor(inputJson("{ 'dimensions': [] }"))); } @Test public void testParsingOfTensorWithEmptyCells() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor(inputJson("{ 'cells': [] }"))); } @Test public void testDisallowedDenseTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{ 'values': [] }"), "dense_tensor", "The 'values' array does not contain any values"); assertCreatePutFails(inputJson("{ 'values': '' }"), "dense_tensor", "The 'values' string does not contain any values"); } @Test public void testDisallowedMixedTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{\"blocks\":{ \"a\": [] } }"), "mixed_tensor", "Expected 3 values, but got 0"); assertCreatePutFails(inputJson("{\"blocks\":[ {\"address\":{\"x\":\"a\"}, \"values\": [] } ] }"), "mixed_tensor", "Expected 3 values, but got 0"); } @Test public void testParsingOfSparseTensorWithCells() { Tensor tensor = assertSparseTensorField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createPutWithSparseTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' },", " 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'b' },", " 'value': 3.0 }", " ]", "}"))); assertTrue(tensor instanceof MappedTensor); // any functional instance is fine } @Test public void testParsingOfDenseTensorWithCells() { Tensor tensor = assertTensorField("{{x:0,y:0}:2.0,{x:1,y:0}:3.0}}", createPutWithTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' },", " 'value': 2.0 },", " { 'address': { 'x': '1', 'y': '0' },", " 'value': 3.0 }", " ]", "}"), "dense_unbound_tensor"), "dense_unbound_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorOnDenseForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson("{", " 'values': [2.0, 3.0, 4.0, 5.0, 6.0, 7.0]", "}"), "dense_tensor"), "dense_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<int8>(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson("{", " 'values': \"020304050607\"", "}"), "dense_int8_tensor"), "dense_int8_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfMixedTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")); builder.cell().label("x", "foo").label("y", 0).value(2.0); builder.cell().label("x", "foo").label("y", 1).value(3.0); builder.cell().label("x", "foo").label("y", 2).value(4.0); builder.cell().label("x", "bar").label("y", 0).value(5.0); builder.cell().label("x", "bar").label("y", 1).value(6.0); builder.cell().label("x", "bar").label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":[" + "{\"address\":{\"x\":\"foo\"},\"values\":\"400040404080\"}," + "{\"address\":{\"x\":\"bar\"},\"values\":\"40A040C040E0\"}" + "]}"; var put = createPutWithTensor(inputJson(mixedJson), "mixed_bfloat16_tensor"); Tensor tensor = assertTensorField(expected, put, "mixed_bfloat16_tensor"); } @Test public void testParsingOfMixedTensorOnMixedForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":[" + "{\"address\":{\"x\":\"0\"},\"values\":[2.0,3.0,4.0]}," + "{\"address\":{\"x\":\"1\"},\"values\":[5.0,6.0,7.0]}" + "]}"; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance } @Test public void testMixedTensorInMixedFormWithSingleSparseDimensionShortForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":{" + "\"0\":[2.0,3.0,4.0]," + "\"1\":[5.0,6.0,7.0]" + "}}"; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance } @Test public void testParsingOfTensorWithSingleCellInDifferentJsonOrder() { assertSparseTensorField("{{x:a,y:b}:2.0}", createPutWithSparseTensor(inputJson("{", " 'cells': [", " { 'value': 2.0,", " 'address': { 'x': 'a', 'y': 'b' } }", " ]", "}"))); } @Test public void testAssignUpdateOfEmptySparseTensor() { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithSparseTensor("{}")); } @Test public void testAssignUpdateOfEmptyDenseTensor() { try { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithTensor("{}", "dense_unbound_tensor")); } catch (IllegalArgumentException e) { assertEquals("An indexed tensor must have a value", "Error in 'dense_unbound_tensor': Tensor of type tensor(x[],y[]) has no values", Exceptions.toMessageString(e)); } } @Test public void testAssignUpdateOfNullTensor() { ClearValueUpdate clearUpdate = (ClearValueUpdate) getTensorField(createAssignUpdateWithSparseTensor(null)).getValueUpdate(0); assertTrue(clearUpdate != null); assertTrue(clearUpdate.getValue() == null); } @Test public void testAssignUpdateOfTensorWithCells() { assertTensorAssignUpdateSparseField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createAssignUpdateWithSparseTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' },", " 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'b' },", " 'value': 3.0 }", " ]", "}"))); } @Test public void testAssignUpdateOfTensorDenseShortForm() { assertTensorAssignUpdateDenseField("tensor(x[2],y[3]):[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]", createAssignUpdateWithTensor(inputJson("{", " 'values': [1,2,3,4,5,6]", "}"), "dense_tensor")); } @Test public void tensor_modify_update_with_replace_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_add_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, "sparse_tensor", inputJson("{", " 'operation': 'add',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_multiply_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "sparse_tensor", inputJson("{", " 'operation': 'multiply',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_treats_the_input_tensor_as_sparse() { // Note that the type of the tensor in the modify update is sparse (it only has mapped dimensions). assertTensorModifyUpdate("tensor(x{},y{}):{{x:0,y:0}:2.0, {x:1,y:2}:3.0}", TensorModifyUpdate.Operation.REPLACE, "dense_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' }, 'value': 2.0 },", " { 'address': { 'x': '1', 'y': '2' }, 'value': 3.0 } ]}")); } @Test public void tensor_modify_update_on_non_tensor_field_throws() { try { JsonReader reader = createReader(inputJson("{ 'update': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': {", " 'modify': {} }}}")); reader.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::doc1"); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Error in 'something': A modify update can only be applied to tensor fields. Field 'something' is of type 'string'", Exceptions.toMessageString(e)); } } @Test public void tensor_modify_update_on_dense_unbound_tensor_throws() { illegalTensorModifyUpdate("Error in 'dense_unbound_tensor': A modify update cannot be applied to tensor types with indexed unbound dimensions. Field 'dense_unbound_tensor' has unsupported tensor type 'tensor(x[],y[])'", "dense_unbound_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorModifyUpdate("{{x:a}:2.0, {x:c}: 3.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_single_dimension_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': {", " 'a': 2.0,", " 'c': 3.0 }}")); } @Test public void tensor_modify_update_with_replace_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_array() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': [", " { 'address': { 'x': 'a' }, 'values': [1,2,3] } ]}")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_must_specify_full_subspace() { illegalTensorModifyUpdate("Error in 'mixed_tensor': At {x:a}: Expected 3 values, but got 2", "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': {", " 'a': [2,3] } }")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_map() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': {", " 'a': [1,2,3] } }")); } @Test public void tensor_modify_update_with_add_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.ADD, "mixed_tensor", inputJson("{", " 'operation': 'add',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_multiply_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "mixed_tensor", inputJson("{", " 'operation': 'multiply',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws() { illegalTensorModifyUpdate("Error in 'dense_tensor': Dimension 'y' has label '3' but type is tensor(x[2],y[3])", "dense_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws_mixed() { illegalTensorModifyUpdate("Error in 'mixed_tensor': Dimension 'y' has label '3' but type is tensor(x{},y[3])", "mixed_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_with_unknown_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown operation 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", "{", " 'operation': 'unknown',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_without_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain an operation", "sparse_tensor", "{", " 'cells': [] }"); } @Test public void tensor_modify_update_without_cells_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", "{", " 'operation': 'replace' }"); } @Test public void tensor_modify_update_with_unknown_content_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown JSON string 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", "{", " 'unknown': 'here' }"); } @Test public void tensor_add_update_on_sparse_tensor() { assertTensorAddUpdate("{{x:a,y:b}:2.0, {x:c,y:d}: 3.0}", "sparse_tensor", inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'd' }, 'value': 3.0 } ]}")); } @Test public void tensor_add_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorAddUpdate("{{x:a}:2.0, {x:c}: 3.0}", "sparse_single_dimension_tensor", inputJson("{", " 'cells': {", " 'a': 2.0,", " 'c': 3.0 }}")); } @Test public void tensor_add_update_on_mixed_tensor() { assertTensorAddUpdate("{{x:a,y:0}:2.0, {x:a,y:1}:3.0, {x:a,y:2}:0.0}", "mixed_tensor", inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 },", " { 'address': { 'x': 'a', 'y': '1' }, 'value': 3.0 } ]}")); } @Test public void tensor_add_update_on_mixed_with_out_of_bound_dense_cells_throws() { illegalTensorAddUpdate("Error in 'mixed_tensor': Index 3 out of bounds for length 3", "mixed_tensor", "{", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_add_update_on_dense_tensor_throws() { illegalTensorAddUpdate("Error in 'dense_tensor': An add update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", "{", " 'cells': [] }"); } @Test public void tensor_add_update_on_not_fully_specified_cell_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Missing a label for dimension y for tensor(x{},y{})", "sparse_tensor", "{", " 'cells': [", " { 'address': { 'x': 'a' }, 'value': 2.0 } ]}"); } @Test public void tensor_add_update_without_cells_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Add update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", "{}"); illegalTensorAddUpdate("Error in 'mixed_tensor': Add update for field 'mixed_tensor' does not contain tensor cells", "mixed_tensor", "{}"); } @Test public void tensor_remove_update_on_sparse_tensor() { assertTensorRemoveUpdate("{{x:a,y:b}:1.0,{x:c,y:d}:1.0}", "sparse_tensor", inputJson("{", " 'addresses': [", " { 'x': 'a', 'y': 'b' },", " { 'x': 'c', 'y': 'd' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor() { assertTensorRemoveUpdate("{{x:1}:1.0,{x:2}:1.0}", "mixed_tensor", inputJson("{", " 'addresses': [", " { 'x': '1' },", " { 'x': '2' } ]}")); } @Test public void tensor_remove_update_on_sparse_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{y:b}:1.0,{y:d}:1.0}", "sparse_tensor", inputJson("{", " 'addresses': [", " { 'y': 'b' },", " { 'y': 'd' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{x:1,z:a}:1.0,{x:2,z:b}:1.0}", "mixed_tensor_adv", inputJson("{", " 'addresses': [", " { 'x': '1', 'z': 'a' },", " { 'x': '2', 'z': 'b' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor_with_dense_addresses_throws() { illegalTensorRemoveUpdate("Error in 'mixed_tensor': Indexed dimension address 'y' should not be specified in remove update", "mixed_tensor", "{", " 'addresses': [", " { 'x': '1', 'y': '0' },", " { 'x': '2', 'y': '0' } ]}"); } @Test public void tensor_remove_update_on_dense_tensor_throws() { illegalTensorRemoveUpdate("Error in 'dense_tensor': A remove update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", "{", " 'addresses': [] }"); } @Test public void tensor_remove_update_with_stray_dimension_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{},y{}) does not contain dimension 'foo'", "sparse_tensor", "{", " 'addresses': [", " { 'x': 'a', 'foo': 'b' } ]}"); illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{}) does not contain dimension 'foo'", "sparse_tensor", "{", " 'addresses': [", " { 'x': 'c' },", " { 'x': 'a', 'foo': 'b' } ]}"); } @Test public void tensor_remove_update_without_cells_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': Remove update for field 'sparse_tensor' does not contain tensor addresses", "sparse_tensor", "{'addresses': [] }"); illegalTensorRemoveUpdate("Error in 'mixed_tensor': Remove update for field 'mixed_tensor' does not contain tensor addresses", "mixed_tensor", "{'addresses': [] }"); } @Test public void require_that_parser_propagates_datatype_parser_errors_predicate() { assertParserErrorMatches( "Error in document 'id:unittest:testpredicate::0' - could not parse field 'boolean' of type 'predicate': " + "line 1:10 no viable alternative at character '>'", "[", " {", " 'fields': {", " 'boolean': 'timestamp > 9000'", " },", " 'put': 'id:unittest:testpredicate::0'", " }", "]" ); } @Test public void require_that_parser_propagates_datatype_parser_errors_string_as_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \" 1\"", "[", " {", " 'fields': {", " 'integerfield': ' 1'", " },", " 'put': 'id:unittest:testint::0'", " }", "]" ); } @Test public void require_that_parser_propagates_datatype_parser_errors_overflowing_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \"281474976710656\"", "[", " {", " 'fields': {", " 'integerfield': 281474976710656", " },", " 'put': 'id:unittest:testint::0'", " }", "]" ); } @Test public void requireThatUnknownDocTypeThrowsIllegalArgumentException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Document type walrus does not exist"); final String jsonData = inputJson( "[", " {", " 'put': 'id:ns:walrus::walrus1',", " 'fields': {", " 'aField': 42", " }", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } private static final String TENSOR_DOC_ID = "id:unittest:testtensor::0"; private void illegalTensorModifyUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorModifyUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorAddUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorAddUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorRemoveUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorRemoveUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private DocumentPut createPutWithoutTensor() { JsonReader reader = createReader(inputJson("[ { 'put': '" + TENSOR_DOC_ID + "', 'fields': { } } ]")); return (DocumentPut) reader.next(); } private DocumentPut createPutWithSparseTensor(String inputTensor) { return createPutWithTensor(inputTensor, "sparse_tensor"); } private DocumentPut createPutWithTensor(String inputTensor, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'put': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': " + inputTensor + " }}]")); return (DocumentPut) reader.next(); } private DocumentUpdate createAssignUpdateWithSparseTensor(String inputTensor) { return createAssignUpdateWithTensor(inputTensor, "sparse_tensor"); } private DocumentUpdate createAssignUpdateWithTensor(String inputTensor, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'update': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': {", " 'assign': " + (inputTensor != null ? inputTensor : "null") + " } } } ]")); return (DocumentUpdate) reader.next(); } private static Tensor assertSparseTensorField(String expectedTensor, DocumentPut put) { return assertTensorField(expectedTensor, put, "sparse_tensor"); } private static Tensor assertTensorField(String expectedTensor, DocumentPut put, String tensorFieldName) { return assertTensorField(Tensor.from(expectedTensor), put, tensorFieldName); } private static Tensor assertTensorField(Tensor expectedTensor, DocumentPut put, String tensorFieldName) { Document doc = put.getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals(TENSOR_DOC_ID, doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField(tensorFieldName)); assertEquals(expectedTensor, fieldValue.getTensor().get()); return fieldValue.getTensor().get(); } private static void assertTensorFieldUpdate(DocumentUpdate update, String tensorFieldName) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); assertEquals(1, update.fieldUpdates().size()); assertEquals(1, update.getFieldUpdate(tensorFieldName).size()); } private static void assertTensorAssignUpdateSparseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "sparse_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private static void assertTensorAssignUpdateDenseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "dense_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, String tensorFieldName, String modifyJson) { assertTensorModifyUpdate(expectedTensor, expectedOperation, tensorFieldName, createTensorModifyUpdate(modifyJson, tensorFieldName)); } private static void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorModifyUpdate modifyUpdate = (TensorModifyUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(expectedOperation, modifyUpdate.getOperation()); assertEquals(Tensor.from(expectedTensor), modifyUpdate.getValue().getTensor().get()); } private DocumentUpdate createTensorModifyUpdate(String modifyJson, String tensorFieldName) { return createTensorUpdate("modify", modifyJson, tensorFieldName); } private DocumentUpdate createTensorAddUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("add", tensorJson, tensorFieldName); } private DocumentUpdate createTensorRemoveUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("remove", tensorJson, tensorFieldName); } private DocumentUpdate createTensorUpdate(String operation, String tensorJson, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'update': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': {", " '" + operation + "': " + tensorJson + " }}}]")); return (DocumentUpdate) reader.next(); } private void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorAddUpdate(expectedTensor, tensorFieldName, createTensorAddUpdate(tensorJson, tensorFieldName)); } private static void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorAddUpdate addUpdate = (TensorAddUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), addUpdate.getValue().getTensor().get()); } private void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorRemoveUpdate(expectedTensor, tensorFieldName, createTensorRemoveUpdate(tensorJson, tensorFieldName)); } private static void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorRemoveUpdate removeUpdate = (TensorRemoveUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), removeUpdate.getValue().getTensor().get()); } private static FieldUpdate getTensorField(DocumentUpdate update) { return getTensorField(update, "sparse_tensor"); } private static FieldUpdate getTensorField(DocumentUpdate update, String fieldName) { FieldUpdate fieldUpdate = update.getFieldUpdate(fieldName); assertEquals(1, fieldUpdate.size()); return fieldUpdate; } // NOTE: Do not call this method multiple times from a test method as it's using the ExpectedException rule private void assertParserErrorMatches(String expectedError, String... json) { exception.expect(JsonReaderException.class); exception.expectMessage(expectedError); String jsonData = inputJson(json); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } private void assertCreatePutFails(String tensor, String name, String msg) { try { createPutWithTensor(inputJson(tensor), name); fail("Expected exception"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains(msg)); } } }
llorllale/vespa
document/src/test/java/com/yahoo/document/json/JsonReaderTestCase.java
213,282
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.document.json; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.io.JsonStringEncoder; import com.google.common.base.Joiner; import com.yahoo.collections.Tuple2; import com.yahoo.document.ArrayDataType; import com.yahoo.document.DataType; import com.yahoo.document.Document; import com.yahoo.document.DocumentId; import com.yahoo.document.DocumentOperation; import com.yahoo.document.DocumentPut; import com.yahoo.document.DocumentRemove; import com.yahoo.document.DocumentType; import com.yahoo.document.DocumentTypeManager; import com.yahoo.document.DocumentUpdate; import com.yahoo.document.Field; import com.yahoo.document.MapDataType; import com.yahoo.document.PositionDataType; import com.yahoo.document.StructDataType; import com.yahoo.document.TensorDataType; import com.yahoo.document.WeightedSetDataType; import com.yahoo.document.datatypes.Array; import com.yahoo.document.datatypes.BoolFieldValue; import com.yahoo.document.datatypes.FieldValue; import com.yahoo.document.datatypes.IntegerFieldValue; import com.yahoo.document.datatypes.MapFieldValue; import com.yahoo.document.datatypes.Raw; import com.yahoo.document.datatypes.StringFieldValue; import com.yahoo.document.datatypes.Struct; import com.yahoo.document.datatypes.TensorFieldValue; import com.yahoo.document.datatypes.WeightedSet; import com.yahoo.document.internal.GeoPosType; import com.yahoo.document.json.readers.DocumentParseInfo; import com.yahoo.document.json.readers.VespaJsonDocumentReader; import com.yahoo.document.serialization.DocumentSerializer; import com.yahoo.document.serialization.DocumentSerializerFactory; import com.yahoo.document.update.AddValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate.Operator; import com.yahoo.document.update.AssignValueUpdate; import com.yahoo.document.update.ClearValueUpdate; import com.yahoo.document.update.FieldUpdate; import com.yahoo.document.update.MapValueUpdate; import com.yahoo.document.update.TensorAddUpdate; import com.yahoo.document.update.TensorModifyUpdate; import com.yahoo.document.update.TensorRemoveUpdate; import com.yahoo.document.update.ValueUpdate; import com.yahoo.io.GrowableByteBuffer; import com.yahoo.tensor.IndexedTensor; import com.yahoo.tensor.MappedTensor; import com.yahoo.tensor.MixedTensor; import com.yahoo.tensor.Tensor; import com.yahoo.tensor.TensorType; import com.yahoo.text.Utf8; import com.yahoo.yolean.Exceptions; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DECREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DIVIDE; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_INCREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_MULTIPLY; import static com.yahoo.test.json.JsonTestHelper.inputJson; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Basic test of JSON streams to Vespa document instances. * * @author Steinar Knutsen * @author bratseth */ public class JsonReaderTestCase { private DocumentTypeManager types; private JsonFactory parserFactory; @Before public void setUp() throws Exception { parserFactory = new JsonFactory(); types = new DocumentTypeManager(); { DocumentType x = new DocumentType("smoke"); x.addField(new Field("something", DataType.STRING)); x.addField(new Field("nalle", DataType.STRING)); x.addField(new Field("int1", DataType.INT)); x.addField(new Field("flag", DataType.BOOL)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("mirrors"); StructDataType woo = new StructDataType("woo"); woo.addField(new Field("sandra", DataType.STRING)); woo.addField(new Field("cloud", DataType.STRING)); x.addField(new Field("skuggsjaa", woo)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testarray"); DataType d = new ArrayDataType(DataType.STRING); x.addField(new Field("actualarray", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testset"); DataType d = new WeightedSetDataType(DataType.STRING, true, true); x.addField(new Field("actualset", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testmap"); DataType d = new MapDataType(DataType.STRING, DataType.STRING); x.addField(new Field("actualmap", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testraw"); DataType d = DataType.RAW; x.addField(new Field("actualraw", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testMapStringToArrayOfInt"); DataType value = new ArrayDataType(DataType.INT); DataType d = new MapDataType(DataType.STRING, value); x.addField(new Field("actualMapStringToArrayOfInt", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testsinglepos"); DataType d = PositionDataType.INSTANCE; x.addField(new Field("singlepos", d)); x.addField(new Field("geopos", new GeoPosType(8))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testtensor"); x.addField(new Field("sparse_single_dimension_tensor", new TensorDataType(new TensorType.Builder().mapped("x").build()))); x.addField(new Field("sparse_tensor", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").build()))); x.addField(new Field("dense_tensor", new TensorDataType(new TensorType.Builder().indexed("x", 2).indexed("y", 3).build()))); x.addField(new Field("dense_int8_tensor", new TensorDataType(TensorType.fromSpec("tensor<int8>(x[2],y[3])")))); x.addField(new Field("dense_unbound_tensor", new TensorDataType(new TensorType.Builder().indexed("x").indexed("y").build()))); x.addField(new Field("mixed_tensor", new TensorDataType(new TensorType.Builder().mapped("x").indexed("y", 3).build()))); x.addField(new Field("mixed_bfloat16_tensor", new TensorDataType(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")))); x.addField(new Field("mixed_tensor_adv", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").mapped("z").indexed("a", 3).build()))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testpredicate"); x.addField(new Field("boolean", DataType.PREDICATE)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testint"); x.addField(new Field("integerfield", DataType.INT)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testnull"); x.addField(new Field("intfield", DataType.INT)); x.addField(new Field("stringfield", DataType.STRING)); x.addField(new Field("arrayfield", new ArrayDataType(DataType.STRING))); x.addField(new Field("weightedsetfield", new WeightedSetDataType(DataType.STRING, true, true))); x.addField(new Field("mapfield", new MapDataType(DataType.STRING, DataType.STRING))); x.addField(new Field("tensorfield", new TensorDataType(new TensorType.Builder().indexed("x").build()))); types.registerDocumentType(x); } } @After public void tearDown() throws Exception { types = null; parserFactory = null; } private JsonReader createReader(String jsonInput) { InputStream input = new ByteArrayInputStream(Utf8.toBytes(jsonInput)); return new JsonReader(types, input, parserFactory); } @Test public void readSingleDocumentPut() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " }", "}")); DocumentPut put = (DocumentPut) r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:smoke::doc1"); smokeTestDoc(put.getDocument()); } @Test public final void readSingleDocumentUpdate() { JsonReader r = createReader(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': {", " 'assign': 'orOther' }}}")); DocumentUpdate doc = (DocumentUpdate) r.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::whee"); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof AssignValueUpdate); } @Test public void readClearField() { JsonReader r = createReader(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'int1': {", " 'assign': null }}}")); DocumentUpdate doc = (DocumentUpdate) r.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::whee"); FieldUpdate f = doc.getFieldUpdate("int1"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof ClearValueUpdate); assertNull(f.getValueUpdate(0).getValue()); } @Test public void smokeTest() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } @Test public void docIdLookaheadTest() throws IOException { JsonReader r = createReader(inputJson( "{ 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " },", " 'put': 'id:unittest:smoke::doc1'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } @Test public void emptyDocTest() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::whee', 'fields': {}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); assertEquals("id:unittest:smoke::whee", parseInfo.documentId.toString()); } @Test public void testStruct() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:mirrors::whee',", " 'fields': {", " 'skuggsjaa': {", " 'sandra': 'person',", " 'cloud': 'another person' }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("skuggsjaa")); assertSame(Struct.class, f.getClass()); Struct s = (Struct) f; assertEquals("person", ((StringFieldValue) s.getFieldValue("sandra")).getString()); } private DocumentUpdate parseUpdate(String json) throws IOException { InputStream rawDoc = new ByteArrayInputStream(Utf8.toBytes(json)); JsonReader r = new JsonReader(types, rawDoc, parserFactory); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentUpdate update = new DocumentUpdate(docType, parseInfo.documentId); new VespaJsonDocumentReader().readUpdate(parseInfo.fieldsBuffer, update); return update; } @Test public void testStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(inputJson("{ 'update': 'id:unittest:mirrors:g=test:whee',", " 'create': true,", " 'fields': {", " 'skuggsjaa': {", " 'assign': {", " 'sandra': 'person',", " 'cloud': 'another person' }}}}")); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(2, s.getFieldCount()); assertEquals(new StringFieldValue("person"), s.getFieldValue(s.getField("sandra"))); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(107, buf.position()); } @Test public final void testEmptyStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(inputJson("{ 'update': 'id:unittest:mirrors:g=test:whee',", " 'create': true,", " 'fields': { ", " 'skuggsjaa': {", " 'assign': { } }}}")); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(0, s.getFieldCount()); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(69, buf.position()); } @Test public void testUpdateArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}}")); checkSimpleArrayAdd(doc); } @Test public void testUpdateWeighted() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'add': {", " 'person': 37,", " 'another person': 41 }}}}")); Map<String, Integer> weights = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; final String s = ((StringFieldValue) adder.getValue()).getString(); weights.put(s, adder.getWeight()); } assertEquals(2, weights.size()); final String o = "person"; final String o2 = "another person"; assertTrue(weights.containsKey(o)); assertTrue(weights.containsKey(o2)); assertEquals(Integer.valueOf(37), weights.get(o)); assertEquals(Integer.valueOf(41), weights.get(o2)); } @Test public void testUpdateMatch() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'match': {", " 'element': 'person',", " 'increment': 13 }}}}")); Map<String, Tuple2<Number, String>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); String op = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperator().toString(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()).getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertEquals("ADD", matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } @SuppressWarnings({ "cast", "unchecked", "rawtypes" }) @Test public void testArithmeticOperators() throws IOException { Tuple2[] operations = new Tuple2[] { new Tuple2<String, Operator>(UPDATE_DECREMENT, ArithmeticValueUpdate.Operator.SUB), new Tuple2<String, Operator>(UPDATE_DIVIDE, ArithmeticValueUpdate.Operator.DIV), new Tuple2<String, Operator>(UPDATE_INCREMENT, ArithmeticValueUpdate.Operator.ADD), new Tuple2<String, Operator>(UPDATE_MULTIPLY, ArithmeticValueUpdate.Operator.MUL) }; for (Tuple2<String, Operator> operator : operations) { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'match': {", " 'element': 'person',", " '" + (String) operator.first + "': 13 }}}}")); Map<String, Tuple2<Number, Operator>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); Operator op = ((ArithmeticValueUpdate) adder .getUpdate()).getOperator(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertSame(operator.second, matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } } @SuppressWarnings("rawtypes") @Test public void testArrayIndexing() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'match': {", " 'element': 3,", " 'assign': 'nalle' }}}}")); Map<Number, String> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualarray"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final Number key = ((IntegerFieldValue) adder.getValue()) .getNumber(); String op = ((StringFieldValue) ((AssignValueUpdate) adder.getUpdate()) .getValue()).getString(); matches.put(key, op); } assertEquals(1, matches.size()); Number n = Integer.valueOf(3); assertEquals("nalle", matches.get(n)); } @Test public void testDocumentRemove() { JsonReader r = createReader(inputJson("{'remove': 'id:unittest:smoke::whee'}")); DocumentType docType = r.readDocumentType(new DocumentId("id:unittest:smoke::whee")); assertEquals("smoke", docType.getName()); } private Document docFromJson(String json) throws IOException { JsonReader r = createReader(json); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); return put.getDocument(); } @Test public void testWeightedSet() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'nalle': 2,", " 'tralle': 7 }}}")); FieldValue f = doc.getFieldValue(doc.getField("actualset")); assertSame(WeightedSet.class, f.getClass()); WeightedSet<?> w = (WeightedSet<?>) f; assertEquals(2, w.size()); assertEquals(Integer.valueOf(2), w.get(new StringFieldValue("nalle"))); assertEquals(Integer.valueOf(7), w.get(new StringFieldValue("tralle"))); } @Test public void testArray() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': [", " 'nalle',", " 'tralle' ]}}")); FieldValue f = doc.getFieldValue(doc.getField("actualarray")); assertSame(Array.class, f.getClass()); Array<?> a = (Array<?>) f; assertEquals(2, a.size()); assertEquals(new StringFieldValue("nalle"), a.get(0)); assertEquals(new StringFieldValue("tralle"), a.get(1)); } @Test public void testMap() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testmap::whee',", " 'fields': {", " 'actualmap': {", " 'nalle': 'kalle',", " 'tralle': 'skalle' }}}")); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testOldMap() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testmap::whee',", " 'fields': {", " 'actualmap': [", " { 'key': 'nalle', 'value': 'kalle'},", " { 'key': 'tralle', 'value': 'skalle'} ]}}")); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testPositionPositive() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': 'N63.429722;E10.393333' }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionOld() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': {'x':10393333,'y':63429722} }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testGeoPosition() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': {'lat':63.429722,'lng':10.393333} }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testGeoPositionNoAbbreviations() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': {'latitude':63.429722,'longitude':10.393333} }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionGeoPos() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'geopos': 'N63.429722;E10.393333' }}")); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); } @Test public void testPositionOldGeoPos() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'geopos': {'x':10393333,'y':63429722} }}")); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); } @Test public void testGeoPositionGeoPos() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'geopos': {'lat':63.429722,'lng':10.393333} }}")); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); assertEquals(PositionDataType.INSTANCE, f.getDataType()); } @Test public void testPositionNegative() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': 'W46.63;S23.55' }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(-46630000, PositionDataType.getXValue(f).getInteger()); assertEquals(-23550000, PositionDataType.getYValue(f).getInteger()); } @Test public void testRaw() throws IOException { String base64 = new String(new JsonStringEncoder().quoteAsString( Base64.getEncoder().encodeToString(Utf8.toBytes("smoketest")))); String s = fieldStringFromBase64RawContent(base64); assertEquals("smoketest", s); } @Test public void can_read_legacy_chunked_base64_raw_field_encoding() throws IOException { String expected = "this is a string with an impressive length. it's long enough to reach the end of the line, wow!"; String base64withDelims = "dGhpcyBpcyBhIHN0cmluZyB3aXRoIGFuIGltcHJlc3NpdmUgbGVuZ3RoLiBpdCdzIGxvbmcgZW5v\\r\\n" + "dWdoIHRvIHJlYWNoIHRoZSBlbmQgb2YgdGhlIGxpbmUsIHdvdyE=\\r\\n"; assertEquals(expected, fieldStringFromBase64RawContent(base64withDelims)); } private String fieldStringFromBase64RawContent(String base64data) throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testraw::whee',", " 'fields': {", " 'actualraw': '" + base64data + "' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("actualraw")); assertSame(Raw.class, f.getClass()); Raw s = (Raw) f; return Utf8.toString(s.getByteBuffer()); } @Test public void testMapStringToArrayOfInt() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'bamse': [1, 2, 3] }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldMapStringToArrayOfInt() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': [", " { 'key': 'bamse', 'value': [1, 2, 3] } ]}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToString() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': {", " 'assign': 'orOther' }}}")); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); AssignValueUpdate a = (AssignValueUpdate) f.getValueUpdate(0); assertEquals(new StringFieldValue("orOther"), a.getValue()); } @Test public void testAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'assign': { 'bamse': [1, 2, 3] }}}}")); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'assign': [", " { 'key': 'bamse', 'value': [1, 2, 3] } ]}}}")); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToWeightedSet() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'assign': {", " 'person': 37,", " 'another person': 41 }}}}")); FieldUpdate x = doc.getFieldUpdate("actualset"); assertEquals(1, x.size()); AssignValueUpdate assign = (AssignValueUpdate) x.getValueUpdate(0); WeightedSet<?> w = (WeightedSet<?>) assign.getValue(); assertEquals(2, w.size()); assertEquals(Integer.valueOf(37), w.get(new StringFieldValue("person"))); assertEquals(Integer.valueOf(41), w.get(new StringFieldValue("another person"))); } @Test public void testCompleteFeed() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }},", "{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}},", "{ 'remove': 'id:unittest:smoke::whee' }]")); controlBasicFeed(r); } @Test public void testCompleteFeedWithCreateAndCondition() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }},", "{", " 'condition':'bla',", " 'update': 'id:unittest:testarray::whee',", " 'create':true,", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}},", "{ 'remove': 'id:unittest:smoke::whee' }]")); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testUpdateWithConditionAndCreateInDifferentOrdering() { int documentsCreated = 106; List<String> parts = Arrays.asList( "\"condition\":\"bla\"", "\"update\": \"id:unittest:testarray::whee\"", " \"fields\": { " + "\"actualarray\": { \"add\": [" + " \"person\",\"another person\"]}}", " \"create\":true"); Random random = new Random(42); StringBuilder documents = new StringBuilder("["); for (int x = 0; x < documentsCreated; x++) { Collections.shuffle(parts, random); documents.append("{").append(Joiner.on(",").join(parts)).append("}"); if (x < documentsCreated -1) { documents.append(","); } } documents.append("]"); InputStream rawDoc = new ByteArrayInputStream( Utf8.toBytes(documents.toString())); JsonReader r = new JsonReader(types, rawDoc, parserFactory); for (int x = 0; x < documentsCreated; x++) { DocumentUpdate update = (DocumentUpdate) r.next(); checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); } assertNull(r.next()); } @Test(expected=RuntimeException.class) public void testCreateIfNonExistentInPut() { JsonReader r = createReader(inputJson("[{", " 'create':true,", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse' },", " 'put': 'id:unittest:smoke::whee'", "}]")); r.next(); } @Test public void testCompleteFeedWithIdAfterFields() { JsonReader r = createReader(inputJson("[", "{", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' },", " 'put': 'id:unittest:smoke::whee'", "},", "{", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}},", " 'update': 'id:unittest:testarray::whee'", "},", "{ 'remove': 'id:unittest:smoke::whee' }]")); controlBasicFeed(r); } protected void controlBasicFeed(JsonReader r) { DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testCompleteFeedWithEmptyDoc() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee', 'fields': {} },", "{ 'update': 'id:unittest:testarray::whee', 'fields': {} },", "{ 'remove': 'id:unittest:smoke::whee' }]")); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); assertEquals("smoke", doc.getId().getDocType()); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; assertEquals("testarray", update.getId().getDocType()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } private void checkSimpleArrayAdd(DocumentUpdate update) { Set<String> toAdd = new HashSet<>(); FieldUpdate x = update.getFieldUpdate("actualarray"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; toAdd.add(((StringFieldValue) adder.getValue()).getString()); } assertEquals(2, toAdd.size()); assertTrue(toAdd.contains("person")); assertTrue(toAdd.contains("another person")); } private void smokeTestDoc(Document doc) { FieldValue boolField = doc.getFieldValue(doc.getField("flag")); assertSame(BoolFieldValue.class, boolField.getClass()); assertTrue((Boolean)boolField.getWrappedValue()); FieldValue stringField = doc.getFieldValue(doc.getField("nalle")); assertSame(StringFieldValue.class, stringField.getClass()); assertEquals("bamse", ((StringFieldValue) stringField).getString()); } @Test public void misspelledFieldTest() throws IOException{ JsonReader r = createReader(inputJson( "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'smething': 'smoketest',", " 'nalle': 'bamse' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); try { new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); fail(); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().startsWith("No field 'smething' in the structure of type 'smoke'")); } } @Test public void feedWithBasicErrorTest() { JsonReader r = createReader(inputJson("[", " { 'put': 'id:test:smoke::0', 'fields': { 'something': 'foo' } },", " { 'put': 'id:test:smoke::1', 'fields': { 'something': 'foo' } },", " { 'put': 'id:test:smoke::2', 'fields': { 'something': 'foo' } },", "]")); try { while (r.next() != null) ; fail(); } catch (RuntimeException e) { assertTrue(e.getMessage().contains("JsonParseException")); } } @Test public void idAsAliasForPutTest() throws IOException{ JsonReader r = createReader(inputJson("{ 'id': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } private void testFeedWithTestAndSetCondition(String jsonDoc) { ByteArrayInputStream parseInfoDoc = new ByteArrayInputStream(Utf8.toBytes(jsonDoc)); JsonReader reader = new JsonReader(types, parseInfoDoc, parserFactory); int NUM_OPERATIONS_IN_FEED = 3; for (int i = 0; i < NUM_OPERATIONS_IN_FEED; i++) { DocumentOperation operation = reader.next(); assertTrue("A test and set condition should be present", operation.getCondition().isPresent()); assertEquals("DocumentOperation's test and set condition should be equal to the one in the JSON feed", "smoke.something == \"smoketest\"", operation.getCondition().getSelection()); } assertNull(reader.next()); } @Test public void testFeedWithTestAndSetConditionOrderingOne() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'put': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " }", " },", " {", " 'update': 'id:unittest:testarray::whee',", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " },", " {", " 'remove': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\''", " }", "]" )); } @Test public void testFeedWithTestAndSetConditionOrderingTwo() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " }", " },", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " },", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'remove': 'id:unittest:smoke::whee'", " }", "]" )); } @Test public void testFeedWithTestAndSetConditionOrderingThree() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " },", " 'condition': 'smoke.something == \\'smoketest\\''", " },", " {", " 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " },", " 'condition': 'smoke.something == \\'smoketest\\''", " },", " {", " 'remove': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\''", " }", "]" )); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldAfterFieldsFieldShouldFailParse() { final String jsonData = inputJson( "[", " {", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " },", " 'bjarne': 'stroustrup'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldBeforeFieldsFieldShouldFailParse() { final String jsonData = inputJson( "[", " {", " 'update': 'id:unittest:testarray::whee',", " 'what is this': 'nothing to see here',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldWithoutFieldsFieldShouldFailParse() { String jsonData = inputJson( "[", " {", " 'remove': 'id:unittest:smoke::whee',", " 'what is love': 'baby, do not hurt me... much'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test public void testMissingOperation() { try { String jsonData = inputJson( "[", " {", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Missing a document operation ('put', 'update' or 'remove')", e.getMessage()); } } @Test public void testMissingFieldsMapInPut() { try { String jsonData = inputJson( "[", " {", " 'put': 'id:unittest:smoke::whee'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("put of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testMissingFieldsMapInUpdate() { try { String jsonData = inputJson( "[", " {", " 'update': 'id:unittest:smoke::whee'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("update of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testNullValues() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testnull::doc1',", " 'fields': {", " 'intfield': null,", " 'stringfield': null,", " 'arrayfield': null,", " 'weightedsetfield': null,", " 'mapfield': null,", " 'tensorfield': null", " }", "}")); DocumentPut put = (DocumentPut) r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:testnull::doc1"); Document doc = put.getDocument(); assertFieldValueNull(doc, "intfield"); assertFieldValueNull(doc, "stringfield"); assertFieldValueNull(doc, "arrayfield"); assertFieldValueNull(doc, "weightedsetfield"); assertFieldValueNull(doc, "mapfield"); assertFieldValueNull(doc, "tensorfield"); } @Test(expected=JsonReaderException.class) public void testNullArrayElement() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testnull::doc1',", " 'fields': {", " 'arrayfield': [ null ]", " }", "}")); r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:testnull::doc1"); fail(); } private void assertFieldValueNull(Document doc, String fieldName) { Field field = doc.getField(fieldName); assertNotNull(field); FieldValue fieldValue = doc.getFieldValue(field); assertNull(fieldValue); } static ByteArrayInputStream jsonToInputStream(String json) { return new ByteArrayInputStream(Utf8.toBytes(json)); } @Test public void testParsingWithoutTensorField() { Document doc = createPutWithoutTensor().getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals("id:unittest:testtensor::0", doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField("sparse_tensor")); assertNull(fieldValue); } @Test public void testParsingOfEmptyTensor() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor("{}")); } @Test public void testParsingOfTensorWithEmptyDimensions() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor(inputJson("{ 'dimensions': [] }"))); } @Test public void testParsingOfTensorWithEmptyCells() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor(inputJson("{ 'cells': [] }"))); } @Test public void testDisallowedDenseTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{ 'values': [] }"), "dense_tensor", "The 'values' array does not contain any values"); assertCreatePutFails(inputJson("{ 'values': '' }"), "dense_tensor", "The 'values' string does not contain any values"); } @Test public void testDisallowedMixedTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{\"blocks\":{ \"a\": [] } }"), "mixed_tensor", "Expected 3 values, but got 0"); assertCreatePutFails(inputJson("{\"blocks\":[ {\"address\":{\"x\":\"a\"}, \"values\": [] } ] }"), "mixed_tensor", "Expected 3 values, but got 0"); } @Test public void testParsingOfSparseTensorWithCells() { Tensor tensor = assertSparseTensorField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createPutWithSparseTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' },", " 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'b' },", " 'value': 3.0 }", " ]", "}"))); assertTrue(tensor instanceof MappedTensor); // any functional instance is fine } @Test public void testParsingOfDenseTensorWithCells() { Tensor tensor = assertTensorField("{{x:0,y:0}:2.0,{x:1,y:0}:3.0}}", createPutWithTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' },", " 'value': 2.0 },", " { 'address': { 'x': '1', 'y': '0' },", " 'value': 3.0 }", " ]", "}"), "dense_unbound_tensor"), "dense_unbound_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorOnDenseForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson("{", " 'values': [2.0, 3.0, 4.0, 5.0, 6.0, 7.0]", "}"), "dense_tensor"), "dense_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<int8>(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson("{", " 'values': \"020304050607\"", "}"), "dense_int8_tensor"), "dense_int8_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfMixedTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")); builder.cell().label("x", "foo").label("y", 0).value(2.0); builder.cell().label("x", "foo").label("y", 1).value(3.0); builder.cell().label("x", "foo").label("y", 2).value(4.0); builder.cell().label("x", "bar").label("y", 0).value(5.0); builder.cell().label("x", "bar").label("y", 1).value(6.0); builder.cell().label("x", "bar").label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":[" + "{\"address\":{\"x\":\"foo\"},\"values\":\"400040404080\"}," + "{\"address\":{\"x\":\"bar\"},\"values\":\"40A040C040E0\"}" + "]}"; var put = createPutWithTensor(inputJson(mixedJson), "mixed_bfloat16_tensor"); Tensor tensor = assertTensorField(expected, put, "mixed_bfloat16_tensor"); } @Test public void testParsingOfMixedTensorOnMixedForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":[" + "{\"address\":{\"x\":\"0\"},\"values\":[2.0,3.0,4.0]}," + "{\"address\":{\"x\":\"1\"},\"values\":[5.0,6.0,7.0]}" + "]}"; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance } @Test public void testMixedTensorInMixedFormWithSingleSparseDimensionShortForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":{" + "\"0\":[2.0,3.0,4.0]," + "\"1\":[5.0,6.0,7.0]" + "}}"; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance } @Test public void testParsingOfTensorWithSingleCellInDifferentJsonOrder() { assertSparseTensorField("{{x:a,y:b}:2.0}", createPutWithSparseTensor(inputJson("{", " 'cells': [", " { 'value': 2.0,", " 'address': { 'x': 'a', 'y': 'b' } }", " ]", "}"))); } @Test public void testAssignUpdateOfEmptySparseTensor() { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithSparseTensor("{}")); } @Test public void testAssignUpdateOfEmptyDenseTensor() { try { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithTensor("{}", "dense_unbound_tensor")); } catch (IllegalArgumentException e) { assertEquals("An indexed tensor must have a value", "Error in 'dense_unbound_tensor': Tensor of type tensor(x[],y[]) has no values", Exceptions.toMessageString(e)); } } @Test public void testAssignUpdateOfNullTensor() { ClearValueUpdate clearUpdate = (ClearValueUpdate) getTensorField(createAssignUpdateWithSparseTensor(null)).getValueUpdate(0); assertTrue(clearUpdate != null); assertTrue(clearUpdate.getValue() == null); } @Test public void testAssignUpdateOfTensorWithCells() { assertTensorAssignUpdateSparseField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createAssignUpdateWithSparseTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' },", " 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'b' },", " 'value': 3.0 }", " ]", "}"))); } @Test public void testAssignUpdateOfTensorDenseShortForm() { assertTensorAssignUpdateDenseField("tensor(x[2],y[3]):[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]", createAssignUpdateWithTensor(inputJson("{", " 'values': [1,2,3,4,5,6]", "}"), "dense_tensor")); } @Test public void tensor_modify_update_with_replace_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_add_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, "sparse_tensor", inputJson("{", " 'operation': 'add',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_multiply_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "sparse_tensor", inputJson("{", " 'operation': 'multiply',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_treats_the_input_tensor_as_sparse() { // Note that the type of the tensor in the modify update is sparse (it only has mapped dimensions). assertTensorModifyUpdate("tensor(x{},y{}):{{x:0,y:0}:2.0, {x:1,y:2}:3.0}", TensorModifyUpdate.Operation.REPLACE, "dense_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' }, 'value': 2.0 },", " { 'address': { 'x': '1', 'y': '2' }, 'value': 3.0 } ]}")); } @Test public void tensor_modify_update_on_non_tensor_field_throws() { try { JsonReader reader = createReader(inputJson("{ 'update': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': {", " 'modify': {} }}}")); reader.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::doc1"); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Error in 'something': A modify update can only be applied to tensor fields. Field 'something' is of type 'string'", Exceptions.toMessageString(e)); } } @Test public void tensor_modify_update_on_dense_unbound_tensor_throws() { illegalTensorModifyUpdate("Error in 'dense_unbound_tensor': A modify update cannot be applied to tensor types with indexed unbound dimensions. Field 'dense_unbound_tensor' has unsupported tensor type 'tensor(x[],y[])'", "dense_unbound_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorModifyUpdate("{{x:a}:2.0, {x:c}: 3.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_single_dimension_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': {", " 'a': 2.0,", " 'c': 3.0 }}")); } @Test public void tensor_modify_update_with_replace_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_array() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': [", " { 'address': { 'x': 'a' }, 'values': [1,2,3] } ]}")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_must_specify_full_subspace() { illegalTensorModifyUpdate("Error in 'mixed_tensor': At {x:a}: Expected 3 values, but got 2", "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': {", " 'a': [2,3] } }")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_map() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': {", " 'a': [1,2,3] } }")); } @Test public void tensor_modify_update_with_add_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.ADD, "mixed_tensor", inputJson("{", " 'operation': 'add',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_multiply_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "mixed_tensor", inputJson("{", " 'operation': 'multiply',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws() { illegalTensorModifyUpdate("Error in 'dense_tensor': Dimension 'y' has label '3' but type is tensor(x[2],y[3])", "dense_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws_mixed() { illegalTensorModifyUpdate("Error in 'mixed_tensor': Dimension 'y' has label '3' but type is tensor(x{},y[3])", "mixed_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_with_unknown_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown operation 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", "{", " 'operation': 'unknown',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_without_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain an operation", "sparse_tensor", "{", " 'cells': [] }"); } @Test public void tensor_modify_update_without_cells_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", "{", " 'operation': 'replace' }"); } @Test public void tensor_modify_update_with_unknown_content_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown JSON string 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", "{", " 'unknown': 'here' }"); } @Test public void tensor_add_update_on_sparse_tensor() { assertTensorAddUpdate("{{x:a,y:b}:2.0, {x:c,y:d}: 3.0}", "sparse_tensor", inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'd' }, 'value': 3.0 } ]}")); } @Test public void tensor_add_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorAddUpdate("{{x:a}:2.0, {x:c}: 3.0}", "sparse_single_dimension_tensor", inputJson("{", " 'cells': {", " 'a': 2.0,", " 'c': 3.0 }}")); } @Test public void tensor_add_update_on_mixed_tensor() { assertTensorAddUpdate("{{x:a,y:0}:2.0, {x:a,y:1}:3.0, {x:a,y:2}:0.0}", "mixed_tensor", inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 },", " { 'address': { 'x': 'a', 'y': '1' }, 'value': 3.0 } ]}")); } @Test public void tensor_add_update_on_mixed_with_out_of_bound_dense_cells_throws() { illegalTensorAddUpdate("Error in 'mixed_tensor': Index 3 out of bounds for length 3", "mixed_tensor", "{", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_add_update_on_dense_tensor_throws() { illegalTensorAddUpdate("Error in 'dense_tensor': An add update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", "{", " 'cells': [] }"); } @Test public void tensor_add_update_on_not_fully_specified_cell_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Missing a label for dimension y for tensor(x{},y{})", "sparse_tensor", "{", " 'cells': [", " { 'address': { 'x': 'a' }, 'value': 2.0 } ]}"); } @Test public void tensor_add_update_without_cells_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Add update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", "{}"); illegalTensorAddUpdate("Error in 'mixed_tensor': Add update for field 'mixed_tensor' does not contain tensor cells", "mixed_tensor", "{}"); } @Test public void tensor_remove_update_on_sparse_tensor() { assertTensorRemoveUpdate("{{x:a,y:b}:1.0,{x:c,y:d}:1.0}", "sparse_tensor", inputJson("{", " 'addresses': [", " { 'x': 'a', 'y': 'b' },", " { 'x': 'c', 'y': 'd' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor() { assertTensorRemoveUpdate("{{x:1}:1.0,{x:2}:1.0}", "mixed_tensor", inputJson("{", " 'addresses': [", " { 'x': '1' },", " { 'x': '2' } ]}")); } @Test public void tensor_remove_update_on_sparse_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{y:b}:1.0,{y:d}:1.0}", "sparse_tensor", inputJson("{", " 'addresses': [", " { 'y': 'b' },", " { 'y': 'd' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{x:1,z:a}:1.0,{x:2,z:b}:1.0}", "mixed_tensor_adv", inputJson("{", " 'addresses': [", " { 'x': '1', 'z': 'a' },", " { 'x': '2', 'z': 'b' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor_with_dense_addresses_throws() { illegalTensorRemoveUpdate("Error in 'mixed_tensor': Indexed dimension address 'y' should not be specified in remove update", "mixed_tensor", "{", " 'addresses': [", " { 'x': '1', 'y': '0' },", " { 'x': '2', 'y': '0' } ]}"); } @Test public void tensor_remove_update_on_dense_tensor_throws() { illegalTensorRemoveUpdate("Error in 'dense_tensor': A remove update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", "{", " 'addresses': [] }"); } @Test public void tensor_remove_update_with_stray_dimension_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{},y{}) does not contain dimension 'foo'", "sparse_tensor", "{", " 'addresses': [", " { 'x': 'a', 'foo': 'b' } ]}"); illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{}) does not contain dimension 'foo'", "sparse_tensor", "{", " 'addresses': [", " { 'x': 'c' },", " { 'x': 'a', 'foo': 'b' } ]}"); } @Test public void tensor_remove_update_without_cells_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': Remove update for field 'sparse_tensor' does not contain tensor addresses", "sparse_tensor", "{'addresses': [] }"); illegalTensorRemoveUpdate("Error in 'mixed_tensor': Remove update for field 'mixed_tensor' does not contain tensor addresses", "mixed_tensor", "{'addresses': [] }"); } @Test public void require_that_parser_propagates_datatype_parser_errors_predicate() { assertParserErrorMatches( "Error in document 'id:unittest:testpredicate::0' - could not parse field 'boolean' of type 'predicate': " + "line 1:10 no viable alternative at character '>'", "[", " {", " 'fields': {", " 'boolean': 'timestamp > 9000'", " },", " 'put': 'id:unittest:testpredicate::0'", " }", "]" ); } @Test public void require_that_parser_propagates_datatype_parser_errors_string_as_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \" 1\"", "[", " {", " 'fields': {", " 'integerfield': ' 1'", " },", " 'put': 'id:unittest:testint::0'", " }", "]" ); } @Test public void require_that_parser_propagates_datatype_parser_errors_overflowing_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \"281474976710656\"", "[", " {", " 'fields': {", " 'integerfield': 281474976710656", " },", " 'put': 'id:unittest:testint::0'", " }", "]" ); } @Test public void requireThatUnknownDocTypeThrowsIllegalArgumentException() { final String jsonData = inputJson( "[", " {", " 'put': 'id:ns:walrus::walrus1',", " 'fields': {", " 'aField': 42", " }", " }", "]"); try { new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail(); } catch (IllegalArgumentException e) { assertEquals("Document type walrus does not exist", e.getMessage()); } } private static final String TENSOR_DOC_ID = "id:unittest:testtensor::0"; private void illegalTensorModifyUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorModifyUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorAddUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorAddUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorRemoveUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorRemoveUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private DocumentPut createPutWithoutTensor() { JsonReader reader = createReader(inputJson("[ { 'put': '" + TENSOR_DOC_ID + "', 'fields': { } } ]")); return (DocumentPut) reader.next(); } private DocumentPut createPutWithSparseTensor(String inputTensor) { return createPutWithTensor(inputTensor, "sparse_tensor"); } private DocumentPut createPutWithTensor(String inputTensor, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'put': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': " + inputTensor + " }}]")); return (DocumentPut) reader.next(); } private DocumentUpdate createAssignUpdateWithSparseTensor(String inputTensor) { return createAssignUpdateWithTensor(inputTensor, "sparse_tensor"); } private DocumentUpdate createAssignUpdateWithTensor(String inputTensor, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'update': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': {", " 'assign': " + (inputTensor != null ? inputTensor : "null") + " } } } ]")); return (DocumentUpdate) reader.next(); } private static Tensor assertSparseTensorField(String expectedTensor, DocumentPut put) { return assertTensorField(expectedTensor, put, "sparse_tensor"); } private static Tensor assertTensorField(String expectedTensor, DocumentPut put, String tensorFieldName) { return assertTensorField(Tensor.from(expectedTensor), put, tensorFieldName); } private static Tensor assertTensorField(Tensor expectedTensor, DocumentPut put, String tensorFieldName) { Document doc = put.getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals(TENSOR_DOC_ID, doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField(tensorFieldName)); assertEquals(expectedTensor, fieldValue.getTensor().get()); return fieldValue.getTensor().get(); } private static void assertTensorFieldUpdate(DocumentUpdate update, String tensorFieldName) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); assertEquals(1, update.fieldUpdates().size()); assertEquals(1, update.getFieldUpdate(tensorFieldName).size()); } private static void assertTensorAssignUpdateSparseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "sparse_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private static void assertTensorAssignUpdateDenseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "dense_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, String tensorFieldName, String modifyJson) { assertTensorModifyUpdate(expectedTensor, expectedOperation, tensorFieldName, createTensorModifyUpdate(modifyJson, tensorFieldName)); } private static void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorModifyUpdate modifyUpdate = (TensorModifyUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(expectedOperation, modifyUpdate.getOperation()); assertEquals(Tensor.from(expectedTensor), modifyUpdate.getValue().getTensor().get()); } private DocumentUpdate createTensorModifyUpdate(String modifyJson, String tensorFieldName) { return createTensorUpdate("modify", modifyJson, tensorFieldName); } private DocumentUpdate createTensorAddUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("add", tensorJson, tensorFieldName); } private DocumentUpdate createTensorRemoveUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("remove", tensorJson, tensorFieldName); } private DocumentUpdate createTensorUpdate(String operation, String tensorJson, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'update': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': {", " '" + operation + "': " + tensorJson + " }}}]")); return (DocumentUpdate) reader.next(); } private void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorAddUpdate(expectedTensor, tensorFieldName, createTensorAddUpdate(tensorJson, tensorFieldName)); } private static void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorAddUpdate addUpdate = (TensorAddUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), addUpdate.getValue().getTensor().get()); } private void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorRemoveUpdate(expectedTensor, tensorFieldName, createTensorRemoveUpdate(tensorJson, tensorFieldName)); } private static void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorRemoveUpdate removeUpdate = (TensorRemoveUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), removeUpdate.getValue().getTensor().get()); } private static FieldUpdate getTensorField(DocumentUpdate update) { return getTensorField(update, "sparse_tensor"); } private static FieldUpdate getTensorField(DocumentUpdate update, String fieldName) { FieldUpdate fieldUpdate = update.getFieldUpdate(fieldName); assertEquals(1, fieldUpdate.size()); return fieldUpdate; } // NOTE: Do not call this method multiple times from a test method as it's using the ExpectedException rule private void assertParserErrorMatches(String expectedError, String... json) { String jsonData = inputJson(json); try { new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail(); } catch (JsonReaderException e) { assertEquals(expectedError, e.getMessage()); } } private void assertCreatePutFails(String tensor, String name, String msg) { try { createPutWithTensor(inputJson(tensor), name); fail("Expected exception"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains(msg)); } } }
frankfanslc/vespa
document/src/test/java/com/yahoo/document/json/JsonReaderTestCase.java
213,283
/* * Copyright (c) 2018, 2019 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.helidon.security.abac.role; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.annotation.security.DenyAll; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import io.helidon.common.Errors; import io.helidon.config.Config; import io.helidon.security.EndpointConfig; import io.helidon.security.Principal; import io.helidon.security.ProviderRequest; import io.helidon.security.Role; import io.helidon.security.SecurityLevel; import io.helidon.security.Subject; import io.helidon.security.SubjectType; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Unit test for {@link RoleValidator}. */ class RoleValidatorTest { static Config config; @BeforeAll static void beforeAll() { config = Config.create(); } @Test void testRolesAllowedPermit() { RoleValidator validator = RoleValidator.create(); RolesAllowed annot = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(RolesAllowed.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testRolesAllowedDeny() { RoleValidator validator = RoleValidator.create(); RolesAllowed annot = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(RolesAllowed.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("User is not in admin role, should have failed"); } } @Test void testUserRoles() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); when(annot.subjectType()).thenReturn(SubjectType.USER); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(RoleValidator.Roles.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testUserRolesDeny() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.subjectType()).thenReturn(SubjectType.USER); when(annot.value()).thenReturn(roleArray); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(RoleValidator.Roles.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("User is not in admin role, should have failed"); } } @Test void testServiceRoles() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); when(annot.subjectType()).thenReturn(SubjectType.SERVICE); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(RoleValidator.Roles.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.service()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("service")) .addGrant(Role.create("admin")) .build())); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testServiceRolesDeny() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); when(annot.subjectType()).thenReturn(SubjectType.SERVICE); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(RoleValidator.Roles.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("service")) .addGrant(Role.create("user")) .build())); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("Service is not in admin role, should have failed"); } } @Test void testDenyAll() { RoleValidator validator = RoleValidator.create(); DenyAll annot = mock(DenyAll.class); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(DenyAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("DenyAll is set on this method, this should have failed"); } } @Test void testPermitAll() { RoleValidator validator = RoleValidator.create(); PermitAll annot = mock(PermitAll.class); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(PermitAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testDenyAllAndPermitAll() { RoleValidator validator = RoleValidator.create(); PermitAll permitAll = mock(PermitAll.class); DenyAll denyAll = mock(DenyAll.class); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(DenyAll.class, EndpointConfig.AnnotationScope.CLASS)) .thenReturn(List.of(denyAll)); when(classSecurityLevel.filterAnnotations(PermitAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(permitAll)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testDenyAllAndRoles() { RoleValidator validator = RoleValidator.create(); DenyAll denyAll = mock(DenyAll.class); RolesAllowed rolesAllowed = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(rolesAllowed.value()).thenReturn(roleArray); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(DenyAll.class, EndpointConfig.AnnotationScope.CLASS)) .thenReturn(List.of(denyAll)); when(classSecurityLevel.filterAnnotations(RolesAllowed.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(rolesAllowed)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testPermitAllAndRolesAndDenyAll() { RoleValidator validator = RoleValidator.create(); PermitAll permitAll = mock(PermitAll.class); DenyAll denyAll = mock(DenyAll.class); RolesAllowed rolesAllowed = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(rolesAllowed.value()).thenReturn(roleArray); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(PermitAll.class, EndpointConfig.AnnotationScope.CLASS)) .thenReturn(List.of(permitAll)); when(classSecurityLevel.filterAnnotations(DenyAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(denyAll)); when(classSecurityLevel.filterAnnotations(RolesAllowed.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(rolesAllowed)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("DenyAll is set on this method, this should have failed"); } } @Test void testAllAccessAnnotationsOnTheSameLevel() { RoleValidator validator = RoleValidator.create(); PermitAll permitAll = mock(PermitAll.class); DenyAll denyAll = mock(DenyAll.class); RolesAllowed rolesAllowed = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(rolesAllowed.value()).thenReturn(roleArray); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(PermitAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(permitAll)); when(classSecurityLevel.filterAnnotations(DenyAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(denyAll)); when(classSecurityLevel.filterAnnotations(RolesAllowed.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(List.of(rolesAllowed)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("DenyAll is set on this method, this should have failed"); } } @Test void testRolesFromConfig() { RoleValidator roleValidator = RoleValidator.create(); RoleValidator.RoleConfig roleConfig = roleValidator.fromConfig(config.get("test1")); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); roleValidator.validate(roleConfig, collector, request); collector.collect().checkValid(); } @Test void testRolesAndPermitAllFromConfig() { RoleValidator roleValidator = RoleValidator.create(); RoleValidator.RoleConfig roleConfig = roleValidator.fromConfig(config.get("test2")); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("test")) .build())); roleValidator.validate(roleConfig, collector, request); collector.collect().checkValid(); } @Test void testRolesAndDenyAllFromConfig() { RoleValidator roleValidator = RoleValidator.create(); RoleValidator.RoleConfig roleConfig = roleValidator.fromConfig(config.get("test3")); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("test")) .build())); roleValidator.validate(roleConfig, collector, request); if (collector.collect().isValid()) { fail("DenyAll is set on this method, this should have failed"); } } @Test void testAllAccessModificationsOnTheSameLevelFromConfig() { RoleValidator roleValidator = RoleValidator.create(); RoleValidator.RoleConfig roleConfig = roleValidator.fromConfig(config.get("test4")); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("test")) .build())); roleValidator.validate(roleConfig, collector, request); if (collector.collect().isValid()) { fail("DenyAll is set on this method, this should have failed"); } } }
Verdent/helidon
security/abac/role/src/test/java/io/helidon/security/abac/role/RoleValidatorTest.java
213,284
/* * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.helidon.security.abac.role; import java.util.Optional; import javax.annotation.security.RolesAllowed; import io.helidon.common.CollectionsHelper; import io.helidon.common.Errors; import io.helidon.security.Principal; import io.helidon.security.ProviderRequest; import io.helidon.security.Role; import io.helidon.security.Subject; import io.helidon.security.SubjectType; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Unit test for {@link RoleValidator}. */ class RoleValidatorTest { @Test void testRolesAllowedPermit() { RoleValidator validator = RoleValidator.create(); RolesAllowed annot = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(CollectionsHelper.listOf(annot)); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.getSubject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.getService()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testRolesAllowedDeny() { RoleValidator validator = RoleValidator.create(); RolesAllowed annot = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(CollectionsHelper.listOf(annot)); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.getSubject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.getService()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("User is not in admin role, should have failed"); } } @Test void testUserRoles() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); when(annot.subjectType()).thenReturn(SubjectType.USER); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(CollectionsHelper.listOf(annot)); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.getSubject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.getService()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testUserRolesDeny() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.subjectType()).thenReturn(SubjectType.USER); when(annot.value()).thenReturn(roleArray); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(CollectionsHelper.listOf(annot)); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.getSubject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.getService()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("User is not in admin role, should have failed"); } } @Test void testServiceRoles() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); when(annot.subjectType()).thenReturn(SubjectType.SERVICE); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(CollectionsHelper.listOf(annot)); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.getService()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("service")) .addGrant(Role.create("admin")) .build())); when(request.getSubject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testServiceRolesDeny() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); when(annot.subjectType()).thenReturn(SubjectType.SERVICE); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(CollectionsHelper.listOf(annot)); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.getSubject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.getService()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("service")) .addGrant(Role.create("user")) .build())); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("Service is not in admin role, should have failed"); } } }
tomas-langer/helidon
security/abac-validators/role-validator/src/test/java/io/helidon/security/abac/role/RoleValidatorTest.java
213,285
/* * Copyright (c) 2018, 2019 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.helidon.security.abac.role; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.annotation.security.DenyAll; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import io.helidon.common.CollectionsHelper; import io.helidon.common.Errors; import io.helidon.config.Config; import io.helidon.security.EndpointConfig; import io.helidon.security.Principal; import io.helidon.security.ProviderRequest; import io.helidon.security.Role; import io.helidon.security.SecurityLevel; import io.helidon.security.Subject; import io.helidon.security.SubjectType; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Unit test for {@link RoleValidator}. */ class RoleValidatorTest { static Config config; @BeforeAll static void beforeAll() { config = Config.create(); } @Test void testRolesAllowedPermit() { RoleValidator validator = RoleValidator.create(); RolesAllowed annot = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(RolesAllowed.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testRolesAllowedDeny() { RoleValidator validator = RoleValidator.create(); RolesAllowed annot = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(RolesAllowed.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("User is not in admin role, should have failed"); } } @Test void testUserRoles() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); when(annot.subjectType()).thenReturn(SubjectType.USER); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(RoleValidator.Roles.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testUserRolesDeny() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.subjectType()).thenReturn(SubjectType.USER); when(annot.value()).thenReturn(roleArray); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(RoleValidator.Roles.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("User is not in admin role, should have failed"); } } @Test void testServiceRoles() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); when(annot.subjectType()).thenReturn(SubjectType.SERVICE); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(RoleValidator.Roles.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.service()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("service")) .addGrant(Role.create("admin")) .build())); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testServiceRolesDeny() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); when(annot.subjectType()).thenReturn(SubjectType.SERVICE); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(RoleValidator.Roles.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("service")) .addGrant(Role.create("user")) .build())); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("Service is not in admin role, should have failed"); } } @Test void testDenyAll() { RoleValidator validator = RoleValidator.create(); DenyAll annot = mock(DenyAll.class); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(DenyAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("DenyAll is set on this method, this should have failed"); } } @Test void testPermitAll() { RoleValidator validator = RoleValidator.create(); PermitAll annot = mock(PermitAll.class); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(PermitAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testDenyAllAndPermitAll() { RoleValidator validator = RoleValidator.create(); PermitAll permitAll = mock(PermitAll.class); DenyAll denyAll = mock(DenyAll.class); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(DenyAll.class, EndpointConfig.AnnotationScope.CLASS)) .thenReturn(CollectionsHelper.listOf(denyAll)); when(classSecurityLevel.filterAnnotations(PermitAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(permitAll)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testDenyAllAndRoles() { RoleValidator validator = RoleValidator.create(); DenyAll denyAll = mock(DenyAll.class); RolesAllowed rolesAllowed = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(rolesAllowed.value()).thenReturn(roleArray); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(DenyAll.class, EndpointConfig.AnnotationScope.CLASS)) .thenReturn(CollectionsHelper.listOf(denyAll)); when(classSecurityLevel.filterAnnotations(RolesAllowed.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(rolesAllowed)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testPermitAllAndRolesAndDenyAll() { RoleValidator validator = RoleValidator.create(); PermitAll permitAll = mock(PermitAll.class); DenyAll denyAll = mock(DenyAll.class); RolesAllowed rolesAllowed = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(rolesAllowed.value()).thenReturn(roleArray); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(PermitAll.class, EndpointConfig.AnnotationScope.CLASS)) .thenReturn(CollectionsHelper.listOf(permitAll)); when(classSecurityLevel.filterAnnotations(DenyAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(denyAll)); when(classSecurityLevel.filterAnnotations(RolesAllowed.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(rolesAllowed)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("DenyAll is set on this method, this should have failed"); } } @Test void testAllAccessAnnotationsOnTheSameLevel() { RoleValidator validator = RoleValidator.create(); PermitAll permitAll = mock(PermitAll.class); DenyAll denyAll = mock(DenyAll.class); RolesAllowed rolesAllowed = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(rolesAllowed.value()).thenReturn(roleArray); SecurityLevel appSecurityLevel = mock(SecurityLevel.class); SecurityLevel classSecurityLevel = mock(SecurityLevel.class); List<SecurityLevel> securityLevels = new ArrayList<>(); securityLevels.add(appSecurityLevel); securityLevels.add(classSecurityLevel); EndpointConfig ep = mock(EndpointConfig.class); when(ep.securityLevels()).thenReturn(securityLevels); when(classSecurityLevel.filterAnnotations(PermitAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(permitAll)); when(classSecurityLevel.filterAnnotations(DenyAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(denyAll)); when(classSecurityLevel.filterAnnotations(RolesAllowed.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(rolesAllowed)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("DenyAll is set on this method, this should have failed"); } } @Test void testRolesFromConfig() { RoleValidator roleValidator = RoleValidator.create(); RoleValidator.RoleConfig roleConfig = roleValidator.fromConfig(config.get("test1")); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); roleValidator.validate(roleConfig, collector, request); collector.collect().checkValid(); } @Test void testRolesAndPermitAllFromConfig() { RoleValidator roleValidator = RoleValidator.create(); RoleValidator.RoleConfig roleConfig = roleValidator.fromConfig(config.get("test2")); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("test")) .build())); roleValidator.validate(roleConfig, collector, request); collector.collect().checkValid(); } @Test void testRolesAndDenyAllFromConfig() { RoleValidator roleValidator = RoleValidator.create(); RoleValidator.RoleConfig roleConfig = roleValidator.fromConfig(config.get("test3")); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("test")) .build())); roleValidator.validate(roleConfig, collector, request); if (collector.collect().isValid()) { fail("DenyAll is set on this method, this should have failed"); } } @Test void testAllAccessModificationsOnTheSameLevelFromConfig() { RoleValidator roleValidator = RoleValidator.create(); RoleValidator.RoleConfig roleConfig = roleValidator.fromConfig(config.get("test4")); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("test")) .build())); roleValidator.validate(roleConfig, collector, request); if (collector.collect().isValid()) { fail("DenyAll is set on this method, this should have failed"); } } }
mickeyboxell/helidon-1
security/abac/role/src/test/java/io/helidon/security/abac/role/RoleValidatorTest.java
213,286
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.document.json; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.io.JsonStringEncoder; import com.google.common.base.Joiner; import com.yahoo.collections.Tuple2; import com.yahoo.document.ArrayDataType; import com.yahoo.document.DataType; import com.yahoo.document.Document; import com.yahoo.document.DocumentId; import com.yahoo.document.DocumentOperation; import com.yahoo.document.DocumentPut; import com.yahoo.document.DocumentRemove; import com.yahoo.document.DocumentType; import com.yahoo.document.DocumentTypeManager; import com.yahoo.document.DocumentUpdate; import com.yahoo.document.Field; import com.yahoo.document.MapDataType; import com.yahoo.document.PositionDataType; import com.yahoo.document.StructDataType; import com.yahoo.document.TensorDataType; import com.yahoo.document.WeightedSetDataType; import com.yahoo.document.datatypes.Array; import com.yahoo.document.datatypes.BoolFieldValue; import com.yahoo.document.datatypes.FieldValue; import com.yahoo.document.datatypes.IntegerFieldValue; import com.yahoo.document.datatypes.MapFieldValue; import com.yahoo.document.datatypes.Raw; import com.yahoo.document.datatypes.StringFieldValue; import com.yahoo.document.datatypes.Struct; import com.yahoo.document.datatypes.TensorFieldValue; import com.yahoo.document.datatypes.WeightedSet; import com.yahoo.document.json.readers.DocumentParseInfo; import com.yahoo.document.json.readers.VespaJsonDocumentReader; import com.yahoo.document.serialization.DocumentSerializer; import com.yahoo.document.serialization.DocumentSerializerFactory; import com.yahoo.document.update.AddValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate.Operator; import com.yahoo.document.update.AssignValueUpdate; import com.yahoo.document.update.ClearValueUpdate; import com.yahoo.document.update.FieldUpdate; import com.yahoo.document.update.MapValueUpdate; import com.yahoo.document.update.TensorAddUpdate; import com.yahoo.document.update.TensorModifyUpdate; import com.yahoo.document.update.TensorRemoveUpdate; import com.yahoo.document.update.ValueUpdate; import com.yahoo.io.GrowableByteBuffer; import com.yahoo.tensor.IndexedTensor; import com.yahoo.tensor.MappedTensor; import com.yahoo.tensor.MixedTensor; import com.yahoo.tensor.Tensor; import com.yahoo.tensor.TensorType; import com.yahoo.text.Utf8; import com.yahoo.yolean.Exceptions; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DECREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DIVIDE; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_INCREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_MULTIPLY; import static com.yahoo.test.json.JsonTestHelper.inputJson; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Basic test of JSON streams to Vespa document instances. * * @author Steinar Knutsen * @author bratseth */ public class JsonReaderTestCase { private DocumentTypeManager types; private JsonFactory parserFactory; @Rule public ExpectedException exception = ExpectedException.none(); @Before public void setUp() throws Exception { parserFactory = new JsonFactory(); types = new DocumentTypeManager(); { DocumentType x = new DocumentType("smoke"); x.addField(new Field("something", DataType.STRING)); x.addField(new Field("nalle", DataType.STRING)); x.addField(new Field("int1", DataType.INT)); x.addField(new Field("flag", DataType.BOOL)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("mirrors"); StructDataType woo = new StructDataType("woo"); woo.addField(new Field("sandra", DataType.STRING)); woo.addField(new Field("cloud", DataType.STRING)); x.addField(new Field("skuggsjaa", woo)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testarray"); DataType d = new ArrayDataType(DataType.STRING); x.addField(new Field("actualarray", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testset"); DataType d = new WeightedSetDataType(DataType.STRING, true, true); x.addField(new Field("actualset", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testmap"); DataType d = new MapDataType(DataType.STRING, DataType.STRING); x.addField(new Field("actualmap", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testraw"); DataType d = DataType.RAW; x.addField(new Field("actualraw", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testMapStringToArrayOfInt"); DataType value = new ArrayDataType(DataType.INT); DataType d = new MapDataType(DataType.STRING, value); x.addField(new Field("actualMapStringToArrayOfInt", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testsinglepos"); DataType d = PositionDataType.INSTANCE; x.addField(new Field("singlepos", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testtensor"); x.addField(new Field("sparse_single_dimension_tensor", new TensorDataType(new TensorType.Builder().mapped("x").build()))); x.addField(new Field("sparse_tensor", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").build()))); x.addField(new Field("dense_tensor", new TensorDataType(new TensorType.Builder().indexed("x", 2).indexed("y", 3).build()))); x.addField(new Field("dense_int8_tensor", new TensorDataType(TensorType.fromSpec("tensor<int8>(x[2],y[3])")))); x.addField(new Field("dense_unbound_tensor", new TensorDataType(new TensorType.Builder().indexed("x").indexed("y").build()))); x.addField(new Field("mixed_tensor", new TensorDataType(new TensorType.Builder().mapped("x").indexed("y", 3).build()))); x.addField(new Field("mixed_bfloat16_tensor", new TensorDataType(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")))); x.addField(new Field("mixed_tensor_adv", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").mapped("z").indexed("a", 3).build()))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testpredicate"); x.addField(new Field("boolean", DataType.PREDICATE)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testint"); x.addField(new Field("integerfield", DataType.INT)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testnull"); x.addField(new Field("intfield", DataType.INT)); x.addField(new Field("stringfield", DataType.STRING)); x.addField(new Field("arrayfield", new ArrayDataType(DataType.STRING))); x.addField(new Field("weightedsetfield", new WeightedSetDataType(DataType.STRING, true, true))); x.addField(new Field("mapfield", new MapDataType(DataType.STRING, DataType.STRING))); x.addField(new Field("tensorfield", new TensorDataType(new TensorType.Builder().indexed("x").build()))); types.registerDocumentType(x); } } @After public void tearDown() throws Exception { types = null; parserFactory = null; exception = ExpectedException.none(); } private JsonReader createReader(String jsonInput) { InputStream input = new ByteArrayInputStream(Utf8.toBytes(jsonInput)); return new JsonReader(types, input, parserFactory); } @Test public void readSingleDocumentPut() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " }", "}")); DocumentPut put = (DocumentPut) r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:smoke::doc1"); smokeTestDoc(put.getDocument()); } @Test public final void readSingleDocumentUpdate() { JsonReader r = createReader(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': {", " 'assign': 'orOther' }}}")); DocumentUpdate doc = (DocumentUpdate) r.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::whee"); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof AssignValueUpdate); } @Test public void readClearField() { JsonReader r = createReader(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'int1': {", " 'assign': null }}}")); DocumentUpdate doc = (DocumentUpdate) r.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::whee"); FieldUpdate f = doc.getFieldUpdate("int1"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof ClearValueUpdate); assertNull(f.getValueUpdate(0).getValue()); } @Test public void smokeTest() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } @Test public void docIdLookaheadTest() throws IOException { JsonReader r = createReader(inputJson( "{ 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " },", " 'put': 'id:unittest:smoke::doc1'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } @Test public void emptyDocTest() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::whee', 'fields': {}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); assertEquals("id:unittest:smoke::whee", parseInfo.documentId.toString()); } @Test public void testStruct() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:mirrors::whee',", " 'fields': {", " 'skuggsjaa': {", " 'sandra': 'person',", " 'cloud': 'another person' }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("skuggsjaa")); assertSame(Struct.class, f.getClass()); Struct s = (Struct) f; assertEquals("person", ((StringFieldValue) s.getFieldValue("sandra")).getString()); } private DocumentUpdate parseUpdate(String json) throws IOException { InputStream rawDoc = new ByteArrayInputStream(Utf8.toBytes(json)); JsonReader r = new JsonReader(types, rawDoc, parserFactory); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentUpdate update = new DocumentUpdate(docType, parseInfo.documentId); new VespaJsonDocumentReader().readUpdate(parseInfo.fieldsBuffer, update); return update; } @Test public void testStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(inputJson("{ 'update': 'id:unittest:mirrors:g=test:whee',", " 'create': true,", " 'fields': {", " 'skuggsjaa': {", " 'assign': {", " 'sandra': 'person',", " 'cloud': 'another person' }}}}")); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(2, s.getFieldCount()); assertEquals(new StringFieldValue("person"), s.getFieldValue(s.getField("sandra"))); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(107, buf.position()); } @Test public final void testEmptyStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(inputJson("{ 'update': 'id:unittest:mirrors:g=test:whee',", " 'create': true,", " 'fields': { ", " 'skuggsjaa': {", " 'assign': { } }}}")); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(0, s.getFieldCount()); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(69, buf.position()); } @Test public void testUpdateArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}}")); checkSimpleArrayAdd(doc); } @Test public void testUpdateWeighted() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'add': {", " 'person': 37,", " 'another person': 41 }}}}")); Map<String, Integer> weights = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; final String s = ((StringFieldValue) adder.getValue()).getString(); weights.put(s, adder.getWeight()); } assertEquals(2, weights.size()); final String o = "person"; final String o2 = "another person"; assertTrue(weights.containsKey(o)); assertTrue(weights.containsKey(o2)); assertEquals(Integer.valueOf(37), weights.get(o)); assertEquals(Integer.valueOf(41), weights.get(o2)); } @Test public void testUpdateMatch() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'match': {", " 'element': 'person',", " 'increment': 13 }}}}")); Map<String, Tuple2<Number, String>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); String op = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperator().toString(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()).getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertEquals("ADD", matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } @SuppressWarnings({ "cast", "unchecked", "rawtypes" }) @Test public void testArithmeticOperators() throws IOException { Tuple2[] operations = new Tuple2[] { new Tuple2<String, Operator>(UPDATE_DECREMENT, ArithmeticValueUpdate.Operator.SUB), new Tuple2<String, Operator>(UPDATE_DIVIDE, ArithmeticValueUpdate.Operator.DIV), new Tuple2<String, Operator>(UPDATE_INCREMENT, ArithmeticValueUpdate.Operator.ADD), new Tuple2<String, Operator>(UPDATE_MULTIPLY, ArithmeticValueUpdate.Operator.MUL) }; for (Tuple2<String, Operator> operator : operations) { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'match': {", " 'element': 'person',", " '" + (String) operator.first + "': 13 }}}}")); Map<String, Tuple2<Number, Operator>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); Operator op = ((ArithmeticValueUpdate) adder .getUpdate()).getOperator(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertSame(operator.second, matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } } @SuppressWarnings("rawtypes") @Test public void testArrayIndexing() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'match': {", " 'element': 3,", " 'assign': 'nalle' }}}}")); Map<Number, String> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualarray"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final Number key = ((IntegerFieldValue) adder.getValue()) .getNumber(); String op = ((StringFieldValue) ((AssignValueUpdate) adder.getUpdate()) .getValue()).getString(); matches.put(key, op); } assertEquals(1, matches.size()); Number n = Integer.valueOf(3); assertEquals("nalle", matches.get(n)); } @Test public void testDocumentRemove() { JsonReader r = createReader(inputJson("{'remove': 'id:unittest:smoke::whee'}")); DocumentType docType = r.readDocumentType(new DocumentId("id:unittest:smoke::whee")); assertEquals("smoke", docType.getName()); } @Test public void testWeightedSet() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'nalle': 2,", " 'tralle': 7 }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("actualset")); assertSame(WeightedSet.class, f.getClass()); WeightedSet<?> w = (WeightedSet<?>) f; assertEquals(2, w.size()); assertEquals(Integer.valueOf(2), w.get(new StringFieldValue("nalle"))); assertEquals(Integer.valueOf(7), w.get(new StringFieldValue("tralle"))); } @Test public void testArray() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': [", " 'nalle',", " 'tralle' ]}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("actualarray")); assertSame(Array.class, f.getClass()); Array<?> a = (Array<?>) f; assertEquals(2, a.size()); assertEquals(new StringFieldValue("nalle"), a.get(0)); assertEquals(new StringFieldValue("tralle"), a.get(1)); } @Test public void testMap() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testmap::whee',", " 'fields': {", " 'actualmap': {", " 'nalle': 'kalle',", " 'tralle': 'skalle' }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testOldMap() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testmap::whee',", " 'fields': {", " 'actualmap': [", " { 'key': 'nalle', 'value': 'kalle'},", " { 'key': 'tralle', 'value': 'skalle'} ]}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testPositionPositive() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': 'N63.429722;E10.393333' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionNegative() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': 'W46.63;S23.55' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(-46630000, PositionDataType.getXValue(f).getInteger()); assertEquals(-23550000, PositionDataType.getYValue(f).getInteger()); } @Test public void testRaw() throws IOException { String base64 = new String(new JsonStringEncoder().quoteAsString( Base64.getEncoder().encodeToString(Utf8.toBytes("smoketest")))); String s = fieldStringFromBase64RawContent(base64); assertEquals("smoketest", s); } @Test public void can_read_legacy_chunked_base64_raw_field_encoding() throws IOException { String expected = "this is a string with an impressive length. it's long enough to reach the end of the line, wow!"; String base64withDelims = "dGhpcyBpcyBhIHN0cmluZyB3aXRoIGFuIGltcHJlc3NpdmUgbGVuZ3RoLiBpdCdzIGxvbmcgZW5v\\r\\n" + "dWdoIHRvIHJlYWNoIHRoZSBlbmQgb2YgdGhlIGxpbmUsIHdvdyE=\\r\\n"; assertEquals(expected, fieldStringFromBase64RawContent(base64withDelims)); } private String fieldStringFromBase64RawContent(String base64data) throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testraw::whee',", " 'fields': {", " 'actualraw': '" + base64data + "' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("actualraw")); assertSame(Raw.class, f.getClass()); Raw s = (Raw) f; return Utf8.toString(s.getByteBuffer()); } @Test public void testMapStringToArrayOfInt() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'bamse': [1, 2, 3] }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldMapStringToArrayOfInt() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': [", " { 'key': 'bamse', 'value': [1, 2, 3] } ]}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToString() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': {", " 'assign': 'orOther' }}}")); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); AssignValueUpdate a = (AssignValueUpdate) f.getValueUpdate(0); assertEquals(new StringFieldValue("orOther"), a.getValue()); } @Test public void testAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'assign': { 'bamse': [1, 2, 3] }}}}")); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'assign': [", " { 'key': 'bamse', 'value': [1, 2, 3] } ]}}}")); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToWeightedSet() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'assign': {", " 'person': 37,", " 'another person': 41 }}}}")); FieldUpdate x = doc.getFieldUpdate("actualset"); assertEquals(1, x.size()); AssignValueUpdate assign = (AssignValueUpdate) x.getValueUpdate(0); WeightedSet<?> w = (WeightedSet<?>) assign.getValue(); assertEquals(2, w.size()); assertEquals(Integer.valueOf(37), w.get(new StringFieldValue("person"))); assertEquals(Integer.valueOf(41), w.get(new StringFieldValue("another person"))); } @Test public void testCompleteFeed() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }},", "{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}},", "{ 'remove': 'id:unittest:smoke::whee' }]")); controlBasicFeed(r); } @Test public void testCompleteFeedWithCreateAndCondition() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }},", "{", " 'condition':'bla',", " 'update': 'id:unittest:testarray::whee',", " 'create':true,", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}},", "{ 'remove': 'id:unittest:smoke::whee' }]")); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testUpdateWithConditionAndCreateInDifferentOrdering() { int documentsCreated = 106; List<String> parts = Arrays.asList( "\"condition\":\"bla\"", "\"update\": \"id:unittest:testarray::whee\"", " \"fields\": { " + "\"actualarray\": { \"add\": [" + " \"person\",\"another person\"]}}", " \"create\":true"); Random random = new Random(42); StringBuilder documents = new StringBuilder("["); for (int x = 0; x < documentsCreated; x++) { Collections.shuffle(parts, random); documents.append("{").append(Joiner.on(",").join(parts)).append("}"); if (x < documentsCreated -1) { documents.append(","); } } documents.append("]"); InputStream rawDoc = new ByteArrayInputStream( Utf8.toBytes(documents.toString())); JsonReader r = new JsonReader(types, rawDoc, parserFactory); for (int x = 0; x < documentsCreated; x++) { DocumentUpdate update = (DocumentUpdate) r.next(); checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); } assertNull(r.next()); } @Test(expected=RuntimeException.class) public void testCreateIfNonExistentInPut() { JsonReader r = createReader(inputJson("[{", " 'create':true,", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse' },", " 'put': 'id:unittest:smoke::whee'", "}]")); r.next(); } @Test public void testCompleteFeedWithIdAfterFields() { JsonReader r = createReader(inputJson("[", "{", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' },", " 'put': 'id:unittest:smoke::whee'", "},", "{", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}},", " 'update': 'id:unittest:testarray::whee'", "},", "{ 'remove': 'id:unittest:smoke::whee' }]")); controlBasicFeed(r); } protected void controlBasicFeed(JsonReader r) { DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testCompleteFeedWithEmptyDoc() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee', 'fields': {} },", "{ 'update': 'id:unittest:testarray::whee', 'fields': {} },", "{ 'remove': 'id:unittest:smoke::whee' }]")); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); assertEquals("smoke", doc.getId().getDocType()); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; assertEquals("testarray", update.getId().getDocType()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } private void checkSimpleArrayAdd(DocumentUpdate update) { Set<String> toAdd = new HashSet<>(); FieldUpdate x = update.getFieldUpdate("actualarray"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; toAdd.add(((StringFieldValue) adder.getValue()).getString()); } assertEquals(2, toAdd.size()); assertTrue(toAdd.contains("person")); assertTrue(toAdd.contains("another person")); } private void smokeTestDoc(Document doc) { FieldValue boolField = doc.getFieldValue(doc.getField("flag")); assertSame(BoolFieldValue.class, boolField.getClass()); assertTrue((Boolean)boolField.getWrappedValue()); FieldValue stringField = doc.getFieldValue(doc.getField("nalle")); assertSame(StringFieldValue.class, stringField.getClass()); assertEquals("bamse", ((StringFieldValue) stringField).getString()); } @Test public void misspelledFieldTest() throws IOException{ JsonReader r = createReader(inputJson( "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'smething': 'smoketest',", " 'nalle': 'bamse' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); exception.expect(IllegalArgumentException.class); exception.expectMessage("No field 'smething' in the structure of type 'smoke'"); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); } @Test public void feedWithBasicErrorTest() { JsonReader r = createReader(inputJson("[", " { 'put': 'id:test:smoke::0', 'fields': { 'something': 'foo' } },", " { 'put': 'id:test:smoke::1', 'fields': { 'something': 'foo' } },", " { 'put': 'id:test:smoke::2', 'fields': { 'something': 'foo' } },", "]")); exception.expect(RuntimeException.class); exception.expectMessage("JsonParseException"); while (r.next() != null); } @Test public void idAsAliasForPutTest() throws IOException{ JsonReader r = createReader(inputJson("{ 'id': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } private void testFeedWithTestAndSetCondition(String jsonDoc) { ByteArrayInputStream parseInfoDoc = new ByteArrayInputStream(Utf8.toBytes(jsonDoc)); JsonReader reader = new JsonReader(types, parseInfoDoc, parserFactory); int NUM_OPERATIONS_IN_FEED = 3; for (int i = 0; i < NUM_OPERATIONS_IN_FEED; i++) { DocumentOperation operation = reader.next(); assertTrue("A test and set condition should be present", operation.getCondition().isPresent()); assertEquals("DocumentOperation's test and set condition should be equal to the one in the JSON feed", "smoke.something == \"smoketest\"", operation.getCondition().getSelection()); } assertNull(reader.next()); } @Test public void testFeedWithTestAndSetConditionOrderingOne() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'put': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " }", " },", " {", " 'update': 'id:unittest:testarray::whee',", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " },", " {", " 'remove': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\''", " }", "]" )); } @Test public void testFeedWithTestAndSetConditionOrderingTwo() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " }", " },", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " },", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'remove': 'id:unittest:smoke::whee'", " }", "]" )); } @Test public void testFeedWithTestAndSetConditionOrderingThree() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " },", " 'condition': 'smoke.something == \\'smoketest\\''", " },", " {", " 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " },", " 'condition': 'smoke.something == \\'smoketest\\''", " },", " {", " 'remove': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\''", " }", "]" )); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldAfterFieldsFieldShouldFailParse() { final String jsonData = inputJson( "[", " {", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " },", " 'bjarne': 'stroustrup'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldBeforeFieldsFieldShouldFailParse() { final String jsonData = inputJson( "[", " {", " 'update': 'id:unittest:testarray::whee',", " 'what is this': 'nothing to see here',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldWithoutFieldsFieldShouldFailParse() { String jsonData = inputJson( "[", " {", " 'remove': 'id:unittest:smoke::whee',", " 'what is love': 'baby, do not hurt me... much'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test public void testMissingOperation() { try { String jsonData = inputJson( "[", " {", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Missing a document operation ('put', 'update' or 'remove')", e.getMessage()); } } @Test public void testMissingFieldsMapInPut() { try { String jsonData = inputJson( "[", " {", " 'put': 'id:unittest:smoke::whee'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("put of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testMissingFieldsMapInUpdate() { try { String jsonData = inputJson( "[", " {", " 'update': 'id:unittest:smoke::whee'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("update of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testNullValues() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testnull::doc1',", " 'fields': {", " 'intfield': null,", " 'stringfield': null,", " 'arrayfield': null,", " 'weightedsetfield': null,", " 'mapfield': null,", " 'tensorfield': null", " }", "}")); DocumentPut put = (DocumentPut) r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:testnull::doc1"); Document doc = put.getDocument(); assertFieldValueNull(doc, "intfield"); assertFieldValueNull(doc, "stringfield"); assertFieldValueNull(doc, "arrayfield"); assertFieldValueNull(doc, "weightedsetfield"); assertFieldValueNull(doc, "mapfield"); assertFieldValueNull(doc, "tensorfield"); } @Test(expected=JsonReaderException.class) public void testNullArrayElement() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testnull::doc1',", " 'fields': {", " 'arrayfield': [ null ]", " }", "}")); r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:testnull::doc1"); fail(); } private void assertFieldValueNull(Document doc, String fieldName) { Field field = doc.getField(fieldName); assertNotNull(field); FieldValue fieldValue = doc.getFieldValue(field); assertNull(fieldValue); } static ByteArrayInputStream jsonToInputStream(String json) { return new ByteArrayInputStream(Utf8.toBytes(json)); } @Test public void testParsingWithoutTensorField() { Document doc = createPutWithoutTensor().getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals("id:unittest:testtensor::0", doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField("sparse_tensor")); assertNull(fieldValue); } @Test public void testParsingOfEmptyTensor() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor("{}")); } @Test public void testParsingOfTensorWithEmptyDimensions() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor(inputJson("{ 'dimensions': [] }"))); } @Test public void testParsingOfTensorWithEmptyCells() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor(inputJson("{ 'cells': [] }"))); } @Test public void testDisallowedDenseTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{ 'values': [] }"), "dense_tensor", "The 'values' array does not contain any values"); assertCreatePutFails(inputJson("{ 'values': '' }"), "dense_tensor", "The 'values' string does not contain any values"); } @Test public void testDisallowedMixedTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{\"blocks\":{ \"a\": [] } }"), "mixed_tensor", "Expected 3 values, but got 0"); assertCreatePutFails(inputJson("{\"blocks\":[ {\"address\":{\"x\":\"a\"}, \"values\": [] } ] }"), "mixed_tensor", "Expected 3 values, but got 0"); } @Test public void testParsingOfSparseTensorWithCells() { Tensor tensor = assertSparseTensorField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createPutWithSparseTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' },", " 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'b' },", " 'value': 3.0 }", " ]", "}"))); assertTrue(tensor instanceof MappedTensor); // any functional instance is fine } @Test public void testParsingOfDenseTensorWithCells() { Tensor tensor = assertTensorField("{{x:0,y:0}:2.0,{x:1,y:0}:3.0}}", createPutWithTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' },", " 'value': 2.0 },", " { 'address': { 'x': '1', 'y': '0' },", " 'value': 3.0 }", " ]", "}"), "dense_unbound_tensor"), "dense_unbound_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorOnDenseForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson("{", " 'values': [2.0, 3.0, 4.0, 5.0, 6.0, 7.0]", "}"), "dense_tensor"), "dense_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<int8>(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson("{", " 'values': \"020304050607\"", "}"), "dense_int8_tensor"), "dense_int8_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfMixedTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")); builder.cell().label("x", "foo").label("y", 0).value(2.0); builder.cell().label("x", "foo").label("y", 1).value(3.0); builder.cell().label("x", "foo").label("y", 2).value(4.0); builder.cell().label("x", "bar").label("y", 0).value(5.0); builder.cell().label("x", "bar").label("y", 1).value(6.0); builder.cell().label("x", "bar").label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":[" + "{\"address\":{\"x\":\"foo\"},\"values\":\"400040404080\"}," + "{\"address\":{\"x\":\"bar\"},\"values\":\"40A040C040E0\"}" + "]}"; var put = createPutWithTensor(inputJson(mixedJson), "mixed_bfloat16_tensor"); Tensor tensor = assertTensorField(expected, put, "mixed_bfloat16_tensor"); } @Test public void testParsingOfMixedTensorOnMixedForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":[" + "{\"address\":{\"x\":\"0\"},\"values\":[2.0,3.0,4.0]}," + "{\"address\":{\"x\":\"1\"},\"values\":[5.0,6.0,7.0]}" + "]}"; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance } @Test public void testMixedTensorInMixedFormWithSingleSparseDimensionShortForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":{" + "\"0\":[2.0,3.0,4.0]," + "\"1\":[5.0,6.0,7.0]" + "}}"; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance } @Test public void testParsingOfTensorWithSingleCellInDifferentJsonOrder() { assertSparseTensorField("{{x:a,y:b}:2.0}", createPutWithSparseTensor(inputJson("{", " 'cells': [", " { 'value': 2.0,", " 'address': { 'x': 'a', 'y': 'b' } }", " ]", "}"))); } @Test public void testAssignUpdateOfEmptySparseTensor() { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithSparseTensor("{}")); } @Test public void testAssignUpdateOfEmptyDenseTensor() { try { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithTensor("{}", "dense_unbound_tensor")); } catch (IllegalArgumentException e) { assertEquals("An indexed tensor must have a value", "Error in 'dense_unbound_tensor': Tensor of type tensor(x[],y[]) has no values", Exceptions.toMessageString(e)); } } @Test public void testAssignUpdateOfNullTensor() { ClearValueUpdate clearUpdate = (ClearValueUpdate) getTensorField(createAssignUpdateWithSparseTensor(null)).getValueUpdate(0); assertTrue(clearUpdate != null); assertTrue(clearUpdate.getValue() == null); } @Test public void testAssignUpdateOfTensorWithCells() { assertTensorAssignUpdateSparseField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createAssignUpdateWithSparseTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' },", " 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'b' },", " 'value': 3.0 }", " ]", "}"))); } @Test public void testAssignUpdateOfTensorDenseShortForm() { assertTensorAssignUpdateDenseField("tensor(x[2],y[3]):[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]", createAssignUpdateWithTensor(inputJson("{", " 'values': [1,2,3,4,5,6]", "}"), "dense_tensor")); } @Test public void tensor_modify_update_with_replace_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_add_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, "sparse_tensor", inputJson("{", " 'operation': 'add',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_multiply_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "sparse_tensor", inputJson("{", " 'operation': 'multiply',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_treats_the_input_tensor_as_sparse() { // Note that the type of the tensor in the modify update is sparse (it only has mapped dimensions). assertTensorModifyUpdate("tensor(x{},y{}):{{x:0,y:0}:2.0, {x:1,y:2}:3.0}", TensorModifyUpdate.Operation.REPLACE, "dense_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' }, 'value': 2.0 },", " { 'address': { 'x': '1', 'y': '2' }, 'value': 3.0 } ]}")); } @Test public void tensor_modify_update_on_non_tensor_field_throws() { try { JsonReader reader = createReader(inputJson("{ 'update': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': {", " 'modify': {} }}}")); reader.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::doc1"); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Error in 'something': A modify update can only be applied to tensor fields. Field 'something' is of type 'string'", Exceptions.toMessageString(e)); } } @Test public void tensor_modify_update_on_dense_unbound_tensor_throws() { illegalTensorModifyUpdate("Error in 'dense_unbound_tensor': A modify update cannot be applied to tensor types with indexed unbound dimensions. Field 'dense_unbound_tensor' has unsupported tensor type 'tensor(x[],y[])'", "dense_unbound_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorModifyUpdate("{{x:a}:2.0, {x:c}: 3.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_single_dimension_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': {", " 'a': 2.0,", " 'c': 3.0 }}")); } @Test public void tensor_modify_update_with_replace_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_array() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': [", " { 'address': { 'x': 'a' }, 'values': [1,2,3] } ]}")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_must_specify_full_subspace() { illegalTensorModifyUpdate("Error in 'mixed_tensor': At {x:a}: Expected 3 values, but got 2", "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': {", " 'a': [2,3] } }")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_map() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': {", " 'a': [1,2,3] } }")); } @Test public void tensor_modify_update_with_add_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.ADD, "mixed_tensor", inputJson("{", " 'operation': 'add',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_multiply_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "mixed_tensor", inputJson("{", " 'operation': 'multiply',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws() { illegalTensorModifyUpdate("Error in 'dense_tensor': Dimension 'y' has label '3' but type is tensor(x[2],y[3])", "dense_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws_mixed() { illegalTensorModifyUpdate("Error in 'mixed_tensor': Dimension 'y' has label '3' but type is tensor(x{},y[3])", "mixed_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_with_unknown_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown operation 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", "{", " 'operation': 'unknown',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_without_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain an operation", "sparse_tensor", "{", " 'cells': [] }"); } @Test public void tensor_modify_update_without_cells_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", "{", " 'operation': 'replace' }"); } @Test public void tensor_modify_update_with_unknown_content_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown JSON string 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", "{", " 'unknown': 'here' }"); } @Test public void tensor_add_update_on_sparse_tensor() { assertTensorAddUpdate("{{x:a,y:b}:2.0, {x:c,y:d}: 3.0}", "sparse_tensor", inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'd' }, 'value': 3.0 } ]}")); } @Test public void tensor_add_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorAddUpdate("{{x:a}:2.0, {x:c}: 3.0}", "sparse_single_dimension_tensor", inputJson("{", " 'cells': {", " 'a': 2.0,", " 'c': 3.0 }}")); } @Test public void tensor_add_update_on_mixed_tensor() { assertTensorAddUpdate("{{x:a,y:0}:2.0, {x:a,y:1}:3.0, {x:a,y:2}:0.0}", "mixed_tensor", inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 },", " { 'address': { 'x': 'a', 'y': '1' }, 'value': 3.0 } ]}")); } @Test public void tensor_add_update_on_mixed_with_out_of_bound_dense_cells_throws() { illegalTensorAddUpdate("Error in 'mixed_tensor': Index 3 out of bounds for length 3", "mixed_tensor", "{", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_add_update_on_dense_tensor_throws() { illegalTensorAddUpdate("Error in 'dense_tensor': An add update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", "{", " 'cells': [] }"); } @Test public void tensor_add_update_on_not_fully_specified_cell_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Missing a label for dimension y for tensor(x{},y{})", "sparse_tensor", "{", " 'cells': [", " { 'address': { 'x': 'a' }, 'value': 2.0 } ]}"); } @Test public void tensor_add_update_without_cells_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Add update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", "{}"); illegalTensorAddUpdate("Error in 'mixed_tensor': Add update for field 'mixed_tensor' does not contain tensor cells", "mixed_tensor", "{}"); } @Test public void tensor_remove_update_on_sparse_tensor() { assertTensorRemoveUpdate("{{x:a,y:b}:1.0,{x:c,y:d}:1.0}", "sparse_tensor", inputJson("{", " 'addresses': [", " { 'x': 'a', 'y': 'b' },", " { 'x': 'c', 'y': 'd' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor() { assertTensorRemoveUpdate("{{x:1}:1.0,{x:2}:1.0}", "mixed_tensor", inputJson("{", " 'addresses': [", " { 'x': '1' },", " { 'x': '2' } ]}")); } @Test public void tensor_remove_update_on_sparse_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{y:b}:1.0,{y:d}:1.0}", "sparse_tensor", inputJson("{", " 'addresses': [", " { 'y': 'b' },", " { 'y': 'd' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{x:1,z:a}:1.0,{x:2,z:b}:1.0}", "mixed_tensor_adv", inputJson("{", " 'addresses': [", " { 'x': '1', 'z': 'a' },", " { 'x': '2', 'z': 'b' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor_with_dense_addresses_throws() { illegalTensorRemoveUpdate("Error in 'mixed_tensor': Indexed dimension address 'y' should not be specified in remove update", "mixed_tensor", "{", " 'addresses': [", " { 'x': '1', 'y': '0' },", " { 'x': '2', 'y': '0' } ]}"); } @Test public void tensor_remove_update_on_dense_tensor_throws() { illegalTensorRemoveUpdate("Error in 'dense_tensor': A remove update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", "{", " 'addresses': [] }"); } @Test public void tensor_remove_update_with_stray_dimension_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{},y{}) does not contain dimension 'foo'", "sparse_tensor", "{", " 'addresses': [", " { 'x': 'a', 'foo': 'b' } ]}"); illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{}) does not contain dimension 'foo'", "sparse_tensor", "{", " 'addresses': [", " { 'x': 'c' },", " { 'x': 'a', 'foo': 'b' } ]}"); } @Test public void tensor_remove_update_without_cells_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': Remove update for field 'sparse_tensor' does not contain tensor addresses", "sparse_tensor", "{'addresses': [] }"); illegalTensorRemoveUpdate("Error in 'mixed_tensor': Remove update for field 'mixed_tensor' does not contain tensor addresses", "mixed_tensor", "{'addresses': [] }"); } @Test public void require_that_parser_propagates_datatype_parser_errors_predicate() { assertParserErrorMatches( "Error in document 'id:unittest:testpredicate::0' - could not parse field 'boolean' of type 'predicate': " + "line 1:10 no viable alternative at character '>'", "[", " {", " 'fields': {", " 'boolean': 'timestamp > 9000'", " },", " 'put': 'id:unittest:testpredicate::0'", " }", "]" ); } @Test public void require_that_parser_propagates_datatype_parser_errors_string_as_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \" 1\"", "[", " {", " 'fields': {", " 'integerfield': ' 1'", " },", " 'put': 'id:unittest:testint::0'", " }", "]" ); } @Test public void require_that_parser_propagates_datatype_parser_errors_overflowing_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \"281474976710656\"", "[", " {", " 'fields': {", " 'integerfield': 281474976710656", " },", " 'put': 'id:unittest:testint::0'", " }", "]" ); } @Test public void requireThatUnknownDocTypeThrowsIllegalArgumentException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Document type walrus does not exist"); final String jsonData = inputJson( "[", " {", " 'put': 'id:ns:walrus::walrus1',", " 'fields': {", " 'aField': 42", " }", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } private static final String TENSOR_DOC_ID = "id:unittest:testtensor::0"; private void illegalTensorModifyUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorModifyUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorAddUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorAddUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorRemoveUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorRemoveUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private DocumentPut createPutWithoutTensor() { JsonReader reader = createReader(inputJson("[ { 'put': '" + TENSOR_DOC_ID + "', 'fields': { } } ]")); return (DocumentPut) reader.next(); } private DocumentPut createPutWithSparseTensor(String inputTensor) { return createPutWithTensor(inputTensor, "sparse_tensor"); } private DocumentPut createPutWithTensor(String inputTensor, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'put': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': " + inputTensor + " }}]")); return (DocumentPut) reader.next(); } private DocumentUpdate createAssignUpdateWithSparseTensor(String inputTensor) { return createAssignUpdateWithTensor(inputTensor, "sparse_tensor"); } private DocumentUpdate createAssignUpdateWithTensor(String inputTensor, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'update': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': {", " 'assign': " + (inputTensor != null ? inputTensor : "null") + " } } } ]")); return (DocumentUpdate) reader.next(); } private static Tensor assertSparseTensorField(String expectedTensor, DocumentPut put) { return assertTensorField(expectedTensor, put, "sparse_tensor"); } private static Tensor assertTensorField(String expectedTensor, DocumentPut put, String tensorFieldName) { return assertTensorField(Tensor.from(expectedTensor), put, tensorFieldName); } private static Tensor assertTensorField(Tensor expectedTensor, DocumentPut put, String tensorFieldName) { Document doc = put.getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals(TENSOR_DOC_ID, doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField(tensorFieldName)); assertEquals(expectedTensor, fieldValue.getTensor().get()); return fieldValue.getTensor().get(); } private static void assertTensorFieldUpdate(DocumentUpdate update, String tensorFieldName) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); assertEquals(1, update.fieldUpdates().size()); assertEquals(1, update.getFieldUpdate(tensorFieldName).size()); } private static void assertTensorAssignUpdateSparseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "sparse_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private static void assertTensorAssignUpdateDenseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "dense_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, String tensorFieldName, String modifyJson) { assertTensorModifyUpdate(expectedTensor, expectedOperation, tensorFieldName, createTensorModifyUpdate(modifyJson, tensorFieldName)); } private static void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorModifyUpdate modifyUpdate = (TensorModifyUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(expectedOperation, modifyUpdate.getOperation()); assertEquals(Tensor.from(expectedTensor), modifyUpdate.getValue().getTensor().get()); } private DocumentUpdate createTensorModifyUpdate(String modifyJson, String tensorFieldName) { return createTensorUpdate("modify", modifyJson, tensorFieldName); } private DocumentUpdate createTensorAddUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("add", tensorJson, tensorFieldName); } private DocumentUpdate createTensorRemoveUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("remove", tensorJson, tensorFieldName); } private DocumentUpdate createTensorUpdate(String operation, String tensorJson, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'update': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': {", " '" + operation + "': " + tensorJson + " }}}]")); return (DocumentUpdate) reader.next(); } private void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorAddUpdate(expectedTensor, tensorFieldName, createTensorAddUpdate(tensorJson, tensorFieldName)); } private static void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorAddUpdate addUpdate = (TensorAddUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), addUpdate.getValue().getTensor().get()); } private void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorRemoveUpdate(expectedTensor, tensorFieldName, createTensorRemoveUpdate(tensorJson, tensorFieldName)); } private static void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorRemoveUpdate removeUpdate = (TensorRemoveUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), removeUpdate.getValue().getTensor().get()); } private static FieldUpdate getTensorField(DocumentUpdate update) { return getTensorField(update, "sparse_tensor"); } private static FieldUpdate getTensorField(DocumentUpdate update, String fieldName) { FieldUpdate fieldUpdate = update.getFieldUpdate(fieldName); assertEquals(1, fieldUpdate.size()); return fieldUpdate; } // NOTE: Do not call this method multiple times from a test method as it's using the ExpectedException rule private void assertParserErrorMatches(String expectedError, String... json) { exception.expect(JsonReaderException.class); exception.expectMessage(expectedError); String jsonData = inputJson(json); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } private void assertCreatePutFails(String tensor, String name, String msg) { try { createPutWithTensor(inputJson(tensor), name); fail("Expected exception"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains(msg)); } } }
wyfunique/vespa
document/src/test/java/com/yahoo/document/json/JsonReaderTestCase.java
213,287
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.document.json; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.io.JsonStringEncoder; import com.google.common.base.Joiner; import com.yahoo.collections.Tuple2; import com.yahoo.document.ArrayDataType; import com.yahoo.document.DataType; import com.yahoo.document.Document; import com.yahoo.document.DocumentId; import com.yahoo.document.DocumentOperation; import com.yahoo.document.DocumentPut; import com.yahoo.document.DocumentRemove; import com.yahoo.document.DocumentType; import com.yahoo.document.DocumentTypeManager; import com.yahoo.document.DocumentUpdate; import com.yahoo.document.Field; import com.yahoo.document.MapDataType; import com.yahoo.document.PositionDataType; import com.yahoo.document.StructDataType; import com.yahoo.document.TensorDataType; import com.yahoo.document.WeightedSetDataType; import com.yahoo.document.datatypes.Array; import com.yahoo.document.datatypes.BoolFieldValue; import com.yahoo.document.datatypes.FieldValue; import com.yahoo.document.datatypes.IntegerFieldValue; import com.yahoo.document.datatypes.MapFieldValue; import com.yahoo.document.datatypes.Raw; import com.yahoo.document.datatypes.StringFieldValue; import com.yahoo.document.datatypes.Struct; import com.yahoo.document.datatypes.TensorFieldValue; import com.yahoo.document.datatypes.WeightedSet; import com.yahoo.document.json.readers.DocumentParseInfo; import com.yahoo.document.json.readers.VespaJsonDocumentReader; import com.yahoo.document.serialization.DocumentSerializer; import com.yahoo.document.serialization.DocumentSerializerFactory; import com.yahoo.document.update.AddValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate.Operator; import com.yahoo.document.update.AssignValueUpdate; import com.yahoo.document.update.ClearValueUpdate; import com.yahoo.document.update.FieldUpdate; import com.yahoo.document.update.MapValueUpdate; import com.yahoo.document.update.TensorAddUpdate; import com.yahoo.document.update.TensorModifyUpdate; import com.yahoo.document.update.TensorRemoveUpdate; import com.yahoo.document.update.ValueUpdate; import com.yahoo.io.GrowableByteBuffer; import com.yahoo.tensor.IndexedTensor; import com.yahoo.tensor.MappedTensor; import com.yahoo.tensor.MixedTensor; import com.yahoo.tensor.Tensor; import com.yahoo.tensor.TensorType; import com.yahoo.text.Utf8; import com.yahoo.yolean.Exceptions; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DECREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DIVIDE; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_INCREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_MULTIPLY; import static com.yahoo.test.json.JsonTestHelper.inputJson; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Basic test of JSON streams to Vespa document instances. * * @author Steinar Knutsen * @author bratseth */ public class JsonReaderTestCase { private DocumentTypeManager types; private JsonFactory parserFactory; @Before public void setUp() throws Exception { parserFactory = new JsonFactory(); types = new DocumentTypeManager(); { DocumentType x = new DocumentType("smoke"); x.addField(new Field("something", DataType.STRING)); x.addField(new Field("nalle", DataType.STRING)); x.addField(new Field("int1", DataType.INT)); x.addField(new Field("flag", DataType.BOOL)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("mirrors"); StructDataType woo = new StructDataType("woo"); woo.addField(new Field("sandra", DataType.STRING)); woo.addField(new Field("cloud", DataType.STRING)); x.addField(new Field("skuggsjaa", woo)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testarray"); DataType d = new ArrayDataType(DataType.STRING); x.addField(new Field("actualarray", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testset"); DataType d = new WeightedSetDataType(DataType.STRING, true, true); x.addField(new Field("actualset", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testmap"); DataType d = new MapDataType(DataType.STRING, DataType.STRING); x.addField(new Field("actualmap", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testraw"); DataType d = DataType.RAW; x.addField(new Field("actualraw", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testMapStringToArrayOfInt"); DataType value = new ArrayDataType(DataType.INT); DataType d = new MapDataType(DataType.STRING, value); x.addField(new Field("actualMapStringToArrayOfInt", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testsinglepos"); DataType d = PositionDataType.INSTANCE; x.addField(new Field("singlepos", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testtensor"); x.addField(new Field("sparse_single_dimension_tensor", new TensorDataType(new TensorType.Builder().mapped("x").build()))); x.addField(new Field("sparse_tensor", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").build()))); x.addField(new Field("dense_tensor", new TensorDataType(new TensorType.Builder().indexed("x", 2).indexed("y", 3).build()))); x.addField(new Field("dense_int8_tensor", new TensorDataType(TensorType.fromSpec("tensor<int8>(x[2],y[3])")))); x.addField(new Field("dense_unbound_tensor", new TensorDataType(new TensorType.Builder().indexed("x").indexed("y").build()))); x.addField(new Field("mixed_tensor", new TensorDataType(new TensorType.Builder().mapped("x").indexed("y", 3).build()))); x.addField(new Field("mixed_bfloat16_tensor", new TensorDataType(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")))); x.addField(new Field("mixed_tensor_adv", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").mapped("z").indexed("a", 3).build()))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testpredicate"); x.addField(new Field("boolean", DataType.PREDICATE)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testint"); x.addField(new Field("integerfield", DataType.INT)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testnull"); x.addField(new Field("intfield", DataType.INT)); x.addField(new Field("stringfield", DataType.STRING)); x.addField(new Field("arrayfield", new ArrayDataType(DataType.STRING))); x.addField(new Field("weightedsetfield", new WeightedSetDataType(DataType.STRING, true, true))); x.addField(new Field("mapfield", new MapDataType(DataType.STRING, DataType.STRING))); x.addField(new Field("tensorfield", new TensorDataType(new TensorType.Builder().indexed("x").build()))); types.registerDocumentType(x); } } @After public void tearDown() throws Exception { types = null; parserFactory = null; } private JsonReader createReader(String jsonInput) { InputStream input = new ByteArrayInputStream(Utf8.toBytes(jsonInput)); return new JsonReader(types, input, parserFactory); } @Test public void readSingleDocumentPut() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " }", "}")); DocumentPut put = (DocumentPut) r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:smoke::doc1"); smokeTestDoc(put.getDocument()); } @Test public final void readSingleDocumentUpdate() { JsonReader r = createReader(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': {", " 'assign': 'orOther' }}}")); DocumentUpdate doc = (DocumentUpdate) r.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::whee"); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof AssignValueUpdate); } @Test public void readClearField() { JsonReader r = createReader(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'int1': {", " 'assign': null }}}")); DocumentUpdate doc = (DocumentUpdate) r.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::whee"); FieldUpdate f = doc.getFieldUpdate("int1"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof ClearValueUpdate); assertNull(f.getValueUpdate(0).getValue()); } @Test public void smokeTest() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } @Test public void docIdLookaheadTest() throws IOException { JsonReader r = createReader(inputJson( "{ 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " },", " 'put': 'id:unittest:smoke::doc1'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } @Test public void emptyDocTest() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::whee', 'fields': {}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); assertEquals("id:unittest:smoke::whee", parseInfo.documentId.toString()); } @Test public void testStruct() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:mirrors::whee',", " 'fields': {", " 'skuggsjaa': {", " 'sandra': 'person',", " 'cloud': 'another person' }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("skuggsjaa")); assertSame(Struct.class, f.getClass()); Struct s = (Struct) f; assertEquals("person", ((StringFieldValue) s.getFieldValue("sandra")).getString()); } private DocumentUpdate parseUpdate(String json) throws IOException { InputStream rawDoc = new ByteArrayInputStream(Utf8.toBytes(json)); JsonReader r = new JsonReader(types, rawDoc, parserFactory); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentUpdate update = new DocumentUpdate(docType, parseInfo.documentId); new VespaJsonDocumentReader().readUpdate(parseInfo.fieldsBuffer, update); return update; } @Test public void testStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(inputJson("{ 'update': 'id:unittest:mirrors:g=test:whee',", " 'create': true,", " 'fields': {", " 'skuggsjaa': {", " 'assign': {", " 'sandra': 'person',", " 'cloud': 'another person' }}}}")); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(2, s.getFieldCount()); assertEquals(new StringFieldValue("person"), s.getFieldValue(s.getField("sandra"))); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(107, buf.position()); } @Test public final void testEmptyStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(inputJson("{ 'update': 'id:unittest:mirrors:g=test:whee',", " 'create': true,", " 'fields': { ", " 'skuggsjaa': {", " 'assign': { } }}}")); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(0, s.getFieldCount()); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(69, buf.position()); } @Test public void testUpdateArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}}")); checkSimpleArrayAdd(doc); } @Test public void testUpdateWeighted() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'add': {", " 'person': 37,", " 'another person': 41 }}}}")); Map<String, Integer> weights = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; final String s = ((StringFieldValue) adder.getValue()).getString(); weights.put(s, adder.getWeight()); } assertEquals(2, weights.size()); final String o = "person"; final String o2 = "another person"; assertTrue(weights.containsKey(o)); assertTrue(weights.containsKey(o2)); assertEquals(Integer.valueOf(37), weights.get(o)); assertEquals(Integer.valueOf(41), weights.get(o2)); } @Test public void testUpdateMatch() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'match': {", " 'element': 'person',", " 'increment': 13 }}}}")); Map<String, Tuple2<Number, String>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); String op = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperator().toString(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()).getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertEquals("ADD", matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } @SuppressWarnings({ "cast", "unchecked", "rawtypes" }) @Test public void testArithmeticOperators() throws IOException { Tuple2[] operations = new Tuple2[] { new Tuple2<String, Operator>(UPDATE_DECREMENT, ArithmeticValueUpdate.Operator.SUB), new Tuple2<String, Operator>(UPDATE_DIVIDE, ArithmeticValueUpdate.Operator.DIV), new Tuple2<String, Operator>(UPDATE_INCREMENT, ArithmeticValueUpdate.Operator.ADD), new Tuple2<String, Operator>(UPDATE_MULTIPLY, ArithmeticValueUpdate.Operator.MUL) }; for (Tuple2<String, Operator> operator : operations) { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'match': {", " 'element': 'person',", " '" + (String) operator.first + "': 13 }}}}")); Map<String, Tuple2<Number, Operator>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); Operator op = ((ArithmeticValueUpdate) adder .getUpdate()).getOperator(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertSame(operator.second, matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } } @SuppressWarnings("rawtypes") @Test public void testArrayIndexing() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'match': {", " 'element': 3,", " 'assign': 'nalle' }}}}")); Map<Number, String> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualarray"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final Number key = ((IntegerFieldValue) adder.getValue()) .getNumber(); String op = ((StringFieldValue) ((AssignValueUpdate) adder.getUpdate()) .getValue()).getString(); matches.put(key, op); } assertEquals(1, matches.size()); Number n = Integer.valueOf(3); assertEquals("nalle", matches.get(n)); } @Test public void testDocumentRemove() { JsonReader r = createReader(inputJson("{'remove': 'id:unittest:smoke::whee'}")); DocumentType docType = r.readDocumentType(new DocumentId("id:unittest:smoke::whee")); assertEquals("smoke", docType.getName()); } private Document docFromJson(String json) throws IOException { JsonReader r = createReader(json); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); return put.getDocument(); } @Test public void testWeightedSet() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'nalle': 2,", " 'tralle': 7 }}}")); FieldValue f = doc.getFieldValue(doc.getField("actualset")); assertSame(WeightedSet.class, f.getClass()); WeightedSet<?> w = (WeightedSet<?>) f; assertEquals(2, w.size()); assertEquals(Integer.valueOf(2), w.get(new StringFieldValue("nalle"))); assertEquals(Integer.valueOf(7), w.get(new StringFieldValue("tralle"))); } @Test public void testArray() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': [", " 'nalle',", " 'tralle' ]}}")); FieldValue f = doc.getFieldValue(doc.getField("actualarray")); assertSame(Array.class, f.getClass()); Array<?> a = (Array<?>) f; assertEquals(2, a.size()); assertEquals(new StringFieldValue("nalle"), a.get(0)); assertEquals(new StringFieldValue("tralle"), a.get(1)); } @Test public void testMap() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testmap::whee',", " 'fields': {", " 'actualmap': {", " 'nalle': 'kalle',", " 'tralle': 'skalle' }}}")); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testOldMap() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testmap::whee',", " 'fields': {", " 'actualmap': [", " { 'key': 'nalle', 'value': 'kalle'},", " { 'key': 'tralle', 'value': 'skalle'} ]}}")); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testPositionPositive() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': 'N63.429722;E10.393333' }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionOld() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': {'x':10393333,'y':63429722} }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testGeoPosition() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': {'lat':63.429722,'lng':10.393333} }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testGeoPositionNoAbbreviations() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': {'latitude':63.429722,'longitude':10.393333} }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionNegative() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': 'W46.63;S23.55' }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(-46630000, PositionDataType.getXValue(f).getInteger()); assertEquals(-23550000, PositionDataType.getYValue(f).getInteger()); } @Test public void testRaw() throws IOException { String base64 = new String(new JsonStringEncoder().quoteAsString( Base64.getEncoder().encodeToString(Utf8.toBytes("smoketest")))); String s = fieldStringFromBase64RawContent(base64); assertEquals("smoketest", s); } @Test public void can_read_legacy_chunked_base64_raw_field_encoding() throws IOException { String expected = "this is a string with an impressive length. it's long enough to reach the end of the line, wow!"; String base64withDelims = "dGhpcyBpcyBhIHN0cmluZyB3aXRoIGFuIGltcHJlc3NpdmUgbGVuZ3RoLiBpdCdzIGxvbmcgZW5v\\r\\n" + "dWdoIHRvIHJlYWNoIHRoZSBlbmQgb2YgdGhlIGxpbmUsIHdvdyE=\\r\\n"; assertEquals(expected, fieldStringFromBase64RawContent(base64withDelims)); } private String fieldStringFromBase64RawContent(String base64data) throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testraw::whee',", " 'fields': {", " 'actualraw': '" + base64data + "' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("actualraw")); assertSame(Raw.class, f.getClass()); Raw s = (Raw) f; return Utf8.toString(s.getByteBuffer()); } @Test public void testMapStringToArrayOfInt() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'bamse': [1, 2, 3] }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldMapStringToArrayOfInt() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': [", " { 'key': 'bamse', 'value': [1, 2, 3] } ]}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToString() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': {", " 'assign': 'orOther' }}}")); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); AssignValueUpdate a = (AssignValueUpdate) f.getValueUpdate(0); assertEquals(new StringFieldValue("orOther"), a.getValue()); } @Test public void testAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'assign': { 'bamse': [1, 2, 3] }}}}")); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'assign': [", " { 'key': 'bamse', 'value': [1, 2, 3] } ]}}}")); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToWeightedSet() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'assign': {", " 'person': 37,", " 'another person': 41 }}}}")); FieldUpdate x = doc.getFieldUpdate("actualset"); assertEquals(1, x.size()); AssignValueUpdate assign = (AssignValueUpdate) x.getValueUpdate(0); WeightedSet<?> w = (WeightedSet<?>) assign.getValue(); assertEquals(2, w.size()); assertEquals(Integer.valueOf(37), w.get(new StringFieldValue("person"))); assertEquals(Integer.valueOf(41), w.get(new StringFieldValue("another person"))); } @Test public void testCompleteFeed() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }},", "{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}},", "{ 'remove': 'id:unittest:smoke::whee' }]")); controlBasicFeed(r); } @Test public void testCompleteFeedWithCreateAndCondition() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }},", "{", " 'condition':'bla',", " 'update': 'id:unittest:testarray::whee',", " 'create':true,", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}},", "{ 'remove': 'id:unittest:smoke::whee' }]")); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testUpdateWithConditionAndCreateInDifferentOrdering() { int documentsCreated = 106; List<String> parts = Arrays.asList( "\"condition\":\"bla\"", "\"update\": \"id:unittest:testarray::whee\"", " \"fields\": { " + "\"actualarray\": { \"add\": [" + " \"person\",\"another person\"]}}", " \"create\":true"); Random random = new Random(42); StringBuilder documents = new StringBuilder("["); for (int x = 0; x < documentsCreated; x++) { Collections.shuffle(parts, random); documents.append("{").append(Joiner.on(",").join(parts)).append("}"); if (x < documentsCreated -1) { documents.append(","); } } documents.append("]"); InputStream rawDoc = new ByteArrayInputStream( Utf8.toBytes(documents.toString())); JsonReader r = new JsonReader(types, rawDoc, parserFactory); for (int x = 0; x < documentsCreated; x++) { DocumentUpdate update = (DocumentUpdate) r.next(); checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); } assertNull(r.next()); } @Test(expected=RuntimeException.class) public void testCreateIfNonExistentInPut() { JsonReader r = createReader(inputJson("[{", " 'create':true,", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse' },", " 'put': 'id:unittest:smoke::whee'", "}]")); r.next(); } @Test public void testCompleteFeedWithIdAfterFields() { JsonReader r = createReader(inputJson("[", "{", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' },", " 'put': 'id:unittest:smoke::whee'", "},", "{", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}},", " 'update': 'id:unittest:testarray::whee'", "},", "{ 'remove': 'id:unittest:smoke::whee' }]")); controlBasicFeed(r); } protected void controlBasicFeed(JsonReader r) { DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testCompleteFeedWithEmptyDoc() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee', 'fields': {} },", "{ 'update': 'id:unittest:testarray::whee', 'fields': {} },", "{ 'remove': 'id:unittest:smoke::whee' }]")); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); assertEquals("smoke", doc.getId().getDocType()); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; assertEquals("testarray", update.getId().getDocType()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } private void checkSimpleArrayAdd(DocumentUpdate update) { Set<String> toAdd = new HashSet<>(); FieldUpdate x = update.getFieldUpdate("actualarray"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; toAdd.add(((StringFieldValue) adder.getValue()).getString()); } assertEquals(2, toAdd.size()); assertTrue(toAdd.contains("person")); assertTrue(toAdd.contains("another person")); } private void smokeTestDoc(Document doc) { FieldValue boolField = doc.getFieldValue(doc.getField("flag")); assertSame(BoolFieldValue.class, boolField.getClass()); assertTrue((Boolean)boolField.getWrappedValue()); FieldValue stringField = doc.getFieldValue(doc.getField("nalle")); assertSame(StringFieldValue.class, stringField.getClass()); assertEquals("bamse", ((StringFieldValue) stringField).getString()); } @Test public void misspelledFieldTest() throws IOException{ JsonReader r = createReader(inputJson( "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'smething': 'smoketest',", " 'nalle': 'bamse' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); try { new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); fail(); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().startsWith("No field 'smething' in the structure of type 'smoke'")); } } @Test public void feedWithBasicErrorTest() { JsonReader r = createReader(inputJson("[", " { 'put': 'id:test:smoke::0', 'fields': { 'something': 'foo' } },", " { 'put': 'id:test:smoke::1', 'fields': { 'something': 'foo' } },", " { 'put': 'id:test:smoke::2', 'fields': { 'something': 'foo' } },", "]")); try { while (r.next() != null) ; fail(); } catch (RuntimeException e) { assertTrue(e.getMessage().contains("JsonParseException")); } } @Test public void idAsAliasForPutTest() throws IOException{ JsonReader r = createReader(inputJson("{ 'id': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } private void testFeedWithTestAndSetCondition(String jsonDoc) { ByteArrayInputStream parseInfoDoc = new ByteArrayInputStream(Utf8.toBytes(jsonDoc)); JsonReader reader = new JsonReader(types, parseInfoDoc, parserFactory); int NUM_OPERATIONS_IN_FEED = 3; for (int i = 0; i < NUM_OPERATIONS_IN_FEED; i++) { DocumentOperation operation = reader.next(); assertTrue("A test and set condition should be present", operation.getCondition().isPresent()); assertEquals("DocumentOperation's test and set condition should be equal to the one in the JSON feed", "smoke.something == \"smoketest\"", operation.getCondition().getSelection()); } assertNull(reader.next()); } @Test public void testFeedWithTestAndSetConditionOrderingOne() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'put': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " }", " },", " {", " 'update': 'id:unittest:testarray::whee',", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " },", " {", " 'remove': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\''", " }", "]" )); } @Test public void testFeedWithTestAndSetConditionOrderingTwo() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " }", " },", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " },", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'remove': 'id:unittest:smoke::whee'", " }", "]" )); } @Test public void testFeedWithTestAndSetConditionOrderingThree() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " },", " 'condition': 'smoke.something == \\'smoketest\\''", " },", " {", " 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " },", " 'condition': 'smoke.something == \\'smoketest\\''", " },", " {", " 'remove': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\''", " }", "]" )); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldAfterFieldsFieldShouldFailParse() { final String jsonData = inputJson( "[", " {", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " },", " 'bjarne': 'stroustrup'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldBeforeFieldsFieldShouldFailParse() { final String jsonData = inputJson( "[", " {", " 'update': 'id:unittest:testarray::whee',", " 'what is this': 'nothing to see here',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldWithoutFieldsFieldShouldFailParse() { String jsonData = inputJson( "[", " {", " 'remove': 'id:unittest:smoke::whee',", " 'what is love': 'baby, do not hurt me... much'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test public void testMissingOperation() { try { String jsonData = inputJson( "[", " {", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Missing a document operation ('put', 'update' or 'remove')", e.getMessage()); } } @Test public void testMissingFieldsMapInPut() { try { String jsonData = inputJson( "[", " {", " 'put': 'id:unittest:smoke::whee'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("put of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testMissingFieldsMapInUpdate() { try { String jsonData = inputJson( "[", " {", " 'update': 'id:unittest:smoke::whee'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("update of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testNullValues() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testnull::doc1',", " 'fields': {", " 'intfield': null,", " 'stringfield': null,", " 'arrayfield': null,", " 'weightedsetfield': null,", " 'mapfield': null,", " 'tensorfield': null", " }", "}")); DocumentPut put = (DocumentPut) r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:testnull::doc1"); Document doc = put.getDocument(); assertFieldValueNull(doc, "intfield"); assertFieldValueNull(doc, "stringfield"); assertFieldValueNull(doc, "arrayfield"); assertFieldValueNull(doc, "weightedsetfield"); assertFieldValueNull(doc, "mapfield"); assertFieldValueNull(doc, "tensorfield"); } @Test(expected=JsonReaderException.class) public void testNullArrayElement() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testnull::doc1',", " 'fields': {", " 'arrayfield': [ null ]", " }", "}")); r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:testnull::doc1"); fail(); } private void assertFieldValueNull(Document doc, String fieldName) { Field field = doc.getField(fieldName); assertNotNull(field); FieldValue fieldValue = doc.getFieldValue(field); assertNull(fieldValue); } static ByteArrayInputStream jsonToInputStream(String json) { return new ByteArrayInputStream(Utf8.toBytes(json)); } @Test public void testParsingWithoutTensorField() { Document doc = createPutWithoutTensor().getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals("id:unittest:testtensor::0", doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField("sparse_tensor")); assertNull(fieldValue); } @Test public void testParsingOfEmptyTensor() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor("{}")); } @Test public void testParsingOfTensorWithEmptyDimensions() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor(inputJson("{ 'dimensions': [] }"))); } @Test public void testParsingOfTensorWithEmptyCells() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor(inputJson("{ 'cells': [] }"))); } @Test public void testDisallowedDenseTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{ 'values': [] }"), "dense_tensor", "The 'values' array does not contain any values"); assertCreatePutFails(inputJson("{ 'values': '' }"), "dense_tensor", "The 'values' string does not contain any values"); } @Test public void testDisallowedMixedTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{\"blocks\":{ \"a\": [] } }"), "mixed_tensor", "Expected 3 values, but got 0"); assertCreatePutFails(inputJson("{\"blocks\":[ {\"address\":{\"x\":\"a\"}, \"values\": [] } ] }"), "mixed_tensor", "Expected 3 values, but got 0"); } @Test public void testParsingOfSparseTensorWithCells() { Tensor tensor = assertSparseTensorField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createPutWithSparseTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' },", " 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'b' },", " 'value': 3.0 }", " ]", "}"))); assertTrue(tensor instanceof MappedTensor); // any functional instance is fine } @Test public void testParsingOfDenseTensorWithCells() { Tensor tensor = assertTensorField("{{x:0,y:0}:2.0,{x:1,y:0}:3.0}}", createPutWithTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' },", " 'value': 2.0 },", " { 'address': { 'x': '1', 'y': '0' },", " 'value': 3.0 }", " ]", "}"), "dense_unbound_tensor"), "dense_unbound_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorOnDenseForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson("{", " 'values': [2.0, 3.0, 4.0, 5.0, 6.0, 7.0]", "}"), "dense_tensor"), "dense_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<int8>(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson("{", " 'values': \"020304050607\"", "}"), "dense_int8_tensor"), "dense_int8_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfMixedTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")); builder.cell().label("x", "foo").label("y", 0).value(2.0); builder.cell().label("x", "foo").label("y", 1).value(3.0); builder.cell().label("x", "foo").label("y", 2).value(4.0); builder.cell().label("x", "bar").label("y", 0).value(5.0); builder.cell().label("x", "bar").label("y", 1).value(6.0); builder.cell().label("x", "bar").label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":[" + "{\"address\":{\"x\":\"foo\"},\"values\":\"400040404080\"}," + "{\"address\":{\"x\":\"bar\"},\"values\":\"40A040C040E0\"}" + "]}"; var put = createPutWithTensor(inputJson(mixedJson), "mixed_bfloat16_tensor"); Tensor tensor = assertTensorField(expected, put, "mixed_bfloat16_tensor"); } @Test public void testParsingOfMixedTensorOnMixedForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":[" + "{\"address\":{\"x\":\"0\"},\"values\":[2.0,3.0,4.0]}," + "{\"address\":{\"x\":\"1\"},\"values\":[5.0,6.0,7.0]}" + "]}"; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance } @Test public void testMixedTensorInMixedFormWithSingleSparseDimensionShortForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":{" + "\"0\":[2.0,3.0,4.0]," + "\"1\":[5.0,6.0,7.0]" + "}}"; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance } @Test public void testParsingOfTensorWithSingleCellInDifferentJsonOrder() { assertSparseTensorField("{{x:a,y:b}:2.0}", createPutWithSparseTensor(inputJson("{", " 'cells': [", " { 'value': 2.0,", " 'address': { 'x': 'a', 'y': 'b' } }", " ]", "}"))); } @Test public void testAssignUpdateOfEmptySparseTensor() { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithSparseTensor("{}")); } @Test public void testAssignUpdateOfEmptyDenseTensor() { try { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithTensor("{}", "dense_unbound_tensor")); } catch (IllegalArgumentException e) { assertEquals("An indexed tensor must have a value", "Error in 'dense_unbound_tensor': Tensor of type tensor(x[],y[]) has no values", Exceptions.toMessageString(e)); } } @Test public void testAssignUpdateOfNullTensor() { ClearValueUpdate clearUpdate = (ClearValueUpdate) getTensorField(createAssignUpdateWithSparseTensor(null)).getValueUpdate(0); assertTrue(clearUpdate != null); assertTrue(clearUpdate.getValue() == null); } @Test public void testAssignUpdateOfTensorWithCells() { assertTensorAssignUpdateSparseField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createAssignUpdateWithSparseTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' },", " 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'b' },", " 'value': 3.0 }", " ]", "}"))); } @Test public void testAssignUpdateOfTensorDenseShortForm() { assertTensorAssignUpdateDenseField("tensor(x[2],y[3]):[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]", createAssignUpdateWithTensor(inputJson("{", " 'values': [1,2,3,4,5,6]", "}"), "dense_tensor")); } @Test public void tensor_modify_update_with_replace_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_add_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, "sparse_tensor", inputJson("{", " 'operation': 'add',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_multiply_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "sparse_tensor", inputJson("{", " 'operation': 'multiply',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_treats_the_input_tensor_as_sparse() { // Note that the type of the tensor in the modify update is sparse (it only has mapped dimensions). assertTensorModifyUpdate("tensor(x{},y{}):{{x:0,y:0}:2.0, {x:1,y:2}:3.0}", TensorModifyUpdate.Operation.REPLACE, "dense_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' }, 'value': 2.0 },", " { 'address': { 'x': '1', 'y': '2' }, 'value': 3.0 } ]}")); } @Test public void tensor_modify_update_on_non_tensor_field_throws() { try { JsonReader reader = createReader(inputJson("{ 'update': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': {", " 'modify': {} }}}")); reader.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::doc1"); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Error in 'something': A modify update can only be applied to tensor fields. Field 'something' is of type 'string'", Exceptions.toMessageString(e)); } } @Test public void tensor_modify_update_on_dense_unbound_tensor_throws() { illegalTensorModifyUpdate("Error in 'dense_unbound_tensor': A modify update cannot be applied to tensor types with indexed unbound dimensions. Field 'dense_unbound_tensor' has unsupported tensor type 'tensor(x[],y[])'", "dense_unbound_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorModifyUpdate("{{x:a}:2.0, {x:c}: 3.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_single_dimension_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': {", " 'a': 2.0,", " 'c': 3.0 }}")); } @Test public void tensor_modify_update_with_replace_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_array() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': [", " { 'address': { 'x': 'a' }, 'values': [1,2,3] } ]}")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_must_specify_full_subspace() { illegalTensorModifyUpdate("Error in 'mixed_tensor': At {x:a}: Expected 3 values, but got 2", "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': {", " 'a': [2,3] } }")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_map() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': {", " 'a': [1,2,3] } }")); } @Test public void tensor_modify_update_with_add_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.ADD, "mixed_tensor", inputJson("{", " 'operation': 'add',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_multiply_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "mixed_tensor", inputJson("{", " 'operation': 'multiply',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws() { illegalTensorModifyUpdate("Error in 'dense_tensor': Dimension 'y' has label '3' but type is tensor(x[2],y[3])", "dense_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws_mixed() { illegalTensorModifyUpdate("Error in 'mixed_tensor': Dimension 'y' has label '3' but type is tensor(x{},y[3])", "mixed_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_with_unknown_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown operation 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", "{", " 'operation': 'unknown',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_without_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain an operation", "sparse_tensor", "{", " 'cells': [] }"); } @Test public void tensor_modify_update_without_cells_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", "{", " 'operation': 'replace' }"); } @Test public void tensor_modify_update_with_unknown_content_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown JSON string 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", "{", " 'unknown': 'here' }"); } @Test public void tensor_add_update_on_sparse_tensor() { assertTensorAddUpdate("{{x:a,y:b}:2.0, {x:c,y:d}: 3.0}", "sparse_tensor", inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'd' }, 'value': 3.0 } ]}")); } @Test public void tensor_add_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorAddUpdate("{{x:a}:2.0, {x:c}: 3.0}", "sparse_single_dimension_tensor", inputJson("{", " 'cells': {", " 'a': 2.0,", " 'c': 3.0 }}")); } @Test public void tensor_add_update_on_mixed_tensor() { assertTensorAddUpdate("{{x:a,y:0}:2.0, {x:a,y:1}:3.0, {x:a,y:2}:0.0}", "mixed_tensor", inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 },", " { 'address': { 'x': 'a', 'y': '1' }, 'value': 3.0 } ]}")); } @Test public void tensor_add_update_on_mixed_with_out_of_bound_dense_cells_throws() { illegalTensorAddUpdate("Error in 'mixed_tensor': Index 3 out of bounds for length 3", "mixed_tensor", "{", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_add_update_on_dense_tensor_throws() { illegalTensorAddUpdate("Error in 'dense_tensor': An add update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", "{", " 'cells': [] }"); } @Test public void tensor_add_update_on_not_fully_specified_cell_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Missing a label for dimension y for tensor(x{},y{})", "sparse_tensor", "{", " 'cells': [", " { 'address': { 'x': 'a' }, 'value': 2.0 } ]}"); } @Test public void tensor_add_update_without_cells_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Add update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", "{}"); illegalTensorAddUpdate("Error in 'mixed_tensor': Add update for field 'mixed_tensor' does not contain tensor cells", "mixed_tensor", "{}"); } @Test public void tensor_remove_update_on_sparse_tensor() { assertTensorRemoveUpdate("{{x:a,y:b}:1.0,{x:c,y:d}:1.0}", "sparse_tensor", inputJson("{", " 'addresses': [", " { 'x': 'a', 'y': 'b' },", " { 'x': 'c', 'y': 'd' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor() { assertTensorRemoveUpdate("{{x:1}:1.0,{x:2}:1.0}", "mixed_tensor", inputJson("{", " 'addresses': [", " { 'x': '1' },", " { 'x': '2' } ]}")); } @Test public void tensor_remove_update_on_sparse_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{y:b}:1.0,{y:d}:1.0}", "sparse_tensor", inputJson("{", " 'addresses': [", " { 'y': 'b' },", " { 'y': 'd' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{x:1,z:a}:1.0,{x:2,z:b}:1.0}", "mixed_tensor_adv", inputJson("{", " 'addresses': [", " { 'x': '1', 'z': 'a' },", " { 'x': '2', 'z': 'b' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor_with_dense_addresses_throws() { illegalTensorRemoveUpdate("Error in 'mixed_tensor': Indexed dimension address 'y' should not be specified in remove update", "mixed_tensor", "{", " 'addresses': [", " { 'x': '1', 'y': '0' },", " { 'x': '2', 'y': '0' } ]}"); } @Test public void tensor_remove_update_on_dense_tensor_throws() { illegalTensorRemoveUpdate("Error in 'dense_tensor': A remove update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", "{", " 'addresses': [] }"); } @Test public void tensor_remove_update_with_stray_dimension_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{},y{}) does not contain dimension 'foo'", "sparse_tensor", "{", " 'addresses': [", " { 'x': 'a', 'foo': 'b' } ]}"); illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{}) does not contain dimension 'foo'", "sparse_tensor", "{", " 'addresses': [", " { 'x': 'c' },", " { 'x': 'a', 'foo': 'b' } ]}"); } @Test public void tensor_remove_update_without_cells_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': Remove update for field 'sparse_tensor' does not contain tensor addresses", "sparse_tensor", "{'addresses': [] }"); illegalTensorRemoveUpdate("Error in 'mixed_tensor': Remove update for field 'mixed_tensor' does not contain tensor addresses", "mixed_tensor", "{'addresses': [] }"); } @Test public void require_that_parser_propagates_datatype_parser_errors_predicate() { assertParserErrorMatches( "Error in document 'id:unittest:testpredicate::0' - could not parse field 'boolean' of type 'predicate': " + "line 1:10 no viable alternative at character '>'", "[", " {", " 'fields': {", " 'boolean': 'timestamp > 9000'", " },", " 'put': 'id:unittest:testpredicate::0'", " }", "]" ); } @Test public void require_that_parser_propagates_datatype_parser_errors_string_as_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \" 1\"", "[", " {", " 'fields': {", " 'integerfield': ' 1'", " },", " 'put': 'id:unittest:testint::0'", " }", "]" ); } @Test public void require_that_parser_propagates_datatype_parser_errors_overflowing_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \"281474976710656\"", "[", " {", " 'fields': {", " 'integerfield': 281474976710656", " },", " 'put': 'id:unittest:testint::0'", " }", "]" ); } @Test public void requireThatUnknownDocTypeThrowsIllegalArgumentException() { final String jsonData = inputJson( "[", " {", " 'put': 'id:ns:walrus::walrus1',", " 'fields': {", " 'aField': 42", " }", " }", "]"); try { new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail(); } catch (IllegalArgumentException e) { assertEquals("Document type walrus does not exist", e.getMessage()); } } private static final String TENSOR_DOC_ID = "id:unittest:testtensor::0"; private void illegalTensorModifyUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorModifyUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorAddUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorAddUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorRemoveUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorRemoveUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private DocumentPut createPutWithoutTensor() { JsonReader reader = createReader(inputJson("[ { 'put': '" + TENSOR_DOC_ID + "', 'fields': { } } ]")); return (DocumentPut) reader.next(); } private DocumentPut createPutWithSparseTensor(String inputTensor) { return createPutWithTensor(inputTensor, "sparse_tensor"); } private DocumentPut createPutWithTensor(String inputTensor, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'put': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': " + inputTensor + " }}]")); return (DocumentPut) reader.next(); } private DocumentUpdate createAssignUpdateWithSparseTensor(String inputTensor) { return createAssignUpdateWithTensor(inputTensor, "sparse_tensor"); } private DocumentUpdate createAssignUpdateWithTensor(String inputTensor, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'update': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': {", " 'assign': " + (inputTensor != null ? inputTensor : "null") + " } } } ]")); return (DocumentUpdate) reader.next(); } private static Tensor assertSparseTensorField(String expectedTensor, DocumentPut put) { return assertTensorField(expectedTensor, put, "sparse_tensor"); } private static Tensor assertTensorField(String expectedTensor, DocumentPut put, String tensorFieldName) { return assertTensorField(Tensor.from(expectedTensor), put, tensorFieldName); } private static Tensor assertTensorField(Tensor expectedTensor, DocumentPut put, String tensorFieldName) { Document doc = put.getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals(TENSOR_DOC_ID, doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField(tensorFieldName)); assertEquals(expectedTensor, fieldValue.getTensor().get()); return fieldValue.getTensor().get(); } private static void assertTensorFieldUpdate(DocumentUpdate update, String tensorFieldName) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); assertEquals(1, update.fieldUpdates().size()); assertEquals(1, update.getFieldUpdate(tensorFieldName).size()); } private static void assertTensorAssignUpdateSparseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "sparse_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private static void assertTensorAssignUpdateDenseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "dense_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, String tensorFieldName, String modifyJson) { assertTensorModifyUpdate(expectedTensor, expectedOperation, tensorFieldName, createTensorModifyUpdate(modifyJson, tensorFieldName)); } private static void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorModifyUpdate modifyUpdate = (TensorModifyUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(expectedOperation, modifyUpdate.getOperation()); assertEquals(Tensor.from(expectedTensor), modifyUpdate.getValue().getTensor().get()); } private DocumentUpdate createTensorModifyUpdate(String modifyJson, String tensorFieldName) { return createTensorUpdate("modify", modifyJson, tensorFieldName); } private DocumentUpdate createTensorAddUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("add", tensorJson, tensorFieldName); } private DocumentUpdate createTensorRemoveUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("remove", tensorJson, tensorFieldName); } private DocumentUpdate createTensorUpdate(String operation, String tensorJson, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'update': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': {", " '" + operation + "': " + tensorJson + " }}}]")); return (DocumentUpdate) reader.next(); } private void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorAddUpdate(expectedTensor, tensorFieldName, createTensorAddUpdate(tensorJson, tensorFieldName)); } private static void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorAddUpdate addUpdate = (TensorAddUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), addUpdate.getValue().getTensor().get()); } private void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorRemoveUpdate(expectedTensor, tensorFieldName, createTensorRemoveUpdate(tensorJson, tensorFieldName)); } private static void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorRemoveUpdate removeUpdate = (TensorRemoveUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), removeUpdate.getValue().getTensor().get()); } private static FieldUpdate getTensorField(DocumentUpdate update) { return getTensorField(update, "sparse_tensor"); } private static FieldUpdate getTensorField(DocumentUpdate update, String fieldName) { FieldUpdate fieldUpdate = update.getFieldUpdate(fieldName); assertEquals(1, fieldUpdate.size()); return fieldUpdate; } // NOTE: Do not call this method multiple times from a test method as it's using the ExpectedException rule private void assertParserErrorMatches(String expectedError, String... json) { String jsonData = inputJson(json); try { new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail(); } catch (JsonReaderException e) { assertEquals(expectedError, e.getMessage()); } } private void assertCreatePutFails(String tensor, String name, String msg) { try { createPutWithTensor(inputJson(tensor), name); fail("Expected exception"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains(msg)); } } }
Jeetjyoti-Deka/vespa
document/src/test/java/com/yahoo/document/json/JsonReaderTestCase.java
213,288
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.document.json; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.io.JsonStringEncoder; import com.google.common.base.Joiner; import com.yahoo.collections.Tuple2; import com.yahoo.document.ArrayDataType; import com.yahoo.document.DataType; import com.yahoo.document.Document; import com.yahoo.document.DocumentId; import com.yahoo.document.DocumentOperation; import com.yahoo.document.DocumentPut; import com.yahoo.document.DocumentRemove; import com.yahoo.document.DocumentType; import com.yahoo.document.DocumentTypeManager; import com.yahoo.document.DocumentUpdate; import com.yahoo.document.Field; import com.yahoo.document.MapDataType; import com.yahoo.document.PositionDataType; import com.yahoo.document.StructDataType; import com.yahoo.document.TensorDataType; import com.yahoo.document.WeightedSetDataType; import com.yahoo.document.datatypes.Array; import com.yahoo.document.datatypes.BoolFieldValue; import com.yahoo.document.datatypes.FieldValue; import com.yahoo.document.datatypes.IntegerFieldValue; import com.yahoo.document.datatypes.MapFieldValue; import com.yahoo.document.datatypes.Raw; import com.yahoo.document.datatypes.StringFieldValue; import com.yahoo.document.datatypes.Struct; import com.yahoo.document.datatypes.TensorFieldValue; import com.yahoo.document.datatypes.WeightedSet; import com.yahoo.document.internal.GeoPosType; import com.yahoo.document.json.readers.DocumentParseInfo; import com.yahoo.document.json.readers.VespaJsonDocumentReader; import com.yahoo.document.serialization.DocumentSerializer; import com.yahoo.document.serialization.DocumentSerializerFactory; import com.yahoo.document.update.AddValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate.Operator; import com.yahoo.document.update.AssignValueUpdate; import com.yahoo.document.update.ClearValueUpdate; import com.yahoo.document.update.FieldUpdate; import com.yahoo.document.update.MapValueUpdate; import com.yahoo.document.update.TensorAddUpdate; import com.yahoo.document.update.TensorModifyUpdate; import com.yahoo.document.update.TensorRemoveUpdate; import com.yahoo.document.update.ValueUpdate; import com.yahoo.io.GrowableByteBuffer; import com.yahoo.tensor.IndexedTensor; import com.yahoo.tensor.MappedTensor; import com.yahoo.tensor.MixedTensor; import com.yahoo.tensor.Tensor; import com.yahoo.tensor.TensorType; import com.yahoo.text.Utf8; import com.yahoo.yolean.Exceptions; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DECREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DIVIDE; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_INCREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_MULTIPLY; import static com.yahoo.test.json.JsonTestHelper.inputJson; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Basic test of JSON streams to Vespa document instances. * * @author Steinar Knutsen * @author bratseth */ public class JsonReaderTestCase { private DocumentTypeManager types; private JsonFactory parserFactory; @Before public void setUp() throws Exception { parserFactory = new JsonFactory(); types = new DocumentTypeManager(); { DocumentType x = new DocumentType("smoke"); x.addField(new Field("something", DataType.STRING)); x.addField(new Field("nalle", DataType.STRING)); x.addField(new Field("field1", DataType.STRING)); x.addField(new Field("field2", DataType.STRING)); x.addField(new Field("int1", DataType.INT)); x.addField(new Field("flag", DataType.BOOL)); x.addField(new Field("tensor1", DataType.getTensor(TensorType.fromSpec("tensor(x{})")))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("mirrors"); StructDataType woo = new StructDataType("woo"); woo.addField(new Field("sandra", DataType.STRING)); woo.addField(new Field("cloud", DataType.STRING)); x.addField(new Field("skuggsjaa", woo)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testarray"); DataType d = new ArrayDataType(DataType.STRING); x.addField(new Field("actualarray", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testset"); DataType d = new WeightedSetDataType(DataType.STRING, true, true); x.addField(new Field("actualset", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testmap"); DataType d = new MapDataType(DataType.STRING, DataType.STRING); x.addField(new Field("actualmap", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testraw"); DataType d = DataType.RAW; x.addField(new Field("actualraw", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testMapStringToArrayOfInt"); DataType value = new ArrayDataType(DataType.INT); DataType d = new MapDataType(DataType.STRING, value); x.addField(new Field("actualMapStringToArrayOfInt", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testsinglepos"); DataType d = PositionDataType.INSTANCE; x.addField(new Field("singlepos", d)); x.addField(new Field("geopos", new GeoPosType(8))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testtensor"); x.addField(new Field("sparse_single_dimension_tensor", new TensorDataType(new TensorType.Builder().mapped("x").build()))); x.addField(new Field("sparse_tensor", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").build()))); x.addField(new Field("dense_tensor", new TensorDataType(new TensorType.Builder().indexed("x", 2).indexed("y", 3).build()))); x.addField(new Field("dense_int8_tensor", new TensorDataType(TensorType.fromSpec("tensor<int8>(x[2],y[3])")))); x.addField(new Field("dense_unbound_tensor", new TensorDataType(new TensorType.Builder().indexed("x").indexed("y").build()))); x.addField(new Field("mixed_tensor", new TensorDataType(new TensorType.Builder().mapped("x").indexed("y", 3).build()))); x.addField(new Field("mixed_bfloat16_tensor", new TensorDataType(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")))); x.addField(new Field("mixed_tensor_adv", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").mapped("z").indexed("a", 3).build()))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testpredicate"); x.addField(new Field("boolean", DataType.PREDICATE)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testint"); x.addField(new Field("integerfield", DataType.INT)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testnull"); x.addField(new Field("intfield", DataType.INT)); x.addField(new Field("stringfield", DataType.STRING)); x.addField(new Field("arrayfield", new ArrayDataType(DataType.STRING))); x.addField(new Field("weightedsetfield", new WeightedSetDataType(DataType.STRING, true, true))); x.addField(new Field("mapfield", new MapDataType(DataType.STRING, DataType.STRING))); x.addField(new Field("tensorfield", new TensorDataType(new TensorType.Builder().indexed("x").build()))); types.registerDocumentType(x); } } @After public void tearDown() throws Exception { types = null; parserFactory = null; } private JsonReader createReader(String jsonInput) { InputStream input = new ByteArrayInputStream(Utf8.toBytes(jsonInput)); return new JsonReader(types, input, parserFactory); } @Test public void readSingleDocumentPut() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " }", "}")); DocumentPut put = (DocumentPut) r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:smoke::doc1").operation(); smokeTestDoc(put.getDocument()); } @Test public final void readSingleDocumentUpdate() { JsonReader r = createReader(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': {", " 'assign': 'orOther' }}}")); DocumentUpdate doc = (DocumentUpdate) r.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::whee").operation(); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof AssignValueUpdate); } @Test public void readClearField() { JsonReader r = createReader(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'int1': {", " 'assign': null }}}")); DocumentUpdate doc = (DocumentUpdate) r.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::whee").operation(); FieldUpdate f = doc.getFieldUpdate("int1"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof ClearValueUpdate); assertNull(f.getValueUpdate(0).getValue()); } @Test public void smokeTest() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } @Test public void docIdLookaheadTest() throws IOException { JsonReader r = createReader(inputJson( "{ 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " },", " 'put': 'id:unittest:smoke::doc1'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } @Test public void emptyDocTest() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::whee', 'fields': {}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); assertEquals("id:unittest:smoke::whee", parseInfo.documentId.toString()); } @Test public void testStruct() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:mirrors::whee',", " 'fields': {", " 'skuggsjaa': {", " 'sandra': 'person',", " 'cloud': 'another person' }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("skuggsjaa")); assertSame(Struct.class, f.getClass()); Struct s = (Struct) f; assertEquals("person", ((StringFieldValue) s.getFieldValue("sandra")).getString()); } private DocumentUpdate parseUpdate(String json) throws IOException { InputStream rawDoc = new ByteArrayInputStream(Utf8.toBytes(json)); JsonReader r = new JsonReader(types, rawDoc, parserFactory); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentUpdate update = new DocumentUpdate(docType, parseInfo.documentId); new VespaJsonDocumentReader(false).readUpdate(parseInfo.fieldsBuffer, update); return update; } @Test public void testStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(inputJson("{ 'update': 'id:unittest:mirrors:g=test:whee',", " 'create': true,", " 'fields': {", " 'skuggsjaa': {", " 'assign': {", " 'sandra': 'person',", " 'cloud': 'another person' }}}}")); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(2, s.getFieldCount()); assertEquals(new StringFieldValue("person"), s.getFieldValue(s.getField("sandra"))); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(107, buf.position()); } @Test public final void testEmptyStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(inputJson("{ 'update': 'id:unittest:mirrors:g=test:whee',", " 'create': true,", " 'fields': { ", " 'skuggsjaa': {", " 'assign': { } }}}")); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(0, s.getFieldCount()); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(69, buf.position()); } @Test public void testUpdateArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}}")); checkSimpleArrayAdd(doc); } @Test public void testUpdateWeighted() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'add': {", " 'person': 37,", " 'another person': 41 }}}}")); Map<String, Integer> weights = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; final String s = ((StringFieldValue) adder.getValue()).getString(); weights.put(s, adder.getWeight()); } assertEquals(2, weights.size()); final String o = "person"; final String o2 = "another person"; assertTrue(weights.containsKey(o)); assertTrue(weights.containsKey(o2)); assertEquals(Integer.valueOf(37), weights.get(o)); assertEquals(Integer.valueOf(41), weights.get(o2)); } @Test public void testUpdateMatch() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'match': {", " 'element': 'person',", " 'increment': 13 }}}}")); Map<String, Tuple2<Number, String>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); String op = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperator().toString(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()).getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertEquals("ADD", matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } @SuppressWarnings({ "cast", "unchecked", "rawtypes" }) @Test public void testArithmeticOperators() throws IOException { Tuple2[] operations = new Tuple2[] { new Tuple2<String, Operator>(UPDATE_DECREMENT, ArithmeticValueUpdate.Operator.SUB), new Tuple2<String, Operator>(UPDATE_DIVIDE, ArithmeticValueUpdate.Operator.DIV), new Tuple2<String, Operator>(UPDATE_INCREMENT, ArithmeticValueUpdate.Operator.ADD), new Tuple2<String, Operator>(UPDATE_MULTIPLY, ArithmeticValueUpdate.Operator.MUL) }; for (Tuple2<String, Operator> operator : operations) { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'match': {", " 'element': 'person',", " '" + (String) operator.first + "': 13 }}}}")); Map<String, Tuple2<Number, Operator>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); Operator op = ((ArithmeticValueUpdate) adder .getUpdate()).getOperator(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertSame(operator.second, matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } } @SuppressWarnings("rawtypes") @Test public void testArrayIndexing() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'match': {", " 'element': 3,", " 'assign': 'nalle' }}}}")); Map<Number, String> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualarray"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final Number key = ((IntegerFieldValue) adder.getValue()) .getNumber(); String op = ((StringFieldValue) ((AssignValueUpdate) adder.getUpdate()) .getValue()).getString(); matches.put(key, op); } assertEquals(1, matches.size()); Number n = Integer.valueOf(3); assertEquals("nalle", matches.get(n)); } @Test public void testDocumentRemove() { JsonReader r = createReader(inputJson("{'remove': 'id:unittest:smoke::whee'}")); DocumentType docType = r.readDocumentType(new DocumentId("id:unittest:smoke::whee")); assertEquals("smoke", docType.getName()); } private Document docFromJson(String json) throws IOException { JsonReader r = createReader(json); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); return put.getDocument(); } @Test public void testWeightedSet() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'nalle': 2,", " 'tralle': 7 }}}")); FieldValue f = doc.getFieldValue(doc.getField("actualset")); assertSame(WeightedSet.class, f.getClass()); WeightedSet<?> w = (WeightedSet<?>) f; assertEquals(2, w.size()); assertEquals(Integer.valueOf(2), w.get(new StringFieldValue("nalle"))); assertEquals(Integer.valueOf(7), w.get(new StringFieldValue("tralle"))); } @Test public void testArray() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': [", " 'nalle',", " 'tralle' ]}}")); FieldValue f = doc.getFieldValue(doc.getField("actualarray")); assertSame(Array.class, f.getClass()); Array<?> a = (Array<?>) f; assertEquals(2, a.size()); assertEquals(new StringFieldValue("nalle"), a.get(0)); assertEquals(new StringFieldValue("tralle"), a.get(1)); } @Test public void testMap() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testmap::whee',", " 'fields': {", " 'actualmap': {", " 'nalle': 'kalle',", " 'tralle': 'skalle' }}}")); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testOldMap() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testmap::whee',", " 'fields': {", " 'actualmap': [", " { 'key': 'nalle', 'value': 'kalle'},", " { 'key': 'tralle', 'value': 'skalle'} ]}}")); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testPositionPositive() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': 'N63.429722;E10.393333' }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionOld() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': {'x':10393333,'y':63429722} }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testGeoPosition() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': {'lat':63.429722,'lng':10.393333} }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testGeoPositionNoAbbreviations() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': {'latitude':63.429722,'longitude':10.393333} }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionGeoPos() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'geopos': 'N63.429722;E10.393333' }}")); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); } @Test public void testPositionOldGeoPos() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'geopos': {'x':10393333,'y':63429722} }}")); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); } @Test public void testGeoPositionGeoPos() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'geopos': {'lat':63.429722,'lng':10.393333} }}")); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); assertEquals(PositionDataType.INSTANCE, f.getDataType()); } @Test public void testPositionNegative() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': 'W46.63;S23.55' }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(-46630000, PositionDataType.getXValue(f).getInteger()); assertEquals(-23550000, PositionDataType.getYValue(f).getInteger()); } @Test public void testRaw() throws IOException { String base64 = new String(new JsonStringEncoder().quoteAsString( Base64.getEncoder().withoutPadding().encodeToString(Utf8.toBytes("smoketest")))); String s = fieldStringFromBase64RawContent(base64); assertEquals("smoketest", s); } @Test public void can_read_legacy_chunked_base64_raw_field_encoding() throws IOException { String expected = "this is a string with an impressive length. it's long enough to reach the end of the line, wow!"; String base64withDelims = "dGhpcyBpcyBhIHN0cmluZyB3aXRoIGFuIGltcHJlc3NpdmUgbGVuZ3RoLiBpdCdzIGxvbmcgZW5v\\r\\n" + "dWdoIHRvIHJlYWNoIHRoZSBlbmQgb2YgdGhlIGxpbmUsIHdvdyE=\\r\\n"; assertEquals(expected, fieldStringFromBase64RawContent(base64withDelims)); } private String fieldStringFromBase64RawContent(String base64data) throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testraw::whee',", " 'fields': {", " 'actualraw': '" + base64data + "' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("actualraw")); assertSame(Raw.class, f.getClass()); Raw s = (Raw) f; return Utf8.toString(s.getByteBuffer()); } @Test public void testMapStringToArrayOfInt() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'bamse': [1, 2, 3] }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldMapStringToArrayOfInt() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': [", " { 'key': 'bamse', 'value': [1, 2, 3] } ]}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToString() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': {", " 'assign': 'orOther' }}}")); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); AssignValueUpdate a = (AssignValueUpdate) f.getValueUpdate(0); assertEquals(new StringFieldValue("orOther"), a.getValue()); } @Test public void testAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'assign': { 'bamse': [1, 2, 3] }}}}")); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'assign': [", " { 'key': 'bamse', 'value': [1, 2, 3] } ]}}}")); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToWeightedSet() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'assign': {", " 'person': 37,", " 'another person': 41 }}}}")); FieldUpdate x = doc.getFieldUpdate("actualset"); assertEquals(1, x.size()); AssignValueUpdate assign = (AssignValueUpdate) x.getValueUpdate(0); WeightedSet<?> w = (WeightedSet<?>) assign.getValue(); assertEquals(2, w.size()); assertEquals(Integer.valueOf(37), w.get(new StringFieldValue("person"))); assertEquals(Integer.valueOf(41), w.get(new StringFieldValue("another person"))); } @Test public void testCompleteFeed() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }},", "{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}},", "{ 'remove': 'id:unittest:smoke::whee' }]")); controlBasicFeed(r); } @Test public void testCompleteFeedWithCreateAndCondition() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }},", "{", " 'condition':'bla',", " 'update': 'id:unittest:testarray::whee',", " 'create':true,", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}},", "{ 'remove': 'id:unittest:smoke::whee' }]")); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testUpdateWithConditionAndCreateInDifferentOrdering() { int documentsCreated = 106; List<String> parts = Arrays.asList( "\"condition\":\"bla\"", "\"update\": \"id:unittest:testarray::whee\"", " \"fields\": { " + "\"actualarray\": { \"add\": [" + " \"person\",\"another person\"]}}", " \"create\":true"); Random random = new Random(42); StringBuilder documents = new StringBuilder("["); for (int x = 0; x < documentsCreated; x++) { Collections.shuffle(parts, random); documents.append("{").append(Joiner.on(",").join(parts)).append("}"); if (x < documentsCreated -1) { documents.append(","); } } documents.append("]"); InputStream rawDoc = new ByteArrayInputStream( Utf8.toBytes(documents.toString())); JsonReader r = new JsonReader(types, rawDoc, parserFactory); for (int x = 0; x < documentsCreated; x++) { DocumentUpdate update = (DocumentUpdate) r.next(); checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); } assertNull(r.next()); } @Test public void testCreateIfNonExistentInPut() { JsonReader r = createReader(inputJson("[{", " 'create':true,", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse' },", " 'put': 'id:unittest:smoke::whee'", "}]")); var op = r.next(); var put = (DocumentPut) op; assertTrue(put.getCreateIfNonExistent()); } @Test public void testCompleteFeedWithIdAfterFields() { JsonReader r = createReader(inputJson("[", "{", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' },", " 'put': 'id:unittest:smoke::whee'", "},", "{", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}},", " 'update': 'id:unittest:testarray::whee'", "},", "{ 'remove': 'id:unittest:smoke::whee' }]")); controlBasicFeed(r); } protected void controlBasicFeed(JsonReader r) { DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testCompleteFeedWithEmptyDoc() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee', 'fields': {} },", "{ 'update': 'id:unittest:testarray::whee', 'fields': {} },", "{ 'remove': 'id:unittest:smoke::whee' }]")); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); assertEquals("smoke", doc.getId().getDocType()); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; assertEquals("testarray", update.getId().getDocType()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } private void checkSimpleArrayAdd(DocumentUpdate update) { Set<String> toAdd = new HashSet<>(); FieldUpdate x = update.getFieldUpdate("actualarray"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; toAdd.add(((StringFieldValue) adder.getValue()).getString()); } assertEquals(2, toAdd.size()); assertTrue(toAdd.contains("person")); assertTrue(toAdd.contains("another person")); } private void smokeTestDoc(Document doc) { FieldValue boolField = doc.getFieldValue(doc.getField("flag")); assertSame(BoolFieldValue.class, boolField.getClass()); assertTrue((Boolean)boolField.getWrappedValue()); FieldValue stringField = doc.getFieldValue(doc.getField("nalle")); assertSame(StringFieldValue.class, stringField.getClass()); assertEquals("bamse", ((StringFieldValue) stringField).getString()); } @Test public void nonExistingFieldCausesException() throws IOException { JsonReader r = createReader(inputJson( "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'smething': 'smoketest',", " 'nalle': 'bamse' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); try { new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); fail(); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().startsWith("No field 'smething' in the structure of type 'smoke'")); } } @Test public void nonExistingFieldsCanBeIgnoredInPut() throws IOException { JsonReader r = createReader(inputJson( "{ ", " 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'nonexisting1': 'ignored value',", " 'field1': 'value1',", " 'nonexisting2': {", " 'blocks':{", " 'a':[2.0,3.0],", " 'b':[4.0,5.0]", " }", " },", " 'field2': 'value2',", " 'nonexisting3': {", " 'cells': [{'address': {'x': 'x1'}, 'value': 1.0}]", " },", " 'tensor1': {'cells': {'x1': 1.0}},", " 'nonexisting4': 'ignored value'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); boolean fullyApplied = new VespaJsonDocumentReader(true).readPut(parseInfo.fieldsBuffer, put); assertFalse(fullyApplied); assertNull(put.getDocument().getField("nonexisting1")); assertEquals("value1", put.getDocument().getFieldValue("field1").toString()); assertNull(put.getDocument().getField("nonexisting2")); assertEquals("value2", put.getDocument().getFieldValue("field2").toString()); assertNull(put.getDocument().getField("nonexisting3")); assertEquals(Tensor.from("tensor(x{}):{{x:x1}:1.0}"), put.getDocument().getFieldValue("tensor1").getWrappedValue()); assertNull(put.getDocument().getField("nonexisting4")); } @Test public void nonExistingFieldsCanBeIgnoredInUpdate() throws IOException{ JsonReader r = createReader(inputJson( "{ ", " 'update': 'id:unittest:smoke::doc1',", " 'fields': {", " 'nonexisting1': { 'assign': 'ignored value' },", " 'field1': { 'assign': 'value1' },", " 'nonexisting2': { " + " 'assign': {", " 'blocks': {", " 'a':[2.0,3.0],", " 'b':[4.0,5.0]", " }", " }", " },", " 'field2': { 'assign': 'value2' },", " 'nonexisting3': {", " 'assign' : {", " 'cells': [{'address': {'x': 'x1'}, 'value': 1.0}]", " }", " },", " 'tensor1': {'assign': { 'cells': {'x1': 1.0} } },", " 'nonexisting4': { 'assign': 'ignored value' }", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentUpdate update = new DocumentUpdate(docType, parseInfo.documentId); boolean fullyApplied = new VespaJsonDocumentReader(true).readUpdate(parseInfo.fieldsBuffer, update); assertFalse(fullyApplied); assertNull(update.getFieldUpdate("nonexisting1")); assertEquals("value1", update.getFieldUpdate("field1").getValueUpdates().get(0).getValue().getWrappedValue().toString()); assertNull(update.getFieldUpdate("nonexisting2")); assertEquals("value2", update.getFieldUpdate("field2").getValueUpdates().get(0).getValue().getWrappedValue().toString()); assertNull(update.getFieldUpdate("nonexisting3")); assertEquals(Tensor.from("tensor(x{}):{{x:x1}:1.0}"), update.getFieldUpdate("tensor1").getValueUpdates().get(0).getValue().getWrappedValue()); assertNull(update.getFieldUpdate("nonexisting4")); } @Test public void feedWithBasicErrorTest() { JsonReader r = createReader(inputJson("[", " { 'put': 'id:test:smoke::0', 'fields': { 'something': 'foo' } },", " { 'put': 'id:test:smoke::1', 'fields': { 'something': 'foo' } },", " { 'put': 'id:test:smoke::2', 'fields': { 'something': 'foo' } },", "]")); try { while (r.next() != null) ; fail(); } catch (RuntimeException e) { assertTrue(e.getMessage().contains("JsonParseException")); } } @Test public void idAsAliasForPutTest() throws IOException{ JsonReader r = createReader(inputJson("{ 'id': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); boolean fullyApplied = new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); assertTrue(fullyApplied); smokeTestDoc(put.getDocument()); } private void testFeedWithTestAndSetCondition(String jsonDoc) { ByteArrayInputStream parseInfoDoc = new ByteArrayInputStream(Utf8.toBytes(jsonDoc)); JsonReader reader = new JsonReader(types, parseInfoDoc, parserFactory); int NUM_OPERATIONS_IN_FEED = 3; for (int i = 0; i < NUM_OPERATIONS_IN_FEED; i++) { DocumentOperation operation = reader.next(); assertTrue("A test and set condition should be present", operation.getCondition().isPresent()); assertEquals("DocumentOperation's test and set condition should be equal to the one in the JSON feed", "smoke.something == \"smoketest\"", operation.getCondition().getSelection()); } assertNull(reader.next()); } @Test public void testFeedWithTestAndSetConditionOrderingOne() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'put': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " }", " },", " {", " 'update': 'id:unittest:testarray::whee',", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " },", " {", " 'remove': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\''", " }", "]" )); } @Test public void testFeedWithTestAndSetConditionOrderingTwo() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " }", " },", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " },", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'remove': 'id:unittest:smoke::whee'", " }", "]" )); } @Test public void testFeedWithTestAndSetConditionOrderingThree() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " },", " 'condition': 'smoke.something == \\'smoketest\\''", " },", " {", " 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " },", " 'condition': 'smoke.something == \\'smoketest\\''", " },", " {", " 'remove': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\''", " }", "]" )); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldAfterFieldsFieldShouldFailParse() { final String jsonData = inputJson( "[", " {", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " },", " 'bjarne': 'stroustrup'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldBeforeFieldsFieldShouldFailParse() { final String jsonData = inputJson( "[", " {", " 'update': 'id:unittest:testarray::whee',", " 'what is this': 'nothing to see here',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldWithoutFieldsFieldShouldFailParse() { String jsonData = inputJson( "[", " {", " 'remove': 'id:unittest:smoke::whee',", " 'what is love': 'baby, do not hurt me... much'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test public void testMissingOperation() { try { String jsonData = inputJson( "[", " {", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Missing a document operation ('put', 'update' or 'remove')", e.getMessage()); } } @Test public void testMissingFieldsMapInPut() { try { String jsonData = inputJson( "[", " {", " 'put': 'id:unittest:smoke::whee'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("put of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testMissingFieldsMapInUpdate() { try { String jsonData = inputJson( "[", " {", " 'update': 'id:unittest:smoke::whee'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Update of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testNullValues() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testnull::doc1',", " 'fields': {", " 'intfield': null,", " 'stringfield': null,", " 'arrayfield': null,", " 'weightedsetfield': null,", " 'mapfield': null,", " 'tensorfield': null", " }", "}")); DocumentPut put = (DocumentPut) r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:testnull::doc1").operation(); Document doc = put.getDocument(); assertFieldValueNull(doc, "intfield"); assertFieldValueNull(doc, "stringfield"); assertFieldValueNull(doc, "arrayfield"); assertFieldValueNull(doc, "weightedsetfield"); assertFieldValueNull(doc, "mapfield"); assertFieldValueNull(doc, "tensorfield"); } @Test(expected=JsonReaderException.class) public void testNullArrayElement() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testnull::doc1',", " 'fields': {", " 'arrayfield': [ null ]", " }", "}")); r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:testnull::doc1"); fail(); } private void assertFieldValueNull(Document doc, String fieldName) { Field field = doc.getField(fieldName); assertNotNull(field); FieldValue fieldValue = doc.getFieldValue(field); assertNull(fieldValue); } static ByteArrayInputStream jsonToInputStream(String json) { return new ByteArrayInputStream(Utf8.toBytes(json)); } @Test public void testParsingWithoutTensorField() { Document doc = createPutWithoutTensor().getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals("id:unittest:testtensor::0", doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField("sparse_tensor")); assertNull(fieldValue); } @Test public void testParsingOfEmptyTensor() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor("{}")); } @Test public void testParsingOfTensorWithEmptyCells() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor(inputJson("{ 'cells': [] }"))); } @Test public void testDisallowedDenseTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{ 'values': [] }"), "dense_tensor", "The 'values' array does not contain any values"); assertCreatePutFails(inputJson("{ 'values': '' }"), "dense_tensor", "The 'values' string does not contain any values"); } @Test public void testDisallowedMixedTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{\"blocks\":{ \"a\": [] } }"), "mixed_tensor", "Expected 3 values, but got 0"); assertCreatePutFails(inputJson("{\"blocks\":[ {\"address\":{\"x\":\"a\"}, \"values\": [] } ] }"), "mixed_tensor", "Expected 3 values, but got 0"); } @Test public void testParsingOfSparseTensorWithCells() { Tensor tensor = assertSparseTensorField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createPutWithSparseTensor( """ { "type": "tensor(x{},y{})", "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 }, { "address": { "x": "c", "y": "b" }, "value": 3.0 } ] } """)); assertTrue(tensor instanceof MappedTensor); // any functional instance is fine } @Test public void testParsingOfDenseTensorWithCells() { Tensor tensor = assertTensorField("{{x:0,y:0}:2.0,{x:1,y:0}:3.0}}", createPutWithTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' },", " 'value': 2.0 },", " { 'address': { 'x': '1', 'y': '0' },", " 'value': 3.0 }", " ]", "}"), "dense_unbound_tensor"), "dense_unbound_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorOnDenseForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(Double.POSITIVE_INFINITY); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson("{", " 'values': [2.0, 3.0, 4.0, 'inf', 6.0, 7.0]", "}"), "dense_tensor"), "dense_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<int8>(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson("{", " 'values': \"020304050607\"", "}"), "dense_int8_tensor"), "dense_int8_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfMixedTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")); builder.cell().label("x", "foo").label("y", 0).value(2.0); builder.cell().label("x", "foo").label("y", 1).value(3.0); builder.cell().label("x", "foo").label("y", 2).value(4.0); builder.cell().label("x", "bar").label("y", 0).value(5.0); builder.cell().label("x", "bar").label("y", 1).value(6.0); builder.cell().label("x", "bar").label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":[" + "{\"address\":{\"x\":\"foo\"},\"values\":\"400040404080\"}," + "{\"address\":{\"x\":\"bar\"},\"values\":\"40A040C040E0\"}" + "]}"; var put = createPutWithTensor(inputJson(mixedJson), "mixed_bfloat16_tensor"); Tensor tensor = assertTensorField(expected, put, "mixed_bfloat16_tensor"); } /** Tests parsing of various tensor values set at the root, i.e. no 'cells', 'blocks' or 'values' */ @Test public void testDirectValue() { assertTensorField("tensor(x{}):{a:2, b:3}", "sparse_single_dimension_tensor", "{'a':2.0, 'b':3.0}"); assertTensorField("tensor(x[2],y[3]):[2, 3, 4, 5, 6, 7]]", "dense_tensor", "[2, 3, 4, 5, 6, 7]"); assertTensorField("tensor(x[2],y[3]):[2, 3, 4, 5, 6, 7]]", "dense_tensor", "[[2, 3, 4], [5, 6, 7]]"); assertTensorField("tensor(x{},y[3]):{a:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'a':[2, 3, 4], 'b':[4, 5, 6]}"); assertTensorField("tensor(x{},y{}):{{x:a,y:0}:2, {x:b,y:1}:3}", "sparse_tensor", "[{'address':{'x':'a','y':'0'},'value':2}, {'address':{'x':'b','y':'1'},'value':3}]"); } @Test public void testDirectValueReservedNameKeys() { // Single-valued assertTensorField("tensor(x{}):{cells:2, b:3}", "sparse_single_dimension_tensor", "{'cells':2.0, 'b':3.0}"); assertTensorField("tensor(x{}):{values:2, b:3}", "sparse_single_dimension_tensor", "{'values':2.0, 'b':3.0}"); assertTensorField("tensor(x{}):{block:2, b:3}", "sparse_single_dimension_tensor", "{'block':2.0, 'b':3.0}"); // Multi-valued assertTensorField("tensor(x{},y[3]):{cells:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'cells':[2, 3, 4], 'b':[4, 5, 6]}"); assertTensorField("tensor(x{},y[3]):{values:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'values':[2, 3, 4], 'b':[4, 5, 6]}"); assertTensorField("tensor(x{},y[3]):{block:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'block':[2, 3, 4], 'b':[4, 5, 6]}"); } @Test public void testParsingOfMixedTensorOnMixedForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = """ { "blocks":[ {"address":{"x":"0"},"values":[2.0,3.0,4.0]}, {"address":{"x":"1"},"values":[5.0,6.0,7.0]} ] } """; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance String mixedJsonDirect = """ [ {"address":{"x":"0","y":"0"},"value":2.0}, {"address":{"x":"0","y":"1"},"value":3.0}, {"address":{"x":"0","y":"2"},"value":4.0}, {"address":{"x":"1","y":"0"},"value":5.0}, {"address":{"x":"1","y":"1"},"value":6.0}, {"address":{"x":"1","y":"2"},"value":7.0} ] """; Tensor tensorDirect = assertTensorField(expected, createPutWithTensor(inputJson(mixedJsonDirect), "mixed_tensor"), "mixed_tensor"); assertTrue(tensorDirect instanceof MixedTensor); // this matters for performance } @Test public void testMixedTensorInMixedFormWithSingleSparseDimensionShortForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":{" + "\"0\":[2.0,3.0,4.0]," + "\"1\":[5.0,6.0,7.0]" + "}}"; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance } @Test public void testParsingOfTensorWithSingleCellInDifferentJsonOrder() { assertSparseTensorField("{{x:a,y:b}:2.0}", createPutWithSparseTensor(inputJson("{", " 'cells': [", " { 'value': 2.0,", " 'address': { 'x': 'a', 'y': 'b' } }", " ]", "}"))); } @Test public void testAssignUpdateOfEmptySparseTensor() { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithSparseTensor("{}")); } @Test public void testAssignUpdateOfEmptyDenseTensor() { try { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithTensor("{}", "dense_unbound_tensor")); } catch (IllegalArgumentException e) { assertEquals("An indexed tensor must have a value", "Error in 'dense_unbound_tensor': Tensor of type tensor(x[],y[]) has no values", Exceptions.toMessageString(e)); } } @Test public void testAssignUpdateOfNullTensor() { ClearValueUpdate clearUpdate = (ClearValueUpdate) getTensorField(createAssignUpdateWithSparseTensor(null)).getValueUpdate(0); assertNotNull(clearUpdate); assertNull(clearUpdate.getValue()); } @Test public void testAssignUpdateOfTensorWithCells() { assertTensorAssignUpdateSparseField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createAssignUpdateWithSparseTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' },", " 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'b' },", " 'value': 3.0 }", " ]", "}"))); } @Test public void testAssignUpdateOfTensorDenseShortForm() { assertTensorAssignUpdateDenseField("tensor(x[2],y[3]):[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]", createAssignUpdateWithTensor(inputJson("{", " 'values': [1,2,3,4,5,6]", "}"), "dense_tensor")); } @Test public void tensor_modify_update_with_replace_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_add_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, "sparse_tensor", inputJson("{", " 'operation': 'add',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_multiply_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "sparse_tensor", inputJson("{", " 'operation': 'multiply',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_create_non_existing_cells_true() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, true, "sparse_tensor", inputJson("{", " 'operation': 'add',", " 'create': true,", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_create_non_existing_cells_false() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, false, "sparse_tensor", inputJson("{", " 'operation': 'add',", " 'create': false,", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_treats_the_input_tensor_as_sparse() { // Note that the type of the tensor in the modify update is sparse (it only has mapped dimensions). assertTensorModifyUpdate("tensor(x{},y{}):{{x:0,y:0}:2.0, {x:1,y:2}:3.0}", TensorModifyUpdate.Operation.REPLACE, "dense_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' }, 'value': 2.0 },", " { 'address': { 'x': '1', 'y': '2' }, 'value': 3.0 } ]}")); } @Test public void tensor_modify_update_on_non_tensor_field_throws() { try { JsonReader reader = createReader(inputJson("{ 'update': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': {", " 'modify': {} }}}")); reader.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::doc1"); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Error in 'something': A modify update can only be applied to tensor fields. Field 'something' is of type 'string'", Exceptions.toMessageString(e)); } } @Test public void tensor_modify_update_on_dense_unbound_tensor_throws() { illegalTensorModifyUpdate("Error in 'dense_unbound_tensor': A modify update cannot be applied to tensor types with indexed unbound dimensions. Field 'dense_unbound_tensor' has unsupported tensor type 'tensor(x[],y[])'", "dense_unbound_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorModifyUpdate("{{x:a}:2.0, {x:c}: 3.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_single_dimension_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': {", " 'a': 2.0,", " 'c': 3.0 }}")); } @Test public void tensor_modify_update_with_replace_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_array() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': [", " { 'address': { 'x': 'a' }, 'values': [1,2,3] } ]}")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_must_specify_full_subspace() { illegalTensorModifyUpdate("Error in 'mixed_tensor': At {x:a}: Expected 3 values, but got 2", "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': {", " 'a': [2,3] } }")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_map() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': {", " 'a': [1,2,3] } }")); } @Test public void tensor_modify_update_with_add_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.ADD, "mixed_tensor", inputJson("{", " 'operation': 'add',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_multiply_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "mixed_tensor", inputJson("{", " 'operation': 'multiply',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws() { illegalTensorModifyUpdate("Error in 'dense_tensor': Dimension 'y' has label '3' but type is tensor(x[2],y[3])", "dense_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws_mixed() { illegalTensorModifyUpdate("Error in 'mixed_tensor': Dimension 'y' has label '3' but type is tensor(x{},y[3])", "mixed_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_with_unknown_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown operation 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", "{", " 'operation': 'unknown',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_without_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain an operation", "sparse_tensor", "{", " 'cells': [] }"); } @Test public void tensor_modify_update_without_cells_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", "{", " 'operation': 'replace' }"); } @Test public void tensor_modify_update_with_unknown_content_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown JSON string 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", "{", " 'unknown': 'here' }"); } @Test public void tensor_add_update_on_sparse_tensor() { assertTensorAddUpdate("{{x:a,y:b}:2.0, {x:c,y:d}: 3.0}", "sparse_tensor", inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'd' }, 'value': 3.0 } ]}")); } @Test public void tensor_add_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorAddUpdate("{{x:a}:2.0, {x:c}: 3.0}", "sparse_single_dimension_tensor", inputJson("{", " 'cells': {", " 'a': 2.0,", " 'c': 3.0 }}")); } @Test public void tensor_add_update_on_mixed_tensor() { assertTensorAddUpdate("{{x:a,y:0}:2.0, {x:a,y:1}:3.0, {x:a,y:2}:0.0}", "mixed_tensor", inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 },", " { 'address': { 'x': 'a', 'y': '1' }, 'value': 3.0 } ]}")); } @Test public void tensor_add_update_on_mixed_with_out_of_bound_dense_cells_throws() { illegalTensorAddUpdate("Error in 'mixed_tensor': Index 3 out of bounds for length 3", "mixed_tensor", "{", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_add_update_on_dense_tensor_throws() { illegalTensorAddUpdate("Error in 'dense_tensor': An add update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", "{", " 'cells': [] }"); } @Test public void tensor_add_update_on_not_fully_specified_cell_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Missing a label for dimension 'y' for tensor(x{},y{})", "sparse_tensor", "{", " 'cells': [", " { 'address': { 'x': 'a' }, 'value': 2.0 } ]}"); } @Test public void tensor_add_update_without_cells_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Add update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", "{}"); illegalTensorAddUpdate("Error in 'mixed_tensor': Add update for field 'mixed_tensor' does not contain tensor cells", "mixed_tensor", "{}"); } @Test public void tensor_remove_update_on_sparse_tensor() { assertTensorRemoveUpdate("{{x:a,y:b}:1.0,{x:c,y:d}:1.0}", "sparse_tensor", inputJson("{", " 'addresses': [", " { 'x': 'a', 'y': 'b' },", " { 'x': 'c', 'y': 'd' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor() { assertTensorRemoveUpdate("{{x:1}:1.0,{x:2}:1.0}", "mixed_tensor", inputJson("{", " 'addresses': [", " { 'x': '1' },", " { 'x': '2' } ]}")); } @Test public void tensor_remove_update_on_sparse_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{y:b}:1.0,{y:d}:1.0}", "sparse_tensor", inputJson("{", " 'addresses': [", " { 'y': 'b' },", " { 'y': 'd' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{x:1,z:a}:1.0,{x:2,z:b}:1.0}", "mixed_tensor_adv", inputJson("{", " 'addresses': [", " { 'x': '1', 'z': 'a' },", " { 'x': '2', 'z': 'b' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor_with_dense_addresses_throws() { illegalTensorRemoveUpdate("Error in 'mixed_tensor': Indexed dimension address 'y' should not be specified in remove update", "mixed_tensor", "{", " 'addresses': [", " { 'x': '1', 'y': '0' },", " { 'x': '2', 'y': '0' } ]}"); } @Test public void tensor_remove_update_on_dense_tensor_throws() { illegalTensorRemoveUpdate("Error in 'dense_tensor': A remove update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", "{", " 'addresses': [] }"); } @Test public void tensor_remove_update_with_stray_dimension_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{},y{}) does not contain dimension 'foo'", "sparse_tensor", "{", " 'addresses': [", " { 'x': 'a', 'foo': 'b' } ]}"); illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{}) does not contain dimension 'foo'", "sparse_tensor", "{", " 'addresses': [", " { 'x': 'c' },", " { 'x': 'a', 'foo': 'b' } ]}"); } @Test public void tensor_remove_update_without_cells_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': Remove update for field 'sparse_tensor' does not contain tensor addresses", "sparse_tensor", "{'addresses': [] }"); illegalTensorRemoveUpdate("Error in 'mixed_tensor': Remove update for field 'mixed_tensor' does not contain tensor addresses", "mixed_tensor", "{'addresses': [] }"); } @Test public void require_that_parser_propagates_datatype_parser_errors_predicate() { assertParserErrorMatches( "Error in document 'id:unittest:testpredicate::0' - could not parse field 'boolean' of type 'predicate': " + "line 1:10 no viable alternative at character '>'", "[", " {", " 'fields': {", " 'boolean': 'timestamp > 9000'", " },", " 'put': 'id:unittest:testpredicate::0'", " }", "]" ); } @Test public void require_that_parser_propagates_datatype_parser_errors_string_as_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \" 1\"", "[", " {", " 'fields': {", " 'integerfield': ' 1'", " },", " 'put': 'id:unittest:testint::0'", " }", "]" ); } @Test public void require_that_parser_propagates_datatype_parser_errors_overflowing_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \"281474976710656\"", "[", " {", " 'fields': {", " 'integerfield': 281474976710656", " },", " 'put': 'id:unittest:testint::0'", " }", "]" ); } @Test public void requireThatUnknownDocTypeThrowsIllegalArgumentException() { final String jsonData = inputJson( "[", " {", " 'put': 'id:ns:walrus::walrus1',", " 'fields': {", " 'aField': 42", " }", " }", "]"); try { new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail(); } catch (IllegalArgumentException e) { assertEquals("Document type walrus does not exist", e.getMessage()); } } private static final String TENSOR_DOC_ID = "id:unittest:testtensor::0"; private void illegalTensorModifyUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorModifyUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorAddUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorAddUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorRemoveUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorRemoveUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private DocumentPut createPutWithoutTensor() { JsonReader reader = createReader(inputJson("[ { 'put': '" + TENSOR_DOC_ID + "', 'fields': { } } ]")); return (DocumentPut) reader.next(); } private DocumentPut createPutWithSparseTensor(String inputTensor) { return createPutWithTensor(inputTensor, "sparse_tensor"); } private DocumentPut createPutWithTensor(String inputTensor, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'put': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': " + inputTensor + " }}]")); return (DocumentPut) reader.next(); } private DocumentUpdate createAssignUpdateWithSparseTensor(String inputTensor) { return createAssignUpdateWithTensor(inputTensor, "sparse_tensor"); } private DocumentUpdate createAssignUpdateWithTensor(String inputTensor, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'update': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': {", " 'assign': " + (inputTensor != null ? inputTensor : "null") + " } } } ]")); return (DocumentUpdate) reader.next(); } private static Tensor assertSparseTensorField(String expectedTensor, DocumentPut put) { return assertTensorField(expectedTensor, put, "sparse_tensor"); } private Tensor assertTensorField(String expectedTensor, String fieldName, String inputJson) { return assertTensorField(expectedTensor, createPutWithTensor(inputJson, fieldName), fieldName); } private static Tensor assertTensorField(String expectedTensor, DocumentPut put, String tensorFieldName) { return assertTensorField(Tensor.from(expectedTensor), put, tensorFieldName); } private static Tensor assertTensorField(Tensor expectedTensor, DocumentPut put, String tensorFieldName) { Document doc = put.getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals(TENSOR_DOC_ID, doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField(tensorFieldName)); assertEquals(expectedTensor, fieldValue.getTensor().get()); return fieldValue.getTensor().get(); } private static void assertTensorFieldUpdate(DocumentUpdate update, String tensorFieldName) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); assertEquals(1, update.fieldUpdates().size()); assertEquals(1, update.getFieldUpdate(tensorFieldName).size()); } private static void assertTensorAssignUpdateSparseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "sparse_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private static void assertTensorAssignUpdateDenseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "dense_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, String tensorFieldName, String modifyJson) { assertTensorModifyUpdate(expectedTensor, expectedOperation, false, tensorFieldName, createTensorModifyUpdate(modifyJson, tensorFieldName)); } private void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, boolean expectedCreateNonExistingCells, String tensorFieldName, String modifyJson) { assertTensorModifyUpdate(expectedTensor, expectedOperation, expectedCreateNonExistingCells, tensorFieldName, createTensorModifyUpdate(modifyJson, tensorFieldName)); } private static void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, boolean expectedCreateNonExistingCells, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorModifyUpdate modifyUpdate = (TensorModifyUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(expectedOperation, modifyUpdate.getOperation()); assertEquals(Tensor.from(expectedTensor), modifyUpdate.getValue().getTensor().get()); assertEquals(expectedCreateNonExistingCells, modifyUpdate.getCreateNonExistingCells()); } private DocumentUpdate createTensorModifyUpdate(String modifyJson, String tensorFieldName) { return createTensorUpdate("modify", modifyJson, tensorFieldName); } private DocumentUpdate createTensorAddUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("add", tensorJson, tensorFieldName); } private DocumentUpdate createTensorRemoveUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("remove", tensorJson, tensorFieldName); } private DocumentUpdate createTensorUpdate(String operation, String tensorJson, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'update': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': {", " '" + operation + "': " + tensorJson + " }}}]")); return (DocumentUpdate) reader.next(); } private void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorAddUpdate(expectedTensor, tensorFieldName, createTensorAddUpdate(tensorJson, tensorFieldName)); } private static void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorAddUpdate addUpdate = (TensorAddUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), addUpdate.getValue().getTensor().get()); } private void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorRemoveUpdate(expectedTensor, tensorFieldName, createTensorRemoveUpdate(tensorJson, tensorFieldName)); } private static void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorRemoveUpdate removeUpdate = (TensorRemoveUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), removeUpdate.getValue().getTensor().get()); } private static FieldUpdate getTensorField(DocumentUpdate update) { return getTensorField(update, "sparse_tensor"); } private static FieldUpdate getTensorField(DocumentUpdate update, String fieldName) { FieldUpdate fieldUpdate = update.getFieldUpdate(fieldName); assertEquals(1, fieldUpdate.size()); return fieldUpdate; } // NOTE: Do not call this method multiple times from a test method as it's using the ExpectedException rule private void assertParserErrorMatches(String expectedError, String... json) { String jsonData = inputJson(json); try { new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail(); } catch (JsonReaderException e) { assertEquals(expectedError, e.getMessage()); } } private void assertCreatePutFails(String tensor, String name, String msg) { try { createPutWithTensor(inputJson(tensor), name); fail("Expected exception"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains(msg)); } } }
tomglk/vespa
document/src/test/java/com/yahoo/document/json/JsonReaderTestCase.java
213,289
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.document.json; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.io.JsonStringEncoder; import com.google.common.base.Joiner; import com.yahoo.collections.Tuple2; import com.yahoo.document.ArrayDataType; import com.yahoo.document.DataType; import com.yahoo.document.Document; import com.yahoo.document.DocumentId; import com.yahoo.document.DocumentOperation; import com.yahoo.document.DocumentPut; import com.yahoo.document.DocumentRemove; import com.yahoo.document.DocumentType; import com.yahoo.document.DocumentTypeManager; import com.yahoo.document.DocumentUpdate; import com.yahoo.document.Field; import com.yahoo.document.MapDataType; import com.yahoo.document.PositionDataType; import com.yahoo.document.StructDataType; import com.yahoo.document.TensorDataType; import com.yahoo.document.WeightedSetDataType; import com.yahoo.document.datatypes.Array; import com.yahoo.document.datatypes.BoolFieldValue; import com.yahoo.document.datatypes.FieldValue; import com.yahoo.document.datatypes.IntegerFieldValue; import com.yahoo.document.datatypes.MapFieldValue; import com.yahoo.document.datatypes.Raw; import com.yahoo.document.datatypes.StringFieldValue; import com.yahoo.document.datatypes.Struct; import com.yahoo.document.datatypes.TensorFieldValue; import com.yahoo.document.datatypes.WeightedSet; import com.yahoo.document.internal.GeoPosType; import com.yahoo.document.json.readers.DocumentParseInfo; import com.yahoo.document.json.readers.VespaJsonDocumentReader; import com.yahoo.document.serialization.DocumentSerializer; import com.yahoo.document.serialization.DocumentSerializerFactory; import com.yahoo.document.update.AddValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate.Operator; import com.yahoo.document.update.AssignValueUpdate; import com.yahoo.document.update.ClearValueUpdate; import com.yahoo.document.update.FieldUpdate; import com.yahoo.document.update.MapValueUpdate; import com.yahoo.document.update.TensorAddUpdate; import com.yahoo.document.update.TensorModifyUpdate; import com.yahoo.document.update.TensorRemoveUpdate; import com.yahoo.document.update.ValueUpdate; import com.yahoo.io.GrowableByteBuffer; import com.yahoo.tensor.IndexedTensor; import com.yahoo.tensor.MappedTensor; import com.yahoo.tensor.MixedTensor; import com.yahoo.tensor.Tensor; import com.yahoo.tensor.TensorType; import com.yahoo.text.Utf8; import com.yahoo.yolean.Exceptions; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DECREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DIVIDE; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_INCREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_MULTIPLY; import static com.yahoo.test.json.JsonTestHelper.inputJson; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Basic test of JSON streams to Vespa document instances. * * @author Steinar Knutsen * @author bratseth */ public class JsonReaderTestCase { private DocumentTypeManager types; private JsonFactory parserFactory; @Before public void setUp() throws Exception { parserFactory = new JsonFactory(); types = new DocumentTypeManager(); { DocumentType x = new DocumentType("smoke"); x.addField(new Field("something", DataType.STRING)); x.addField(new Field("nalle", DataType.STRING)); x.addField(new Field("int1", DataType.INT)); x.addField(new Field("flag", DataType.BOOL)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("mirrors"); StructDataType woo = new StructDataType("woo"); woo.addField(new Field("sandra", DataType.STRING)); woo.addField(new Field("cloud", DataType.STRING)); x.addField(new Field("skuggsjaa", woo)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testarray"); DataType d = new ArrayDataType(DataType.STRING); x.addField(new Field("actualarray", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testset"); DataType d = new WeightedSetDataType(DataType.STRING, true, true); x.addField(new Field("actualset", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testmap"); DataType d = new MapDataType(DataType.STRING, DataType.STRING); x.addField(new Field("actualmap", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testraw"); DataType d = DataType.RAW; x.addField(new Field("actualraw", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testMapStringToArrayOfInt"); DataType value = new ArrayDataType(DataType.INT); DataType d = new MapDataType(DataType.STRING, value); x.addField(new Field("actualMapStringToArrayOfInt", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testsinglepos"); DataType d = PositionDataType.INSTANCE; x.addField(new Field("singlepos", d)); x.addField(new Field("geopos", new GeoPosType(8))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testtensor"); x.addField(new Field("sparse_single_dimension_tensor", new TensorDataType(new TensorType.Builder().mapped("x").build()))); x.addField(new Field("sparse_tensor", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").build()))); x.addField(new Field("dense_tensor", new TensorDataType(new TensorType.Builder().indexed("x", 2).indexed("y", 3).build()))); x.addField(new Field("dense_int8_tensor", new TensorDataType(TensorType.fromSpec("tensor<int8>(x[2],y[3])")))); x.addField(new Field("dense_unbound_tensor", new TensorDataType(new TensorType.Builder().indexed("x").indexed("y").build()))); x.addField(new Field("mixed_tensor", new TensorDataType(new TensorType.Builder().mapped("x").indexed("y", 3).build()))); x.addField(new Field("mixed_bfloat16_tensor", new TensorDataType(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")))); x.addField(new Field("mixed_tensor_adv", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").mapped("z").indexed("a", 3).build()))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testpredicate"); x.addField(new Field("boolean", DataType.PREDICATE)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testint"); x.addField(new Field("integerfield", DataType.INT)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testnull"); x.addField(new Field("intfield", DataType.INT)); x.addField(new Field("stringfield", DataType.STRING)); x.addField(new Field("arrayfield", new ArrayDataType(DataType.STRING))); x.addField(new Field("weightedsetfield", new WeightedSetDataType(DataType.STRING, true, true))); x.addField(new Field("mapfield", new MapDataType(DataType.STRING, DataType.STRING))); x.addField(new Field("tensorfield", new TensorDataType(new TensorType.Builder().indexed("x").build()))); types.registerDocumentType(x); } } @After public void tearDown() throws Exception { types = null; parserFactory = null; } private JsonReader createReader(String jsonInput) { InputStream input = new ByteArrayInputStream(Utf8.toBytes(jsonInput)); return new JsonReader(types, input, parserFactory); } @Test public void readSingleDocumentPut() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " }", "}")); DocumentPut put = (DocumentPut) r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:smoke::doc1"); smokeTestDoc(put.getDocument()); } @Test public final void readSingleDocumentUpdate() { JsonReader r = createReader(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': {", " 'assign': 'orOther' }}}")); DocumentUpdate doc = (DocumentUpdate) r.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::whee"); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof AssignValueUpdate); } @Test public void readClearField() { JsonReader r = createReader(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'int1': {", " 'assign': null }}}")); DocumentUpdate doc = (DocumentUpdate) r.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::whee"); FieldUpdate f = doc.getFieldUpdate("int1"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof ClearValueUpdate); assertNull(f.getValueUpdate(0).getValue()); } @Test public void smokeTest() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } @Test public void docIdLookaheadTest() throws IOException { JsonReader r = createReader(inputJson( "{ 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " },", " 'put': 'id:unittest:smoke::doc1'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } @Test public void emptyDocTest() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::whee', 'fields': {}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); assertEquals("id:unittest:smoke::whee", parseInfo.documentId.toString()); } @Test public void testStruct() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:mirrors::whee',", " 'fields': {", " 'skuggsjaa': {", " 'sandra': 'person',", " 'cloud': 'another person' }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("skuggsjaa")); assertSame(Struct.class, f.getClass()); Struct s = (Struct) f; assertEquals("person", ((StringFieldValue) s.getFieldValue("sandra")).getString()); } private DocumentUpdate parseUpdate(String json) throws IOException { InputStream rawDoc = new ByteArrayInputStream(Utf8.toBytes(json)); JsonReader r = new JsonReader(types, rawDoc, parserFactory); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentUpdate update = new DocumentUpdate(docType, parseInfo.documentId); new VespaJsonDocumentReader(false).readUpdate(parseInfo.fieldsBuffer, update); return update; } @Test public void testStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(inputJson("{ 'update': 'id:unittest:mirrors:g=test:whee',", " 'create': true,", " 'fields': {", " 'skuggsjaa': {", " 'assign': {", " 'sandra': 'person',", " 'cloud': 'another person' }}}}")); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(2, s.getFieldCount()); assertEquals(new StringFieldValue("person"), s.getFieldValue(s.getField("sandra"))); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(107, buf.position()); } @Test public final void testEmptyStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(inputJson("{ 'update': 'id:unittest:mirrors:g=test:whee',", " 'create': true,", " 'fields': { ", " 'skuggsjaa': {", " 'assign': { } }}}")); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(0, s.getFieldCount()); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(69, buf.position()); } @Test public void testUpdateArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}}")); checkSimpleArrayAdd(doc); } @Test public void testUpdateWeighted() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'add': {", " 'person': 37,", " 'another person': 41 }}}}")); Map<String, Integer> weights = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; final String s = ((StringFieldValue) adder.getValue()).getString(); weights.put(s, adder.getWeight()); } assertEquals(2, weights.size()); final String o = "person"; final String o2 = "another person"; assertTrue(weights.containsKey(o)); assertTrue(weights.containsKey(o2)); assertEquals(Integer.valueOf(37), weights.get(o)); assertEquals(Integer.valueOf(41), weights.get(o2)); } @Test public void testUpdateMatch() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'match': {", " 'element': 'person',", " 'increment': 13 }}}}")); Map<String, Tuple2<Number, String>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); String op = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperator().toString(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()).getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertEquals("ADD", matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } @SuppressWarnings({ "cast", "unchecked", "rawtypes" }) @Test public void testArithmeticOperators() throws IOException { Tuple2[] operations = new Tuple2[] { new Tuple2<String, Operator>(UPDATE_DECREMENT, ArithmeticValueUpdate.Operator.SUB), new Tuple2<String, Operator>(UPDATE_DIVIDE, ArithmeticValueUpdate.Operator.DIV), new Tuple2<String, Operator>(UPDATE_INCREMENT, ArithmeticValueUpdate.Operator.ADD), new Tuple2<String, Operator>(UPDATE_MULTIPLY, ArithmeticValueUpdate.Operator.MUL) }; for (Tuple2<String, Operator> operator : operations) { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'match': {", " 'element': 'person',", " '" + (String) operator.first + "': 13 }}}}")); Map<String, Tuple2<Number, Operator>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); Operator op = ((ArithmeticValueUpdate) adder .getUpdate()).getOperator(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertSame(operator.second, matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } } @SuppressWarnings("rawtypes") @Test public void testArrayIndexing() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'match': {", " 'element': 3,", " 'assign': 'nalle' }}}}")); Map<Number, String> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualarray"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final Number key = ((IntegerFieldValue) adder.getValue()) .getNumber(); String op = ((StringFieldValue) ((AssignValueUpdate) adder.getUpdate()) .getValue()).getString(); matches.put(key, op); } assertEquals(1, matches.size()); Number n = Integer.valueOf(3); assertEquals("nalle", matches.get(n)); } @Test public void testDocumentRemove() { JsonReader r = createReader(inputJson("{'remove': 'id:unittest:smoke::whee'}")); DocumentType docType = r.readDocumentType(new DocumentId("id:unittest:smoke::whee")); assertEquals("smoke", docType.getName()); } private Document docFromJson(String json) throws IOException { JsonReader r = createReader(json); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); return put.getDocument(); } @Test public void testWeightedSet() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'nalle': 2,", " 'tralle': 7 }}}")); FieldValue f = doc.getFieldValue(doc.getField("actualset")); assertSame(WeightedSet.class, f.getClass()); WeightedSet<?> w = (WeightedSet<?>) f; assertEquals(2, w.size()); assertEquals(Integer.valueOf(2), w.get(new StringFieldValue("nalle"))); assertEquals(Integer.valueOf(7), w.get(new StringFieldValue("tralle"))); } @Test public void testArray() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': [", " 'nalle',", " 'tralle' ]}}")); FieldValue f = doc.getFieldValue(doc.getField("actualarray")); assertSame(Array.class, f.getClass()); Array<?> a = (Array<?>) f; assertEquals(2, a.size()); assertEquals(new StringFieldValue("nalle"), a.get(0)); assertEquals(new StringFieldValue("tralle"), a.get(1)); } @Test public void testMap() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testmap::whee',", " 'fields': {", " 'actualmap': {", " 'nalle': 'kalle',", " 'tralle': 'skalle' }}}")); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testOldMap() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testmap::whee',", " 'fields': {", " 'actualmap': [", " { 'key': 'nalle', 'value': 'kalle'},", " { 'key': 'tralle', 'value': 'skalle'} ]}}")); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testPositionPositive() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': 'N63.429722;E10.393333' }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionOld() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': {'x':10393333,'y':63429722} }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testGeoPosition() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': {'lat':63.429722,'lng':10.393333} }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testGeoPositionNoAbbreviations() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': {'latitude':63.429722,'longitude':10.393333} }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionGeoPos() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'geopos': 'N63.429722;E10.393333' }}")); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); } @Test public void testPositionOldGeoPos() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'geopos': {'x':10393333,'y':63429722} }}")); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); } @Test public void testGeoPositionGeoPos() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'geopos': {'lat':63.429722,'lng':10.393333} }}")); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); assertEquals(PositionDataType.INSTANCE, f.getDataType()); } @Test public void testPositionNegative() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': 'W46.63;S23.55' }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(-46630000, PositionDataType.getXValue(f).getInteger()); assertEquals(-23550000, PositionDataType.getYValue(f).getInteger()); } @Test public void testRaw() throws IOException { String base64 = new String(new JsonStringEncoder().quoteAsString( Base64.getEncoder().encodeToString(Utf8.toBytes("smoketest")))); String s = fieldStringFromBase64RawContent(base64); assertEquals("smoketest", s); } @Test public void can_read_legacy_chunked_base64_raw_field_encoding() throws IOException { String expected = "this is a string with an impressive length. it's long enough to reach the end of the line, wow!"; String base64withDelims = "dGhpcyBpcyBhIHN0cmluZyB3aXRoIGFuIGltcHJlc3NpdmUgbGVuZ3RoLiBpdCdzIGxvbmcgZW5v\\r\\n" + "dWdoIHRvIHJlYWNoIHRoZSBlbmQgb2YgdGhlIGxpbmUsIHdvdyE=\\r\\n"; assertEquals(expected, fieldStringFromBase64RawContent(base64withDelims)); } private String fieldStringFromBase64RawContent(String base64data) throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testraw::whee',", " 'fields': {", " 'actualraw': '" + base64data + "' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("actualraw")); assertSame(Raw.class, f.getClass()); Raw s = (Raw) f; return Utf8.toString(s.getByteBuffer()); } @Test public void testMapStringToArrayOfInt() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'bamse': [1, 2, 3] }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldMapStringToArrayOfInt() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': [", " { 'key': 'bamse', 'value': [1, 2, 3] } ]}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToString() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': {", " 'assign': 'orOther' }}}")); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); AssignValueUpdate a = (AssignValueUpdate) f.getValueUpdate(0); assertEquals(new StringFieldValue("orOther"), a.getValue()); } @Test public void testAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'assign': { 'bamse': [1, 2, 3] }}}}")); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'assign': [", " { 'key': 'bamse', 'value': [1, 2, 3] } ]}}}")); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToWeightedSet() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'assign': {", " 'person': 37,", " 'another person': 41 }}}}")); FieldUpdate x = doc.getFieldUpdate("actualset"); assertEquals(1, x.size()); AssignValueUpdate assign = (AssignValueUpdate) x.getValueUpdate(0); WeightedSet<?> w = (WeightedSet<?>) assign.getValue(); assertEquals(2, w.size()); assertEquals(Integer.valueOf(37), w.get(new StringFieldValue("person"))); assertEquals(Integer.valueOf(41), w.get(new StringFieldValue("another person"))); } @Test public void testCompleteFeed() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }},", "{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}},", "{ 'remove': 'id:unittest:smoke::whee' }]")); controlBasicFeed(r); } @Test public void testCompleteFeedWithCreateAndCondition() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }},", "{", " 'condition':'bla',", " 'update': 'id:unittest:testarray::whee',", " 'create':true,", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}},", "{ 'remove': 'id:unittest:smoke::whee' }]")); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testUpdateWithConditionAndCreateInDifferentOrdering() { int documentsCreated = 106; List<String> parts = Arrays.asList( "\"condition\":\"bla\"", "\"update\": \"id:unittest:testarray::whee\"", " \"fields\": { " + "\"actualarray\": { \"add\": [" + " \"person\",\"another person\"]}}", " \"create\":true"); Random random = new Random(42); StringBuilder documents = new StringBuilder("["); for (int x = 0; x < documentsCreated; x++) { Collections.shuffle(parts, random); documents.append("{").append(Joiner.on(",").join(parts)).append("}"); if (x < documentsCreated -1) { documents.append(","); } } documents.append("]"); InputStream rawDoc = new ByteArrayInputStream( Utf8.toBytes(documents.toString())); JsonReader r = new JsonReader(types, rawDoc, parserFactory); for (int x = 0; x < documentsCreated; x++) { DocumentUpdate update = (DocumentUpdate) r.next(); checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); } assertNull(r.next()); } @Test(expected=RuntimeException.class) public void testCreateIfNonExistentInPut() { JsonReader r = createReader(inputJson("[{", " 'create':true,", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse' },", " 'put': 'id:unittest:smoke::whee'", "}]")); r.next(); } @Test public void testCompleteFeedWithIdAfterFields() { JsonReader r = createReader(inputJson("[", "{", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' },", " 'put': 'id:unittest:smoke::whee'", "},", "{", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}},", " 'update': 'id:unittest:testarray::whee'", "},", "{ 'remove': 'id:unittest:smoke::whee' }]")); controlBasicFeed(r); } protected void controlBasicFeed(JsonReader r) { DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testCompleteFeedWithEmptyDoc() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee', 'fields': {} },", "{ 'update': 'id:unittest:testarray::whee', 'fields': {} },", "{ 'remove': 'id:unittest:smoke::whee' }]")); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); assertEquals("smoke", doc.getId().getDocType()); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; assertEquals("testarray", update.getId().getDocType()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } private void checkSimpleArrayAdd(DocumentUpdate update) { Set<String> toAdd = new HashSet<>(); FieldUpdate x = update.getFieldUpdate("actualarray"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; toAdd.add(((StringFieldValue) adder.getValue()).getString()); } assertEquals(2, toAdd.size()); assertTrue(toAdd.contains("person")); assertTrue(toAdd.contains("another person")); } private void smokeTestDoc(Document doc) { FieldValue boolField = doc.getFieldValue(doc.getField("flag")); assertSame(BoolFieldValue.class, boolField.getClass()); assertTrue((Boolean)boolField.getWrappedValue()); FieldValue stringField = doc.getFieldValue(doc.getField("nalle")); assertSame(StringFieldValue.class, stringField.getClass()); assertEquals("bamse", ((StringFieldValue) stringField).getString()); } @Test public void nonExistingFieldCausesException() throws IOException{ JsonReader r = createReader(inputJson( "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'smething': 'smoketest',", " 'nalle': 'bamse' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); try { new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); fail(); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().startsWith("No field 'smething' in the structure of type 'smoke'")); } } @Test public void nonExistingFieldCanBeIgnored() throws IOException{ JsonReader r = createReader(inputJson( "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'smething': 'smoketest',", " 'nalle': 'bamse' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(true).readPut(parseInfo.fieldsBuffer, put); } @Test public void feedWithBasicErrorTest() { JsonReader r = createReader(inputJson("[", " { 'put': 'id:test:smoke::0', 'fields': { 'something': 'foo' } },", " { 'put': 'id:test:smoke::1', 'fields': { 'something': 'foo' } },", " { 'put': 'id:test:smoke::2', 'fields': { 'something': 'foo' } },", "]")); try { while (r.next() != null) ; fail(); } catch (RuntimeException e) { assertTrue(e.getMessage().contains("JsonParseException")); } } @Test public void idAsAliasForPutTest() throws IOException{ JsonReader r = createReader(inputJson("{ 'id': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } private void testFeedWithTestAndSetCondition(String jsonDoc) { ByteArrayInputStream parseInfoDoc = new ByteArrayInputStream(Utf8.toBytes(jsonDoc)); JsonReader reader = new JsonReader(types, parseInfoDoc, parserFactory); int NUM_OPERATIONS_IN_FEED = 3; for (int i = 0; i < NUM_OPERATIONS_IN_FEED; i++) { DocumentOperation operation = reader.next(); assertTrue("A test and set condition should be present", operation.getCondition().isPresent()); assertEquals("DocumentOperation's test and set condition should be equal to the one in the JSON feed", "smoke.something == \"smoketest\"", operation.getCondition().getSelection()); } assertNull(reader.next()); } @Test public void testFeedWithTestAndSetConditionOrderingOne() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'put': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " }", " },", " {", " 'update': 'id:unittest:testarray::whee',", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " },", " {", " 'remove': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\''", " }", "]" )); } @Test public void testFeedWithTestAndSetConditionOrderingTwo() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " }", " },", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " },", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'remove': 'id:unittest:smoke::whee'", " }", "]" )); } @Test public void testFeedWithTestAndSetConditionOrderingThree() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " },", " 'condition': 'smoke.something == \\'smoketest\\''", " },", " {", " 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " },", " 'condition': 'smoke.something == \\'smoketest\\''", " },", " {", " 'remove': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\''", " }", "]" )); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldAfterFieldsFieldShouldFailParse() { final String jsonData = inputJson( "[", " {", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " },", " 'bjarne': 'stroustrup'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldBeforeFieldsFieldShouldFailParse() { final String jsonData = inputJson( "[", " {", " 'update': 'id:unittest:testarray::whee',", " 'what is this': 'nothing to see here',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldWithoutFieldsFieldShouldFailParse() { String jsonData = inputJson( "[", " {", " 'remove': 'id:unittest:smoke::whee',", " 'what is love': 'baby, do not hurt me... much'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test public void testMissingOperation() { try { String jsonData = inputJson( "[", " {", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Missing a document operation ('put', 'update' or 'remove')", e.getMessage()); } } @Test public void testMissingFieldsMapInPut() { try { String jsonData = inputJson( "[", " {", " 'put': 'id:unittest:smoke::whee'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("put of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testMissingFieldsMapInUpdate() { try { String jsonData = inputJson( "[", " {", " 'update': 'id:unittest:smoke::whee'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("update of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testNullValues() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testnull::doc1',", " 'fields': {", " 'intfield': null,", " 'stringfield': null,", " 'arrayfield': null,", " 'weightedsetfield': null,", " 'mapfield': null,", " 'tensorfield': null", " }", "}")); DocumentPut put = (DocumentPut) r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:testnull::doc1"); Document doc = put.getDocument(); assertFieldValueNull(doc, "intfield"); assertFieldValueNull(doc, "stringfield"); assertFieldValueNull(doc, "arrayfield"); assertFieldValueNull(doc, "weightedsetfield"); assertFieldValueNull(doc, "mapfield"); assertFieldValueNull(doc, "tensorfield"); } @Test(expected=JsonReaderException.class) public void testNullArrayElement() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testnull::doc1',", " 'fields': {", " 'arrayfield': [ null ]", " }", "}")); r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:testnull::doc1"); fail(); } private void assertFieldValueNull(Document doc, String fieldName) { Field field = doc.getField(fieldName); assertNotNull(field); FieldValue fieldValue = doc.getFieldValue(field); assertNull(fieldValue); } static ByteArrayInputStream jsonToInputStream(String json) { return new ByteArrayInputStream(Utf8.toBytes(json)); } @Test public void testParsingWithoutTensorField() { Document doc = createPutWithoutTensor().getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals("id:unittest:testtensor::0", doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField("sparse_tensor")); assertNull(fieldValue); } @Test public void testParsingOfEmptyTensor() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor("{}")); } @Test public void testParsingOfTensorWithEmptyDimensions() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor(inputJson("{ 'dimensions': [] }"))); } @Test public void testParsingOfTensorWithEmptyCells() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor(inputJson("{ 'cells': [] }"))); } @Test public void testDisallowedDenseTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{ 'values': [] }"), "dense_tensor", "The 'values' array does not contain any values"); assertCreatePutFails(inputJson("{ 'values': '' }"), "dense_tensor", "The 'values' string does not contain any values"); } @Test public void testDisallowedMixedTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{\"blocks\":{ \"a\": [] } }"), "mixed_tensor", "Expected 3 values, but got 0"); assertCreatePutFails(inputJson("{\"blocks\":[ {\"address\":{\"x\":\"a\"}, \"values\": [] } ] }"), "mixed_tensor", "Expected 3 values, but got 0"); } @Test public void testParsingOfSparseTensorWithCells() { Tensor tensor = assertSparseTensorField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createPutWithSparseTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' },", " 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'b' },", " 'value': 3.0 }", " ]", "}"))); assertTrue(tensor instanceof MappedTensor); // any functional instance is fine } @Test public void testParsingOfDenseTensorWithCells() { Tensor tensor = assertTensorField("{{x:0,y:0}:2.0,{x:1,y:0}:3.0}}", createPutWithTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' },", " 'value': 2.0 },", " { 'address': { 'x': '1', 'y': '0' },", " 'value': 3.0 }", " ]", "}"), "dense_unbound_tensor"), "dense_unbound_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorOnDenseForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson("{", " 'values': [2.0, 3.0, 4.0, 5.0, 6.0, 7.0]", "}"), "dense_tensor"), "dense_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<int8>(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson("{", " 'values': \"020304050607\"", "}"), "dense_int8_tensor"), "dense_int8_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfMixedTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")); builder.cell().label("x", "foo").label("y", 0).value(2.0); builder.cell().label("x", "foo").label("y", 1).value(3.0); builder.cell().label("x", "foo").label("y", 2).value(4.0); builder.cell().label("x", "bar").label("y", 0).value(5.0); builder.cell().label("x", "bar").label("y", 1).value(6.0); builder.cell().label("x", "bar").label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":[" + "{\"address\":{\"x\":\"foo\"},\"values\":\"400040404080\"}," + "{\"address\":{\"x\":\"bar\"},\"values\":\"40A040C040E0\"}" + "]}"; var put = createPutWithTensor(inputJson(mixedJson), "mixed_bfloat16_tensor"); Tensor tensor = assertTensorField(expected, put, "mixed_bfloat16_tensor"); } @Test public void testParsingOfMixedTensorOnMixedForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":[" + "{\"address\":{\"x\":\"0\"},\"values\":[2.0,3.0,4.0]}," + "{\"address\":{\"x\":\"1\"},\"values\":[5.0,6.0,7.0]}" + "]}"; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance } @Test public void testMixedTensorInMixedFormWithSingleSparseDimensionShortForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":{" + "\"0\":[2.0,3.0,4.0]," + "\"1\":[5.0,6.0,7.0]" + "}}"; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance } @Test public void testParsingOfTensorWithSingleCellInDifferentJsonOrder() { assertSparseTensorField("{{x:a,y:b}:2.0}", createPutWithSparseTensor(inputJson("{", " 'cells': [", " { 'value': 2.0,", " 'address': { 'x': 'a', 'y': 'b' } }", " ]", "}"))); } @Test public void testAssignUpdateOfEmptySparseTensor() { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithSparseTensor("{}")); } @Test public void testAssignUpdateOfEmptyDenseTensor() { try { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithTensor("{}", "dense_unbound_tensor")); } catch (IllegalArgumentException e) { assertEquals("An indexed tensor must have a value", "Error in 'dense_unbound_tensor': Tensor of type tensor(x[],y[]) has no values", Exceptions.toMessageString(e)); } } @Test public void testAssignUpdateOfNullTensor() { ClearValueUpdate clearUpdate = (ClearValueUpdate) getTensorField(createAssignUpdateWithSparseTensor(null)).getValueUpdate(0); assertTrue(clearUpdate != null); assertTrue(clearUpdate.getValue() == null); } @Test public void testAssignUpdateOfTensorWithCells() { assertTensorAssignUpdateSparseField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createAssignUpdateWithSparseTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' },", " 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'b' },", " 'value': 3.0 }", " ]", "}"))); } @Test public void testAssignUpdateOfTensorDenseShortForm() { assertTensorAssignUpdateDenseField("tensor(x[2],y[3]):[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]", createAssignUpdateWithTensor(inputJson("{", " 'values': [1,2,3,4,5,6]", "}"), "dense_tensor")); } @Test public void tensor_modify_update_with_replace_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_add_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, "sparse_tensor", inputJson("{", " 'operation': 'add',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_multiply_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "sparse_tensor", inputJson("{", " 'operation': 'multiply',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_treats_the_input_tensor_as_sparse() { // Note that the type of the tensor in the modify update is sparse (it only has mapped dimensions). assertTensorModifyUpdate("tensor(x{},y{}):{{x:0,y:0}:2.0, {x:1,y:2}:3.0}", TensorModifyUpdate.Operation.REPLACE, "dense_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' }, 'value': 2.0 },", " { 'address': { 'x': '1', 'y': '2' }, 'value': 3.0 } ]}")); } @Test public void tensor_modify_update_on_non_tensor_field_throws() { try { JsonReader reader = createReader(inputJson("{ 'update': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': {", " 'modify': {} }}}")); reader.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::doc1"); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Error in 'something': A modify update can only be applied to tensor fields. Field 'something' is of type 'string'", Exceptions.toMessageString(e)); } } @Test public void tensor_modify_update_on_dense_unbound_tensor_throws() { illegalTensorModifyUpdate("Error in 'dense_unbound_tensor': A modify update cannot be applied to tensor types with indexed unbound dimensions. Field 'dense_unbound_tensor' has unsupported tensor type 'tensor(x[],y[])'", "dense_unbound_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorModifyUpdate("{{x:a}:2.0, {x:c}: 3.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_single_dimension_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': {", " 'a': 2.0,", " 'c': 3.0 }}")); } @Test public void tensor_modify_update_with_replace_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_array() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': [", " { 'address': { 'x': 'a' }, 'values': [1,2,3] } ]}")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_must_specify_full_subspace() { illegalTensorModifyUpdate("Error in 'mixed_tensor': At {x:a}: Expected 3 values, but got 2", "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': {", " 'a': [2,3] } }")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_map() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': {", " 'a': [1,2,3] } }")); } @Test public void tensor_modify_update_with_add_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.ADD, "mixed_tensor", inputJson("{", " 'operation': 'add',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_multiply_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "mixed_tensor", inputJson("{", " 'operation': 'multiply',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws() { illegalTensorModifyUpdate("Error in 'dense_tensor': Dimension 'y' has label '3' but type is tensor(x[2],y[3])", "dense_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws_mixed() { illegalTensorModifyUpdate("Error in 'mixed_tensor': Dimension 'y' has label '3' but type is tensor(x{},y[3])", "mixed_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_with_unknown_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown operation 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", "{", " 'operation': 'unknown',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_without_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain an operation", "sparse_tensor", "{", " 'cells': [] }"); } @Test public void tensor_modify_update_without_cells_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", "{", " 'operation': 'replace' }"); } @Test public void tensor_modify_update_with_unknown_content_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown JSON string 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", "{", " 'unknown': 'here' }"); } @Test public void tensor_add_update_on_sparse_tensor() { assertTensorAddUpdate("{{x:a,y:b}:2.0, {x:c,y:d}: 3.0}", "sparse_tensor", inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'd' }, 'value': 3.0 } ]}")); } @Test public void tensor_add_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorAddUpdate("{{x:a}:2.0, {x:c}: 3.0}", "sparse_single_dimension_tensor", inputJson("{", " 'cells': {", " 'a': 2.0,", " 'c': 3.0 }}")); } @Test public void tensor_add_update_on_mixed_tensor() { assertTensorAddUpdate("{{x:a,y:0}:2.0, {x:a,y:1}:3.0, {x:a,y:2}:0.0}", "mixed_tensor", inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 },", " { 'address': { 'x': 'a', 'y': '1' }, 'value': 3.0 } ]}")); } @Test public void tensor_add_update_on_mixed_with_out_of_bound_dense_cells_throws() { illegalTensorAddUpdate("Error in 'mixed_tensor': Index 3 out of bounds for length 3", "mixed_tensor", "{", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_add_update_on_dense_tensor_throws() { illegalTensorAddUpdate("Error in 'dense_tensor': An add update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", "{", " 'cells': [] }"); } @Test public void tensor_add_update_on_not_fully_specified_cell_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Missing a label for dimension 'y' for tensor(x{},y{})", "sparse_tensor", "{", " 'cells': [", " { 'address': { 'x': 'a' }, 'value': 2.0 } ]}"); } @Test public void tensor_add_update_without_cells_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Add update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", "{}"); illegalTensorAddUpdate("Error in 'mixed_tensor': Add update for field 'mixed_tensor' does not contain tensor cells", "mixed_tensor", "{}"); } @Test public void tensor_remove_update_on_sparse_tensor() { assertTensorRemoveUpdate("{{x:a,y:b}:1.0,{x:c,y:d}:1.0}", "sparse_tensor", inputJson("{", " 'addresses': [", " { 'x': 'a', 'y': 'b' },", " { 'x': 'c', 'y': 'd' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor() { assertTensorRemoveUpdate("{{x:1}:1.0,{x:2}:1.0}", "mixed_tensor", inputJson("{", " 'addresses': [", " { 'x': '1' },", " { 'x': '2' } ]}")); } @Test public void tensor_remove_update_on_sparse_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{y:b}:1.0,{y:d}:1.0}", "sparse_tensor", inputJson("{", " 'addresses': [", " { 'y': 'b' },", " { 'y': 'd' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{x:1,z:a}:1.0,{x:2,z:b}:1.0}", "mixed_tensor_adv", inputJson("{", " 'addresses': [", " { 'x': '1', 'z': 'a' },", " { 'x': '2', 'z': 'b' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor_with_dense_addresses_throws() { illegalTensorRemoveUpdate("Error in 'mixed_tensor': Indexed dimension address 'y' should not be specified in remove update", "mixed_tensor", "{", " 'addresses': [", " { 'x': '1', 'y': '0' },", " { 'x': '2', 'y': '0' } ]}"); } @Test public void tensor_remove_update_on_dense_tensor_throws() { illegalTensorRemoveUpdate("Error in 'dense_tensor': A remove update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", "{", " 'addresses': [] }"); } @Test public void tensor_remove_update_with_stray_dimension_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{},y{}) does not contain dimension 'foo'", "sparse_tensor", "{", " 'addresses': [", " { 'x': 'a', 'foo': 'b' } ]}"); illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{}) does not contain dimension 'foo'", "sparse_tensor", "{", " 'addresses': [", " { 'x': 'c' },", " { 'x': 'a', 'foo': 'b' } ]}"); } @Test public void tensor_remove_update_without_cells_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': Remove update for field 'sparse_tensor' does not contain tensor addresses", "sparse_tensor", "{'addresses': [] }"); illegalTensorRemoveUpdate("Error in 'mixed_tensor': Remove update for field 'mixed_tensor' does not contain tensor addresses", "mixed_tensor", "{'addresses': [] }"); } @Test public void require_that_parser_propagates_datatype_parser_errors_predicate() { assertParserErrorMatches( "Error in document 'id:unittest:testpredicate::0' - could not parse field 'boolean' of type 'predicate': " + "line 1:10 no viable alternative at character '>'", "[", " {", " 'fields': {", " 'boolean': 'timestamp > 9000'", " },", " 'put': 'id:unittest:testpredicate::0'", " }", "]" ); } @Test public void require_that_parser_propagates_datatype_parser_errors_string_as_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \" 1\"", "[", " {", " 'fields': {", " 'integerfield': ' 1'", " },", " 'put': 'id:unittest:testint::0'", " }", "]" ); } @Test public void require_that_parser_propagates_datatype_parser_errors_overflowing_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \"281474976710656\"", "[", " {", " 'fields': {", " 'integerfield': 281474976710656", " },", " 'put': 'id:unittest:testint::0'", " }", "]" ); } @Test public void requireThatUnknownDocTypeThrowsIllegalArgumentException() { final String jsonData = inputJson( "[", " {", " 'put': 'id:ns:walrus::walrus1',", " 'fields': {", " 'aField': 42", " }", " }", "]"); try { new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail(); } catch (IllegalArgumentException e) { assertEquals("Document type walrus does not exist", e.getMessage()); } } private static final String TENSOR_DOC_ID = "id:unittest:testtensor::0"; private void illegalTensorModifyUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorModifyUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorAddUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorAddUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorRemoveUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorRemoveUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private DocumentPut createPutWithoutTensor() { JsonReader reader = createReader(inputJson("[ { 'put': '" + TENSOR_DOC_ID + "', 'fields': { } } ]")); return (DocumentPut) reader.next(); } private DocumentPut createPutWithSparseTensor(String inputTensor) { return createPutWithTensor(inputTensor, "sparse_tensor"); } private DocumentPut createPutWithTensor(String inputTensor, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'put': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': " + inputTensor + " }}]")); return (DocumentPut) reader.next(); } private DocumentUpdate createAssignUpdateWithSparseTensor(String inputTensor) { return createAssignUpdateWithTensor(inputTensor, "sparse_tensor"); } private DocumentUpdate createAssignUpdateWithTensor(String inputTensor, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'update': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': {", " 'assign': " + (inputTensor != null ? inputTensor : "null") + " } } } ]")); return (DocumentUpdate) reader.next(); } private static Tensor assertSparseTensorField(String expectedTensor, DocumentPut put) { return assertTensorField(expectedTensor, put, "sparse_tensor"); } private static Tensor assertTensorField(String expectedTensor, DocumentPut put, String tensorFieldName) { return assertTensorField(Tensor.from(expectedTensor), put, tensorFieldName); } private static Tensor assertTensorField(Tensor expectedTensor, DocumentPut put, String tensorFieldName) { Document doc = put.getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals(TENSOR_DOC_ID, doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField(tensorFieldName)); assertEquals(expectedTensor, fieldValue.getTensor().get()); return fieldValue.getTensor().get(); } private static void assertTensorFieldUpdate(DocumentUpdate update, String tensorFieldName) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); assertEquals(1, update.fieldUpdates().size()); assertEquals(1, update.getFieldUpdate(tensorFieldName).size()); } private static void assertTensorAssignUpdateSparseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "sparse_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private static void assertTensorAssignUpdateDenseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "dense_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, String tensorFieldName, String modifyJson) { assertTensorModifyUpdate(expectedTensor, expectedOperation, tensorFieldName, createTensorModifyUpdate(modifyJson, tensorFieldName)); } private static void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorModifyUpdate modifyUpdate = (TensorModifyUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(expectedOperation, modifyUpdate.getOperation()); assertEquals(Tensor.from(expectedTensor), modifyUpdate.getValue().getTensor().get()); } private DocumentUpdate createTensorModifyUpdate(String modifyJson, String tensorFieldName) { return createTensorUpdate("modify", modifyJson, tensorFieldName); } private DocumentUpdate createTensorAddUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("add", tensorJson, tensorFieldName); } private DocumentUpdate createTensorRemoveUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("remove", tensorJson, tensorFieldName); } private DocumentUpdate createTensorUpdate(String operation, String tensorJson, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'update': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': {", " '" + operation + "': " + tensorJson + " }}}]")); return (DocumentUpdate) reader.next(); } private void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorAddUpdate(expectedTensor, tensorFieldName, createTensorAddUpdate(tensorJson, tensorFieldName)); } private static void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorAddUpdate addUpdate = (TensorAddUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), addUpdate.getValue().getTensor().get()); } private void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorRemoveUpdate(expectedTensor, tensorFieldName, createTensorRemoveUpdate(tensorJson, tensorFieldName)); } private static void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorRemoveUpdate removeUpdate = (TensorRemoveUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), removeUpdate.getValue().getTensor().get()); } private static FieldUpdate getTensorField(DocumentUpdate update) { return getTensorField(update, "sparse_tensor"); } private static FieldUpdate getTensorField(DocumentUpdate update, String fieldName) { FieldUpdate fieldUpdate = update.getFieldUpdate(fieldName); assertEquals(1, fieldUpdate.size()); return fieldUpdate; } // NOTE: Do not call this method multiple times from a test method as it's using the ExpectedException rule private void assertParserErrorMatches(String expectedError, String... json) { String jsonData = inputJson(json); try { new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail(); } catch (JsonReaderException e) { assertEquals(expectedError, e.getMessage()); } } private void assertCreatePutFails(String tensor, String name, String msg) { try { createPutWithTensor(inputJson(tensor), name); fail("Expected exception"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains(msg)); } } }
Ethnas/vespa
document/src/test/java/com/yahoo/document/json/JsonReaderTestCase.java
213,290
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.document.json; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.io.JsonStringEncoder; import com.google.common.base.Joiner; import com.yahoo.collections.Tuple2; import com.yahoo.document.ArrayDataType; import com.yahoo.document.DataType; import com.yahoo.document.Document; import com.yahoo.document.DocumentId; import com.yahoo.document.DocumentOperation; import com.yahoo.document.DocumentPut; import com.yahoo.document.DocumentRemove; import com.yahoo.document.DocumentType; import com.yahoo.document.DocumentTypeManager; import com.yahoo.document.DocumentUpdate; import com.yahoo.document.Field; import com.yahoo.document.MapDataType; import com.yahoo.document.PositionDataType; import com.yahoo.document.StructDataType; import com.yahoo.document.TensorDataType; import com.yahoo.document.WeightedSetDataType; import com.yahoo.document.datatypes.Array; import com.yahoo.document.datatypes.BoolFieldValue; import com.yahoo.document.datatypes.FieldValue; import com.yahoo.document.datatypes.IntegerFieldValue; import com.yahoo.document.datatypes.MapFieldValue; import com.yahoo.document.datatypes.Raw; import com.yahoo.document.datatypes.StringFieldValue; import com.yahoo.document.datatypes.Struct; import com.yahoo.document.datatypes.TensorFieldValue; import com.yahoo.document.datatypes.WeightedSet; import com.yahoo.document.internal.GeoPosType; import com.yahoo.document.json.readers.DocumentParseInfo; import com.yahoo.document.json.readers.VespaJsonDocumentReader; import com.yahoo.document.serialization.DocumentSerializer; import com.yahoo.document.serialization.DocumentSerializerFactory; import com.yahoo.document.update.AddValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate.Operator; import com.yahoo.document.update.AssignValueUpdate; import com.yahoo.document.update.ClearValueUpdate; import com.yahoo.document.update.FieldUpdate; import com.yahoo.document.update.MapValueUpdate; import com.yahoo.document.update.TensorAddUpdate; import com.yahoo.document.update.TensorModifyUpdate; import com.yahoo.document.update.TensorRemoveUpdate; import com.yahoo.document.update.ValueUpdate; import com.yahoo.io.GrowableByteBuffer; import com.yahoo.tensor.IndexedTensor; import com.yahoo.tensor.MappedTensor; import com.yahoo.tensor.MixedTensor; import com.yahoo.tensor.Tensor; import com.yahoo.tensor.TensorType; import com.yahoo.text.Utf8; import com.yahoo.yolean.Exceptions; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DECREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DIVIDE; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_INCREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_MULTIPLY; import static com.yahoo.test.json.JsonTestHelper.inputJson; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Basic test of JSON streams to Vespa document instances. * * @author Steinar Knutsen * @author bratseth */ public class JsonReaderTestCase { private DocumentTypeManager types; private JsonFactory parserFactory; @Before public void setUp() throws Exception { parserFactory = new JsonFactory(); types = new DocumentTypeManager(); { DocumentType x = new DocumentType("smoke"); x.addField(new Field("something", DataType.STRING)); x.addField(new Field("nalle", DataType.STRING)); x.addField(new Field("field1", DataType.STRING)); x.addField(new Field("field2", DataType.STRING)); x.addField(new Field("int1", DataType.INT)); x.addField(new Field("flag", DataType.BOOL)); x.addField(new Field("tensor1", DataType.getTensor(TensorType.fromSpec("tensor(x{})")))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("mirrors"); StructDataType woo = new StructDataType("woo"); woo.addField(new Field("sandra", DataType.STRING)); woo.addField(new Field("cloud", DataType.STRING)); x.addField(new Field("skuggsjaa", woo)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testarray"); DataType d = new ArrayDataType(DataType.STRING); x.addField(new Field("actualarray", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testset"); DataType d = new WeightedSetDataType(DataType.STRING, true, true); x.addField(new Field("actualset", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testmap"); DataType d = new MapDataType(DataType.STRING, DataType.STRING); x.addField(new Field("actualmap", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testraw"); DataType d = DataType.RAW; x.addField(new Field("actualraw", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testMapStringToArrayOfInt"); DataType value = new ArrayDataType(DataType.INT); DataType d = new MapDataType(DataType.STRING, value); x.addField(new Field("actualMapStringToArrayOfInt", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testsinglepos"); DataType d = PositionDataType.INSTANCE; x.addField(new Field("singlepos", d)); x.addField(new Field("geopos", new GeoPosType(8))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testtensor"); x.addField(new Field("sparse_single_dimension_tensor", new TensorDataType(new TensorType.Builder().mapped("x").build()))); x.addField(new Field("sparse_tensor", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").build()))); x.addField(new Field("dense_tensor", new TensorDataType(new TensorType.Builder().indexed("x", 2).indexed("y", 3).build()))); x.addField(new Field("dense_int8_tensor", new TensorDataType(TensorType.fromSpec("tensor<int8>(x[2],y[3])")))); x.addField(new Field("dense_unbound_tensor", new TensorDataType(new TensorType.Builder().indexed("x").indexed("y").build()))); x.addField(new Field("mixed_tensor", new TensorDataType(new TensorType.Builder().mapped("x").indexed("y", 3).build()))); x.addField(new Field("mixed_bfloat16_tensor", new TensorDataType(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")))); x.addField(new Field("mixed_tensor_adv", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").mapped("z").indexed("a", 3).build()))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testpredicate"); x.addField(new Field("boolean", DataType.PREDICATE)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testint"); x.addField(new Field("integerfield", DataType.INT)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testnull"); x.addField(new Field("intfield", DataType.INT)); x.addField(new Field("stringfield", DataType.STRING)); x.addField(new Field("arrayfield", new ArrayDataType(DataType.STRING))); x.addField(new Field("weightedsetfield", new WeightedSetDataType(DataType.STRING, true, true))); x.addField(new Field("mapfield", new MapDataType(DataType.STRING, DataType.STRING))); x.addField(new Field("tensorfield", new TensorDataType(new TensorType.Builder().indexed("x").build()))); types.registerDocumentType(x); } } @After public void tearDown() throws Exception { types = null; parserFactory = null; } private JsonReader createReader(String jsonInput) { InputStream input = new ByteArrayInputStream(Utf8.toBytes(jsonInput)); return new JsonReader(types, input, parserFactory); } @Test public void readSingleDocumentPut() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " }", "}")); DocumentPut put = (DocumentPut) r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:smoke::doc1").operation(); smokeTestDoc(put.getDocument()); } @Test public final void readSingleDocumentUpdate() { JsonReader r = createReader(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': {", " 'assign': 'orOther' }}}")); DocumentUpdate doc = (DocumentUpdate) r.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::whee").operation(); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof AssignValueUpdate); } @Test public void readClearField() { JsonReader r = createReader(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'int1': {", " 'assign': null }}}")); DocumentUpdate doc = (DocumentUpdate) r.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::whee").operation(); FieldUpdate f = doc.getFieldUpdate("int1"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof ClearValueUpdate); assertNull(f.getValueUpdate(0).getValue()); } @Test public void smokeTest() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } @Test public void docIdLookaheadTest() throws IOException { JsonReader r = createReader(inputJson( "{ 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " },", " 'put': 'id:unittest:smoke::doc1'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } @Test public void emptyDocTest() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::whee', 'fields': {}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); assertEquals("id:unittest:smoke::whee", parseInfo.documentId.toString()); } @Test public void testStruct() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:mirrors::whee',", " 'fields': {", " 'skuggsjaa': {", " 'sandra': 'person',", " 'cloud': 'another person' }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("skuggsjaa")); assertSame(Struct.class, f.getClass()); Struct s = (Struct) f; assertEquals("person", ((StringFieldValue) s.getFieldValue("sandra")).getString()); } private DocumentUpdate parseUpdate(String json) throws IOException { InputStream rawDoc = new ByteArrayInputStream(Utf8.toBytes(json)); JsonReader r = new JsonReader(types, rawDoc, parserFactory); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentUpdate update = new DocumentUpdate(docType, parseInfo.documentId); new VespaJsonDocumentReader(false).readUpdate(parseInfo.fieldsBuffer, update); return update; } @Test public void testStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(inputJson("{ 'update': 'id:unittest:mirrors:g=test:whee',", " 'create': true,", " 'fields': {", " 'skuggsjaa': {", " 'assign': {", " 'sandra': 'person',", " 'cloud': 'another person' }}}}")); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(2, s.getFieldCount()); assertEquals(new StringFieldValue("person"), s.getFieldValue(s.getField("sandra"))); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(107, buf.position()); } @Test public final void testEmptyStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(inputJson("{ 'update': 'id:unittest:mirrors:g=test:whee',", " 'create': true,", " 'fields': { ", " 'skuggsjaa': {", " 'assign': { } }}}")); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(0, s.getFieldCount()); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(69, buf.position()); } @Test public void testUpdateArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}}")); checkSimpleArrayAdd(doc); } @Test public void testUpdateWeighted() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'add': {", " 'person': 37,", " 'another person': 41 }}}}")); Map<String, Integer> weights = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; final String s = ((StringFieldValue) adder.getValue()).getString(); weights.put(s, adder.getWeight()); } assertEquals(2, weights.size()); final String o = "person"; final String o2 = "another person"; assertTrue(weights.containsKey(o)); assertTrue(weights.containsKey(o2)); assertEquals(Integer.valueOf(37), weights.get(o)); assertEquals(Integer.valueOf(41), weights.get(o2)); } @Test public void testUpdateMatch() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'match': {", " 'element': 'person',", " 'increment': 13 }}}}")); Map<String, Tuple2<Number, String>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); String op = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperator().toString(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()).getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertEquals("ADD", matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } @SuppressWarnings({ "cast", "unchecked", "rawtypes" }) @Test public void testArithmeticOperators() throws IOException { Tuple2[] operations = new Tuple2[] { new Tuple2<String, Operator>(UPDATE_DECREMENT, ArithmeticValueUpdate.Operator.SUB), new Tuple2<String, Operator>(UPDATE_DIVIDE, ArithmeticValueUpdate.Operator.DIV), new Tuple2<String, Operator>(UPDATE_INCREMENT, ArithmeticValueUpdate.Operator.ADD), new Tuple2<String, Operator>(UPDATE_MULTIPLY, ArithmeticValueUpdate.Operator.MUL) }; for (Tuple2<String, Operator> operator : operations) { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'match': {", " 'element': 'person',", " '" + (String) operator.first + "': 13 }}}}")); Map<String, Tuple2<Number, Operator>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); Operator op = ((ArithmeticValueUpdate) adder .getUpdate()).getOperator(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertSame(operator.second, matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } } @SuppressWarnings("rawtypes") @Test public void testArrayIndexing() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'match': {", " 'element': 3,", " 'assign': 'nalle' }}}}")); Map<Number, String> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualarray"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final Number key = ((IntegerFieldValue) adder.getValue()) .getNumber(); String op = ((StringFieldValue) ((AssignValueUpdate) adder.getUpdate()) .getValue()).getString(); matches.put(key, op); } assertEquals(1, matches.size()); Number n = Integer.valueOf(3); assertEquals("nalle", matches.get(n)); } @Test public void testDocumentRemove() { JsonReader r = createReader(inputJson("{'remove': 'id:unittest:smoke::whee'}")); DocumentType docType = r.readDocumentType(new DocumentId("id:unittest:smoke::whee")); assertEquals("smoke", docType.getName()); } private Document docFromJson(String json) throws IOException { JsonReader r = createReader(json); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); return put.getDocument(); } @Test public void testWeightedSet() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'nalle': 2,", " 'tralle': 7 }}}")); FieldValue f = doc.getFieldValue(doc.getField("actualset")); assertSame(WeightedSet.class, f.getClass()); WeightedSet<?> w = (WeightedSet<?>) f; assertEquals(2, w.size()); assertEquals(Integer.valueOf(2), w.get(new StringFieldValue("nalle"))); assertEquals(Integer.valueOf(7), w.get(new StringFieldValue("tralle"))); } @Test public void testArray() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': [", " 'nalle',", " 'tralle' ]}}")); FieldValue f = doc.getFieldValue(doc.getField("actualarray")); assertSame(Array.class, f.getClass()); Array<?> a = (Array<?>) f; assertEquals(2, a.size()); assertEquals(new StringFieldValue("nalle"), a.get(0)); assertEquals(new StringFieldValue("tralle"), a.get(1)); } @Test public void testMap() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testmap::whee',", " 'fields': {", " 'actualmap': {", " 'nalle': 'kalle',", " 'tralle': 'skalle' }}}")); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testOldMap() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testmap::whee',", " 'fields': {", " 'actualmap': [", " { 'key': 'nalle', 'value': 'kalle'},", " { 'key': 'tralle', 'value': 'skalle'} ]}}")); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testPositionPositive() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': 'N63.429722;E10.393333' }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionOld() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': {'x':10393333,'y':63429722} }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testGeoPosition() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': {'lat':63.429722,'lng':10.393333} }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testGeoPositionNoAbbreviations() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': {'latitude':63.429722,'longitude':10.393333} }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionGeoPos() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'geopos': 'N63.429722;E10.393333' }}")); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); } @Test public void testPositionOldGeoPos() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'geopos': {'x':10393333,'y':63429722} }}")); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); } @Test public void testGeoPositionGeoPos() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'geopos': {'lat':63.429722,'lng':10.393333} }}")); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); assertEquals(PositionDataType.INSTANCE, f.getDataType()); } @Test public void testPositionNegative() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': 'W46.63;S23.55' }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(-46630000, PositionDataType.getXValue(f).getInteger()); assertEquals(-23550000, PositionDataType.getYValue(f).getInteger()); } @Test public void testRaw() throws IOException { String base64 = new String(new JsonStringEncoder().quoteAsString( Base64.getEncoder().withoutPadding().encodeToString(Utf8.toBytes("smoketest")))); String s = fieldStringFromBase64RawContent(base64); assertEquals("smoketest", s); } @Test public void can_read_legacy_chunked_base64_raw_field_encoding() throws IOException { String expected = "this is a string with an impressive length. it's long enough to reach the end of the line, wow!"; String base64withDelims = "dGhpcyBpcyBhIHN0cmluZyB3aXRoIGFuIGltcHJlc3NpdmUgbGVuZ3RoLiBpdCdzIGxvbmcgZW5v\\r\\n" + "dWdoIHRvIHJlYWNoIHRoZSBlbmQgb2YgdGhlIGxpbmUsIHdvdyE=\\r\\n"; assertEquals(expected, fieldStringFromBase64RawContent(base64withDelims)); } private String fieldStringFromBase64RawContent(String base64data) throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testraw::whee',", " 'fields': {", " 'actualraw': '" + base64data + "' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("actualraw")); assertSame(Raw.class, f.getClass()); Raw s = (Raw) f; return Utf8.toString(s.getByteBuffer()); } @Test public void testMapStringToArrayOfInt() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'bamse': [1, 2, 3] }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldMapStringToArrayOfInt() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': [", " { 'key': 'bamse', 'value': [1, 2, 3] } ]}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToString() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': {", " 'assign': 'orOther' }}}")); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); AssignValueUpdate a = (AssignValueUpdate) f.getValueUpdate(0); assertEquals(new StringFieldValue("orOther"), a.getValue()); } @Test public void testAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'assign': { 'bamse': [1, 2, 3] }}}}")); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'assign': [", " { 'key': 'bamse', 'value': [1, 2, 3] } ]}}}")); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToWeightedSet() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'assign': {", " 'person': 37,", " 'another person': 41 }}}}")); FieldUpdate x = doc.getFieldUpdate("actualset"); assertEquals(1, x.size()); AssignValueUpdate assign = (AssignValueUpdate) x.getValueUpdate(0); WeightedSet<?> w = (WeightedSet<?>) assign.getValue(); assertEquals(2, w.size()); assertEquals(Integer.valueOf(37), w.get(new StringFieldValue("person"))); assertEquals(Integer.valueOf(41), w.get(new StringFieldValue("another person"))); } @Test public void testCompleteFeed() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }},", "{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}},", "{ 'remove': 'id:unittest:smoke::whee' }]")); controlBasicFeed(r); } @Test public void testCompleteFeedWithCreateAndCondition() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }},", "{", " 'condition':'bla',", " 'update': 'id:unittest:testarray::whee',", " 'create':true,", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}},", "{ 'remove': 'id:unittest:smoke::whee' }]")); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testUpdateWithConditionAndCreateInDifferentOrdering() { int documentsCreated = 106; List<String> parts = Arrays.asList( "\"condition\":\"bla\"", "\"update\": \"id:unittest:testarray::whee\"", " \"fields\": { " + "\"actualarray\": { \"add\": [" + " \"person\",\"another person\"]}}", " \"create\":true"); Random random = new Random(42); StringBuilder documents = new StringBuilder("["); for (int x = 0; x < documentsCreated; x++) { Collections.shuffle(parts, random); documents.append("{").append(Joiner.on(",").join(parts)).append("}"); if (x < documentsCreated -1) { documents.append(","); } } documents.append("]"); InputStream rawDoc = new ByteArrayInputStream( Utf8.toBytes(documents.toString())); JsonReader r = new JsonReader(types, rawDoc, parserFactory); for (int x = 0; x < documentsCreated; x++) { DocumentUpdate update = (DocumentUpdate) r.next(); checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); } assertNull(r.next()); } @Test public void testCreateIfNonExistentInPut() { JsonReader r = createReader(inputJson("[{", " 'create':true,", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse' },", " 'put': 'id:unittest:smoke::whee'", "}]")); var op = r.next(); var put = (DocumentPut) op; assertTrue(put.getCreateIfNonExistent()); } @Test public void testCompleteFeedWithIdAfterFields() { JsonReader r = createReader(inputJson("[", "{", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' },", " 'put': 'id:unittest:smoke::whee'", "},", "{", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}},", " 'update': 'id:unittest:testarray::whee'", "},", "{ 'remove': 'id:unittest:smoke::whee' }]")); controlBasicFeed(r); } protected void controlBasicFeed(JsonReader r) { DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testCompleteFeedWithEmptyDoc() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee', 'fields': {} },", "{ 'update': 'id:unittest:testarray::whee', 'fields': {} },", "{ 'remove': 'id:unittest:smoke::whee' }]")); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); assertEquals("smoke", doc.getId().getDocType()); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; assertEquals("testarray", update.getId().getDocType()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } private void checkSimpleArrayAdd(DocumentUpdate update) { Set<String> toAdd = new HashSet<>(); FieldUpdate x = update.getFieldUpdate("actualarray"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; toAdd.add(((StringFieldValue) adder.getValue()).getString()); } assertEquals(2, toAdd.size()); assertTrue(toAdd.contains("person")); assertTrue(toAdd.contains("another person")); } private void smokeTestDoc(Document doc) { FieldValue boolField = doc.getFieldValue(doc.getField("flag")); assertSame(BoolFieldValue.class, boolField.getClass()); assertTrue((Boolean)boolField.getWrappedValue()); FieldValue stringField = doc.getFieldValue(doc.getField("nalle")); assertSame(StringFieldValue.class, stringField.getClass()); assertEquals("bamse", ((StringFieldValue) stringField).getString()); } @Test public void nonExistingFieldCausesException() throws IOException { JsonReader r = createReader(inputJson( "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'smething': 'smoketest',", " 'nalle': 'bamse' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); try { new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); fail(); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().startsWith("No field 'smething' in the structure of type 'smoke'")); } } @Test public void nonExistingFieldsCanBeIgnoredInPut() throws IOException { JsonReader r = createReader(inputJson( "{ ", " 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'nonexisting1': 'ignored value',", " 'field1': 'value1',", " 'nonexisting2': {", " 'blocks':{", " 'a':[2.0,3.0],", " 'b':[4.0,5.0]", " }", " },", " 'field2': 'value2',", " 'nonexisting3': {", " 'cells': [{'address': {'x': 'x1'}, 'value': 1.0}]", " },", " 'tensor1': {'cells': {'x1': 1.0}},", " 'nonexisting4': 'ignored value'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); boolean fullyApplied = new VespaJsonDocumentReader(true).readPut(parseInfo.fieldsBuffer, put); assertFalse(fullyApplied); assertNull(put.getDocument().getField("nonexisting1")); assertEquals("value1", put.getDocument().getFieldValue("field1").toString()); assertNull(put.getDocument().getField("nonexisting2")); assertEquals("value2", put.getDocument().getFieldValue("field2").toString()); assertNull(put.getDocument().getField("nonexisting3")); assertEquals(Tensor.from("tensor(x{}):{{x:x1}:1.0}"), put.getDocument().getFieldValue("tensor1").getWrappedValue()); assertNull(put.getDocument().getField("nonexisting4")); } @Test public void nonExistingFieldsCanBeIgnoredInUpdate() throws IOException{ JsonReader r = createReader(inputJson( "{ ", " 'update': 'id:unittest:smoke::doc1',", " 'fields': {", " 'nonexisting1': { 'assign': 'ignored value' },", " 'field1': { 'assign': 'value1' },", " 'nonexisting2': { " + " 'assign': {", " 'blocks': {", " 'a':[2.0,3.0],", " 'b':[4.0,5.0]", " }", " }", " },", " 'field2': { 'assign': 'value2' },", " 'nonexisting3': {", " 'assign' : {", " 'cells': [{'address': {'x': 'x1'}, 'value': 1.0}]", " }", " },", " 'tensor1': {'assign': { 'cells': {'x1': 1.0} } },", " 'nonexisting4': { 'assign': 'ignored value' }", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentUpdate update = new DocumentUpdate(docType, parseInfo.documentId); boolean fullyApplied = new VespaJsonDocumentReader(true).readUpdate(parseInfo.fieldsBuffer, update); assertFalse(fullyApplied); assertNull(update.getFieldUpdate("nonexisting1")); assertEquals("value1", update.getFieldUpdate("field1").getValueUpdates().get(0).getValue().getWrappedValue().toString()); assertNull(update.getFieldUpdate("nonexisting2")); assertEquals("value2", update.getFieldUpdate("field2").getValueUpdates().get(0).getValue().getWrappedValue().toString()); assertNull(update.getFieldUpdate("nonexisting3")); assertEquals(Tensor.from("tensor(x{}):{{x:x1}:1.0}"), update.getFieldUpdate("tensor1").getValueUpdates().get(0).getValue().getWrappedValue()); assertNull(update.getFieldUpdate("nonexisting4")); } @Test public void feedWithBasicErrorTest() { JsonReader r = createReader(inputJson("[", " { 'put': 'id:test:smoke::0', 'fields': { 'something': 'foo' } },", " { 'put': 'id:test:smoke::1', 'fields': { 'something': 'foo' } },", " { 'put': 'id:test:smoke::2', 'fields': { 'something': 'foo' } },", "]")); try { while (r.next() != null) ; fail(); } catch (RuntimeException e) { assertTrue(e.getMessage().contains("JsonParseException")); } } @Test public void idAsAliasForPutTest() throws IOException{ JsonReader r = createReader(inputJson("{ 'id': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); boolean fullyApplied = new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); assertTrue(fullyApplied); smokeTestDoc(put.getDocument()); } private void testFeedWithTestAndSetCondition(String jsonDoc) { ByteArrayInputStream parseInfoDoc = new ByteArrayInputStream(Utf8.toBytes(jsonDoc)); JsonReader reader = new JsonReader(types, parseInfoDoc, parserFactory); int NUM_OPERATIONS_IN_FEED = 3; for (int i = 0; i < NUM_OPERATIONS_IN_FEED; i++) { DocumentOperation operation = reader.next(); assertTrue("A test and set condition should be present", operation.getCondition().isPresent()); assertEquals("DocumentOperation's test and set condition should be equal to the one in the JSON feed", "smoke.something == \"smoketest\"", operation.getCondition().getSelection()); } assertNull(reader.next()); } @Test public void testFeedWithTestAndSetConditionOrderingOne() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'put': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " }", " },", " {", " 'update': 'id:unittest:testarray::whee',", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " },", " {", " 'remove': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\''", " }", "]" )); } @Test public void testFeedWithTestAndSetConditionOrderingTwo() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " }", " },", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " },", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'remove': 'id:unittest:smoke::whee'", " }", "]" )); } @Test public void testFeedWithTestAndSetConditionOrderingThree() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " },", " 'condition': 'smoke.something == \\'smoketest\\''", " },", " {", " 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " },", " 'condition': 'smoke.something == \\'smoketest\\''", " },", " {", " 'remove': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\''", " }", "]" )); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldAfterFieldsFieldShouldFailParse() { final String jsonData = inputJson( "[", " {", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " },", " 'bjarne': 'stroustrup'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldBeforeFieldsFieldShouldFailParse() { final String jsonData = inputJson( "[", " {", " 'update': 'id:unittest:testarray::whee',", " 'what is this': 'nothing to see here',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldWithoutFieldsFieldShouldFailParse() { String jsonData = inputJson( "[", " {", " 'remove': 'id:unittest:smoke::whee',", " 'what is love': 'baby, do not hurt me... much'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test public void testMissingOperation() { try { String jsonData = inputJson( "[", " {", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Missing a document operation ('put', 'update' or 'remove')", e.getMessage()); } } @Test public void testMissingFieldsMapInPut() { try { String jsonData = inputJson( "[", " {", " 'put': 'id:unittest:smoke::whee'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("put of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testMissingFieldsMapInUpdate() { try { String jsonData = inputJson( "[", " {", " 'update': 'id:unittest:smoke::whee'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Update of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testNullValues() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testnull::doc1',", " 'fields': {", " 'intfield': null,", " 'stringfield': null,", " 'arrayfield': null,", " 'weightedsetfield': null,", " 'mapfield': null,", " 'tensorfield': null", " }", "}")); DocumentPut put = (DocumentPut) r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:testnull::doc1").operation(); Document doc = put.getDocument(); assertFieldValueNull(doc, "intfield"); assertFieldValueNull(doc, "stringfield"); assertFieldValueNull(doc, "arrayfield"); assertFieldValueNull(doc, "weightedsetfield"); assertFieldValueNull(doc, "mapfield"); assertFieldValueNull(doc, "tensorfield"); } @Test(expected=JsonReaderException.class) public void testNullArrayElement() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testnull::doc1',", " 'fields': {", " 'arrayfield': [ null ]", " }", "}")); r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:testnull::doc1"); fail(); } private void assertFieldValueNull(Document doc, String fieldName) { Field field = doc.getField(fieldName); assertNotNull(field); FieldValue fieldValue = doc.getFieldValue(field); assertNull(fieldValue); } static ByteArrayInputStream jsonToInputStream(String json) { return new ByteArrayInputStream(Utf8.toBytes(json)); } @Test public void testParsingWithoutTensorField() { Document doc = createPutWithoutTensor().getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals("id:unittest:testtensor::0", doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField("sparse_tensor")); assertNull(fieldValue); } @Test public void testParsingOfEmptyTensor() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor("{}")); } @Test public void testParsingOfTensorWithEmptyCells() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor(inputJson("{ 'cells': [] }"))); } @Test public void testDisallowedDenseTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{ 'values': [] }"), "dense_tensor", "The 'values' array does not contain any values"); assertCreatePutFails(inputJson("{ 'values': '' }"), "dense_tensor", "The 'values' string does not contain any values"); } @Test public void testDisallowedMixedTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{\"blocks\":{ \"a\": [] } }"), "mixed_tensor", "Expected 3 values, but got 0"); assertCreatePutFails(inputJson("{\"blocks\":[ {\"address\":{\"x\":\"a\"}, \"values\": [] } ] }"), "mixed_tensor", "Expected 3 values, but got 0"); } @Test public void testParsingOfSparseTensorWithCells() { Tensor tensor = assertSparseTensorField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createPutWithSparseTensor( """ { "type": "tensor(x{},y{})", "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 }, { "address": { "x": "c", "y": "b" }, "value": 3.0 } ] } """)); assertTrue(tensor instanceof MappedTensor); // any functional instance is fine } @Test public void testParsingOfDenseTensorWithCells() { Tensor tensor = assertTensorField("{{x:0,y:0}:2.0,{x:1,y:0}:3.0}}", createPutWithTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' },", " 'value': 2.0 },", " { 'address': { 'x': '1', 'y': '0' },", " 'value': 3.0 }", " ]", "}"), "dense_unbound_tensor"), "dense_unbound_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorOnDenseForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson("{", " 'values': [2.0, 3.0, 4.0, 5.0, 6.0, 7.0]", "}"), "dense_tensor"), "dense_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<int8>(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson("{", " 'values': \"020304050607\"", "}"), "dense_int8_tensor"), "dense_int8_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfMixedTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")); builder.cell().label("x", "foo").label("y", 0).value(2.0); builder.cell().label("x", "foo").label("y", 1).value(3.0); builder.cell().label("x", "foo").label("y", 2).value(4.0); builder.cell().label("x", "bar").label("y", 0).value(5.0); builder.cell().label("x", "bar").label("y", 1).value(6.0); builder.cell().label("x", "bar").label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":[" + "{\"address\":{\"x\":\"foo\"},\"values\":\"400040404080\"}," + "{\"address\":{\"x\":\"bar\"},\"values\":\"40A040C040E0\"}" + "]}"; var put = createPutWithTensor(inputJson(mixedJson), "mixed_bfloat16_tensor"); Tensor tensor = assertTensorField(expected, put, "mixed_bfloat16_tensor"); } /** Tests parsing of various tensor values set at the root, i.e. no 'cells', 'blocks' or 'values' */ @Test public void testDirectValue() { assertTensorField("tensor(x{}):{a:2, b:3}", "sparse_single_dimension_tensor", "{'a':2.0, 'b':3.0}"); assertTensorField("tensor(x[2],y[3]):[2, 3, 4, 5, 6, 7]]", "dense_tensor", "[2, 3, 4, 5, 6, 7]"); assertTensorField("tensor(x[2],y[3]):[2, 3, 4, 5, 6, 7]]", "dense_tensor", "[[2, 3, 4], [5, 6, 7]]"); assertTensorField("tensor(x{},y[3]):{a:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'a':[2, 3, 4], 'b':[4, 5, 6]}"); assertTensorField("tensor(x{},y{}):{{x:a,y:0}:2, {x:b,y:1}:3}", "sparse_tensor", "[{'address':{'x':'a','y':'0'},'value':2}, {'address':{'x':'b','y':'1'},'value':3}]"); } @Test public void testDirectValueReservedNameKeys() { // Single-valued assertTensorField("tensor(x{}):{cells:2, b:3}", "sparse_single_dimension_tensor", "{'cells':2.0, 'b':3.0}"); assertTensorField("tensor(x{}):{values:2, b:3}", "sparse_single_dimension_tensor", "{'values':2.0, 'b':3.0}"); assertTensorField("tensor(x{}):{block:2, b:3}", "sparse_single_dimension_tensor", "{'block':2.0, 'b':3.0}"); // Multi-valued assertTensorField("tensor(x{},y[3]):{cells:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'cells':[2, 3, 4], 'b':[4, 5, 6]}"); assertTensorField("tensor(x{},y[3]):{values:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'values':[2, 3, 4], 'b':[4, 5, 6]}"); assertTensorField("tensor(x{},y[3]):{block:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'block':[2, 3, 4], 'b':[4, 5, 6]}"); } @Test public void testParsingOfMixedTensorOnMixedForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = """ { "blocks":[ {"address":{"x":"0"},"values":[2.0,3.0,4.0]}, {"address":{"x":"1"},"values":[5.0,6.0,7.0]} ] } """; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance String mixedJsonDirect = """ [ {"address":{"x":"0","y":"0"},"value":2.0}, {"address":{"x":"0","y":"1"},"value":3.0}, {"address":{"x":"0","y":"2"},"value":4.0}, {"address":{"x":"1","y":"0"},"value":5.0}, {"address":{"x":"1","y":"1"},"value":6.0}, {"address":{"x":"1","y":"2"},"value":7.0} ] """; Tensor tensorDirect = assertTensorField(expected, createPutWithTensor(inputJson(mixedJsonDirect), "mixed_tensor"), "mixed_tensor"); assertTrue(tensorDirect instanceof MixedTensor); // this matters for performance } @Test public void testMixedTensorInMixedFormWithSingleSparseDimensionShortForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":{" + "\"0\":[2.0,3.0,4.0]," + "\"1\":[5.0,6.0,7.0]" + "}}"; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance } @Test public void testParsingOfTensorWithSingleCellInDifferentJsonOrder() { assertSparseTensorField("{{x:a,y:b}:2.0}", createPutWithSparseTensor(inputJson("{", " 'cells': [", " { 'value': 2.0,", " 'address': { 'x': 'a', 'y': 'b' } }", " ]", "}"))); } @Test public void testAssignUpdateOfEmptySparseTensor() { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithSparseTensor("{}")); } @Test public void testAssignUpdateOfEmptyDenseTensor() { try { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithTensor("{}", "dense_unbound_tensor")); } catch (IllegalArgumentException e) { assertEquals("An indexed tensor must have a value", "Error in 'dense_unbound_tensor': Tensor of type tensor(x[],y[]) has no values", Exceptions.toMessageString(e)); } } @Test public void testAssignUpdateOfNullTensor() { ClearValueUpdate clearUpdate = (ClearValueUpdate) getTensorField(createAssignUpdateWithSparseTensor(null)).getValueUpdate(0); assertNotNull(clearUpdate); assertNull(clearUpdate.getValue()); } @Test public void testAssignUpdateOfTensorWithCells() { assertTensorAssignUpdateSparseField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createAssignUpdateWithSparseTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' },", " 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'b' },", " 'value': 3.0 }", " ]", "}"))); } @Test public void testAssignUpdateOfTensorDenseShortForm() { assertTensorAssignUpdateDenseField("tensor(x[2],y[3]):[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]", createAssignUpdateWithTensor(inputJson("{", " 'values': [1,2,3,4,5,6]", "}"), "dense_tensor")); } @Test public void tensor_modify_update_with_replace_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_add_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, "sparse_tensor", inputJson("{", " 'operation': 'add',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_multiply_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "sparse_tensor", inputJson("{", " 'operation': 'multiply',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_create_non_existing_cells_true() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, true, "sparse_tensor", inputJson("{", " 'operation': 'add',", " 'create': true,", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_create_non_existing_cells_false() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, false, "sparse_tensor", inputJson("{", " 'operation': 'add',", " 'create': false,", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_treats_the_input_tensor_as_sparse() { // Note that the type of the tensor in the modify update is sparse (it only has mapped dimensions). assertTensorModifyUpdate("tensor(x{},y{}):{{x:0,y:0}:2.0, {x:1,y:2}:3.0}", TensorModifyUpdate.Operation.REPLACE, "dense_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' }, 'value': 2.0 },", " { 'address': { 'x': '1', 'y': '2' }, 'value': 3.0 } ]}")); } @Test public void tensor_modify_update_on_non_tensor_field_throws() { try { JsonReader reader = createReader(inputJson("{ 'update': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': {", " 'modify': {} }}}")); reader.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::doc1"); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Error in 'something': A modify update can only be applied to tensor fields. Field 'something' is of type 'string'", Exceptions.toMessageString(e)); } } @Test public void tensor_modify_update_on_dense_unbound_tensor_throws() { illegalTensorModifyUpdate("Error in 'dense_unbound_tensor': A modify update cannot be applied to tensor types with indexed unbound dimensions. Field 'dense_unbound_tensor' has unsupported tensor type 'tensor(x[],y[])'", "dense_unbound_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorModifyUpdate("{{x:a}:2.0, {x:c}: 3.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_single_dimension_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': {", " 'a': 2.0,", " 'c': 3.0 }}")); } @Test public void tensor_modify_update_with_replace_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_array() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': [", " { 'address': { 'x': 'a' }, 'values': [1,2,3] } ]}")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_must_specify_full_subspace() { illegalTensorModifyUpdate("Error in 'mixed_tensor': At {x:a}: Expected 3 values, but got 2", "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': {", " 'a': [2,3] } }")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_map() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': {", " 'a': [1,2,3] } }")); } @Test public void tensor_modify_update_with_add_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.ADD, "mixed_tensor", inputJson("{", " 'operation': 'add',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_multiply_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "mixed_tensor", inputJson("{", " 'operation': 'multiply',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws() { illegalTensorModifyUpdate("Error in 'dense_tensor': Dimension 'y' has label '3' but type is tensor(x[2],y[3])", "dense_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws_mixed() { illegalTensorModifyUpdate("Error in 'mixed_tensor': Dimension 'y' has label '3' but type is tensor(x{},y[3])", "mixed_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_with_unknown_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown operation 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", "{", " 'operation': 'unknown',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_without_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain an operation", "sparse_tensor", "{", " 'cells': [] }"); } @Test public void tensor_modify_update_without_cells_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", "{", " 'operation': 'replace' }"); } @Test public void tensor_modify_update_with_unknown_content_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown JSON string 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", "{", " 'unknown': 'here' }"); } @Test public void tensor_add_update_on_sparse_tensor() { assertTensorAddUpdate("{{x:a,y:b}:2.0, {x:c,y:d}: 3.0}", "sparse_tensor", inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'd' }, 'value': 3.0 } ]}")); } @Test public void tensor_add_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorAddUpdate("{{x:a}:2.0, {x:c}: 3.0}", "sparse_single_dimension_tensor", inputJson("{", " 'cells': {", " 'a': 2.0,", " 'c': 3.0 }}")); } @Test public void tensor_add_update_on_mixed_tensor() { assertTensorAddUpdate("{{x:a,y:0}:2.0, {x:a,y:1}:3.0, {x:a,y:2}:0.0}", "mixed_tensor", inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 },", " { 'address': { 'x': 'a', 'y': '1' }, 'value': 3.0 } ]}")); } @Test public void tensor_add_update_on_mixed_with_out_of_bound_dense_cells_throws() { illegalTensorAddUpdate("Error in 'mixed_tensor': Index 3 out of bounds for length 3", "mixed_tensor", "{", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_add_update_on_dense_tensor_throws() { illegalTensorAddUpdate("Error in 'dense_tensor': An add update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", "{", " 'cells': [] }"); } @Test public void tensor_add_update_on_not_fully_specified_cell_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Missing a label for dimension 'y' for tensor(x{},y{})", "sparse_tensor", "{", " 'cells': [", " { 'address': { 'x': 'a' }, 'value': 2.0 } ]}"); } @Test public void tensor_add_update_without_cells_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Add update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", "{}"); illegalTensorAddUpdate("Error in 'mixed_tensor': Add update for field 'mixed_tensor' does not contain tensor cells", "mixed_tensor", "{}"); } @Test public void tensor_remove_update_on_sparse_tensor() { assertTensorRemoveUpdate("{{x:a,y:b}:1.0,{x:c,y:d}:1.0}", "sparse_tensor", inputJson("{", " 'addresses': [", " { 'x': 'a', 'y': 'b' },", " { 'x': 'c', 'y': 'd' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor() { assertTensorRemoveUpdate("{{x:1}:1.0,{x:2}:1.0}", "mixed_tensor", inputJson("{", " 'addresses': [", " { 'x': '1' },", " { 'x': '2' } ]}")); } @Test public void tensor_remove_update_on_sparse_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{y:b}:1.0,{y:d}:1.0}", "sparse_tensor", inputJson("{", " 'addresses': [", " { 'y': 'b' },", " { 'y': 'd' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{x:1,z:a}:1.0,{x:2,z:b}:1.0}", "mixed_tensor_adv", inputJson("{", " 'addresses': [", " { 'x': '1', 'z': 'a' },", " { 'x': '2', 'z': 'b' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor_with_dense_addresses_throws() { illegalTensorRemoveUpdate("Error in 'mixed_tensor': Indexed dimension address 'y' should not be specified in remove update", "mixed_tensor", "{", " 'addresses': [", " { 'x': '1', 'y': '0' },", " { 'x': '2', 'y': '0' } ]}"); } @Test public void tensor_remove_update_on_dense_tensor_throws() { illegalTensorRemoveUpdate("Error in 'dense_tensor': A remove update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", "{", " 'addresses': [] }"); } @Test public void tensor_remove_update_with_stray_dimension_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{},y{}) does not contain dimension 'foo'", "sparse_tensor", "{", " 'addresses': [", " { 'x': 'a', 'foo': 'b' } ]}"); illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{}) does not contain dimension 'foo'", "sparse_tensor", "{", " 'addresses': [", " { 'x': 'c' },", " { 'x': 'a', 'foo': 'b' } ]}"); } @Test public void tensor_remove_update_without_cells_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': Remove update for field 'sparse_tensor' does not contain tensor addresses", "sparse_tensor", "{'addresses': [] }"); illegalTensorRemoveUpdate("Error in 'mixed_tensor': Remove update for field 'mixed_tensor' does not contain tensor addresses", "mixed_tensor", "{'addresses': [] }"); } @Test public void require_that_parser_propagates_datatype_parser_errors_predicate() { assertParserErrorMatches( "Error in document 'id:unittest:testpredicate::0' - could not parse field 'boolean' of type 'predicate': " + "line 1:10 no viable alternative at character '>'", "[", " {", " 'fields': {", " 'boolean': 'timestamp > 9000'", " },", " 'put': 'id:unittest:testpredicate::0'", " }", "]" ); } @Test public void require_that_parser_propagates_datatype_parser_errors_string_as_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \" 1\"", "[", " {", " 'fields': {", " 'integerfield': ' 1'", " },", " 'put': 'id:unittest:testint::0'", " }", "]" ); } @Test public void require_that_parser_propagates_datatype_parser_errors_overflowing_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \"281474976710656\"", "[", " {", " 'fields': {", " 'integerfield': 281474976710656", " },", " 'put': 'id:unittest:testint::0'", " }", "]" ); } @Test public void requireThatUnknownDocTypeThrowsIllegalArgumentException() { final String jsonData = inputJson( "[", " {", " 'put': 'id:ns:walrus::walrus1',", " 'fields': {", " 'aField': 42", " }", " }", "]"); try { new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail(); } catch (IllegalArgumentException e) { assertEquals("Document type walrus does not exist", e.getMessage()); } } private static final String TENSOR_DOC_ID = "id:unittest:testtensor::0"; private void illegalTensorModifyUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorModifyUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorAddUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorAddUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorRemoveUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorRemoveUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private DocumentPut createPutWithoutTensor() { JsonReader reader = createReader(inputJson("[ { 'put': '" + TENSOR_DOC_ID + "', 'fields': { } } ]")); return (DocumentPut) reader.next(); } private DocumentPut createPutWithSparseTensor(String inputTensor) { return createPutWithTensor(inputTensor, "sparse_tensor"); } private DocumentPut createPutWithTensor(String inputTensor, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'put': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': " + inputTensor + " }}]")); return (DocumentPut) reader.next(); } private DocumentUpdate createAssignUpdateWithSparseTensor(String inputTensor) { return createAssignUpdateWithTensor(inputTensor, "sparse_tensor"); } private DocumentUpdate createAssignUpdateWithTensor(String inputTensor, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'update': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': {", " 'assign': " + (inputTensor != null ? inputTensor : "null") + " } } } ]")); return (DocumentUpdate) reader.next(); } private static Tensor assertSparseTensorField(String expectedTensor, DocumentPut put) { return assertTensorField(expectedTensor, put, "sparse_tensor"); } private Tensor assertTensorField(String expectedTensor, String fieldName, String inputJson) { return assertTensorField(expectedTensor, createPutWithTensor(inputJson, fieldName), fieldName); } private static Tensor assertTensorField(String expectedTensor, DocumentPut put, String tensorFieldName) { return assertTensorField(Tensor.from(expectedTensor), put, tensorFieldName); } private static Tensor assertTensorField(Tensor expectedTensor, DocumentPut put, String tensorFieldName) { Document doc = put.getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals(TENSOR_DOC_ID, doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField(tensorFieldName)); assertEquals(expectedTensor, fieldValue.getTensor().get()); return fieldValue.getTensor().get(); } private static void assertTensorFieldUpdate(DocumentUpdate update, String tensorFieldName) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); assertEquals(1, update.fieldUpdates().size()); assertEquals(1, update.getFieldUpdate(tensorFieldName).size()); } private static void assertTensorAssignUpdateSparseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "sparse_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private static void assertTensorAssignUpdateDenseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "dense_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, String tensorFieldName, String modifyJson) { assertTensorModifyUpdate(expectedTensor, expectedOperation, false, tensorFieldName, createTensorModifyUpdate(modifyJson, tensorFieldName)); } private void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, boolean expectedCreateNonExistingCells, String tensorFieldName, String modifyJson) { assertTensorModifyUpdate(expectedTensor, expectedOperation, expectedCreateNonExistingCells, tensorFieldName, createTensorModifyUpdate(modifyJson, tensorFieldName)); } private static void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, boolean expectedCreateNonExistingCells, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorModifyUpdate modifyUpdate = (TensorModifyUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(expectedOperation, modifyUpdate.getOperation()); assertEquals(Tensor.from(expectedTensor), modifyUpdate.getValue().getTensor().get()); assertEquals(expectedCreateNonExistingCells, modifyUpdate.getCreateNonExistingCells()); } private DocumentUpdate createTensorModifyUpdate(String modifyJson, String tensorFieldName) { return createTensorUpdate("modify", modifyJson, tensorFieldName); } private DocumentUpdate createTensorAddUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("add", tensorJson, tensorFieldName); } private DocumentUpdate createTensorRemoveUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("remove", tensorJson, tensorFieldName); } private DocumentUpdate createTensorUpdate(String operation, String tensorJson, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'update': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': {", " '" + operation + "': " + tensorJson + " }}}]")); return (DocumentUpdate) reader.next(); } private void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorAddUpdate(expectedTensor, tensorFieldName, createTensorAddUpdate(tensorJson, tensorFieldName)); } private static void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorAddUpdate addUpdate = (TensorAddUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), addUpdate.getValue().getTensor().get()); } private void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorRemoveUpdate(expectedTensor, tensorFieldName, createTensorRemoveUpdate(tensorJson, tensorFieldName)); } private static void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorRemoveUpdate removeUpdate = (TensorRemoveUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), removeUpdate.getValue().getTensor().get()); } private static FieldUpdate getTensorField(DocumentUpdate update) { return getTensorField(update, "sparse_tensor"); } private static FieldUpdate getTensorField(DocumentUpdate update, String fieldName) { FieldUpdate fieldUpdate = update.getFieldUpdate(fieldName); assertEquals(1, fieldUpdate.size()); return fieldUpdate; } // NOTE: Do not call this method multiple times from a test method as it's using the ExpectedException rule private void assertParserErrorMatches(String expectedError, String... json) { String jsonData = inputJson(json); try { new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail(); } catch (JsonReaderException e) { assertEquals(expectedError, e.getMessage()); } } private void assertCreatePutFails(String tensor, String name, String msg) { try { createPutWithTensor(inputJson(tensor), name); fail("Expected exception"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains(msg)); } } }
ready-research/vespa
document/src/test/java/com/yahoo/document/json/JsonReaderTestCase.java
213,291
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.document.json; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.io.JsonStringEncoder; import com.google.common.base.Joiner; import com.yahoo.collections.Tuple2; import com.yahoo.document.ArrayDataType; import com.yahoo.document.DataType; import com.yahoo.document.Document; import com.yahoo.document.DocumentId; import com.yahoo.document.DocumentOperation; import com.yahoo.document.DocumentPut; import com.yahoo.document.DocumentRemove; import com.yahoo.document.DocumentType; import com.yahoo.document.DocumentTypeManager; import com.yahoo.document.DocumentUpdate; import com.yahoo.document.Field; import com.yahoo.document.MapDataType; import com.yahoo.document.PositionDataType; import com.yahoo.document.StructDataType; import com.yahoo.document.TensorDataType; import com.yahoo.document.WeightedSetDataType; import com.yahoo.document.datatypes.Array; import com.yahoo.document.datatypes.BoolFieldValue; import com.yahoo.document.datatypes.FieldValue; import com.yahoo.document.datatypes.IntegerFieldValue; import com.yahoo.document.datatypes.MapFieldValue; import com.yahoo.document.datatypes.Raw; import com.yahoo.document.datatypes.StringFieldValue; import com.yahoo.document.datatypes.Struct; import com.yahoo.document.datatypes.TensorFieldValue; import com.yahoo.document.datatypes.WeightedSet; import com.yahoo.document.internal.GeoPosType; import com.yahoo.document.json.readers.DocumentParseInfo; import com.yahoo.document.json.readers.VespaJsonDocumentReader; import com.yahoo.document.serialization.DocumentSerializer; import com.yahoo.document.serialization.DocumentSerializerFactory; import com.yahoo.document.update.AddValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate.Operator; import com.yahoo.document.update.AssignValueUpdate; import com.yahoo.document.update.ClearValueUpdate; import com.yahoo.document.update.FieldUpdate; import com.yahoo.document.update.MapValueUpdate; import com.yahoo.document.update.TensorAddUpdate; import com.yahoo.document.update.TensorModifyUpdate; import com.yahoo.document.update.TensorRemoveUpdate; import com.yahoo.document.update.ValueUpdate; import com.yahoo.io.GrowableByteBuffer; import com.yahoo.tensor.IndexedTensor; import com.yahoo.tensor.MappedTensor; import com.yahoo.tensor.MixedTensor; import com.yahoo.tensor.Tensor; import com.yahoo.tensor.TensorType; import com.yahoo.text.Utf8; import com.yahoo.yolean.Exceptions; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DECREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DIVIDE; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_INCREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_MULTIPLY; import static com.yahoo.test.json.JsonTestHelper.inputJson; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Basic test of JSON streams to Vespa document instances. * * @author Steinar Knutsen * @author bratseth */ public class JsonReaderTestCase { private DocumentTypeManager types; private JsonFactory parserFactory; @Before public void setUp() throws Exception { parserFactory = new JsonFactory(); types = new DocumentTypeManager(); { DocumentType x = new DocumentType("smoke"); x.addField(new Field("something", DataType.STRING)); x.addField(new Field("nalle", DataType.STRING)); x.addField(new Field("field1", DataType.STRING)); x.addField(new Field("field2", DataType.STRING)); x.addField(new Field("int1", DataType.INT)); x.addField(new Field("flag", DataType.BOOL)); x.addField(new Field("tensor1", DataType.getTensor(TensorType.fromSpec("tensor(x{})")))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("mirrors"); StructDataType woo = new StructDataType("woo"); woo.addField(new Field("sandra", DataType.STRING)); woo.addField(new Field("cloud", DataType.STRING)); x.addField(new Field("skuggsjaa", woo)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testarray"); DataType d = new ArrayDataType(DataType.STRING); x.addField(new Field("actualarray", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testset"); DataType d = new WeightedSetDataType(DataType.STRING, true, true); x.addField(new Field("actualset", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testmap"); DataType d = new MapDataType(DataType.STRING, DataType.STRING); x.addField(new Field("actualmap", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testraw"); DataType d = DataType.RAW; x.addField(new Field("actualraw", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testMapStringToArrayOfInt"); DataType value = new ArrayDataType(DataType.INT); DataType d = new MapDataType(DataType.STRING, value); x.addField(new Field("actualMapStringToArrayOfInt", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testsinglepos"); DataType d = PositionDataType.INSTANCE; x.addField(new Field("singlepos", d)); x.addField(new Field("geopos", new GeoPosType(8))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testtensor"); x.addField(new Field("sparse_single_dimension_tensor", new TensorDataType(new TensorType.Builder().mapped("x").build()))); x.addField(new Field("sparse_tensor", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").build()))); x.addField(new Field("dense_tensor", new TensorDataType(new TensorType.Builder().indexed("x", 2).indexed("y", 3).build()))); x.addField(new Field("dense_int8_tensor", new TensorDataType(TensorType.fromSpec("tensor<int8>(x[2],y[3])")))); x.addField(new Field("dense_unbound_tensor", new TensorDataType(new TensorType.Builder().indexed("x").indexed("y").build()))); x.addField(new Field("mixed_tensor", new TensorDataType(new TensorType.Builder().mapped("x").indexed("y", 3).build()))); x.addField(new Field("mixed_bfloat16_tensor", new TensorDataType(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")))); x.addField(new Field("mixed_tensor_adv", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").mapped("z").indexed("a", 3).build()))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testpredicate"); x.addField(new Field("boolean", DataType.PREDICATE)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testint"); x.addField(new Field("integerfield", DataType.INT)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testnull"); x.addField(new Field("intfield", DataType.INT)); x.addField(new Field("stringfield", DataType.STRING)); x.addField(new Field("arrayfield", new ArrayDataType(DataType.STRING))); x.addField(new Field("weightedsetfield", new WeightedSetDataType(DataType.STRING, true, true))); x.addField(new Field("mapfield", new MapDataType(DataType.STRING, DataType.STRING))); x.addField(new Field("tensorfield", new TensorDataType(new TensorType.Builder().indexed("x").build()))); types.registerDocumentType(x); } } @After public void tearDown() throws Exception { types = null; parserFactory = null; } private JsonReader createReader(String jsonInput) { InputStream input = new ByteArrayInputStream(Utf8.toBytes(jsonInput)); return new JsonReader(types, input, parserFactory); } @Test public void readSingleDocumentPut() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " }", "}")); DocumentPut put = (DocumentPut) r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:smoke::doc1").operation(); smokeTestDoc(put.getDocument()); } @Test public final void readSingleDocumentUpdate() { JsonReader r = createReader(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': {", " 'assign': 'orOther' }}}")); DocumentUpdate doc = (DocumentUpdate) r.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::whee").operation(); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof AssignValueUpdate); } @Test public void readClearField() { JsonReader r = createReader(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'int1': {", " 'assign': null }}}")); DocumentUpdate doc = (DocumentUpdate) r.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::whee").operation(); FieldUpdate f = doc.getFieldUpdate("int1"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof ClearValueUpdate); assertNull(f.getValueUpdate(0).getValue()); } @Test public void smokeTest() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } @Test public void docIdLookaheadTest() throws IOException { JsonReader r = createReader(inputJson( "{ 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " },", " 'put': 'id:unittest:smoke::doc1'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } @Test public void emptyDocTest() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::whee', 'fields': {}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); assertEquals("id:unittest:smoke::whee", parseInfo.documentId.toString()); } @Test public void testStruct() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:mirrors::whee',", " 'fields': {", " 'skuggsjaa': {", " 'sandra': 'person',", " 'cloud': 'another person' }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("skuggsjaa")); assertSame(Struct.class, f.getClass()); Struct s = (Struct) f; assertEquals("person", ((StringFieldValue) s.getFieldValue("sandra")).getString()); } private DocumentUpdate parseUpdate(String json) throws IOException { InputStream rawDoc = new ByteArrayInputStream(Utf8.toBytes(json)); JsonReader r = new JsonReader(types, rawDoc, parserFactory); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentUpdate update = new DocumentUpdate(docType, parseInfo.documentId); new VespaJsonDocumentReader(false).readUpdate(parseInfo.fieldsBuffer, update); return update; } @Test public void testStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(inputJson("{ 'update': 'id:unittest:mirrors:g=test:whee',", " 'create': true,", " 'fields': {", " 'skuggsjaa': {", " 'assign': {", " 'sandra': 'person',", " 'cloud': 'another person' }}}}")); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(2, s.getFieldCount()); assertEquals(new StringFieldValue("person"), s.getFieldValue(s.getField("sandra"))); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(107, buf.position()); } @Test public final void testEmptyStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(inputJson("{ 'update': 'id:unittest:mirrors:g=test:whee',", " 'create': true,", " 'fields': { ", " 'skuggsjaa': {", " 'assign': { } }}}")); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(0, s.getFieldCount()); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(69, buf.position()); } @Test public void testUpdateArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}}")); checkSimpleArrayAdd(doc); } @Test public void testUpdateWeighted() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'add': {", " 'person': 37,", " 'another person': 41 }}}}")); Map<String, Integer> weights = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; final String s = ((StringFieldValue) adder.getValue()).getString(); weights.put(s, adder.getWeight()); } assertEquals(2, weights.size()); final String o = "person"; final String o2 = "another person"; assertTrue(weights.containsKey(o)); assertTrue(weights.containsKey(o2)); assertEquals(Integer.valueOf(37), weights.get(o)); assertEquals(Integer.valueOf(41), weights.get(o2)); } @Test public void testUpdateMatch() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'match': {", " 'element': 'person',", " 'increment': 13 }}}}")); Map<String, Tuple2<Number, String>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); String op = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperator().toString(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()).getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertEquals("ADD", matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } @SuppressWarnings({ "cast", "unchecked", "rawtypes" }) @Test public void testArithmeticOperators() throws IOException { Tuple2[] operations = new Tuple2[] { new Tuple2<String, Operator>(UPDATE_DECREMENT, ArithmeticValueUpdate.Operator.SUB), new Tuple2<String, Operator>(UPDATE_DIVIDE, ArithmeticValueUpdate.Operator.DIV), new Tuple2<String, Operator>(UPDATE_INCREMENT, ArithmeticValueUpdate.Operator.ADD), new Tuple2<String, Operator>(UPDATE_MULTIPLY, ArithmeticValueUpdate.Operator.MUL) }; for (Tuple2<String, Operator> operator : operations) { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'match': {", " 'element': 'person',", " '" + (String) operator.first + "': 13 }}}}")); Map<String, Tuple2<Number, Operator>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); Operator op = ((ArithmeticValueUpdate) adder .getUpdate()).getOperator(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertSame(operator.second, matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } } @SuppressWarnings("rawtypes") @Test public void testArrayIndexing() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'match': {", " 'element': 3,", " 'assign': 'nalle' }}}}")); Map<Number, String> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualarray"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final Number key = ((IntegerFieldValue) adder.getValue()) .getNumber(); String op = ((StringFieldValue) ((AssignValueUpdate) adder.getUpdate()) .getValue()).getString(); matches.put(key, op); } assertEquals(1, matches.size()); Number n = Integer.valueOf(3); assertEquals("nalle", matches.get(n)); } @Test public void testDocumentRemove() { JsonReader r = createReader(inputJson("{'remove': 'id:unittest:smoke::whee'}")); DocumentType docType = r.readDocumentType(new DocumentId("id:unittest:smoke::whee")); assertEquals("smoke", docType.getName()); } private Document docFromJson(String json) throws IOException { JsonReader r = createReader(json); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); return put.getDocument(); } @Test public void testWeightedSet() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'nalle': 2,", " 'tralle': 7 }}}")); FieldValue f = doc.getFieldValue(doc.getField("actualset")); assertSame(WeightedSet.class, f.getClass()); WeightedSet<?> w = (WeightedSet<?>) f; assertEquals(2, w.size()); assertEquals(Integer.valueOf(2), w.get(new StringFieldValue("nalle"))); assertEquals(Integer.valueOf(7), w.get(new StringFieldValue("tralle"))); } @Test public void testArray() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': [", " 'nalle',", " 'tralle' ]}}")); FieldValue f = doc.getFieldValue(doc.getField("actualarray")); assertSame(Array.class, f.getClass()); Array<?> a = (Array<?>) f; assertEquals(2, a.size()); assertEquals(new StringFieldValue("nalle"), a.get(0)); assertEquals(new StringFieldValue("tralle"), a.get(1)); } @Test public void testMap() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testmap::whee',", " 'fields': {", " 'actualmap': {", " 'nalle': 'kalle',", " 'tralle': 'skalle' }}}")); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testOldMap() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testmap::whee',", " 'fields': {", " 'actualmap': [", " { 'key': 'nalle', 'value': 'kalle'},", " { 'key': 'tralle', 'value': 'skalle'} ]}}")); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testPositionPositive() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': 'N63.429722;E10.393333' }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionOld() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': {'x':10393333,'y':63429722} }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testGeoPosition() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': {'lat':63.429722,'lng':10.393333} }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testGeoPositionNoAbbreviations() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': {'latitude':63.429722,'longitude':10.393333} }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionGeoPos() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'geopos': 'N63.429722;E10.393333' }}")); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); } @Test public void testPositionOldGeoPos() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'geopos': {'x':10393333,'y':63429722} }}")); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); } @Test public void testGeoPositionGeoPos() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'geopos': {'lat':63.429722,'lng':10.393333} }}")); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); assertEquals(PositionDataType.INSTANCE, f.getDataType()); } @Test public void testPositionNegative() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': 'W46.63;S23.55' }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(-46630000, PositionDataType.getXValue(f).getInteger()); assertEquals(-23550000, PositionDataType.getYValue(f).getInteger()); } @Test public void testRaw() throws IOException { String base64 = new String(new JsonStringEncoder().quoteAsString( Base64.getEncoder().encodeToString(Utf8.toBytes("smoketest")))); String s = fieldStringFromBase64RawContent(base64); assertEquals("smoketest", s); } @Test public void can_read_legacy_chunked_base64_raw_field_encoding() throws IOException { String expected = "this is a string with an impressive length. it's long enough to reach the end of the line, wow!"; String base64withDelims = "dGhpcyBpcyBhIHN0cmluZyB3aXRoIGFuIGltcHJlc3NpdmUgbGVuZ3RoLiBpdCdzIGxvbmcgZW5v\\r\\n" + "dWdoIHRvIHJlYWNoIHRoZSBlbmQgb2YgdGhlIGxpbmUsIHdvdyE=\\r\\n"; assertEquals(expected, fieldStringFromBase64RawContent(base64withDelims)); } private String fieldStringFromBase64RawContent(String base64data) throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testraw::whee',", " 'fields': {", " 'actualraw': '" + base64data + "' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("actualraw")); assertSame(Raw.class, f.getClass()); Raw s = (Raw) f; return Utf8.toString(s.getByteBuffer()); } @Test public void testMapStringToArrayOfInt() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'bamse': [1, 2, 3] }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldMapStringToArrayOfInt() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': [", " { 'key': 'bamse', 'value': [1, 2, 3] } ]}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToString() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': {", " 'assign': 'orOther' }}}")); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); AssignValueUpdate a = (AssignValueUpdate) f.getValueUpdate(0); assertEquals(new StringFieldValue("orOther"), a.getValue()); } @Test public void testAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'assign': { 'bamse': [1, 2, 3] }}}}")); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'assign': [", " { 'key': 'bamse', 'value': [1, 2, 3] } ]}}}")); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToWeightedSet() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'assign': {", " 'person': 37,", " 'another person': 41 }}}}")); FieldUpdate x = doc.getFieldUpdate("actualset"); assertEquals(1, x.size()); AssignValueUpdate assign = (AssignValueUpdate) x.getValueUpdate(0); WeightedSet<?> w = (WeightedSet<?>) assign.getValue(); assertEquals(2, w.size()); assertEquals(Integer.valueOf(37), w.get(new StringFieldValue("person"))); assertEquals(Integer.valueOf(41), w.get(new StringFieldValue("another person"))); } @Test public void testCompleteFeed() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }},", "{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}},", "{ 'remove': 'id:unittest:smoke::whee' }]")); controlBasicFeed(r); } @Test public void testCompleteFeedWithCreateAndCondition() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }},", "{", " 'condition':'bla',", " 'update': 'id:unittest:testarray::whee',", " 'create':true,", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}},", "{ 'remove': 'id:unittest:smoke::whee' }]")); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testUpdateWithConditionAndCreateInDifferentOrdering() { int documentsCreated = 106; List<String> parts = Arrays.asList( "\"condition\":\"bla\"", "\"update\": \"id:unittest:testarray::whee\"", " \"fields\": { " + "\"actualarray\": { \"add\": [" + " \"person\",\"another person\"]}}", " \"create\":true"); Random random = new Random(42); StringBuilder documents = new StringBuilder("["); for (int x = 0; x < documentsCreated; x++) { Collections.shuffle(parts, random); documents.append("{").append(Joiner.on(",").join(parts)).append("}"); if (x < documentsCreated -1) { documents.append(","); } } documents.append("]"); InputStream rawDoc = new ByteArrayInputStream( Utf8.toBytes(documents.toString())); JsonReader r = new JsonReader(types, rawDoc, parserFactory); for (int x = 0; x < documentsCreated; x++) { DocumentUpdate update = (DocumentUpdate) r.next(); checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); } assertNull(r.next()); } @Test(expected=RuntimeException.class) public void testCreateIfNonExistentInPut() { JsonReader r = createReader(inputJson("[{", " 'create':true,", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse' },", " 'put': 'id:unittest:smoke::whee'", "}]")); r.next(); } @Test public void testCompleteFeedWithIdAfterFields() { JsonReader r = createReader(inputJson("[", "{", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' },", " 'put': 'id:unittest:smoke::whee'", "},", "{", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}},", " 'update': 'id:unittest:testarray::whee'", "},", "{ 'remove': 'id:unittest:smoke::whee' }]")); controlBasicFeed(r); } protected void controlBasicFeed(JsonReader r) { DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testCompleteFeedWithEmptyDoc() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee', 'fields': {} },", "{ 'update': 'id:unittest:testarray::whee', 'fields': {} },", "{ 'remove': 'id:unittest:smoke::whee' }]")); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); assertEquals("smoke", doc.getId().getDocType()); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; assertEquals("testarray", update.getId().getDocType()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } private void checkSimpleArrayAdd(DocumentUpdate update) { Set<String> toAdd = new HashSet<>(); FieldUpdate x = update.getFieldUpdate("actualarray"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; toAdd.add(((StringFieldValue) adder.getValue()).getString()); } assertEquals(2, toAdd.size()); assertTrue(toAdd.contains("person")); assertTrue(toAdd.contains("another person")); } private void smokeTestDoc(Document doc) { FieldValue boolField = doc.getFieldValue(doc.getField("flag")); assertSame(BoolFieldValue.class, boolField.getClass()); assertTrue((Boolean)boolField.getWrappedValue()); FieldValue stringField = doc.getFieldValue(doc.getField("nalle")); assertSame(StringFieldValue.class, stringField.getClass()); assertEquals("bamse", ((StringFieldValue) stringField).getString()); } @Test public void nonExistingFieldCausesException() throws IOException { JsonReader r = createReader(inputJson( "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'smething': 'smoketest',", " 'nalle': 'bamse' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); try { new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); fail(); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().startsWith("No field 'smething' in the structure of type 'smoke'")); } } @Test public void nonExistingFieldsCanBeIgnoredInPut() throws IOException { JsonReader r = createReader(inputJson( "{ ", " 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'nonexisting1': 'ignored value',", " 'field1': 'value1',", " 'nonexisting2': {", " 'blocks':{", " 'a':[2.0,3.0],", " 'b':[4.0,5.0]", " }", " },", " 'field2': 'value2',", " 'nonexisting3': {", " 'cells': [{'address': {'x': 'x1'}, 'value': 1.0}]", " },", " 'tensor1': {'cells': {'x1': 1.0}},", " 'nonexisting4': 'ignored value'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); boolean fullyApplied = new VespaJsonDocumentReader(true).readPut(parseInfo.fieldsBuffer, put); assertFalse(fullyApplied); assertNull(put.getDocument().getField("nonexisting1")); assertEquals("value1", put.getDocument().getFieldValue("field1").toString()); assertNull(put.getDocument().getField("nonexisting2")); assertEquals("value2", put.getDocument().getFieldValue("field2").toString()); assertNull(put.getDocument().getField("nonexisting3")); assertEquals(Tensor.from("tensor(x{}):{{x:x1}:1.0}"), put.getDocument().getFieldValue("tensor1").getWrappedValue()); assertNull(put.getDocument().getField("nonexisting4")); } @Test public void nonExistingFieldsCanBeIgnoredInUpdate() throws IOException{ JsonReader r = createReader(inputJson( "{ ", " 'update': 'id:unittest:smoke::doc1',", " 'fields': {", " 'nonexisting1': { 'assign': 'ignored value' },", " 'field1': { 'assign': 'value1' },", " 'nonexisting2': { " + " 'assign': {", " 'blocks': {", " 'a':[2.0,3.0],", " 'b':[4.0,5.0]", " }", " }", " },", " 'field2': { 'assign': 'value2' },", " 'nonexisting3': {", " 'assign' : {", " 'cells': [{'address': {'x': 'x1'}, 'value': 1.0}]", " }", " },", " 'tensor1': {'assign': { 'cells': {'x1': 1.0} } },", " 'nonexisting4': { 'assign': 'ignored value' }", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentUpdate update = new DocumentUpdate(docType, parseInfo.documentId); boolean fullyApplied = new VespaJsonDocumentReader(true).readUpdate(parseInfo.fieldsBuffer, update); assertFalse(fullyApplied); assertNull(update.getFieldUpdate("nonexisting1")); assertEquals("value1", update.getFieldUpdate("field1").getValueUpdates().get(0).getValue().getWrappedValue().toString()); assertNull(update.getFieldUpdate("nonexisting2")); assertEquals("value2", update.getFieldUpdate("field2").getValueUpdates().get(0).getValue().getWrappedValue().toString()); assertNull(update.getFieldUpdate("nonexisting3")); assertEquals(Tensor.from("tensor(x{}):{{x:x1}:1.0}"), update.getFieldUpdate("tensor1").getValueUpdates().get(0).getValue().getWrappedValue()); assertNull(update.getFieldUpdate("nonexisting4")); } @Test public void feedWithBasicErrorTest() { JsonReader r = createReader(inputJson("[", " { 'put': 'id:test:smoke::0', 'fields': { 'something': 'foo' } },", " { 'put': 'id:test:smoke::1', 'fields': { 'something': 'foo' } },", " { 'put': 'id:test:smoke::2', 'fields': { 'something': 'foo' } },", "]")); try { while (r.next() != null) ; fail(); } catch (RuntimeException e) { assertTrue(e.getMessage().contains("JsonParseException")); } } @Test public void idAsAliasForPutTest() throws IOException{ JsonReader r = createReader(inputJson("{ 'id': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); boolean fullyApplied = new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); assertTrue(fullyApplied); smokeTestDoc(put.getDocument()); } private void testFeedWithTestAndSetCondition(String jsonDoc) { ByteArrayInputStream parseInfoDoc = new ByteArrayInputStream(Utf8.toBytes(jsonDoc)); JsonReader reader = new JsonReader(types, parseInfoDoc, parserFactory); int NUM_OPERATIONS_IN_FEED = 3; for (int i = 0; i < NUM_OPERATIONS_IN_FEED; i++) { DocumentOperation operation = reader.next(); assertTrue("A test and set condition should be present", operation.getCondition().isPresent()); assertEquals("DocumentOperation's test and set condition should be equal to the one in the JSON feed", "smoke.something == \"smoketest\"", operation.getCondition().getSelection()); } assertNull(reader.next()); } @Test public void testFeedWithTestAndSetConditionOrderingOne() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'put': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " }", " },", " {", " 'update': 'id:unittest:testarray::whee',", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " },", " {", " 'remove': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\''", " }", "]" )); } @Test public void testFeedWithTestAndSetConditionOrderingTwo() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " }", " },", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " },", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'remove': 'id:unittest:smoke::whee'", " }", "]" )); } @Test public void testFeedWithTestAndSetConditionOrderingThree() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " },", " 'condition': 'smoke.something == \\'smoketest\\''", " },", " {", " 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " },", " 'condition': 'smoke.something == \\'smoketest\\''", " },", " {", " 'remove': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\''", " }", "]" )); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldAfterFieldsFieldShouldFailParse() { final String jsonData = inputJson( "[", " {", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " },", " 'bjarne': 'stroustrup'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldBeforeFieldsFieldShouldFailParse() { final String jsonData = inputJson( "[", " {", " 'update': 'id:unittest:testarray::whee',", " 'what is this': 'nothing to see here',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldWithoutFieldsFieldShouldFailParse() { String jsonData = inputJson( "[", " {", " 'remove': 'id:unittest:smoke::whee',", " 'what is love': 'baby, do not hurt me... much'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test public void testMissingOperation() { try { String jsonData = inputJson( "[", " {", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Missing a document operation ('put', 'update' or 'remove')", e.getMessage()); } } @Test public void testMissingFieldsMapInPut() { try { String jsonData = inputJson( "[", " {", " 'put': 'id:unittest:smoke::whee'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("put of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testMissingFieldsMapInUpdate() { try { String jsonData = inputJson( "[", " {", " 'update': 'id:unittest:smoke::whee'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Update of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testNullValues() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testnull::doc1',", " 'fields': {", " 'intfield': null,", " 'stringfield': null,", " 'arrayfield': null,", " 'weightedsetfield': null,", " 'mapfield': null,", " 'tensorfield': null", " }", "}")); DocumentPut put = (DocumentPut) r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:testnull::doc1").operation(); Document doc = put.getDocument(); assertFieldValueNull(doc, "intfield"); assertFieldValueNull(doc, "stringfield"); assertFieldValueNull(doc, "arrayfield"); assertFieldValueNull(doc, "weightedsetfield"); assertFieldValueNull(doc, "mapfield"); assertFieldValueNull(doc, "tensorfield"); } @Test(expected=JsonReaderException.class) public void testNullArrayElement() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testnull::doc1',", " 'fields': {", " 'arrayfield': [ null ]", " }", "}")); r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:testnull::doc1"); fail(); } private void assertFieldValueNull(Document doc, String fieldName) { Field field = doc.getField(fieldName); assertNotNull(field); FieldValue fieldValue = doc.getFieldValue(field); assertNull(fieldValue); } static ByteArrayInputStream jsonToInputStream(String json) { return new ByteArrayInputStream(Utf8.toBytes(json)); } @Test public void testParsingWithoutTensorField() { Document doc = createPutWithoutTensor().getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals("id:unittest:testtensor::0", doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField("sparse_tensor")); assertNull(fieldValue); } @Test public void testParsingOfEmptyTensor() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor("{}")); } @Test public void testParsingOfTensorWithEmptyCells() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor(inputJson("{ 'cells': [] }"))); } @Test public void testDisallowedDenseTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{ 'values': [] }"), "dense_tensor", "The 'values' array does not contain any values"); assertCreatePutFails(inputJson("{ 'values': '' }"), "dense_tensor", "The 'values' string does not contain any values"); } @Test public void testDisallowedMixedTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{\"blocks\":{ \"a\": [] } }"), "mixed_tensor", "Expected 3 values, but got 0"); assertCreatePutFails(inputJson("{\"blocks\":[ {\"address\":{\"x\":\"a\"}, \"values\": [] } ] }"), "mixed_tensor", "Expected 3 values, but got 0"); } @Test public void testParsingOfSparseTensorWithCells() { Tensor tensor = assertSparseTensorField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createPutWithSparseTensor( """ { "type": "tensor(x{},y{})", "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 }, { "address": { "x": "c", "y": "b" }, "value": 3.0 } ] } """)); assertTrue(tensor instanceof MappedTensor); // any functional instance is fine } @Test public void testParsingOfDenseTensorWithCells() { Tensor tensor = assertTensorField("{{x:0,y:0}:2.0,{x:1,y:0}:3.0}}", createPutWithTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' },", " 'value': 2.0 },", " { 'address': { 'x': '1', 'y': '0' },", " 'value': 3.0 }", " ]", "}"), "dense_unbound_tensor"), "dense_unbound_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorOnDenseForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson("{", " 'values': [2.0, 3.0, 4.0, 5.0, 6.0, 7.0]", "}"), "dense_tensor"), "dense_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<int8>(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson("{", " 'values': \"020304050607\"", "}"), "dense_int8_tensor"), "dense_int8_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfMixedTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")); builder.cell().label("x", "foo").label("y", 0).value(2.0); builder.cell().label("x", "foo").label("y", 1).value(3.0); builder.cell().label("x", "foo").label("y", 2).value(4.0); builder.cell().label("x", "bar").label("y", 0).value(5.0); builder.cell().label("x", "bar").label("y", 1).value(6.0); builder.cell().label("x", "bar").label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":[" + "{\"address\":{\"x\":\"foo\"},\"values\":\"400040404080\"}," + "{\"address\":{\"x\":\"bar\"},\"values\":\"40A040C040E0\"}" + "]}"; var put = createPutWithTensor(inputJson(mixedJson), "mixed_bfloat16_tensor"); Tensor tensor = assertTensorField(expected, put, "mixed_bfloat16_tensor"); } /** Tests parsing of various tensor values set at the root, i.e. no 'cells', 'blocks' or 'values' */ @Test public void testDirectValue() { assertTensorField("tensor(x{}):{a:2, b:3}", "sparse_single_dimension_tensor", "{'a':2.0, 'b':3.0}"); assertTensorField("tensor(x[2],y[3]):[2, 3, 4, 5, 6, 7]]", "dense_tensor", "[2, 3, 4, 5, 6, 7]"); assertTensorField("tensor(x[2],y[3]):[2, 3, 4, 5, 6, 7]]", "dense_tensor", "[[2, 3, 4], [5, 6, 7]]"); assertTensorField("tensor(x{},y[3]):{a:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'a':[2, 3, 4], 'b':[4, 5, 6]}"); assertTensorField("tensor(x{},y{}):{{x:a,y:0}:2, {x:b,y:1}:3}", "sparse_tensor", "[{'address':{'x':'a','y':'0'},'value':2}, {'address':{'x':'b','y':'1'},'value':3}]"); } @Test public void testDirectValueReservedNameKeys() { // Single-valued assertTensorField("tensor(x{}):{cells:2, b:3}", "sparse_single_dimension_tensor", "{'cells':2.0, 'b':3.0}"); assertTensorField("tensor(x{}):{values:2, b:3}", "sparse_single_dimension_tensor", "{'values':2.0, 'b':3.0}"); assertTensorField("tensor(x{}):{block:2, b:3}", "sparse_single_dimension_tensor", "{'block':2.0, 'b':3.0}"); // Multi-valued assertTensorField("tensor(x{},y[3]):{cells:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'cells':[2, 3, 4], 'b':[4, 5, 6]}"); assertTensorField("tensor(x{},y[3]):{values:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'values':[2, 3, 4], 'b':[4, 5, 6]}"); assertTensorField("tensor(x{},y[3]):{block:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'block':[2, 3, 4], 'b':[4, 5, 6]}"); } @Test public void testParsingOfMixedTensorOnMixedForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = """ { "blocks":[ {"address":{"x":"0"},"values":[2.0,3.0,4.0]}, {"address":{"x":"1"},"values":[5.0,6.0,7.0]} ] } """; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance String mixedJsonDirect = """ [ {"address":{"x":"0","y":"0"},"value":2.0}, {"address":{"x":"0","y":"1"},"value":3.0}, {"address":{"x":"0","y":"2"},"value":4.0}, {"address":{"x":"1","y":"0"},"value":5.0}, {"address":{"x":"1","y":"1"},"value":6.0}, {"address":{"x":"1","y":"2"},"value":7.0} ] """; Tensor tensorDirect = assertTensorField(expected, createPutWithTensor(inputJson(mixedJsonDirect), "mixed_tensor"), "mixed_tensor"); assertTrue(tensorDirect instanceof MixedTensor); // this matters for performance } @Test public void testMixedTensorInMixedFormWithSingleSparseDimensionShortForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":{" + "\"0\":[2.0,3.0,4.0]," + "\"1\":[5.0,6.0,7.0]" + "}}"; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance } @Test public void testParsingOfTensorWithSingleCellInDifferentJsonOrder() { assertSparseTensorField("{{x:a,y:b}:2.0}", createPutWithSparseTensor(inputJson("{", " 'cells': [", " { 'value': 2.0,", " 'address': { 'x': 'a', 'y': 'b' } }", " ]", "}"))); } @Test public void testAssignUpdateOfEmptySparseTensor() { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithSparseTensor("{}")); } @Test public void testAssignUpdateOfEmptyDenseTensor() { try { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithTensor("{}", "dense_unbound_tensor")); } catch (IllegalArgumentException e) { assertEquals("An indexed tensor must have a value", "Error in 'dense_unbound_tensor': Tensor of type tensor(x[],y[]) has no values", Exceptions.toMessageString(e)); } } @Test public void testAssignUpdateOfNullTensor() { ClearValueUpdate clearUpdate = (ClearValueUpdate) getTensorField(createAssignUpdateWithSparseTensor(null)).getValueUpdate(0); assertNotNull(clearUpdate); assertNull(clearUpdate.getValue()); } @Test public void testAssignUpdateOfTensorWithCells() { assertTensorAssignUpdateSparseField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createAssignUpdateWithSparseTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' },", " 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'b' },", " 'value': 3.0 }", " ]", "}"))); } @Test public void testAssignUpdateOfTensorDenseShortForm() { assertTensorAssignUpdateDenseField("tensor(x[2],y[3]):[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]", createAssignUpdateWithTensor(inputJson("{", " 'values': [1,2,3,4,5,6]", "}"), "dense_tensor")); } @Test public void tensor_modify_update_with_replace_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_add_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, "sparse_tensor", inputJson("{", " 'operation': 'add',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_multiply_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "sparse_tensor", inputJson("{", " 'operation': 'multiply',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_treats_the_input_tensor_as_sparse() { // Note that the type of the tensor in the modify update is sparse (it only has mapped dimensions). assertTensorModifyUpdate("tensor(x{},y{}):{{x:0,y:0}:2.0, {x:1,y:2}:3.0}", TensorModifyUpdate.Operation.REPLACE, "dense_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' }, 'value': 2.0 },", " { 'address': { 'x': '1', 'y': '2' }, 'value': 3.0 } ]}")); } @Test public void tensor_modify_update_on_non_tensor_field_throws() { try { JsonReader reader = createReader(inputJson("{ 'update': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': {", " 'modify': {} }}}")); reader.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::doc1"); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Error in 'something': A modify update can only be applied to tensor fields. Field 'something' is of type 'string'", Exceptions.toMessageString(e)); } } @Test public void tensor_modify_update_on_dense_unbound_tensor_throws() { illegalTensorModifyUpdate("Error in 'dense_unbound_tensor': A modify update cannot be applied to tensor types with indexed unbound dimensions. Field 'dense_unbound_tensor' has unsupported tensor type 'tensor(x[],y[])'", "dense_unbound_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorModifyUpdate("{{x:a}:2.0, {x:c}: 3.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_single_dimension_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': {", " 'a': 2.0,", " 'c': 3.0 }}")); } @Test public void tensor_modify_update_with_replace_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_array() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': [", " { 'address': { 'x': 'a' }, 'values': [1,2,3] } ]}")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_must_specify_full_subspace() { illegalTensorModifyUpdate("Error in 'mixed_tensor': At {x:a}: Expected 3 values, but got 2", "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': {", " 'a': [2,3] } }")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_map() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': {", " 'a': [1,2,3] } }")); } @Test public void tensor_modify_update_with_add_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.ADD, "mixed_tensor", inputJson("{", " 'operation': 'add',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_multiply_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "mixed_tensor", inputJson("{", " 'operation': 'multiply',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws() { illegalTensorModifyUpdate("Error in 'dense_tensor': Dimension 'y' has label '3' but type is tensor(x[2],y[3])", "dense_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws_mixed() { illegalTensorModifyUpdate("Error in 'mixed_tensor': Dimension 'y' has label '3' but type is tensor(x{},y[3])", "mixed_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_with_unknown_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown operation 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", "{", " 'operation': 'unknown',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_without_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain an operation", "sparse_tensor", "{", " 'cells': [] }"); } @Test public void tensor_modify_update_without_cells_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", "{", " 'operation': 'replace' }"); } @Test public void tensor_modify_update_with_unknown_content_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown JSON string 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", "{", " 'unknown': 'here' }"); } @Test public void tensor_add_update_on_sparse_tensor() { assertTensorAddUpdate("{{x:a,y:b}:2.0, {x:c,y:d}: 3.0}", "sparse_tensor", inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'd' }, 'value': 3.0 } ]}")); } @Test public void tensor_add_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorAddUpdate("{{x:a}:2.0, {x:c}: 3.0}", "sparse_single_dimension_tensor", inputJson("{", " 'cells': {", " 'a': 2.0,", " 'c': 3.0 }}")); } @Test public void tensor_add_update_on_mixed_tensor() { assertTensorAddUpdate("{{x:a,y:0}:2.0, {x:a,y:1}:3.0, {x:a,y:2}:0.0}", "mixed_tensor", inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 },", " { 'address': { 'x': 'a', 'y': '1' }, 'value': 3.0 } ]}")); } @Test public void tensor_add_update_on_mixed_with_out_of_bound_dense_cells_throws() { illegalTensorAddUpdate("Error in 'mixed_tensor': Index 3 out of bounds for length 3", "mixed_tensor", "{", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_add_update_on_dense_tensor_throws() { illegalTensorAddUpdate("Error in 'dense_tensor': An add update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", "{", " 'cells': [] }"); } @Test public void tensor_add_update_on_not_fully_specified_cell_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Missing a label for dimension 'y' for tensor(x{},y{})", "sparse_tensor", "{", " 'cells': [", " { 'address': { 'x': 'a' }, 'value': 2.0 } ]}"); } @Test public void tensor_add_update_without_cells_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Add update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", "{}"); illegalTensorAddUpdate("Error in 'mixed_tensor': Add update for field 'mixed_tensor' does not contain tensor cells", "mixed_tensor", "{}"); } @Test public void tensor_remove_update_on_sparse_tensor() { assertTensorRemoveUpdate("{{x:a,y:b}:1.0,{x:c,y:d}:1.0}", "sparse_tensor", inputJson("{", " 'addresses': [", " { 'x': 'a', 'y': 'b' },", " { 'x': 'c', 'y': 'd' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor() { assertTensorRemoveUpdate("{{x:1}:1.0,{x:2}:1.0}", "mixed_tensor", inputJson("{", " 'addresses': [", " { 'x': '1' },", " { 'x': '2' } ]}")); } @Test public void tensor_remove_update_on_sparse_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{y:b}:1.0,{y:d}:1.0}", "sparse_tensor", inputJson("{", " 'addresses': [", " { 'y': 'b' },", " { 'y': 'd' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{x:1,z:a}:1.0,{x:2,z:b}:1.0}", "mixed_tensor_adv", inputJson("{", " 'addresses': [", " { 'x': '1', 'z': 'a' },", " { 'x': '2', 'z': 'b' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor_with_dense_addresses_throws() { illegalTensorRemoveUpdate("Error in 'mixed_tensor': Indexed dimension address 'y' should not be specified in remove update", "mixed_tensor", "{", " 'addresses': [", " { 'x': '1', 'y': '0' },", " { 'x': '2', 'y': '0' } ]}"); } @Test public void tensor_remove_update_on_dense_tensor_throws() { illegalTensorRemoveUpdate("Error in 'dense_tensor': A remove update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", "{", " 'addresses': [] }"); } @Test public void tensor_remove_update_with_stray_dimension_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{},y{}) does not contain dimension 'foo'", "sparse_tensor", "{", " 'addresses': [", " { 'x': 'a', 'foo': 'b' } ]}"); illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{}) does not contain dimension 'foo'", "sparse_tensor", "{", " 'addresses': [", " { 'x': 'c' },", " { 'x': 'a', 'foo': 'b' } ]}"); } @Test public void tensor_remove_update_without_cells_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': Remove update for field 'sparse_tensor' does not contain tensor addresses", "sparse_tensor", "{'addresses': [] }"); illegalTensorRemoveUpdate("Error in 'mixed_tensor': Remove update for field 'mixed_tensor' does not contain tensor addresses", "mixed_tensor", "{'addresses': [] }"); } @Test public void require_that_parser_propagates_datatype_parser_errors_predicate() { assertParserErrorMatches( "Error in document 'id:unittest:testpredicate::0' - could not parse field 'boolean' of type 'predicate': " + "line 1:10 no viable alternative at character '>'", "[", " {", " 'fields': {", " 'boolean': 'timestamp > 9000'", " },", " 'put': 'id:unittest:testpredicate::0'", " }", "]" ); } @Test public void require_that_parser_propagates_datatype_parser_errors_string_as_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \" 1\"", "[", " {", " 'fields': {", " 'integerfield': ' 1'", " },", " 'put': 'id:unittest:testint::0'", " }", "]" ); } @Test public void require_that_parser_propagates_datatype_parser_errors_overflowing_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \"281474976710656\"", "[", " {", " 'fields': {", " 'integerfield': 281474976710656", " },", " 'put': 'id:unittest:testint::0'", " }", "]" ); } @Test public void requireThatUnknownDocTypeThrowsIllegalArgumentException() { final String jsonData = inputJson( "[", " {", " 'put': 'id:ns:walrus::walrus1',", " 'fields': {", " 'aField': 42", " }", " }", "]"); try { new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail(); } catch (IllegalArgumentException e) { assertEquals("Document type walrus does not exist", e.getMessage()); } } private static final String TENSOR_DOC_ID = "id:unittest:testtensor::0"; private void illegalTensorModifyUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorModifyUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorAddUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorAddUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorRemoveUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorRemoveUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private DocumentPut createPutWithoutTensor() { JsonReader reader = createReader(inputJson("[ { 'put': '" + TENSOR_DOC_ID + "', 'fields': { } } ]")); return (DocumentPut) reader.next(); } private DocumentPut createPutWithSparseTensor(String inputTensor) { return createPutWithTensor(inputTensor, "sparse_tensor"); } private DocumentPut createPutWithTensor(String inputTensor, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'put': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': " + inputTensor + " }}]")); return (DocumentPut) reader.next(); } private DocumentUpdate createAssignUpdateWithSparseTensor(String inputTensor) { return createAssignUpdateWithTensor(inputTensor, "sparse_tensor"); } private DocumentUpdate createAssignUpdateWithTensor(String inputTensor, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'update': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': {", " 'assign': " + (inputTensor != null ? inputTensor : "null") + " } } } ]")); return (DocumentUpdate) reader.next(); } private static Tensor assertSparseTensorField(String expectedTensor, DocumentPut put) { return assertTensorField(expectedTensor, put, "sparse_tensor"); } private Tensor assertTensorField(String expectedTensor, String fieldName, String inputJson) { return assertTensorField(expectedTensor, createPutWithTensor(inputJson, fieldName), fieldName); } private static Tensor assertTensorField(String expectedTensor, DocumentPut put, String tensorFieldName) { return assertTensorField(Tensor.from(expectedTensor), put, tensorFieldName); } private static Tensor assertTensorField(Tensor expectedTensor, DocumentPut put, String tensorFieldName) { Document doc = put.getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals(TENSOR_DOC_ID, doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField(tensorFieldName)); assertEquals(expectedTensor, fieldValue.getTensor().get()); return fieldValue.getTensor().get(); } private static void assertTensorFieldUpdate(DocumentUpdate update, String tensorFieldName) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); assertEquals(1, update.fieldUpdates().size()); assertEquals(1, update.getFieldUpdate(tensorFieldName).size()); } private static void assertTensorAssignUpdateSparseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "sparse_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private static void assertTensorAssignUpdateDenseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "dense_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, String tensorFieldName, String modifyJson) { assertTensorModifyUpdate(expectedTensor, expectedOperation, tensorFieldName, createTensorModifyUpdate(modifyJson, tensorFieldName)); } private static void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorModifyUpdate modifyUpdate = (TensorModifyUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(expectedOperation, modifyUpdate.getOperation()); assertEquals(Tensor.from(expectedTensor), modifyUpdate.getValue().getTensor().get()); } private DocumentUpdate createTensorModifyUpdate(String modifyJson, String tensorFieldName) { return createTensorUpdate("modify", modifyJson, tensorFieldName); } private DocumentUpdate createTensorAddUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("add", tensorJson, tensorFieldName); } private DocumentUpdate createTensorRemoveUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("remove", tensorJson, tensorFieldName); } private DocumentUpdate createTensorUpdate(String operation, String tensorJson, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'update': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': {", " '" + operation + "': " + tensorJson + " }}}]")); return (DocumentUpdate) reader.next(); } private void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorAddUpdate(expectedTensor, tensorFieldName, createTensorAddUpdate(tensorJson, tensorFieldName)); } private static void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorAddUpdate addUpdate = (TensorAddUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), addUpdate.getValue().getTensor().get()); } private void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorRemoveUpdate(expectedTensor, tensorFieldName, createTensorRemoveUpdate(tensorJson, tensorFieldName)); } private static void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorRemoveUpdate removeUpdate = (TensorRemoveUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), removeUpdate.getValue().getTensor().get()); } private static FieldUpdate getTensorField(DocumentUpdate update) { return getTensorField(update, "sparse_tensor"); } private static FieldUpdate getTensorField(DocumentUpdate update, String fieldName) { FieldUpdate fieldUpdate = update.getFieldUpdate(fieldName); assertEquals(1, fieldUpdate.size()); return fieldUpdate; } // NOTE: Do not call this method multiple times from a test method as it's using the ExpectedException rule private void assertParserErrorMatches(String expectedError, String... json) { String jsonData = inputJson(json); try { new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail(); } catch (JsonReaderException e) { assertEquals(expectedError, e.getMessage()); } } private void assertCreatePutFails(String tensor, String name, String msg) { try { createPutWithTensor(inputJson(tensor), name); fail("Expected exception"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains(msg)); } } }
rr-hung-nguyen/vespa
document/src/test/java/com/yahoo/document/json/JsonReaderTestCase.java
213,292
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.document.json; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.io.JsonStringEncoder; import com.google.common.base.Joiner; import com.yahoo.collections.Tuple2; import com.yahoo.document.ArrayDataType; import com.yahoo.document.DataType; import com.yahoo.document.Document; import com.yahoo.document.DocumentId; import com.yahoo.document.DocumentOperation; import com.yahoo.document.DocumentPut; import com.yahoo.document.DocumentRemove; import com.yahoo.document.DocumentType; import com.yahoo.document.DocumentTypeManager; import com.yahoo.document.DocumentUpdate; import com.yahoo.document.Field; import com.yahoo.document.MapDataType; import com.yahoo.document.PositionDataType; import com.yahoo.document.StructDataType; import com.yahoo.document.TensorDataType; import com.yahoo.document.WeightedSetDataType; import com.yahoo.document.datatypes.Array; import com.yahoo.document.datatypes.BoolFieldValue; import com.yahoo.document.datatypes.FieldValue; import com.yahoo.document.datatypes.IntegerFieldValue; import com.yahoo.document.datatypes.MapFieldValue; import com.yahoo.document.datatypes.Raw; import com.yahoo.document.datatypes.StringFieldValue; import com.yahoo.document.datatypes.Struct; import com.yahoo.document.datatypes.TensorFieldValue; import com.yahoo.document.datatypes.WeightedSet; import com.yahoo.document.internal.GeoPosType; import com.yahoo.document.json.readers.DocumentParseInfo; import com.yahoo.document.json.readers.VespaJsonDocumentReader; import com.yahoo.document.serialization.DocumentSerializer; import com.yahoo.document.serialization.DocumentSerializerFactory; import com.yahoo.document.update.AddValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate.Operator; import com.yahoo.document.update.AssignValueUpdate; import com.yahoo.document.update.ClearValueUpdate; import com.yahoo.document.update.FieldUpdate; import com.yahoo.document.update.MapValueUpdate; import com.yahoo.document.update.TensorAddUpdate; import com.yahoo.document.update.TensorModifyUpdate; import com.yahoo.document.update.TensorRemoveUpdate; import com.yahoo.document.update.ValueUpdate; import com.yahoo.io.GrowableByteBuffer; import com.yahoo.tensor.IndexedTensor; import com.yahoo.tensor.MappedTensor; import com.yahoo.tensor.MixedTensor; import com.yahoo.tensor.Tensor; import com.yahoo.tensor.TensorType; import com.yahoo.text.Utf8; import com.yahoo.yolean.Exceptions; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DECREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DIVIDE; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_INCREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_MULTIPLY; import static com.yahoo.test.json.JsonTestHelper.inputJson; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Basic test of JSON streams to Vespa document instances. * * @author Steinar Knutsen * @author bratseth */ public class JsonReaderTestCase { private DocumentTypeManager types; private JsonFactory parserFactory; @Before public void setUp() throws Exception { parserFactory = new JsonFactory(); types = new DocumentTypeManager(); { DocumentType x = new DocumentType("smoke"); x.addField(new Field("something", DataType.STRING)); x.addField(new Field("nalle", DataType.STRING)); x.addField(new Field("field1", DataType.STRING)); x.addField(new Field("field2", DataType.STRING)); x.addField(new Field("int1", DataType.INT)); x.addField(new Field("flag", DataType.BOOL)); x.addField(new Field("tensor1", DataType.getTensor(TensorType.fromSpec("tensor(x{})")))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("mirrors"); StructDataType woo = new StructDataType("woo"); woo.addField(new Field("sandra", DataType.STRING)); woo.addField(new Field("cloud", DataType.STRING)); x.addField(new Field("skuggsjaa", woo)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testarray"); DataType d = new ArrayDataType(DataType.STRING); x.addField(new Field("actualarray", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testset"); DataType d = new WeightedSetDataType(DataType.STRING, true, true); x.addField(new Field("actualset", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testmap"); DataType d = new MapDataType(DataType.STRING, DataType.STRING); x.addField(new Field("actualmap", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testraw"); DataType d = DataType.RAW; x.addField(new Field("actualraw", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testMapStringToArrayOfInt"); DataType value = new ArrayDataType(DataType.INT); DataType d = new MapDataType(DataType.STRING, value); x.addField(new Field("actualMapStringToArrayOfInt", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testsinglepos"); DataType d = PositionDataType.INSTANCE; x.addField(new Field("singlepos", d)); x.addField(new Field("geopos", new GeoPosType(8))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testtensor"); x.addField(new Field("sparse_single_dimension_tensor", new TensorDataType(new TensorType.Builder().mapped("x").build()))); x.addField(new Field("sparse_tensor", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").build()))); x.addField(new Field("dense_tensor", new TensorDataType(new TensorType.Builder().indexed("x", 2).indexed("y", 3).build()))); x.addField(new Field("dense_int8_tensor", new TensorDataType(TensorType.fromSpec("tensor<int8>(x[2],y[3])")))); x.addField(new Field("dense_unbound_tensor", new TensorDataType(new TensorType.Builder().indexed("x").indexed("y").build()))); x.addField(new Field("mixed_tensor", new TensorDataType(new TensorType.Builder().mapped("x").indexed("y", 3).build()))); x.addField(new Field("mixed_bfloat16_tensor", new TensorDataType(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")))); x.addField(new Field("mixed_tensor_adv", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").mapped("z").indexed("a", 3).build()))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testpredicate"); x.addField(new Field("boolean", DataType.PREDICATE)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testint"); x.addField(new Field("integerfield", DataType.INT)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testnull"); x.addField(new Field("intfield", DataType.INT)); x.addField(new Field("stringfield", DataType.STRING)); x.addField(new Field("arrayfield", new ArrayDataType(DataType.STRING))); x.addField(new Field("weightedsetfield", new WeightedSetDataType(DataType.STRING, true, true))); x.addField(new Field("mapfield", new MapDataType(DataType.STRING, DataType.STRING))); x.addField(new Field("tensorfield", new TensorDataType(new TensorType.Builder().indexed("x").build()))); types.registerDocumentType(x); } } @After public void tearDown() throws Exception { types = null; parserFactory = null; } private JsonReader createReader(String jsonInput) { InputStream input = new ByteArrayInputStream(Utf8.toBytes(jsonInput)); return new JsonReader(types, input, parserFactory); } @Test public void readSingleDocumentPut() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " }", "}")); DocumentPut put = (DocumentPut) r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:smoke::doc1").operation(); smokeTestDoc(put.getDocument()); } @Test public final void readSingleDocumentUpdate() { JsonReader r = createReader(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': {", " 'assign': 'orOther' }}}")); DocumentUpdate doc = (DocumentUpdate) r.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::whee").operation(); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof AssignValueUpdate); } @Test public void readClearField() { JsonReader r = createReader(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'int1': {", " 'assign': null }}}")); DocumentUpdate doc = (DocumentUpdate) r.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::whee").operation(); FieldUpdate f = doc.getFieldUpdate("int1"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof ClearValueUpdate); assertNull(f.getValueUpdate(0).getValue()); } @Test public void smokeTest() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } @Test public void docIdLookaheadTest() throws IOException { JsonReader r = createReader(inputJson( "{ 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse'", " },", " 'put': 'id:unittest:smoke::doc1'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); smokeTestDoc(put.getDocument()); } @Test public void emptyDocTest() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:smoke::whee', 'fields': {}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); assertEquals("id:unittest:smoke::whee", parseInfo.documentId.toString()); } @Test public void testStruct() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:mirrors::whee',", " 'fields': {", " 'skuggsjaa': {", " 'sandra': 'person',", " 'cloud': 'another person' }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("skuggsjaa")); assertSame(Struct.class, f.getClass()); Struct s = (Struct) f; assertEquals("person", ((StringFieldValue) s.getFieldValue("sandra")).getString()); } private DocumentUpdate parseUpdate(String json) throws IOException { InputStream rawDoc = new ByteArrayInputStream(Utf8.toBytes(json)); JsonReader r = new JsonReader(types, rawDoc, parserFactory); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentUpdate update = new DocumentUpdate(docType, parseInfo.documentId); new VespaJsonDocumentReader(false).readUpdate(parseInfo.fieldsBuffer, update); return update; } @Test public void testStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(inputJson("{ 'update': 'id:unittest:mirrors:g=test:whee',", " 'create': true,", " 'fields': {", " 'skuggsjaa': {", " 'assign': {", " 'sandra': 'person',", " 'cloud': 'another person' }}}}")); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(2, s.getFieldCount()); assertEquals(new StringFieldValue("person"), s.getFieldValue(s.getField("sandra"))); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(107, buf.position()); } @Test public final void testEmptyStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(inputJson("{ 'update': 'id:unittest:mirrors:g=test:whee',", " 'create': true,", " 'fields': { ", " 'skuggsjaa': {", " 'assign': { } }}}")); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(0, s.getFieldCount()); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(69, buf.position()); } @Test public void testUpdateArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}}")); checkSimpleArrayAdd(doc); } @Test public void testUpdateWeighted() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'add': {", " 'person': 37,", " 'another person': 41 }}}}")); Map<String, Integer> weights = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; final String s = ((StringFieldValue) adder.getValue()).getString(); weights.put(s, adder.getWeight()); } assertEquals(2, weights.size()); final String o = "person"; final String o2 = "another person"; assertTrue(weights.containsKey(o)); assertTrue(weights.containsKey(o2)); assertEquals(Integer.valueOf(37), weights.get(o)); assertEquals(Integer.valueOf(41), weights.get(o2)); } @Test public void testUpdateMatch() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'match': {", " 'element': 'person',", " 'increment': 13 }}}}")); Map<String, Tuple2<Number, String>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); String op = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperator().toString(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()).getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertEquals("ADD", matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } @SuppressWarnings({ "cast", "unchecked", "rawtypes" }) @Test public void testArithmeticOperators() throws IOException { Tuple2[] operations = new Tuple2[] { new Tuple2<String, Operator>(UPDATE_DECREMENT, ArithmeticValueUpdate.Operator.SUB), new Tuple2<String, Operator>(UPDATE_DIVIDE, ArithmeticValueUpdate.Operator.DIV), new Tuple2<String, Operator>(UPDATE_INCREMENT, ArithmeticValueUpdate.Operator.ADD), new Tuple2<String, Operator>(UPDATE_MULTIPLY, ArithmeticValueUpdate.Operator.MUL) }; for (Tuple2<String, Operator> operator : operations) { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'match': {", " 'element': 'person',", " '" + (String) operator.first + "': 13 }}}}")); Map<String, Tuple2<Number, Operator>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); Operator op = ((ArithmeticValueUpdate) adder .getUpdate()).getOperator(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertSame(operator.second, matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } } @SuppressWarnings("rawtypes") @Test public void testArrayIndexing() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'match': {", " 'element': 3,", " 'assign': 'nalle' }}}}")); Map<Number, String> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualarray"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final Number key = ((IntegerFieldValue) adder.getValue()) .getNumber(); String op = ((StringFieldValue) ((AssignValueUpdate) adder.getUpdate()) .getValue()).getString(); matches.put(key, op); } assertEquals(1, matches.size()); Number n = Integer.valueOf(3); assertEquals("nalle", matches.get(n)); } @Test public void testDocumentRemove() { JsonReader r = createReader(inputJson("{'remove': 'id:unittest:smoke::whee'}")); DocumentType docType = r.readDocumentType(new DocumentId("id:unittest:smoke::whee")); assertEquals("smoke", docType.getName()); } private Document docFromJson(String json) throws IOException { JsonReader r = createReader(json); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); return put.getDocument(); } @Test public void testWeightedSet() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'nalle': 2,", " 'tralle': 7 }}}")); FieldValue f = doc.getFieldValue(doc.getField("actualset")); assertSame(WeightedSet.class, f.getClass()); WeightedSet<?> w = (WeightedSet<?>) f; assertEquals(2, w.size()); assertEquals(Integer.valueOf(2), w.get(new StringFieldValue("nalle"))); assertEquals(Integer.valueOf(7), w.get(new StringFieldValue("tralle"))); } @Test public void testArray() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': [", " 'nalle',", " 'tralle' ]}}")); FieldValue f = doc.getFieldValue(doc.getField("actualarray")); assertSame(Array.class, f.getClass()); Array<?> a = (Array<?>) f; assertEquals(2, a.size()); assertEquals(new StringFieldValue("nalle"), a.get(0)); assertEquals(new StringFieldValue("tralle"), a.get(1)); } @Test public void testMap() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testmap::whee',", " 'fields': {", " 'actualmap': {", " 'nalle': 'kalle',", " 'tralle': 'skalle' }}}")); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testOldMap() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testmap::whee',", " 'fields': {", " 'actualmap': [", " { 'key': 'nalle', 'value': 'kalle'},", " { 'key': 'tralle', 'value': 'skalle'} ]}}")); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testPositionPositive() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': 'N63.429722;E10.393333' }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionOld() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': {'x':10393333,'y':63429722} }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testGeoPosition() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': {'lat':63.429722,'lng':10.393333} }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testGeoPositionNoAbbreviations() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': {'latitude':63.429722,'longitude':10.393333} }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionGeoPos() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'geopos': 'N63.429722;E10.393333' }}")); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); } @Test public void testPositionOldGeoPos() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'geopos': {'x':10393333,'y':63429722} }}")); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); } @Test public void testGeoPositionGeoPos() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'geopos': {'lat':63.429722,'lng':10.393333} }}")); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); assertEquals(PositionDataType.INSTANCE, f.getDataType()); } @Test public void testPositionNegative() throws IOException { Document doc = docFromJson(inputJson("{ 'put': 'id:unittest:testsinglepos::bamf',", " 'fields': {", " 'singlepos': 'W46.63;S23.55' }}")); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(-46630000, PositionDataType.getXValue(f).getInteger()); assertEquals(-23550000, PositionDataType.getYValue(f).getInteger()); } @Test public void testRaw() throws IOException { String base64 = new String(new JsonStringEncoder().quoteAsString( Base64.getEncoder().withoutPadding().encodeToString(Utf8.toBytes("smoketest")))); String s = fieldStringFromBase64RawContent(base64); assertEquals("smoketest", s); } @Test public void can_read_legacy_chunked_base64_raw_field_encoding() throws IOException { String expected = "this is a string with an impressive length. it's long enough to reach the end of the line, wow!"; String base64withDelims = "dGhpcyBpcyBhIHN0cmluZyB3aXRoIGFuIGltcHJlc3NpdmUgbGVuZ3RoLiBpdCdzIGxvbmcgZW5v\\r\\n" + "dWdoIHRvIHJlYWNoIHRoZSBlbmQgb2YgdGhlIGxpbmUsIHdvdyE=\\r\\n"; assertEquals(expected, fieldStringFromBase64RawContent(base64withDelims)); } private String fieldStringFromBase64RawContent(String base64data) throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testraw::whee',", " 'fields': {", " 'actualraw': '" + base64data + "' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue(doc.getField("actualraw")); assertSame(Raw.class, f.getClass()); Raw s = (Raw) f; return Utf8.toString(s.getByteBuffer()); } @Test public void testMapStringToArrayOfInt() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'bamse': [1, 2, 3] }}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldMapStringToArrayOfInt() throws IOException { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': [", " { 'key': 'bamse', 'value': [1, 2, 3] } ]}}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); Document doc = put.getDocument(); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToString() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': {", " 'assign': 'orOther' }}}")); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); AssignValueUpdate a = (AssignValueUpdate) f.getValueUpdate(0); assertEquals(new StringFieldValue("orOther"), a.getValue()); } @Test public void testAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'assign': { 'bamse': [1, 2, 3] }}}}")); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testMapStringToArrayOfInt::whee',", " 'fields': {", " 'actualMapStringToArrayOfInt': {", " 'assign': [", " { 'key': 'bamse', 'value': [1, 2, 3] } ]}}}")); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToWeightedSet() throws IOException { DocumentUpdate doc = parseUpdate(inputJson("{ 'update': 'id:unittest:testset::whee',", " 'fields': {", " 'actualset': {", " 'assign': {", " 'person': 37,", " 'another person': 41 }}}}")); FieldUpdate x = doc.getFieldUpdate("actualset"); assertEquals(1, x.size()); AssignValueUpdate assign = (AssignValueUpdate) x.getValueUpdate(0); WeightedSet<?> w = (WeightedSet<?>) assign.getValue(); assertEquals(2, w.size()); assertEquals(Integer.valueOf(37), w.get(new StringFieldValue("person"))); assertEquals(Integer.valueOf(41), w.get(new StringFieldValue("another person"))); } @Test public void testCompleteFeed() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }},", "{ 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}},", "{ 'remove': 'id:unittest:smoke::whee' }]")); controlBasicFeed(r); } @Test public void testCompleteFeedWithCreateAndCondition() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }},", "{", " 'condition':'bla',", " 'update': 'id:unittest:testarray::whee',", " 'create':true,", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}}},", "{ 'remove': 'id:unittest:smoke::whee' }]")); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testUpdateWithConditionAndCreateInDifferentOrdering() { int documentsCreated = 106; List<String> parts = Arrays.asList( "\"condition\":\"bla\"", "\"update\": \"id:unittest:testarray::whee\"", " \"fields\": { " + "\"actualarray\": { \"add\": [" + " \"person\",\"another person\"]}}", " \"create\":true"); Random random = new Random(42); StringBuilder documents = new StringBuilder("["); for (int x = 0; x < documentsCreated; x++) { Collections.shuffle(parts, random); documents.append("{").append(Joiner.on(",").join(parts)).append("}"); if (x < documentsCreated -1) { documents.append(","); } } documents.append("]"); InputStream rawDoc = new ByteArrayInputStream( Utf8.toBytes(documents.toString())); JsonReader r = new JsonReader(types, rawDoc, parserFactory); for (int x = 0; x < documentsCreated; x++) { DocumentUpdate update = (DocumentUpdate) r.next(); checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); } assertNull(r.next()); } @Test public void testCreateIfNonExistentInPut() { JsonReader r = createReader(inputJson("[{", " 'create':true,", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse' },", " 'put': 'id:unittest:smoke::whee'", "}]")); var op = r.next(); var put = (DocumentPut) op; assertTrue(put.getCreateIfNonExistent()); } @Test public void testCompleteFeedWithIdAfterFields() { JsonReader r = createReader(inputJson("[", "{", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' },", " 'put': 'id:unittest:smoke::whee'", "},", "{", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person' ]}},", " 'update': 'id:unittest:testarray::whee'", "},", "{ 'remove': 'id:unittest:smoke::whee' }]")); controlBasicFeed(r); } protected void controlBasicFeed(JsonReader r) { DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testCompleteFeedWithEmptyDoc() { JsonReader r = createReader(inputJson("[", "{ 'put': 'id:unittest:smoke::whee', 'fields': {} },", "{ 'update': 'id:unittest:testarray::whee', 'fields': {} },", "{ 'remove': 'id:unittest:smoke::whee' }]")); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); assertEquals("smoke", doc.getId().getDocType()); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; assertEquals("testarray", update.getId().getDocType()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } private void checkSimpleArrayAdd(DocumentUpdate update) { Set<String> toAdd = new HashSet<>(); FieldUpdate x = update.getFieldUpdate("actualarray"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; toAdd.add(((StringFieldValue) adder.getValue()).getString()); } assertEquals(2, toAdd.size()); assertTrue(toAdd.contains("person")); assertTrue(toAdd.contains("another person")); } private void smokeTestDoc(Document doc) { FieldValue boolField = doc.getFieldValue(doc.getField("flag")); assertSame(BoolFieldValue.class, boolField.getClass()); assertTrue((Boolean)boolField.getWrappedValue()); FieldValue stringField = doc.getFieldValue(doc.getField("nalle")); assertSame(StringFieldValue.class, stringField.getClass()); assertEquals("bamse", ((StringFieldValue) stringField).getString()); } @Test public void nonExistingFieldCausesException() throws IOException { JsonReader r = createReader(inputJson( "{ 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'smething': 'smoketest',", " 'nalle': 'bamse' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); try { new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); fail(); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().startsWith("No field 'smething' in the structure of type 'smoke'")); } } @Test public void nonExistingFieldsCanBeIgnoredInPut() throws IOException { JsonReader r = createReader(inputJson( "{ ", " 'put': 'id:unittest:smoke::doc1',", " 'fields': {", " 'nonexisting1': 'ignored value',", " 'field1': 'value1',", " 'nonexisting2': {", " 'blocks':{", " 'a':[2.0,3.0],", " 'b':[4.0,5.0]", " }", " },", " 'field2': 'value2',", " 'nonexisting3': {", " 'cells': [{'address': {'x': 'x1'}, 'value': 1.0}]", " },", " 'tensor1': {'cells': {'x1': 1.0}},", " 'nonexisting4': 'ignored value'", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); boolean fullyApplied = new VespaJsonDocumentReader(true).readPut(parseInfo.fieldsBuffer, put); assertFalse(fullyApplied); assertNull(put.getDocument().getField("nonexisting1")); assertEquals("value1", put.getDocument().getFieldValue("field1").toString()); assertNull(put.getDocument().getField("nonexisting2")); assertEquals("value2", put.getDocument().getFieldValue("field2").toString()); assertNull(put.getDocument().getField("nonexisting3")); assertEquals(Tensor.from("tensor(x{}):{{x:x1}:1.0}"), put.getDocument().getFieldValue("tensor1").getWrappedValue()); assertNull(put.getDocument().getField("nonexisting4")); } @Test public void nonExistingFieldsCanBeIgnoredInUpdate() throws IOException{ JsonReader r = createReader(inputJson( "{ ", " 'update': 'id:unittest:smoke::doc1',", " 'fields': {", " 'nonexisting1': { 'assign': 'ignored value' },", " 'field1': { 'assign': 'value1' },", " 'nonexisting2': { " + " 'assign': {", " 'blocks': {", " 'a':[2.0,3.0],", " 'b':[4.0,5.0]", " }", " }", " },", " 'field2': { 'assign': 'value2' },", " 'nonexisting3': {", " 'assign' : {", " 'cells': [{'address': {'x': 'x1'}, 'value': 1.0}]", " }", " },", " 'tensor1': {'assign': { 'cells': {'x1': 1.0} } },", " 'nonexisting4': { 'assign': 'ignored value' }", " }", "}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentUpdate update = new DocumentUpdate(docType, parseInfo.documentId); boolean fullyApplied = new VespaJsonDocumentReader(true).readUpdate(parseInfo.fieldsBuffer, update); assertFalse(fullyApplied); assertNull(update.getFieldUpdate("nonexisting1")); assertEquals("value1", update.getFieldUpdate("field1").getValueUpdates().get(0).getValue().getWrappedValue().toString()); assertNull(update.getFieldUpdate("nonexisting2")); assertEquals("value2", update.getFieldUpdate("field2").getValueUpdates().get(0).getValue().getWrappedValue().toString()); assertNull(update.getFieldUpdate("nonexisting3")); assertEquals(Tensor.from("tensor(x{}):{{x:x1}:1.0}"), update.getFieldUpdate("tensor1").getValueUpdates().get(0).getValue().getWrappedValue()); assertNull(update.getFieldUpdate("nonexisting4")); } @Test public void feedWithBasicErrorTest() { JsonReader r = createReader(inputJson("[", " { 'put': 'id:test:smoke::0', 'fields': { 'something': 'foo' } },", " { 'put': 'id:test:smoke::1', 'fields': { 'something': 'foo' } },", " { 'put': 'id:test:smoke::2', 'fields': { 'something': 'foo' } },", "]")); try { while (r.next() != null) ; fail(); } catch (RuntimeException e) { assertTrue(e.getMessage().contains("JsonParseException")); } } @Test public void idAsAliasForPutTest() throws IOException{ JsonReader r = createReader(inputJson("{ 'id': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': 'smoketest',", " 'flag': true,", " 'nalle': 'bamse' }}")); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); boolean fullyApplied = new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); assertTrue(fullyApplied); smokeTestDoc(put.getDocument()); } private void testFeedWithTestAndSetCondition(String jsonDoc) { ByteArrayInputStream parseInfoDoc = new ByteArrayInputStream(Utf8.toBytes(jsonDoc)); JsonReader reader = new JsonReader(types, parseInfoDoc, parserFactory); int NUM_OPERATIONS_IN_FEED = 3; for (int i = 0; i < NUM_OPERATIONS_IN_FEED; i++) { DocumentOperation operation = reader.next(); assertTrue("A test and set condition should be present", operation.getCondition().isPresent()); assertEquals("DocumentOperation's test and set condition should be equal to the one in the JSON feed", "smoke.something == \"smoketest\"", operation.getCondition().getSelection()); } assertNull(reader.next()); } @Test public void testFeedWithTestAndSetConditionOrderingOne() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'put': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " }", " },", " {", " 'update': 'id:unittest:testarray::whee',", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " },", " {", " 'remove': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\''", " }", "]" )); } @Test public void testFeedWithTestAndSetConditionOrderingTwo() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " }", " },", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " },", " {", " 'condition': 'smoke.something == \\'smoketest\\'',", " 'remove': 'id:unittest:smoke::whee'", " }", "]" )); } @Test public void testFeedWithTestAndSetConditionOrderingThree() { testFeedWithTestAndSetCondition( inputJson("[", " {", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " },", " 'condition': 'smoke.something == \\'smoketest\\''", " },", " {", " 'update': 'id:unittest:testarray::whee',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " },", " 'condition': 'smoke.something == \\'smoketest\\''", " },", " {", " 'remove': 'id:unittest:smoke::whee',", " 'condition': 'smoke.something == \\'smoketest\\''", " }", "]" )); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldAfterFieldsFieldShouldFailParse() { final String jsonData = inputJson( "[", " {", " 'put': 'id:unittest:smoke::whee',", " 'fields': {", " 'something': 'smoketest',", " 'nalle': 'bamse'", " },", " 'bjarne': 'stroustrup'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldBeforeFieldsFieldShouldFailParse() { final String jsonData = inputJson( "[", " {", " 'update': 'id:unittest:testarray::whee',", " 'what is this': 'nothing to see here',", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldWithoutFieldsFieldShouldFailParse() { String jsonData = inputJson( "[", " {", " 'remove': 'id:unittest:smoke::whee',", " 'what is love': 'baby, do not hurt me... much'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test public void testMissingOperation() { try { String jsonData = inputJson( "[", " {", " 'fields': {", " 'actualarray': {", " 'add': [", " 'person',", " 'another person'", " ]", " }", " }", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Missing a document operation ('put', 'update' or 'remove')", e.getMessage()); } } @Test public void testMissingFieldsMapInPut() { try { String jsonData = inputJson( "[", " {", " 'put': 'id:unittest:smoke::whee'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("put of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testMissingFieldsMapInUpdate() { try { String jsonData = inputJson( "[", " {", " 'update': 'id:unittest:smoke::whee'", " }", "]"); new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Update of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testNullValues() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testnull::doc1',", " 'fields': {", " 'intfield': null,", " 'stringfield': null,", " 'arrayfield': null,", " 'weightedsetfield': null,", " 'mapfield': null,", " 'tensorfield': null", " }", "}")); DocumentPut put = (DocumentPut) r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:testnull::doc1").operation(); Document doc = put.getDocument(); assertFieldValueNull(doc, "intfield"); assertFieldValueNull(doc, "stringfield"); assertFieldValueNull(doc, "arrayfield"); assertFieldValueNull(doc, "weightedsetfield"); assertFieldValueNull(doc, "mapfield"); assertFieldValueNull(doc, "tensorfield"); } @Test(expected=JsonReaderException.class) public void testNullArrayElement() { JsonReader r = createReader(inputJson("{ 'put': 'id:unittest:testnull::doc1',", " 'fields': {", " 'arrayfield': [ null ]", " }", "}")); r.readSingleDocument(DocumentOperationType.PUT, "id:unittest:testnull::doc1"); fail(); } private void assertFieldValueNull(Document doc, String fieldName) { Field field = doc.getField(fieldName); assertNotNull(field); FieldValue fieldValue = doc.getFieldValue(field); assertNull(fieldValue); } static ByteArrayInputStream jsonToInputStream(String json) { return new ByteArrayInputStream(Utf8.toBytes(json)); } @Test public void testParsingWithoutTensorField() { Document doc = createPutWithoutTensor().getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals("id:unittest:testtensor::0", doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField("sparse_tensor")); assertNull(fieldValue); } @Test public void testParsingOfEmptyTensor() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor("{}")); } @Test public void testParsingOfTensorWithEmptyCells() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor(inputJson("{ 'cells': [] }"))); } @Test public void testDisallowedDenseTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{ 'values': [] }"), "dense_tensor", "The 'values' array does not contain any values"); assertCreatePutFails(inputJson("{ 'values': '' }"), "dense_tensor", "The 'values' string does not contain any values"); } @Test public void testDisallowedMixedTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{\"blocks\":{ \"a\": [] } }"), "mixed_tensor", "Expected 3 values, but got 0"); assertCreatePutFails(inputJson("{\"blocks\":[ {\"address\":{\"x\":\"a\"}, \"values\": [] } ] }"), "mixed_tensor", "Expected 3 values, but got 0"); } @Test public void testParsingOfSparseTensorWithCells() { Tensor tensor = assertSparseTensorField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createPutWithSparseTensor( """ { "type": "tensor(x{},y{})", "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 }, { "address": { "x": "c", "y": "b" }, "value": 3.0 } ] } """)); assertTrue(tensor instanceof MappedTensor); // any functional instance is fine } @Test public void testParsingOfDenseTensorWithCells() { Tensor tensor = assertTensorField("{{x:0,y:0}:2.0,{x:1,y:0}:3.0}}", createPutWithTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' },", " 'value': 2.0 },", " { 'address': { 'x': '1', 'y': '0' },", " 'value': 3.0 }", " ]", "}"), "dense_unbound_tensor"), "dense_unbound_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorOnDenseForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson("{", " 'values': [2.0, 3.0, 4.0, 5.0, 6.0, 7.0]", "}"), "dense_tensor"), "dense_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<int8>(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson("{", " 'values': \"020304050607\"", "}"), "dense_int8_tensor"), "dense_int8_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfMixedTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")); builder.cell().label("x", "foo").label("y", 0).value(2.0); builder.cell().label("x", "foo").label("y", 1).value(3.0); builder.cell().label("x", "foo").label("y", 2).value(4.0); builder.cell().label("x", "bar").label("y", 0).value(5.0); builder.cell().label("x", "bar").label("y", 1).value(6.0); builder.cell().label("x", "bar").label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":[" + "{\"address\":{\"x\":\"foo\"},\"values\":\"400040404080\"}," + "{\"address\":{\"x\":\"bar\"},\"values\":\"40A040C040E0\"}" + "]}"; var put = createPutWithTensor(inputJson(mixedJson), "mixed_bfloat16_tensor"); Tensor tensor = assertTensorField(expected, put, "mixed_bfloat16_tensor"); } /** Tests parsing of various tensor values set at the root, i.e. no 'cells', 'blocks' or 'values' */ @Test public void testDirectValue() { assertTensorField("tensor(x{}):{a:2, b:3}", "sparse_single_dimension_tensor", "{'a':2.0, 'b':3.0}"); assertTensorField("tensor(x[2],y[3]):[2, 3, 4, 5, 6, 7]]", "dense_tensor", "[2, 3, 4, 5, 6, 7]"); assertTensorField("tensor(x[2],y[3]):[2, 3, 4, 5, 6, 7]]", "dense_tensor", "[[2, 3, 4], [5, 6, 7]]"); assertTensorField("tensor(x{},y[3]):{a:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'a':[2, 3, 4], 'b':[4, 5, 6]}"); assertTensorField("tensor(x{},y{}):{{x:a,y:0}:2, {x:b,y:1}:3}", "sparse_tensor", "[{'address':{'x':'a','y':'0'},'value':2}, {'address':{'x':'b','y':'1'},'value':3}]"); } @Test public void testDirectValueReservedNameKeys() { // Single-valued assertTensorField("tensor(x{}):{cells:2, b:3}", "sparse_single_dimension_tensor", "{'cells':2.0, 'b':3.0}"); assertTensorField("tensor(x{}):{values:2, b:3}", "sparse_single_dimension_tensor", "{'values':2.0, 'b':3.0}"); assertTensorField("tensor(x{}):{block:2, b:3}", "sparse_single_dimension_tensor", "{'block':2.0, 'b':3.0}"); // Multi-valued assertTensorField("tensor(x{},y[3]):{cells:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'cells':[2, 3, 4], 'b':[4, 5, 6]}"); assertTensorField("tensor(x{},y[3]):{values:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'values':[2, 3, 4], 'b':[4, 5, 6]}"); assertTensorField("tensor(x{},y[3]):{block:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'block':[2, 3, 4], 'b':[4, 5, 6]}"); } @Test public void testParsingOfMixedTensorOnMixedForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = """ { "blocks":[ {"address":{"x":"0"},"values":[2.0,3.0,4.0]}, {"address":{"x":"1"},"values":[5.0,6.0,7.0]} ] } """; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance String mixedJsonDirect = """ [ {"address":{"x":"0","y":"0"},"value":2.0}, {"address":{"x":"0","y":"1"},"value":3.0}, {"address":{"x":"0","y":"2"},"value":4.0}, {"address":{"x":"1","y":"0"},"value":5.0}, {"address":{"x":"1","y":"1"},"value":6.0}, {"address":{"x":"1","y":"2"},"value":7.0} ] """; Tensor tensorDirect = assertTensorField(expected, createPutWithTensor(inputJson(mixedJsonDirect), "mixed_tensor"), "mixed_tensor"); assertTrue(tensorDirect instanceof MixedTensor); // this matters for performance } @Test public void testMixedTensorInMixedFormWithSingleSparseDimensionShortForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = "{\"blocks\":{" + "\"0\":[2.0,3.0,4.0]," + "\"1\":[5.0,6.0,7.0]" + "}}"; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance } @Test public void testParsingOfTensorWithSingleCellInDifferentJsonOrder() { assertSparseTensorField("{{x:a,y:b}:2.0}", createPutWithSparseTensor(inputJson("{", " 'cells': [", " { 'value': 2.0,", " 'address': { 'x': 'a', 'y': 'b' } }", " ]", "}"))); } @Test public void testAssignUpdateOfEmptySparseTensor() { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithSparseTensor("{}")); } @Test public void testAssignUpdateOfEmptyDenseTensor() { try { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithTensor("{}", "dense_unbound_tensor")); } catch (IllegalArgumentException e) { assertEquals("An indexed tensor must have a value", "Error in 'dense_unbound_tensor': Tensor of type tensor(x[],y[]) has no values", Exceptions.toMessageString(e)); } } @Test public void testAssignUpdateOfNullTensor() { ClearValueUpdate clearUpdate = (ClearValueUpdate) getTensorField(createAssignUpdateWithSparseTensor(null)).getValueUpdate(0); assertNotNull(clearUpdate); assertNull(clearUpdate.getValue()); } @Test public void testAssignUpdateOfTensorWithCells() { assertTensorAssignUpdateSparseField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createAssignUpdateWithSparseTensor(inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' },", " 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'b' },", " 'value': 3.0 }", " ]", "}"))); } @Test public void testAssignUpdateOfTensorDenseShortForm() { assertTensorAssignUpdateDenseField("tensor(x[2],y[3]):[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]", createAssignUpdateWithTensor(inputJson("{", " 'values': [1,2,3,4,5,6]", "}"), "dense_tensor")); } @Test public void tensor_modify_update_with_replace_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_add_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, "sparse_tensor", inputJson("{", " 'operation': 'add',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_multiply_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "sparse_tensor", inputJson("{", " 'operation': 'multiply',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_treats_the_input_tensor_as_sparse() { // Note that the type of the tensor in the modify update is sparse (it only has mapped dimensions). assertTensorModifyUpdate("tensor(x{},y{}):{{x:0,y:0}:2.0, {x:1,y:2}:3.0}", TensorModifyUpdate.Operation.REPLACE, "dense_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' }, 'value': 2.0 },", " { 'address': { 'x': '1', 'y': '2' }, 'value': 3.0 } ]}")); } @Test public void tensor_modify_update_on_non_tensor_field_throws() { try { JsonReader reader = createReader(inputJson("{ 'update': 'id:unittest:smoke::doc1',", " 'fields': {", " 'something': {", " 'modify': {} }}}")); reader.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::doc1"); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Error in 'something': A modify update can only be applied to tensor fields. Field 'something' is of type 'string'", Exceptions.toMessageString(e)); } } @Test public void tensor_modify_update_on_dense_unbound_tensor_throws() { illegalTensorModifyUpdate("Error in 'dense_unbound_tensor': A modify update cannot be applied to tensor types with indexed unbound dimensions. Field 'dense_unbound_tensor' has unsupported tensor type 'tensor(x[],y[])'", "dense_unbound_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '0' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorModifyUpdate("{{x:a}:2.0, {x:c}: 3.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_single_dimension_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': {", " 'a': 2.0,", " 'c': 3.0 }}")); } @Test public void tensor_modify_update_with_replace_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_array() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': [", " { 'address': { 'x': 'a' }, 'values': [1,2,3] } ]}")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_must_specify_full_subspace() { illegalTensorModifyUpdate("Error in 'mixed_tensor': At {x:a}: Expected 3 values, but got 2", "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': {", " 'a': [2,3] } }")); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_map() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", inputJson("{", " 'operation': 'replace',", " 'blocks': {", " 'a': [1,2,3] } }")); } @Test public void tensor_modify_update_with_add_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.ADD, "mixed_tensor", inputJson("{", " 'operation': 'add',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_multiply_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "mixed_tensor", inputJson("{", " 'operation': 'multiply',", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 } ]}")); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws() { illegalTensorModifyUpdate("Error in 'dense_tensor': Dimension 'y' has label '3' but type is tensor(x[2],y[3])", "dense_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws_mixed() { illegalTensorModifyUpdate("Error in 'mixed_tensor': Dimension 'y' has label '3' but type is tensor(x{},y[3])", "mixed_tensor", "{", " 'operation': 'replace',", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_with_unknown_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown operation 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", "{", " 'operation': 'unknown',", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 } ]}"); } @Test public void tensor_modify_update_without_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain an operation", "sparse_tensor", "{", " 'cells': [] }"); } @Test public void tensor_modify_update_without_cells_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", "{", " 'operation': 'replace' }"); } @Test public void tensor_modify_update_with_unknown_content_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown JSON string 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", "{", " 'unknown': 'here' }"); } @Test public void tensor_add_update_on_sparse_tensor() { assertTensorAddUpdate("{{x:a,y:b}:2.0, {x:c,y:d}: 3.0}", "sparse_tensor", inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'd' }, 'value': 3.0 } ]}")); } @Test public void tensor_add_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorAddUpdate("{{x:a}:2.0, {x:c}: 3.0}", "sparse_single_dimension_tensor", inputJson("{", " 'cells': {", " 'a': 2.0,", " 'c': 3.0 }}")); } @Test public void tensor_add_update_on_mixed_tensor() { assertTensorAddUpdate("{{x:a,y:0}:2.0, {x:a,y:1}:3.0, {x:a,y:2}:0.0}", "mixed_tensor", inputJson("{", " 'cells': [", " { 'address': { 'x': 'a', 'y': '0' }, 'value': 2.0 },", " { 'address': { 'x': 'a', 'y': '1' }, 'value': 3.0 } ]}")); } @Test public void tensor_add_update_on_mixed_with_out_of_bound_dense_cells_throws() { illegalTensorAddUpdate("Error in 'mixed_tensor': Index 3 out of bounds for length 3", "mixed_tensor", "{", " 'cells': [", " { 'address': { 'x': '0', 'y': '3' }, 'value': 2.0 } ]}"); } @Test public void tensor_add_update_on_dense_tensor_throws() { illegalTensorAddUpdate("Error in 'dense_tensor': An add update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", "{", " 'cells': [] }"); } @Test public void tensor_add_update_on_not_fully_specified_cell_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Missing a label for dimension 'y' for tensor(x{},y{})", "sparse_tensor", "{", " 'cells': [", " { 'address': { 'x': 'a' }, 'value': 2.0 } ]}"); } @Test public void tensor_add_update_without_cells_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Add update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", "{}"); illegalTensorAddUpdate("Error in 'mixed_tensor': Add update for field 'mixed_tensor' does not contain tensor cells", "mixed_tensor", "{}"); } @Test public void tensor_remove_update_on_sparse_tensor() { assertTensorRemoveUpdate("{{x:a,y:b}:1.0,{x:c,y:d}:1.0}", "sparse_tensor", inputJson("{", " 'addresses': [", " { 'x': 'a', 'y': 'b' },", " { 'x': 'c', 'y': 'd' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor() { assertTensorRemoveUpdate("{{x:1}:1.0,{x:2}:1.0}", "mixed_tensor", inputJson("{", " 'addresses': [", " { 'x': '1' },", " { 'x': '2' } ]}")); } @Test public void tensor_remove_update_on_sparse_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{y:b}:1.0,{y:d}:1.0}", "sparse_tensor", inputJson("{", " 'addresses': [", " { 'y': 'b' },", " { 'y': 'd' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{x:1,z:a}:1.0,{x:2,z:b}:1.0}", "mixed_tensor_adv", inputJson("{", " 'addresses': [", " { 'x': '1', 'z': 'a' },", " { 'x': '2', 'z': 'b' } ]}")); } @Test public void tensor_remove_update_on_mixed_tensor_with_dense_addresses_throws() { illegalTensorRemoveUpdate("Error in 'mixed_tensor': Indexed dimension address 'y' should not be specified in remove update", "mixed_tensor", "{", " 'addresses': [", " { 'x': '1', 'y': '0' },", " { 'x': '2', 'y': '0' } ]}"); } @Test public void tensor_remove_update_on_dense_tensor_throws() { illegalTensorRemoveUpdate("Error in 'dense_tensor': A remove update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", "{", " 'addresses': [] }"); } @Test public void tensor_remove_update_with_stray_dimension_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{},y{}) does not contain dimension 'foo'", "sparse_tensor", "{", " 'addresses': [", " { 'x': 'a', 'foo': 'b' } ]}"); illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{}) does not contain dimension 'foo'", "sparse_tensor", "{", " 'addresses': [", " { 'x': 'c' },", " { 'x': 'a', 'foo': 'b' } ]}"); } @Test public void tensor_remove_update_without_cells_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': Remove update for field 'sparse_tensor' does not contain tensor addresses", "sparse_tensor", "{'addresses': [] }"); illegalTensorRemoveUpdate("Error in 'mixed_tensor': Remove update for field 'mixed_tensor' does not contain tensor addresses", "mixed_tensor", "{'addresses': [] }"); } @Test public void require_that_parser_propagates_datatype_parser_errors_predicate() { assertParserErrorMatches( "Error in document 'id:unittest:testpredicate::0' - could not parse field 'boolean' of type 'predicate': " + "line 1:10 no viable alternative at character '>'", "[", " {", " 'fields': {", " 'boolean': 'timestamp > 9000'", " },", " 'put': 'id:unittest:testpredicate::0'", " }", "]" ); } @Test public void require_that_parser_propagates_datatype_parser_errors_string_as_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \" 1\"", "[", " {", " 'fields': {", " 'integerfield': ' 1'", " },", " 'put': 'id:unittest:testint::0'", " }", "]" ); } @Test public void require_that_parser_propagates_datatype_parser_errors_overflowing_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \"281474976710656\"", "[", " {", " 'fields': {", " 'integerfield': 281474976710656", " },", " 'put': 'id:unittest:testint::0'", " }", "]" ); } @Test public void requireThatUnknownDocTypeThrowsIllegalArgumentException() { final String jsonData = inputJson( "[", " {", " 'put': 'id:ns:walrus::walrus1',", " 'fields': {", " 'aField': 42", " }", " }", "]"); try { new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail(); } catch (IllegalArgumentException e) { assertEquals("Document type walrus does not exist", e.getMessage()); } } private static final String TENSOR_DOC_ID = "id:unittest:testtensor::0"; private void illegalTensorModifyUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorModifyUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorAddUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorAddUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorRemoveUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorRemoveUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private DocumentPut createPutWithoutTensor() { JsonReader reader = createReader(inputJson("[ { 'put': '" + TENSOR_DOC_ID + "', 'fields': { } } ]")); return (DocumentPut) reader.next(); } private DocumentPut createPutWithSparseTensor(String inputTensor) { return createPutWithTensor(inputTensor, "sparse_tensor"); } private DocumentPut createPutWithTensor(String inputTensor, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'put': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': " + inputTensor + " }}]")); return (DocumentPut) reader.next(); } private DocumentUpdate createAssignUpdateWithSparseTensor(String inputTensor) { return createAssignUpdateWithTensor(inputTensor, "sparse_tensor"); } private DocumentUpdate createAssignUpdateWithTensor(String inputTensor, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'update': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': {", " 'assign': " + (inputTensor != null ? inputTensor : "null") + " } } } ]")); return (DocumentUpdate) reader.next(); } private static Tensor assertSparseTensorField(String expectedTensor, DocumentPut put) { return assertTensorField(expectedTensor, put, "sparse_tensor"); } private Tensor assertTensorField(String expectedTensor, String fieldName, String inputJson) { return assertTensorField(expectedTensor, createPutWithTensor(inputJson, fieldName), fieldName); } private static Tensor assertTensorField(String expectedTensor, DocumentPut put, String tensorFieldName) { return assertTensorField(Tensor.from(expectedTensor), put, tensorFieldName); } private static Tensor assertTensorField(Tensor expectedTensor, DocumentPut put, String tensorFieldName) { Document doc = put.getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals(TENSOR_DOC_ID, doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField(tensorFieldName)); assertEquals(expectedTensor, fieldValue.getTensor().get()); return fieldValue.getTensor().get(); } private static void assertTensorFieldUpdate(DocumentUpdate update, String tensorFieldName) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); assertEquals(1, update.fieldUpdates().size()); assertEquals(1, update.getFieldUpdate(tensorFieldName).size()); } private static void assertTensorAssignUpdateSparseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "sparse_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private static void assertTensorAssignUpdateDenseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "dense_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, String tensorFieldName, String modifyJson) { assertTensorModifyUpdate(expectedTensor, expectedOperation, tensorFieldName, createTensorModifyUpdate(modifyJson, tensorFieldName)); } private static void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorModifyUpdate modifyUpdate = (TensorModifyUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(expectedOperation, modifyUpdate.getOperation()); assertEquals(Tensor.from(expectedTensor), modifyUpdate.getValue().getTensor().get()); } private DocumentUpdate createTensorModifyUpdate(String modifyJson, String tensorFieldName) { return createTensorUpdate("modify", modifyJson, tensorFieldName); } private DocumentUpdate createTensorAddUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("add", tensorJson, tensorFieldName); } private DocumentUpdate createTensorRemoveUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("remove", tensorJson, tensorFieldName); } private DocumentUpdate createTensorUpdate(String operation, String tensorJson, String tensorFieldName) { JsonReader reader = createReader(inputJson("[", "{ 'update': '" + TENSOR_DOC_ID + "',", " 'fields': {", " '" + tensorFieldName + "': {", " '" + operation + "': " + tensorJson + " }}}]")); return (DocumentUpdate) reader.next(); } private void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorAddUpdate(expectedTensor, tensorFieldName, createTensorAddUpdate(tensorJson, tensorFieldName)); } private static void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorAddUpdate addUpdate = (TensorAddUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), addUpdate.getValue().getTensor().get()); } private void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorRemoveUpdate(expectedTensor, tensorFieldName, createTensorRemoveUpdate(tensorJson, tensorFieldName)); } private static void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorRemoveUpdate removeUpdate = (TensorRemoveUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), removeUpdate.getValue().getTensor().get()); } private static FieldUpdate getTensorField(DocumentUpdate update) { return getTensorField(update, "sparse_tensor"); } private static FieldUpdate getTensorField(DocumentUpdate update, String fieldName) { FieldUpdate fieldUpdate = update.getFieldUpdate(fieldName); assertEquals(1, fieldUpdate.size()); return fieldUpdate; } // NOTE: Do not call this method multiple times from a test method as it's using the ExpectedException rule private void assertParserErrorMatches(String expectedError, String... json) { String jsonData = inputJson(json); try { new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail(); } catch (JsonReaderException e) { assertEquals(expectedError, e.getMessage()); } } private void assertCreatePutFails(String tensor, String name, String msg) { try { createPutWithTensor(inputJson(tensor), name); fail("Expected exception"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains(msg)); } } }
cloudcompute/vespa
document/src/test/java/com/yahoo/document/json/JsonReaderTestCase.java
213,293
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.document.json; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.io.JsonStringEncoder; import com.google.common.base.Joiner; import com.yahoo.collections.Tuple2; import com.yahoo.document.ArrayDataType; import com.yahoo.document.DataType; import com.yahoo.document.Document; import com.yahoo.document.DocumentId; import com.yahoo.document.DocumentOperation; import com.yahoo.document.DocumentPut; import com.yahoo.document.DocumentRemove; import com.yahoo.document.DocumentType; import com.yahoo.document.DocumentTypeManager; import com.yahoo.document.DocumentUpdate; import com.yahoo.document.Field; import com.yahoo.document.MapDataType; import com.yahoo.document.PositionDataType; import com.yahoo.document.StructDataType; import com.yahoo.document.TensorDataType; import com.yahoo.document.WeightedSetDataType; import com.yahoo.document.datatypes.Array; import com.yahoo.document.datatypes.BoolFieldValue; import com.yahoo.document.datatypes.FieldValue; import com.yahoo.document.datatypes.IntegerFieldValue; import com.yahoo.document.datatypes.MapFieldValue; import com.yahoo.document.datatypes.Raw; import com.yahoo.document.datatypes.StringFieldValue; import com.yahoo.document.datatypes.Struct; import com.yahoo.document.datatypes.TensorFieldValue; import com.yahoo.document.datatypes.WeightedSet; import com.yahoo.document.internal.GeoPosType; import com.yahoo.document.json.readers.DocumentParseInfo; import com.yahoo.document.json.readers.VespaJsonDocumentReader; import com.yahoo.document.serialization.DocumentSerializer; import com.yahoo.document.serialization.DocumentSerializerFactory; import com.yahoo.document.update.AddValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate.Operator; import com.yahoo.document.update.AssignValueUpdate; import com.yahoo.document.update.ClearValueUpdate; import com.yahoo.document.update.FieldUpdate; import com.yahoo.document.update.MapValueUpdate; import com.yahoo.document.update.TensorAddUpdate; import com.yahoo.document.update.TensorModifyUpdate; import com.yahoo.document.update.TensorRemoveUpdate; import com.yahoo.document.update.ValueUpdate; import com.yahoo.io.GrowableByteBuffer; import com.yahoo.tensor.IndexedTensor; import com.yahoo.tensor.MappedTensor; import com.yahoo.tensor.MixedTensor; import com.yahoo.tensor.Tensor; import com.yahoo.tensor.TensorType; import com.yahoo.text.Utf8; import com.yahoo.yolean.Exceptions; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DECREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DIVIDE; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_INCREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_MULTIPLY; import static com.yahoo.test.json.JsonTestHelper.inputJson; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Basic test of JSON streams to Vespa document instances. * * @author Steinar Knutsen * @author bratseth */ public class JsonReaderTestCase { private DocumentTypeManager types; private JsonFactory parserFactory; @Before public void setUp() throws Exception { parserFactory = new JsonFactory(); types = new DocumentTypeManager(); { DocumentType x = new DocumentType("smoke"); x.addField(new Field("something", DataType.STRING)); x.addField(new Field("nalle", DataType.STRING)); x.addField(new Field("field1", DataType.STRING)); x.addField(new Field("field2", DataType.STRING)); x.addField(new Field("int1", DataType.INT)); x.addField(new Field("flag", DataType.BOOL)); x.addField(new Field("tensor1", DataType.getTensor(TensorType.fromSpec("tensor(x{})")))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("mirrors"); StructDataType woo = new StructDataType("woo"); woo.addField(new Field("sandra", DataType.STRING)); woo.addField(new Field("cloud", DataType.STRING)); x.addField(new Field("skuggsjaa", woo)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testarray"); DataType d = new ArrayDataType(DataType.STRING); x.addField(new Field("actualarray", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testset"); DataType d = new WeightedSetDataType(DataType.STRING, true, true); x.addField(new Field("actualset", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testmap"); DataType d = new MapDataType(DataType.STRING, DataType.STRING); x.addField(new Field("actualmap", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testraw"); DataType d = DataType.RAW; x.addField(new Field("actualraw", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testMapStringToArrayOfInt"); DataType value = new ArrayDataType(DataType.INT); DataType d = new MapDataType(DataType.STRING, value); x.addField(new Field("actualMapStringToArrayOfInt", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testArrayOfArrayOfInt"); DataType inner = new ArrayDataType(DataType.INT); DataType outer = new ArrayDataType(inner); x.addField(new Field("arrayOfArrayOfInt", outer)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testsinglepos"); DataType d = PositionDataType.INSTANCE; x.addField(new Field("singlepos", d)); x.addField(new Field("geopos", new GeoPosType(8))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testtensor"); x.addField(new Field("sparse_single_dimension_tensor", new TensorDataType(new TensorType.Builder().mapped("x").build()))); x.addField(new Field("sparse_tensor", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").build()))); x.addField(new Field("dense_tensor", new TensorDataType(new TensorType.Builder().indexed("x", 2).indexed("y", 3).build()))); x.addField(new Field("dense_int8_tensor", new TensorDataType(TensorType.fromSpec("tensor<int8>(x[2],y[3])")))); x.addField(new Field("dense_unbound_tensor", new TensorDataType(new TensorType.Builder().indexed("x").indexed("y").build()))); x.addField(new Field("mixed_tensor", new TensorDataType(new TensorType.Builder().mapped("x").indexed("y", 3).build()))); x.addField(new Field("mixed_bfloat16_tensor", new TensorDataType(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")))); x.addField(new Field("mixed_tensor_adv", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").mapped("z").indexed("a", 3).build()))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testpredicate"); x.addField(new Field("boolean", DataType.PREDICATE)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testint"); x.addField(new Field("integerfield", DataType.INT)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testnull"); x.addField(new Field("intfield", DataType.INT)); x.addField(new Field("stringfield", DataType.STRING)); x.addField(new Field("arrayfield", new ArrayDataType(DataType.STRING))); x.addField(new Field("weightedsetfield", new WeightedSetDataType(DataType.STRING, true, true))); x.addField(new Field("mapfield", new MapDataType(DataType.STRING, DataType.STRING))); x.addField(new Field("tensorfield", new TensorDataType(new TensorType.Builder().indexed("x").build()))); types.registerDocumentType(x); } } @After public void tearDown() throws Exception { types = null; parserFactory = null; } private JsonReader createReader(String jsonInput) { InputStream input = new ByteArrayInputStream(Utf8.toBytes(jsonInput)); return new JsonReader(types, input, parserFactory); } @Test public void readDocumentWithMissingFieldsField() { assertEquals("document is missing the required \"fields\" field", assertThrows(IllegalArgumentException.class, () -> createReader("{ }").readSingleDocumentStreaming(DocumentOperationType.PUT, "id:unittest:testnull::whee")) .getMessage()); } @Test public void readSingleDocumentsPutStreaming() throws IOException { String json = """ { "remove": "id:unittest:smoke::ignored", "ignored-extra-array": [{ "foo": null }, { }], "ignored-extra-object": { "foo": [null, { }], "bar": { } }, "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" }, "id": "id:unittest:smoke::ignored", "create": false, "condition": "true" } """; ParsedDocumentOperation operation = createReader(json).readSingleDocumentStreaming(DocumentOperationType.PUT,"id:unittest:smoke::doc1"); DocumentPut put = ((DocumentPut) operation.operation()); assertFalse(put.getCreateIfNonExistent()); assertEquals("true", put.getCondition().getSelection()); smokeTestDoc(put.getDocument()); } @Test public void readSingleDocumentsUpdateStreaming() throws IOException { String json = """ { "remove": "id:unittest:smoke::ignored", "ignored-extra-array": [{ "foo": null }, { }], "ignored-extra-object": { "foo": [null, { }], "bar": { } }, "fields": { "something": { "assign": "smoketest" }, "flag": { "assign": true }, "nalle": { "assign": "bamse" } }, "id": "id:unittest:smoke::ignored", "create": true, "condition": "false" } """; ParsedDocumentOperation operation = createReader(json).readSingleDocumentStreaming(DocumentOperationType.UPDATE,"id:unittest:smoke::doc1"); Document doc = new Document(types.getDocumentType("smoke"), new DocumentId("id:unittest:smoke::doc1")); DocumentUpdate update = ((DocumentUpdate) operation.operation()); update.applyTo(doc); smokeTestDoc(doc); assertTrue(update.getCreateIfNonExistent()); assertEquals("false", update.getCondition().getSelection()); } @Test public void readSingleDocumentPut() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:smoke::doc1", "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" } } """); smokeTestDoc(doc); } @Test public final void readSingleDocumentUpdate() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:smoke::whee", "fields": { "something": { "assign": "orOther" } } } """); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof AssignValueUpdate); assertEquals(new StringFieldValue("orOther"), f.getValueUpdate(0).getValue()); } @Test public void readClearField() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:smoke::whee", "fields": { "int1": { "assign": null } } } """); FieldUpdate f = doc.getFieldUpdate("int1"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof ClearValueUpdate); assertNull(f.getValueUpdate(0).getValue()); } @Test public void smokeTest() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:smoke::doc1", "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" } } """); smokeTestDoc(doc); } @Test public void docIdLookaheadTest() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:smoke::doc1", "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" } } """); smokeTestDoc(doc); } @Test public void emptyDocTest() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:smoke::whee", "fields": { } }"""); assertEquals(new Document(types.getDocumentType("smoke"), new DocumentId("id:unittest:smoke::whee")), doc); } @Test public void testStruct() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:mirrors::whee", "fields": { "skuggsjaa": { "sandra": "person", "cloud": "another person" } } } """); FieldValue f = doc.getFieldValue(doc.getField("skuggsjaa")); assertSame(Struct.class, f.getClass()); Struct s = (Struct) f; assertEquals("person", ((StringFieldValue) s.getFieldValue("sandra")).getString()); } private DocumentUpdate parseUpdate(String json) throws IOException { InputStream rawDoc = new ByteArrayInputStream(Utf8.toBytes(json)); JsonReader r = new JsonReader(types, rawDoc, parserFactory); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentUpdate update = new DocumentUpdate(docType, parseInfo.documentId); new VespaJsonDocumentReader(false).readUpdate(parseInfo.fieldsBuffer, update); return update; } @Test public void testStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(""" { "update": "id:unittest:mirrors:g=test:whee", "create": true, "fields": { "skuggsjaa": { "assign": { "sandra": "person", "cloud": "another person" } } } } """); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(2, s.getFieldCount()); assertEquals(new StringFieldValue("person"), s.getFieldValue(s.getField("sandra"))); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(107, buf.position()); } @Test public final void testEmptyStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(""" { "update": "id:unittest:mirrors:g=test:whee", "create": true, "fields": { "skuggsjaa": { "assign": { } } } } """); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(0, s.getFieldCount()); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(69, buf.position()); } @Test public void testUpdateArray() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testarray::whee", "fields": { "actualarray": { "add": [ "person", "another person" ] } } } """); checkSimpleArrayAdd(doc); } @Test public void testUpdateWeighted() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testset::whee", "fields": { "actualset": { "add": { "person": 37, "another person": 41 } } } } """); Map<String, Integer> weights = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; final String s = ((StringFieldValue) adder.getValue()).getString(); weights.put(s, adder.getWeight()); } assertEquals(2, weights.size()); final String o = "person"; final String o2 = "another person"; assertTrue(weights.containsKey(o)); assertTrue(weights.containsKey(o2)); assertEquals(Integer.valueOf(37), weights.get(o)); assertEquals(Integer.valueOf(41), weights.get(o2)); } @Test public void testUpdateMatch() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testset::whee", "fields": { "actualset": { "match": { "element": "person", "increment": 13 } } } } """); DocumentUpdate otherDoc = parseUpdate(""" { "update": "id:unittest:testset::whee", "fields": { "actualset": { "match": { "increment": 13, "element": "person" } } } }"""); assertEquals(doc, otherDoc); Map<String, Tuple2<Number, String>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); String op = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperator().toString(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()).getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertEquals("ADD", matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } @SuppressWarnings({ "cast", "unchecked", "rawtypes" }) @Test public void testArithmeticOperators() throws IOException { Tuple2[] operations = new Tuple2[] { new Tuple2<>(UPDATE_DECREMENT, ArithmeticValueUpdate.Operator.SUB), new Tuple2<>(UPDATE_DIVIDE, ArithmeticValueUpdate.Operator.DIV), new Tuple2<>(UPDATE_INCREMENT, ArithmeticValueUpdate.Operator.ADD), new Tuple2<>(UPDATE_MULTIPLY, ArithmeticValueUpdate.Operator.MUL) }; for (Tuple2<String, Operator> operator : operations) { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testset::whee", "fields": { "actualset": { "match": { "element": "person", "%s": 13 } } } } """.formatted(operator.first)); Map<String, Tuple2<Number, Operator>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); Operator op = ((ArithmeticValueUpdate) adder .getUpdate()).getOperator(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertSame(operator.second, matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } } @SuppressWarnings("rawtypes") @Test public void testArrayIndexing() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testarray::whee", "fields": { "actualarray": { "match": { "element": 3, "assign": "nalle" } } } } """); Map<Number, String> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualarray"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final Number key = ((IntegerFieldValue) adder.getValue()) .getNumber(); String op = ((StringFieldValue) adder.getUpdate() .getValue()).getString(); matches.put(key, op); } assertEquals(1, matches.size()); Number n = Integer.valueOf(3); assertEquals("nalle", matches.get(n)); } @Test public void testDocumentRemove() { JsonReader r = createReader(inputJson("{'remove': 'id:unittest:smoke::whee'}")); DocumentType docType = r.readDocumentType(new DocumentId("id:unittest:smoke::whee")); assertEquals("smoke", docType.getName()); } private Document docFromJson(String json) throws IOException { JsonReader r = createReader(json); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); return put.getDocument(); } @Test public void testWeightedSet() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testset::whee", "fields": { "actualset": { "nalle": 2, "tralle": 7 } } } """); FieldValue f = doc.getFieldValue(doc.getField("actualset")); assertSame(WeightedSet.class, f.getClass()); WeightedSet<?> w = (WeightedSet<?>) f; assertEquals(2, w.size()); assertEquals(Integer.valueOf(2), w.get(new StringFieldValue("nalle"))); assertEquals(Integer.valueOf(7), w.get(new StringFieldValue("tralle"))); } @Test public void testArray() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testarray::whee", "fields": { "actualarray": [ "nalle", "tralle" ] } } """); FieldValue f = doc.getFieldValue(doc.getField("actualarray")); assertSame(Array.class, f.getClass()); Array<?> a = (Array<?>) f; assertEquals(2, a.size()); assertEquals(new StringFieldValue("nalle"), a.get(0)); assertEquals(new StringFieldValue("tralle"), a.get(1)); } @Test public void testMap() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testmap::whee", "fields": { "actualmap": { "nalle": "kalle", "tralle": "skalle" } } } """); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testOldMap() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testmap::whee", "fields": { "actualmap": [ { "key": "nalle", "value": "kalle" }, { "key": "tralle", "value": "skalle" } ] } } """); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testPositionPositive() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "singlepos": "N63.429722;E10.393333" } } """); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionOld() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "singlepos": { "x": 10393333, "y": 63429722 } } } """); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testGeoPosition() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "singlepos": { "lat": 63.429722, "lng": 10.393333 } } } """); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testGeoPositionNoAbbreviations() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "singlepos": { "latitude": 63.429722, "longitude": 10.393333 } } } """); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionGeoPos() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "geopos": "N63.429722;E10.393333" } } """); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); } @Test public void testPositionOldGeoPos() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "geopos": { "x": 10393333, "y": 63429722 } } } """); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); } @Test public void testGeoPositionGeoPos() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "geopos": { "lat": 63.429722, "lng": 10.393333 } } } """); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); assertEquals(PositionDataType.INSTANCE, f.getDataType()); } @Test public void testPositionNegative() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "singlepos": "W46.63;S23.55" } } """); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(-46630000, PositionDataType.getXValue(f).getInteger()); assertEquals(-23550000, PositionDataType.getYValue(f).getInteger()); } @Test public void testRaw() throws IOException { String base64 = new String(new JsonStringEncoder().quoteAsString( Base64.getEncoder().withoutPadding().encodeToString(Utf8.toBytes("smoketest")))); String s = fieldStringFromBase64RawContent(base64); assertEquals("smoketest", s); } @Test public void can_read_legacy_chunked_base64_raw_field_encoding() throws IOException { String expected = "this is a string with an impressive length. it's long enough to reach the end of the line, wow!"; String base64withDelims = "dGhpcyBpcyBhIHN0cmluZyB3aXRoIGFuIGltcHJlc3NpdmUgbGVuZ3RoLiBpdCdzIGxvbmcgZW5v\\r\\n" + "dWdoIHRvIHJlYWNoIHRoZSBlbmQgb2YgdGhlIGxpbmUsIHdvdyE=\\r\\n"; assertEquals(expected, fieldStringFromBase64RawContent(base64withDelims)); } private String fieldStringFromBase64RawContent(String base64data) throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testraw::whee", "fields": { "actualraw": "%s" } } """.formatted(base64data)); FieldValue f = doc.getFieldValue(doc.getField("actualraw")); assertSame(Raw.class, f.getClass()); Raw s = (Raw) f; return Utf8.toString(s.getByteBuffer()); } @Test public void testMapStringToArrayOfInt() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt": { "bamse": [1, 2, 3] } } } """); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldMapStringToArrayOfInt() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt": [ { "key": "bamse", "value": [1, 2, 3] } ] } } """); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToString() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:smoke::whee", "fields": { "something": { "assign": "orOther" } } } """); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); AssignValueUpdate a = (AssignValueUpdate) f.getValueUpdate(0); assertEquals(new StringFieldValue("orOther"), a.getValue()); } @Test public void testNestedArrayMatch() throws IOException { DocumentUpdate nested = parseUpdate(""" { "update": "id:unittest:testArrayOfArrayOfInt::whee", "fields": { "arrayOfArrayOfInt": { "match": { "element": 1, "match": { "element": 2, "assign": 3 } } } } } """); DocumentUpdate equivalent = parseUpdate(""" { "update": "id:unittest:testArrayOfArrayOfInt::whee", "fields": { "arrayOfArrayOfInt": { "match": { "match": { "assign": 3, "element": 2 }, "element": 1 } } } } """); assertEquals(nested, equivalent); assertEquals(1, nested.fieldUpdates().size()); FieldUpdate fu = nested.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); MapValueUpdate mvu = (MapValueUpdate) fu.getValueUpdate(0); assertEquals(new IntegerFieldValue(1), mvu.getValue()); MapValueUpdate nvu = (MapValueUpdate) mvu.getUpdate(); assertEquals(new IntegerFieldValue(2), nvu.getValue()); AssignValueUpdate avu = (AssignValueUpdate) nvu.getUpdate(); assertEquals(new IntegerFieldValue(3), avu.getValue()); Document doc = docFromJson(""" { "put": "id:unittest:testArrayOfArrayOfInt::whee", "fields": { "arrayOfArrayOfInt": [ [1, 2, 3], [4, 5, 6] ] } } """); nested.applyTo(doc); Document expected = docFromJson(""" { "put": "id:unittest:testArrayOfArrayOfInt::whee", "fields": { "arrayOfArrayOfInt": [ [1, 2, 3], [4, 5, 3] ] } } """); assertEquals(expected, doc); } @Test public void testMatchCannotUpdateNestedFields() { // Should this work? It doesn't. assertEquals("Field type Map<string,Array<int>> not supported.", assertThrows(UnsupportedOperationException.class, () -> parseUpdate(""" { "update": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt": { "match": { "element": "bamse", "match": { "element": 1, "assign": 4 } } } } } """)).getMessage()); } @Test public void testMatchCannotAssignToNestedMap() { // Unsupported value type for map value assign. assertEquals("Field type Map<string,Array<int>> not supported.", assertThrows(UnsupportedOperationException.class, () -> parseUpdate(""" { "update": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt": { "match": { "element": "bamse", "assign": [1, 3, 4] } } } } """)).getMessage()); } @Test public void testMatchCannotAssignToMap() { // Unsupported value type for map value assign. assertEquals("Field type Map<string,string> not supported.", assertThrows(UnsupportedOperationException.class, () -> parseUpdate(""" { "update": "id:unittest:testmap::whee", "fields": { "actualmap": { "match": { "element": "bamse", "assign": "bar" } } } } """)).getMessage()); } @Test public void testAssignInsideArrayInMap() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt": { "bamse": [1, 2, 3] } } }"""); assertEquals(2, ((MapFieldValue<StringFieldValue, Array<IntegerFieldValue>>) doc.getFieldValue("actualMapStringToArrayOfInt")) .get(StringFieldValue.getFactory().create("bamse")).get(1).getInteger()); DocumentUpdate update = parseUpdate(""" { "update": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt{bamse}[1]": { "assign": 4 } } } """); assertEquals(1, update.fieldPathUpdates().size()); update.applyTo(doc); assertEquals(4, ((MapFieldValue<StringFieldValue, Array<IntegerFieldValue>>) doc.getFieldValue("actualMapStringToArrayOfInt")) .get(StringFieldValue.getFactory().create("bamse")).get(1).getInteger()); } @Test public void testAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt": { "assign": { "bamse": [1, 2, 3] } } } } """); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt": { "assign": [ { "key": "bamse", "value": [1, 2, 3] } ] } } } """); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToWeightedSet() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testset::whee", "fields": { "actualset": { "assign": { "person": 37, "another person": 41 } } } } """); FieldUpdate x = doc.getFieldUpdate("actualset"); assertEquals(1, x.size()); AssignValueUpdate assign = (AssignValueUpdate) x.getValueUpdate(0); WeightedSet<?> w = (WeightedSet<?>) assign.getValue(); assertEquals(2, w.size()); assertEquals(Integer.valueOf(37), w.get(new StringFieldValue("person"))); assertEquals(Integer.valueOf(41), w.get(new StringFieldValue("another person"))); } @Test public void testCompleteFeed() { JsonReader r = createReader(""" [ { "put": "id:unittest:smoke::whee", "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" } }, { "update": "id:unittest:testarray::whee", "fields": { "actualarray": { "add": [ "person", "another person" ] } } }, { "remove": "id:unittest:smoke::whee" } ] """); controlBasicFeed(r); } @Test public void testCompleteFeedWithCreateAndCondition() { JsonReader r = createReader(""" [ { "put": "id:unittest:smoke::whee", "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" } }, { "condition":"bla", "update": "id:unittest:testarray::whee", "create":true, "fields": { "actualarray": { "add": [ "person", "another person" ] } } }, { "remove": "id:unittest:smoke::whee" } ] """); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testUpdateWithConditionAndCreateInDifferentOrdering() { int documentsCreated = 106; List<String> parts = Arrays.asList( "\"condition\":\"bla\"", "\"update\": \"id:unittest:testarray::whee\"", " \"fields\": { " + "\"actualarray\": { \"add\": [" + " \"person\",\"another person\"]}}", " \"create\":true"); Random random = new Random(42); StringBuilder documents = new StringBuilder("["); for (int x = 0; x < documentsCreated; x++) { Collections.shuffle(parts, random); documents.append("{").append(Joiner.on(",").join(parts)).append("}"); if (x < documentsCreated -1) { documents.append(","); } } documents.append("]"); InputStream rawDoc = new ByteArrayInputStream(Utf8.toBytes(documents.toString())); JsonReader r = new JsonReader(types, rawDoc, parserFactory); for (int x = 0; x < documentsCreated; x++) { DocumentUpdate update = (DocumentUpdate) r.next(); checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); } assertNull(r.next()); } @Test public void testCreateIfNonExistentInPut() { JsonReader r = createReader(""" [ { "create":true, "fields": { "something": "smoketest", "nalle": "bamse" }, "put": "id:unittest:smoke::whee" } ] """); var op = r.next(); var put = (DocumentPut) op; assertTrue(put.getCreateIfNonExistent()); } @Test public void testCompleteFeedWithIdAfterFields() { JsonReader r = createReader(""" [ { "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" }, "put": "id:unittest:smoke::whee" }, { "fields": { "actualarray": { "add": [ "person", "another person" ] } }, "update": "id:unittest:testarray::whee" }, { "remove": "id:unittest:smoke::whee" } ] """); controlBasicFeed(r); } protected void controlBasicFeed(JsonReader r) { DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testCompleteFeedWithEmptyDoc() { JsonReader r = createReader(""" [ { "put": "id:unittest:smoke::whee", "fields": {} }, { "update": "id:unittest:testarray::whee", "fields": {} }, { "remove": "id:unittest:smoke::whee" } ] """); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); assertEquals("smoke", doc.getId().getDocType()); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; assertEquals("testarray", update.getId().getDocType()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } private void checkSimpleArrayAdd(DocumentUpdate update) { Set<String> toAdd = new HashSet<>(); FieldUpdate x = update.getFieldUpdate("actualarray"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; toAdd.add(((StringFieldValue) adder.getValue()).getString()); } assertEquals(2, toAdd.size()); assertTrue(toAdd.contains("person")); assertTrue(toAdd.contains("another person")); } private void smokeTestDoc(Document doc) { FieldValue boolField = doc.getFieldValue(doc.getField("flag")); assertSame(BoolFieldValue.class, boolField.getClass()); assertTrue((Boolean)boolField.getWrappedValue()); FieldValue stringField = doc.getFieldValue(doc.getField("nalle")); assertSame(StringFieldValue.class, stringField.getClass()); assertEquals("bamse", ((StringFieldValue) stringField).getString()); } @Test public void nonExistingFieldCausesException() throws IOException { Exception expected = assertThrows(IllegalArgumentException.class, () -> docFromJson(""" { "put": "id:unittest:smoke::whee", "fields": { "smething": "smoketest", "nalle": "bamse" } } """)); assertTrue(expected.getMessage().startsWith("No field 'smething' in the structure of type 'smoke'")); } @Test public void nonExistingFieldsCanBeIgnoredInPut() throws IOException { JsonReader r = createReader(""" { "put": "id:unittest:smoke::doc1", "fields": { "nonexisting1": "ignored value", "field1": "value1", "nonexisting2": { "blocks": { "a": [2.0, 3.0], "b": [4.0, 5.0] } }, "field2": "value2", "nonexisting3": { "cells": [ { "address": { "x": "x1" }, "value": 1.0 } ] }, "tensor1": { "cells": { "x1": 1.0 } }, "nonexisting4": "ignored value" } } """); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); boolean fullyApplied = new VespaJsonDocumentReader(true).readPut(parseInfo.fieldsBuffer, put); assertFalse(fullyApplied); assertNull(put.getDocument().getField("nonexisting1")); assertEquals("value1", put.getDocument().getFieldValue("field1").toString()); assertNull(put.getDocument().getField("nonexisting2")); assertEquals("value2", put.getDocument().getFieldValue("field2").toString()); assertNull(put.getDocument().getField("nonexisting3")); assertEquals(Tensor.from("tensor(x{}):{{x:x1}:1.0}"), put.getDocument().getFieldValue("tensor1").getWrappedValue()); assertNull(put.getDocument().getField("nonexisting4")); } @Test public void nonExistingFieldsCanBeIgnoredInUpdate() throws IOException{ JsonReader r = createReader(""" { "update": "id:unittest:smoke::doc1", "fields": { "nonexisting1": { "assign": "ignored value" }, "field1": { "assign": "value1" }, "nonexisting2": { "assign": { "blocks": { "a":[2.0,3.0], "b":[4.0,5.0] } } }, "field2": { "assign": "value2" }, "nonexisting3": { "assign" : { "cells": [{"address": {"x": "x1"}, "value": 1.0}] } }, "tensor1": {"assign": { "cells": {"x1": 1.0} } }, "nonexisting4": { "assign": "ignored value" } } } """); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentUpdate update = new DocumentUpdate(docType, parseInfo.documentId); boolean fullyApplied = new VespaJsonDocumentReader(true).readUpdate(parseInfo.fieldsBuffer, update); assertFalse(fullyApplied); assertNull(update.getFieldUpdate("nonexisting1")); assertEquals("value1", update.getFieldUpdate("field1").getValueUpdates().get(0).getValue().getWrappedValue().toString()); assertNull(update.getFieldUpdate("nonexisting2")); assertEquals("value2", update.getFieldUpdate("field2").getValueUpdates().get(0).getValue().getWrappedValue().toString()); assertNull(update.getFieldUpdate("nonexisting3")); assertEquals(Tensor.from("tensor(x{}):{{x:x1}:1.0}"), update.getFieldUpdate("tensor1").getValueUpdates().get(0).getValue().getWrappedValue()); assertNull(update.getFieldUpdate("nonexisting4")); } @Test public void feedWithBasicErrorTest() { JsonReader r = createReader(""" [ { "put": "id:test:smoke::0", "fields": { "something": "foo" } }, { "put": "id:test:smoke::1", "fields": { "something": "foo" } }, { "put": "id:test:smoke::2", "fields": { "something": "foo" } }, ]"""); // Trailing comma in array ... assertTrue(assertThrows(RuntimeException.class, () -> { while (r.next() != null); }) .getMessage().contains("JsonParseException")); } @Test public void idAsAliasForPutTest() throws IOException{ JsonReader r = createReader(""" { "id": "id:unittest:smoke::doc1", "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" } } """); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); boolean fullyApplied = new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); assertTrue(fullyApplied); smokeTestDoc(put.getDocument()); } private void testFeedWithTestAndSetCondition(String jsonDoc) { ByteArrayInputStream parseInfoDoc = new ByteArrayInputStream(Utf8.toBytes(jsonDoc)); JsonReader reader = new JsonReader(types, parseInfoDoc, parserFactory); int NUM_OPERATIONS_IN_FEED = 3; for (int i = 0; i < NUM_OPERATIONS_IN_FEED; i++) { DocumentOperation operation = reader.next(); assertTrue("A test and set condition should be present", operation.getCondition().isPresent()); assertEquals("DocumentOperation's test and set condition should be equal to the one in the JSON feed", "smoke.something == \"smoketest\"", operation.getCondition().getSelection()); } assertNull(reader.next()); } @Test public void testFeedWithTestAndSetConditionOrderingOne() { testFeedWithTestAndSetCondition(""" [ { "put": "id:unittest:smoke::whee", "condition": "smoke.something == \\"smoketest\\"", "fields": { "something": "smoketest", "nalle": "bamse" } }, { "update": "id:unittest:testarray::whee", "condition": "smoke.something == \\"smoketest\\"", "fields": { "actualarray": { "add": [ "person", "another person" ] } } }, { "remove": "id:unittest:smoke::whee", "condition": "smoke.something == \\"smoketest\\"" } ] """); } @Test public void testFeedWithTestAndSetConditionOrderingTwo() { testFeedWithTestAndSetCondition(""" [ { "condition": "smoke.something == \\"smoketest\\"", "put": "id:unittest:smoke::whee", "fields": { "something": "smoketest", "nalle": "bamse" } }, { "condition": "smoke.something == \\"smoketest\\"", "update": "id:unittest:testarray::whee", "fields": { "actualarray": { "add": [ "person", "another person" ] } } }, { "condition": "smoke.something == \\"smoketest\\"", "remove": "id:unittest:smoke::whee" } ] """); } @Test public void testFeedWithTestAndSetConditionOrderingThree() { testFeedWithTestAndSetCondition(""" [ { "put": "id:unittest:smoke::whee", "fields": { "something": "smoketest", "nalle": "bamse" }, "condition": "smoke.something == \\"smoketest\\"" }, { "update": "id:unittest:testarray::whee", "fields": { "actualarray": { "add": [ "person", "another person" ] } }, "condition": "smoke.something == \\"smoketest\\"" }, { "remove": "id:unittest:smoke::whee", "condition": "smoke.something == \\"smoketest\\"" } ] """); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldAfterFieldsFieldShouldFailParse() { String jsonData = """ [ { "put": "id:unittest:smoke::whee", "fields": { "something": "smoketest", "nalle": "bamse" }, "bjarne": "stroustrup" } ]"""; new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldBeforeFieldsFieldShouldFailParse() { String jsonData = """ [ { "update": "id:unittest:testarray::whee", "what is this": "nothing to see here", "fields": { "actualarray": { "add": [ "person", "another person" ] } } } ]"""; new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldWithoutFieldsFieldShouldFailParse() { String jsonData = """ [ { "remove": "id:unittest:smoke::whee", "what is love": "baby, do not hurt me... much } ]"""; new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test public void testMissingOperation() { try { String jsonData = """ [ { "fields": { "actualarray": { "add": [ "person", "another person" ] } } } ]"""; new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Missing a document operation ('put', 'update' or 'remove')", e.getMessage()); } } @Test public void testMissingFieldsMapInPut() { try { String jsonData = """ [ { "put": "id:unittest:smoke::whee" } ]"""; new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("put of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testMissingFieldsMapInUpdate() { try { String jsonData = """ [ { "update": "id:unittest:smoke::whee" } ]"""; new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Update of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testNullValues() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testnull::doc1", "fields": { "intfield": null, "stringfield": null, "arrayfield": null, "weightedsetfield": null, "mapfield": null, "tensorfield": null } } """); assertFieldValueNull(doc, "intfield"); assertFieldValueNull(doc, "stringfield"); assertFieldValueNull(doc, "arrayfield"); assertFieldValueNull(doc, "weightedsetfield"); assertFieldValueNull(doc, "mapfield"); assertFieldValueNull(doc, "tensorfield"); } @Test(expected=JsonReaderException.class) public void testNullArrayElement() throws IOException { docFromJson(""" { "put": "id:unittest:testnull::doc1", "fields": { "arrayfield": [ null ] } } """); fail(); } private void assertFieldValueNull(Document doc, String fieldName) { Field field = doc.getField(fieldName); assertNotNull(field); FieldValue fieldValue = doc.getFieldValue(field); assertNull(fieldValue); } static ByteArrayInputStream jsonToInputStream(String json) { return new ByteArrayInputStream(Utf8.toBytes(json)); } @Test public void testParsingWithoutTensorField() { Document doc = createPutWithoutTensor().getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals("id:unittest:testtensor::0", doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField("sparse_tensor")); assertNull(fieldValue); } @Test public void testParsingOfEmptyTensor() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor("{}")); } @Test public void testParsingOfTensorWithEmptyCells() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor(inputJson("{ 'cells': [] }"))); } @Test public void testDisallowedDenseTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{ 'values': [] }"), "dense_tensor", "The 'values' array does not contain any values"); assertCreatePutFails(inputJson("{ 'values': '' }"), "dense_tensor", "The 'values' string does not contain any values"); } @Test public void testDisallowedMixedTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{\"blocks\":{ \"a\": [] } }"), "mixed_tensor", "Expected 3 values, but got 0"); assertCreatePutFails(inputJson("{\"blocks\":[ {\"address\":{\"x\":\"a\"}, \"values\": [] } ] }"), "mixed_tensor", "Expected 3 values, but got 0"); } @Test public void testParsingOfSparseTensorWithCells() { Tensor tensor = assertSparseTensorField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createPutWithSparseTensor(""" { "type": "tensor(x{},y{})", "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 }, { "address": { "x": "c", "y": "b" }, "value": 3.0 } ] } """)); assertTrue(tensor instanceof MappedTensor); // any functional instance is fine } @Test public void testParsingOfDenseTensorWithCells() { Tensor tensor = assertTensorField("{{x:0,y:0}:2.0,{x:1,y:0}:3.0}}", createPutWithTensor(""" { "cells": [ { "address": { "x": 0, "y": 0 }, "value": 2.0 }, { "address": { "x": 1, "y": 0 }, "value": 3.0 } ] } """, "dense_unbound_tensor"), "dense_unbound_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorOnDenseForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(Double.POSITIVE_INFINITY); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(""" { "values": [2.0, 3.0, 4.0, "inf", 6.0, 7.0] }""", "dense_tensor"), "dense_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<int8>(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(""" { "values": "020304050607" }""", "dense_int8_tensor"), "dense_int8_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfMixedTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")); builder.cell().label("x", "foo").label("y", 0).value(2.0); builder.cell().label("x", "foo").label("y", 1).value(3.0); builder.cell().label("x", "foo").label("y", 2).value(4.0); builder.cell().label("x", "bar").label("y", 0).value(5.0); builder.cell().label("x", "bar").label("y", 1).value(6.0); builder.cell().label("x", "bar").label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = """ { "blocks":[ {"address":{"x":"foo"},"values":"400040404080"}, {"address":{"x":"bar"},"values":"40A040C040E0"} ] } """; var put = createPutWithTensor(inputJson(mixedJson), "mixed_bfloat16_tensor"); Tensor tensor = assertTensorField(expected, put, "mixed_bfloat16_tensor"); } /** Tests parsing of various tensor values set at the root, i.e. no 'cells', 'blocks' or 'values' */ @Test public void testDirectValue() { assertTensorField("tensor(x{}):{a:2, b:3}", "sparse_single_dimension_tensor", "{'a':2.0, 'b':3.0}"); assertTensorField("tensor(x[2],y[3]):[2, 3, 4, 5, 6, 7]]", "dense_tensor", "[2, 3, 4, 5, 6, 7]"); assertTensorField("tensor(x[2],y[3]):[2, 3, 4, 5, 6, 7]]", "dense_tensor", "[[2, 3, 4], [5, 6, 7]]"); assertTensorField("tensor(x{},y[3]):{a:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'a':[2, 3, 4], 'b':[4, 5, 6]}"); assertTensorField("tensor(x{},y{}):{{x:a,y:0}:2, {x:b,y:1}:3}", "sparse_tensor", "[{'address':{'x':'a','y':'0'},'value':2}, {'address':{'x':'b','y':'1'},'value':3}]"); } @Test public void testDirectValueReservedNameKeys() { // Single-valued assertTensorField("tensor(x{}):{cells:2, b:3}", "sparse_single_dimension_tensor", "{'cells':2.0, 'b':3.0}"); assertTensorField("tensor(x{}):{values:2, b:3}", "sparse_single_dimension_tensor", "{'values':2.0, 'b':3.0}"); assertTensorField("tensor(x{}):{block:2, b:3}", "sparse_single_dimension_tensor", "{'block':2.0, 'b':3.0}"); // Multi-valued assertTensorField("tensor(x{},y[3]):{cells:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'cells':[2, 3, 4], 'b':[4, 5, 6]}"); assertTensorField("tensor(x{},y[3]):{values:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'values':[2, 3, 4], 'b':[4, 5, 6]}"); assertTensorField("tensor(x{},y[3]):{block:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'block':[2, 3, 4], 'b':[4, 5, 6]}"); } @Test public void testParsingOfMixedTensorOnMixedForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = """ { "blocks":[ {"address":{"x":"0"},"values":[2.0,3.0,4.0]}, {"address":{"x":"1"},"values":[5.0,6.0,7.0]} ] } """; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance String mixedJsonDirect = """ [ {"address":{"x":"0","y":"0"},"value":2.0}, {"address":{"x":"0","y":"1"},"value":3.0}, {"address":{"x":"0","y":"2"},"value":4.0}, {"address":{"x":"1","y":"0"},"value":5.0}, {"address":{"x":"1","y":"1"},"value":6.0}, {"address":{"x":"1","y":"2"},"value":7.0} ] """; Tensor tensorDirect = assertTensorField(expected, createPutWithTensor(inputJson(mixedJsonDirect), "mixed_tensor"), "mixed_tensor"); assertTrue(tensorDirect instanceof MixedTensor); // this matters for performance } @Test public void testMixedTensorInMixedFormWithSingleSparseDimensionShortForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = """ { "blocks":{ "0":[2.0,3.0,4.0], "1":[5.0,6.0,7.0] } } """; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance } @Test public void testParsingOfTensorWithSingleCellInDifferentJsonOrder() { assertSparseTensorField("{{x:a,y:b}:2.0}", createPutWithSparseTensor(""" { "cells": [ { "value": 2.0, "address": { "x": "a", "y": "b" } } ] } """)); } @Test public void testAssignUpdateOfEmptySparseTensor() { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithSparseTensor("{}")); } @Test public void testAssignUpdateOfEmptyDenseTensor() { try { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithTensor("{}", "dense_unbound_tensor")); } catch (IllegalArgumentException e) { assertEquals("An indexed tensor must have a value", "Error in 'dense_unbound_tensor': Tensor of type tensor(x[],y[]) has no values", Exceptions.toMessageString(e)); } } @Test public void testAssignUpdateOfNullTensor() { ClearValueUpdate clearUpdate = (ClearValueUpdate) getTensorField(createAssignUpdateWithSparseTensor(null)).getValueUpdate(0); assertNotNull(clearUpdate); assertNull(clearUpdate.getValue()); } @Test public void testAssignUpdateOfTensorWithCells() { assertTensorAssignUpdateSparseField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createAssignUpdateWithSparseTensor(""" { "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 }, { "address": { "x": "c", "y": "b" }, "value": 3.0 } ] } """)); } @Test public void testAssignUpdateOfTensorDenseShortForm() { assertTensorAssignUpdateDenseField("tensor(x[2],y[3]):[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]", createAssignUpdateWithTensor(""" { "values": [1,2,3,4,5,6] } """, "dense_tensor")); } @Test public void tensor_modify_update_with_replace_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_tensor", """ { "operation": "replace", "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_add_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, "sparse_tensor", """ { "operation": "add", "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_multiply_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "sparse_tensor", """ { "operation": "multiply", "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_create_non_existing_cells_true() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, true, "sparse_tensor", """ { "operation": "add", "create": true, "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_create_non_existing_cells_false() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, false, "sparse_tensor", """ { "operation": "add", "create": false, "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_treats_the_input_tensor_as_sparse() { // Note that the type of the tensor in the modify update is sparse (it only has mapped dimensions). assertTensorModifyUpdate("tensor(x{},y{}):{{x:0,y:0}:2.0, {x:1,y:2}:3.0}", TensorModifyUpdate.Operation.REPLACE, "dense_tensor", """ { "operation": "replace", "cells": [ { "address": { "x": "0", "y": "0" }, "value": 2.0 }, { "address": { "x": "1", "y": "2" }, "value": 3.0 } ] }"""); } @Test public void tensor_modify_update_on_non_tensor_field_throws() { try { JsonReader reader = createReader(""" { "update": "id:unittest:smoke::doc1", "fields": { "something": { "modify": {} } } } """); reader.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::doc1"); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Error in 'something': A modify update can only be applied to tensor fields. Field 'something' is of type 'string'", Exceptions.toMessageString(e)); } } @Test public void tensor_modify_update_on_dense_unbound_tensor_throws() { illegalTensorModifyUpdate("Error in 'dense_unbound_tensor': A modify update cannot be applied to tensor types with indexed unbound dimensions. Field 'dense_unbound_tensor' has unsupported tensor type 'tensor(x[],y[])'", "dense_unbound_tensor", """ { "operation": "replace", "cells": [ { "address": { "x": "0", "y": "0" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorModifyUpdate("{{x:a}:2.0, {x:c}: 3.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_single_dimension_tensor", """ { "operation": "replace", "cells": { "a": 2.0, "c": 3.0 } }"""); } @Test public void tensor_modify_update_with_replace_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", """ { "operation": "replace", "cells": [ { "address": { "x": "a", "y": "0" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_array() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", """ { "operation": "replace", "blocks": [ { "address": { "x": "a" }, "values": [1,2,3] } ] }"""); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_must_specify_full_subspace() { illegalTensorModifyUpdate("Error in 'mixed_tensor': At {x:a}: Expected 3 values, but got 2", "mixed_tensor", """ { "operation": "replace", "blocks": { "a": [2,3] } }"""); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_map() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", """ { "operation": "replace", "blocks": { "a": [1,2,3] } }"""); } @Test public void tensor_modify_update_with_add_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.ADD, "mixed_tensor", """ { "operation": "add", "cells": [ { "address": { "x": "a", "y": "0" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_multiply_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "mixed_tensor", """ { "operation": "multiply", "cells": [ { "address": { "x": "a", "y": "0" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws() { illegalTensorModifyUpdate("Error in 'dense_tensor': Dimension 'y' has label '3' but type is tensor(x[2],y[3])", "dense_tensor", """ { "operation": "replace", "cells": [ { "address": { "x": "0", "y": "3" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws_mixed() { illegalTensorModifyUpdate("Error in 'mixed_tensor': Dimension 'y' has label '3' but type is tensor(x{},y[3])", "mixed_tensor", """ { "operation": "replace", "cells": [ { "address": { "x": "0", "y": "3" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_unknown_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown operation 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", """ { "operation": "unknown", "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_without_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain an operation", "sparse_tensor", """ { "cells": [] }"""); } @Test public void tensor_modify_update_without_cells_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", """ { "operation": "replace" }"""); } @Test public void tensor_modify_update_with_unknown_content_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown JSON string 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", """ { "unknown": "here" }"""); } @Test public void tensor_add_update_on_sparse_tensor() { assertTensorAddUpdate("{{x:a,y:b}:2.0, {x:c,y:d}: 3.0}", "sparse_tensor", """ { "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 }, { "address": { "x": "c", "y": "d" }, "value": 3.0 } ] }"""); } @Test public void tensor_add_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorAddUpdate("{{x:a}:2.0, {x:c}: 3.0}", "sparse_single_dimension_tensor", """ { "cells": { "a": 2.0, "c": 3.0 } }"""); } @Test public void tensor_add_update_on_mixed_tensor() { assertTensorAddUpdate("{{x:a,y:0}:2.0, {x:a,y:1}:3.0, {x:a,y:2}:0.0}", "mixed_tensor", """ { "cells": [ { "address": { "x": "a", "y": "0" }, "value": 2.0 }, { "address": { "x": "a", "y": "1" }, "value": 3.0 } ] }"""); } @Test public void tensor_add_update_on_mixed_with_out_of_bound_dense_cells_throws() { illegalTensorAddUpdate("Error in 'mixed_tensor': Index 3 out of bounds for length 3", "mixed_tensor", """ { "cells": [ { "address": { "x": "0", "y": "3" }, "value": 2.0 } ] }"""); } @Test public void tensor_add_update_on_dense_tensor_throws() { illegalTensorAddUpdate("Error in 'dense_tensor': An add update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", """ { "cells": [ ] }"""); } @Test public void tensor_add_update_on_not_fully_specified_cell_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Missing a label for dimension 'y' for tensor(x{},y{})", "sparse_tensor", """ { "cells": [ { "address": { "x": "a" }, "value": 2.0 } ] }"""); } @Test public void tensor_add_update_without_cells_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Add update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", "{}"); illegalTensorAddUpdate("Error in 'mixed_tensor': Add update for field 'mixed_tensor' does not contain tensor cells", "mixed_tensor", "{}"); } @Test public void tensor_remove_update_on_sparse_tensor() { assertTensorRemoveUpdate("{{x:a,y:b}:1.0,{x:c,y:d}:1.0}", "sparse_tensor", """ { "addresses": [ { "x": "a", "y": "b" }, { "x": "c", "y": "d" } ] }"""); } @Test public void tensor_remove_update_on_mixed_tensor() { assertTensorRemoveUpdate("{{x:1}:1.0,{x:2}:1.0}", "mixed_tensor", """ { "addresses": [ { "x": "1" }, { "x": "2" } ] }"""); } @Test public void tensor_remove_update_on_sparse_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{y:b}:1.0,{y:d}:1.0}", "sparse_tensor", """ { "addresses": [ { "y": "b" }, { "y": "d" } ] }"""); } @Test public void tensor_remove_update_on_mixed_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{x:1,z:a}:1.0,{x:2,z:b}:1.0}", "mixed_tensor_adv", """ { "addresses": [ { "x": "1", "z": "a" }, { "x": "2", "z": "b" } ] }"""); } @Test public void tensor_remove_update_on_mixed_tensor_with_dense_addresses_throws() { illegalTensorRemoveUpdate("Error in 'mixed_tensor': Indexed dimension address 'y' should not be specified in remove update", "mixed_tensor", """ { "addresses": [ { "x": "1", "y": "0" }, { "x": "2", "y": "0" } ] }"""); } @Test public void tensor_remove_update_on_dense_tensor_throws() { illegalTensorRemoveUpdate("Error in 'dense_tensor': A remove update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", """ { "addresses": [] }"""); } @Test public void tensor_remove_update_with_stray_dimension_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{},y{}) does not contain dimension 'foo'", "sparse_tensor", """ { "addresses": [ { "x": "a", "foo": "b" } ] }"""); illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{}) does not contain dimension 'foo'", "sparse_tensor", """ { "addresses": [ { "x": "c" }, { "x": "a", "foo": "b" } ] }"""); } @Test public void tensor_remove_update_without_cells_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': Remove update for field 'sparse_tensor' does not contain tensor addresses", "sparse_tensor", """ { "addresses": [] }"""); illegalTensorRemoveUpdate("Error in 'mixed_tensor': Remove update for field 'mixed_tensor' does not contain tensor addresses", "mixed_tensor", """ { "addresses": [] }"""); } @Test public void require_that_parser_propagates_datatype_parser_errors_predicate() { assertParserErrorMatches( "Error in document 'id:unittest:testpredicate::0' - could not parse field 'boolean' of type 'predicate': " + "line 1:10 no viable alternative at character '>'", """ [ { "fields": { "boolean": "timestamp > 9000" }, "put": "id:unittest:testpredicate::0" } ] """); } @Test public void require_that_parser_propagates_datatype_parser_errors_string_as_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \" 1\"", """ [ { "fields": { "integerfield": " 1" }, "put": "id:unittest:testint::0" } ] """); } @Test public void require_that_parser_propagates_datatype_parser_errors_overflowing_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \"281474976710656\"", """ [ { "fields": { "integerfield": 281474976710656 }, "put": "id:unittest:testint::0" } ] """); } @Test public void requireThatUnknownDocTypeThrowsIllegalArgumentException() { String jsonData = """ [ { "put": "id:ns:walrus::walrus1", "fields": { "aField": 42 } } ] """; try { new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail(); } catch (IllegalArgumentException e) { assertEquals("Document type walrus does not exist", e.getMessage()); } } private static final String TENSOR_DOC_ID = "id:unittest:testtensor::0"; private void illegalTensorModifyUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorModifyUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorAddUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorAddUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorRemoveUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorRemoveUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private DocumentPut createPutWithoutTensor() { JsonReader reader = createReader(inputJson("[ { 'put': '" + TENSOR_DOC_ID + "', 'fields': { } } ]")); return (DocumentPut) reader.next(); } private DocumentPut createPutWithSparseTensor(String inputTensor) { return createPutWithTensor(inputTensor, "sparse_tensor"); } private DocumentPut createPutWithTensor(String inputTensor, String tensorFieldName) { JsonReader streaming = createReader(""" { "fields": { "%s": %s } } """.formatted(tensorFieldName, inputTensor)); DocumentPut lazyParsed = (DocumentPut) streaming.readSingleDocumentStreaming(DocumentOperationType.PUT, TENSOR_DOC_ID).operation(); JsonReader reader = createReader(""" [ { "put": "%s", "fields": { "%s": %s } } ]""".formatted(TENSOR_DOC_ID, tensorFieldName, inputTensor)); DocumentPut bufferParsed = (DocumentPut) reader.next(); assertEquals(lazyParsed, bufferParsed); return bufferParsed; } private DocumentUpdate createAssignUpdateWithSparseTensor(String inputTensor) { return createAssignUpdateWithTensor(inputTensor, "sparse_tensor"); } private DocumentUpdate createAssignUpdateWithTensor(String inputTensor, String tensorFieldName) { return createTensorUpdate("assign", inputTensor, tensorFieldName); } private static Tensor assertSparseTensorField(String expectedTensor, DocumentPut put) { return assertTensorField(expectedTensor, put, "sparse_tensor"); } private Tensor assertTensorField(String expectedTensor, String fieldName, String inputJson) { return assertTensorField(expectedTensor, createPutWithTensor(inputJson(inputJson), fieldName), fieldName); } private static Tensor assertTensorField(String expectedTensor, DocumentPut put, String tensorFieldName) { return assertTensorField(Tensor.from(expectedTensor), put, tensorFieldName); } private static Tensor assertTensorField(Tensor expectedTensor, DocumentPut put, String tensorFieldName) { Document doc = put.getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals(TENSOR_DOC_ID, doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField(tensorFieldName)); assertEquals(expectedTensor, fieldValue.getTensor().get()); return fieldValue.getTensor().get(); } private static void assertTensorFieldUpdate(DocumentUpdate update, String tensorFieldName) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); assertEquals(1, update.fieldUpdates().size()); assertEquals(1, update.getFieldUpdate(tensorFieldName).size()); } private static void assertTensorAssignUpdateSparseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "sparse_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private static void assertTensorAssignUpdateDenseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "dense_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, String tensorFieldName, String modifyJson) { assertTensorModifyUpdate(expectedTensor, expectedOperation, false, tensorFieldName, createTensorModifyUpdate(modifyJson, tensorFieldName)); } private void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, boolean expectedCreateNonExistingCells, String tensorFieldName, String modifyJson) { assertTensorModifyUpdate(expectedTensor, expectedOperation, expectedCreateNonExistingCells, tensorFieldName, createTensorModifyUpdate(modifyJson, tensorFieldName)); } private static void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, boolean expectedCreateNonExistingCells, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorModifyUpdate modifyUpdate = (TensorModifyUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(expectedOperation, modifyUpdate.getOperation()); assertEquals(Tensor.from(expectedTensor), modifyUpdate.getValue().getTensor().get()); assertEquals(expectedCreateNonExistingCells, modifyUpdate.getCreateNonExistingCells()); } private DocumentUpdate createTensorModifyUpdate(String modifyJson, String tensorFieldName) { return createTensorUpdate("modify", modifyJson, tensorFieldName); } private DocumentUpdate createTensorAddUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("add", tensorJson, tensorFieldName); } private DocumentUpdate createTensorRemoveUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("remove", tensorJson, tensorFieldName); } private DocumentUpdate createTensorUpdate(String operation, String tensorJson, String tensorFieldName) { JsonReader streaming = createReader(""" { "fields": { "%s": { "%s": %s } } }""".formatted(tensorFieldName, operation, tensorJson)); DocumentUpdate lazyParsed = (DocumentUpdate) streaming.readSingleDocumentStreaming(DocumentOperationType.UPDATE, TENSOR_DOC_ID).operation(); JsonReader reader = createReader(""" [ { "update": "%s", "fields": { "%s": { "%s": %s } } } ]""".formatted(TENSOR_DOC_ID, tensorFieldName, operation, tensorJson)); DocumentUpdate bufferParsed = (DocumentUpdate) reader.next(); assertEquals(lazyParsed, bufferParsed); return bufferParsed; } private void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorAddUpdate(expectedTensor, tensorFieldName, createTensorAddUpdate(tensorJson, tensorFieldName)); } private static void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorAddUpdate addUpdate = (TensorAddUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), addUpdate.getValue().getTensor().get()); } private void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorRemoveUpdate(expectedTensor, tensorFieldName, createTensorRemoveUpdate(tensorJson, tensorFieldName)); } private static void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorRemoveUpdate removeUpdate = (TensorRemoveUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), removeUpdate.getValue().getTensor().get()); } private static FieldUpdate getTensorField(DocumentUpdate update) { return getTensorField(update, "sparse_tensor"); } private static FieldUpdate getTensorField(DocumentUpdate update, String fieldName) { FieldUpdate fieldUpdate = update.getFieldUpdate(fieldName); assertEquals(1, fieldUpdate.size()); return fieldUpdate; } // NOTE: Do not call this method multiple times from a test method as it's using the ExpectedException rule private void assertParserErrorMatches(String expectedError, String... json) { String jsonData = inputJson(json); try { new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail(); } catch (JsonReaderException e) { assertEquals(expectedError, e.getMessage()); } } private void assertCreatePutFails(String tensor, String name, String msg) { try { createPutWithTensor(inputJson(tensor), name); fail("Expected exception"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains(msg)); } } }
userMocius/vespa
document/src/test/java/com/yahoo/document/json/JsonReaderTestCase.java
213,294
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.document.json; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.io.JsonStringEncoder; import com.google.common.base.Joiner; import com.yahoo.collections.Tuple2; import com.yahoo.document.ArrayDataType; import com.yahoo.document.DataType; import com.yahoo.document.Document; import com.yahoo.document.DocumentId; import com.yahoo.document.DocumentOperation; import com.yahoo.document.DocumentPut; import com.yahoo.document.DocumentRemove; import com.yahoo.document.DocumentType; import com.yahoo.document.DocumentTypeManager; import com.yahoo.document.DocumentUpdate; import com.yahoo.document.Field; import com.yahoo.document.MapDataType; import com.yahoo.document.PositionDataType; import com.yahoo.document.StructDataType; import com.yahoo.document.TensorDataType; import com.yahoo.document.TestAndSetCondition; import com.yahoo.document.WeightedSetDataType; import com.yahoo.document.datatypes.Array; import com.yahoo.document.datatypes.BoolFieldValue; import com.yahoo.document.datatypes.FieldValue; import com.yahoo.document.datatypes.IntegerFieldValue; import com.yahoo.document.datatypes.MapFieldValue; import com.yahoo.document.datatypes.Raw; import com.yahoo.document.datatypes.StringFieldValue; import com.yahoo.document.datatypes.Struct; import com.yahoo.document.datatypes.TensorFieldValue; import com.yahoo.document.datatypes.WeightedSet; import com.yahoo.document.fieldpathupdate.FieldPathUpdate; import com.yahoo.document.internal.GeoPosType; import com.yahoo.document.json.readers.DocumentParseInfo; import com.yahoo.document.json.readers.VespaJsonDocumentReader; import com.yahoo.document.serialization.DocumentSerializer; import com.yahoo.document.serialization.DocumentSerializerFactory; import com.yahoo.document.update.AddValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate; import com.yahoo.document.update.ArithmeticValueUpdate.Operator; import com.yahoo.document.update.AssignValueUpdate; import com.yahoo.document.update.ClearValueUpdate; import com.yahoo.document.update.FieldUpdate; import com.yahoo.document.update.MapValueUpdate; import com.yahoo.document.update.TensorAddUpdate; import com.yahoo.document.update.TensorModifyUpdate; import com.yahoo.document.update.TensorRemoveUpdate; import com.yahoo.document.update.ValueUpdate; import com.yahoo.io.GrowableByteBuffer; import com.yahoo.tensor.IndexedTensor; import com.yahoo.tensor.MappedTensor; import com.yahoo.tensor.MixedTensor; import com.yahoo.tensor.Tensor; import com.yahoo.tensor.TensorType; import com.yahoo.text.Utf8; import com.yahoo.yolean.Exceptions; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DECREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_DIVIDE; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_INCREMENT; import static com.yahoo.document.json.readers.SingleValueReader.UPDATE_MULTIPLY; import static com.yahoo.test.json.JsonTestHelper.inputJson; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Basic test of JSON streams to Vespa document instances. * * @author Steinar Knutsen * @author bratseth */ public class JsonReaderTestCase { private DocumentTypeManager types; private JsonFactory parserFactory; @Before public void setUp() throws Exception { parserFactory = new JsonFactory(); types = new DocumentTypeManager(); { DocumentType x = new DocumentType("smoke"); x.addField(new Field("something", DataType.STRING)); x.addField(new Field("nalle", DataType.STRING)); x.addField(new Field("field1", DataType.STRING)); x.addField(new Field("field2", DataType.STRING)); x.addField(new Field("int1", DataType.INT)); x.addField(new Field("flag", DataType.BOOL)); x.addField(new Field("tensor1", DataType.getTensor(TensorType.fromSpec("tensor(x{})")))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("mirrors"); StructDataType woo = new StructDataType("woo"); woo.addField(new Field("sandra", DataType.STRING)); woo.addField(new Field("cloud", DataType.STRING)); x.addField(new Field("skuggsjaa", woo)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testarray"); DataType d = new ArrayDataType(DataType.STRING); x.addField(new Field("actualarray", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testset"); DataType d = new WeightedSetDataType(DataType.STRING, true, true); x.addField(new Field("actualset", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testmap"); DataType d = new MapDataType(DataType.STRING, DataType.STRING); x.addField(new Field("actualmap", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testraw"); DataType d = DataType.RAW; x.addField(new Field("actualraw", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testMapStringToArrayOfInt"); DataType value = new ArrayDataType(DataType.INT); DataType d = new MapDataType(DataType.STRING, value); x.addField(new Field("actualMapStringToArrayOfInt", d)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testArrayOfArrayOfInt"); DataType inner = new ArrayDataType(DataType.INT); DataType outer = new ArrayDataType(inner); x.addField(new Field("arrayOfArrayOfInt", outer)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testsinglepos"); DataType d = PositionDataType.INSTANCE; x.addField(new Field("singlepos", d)); x.addField(new Field("geopos", new GeoPosType(8))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testtensor"); x.addField(new Field("sparse_single_dimension_tensor", new TensorDataType(new TensorType.Builder().mapped("x").build()))); x.addField(new Field("sparse_tensor", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").build()))); x.addField(new Field("dense_tensor", new TensorDataType(new TensorType.Builder().indexed("x", 2).indexed("y", 3).build()))); x.addField(new Field("dense_int8_tensor", new TensorDataType(TensorType.fromSpec("tensor<int8>(x[2],y[3])")))); x.addField(new Field("dense_unbound_tensor", new TensorDataType(new TensorType.Builder().indexed("x").indexed("y").build()))); x.addField(new Field("mixed_tensor", new TensorDataType(new TensorType.Builder().mapped("x").indexed("y", 3).build()))); x.addField(new Field("mixed_bfloat16_tensor", new TensorDataType(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")))); x.addField(new Field("mixed_tensor_adv", new TensorDataType(new TensorType.Builder().mapped("x").mapped("y").mapped("z").indexed("a", 3).build()))); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testpredicate"); x.addField(new Field("boolean", DataType.PREDICATE)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testint"); x.addField(new Field("integerfield", DataType.INT)); types.registerDocumentType(x); } { DocumentType x = new DocumentType("testnull"); x.addField(new Field("intfield", DataType.INT)); x.addField(new Field("stringfield", DataType.STRING)); x.addField(new Field("arrayfield", new ArrayDataType(DataType.STRING))); x.addField(new Field("weightedsetfield", new WeightedSetDataType(DataType.STRING, true, true))); x.addField(new Field("mapfield", new MapDataType(DataType.STRING, DataType.STRING))); x.addField(new Field("tensorfield", new TensorDataType(new TensorType.Builder().indexed("x").build()))); types.registerDocumentType(x); } } @After public void tearDown() throws Exception { types = null; parserFactory = null; } private JsonReader createReader(String jsonInput) { InputStream input = new ByteArrayInputStream(Utf8.toBytes(jsonInput)); return new JsonReader(types, input, parserFactory); } @Test public void readDocumentWithMissingFieldsField() { assertEquals("document is missing the required \"fields\" field", assertThrows(IllegalArgumentException.class, () -> createReader("{ }").readSingleDocumentStreaming(DocumentOperationType.PUT, "id:unittest:testnull::whee")) .getMessage()); } @Test public void readSingleDocumentsPutStreaming() throws IOException { String json = """ { "remove": "id:unittest:smoke::ignored", "ignored-extra-array": [{ "foo": null }, { }], "ignored-extra-object": { "foo": [null, { }], "bar": { } }, "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" }, "id": "id:unittest:smoke::ignored", "create": false, "condition": "true" } """; ParsedDocumentOperation operation = createReader(json).readSingleDocumentStreaming(DocumentOperationType.PUT,"id:unittest:smoke::doc1"); DocumentPut put = ((DocumentPut) operation.operation()); assertFalse(put.getCreateIfNonExistent()); assertEquals("true", put.getCondition().getSelection()); smokeTestDoc(put.getDocument()); } @Test public void readSingleDocumentsUpdateStreaming() throws IOException { String json = """ { "remove": "id:unittest:smoke::ignored", "ignored-extra-array": [{ "foo": null }, { }], "ignored-extra-object": { "foo": [null, { }], "bar": { } }, "fields": { "something": { "assign": "smoketest" }, "flag": { "assign": true }, "nalle": { "assign": "bamse" } }, "id": "id:unittest:smoke::ignored", "create": true, "condition": "false" } """; ParsedDocumentOperation operation = createReader(json).readSingleDocumentStreaming(DocumentOperationType.UPDATE,"id:unittest:smoke::doc1"); Document doc = new Document(types.getDocumentType("smoke"), new DocumentId("id:unittest:smoke::doc1")); DocumentUpdate update = ((DocumentUpdate) operation.operation()); update.applyTo(doc); smokeTestDoc(doc); assertTrue(update.getCreateIfNonExistent()); assertEquals("false", update.getCondition().getSelection()); } @Test public void readSingleDocumentPut() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:smoke::doc1", "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" } } """); smokeTestDoc(doc); } @Test public final void readSingleDocumentUpdate() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:smoke::whee", "fields": { "something": { "assign": "orOther" } } } """); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof AssignValueUpdate); assertEquals(new StringFieldValue("orOther"), f.getValueUpdate(0).getValue()); } @Test public void readClearField() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:smoke::whee", "fields": { "int1": { "assign": null } } } """); FieldUpdate f = doc.getFieldUpdate("int1"); assertEquals(1, f.size()); assertTrue(f.getValueUpdate(0) instanceof ClearValueUpdate); assertNull(f.getValueUpdate(0).getValue()); } @Test public void smokeTest() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:smoke::doc1", "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" } } """); smokeTestDoc(doc); } @Test public void docIdLookaheadTest() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:smoke::doc1", "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" } } """); smokeTestDoc(doc); } @Test public void emptyDocTest() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:smoke::whee", "fields": { } }"""); assertEquals(new Document(types.getDocumentType("smoke"), new DocumentId("id:unittest:smoke::whee")), doc); } @Test public void testStruct() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:mirrors::whee", "fields": { "skuggsjaa": { "sandra": "person", "cloud": "another person" } } } """); FieldValue f = doc.getFieldValue(doc.getField("skuggsjaa")); assertSame(Struct.class, f.getClass()); Struct s = (Struct) f; assertEquals("person", ((StringFieldValue) s.getFieldValue("sandra")).getString()); } private DocumentUpdate parseUpdate(String json) throws IOException { InputStream rawDoc = new ByteArrayInputStream(Utf8.toBytes(json)); JsonReader r = new JsonReader(types, rawDoc, parserFactory); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentUpdate update = new DocumentUpdate(docType, parseInfo.documentId); new VespaJsonDocumentReader(false).readUpdate(parseInfo.fieldsBuffer, update); return update; } @Test public void testStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(""" { "update": "id:unittest:mirrors:g=test:whee", "create": true, "fields": { "skuggsjaa": { "assign": { "sandra": "person", "cloud": "another person" } } } } """); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(2, s.getFieldCount()); assertEquals(new StringFieldValue("person"), s.getFieldValue(s.getField("sandra"))); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(107, buf.position()); } @Test public final void testEmptyStructUpdate() throws IOException { DocumentUpdate put = parseUpdate(""" { "update": "id:unittest:mirrors:g=test:whee", "create": true, "fields": { "skuggsjaa": { "assign": { } } } } """); assertEquals(1, put.fieldUpdates().size()); FieldUpdate fu = put.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); ValueUpdate vu = fu.getValueUpdate(0); assertTrue(vu instanceof AssignValueUpdate); AssignValueUpdate avu = (AssignValueUpdate) vu; assertTrue(avu.getValue() instanceof Struct); Struct s = (Struct) avu.getValue(); assertEquals(0, s.getFieldCount()); GrowableByteBuffer buf = new GrowableByteBuffer(); DocumentSerializer serializer = DocumentSerializerFactory.create6(buf); put.serialize(serializer); assertEquals(69, buf.position()); } @Test public void testUpdateArray() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testarray::whee", "fields": { "actualarray": { "add": [ "person", "another person" ] } } } """); checkSimpleArrayAdd(doc); } @Test public void testUpdateWeighted() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testset::whee", "fields": { "actualset": { "add": { "person": 37, "another person": 41 } } } } """); Map<String, Integer> weights = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; final String s = ((StringFieldValue) adder.getValue()).getString(); weights.put(s, adder.getWeight()); } assertEquals(2, weights.size()); final String o = "person"; final String o2 = "another person"; assertTrue(weights.containsKey(o)); assertTrue(weights.containsKey(o2)); assertEquals(Integer.valueOf(37), weights.get(o)); assertEquals(Integer.valueOf(41), weights.get(o2)); } @Test public void testUpdateMatch() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testset::whee", "fields": { "actualset": { "match": { "element": "person", "increment": 13 } } } } """); DocumentUpdate otherDoc = parseUpdate(""" { "update": "id:unittest:testset::whee", "fields": { "actualset": { "match": { "increment": 13, "element": "person" } } } }"""); assertEquals(doc, otherDoc); Map<String, Tuple2<Number, String>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate<?> v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); String op = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperator().toString(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()).getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertEquals("ADD", matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } @SuppressWarnings({ "cast", "unchecked", "rawtypes" }) @Test public void testArithmeticOperators() throws IOException { Tuple2[] operations = new Tuple2[] { new Tuple2<>(UPDATE_DECREMENT, ArithmeticValueUpdate.Operator.SUB), new Tuple2<>(UPDATE_DIVIDE, ArithmeticValueUpdate.Operator.DIV), new Tuple2<>(UPDATE_INCREMENT, ArithmeticValueUpdate.Operator.ADD), new Tuple2<>(UPDATE_MULTIPLY, ArithmeticValueUpdate.Operator.MUL) }; for (Tuple2<String, Operator> operator : operations) { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testset::whee", "fields": { "actualset": { "match": { "element": "person", "%s": 13 } } } } """.formatted(operator.first)); Map<String, Tuple2<Number, Operator>> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualset"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final String key = ((StringFieldValue) adder.getValue()) .getString(); Operator op = ((ArithmeticValueUpdate) adder .getUpdate()).getOperator(); Number n = ((ArithmeticValueUpdate) adder.getUpdate()) .getOperand(); matches.put(key, new Tuple2<>(n, op)); } assertEquals(1, matches.size()); final String o = "person"; assertSame(operator.second, matches.get(o).second); assertEquals(Double.valueOf(13), matches.get(o).first); } } @SuppressWarnings("rawtypes") @Test public void testArrayIndexing() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testarray::whee", "fields": { "actualarray": { "match": { "element": 3, "assign": "nalle" } } } } """); Map<Number, String> matches = new HashMap<>(); FieldUpdate x = doc.getFieldUpdate("actualarray"); for (ValueUpdate v : x.getValueUpdates()) { MapValueUpdate adder = (MapValueUpdate) v; final Number key = ((IntegerFieldValue) adder.getValue()) .getNumber(); String op = ((StringFieldValue) adder.getUpdate() .getValue()).getString(); matches.put(key, op); } assertEquals(1, matches.size()); Number n = Integer.valueOf(3); assertEquals("nalle", matches.get(n)); } @Test public void testDocumentRemove() { JsonReader r = createReader(inputJson("{'remove': 'id:unittest:smoke::whee'}")); DocumentType docType = r.readDocumentType(new DocumentId("id:unittest:smoke::whee")); assertEquals("smoke", docType.getName()); } private Document docFromJson(String json) throws IOException { JsonReader r = createReader(json); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); return put.getDocument(); } @Test public void testWeightedSet() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testset::whee", "fields": { "actualset": { "nalle": 2, "tralle": 7 } } } """); FieldValue f = doc.getFieldValue(doc.getField("actualset")); assertSame(WeightedSet.class, f.getClass()); WeightedSet<?> w = (WeightedSet<?>) f; assertEquals(2, w.size()); assertEquals(Integer.valueOf(2), w.get(new StringFieldValue("nalle"))); assertEquals(Integer.valueOf(7), w.get(new StringFieldValue("tralle"))); } @Test public void testArray() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testarray::whee", "fields": { "actualarray": [ "nalle", "tralle" ] } } """); FieldValue f = doc.getFieldValue(doc.getField("actualarray")); assertSame(Array.class, f.getClass()); Array<?> a = (Array<?>) f; assertEquals(2, a.size()); assertEquals(new StringFieldValue("nalle"), a.get(0)); assertEquals(new StringFieldValue("tralle"), a.get(1)); } @Test public void testMap() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testmap::whee", "fields": { "actualmap": { "nalle": "kalle", "tralle": "skalle" } } } """); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testOldMap() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testmap::whee", "fields": { "actualmap": [ { "key": "nalle", "value": "kalle" }, { "key": "tralle", "value": "skalle" } ] } } """); FieldValue f = doc.getFieldValue(doc.getField("actualmap")); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; assertEquals(2, m.size()); assertEquals(new StringFieldValue("kalle"), m.get(new StringFieldValue("nalle"))); assertEquals(new StringFieldValue("skalle"), m.get(new StringFieldValue("tralle"))); } @Test public void testPositionPositive() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "singlepos": "N63.429722;E10.393333" } } """); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionOld() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "singlepos": { "x": 10393333, "y": 63429722 } } } """); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testGeoPosition() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "singlepos": { "lat": 63.429722, "lng": 10.393333 } } } """); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testGeoPositionNoAbbreviations() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "singlepos": { "latitude": 63.429722, "longitude": 10.393333 } } } """); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); } @Test public void testPositionGeoPos() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "geopos": "N63.429722;E10.393333" } } """); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); } @Test public void testPositionOldGeoPos() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "geopos": { "x": 10393333, "y": 63429722 } } } """); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); } @Test public void testGeoPositionGeoPos() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "geopos": { "lat": 63.429722, "lng": 10.393333 } } } """); FieldValue f = doc.getFieldValue(doc.getField("geopos")); assertSame(Struct.class, f.getClass()); assertEquals(10393333, PositionDataType.getXValue(f).getInteger()); assertEquals(63429722, PositionDataType.getYValue(f).getInteger()); assertEquals(f.getDataType(), PositionDataType.INSTANCE); assertEquals(PositionDataType.INSTANCE, f.getDataType()); } @Test public void testPositionNegative() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testsinglepos::bamf", "fields": { "singlepos": "W46.63;S23.55" } } """); FieldValue f = doc.getFieldValue(doc.getField("singlepos")); assertSame(Struct.class, f.getClass()); assertEquals(-46630000, PositionDataType.getXValue(f).getInteger()); assertEquals(-23550000, PositionDataType.getYValue(f).getInteger()); } @Test public void testRaw() throws IOException { String base64 = new String(new JsonStringEncoder().quoteAsString( Base64.getEncoder().withoutPadding().encodeToString(Utf8.toBytes("smoketest")))); String s = fieldStringFromBase64RawContent(base64); assertEquals("smoketest", s); } @Test public void can_read_legacy_chunked_base64_raw_field_encoding() throws IOException { String expected = "this is a string with an impressive length. it's long enough to reach the end of the line, wow!"; String base64withDelims = "dGhpcyBpcyBhIHN0cmluZyB3aXRoIGFuIGltcHJlc3NpdmUgbGVuZ3RoLiBpdCdzIGxvbmcgZW5v\\r\\n" + "dWdoIHRvIHJlYWNoIHRoZSBlbmQgb2YgdGhlIGxpbmUsIHdvdyE=\\r\\n"; assertEquals(expected, fieldStringFromBase64RawContent(base64withDelims)); } private String fieldStringFromBase64RawContent(String base64data) throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testraw::whee", "fields": { "actualraw": "%s" } } """.formatted(base64data)); FieldValue f = doc.getFieldValue(doc.getField("actualraw")); assertSame(Raw.class, f.getClass()); Raw s = (Raw) f; return Utf8.toString(s.getByteBuffer()); } @Test public void testMapStringToArrayOfInt() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt": { "bamse": [1, 2, 3] } } } """); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldMapStringToArrayOfInt() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt": [ { "key": "bamse", "value": [1, 2, 3] } ] } } """); FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt"); assertSame(MapFieldValue.class, f.getClass()); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) f; Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToString() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:smoke::whee", "fields": { "something": { "assign": "orOther" } } } """); FieldUpdate f = doc.getFieldUpdate("something"); assertEquals(1, f.size()); AssignValueUpdate a = (AssignValueUpdate) f.getValueUpdate(0); assertEquals(new StringFieldValue("orOther"), a.getValue()); } @Test public void testNestedArrayMatch() throws IOException { DocumentUpdate nested = parseUpdate(""" { "update": "id:unittest:testArrayOfArrayOfInt::whee", "fields": { "arrayOfArrayOfInt": { "match": { "element": 1, "match": { "element": 2, "assign": 3 } } } } } """); DocumentUpdate equivalent = parseUpdate(""" { "update": "id:unittest:testArrayOfArrayOfInt::whee", "fields": { "arrayOfArrayOfInt": { "match": { "match": { "assign": 3, "element": 2 }, "element": 1 } } } } """); assertEquals(nested, equivalent); assertEquals(1, nested.fieldUpdates().size()); FieldUpdate fu = nested.fieldUpdates().iterator().next(); assertEquals(1, fu.getValueUpdates().size()); MapValueUpdate mvu = (MapValueUpdate) fu.getValueUpdate(0); assertEquals(new IntegerFieldValue(1), mvu.getValue()); MapValueUpdate nvu = (MapValueUpdate) mvu.getUpdate(); assertEquals(new IntegerFieldValue(2), nvu.getValue()); AssignValueUpdate avu = (AssignValueUpdate) nvu.getUpdate(); assertEquals(new IntegerFieldValue(3), avu.getValue()); Document doc = docFromJson(""" { "put": "id:unittest:testArrayOfArrayOfInt::whee", "fields": { "arrayOfArrayOfInt": [ [1, 2, 3], [4, 5, 6] ] } } """); nested.applyTo(doc); Document expected = docFromJson(""" { "put": "id:unittest:testArrayOfArrayOfInt::whee", "fields": { "arrayOfArrayOfInt": [ [1, 2, 3], [4, 5, 3] ] } } """); assertEquals(expected, doc); } @Test public void testMatchCannotUpdateNestedFields() { // Should this work? It doesn't. assertEquals("Field type Map<string,Array<int>> not supported.", assertThrows(UnsupportedOperationException.class, () -> parseUpdate(""" { "update": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt": { "match": { "element": "bamse", "match": { "element": 1, "assign": 4 } } } } } """)).getMessage()); } @Test public void testMatchCannotAssignToNestedMap() { // Unsupported value type for map value assign. assertEquals("Field type Map<string,Array<int>> not supported.", assertThrows(UnsupportedOperationException.class, () -> parseUpdate(""" { "update": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt": { "match": { "element": "bamse", "assign": [1, 3, 4] } } } } """)).getMessage()); } @Test public void testMatchCannotAssignToMap() { // Unsupported value type for map value assign. assertEquals("Field type Map<string,string> not supported.", assertThrows(UnsupportedOperationException.class, () -> parseUpdate(""" { "update": "id:unittest:testmap::whee", "fields": { "actualmap": { "match": { "element": "bamse", "assign": "bar" } } } } """)).getMessage()); } @Test public void testAssignInsideArrayInMap() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt": { "bamse": [1, 2, 3] } } }"""); assertEquals(2, ((MapFieldValue<StringFieldValue, Array<IntegerFieldValue>>) doc.getFieldValue("actualMapStringToArrayOfInt")) .get(StringFieldValue.getFactory().create("bamse")).get(1).getInteger()); DocumentUpdate update = parseUpdate(""" { "update": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt{bamse}[1]": { "assign": 4 } } } """); assertEquals(1, update.fieldPathUpdates().size()); update.applyTo(doc); assertEquals(4, ((MapFieldValue<StringFieldValue, Array<IntegerFieldValue>>) doc.getFieldValue("actualMapStringToArrayOfInt")) .get(StringFieldValue.getFactory().create("bamse")).get(1).getInteger()); } @Test public void testAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt": { "assign": { "bamse": [1, 2, 3] } } } } """); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testOldAssignToArray() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testMapStringToArrayOfInt::whee", "fields": { "actualMapStringToArrayOfInt": { "assign": [ { "key": "bamse", "value": [1, 2, 3] } ] } } } """); FieldUpdate f = doc.getFieldUpdate("actualMapStringToArrayOfInt"); assertEquals(1, f.size()); AssignValueUpdate assign = (AssignValueUpdate) f.getValueUpdate(0); MapFieldValue<?, ?> m = (MapFieldValue<?, ?>) assign.getValue(); Array<?> a = (Array<?>) m.get(new StringFieldValue("bamse")); assertEquals(3, a.size()); assertEquals(new IntegerFieldValue(1), a.get(0)); assertEquals(new IntegerFieldValue(2), a.get(1)); assertEquals(new IntegerFieldValue(3), a.get(2)); } @Test public void testAssignToWeightedSet() throws IOException { DocumentUpdate doc = parseUpdate(""" { "update": "id:unittest:testset::whee", "fields": { "actualset": { "assign": { "person": 37, "another person": 41 } } } } """); FieldUpdate x = doc.getFieldUpdate("actualset"); assertEquals(1, x.size()); AssignValueUpdate assign = (AssignValueUpdate) x.getValueUpdate(0); WeightedSet<?> w = (WeightedSet<?>) assign.getValue(); assertEquals(2, w.size()); assertEquals(Integer.valueOf(37), w.get(new StringFieldValue("person"))); assertEquals(Integer.valueOf(41), w.get(new StringFieldValue("another person"))); } @Test public void testCompleteFeed() { JsonReader r = createReader(""" [ { "put": "id:unittest:smoke::whee", "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" } }, { "update": "id:unittest:testarray::whee", "fields": { "actualarray": { "add": [ "person", "another person" ] } } }, { "remove": "id:unittest:smoke::whee" } ] """); controlBasicFeed(r); } @Test public void testCompleteFeedWithCreateAndCondition() { JsonReader r = createReader(""" [ { "put": "id:unittest:smoke::whee", "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" } }, { "condition":"bla", "update": "id:unittest:testarray::whee", "create":true, "fields": { "actualarray": { "add": [ "person", "another person" ] } } }, { "remove": "id:unittest:smoke::whee" } ] """); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testUpdateWithConditionAndCreateInDifferentOrdering() { int documentsCreated = 106; List<String> parts = Arrays.asList( "\"condition\":\"bla\"", "\"update\": \"id:unittest:testarray::whee\"", " \"fields\": { " + "\"actualarray\": { \"add\": [" + " \"person\",\"another person\"]}}", " \"create\":true"); Random random = new Random(42); StringBuilder documents = new StringBuilder("["); for (int x = 0; x < documentsCreated; x++) { Collections.shuffle(parts, random); documents.append("{").append(Joiner.on(",").join(parts)).append("}"); if (x < documentsCreated -1) { documents.append(","); } } documents.append("]"); InputStream rawDoc = new ByteArrayInputStream(Utf8.toBytes(documents.toString())); JsonReader r = new JsonReader(types, rawDoc, parserFactory); for (int x = 0; x < documentsCreated; x++) { DocumentUpdate update = (DocumentUpdate) r.next(); checkSimpleArrayAdd(update); assertTrue(update.getCreateIfNonExistent()); assertEquals("bla", update.getCondition().getSelection()); } assertNull(r.next()); } @Test public void testCreateIfNonExistentInPut() { JsonReader r = createReader(""" [ { "create":true, "fields": { "something": "smoketest", "nalle": "bamse" }, "put": "id:unittest:smoke::whee" } ] """); var op = r.next(); var put = (DocumentPut) op; assertTrue(put.getCreateIfNonExistent()); } @Test public void testCompleteFeedWithIdAfterFields() { JsonReader r = createReader(""" [ { "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" }, "put": "id:unittest:smoke::whee" }, { "fields": { "actualarray": { "add": [ "person", "another person" ] } }, "update": "id:unittest:testarray::whee" }, { "remove": "id:unittest:smoke::whee" } ] """); controlBasicFeed(r); } protected void controlBasicFeed(JsonReader r) { DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); smokeTestDoc(doc); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; checkSimpleArrayAdd(update); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } @Test public void testCompleteFeedWithEmptyDoc() { JsonReader r = createReader(""" [ { "put": "id:unittest:smoke::whee", "fields": {} }, { "update": "id:unittest:testarray::whee", "fields": {} }, { "remove": "id:unittest:smoke::whee" } ] """); DocumentOperation d = r.next(); Document doc = ((DocumentPut) d).getDocument(); assertEquals("smoke", doc.getId().getDocType()); d = r.next(); DocumentUpdate update = (DocumentUpdate) d; assertEquals("testarray", update.getId().getDocType()); d = r.next(); DocumentRemove remove = (DocumentRemove) d; assertEquals("smoke", remove.getId().getDocType()); assertNull(r.next()); } private void checkSimpleArrayAdd(DocumentUpdate update) { Set<String> toAdd = new HashSet<>(); FieldUpdate x = update.getFieldUpdate("actualarray"); for (ValueUpdate<?> v : x.getValueUpdates()) { AddValueUpdate adder = (AddValueUpdate) v; toAdd.add(((StringFieldValue) adder.getValue()).getString()); } assertEquals(2, toAdd.size()); assertTrue(toAdd.contains("person")); assertTrue(toAdd.contains("another person")); } private void smokeTestDoc(Document doc) { FieldValue boolField = doc.getFieldValue(doc.getField("flag")); assertSame(BoolFieldValue.class, boolField.getClass()); assertTrue((Boolean)boolField.getWrappedValue()); FieldValue stringField = doc.getFieldValue(doc.getField("nalle")); assertSame(StringFieldValue.class, stringField.getClass()); assertEquals("bamse", ((StringFieldValue) stringField).getString()); } @Test public void nonExistingFieldCausesException() throws IOException { Exception expected = assertThrows(IllegalArgumentException.class, () -> docFromJson(""" { "put": "id:unittest:smoke::whee", "fields": { "smething": "smoketest", "nalle": "bamse" } } """)); assertTrue(expected.getMessage().startsWith("No field 'smething' in the structure of type 'smoke'")); } @Test public void nonExistingFieldsCanBeIgnoredInPut() throws IOException { JsonReader r = createReader(""" { "put": "id:unittest:smoke::doc1", "fields": { "nonexisting1": "ignored value", "field1": "value1", "nonexisting2": { "blocks": { "a": [2.0, 3.0], "b": [4.0, 5.0] } }, "field2": "value2", "nonexisting3": { "cells": [ { "address": { "x": "x1" }, "value": 1.0 } ] }, "tensor1": { "cells": { "x1": 1.0 } }, "nonexisting4": "ignored value" } } """); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); boolean fullyApplied = new VespaJsonDocumentReader(true).readPut(parseInfo.fieldsBuffer, put); assertFalse(fullyApplied); assertNull(put.getDocument().getField("nonexisting1")); assertEquals("value1", put.getDocument().getFieldValue("field1").toString()); assertNull(put.getDocument().getField("nonexisting2")); assertEquals("value2", put.getDocument().getFieldValue("field2").toString()); assertNull(put.getDocument().getField("nonexisting3")); assertEquals(Tensor.from("tensor(x{}):{{x:x1}:1.0}"), put.getDocument().getFieldValue("tensor1").getWrappedValue()); assertNull(put.getDocument().getField("nonexisting4")); } @Test public void nonExistingFieldsCanBeIgnoredInUpdate() throws IOException{ JsonReader r = createReader(""" { "update": "id:unittest:smoke::doc1", "fields": { "nonexisting1": { "assign": "ignored value" }, "field1": { "assign": "value1" }, "nonexisting2": { "assign": { "blocks": { "a":[2.0,3.0], "b":[4.0,5.0] } } }, "field2": { "assign": "value2" }, "nonexisting3": { "assign" : { "cells": [{"address": {"x": "x1"}, "value": 1.0}] } }, "tensor1": {"assign": { "cells": {"x1": 1.0} } }, "nonexisting4": { "assign": "ignored value" } } } """); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentUpdate update = new DocumentUpdate(docType, parseInfo.documentId); boolean fullyApplied = new VespaJsonDocumentReader(true).readUpdate(parseInfo.fieldsBuffer, update); assertFalse(fullyApplied); assertNull(update.getFieldUpdate("nonexisting1")); assertEquals("value1", update.getFieldUpdate("field1").getValueUpdates().get(0).getValue().getWrappedValue().toString()); assertNull(update.getFieldUpdate("nonexisting2")); assertEquals("value2", update.getFieldUpdate("field2").getValueUpdates().get(0).getValue().getWrappedValue().toString()); assertNull(update.getFieldUpdate("nonexisting3")); assertEquals(Tensor.from("tensor(x{}):{{x:x1}:1.0}"), update.getFieldUpdate("tensor1").getValueUpdates().get(0).getValue().getWrappedValue()); assertNull(update.getFieldUpdate("nonexisting4")); } @Test public void feedWithBasicErrorTest() { JsonReader r = createReader(""" [ { "put": "id:test:smoke::0", "fields": { "something": "foo" } }, { "put": "id:test:smoke::1", "fields": { "something": "foo" } }, { "put": "id:test:smoke::2", "fields": { "something": "foo" } }, ]"""); // Trailing comma in array ... assertTrue(assertThrows(RuntimeException.class, () -> { while (r.next() != null); }) .getMessage().contains("JsonParseException")); } @Test public void idAsAliasForPutTest() throws IOException{ JsonReader r = createReader(""" { "id": "id:unittest:smoke::doc1", "fields": { "something": "smoketest", "flag": true, "nalle": "bamse" } } """); DocumentParseInfo parseInfo = r.parseDocument().get(); DocumentType docType = r.readDocumentType(parseInfo.documentId); DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId)); boolean fullyApplied = new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put); assertTrue(fullyApplied); smokeTestDoc(put.getDocument()); } private void testFeedWithTestAndSetCondition(String jsonDoc) { ByteArrayInputStream parseInfoDoc = new ByteArrayInputStream(Utf8.toBytes(jsonDoc)); JsonReader reader = new JsonReader(types, parseInfoDoc, parserFactory); int NUM_OPERATIONS_IN_FEED = 3; for (int i = 0; i < NUM_OPERATIONS_IN_FEED; i++) { DocumentOperation operation = reader.next(); assertTrue("A test and set condition should be present", operation.getCondition().isPresent()); assertEquals("DocumentOperation's test and set condition should be equal to the one in the JSON feed", "smoke.something == \"smoketest\"", operation.getCondition().getSelection()); } assertNull(reader.next()); } @Test public void testFeedWithTestAndSetConditionOrderingOne() { testFeedWithTestAndSetCondition(""" [ { "put": "id:unittest:smoke::whee", "condition": "smoke.something == \\"smoketest\\"", "fields": { "something": "smoketest", "nalle": "bamse" } }, { "update": "id:unittest:testarray::whee", "condition": "smoke.something == \\"smoketest\\"", "fields": { "actualarray": { "add": [ "person", "another person" ] } } }, { "remove": "id:unittest:smoke::whee", "condition": "smoke.something == \\"smoketest\\"" } ] """); } @Test public void testFeedWithTestAndSetConditionOrderingTwo() { testFeedWithTestAndSetCondition(""" [ { "condition": "smoke.something == \\"smoketest\\"", "put": "id:unittest:smoke::whee", "fields": { "something": "smoketest", "nalle": "bamse" } }, { "condition": "smoke.something == \\"smoketest\\"", "update": "id:unittest:testarray::whee", "fields": { "actualarray": { "add": [ "person", "another person" ] } } }, { "condition": "smoke.something == \\"smoketest\\"", "remove": "id:unittest:smoke::whee" } ] """); } @Test public void testFeedWithTestAndSetConditionOrderingThree() { testFeedWithTestAndSetCondition(""" [ { "put": "id:unittest:smoke::whee", "fields": { "something": "smoketest", "nalle": "bamse" }, "condition": "smoke.something == \\"smoketest\\"" }, { "update": "id:unittest:testarray::whee", "fields": { "actualarray": { "add": [ "person", "another person" ] } }, "condition": "smoke.something == \\"smoketest\\"" }, { "remove": "id:unittest:smoke::whee", "condition": "smoke.something == \\"smoketest\\"" } ] """); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldAfterFieldsFieldShouldFailParse() { String jsonData = """ [ { "put": "id:unittest:smoke::whee", "fields": { "something": "smoketest", "nalle": "bamse" }, "bjarne": "stroustrup" } ]"""; new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldBeforeFieldsFieldShouldFailParse() { String jsonData = """ [ { "update": "id:unittest:testarray::whee", "what is this": "nothing to see here", "fields": { "actualarray": { "add": [ "person", "another person" ] } } } ]"""; new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldWithoutFieldsFieldShouldFailParse() { String jsonData = """ [ { "remove": "id:unittest:smoke::whee", "what is love": "baby, do not hurt me... much } ]"""; new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); } @Test public void testMissingOperation() { try { String jsonData = """ [ { "fields": { "actualarray": { "add": [ "person", "another person" ] } } } ]"""; new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Missing a document operation ('put', 'update' or 'remove')", e.getMessage()); } } @Test public void testMissingFieldsMapInPut() { try { String jsonData = """ [ { "put": "id:unittest:smoke::whee" } ]"""; new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("put of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testMissingFieldsMapInUpdate() { try { String jsonData = """ [ { "update": "id:unittest:smoke::whee" } ]"""; new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Update of document id:unittest:smoke::whee is missing a 'fields' map", e.getMessage()); } } @Test public void testNullValues() throws IOException { Document doc = docFromJson(""" { "put": "id:unittest:testnull::doc1", "fields": { "intfield": null, "stringfield": null, "arrayfield": null, "weightedsetfield": null, "mapfield": null, "tensorfield": null } } """); assertFieldValueNull(doc, "intfield"); assertFieldValueNull(doc, "stringfield"); assertFieldValueNull(doc, "arrayfield"); assertFieldValueNull(doc, "weightedsetfield"); assertFieldValueNull(doc, "mapfield"); assertFieldValueNull(doc, "tensorfield"); } @Test(expected=JsonReaderException.class) public void testNullArrayElement() throws IOException { docFromJson(""" { "put": "id:unittest:testnull::doc1", "fields": { "arrayfield": [ null ] } } """); fail(); } private void assertFieldValueNull(Document doc, String fieldName) { Field field = doc.getField(fieldName); assertNotNull(field); FieldValue fieldValue = doc.getFieldValue(field); assertNull(fieldValue); } static ByteArrayInputStream jsonToInputStream(String json) { return new ByteArrayInputStream(Utf8.toBytes(json)); } @Test public void testParsingWithoutTensorField() { Document doc = createPutWithoutTensor().getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals("id:unittest:testtensor::0", doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField("sparse_tensor")); assertNull(fieldValue); } @Test public void testParsingOfEmptyTensor() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor("{}")); } @Test public void testParsingOfTensorWithEmptyCells() { assertSparseTensorField("tensor(x{},y{}):{}", createPutWithSparseTensor(inputJson("{ 'cells': [] }"))); } @Test public void testDisallowedDenseTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{ 'values': [] }"), "dense_tensor", "The 'values' array does not contain any values"); assertCreatePutFails(inputJson("{ 'values': '' }"), "dense_tensor", "The 'values' string does not contain any values"); } @Test public void testDisallowedMixedTensorShortFormWithoutValues() { assertCreatePutFails(inputJson("{\"blocks\":{ \"a\": [] } }"), "mixed_tensor", "Expected 3 values, but got 0"); assertCreatePutFails(inputJson("{\"blocks\":[ {\"address\":{\"x\":\"a\"}, \"values\": [] } ] }"), "mixed_tensor", "Expected 3 values, but got 0"); } @Test public void testParsingOfSparseTensorWithCells() { Tensor tensor = assertSparseTensorField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createPutWithSparseTensor(""" { "type": "tensor(x{},y{})", "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 }, { "address": { "x": "c", "y": "b" }, "value": 3.0 } ] } """)); assertTrue(tensor instanceof MappedTensor); // any functional instance is fine } @Test public void testParsingOfDenseTensorWithCells() { Tensor tensor = assertTensorField("{{x:0,y:0}:2.0,{x:1,y:0}:3.0}}", createPutWithTensor(""" { "cells": [ { "address": { "x": 0, "y": 0 }, "value": 2.0 }, { "address": { "x": 1, "y": 0 }, "value": 3.0 } ] } """, "dense_unbound_tensor"), "dense_unbound_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorOnDenseForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(Double.POSITIVE_INFINITY); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(""" { "values": [2.0, 3.0, 4.0, "inf", 6.0, 7.0] }""", "dense_tensor"), "dense_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfDenseTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<int8>(x[2],y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); Tensor tensor = assertTensorField(expected, createPutWithTensor(""" { "values": "020304050607" }""", "dense_int8_tensor"), "dense_int8_tensor"); assertTrue(tensor instanceof IndexedTensor); // this matters for performance } @Test public void testParsingOfMixedTensorHexFormat() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor<bfloat16>(x{},y[3])")); builder.cell().label("x", "foo").label("y", 0).value(2.0); builder.cell().label("x", "foo").label("y", 1).value(3.0); builder.cell().label("x", "foo").label("y", 2).value(4.0); builder.cell().label("x", "bar").label("y", 0).value(5.0); builder.cell().label("x", "bar").label("y", 1).value(6.0); builder.cell().label("x", "bar").label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = """ { "blocks":[ {"address":{"x":"foo"},"values":"400040404080"}, {"address":{"x":"bar"},"values":"40A040C040E0"} ] } """; var put = createPutWithTensor(inputJson(mixedJson), "mixed_bfloat16_tensor"); Tensor tensor = assertTensorField(expected, put, "mixed_bfloat16_tensor"); } /** Tests parsing of various tensor values set at the root, i.e. no 'cells', 'blocks' or 'values' */ @Test public void testDirectValue() { assertTensorField("tensor(x{}):{a:2, b:3}", "sparse_single_dimension_tensor", "{'a':2.0, 'b':3.0}"); assertTensorField("tensor(x[2],y[3]):[2, 3, 4, 5, 6, 7]]", "dense_tensor", "[2, 3, 4, 5, 6, 7]"); assertTensorField("tensor(x[2],y[3]):[2, 3, 4, 5, 6, 7]]", "dense_tensor", "[[2, 3, 4], [5, 6, 7]]"); assertTensorField("tensor(x{},y[3]):{a:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'a':[2, 3, 4], 'b':[4, 5, 6]}"); assertTensorField("tensor(x{},y{}):{{x:a,y:0}:2, {x:b,y:1}:3}", "sparse_tensor", "[{'address':{'x':'a','y':'0'},'value':2}, {'address':{'x':'b','y':'1'},'value':3}]"); } @Test public void testDirectValueReservedNameKeys() { // Single-valued assertTensorField("tensor(x{}):{cells:2, b:3}", "sparse_single_dimension_tensor", "{'cells':2.0, 'b':3.0}"); assertTensorField("tensor(x{}):{values:2, b:3}", "sparse_single_dimension_tensor", "{'values':2.0, 'b':3.0}"); assertTensorField("tensor(x{}):{block:2, b:3}", "sparse_single_dimension_tensor", "{'block':2.0, 'b':3.0}"); // Multi-valued assertTensorField("tensor(x{},y[3]):{cells:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'cells':[2, 3, 4], 'b':[4, 5, 6]}"); assertTensorField("tensor(x{},y[3]):{values:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'values':[2, 3, 4], 'b':[4, 5, 6]}"); assertTensorField("tensor(x{},y[3]):{block:[2, 3, 4], b:[4, 5, 6]}", "mixed_tensor", "{'block':[2, 3, 4], 'b':[4, 5, 6]}"); } @Test public void testParsingOfMixedTensorOnMixedForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = """ { "blocks":[ {"address":{"x":"0"},"values":[2.0,3.0,4.0]}, {"address":{"x":"1"},"values":[5.0,6.0,7.0]} ] } """; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance String mixedJsonDirect = """ [ {"address":{"x":"0","y":"0"},"value":2.0}, {"address":{"x":"0","y":"1"},"value":3.0}, {"address":{"x":"0","y":"2"},"value":4.0}, {"address":{"x":"1","y":"0"},"value":5.0}, {"address":{"x":"1","y":"1"},"value":6.0}, {"address":{"x":"1","y":"2"},"value":7.0} ] """; Tensor tensorDirect = assertTensorField(expected, createPutWithTensor(inputJson(mixedJsonDirect), "mixed_tensor"), "mixed_tensor"); assertTrue(tensorDirect instanceof MixedTensor); // this matters for performance } @Test public void testMixedTensorInMixedFormWithSingleSparseDimensionShortForm() { Tensor.Builder builder = Tensor.Builder.of(TensorType.fromSpec("tensor(x{},y[3])")); builder.cell().label("x", 0).label("y", 0).value(2.0); builder.cell().label("x", 0).label("y", 1).value(3.0); builder.cell().label("x", 0).label("y", 2).value(4.0); builder.cell().label("x", 1).label("y", 0).value(5.0); builder.cell().label("x", 1).label("y", 1).value(6.0); builder.cell().label("x", 1).label("y", 2).value(7.0); Tensor expected = builder.build(); String mixedJson = """ { "blocks":{ "0":[2.0,3.0,4.0], "1":[5.0,6.0,7.0] } } """; Tensor tensor = assertTensorField(expected, createPutWithTensor(inputJson(mixedJson), "mixed_tensor"), "mixed_tensor"); assertTrue(tensor instanceof MixedTensor); // this matters for performance } @Test public void testParsingOfTensorWithSingleCellInDifferentJsonOrder() { assertSparseTensorField("{{x:a,y:b}:2.0}", createPutWithSparseTensor(""" { "cells": [ { "value": 2.0, "address": { "x": "a", "y": "b" } } ] } """)); } @Test public void testAssignUpdateOfEmptySparseTensor() { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithSparseTensor("{}")); } @Test public void testAssignUpdateOfEmptyDenseTensor() { try { assertTensorAssignUpdateSparseField("tensor(x{},y{}):{}", createAssignUpdateWithTensor("{}", "dense_unbound_tensor")); } catch (IllegalArgumentException e) { assertEquals("An indexed tensor must have a value", "Error in 'dense_unbound_tensor': Tensor of type tensor(x[],y[]) has no values", Exceptions.toMessageString(e)); } } @Test public void testAssignUpdateOfNullTensor() { ClearValueUpdate clearUpdate = (ClearValueUpdate) getTensorField(createAssignUpdateWithSparseTensor(null)).getValueUpdate(0); assertNotNull(clearUpdate); assertNull(clearUpdate.getValue()); } @Test public void testAssignUpdateOfTensorWithCells() { assertTensorAssignUpdateSparseField("{{x:a,y:b}:2.0,{x:c,y:b}:3.0}}", createAssignUpdateWithSparseTensor(""" { "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 }, { "address": { "x": "c", "y": "b" }, "value": 3.0 } ] } """)); } @Test public void testAssignUpdateOfTensorDenseShortForm() { assertTensorAssignUpdateDenseField("tensor(x[2],y[3]):[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]", createAssignUpdateWithTensor(""" { "values": [1,2,3,4,5,6] } """, "dense_tensor")); } @Test public void tensor_modify_update_with_replace_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_tensor", """ { "operation": "replace", "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_add_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, "sparse_tensor", """ { "operation": "add", "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_multiply_operation() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "sparse_tensor", """ { "operation": "multiply", "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_create_non_existing_cells_true() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, true, "sparse_tensor", """ { "operation": "add", "create": true, "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_create_non_existing_cells_false() { assertTensorModifyUpdate("{{x:a,y:b}:2.0}", TensorModifyUpdate.Operation.ADD, false, "sparse_tensor", """ { "operation": "add", "create": false, "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_treats_the_input_tensor_as_sparse() { // Note that the type of the tensor in the modify update is sparse (it only has mapped dimensions). assertTensorModifyUpdate("tensor(x{},y{}):{{x:0,y:0}:2.0, {x:1,y:2}:3.0}", TensorModifyUpdate.Operation.REPLACE, "dense_tensor", """ { "operation": "replace", "cells": [ { "address": { "x": "0", "y": "0" }, "value": 2.0 }, { "address": { "x": "1", "y": "2" }, "value": 3.0 } ] }"""); } @Test public void tensor_modify_update_on_non_tensor_field_throws() { try { JsonReader reader = createReader(""" { "update": "id:unittest:smoke::doc1", "fields": { "something": { "modify": {} } } } """); reader.readSingleDocument(DocumentOperationType.UPDATE, "id:unittest:smoke::doc1"); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Error in 'something': A modify update can only be applied to tensor fields. Field 'something' is of type 'string'", Exceptions.toMessageString(e)); } } @Test public void tensor_modify_update_on_dense_unbound_tensor_throws() { illegalTensorModifyUpdate("Error in 'dense_unbound_tensor': A modify update cannot be applied to tensor types with indexed unbound dimensions. Field 'dense_unbound_tensor' has unsupported tensor type 'tensor(x[],y[])'", "dense_unbound_tensor", """ { "operation": "replace", "cells": [ { "address": { "x": "0", "y": "0" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorModifyUpdate("{{x:a}:2.0, {x:c}: 3.0}", TensorModifyUpdate.Operation.REPLACE, "sparse_single_dimension_tensor", """ { "operation": "replace", "cells": { "a": 2.0, "c": 3.0 } }"""); } @Test public void tensor_modify_update_with_replace_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", """ { "operation": "replace", "cells": [ { "address": { "x": "a", "y": "0" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_array() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", """ { "operation": "replace", "blocks": [ { "address": { "x": "a" }, "values": [1,2,3] } ] }"""); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_must_specify_full_subspace() { illegalTensorModifyUpdate("Error in 'mixed_tensor': At {x:a}: Expected 3 values, but got 2", "mixed_tensor", """ { "operation": "replace", "blocks": { "a": [2,3] } }"""); } @Test public void tensor_modify_update_with_replace_operation_mixed_block_short_form_map() { assertTensorModifyUpdate("{{x:a,y:0}:1,{x:a,y:1}:2,{x:a,y:2}:3}", TensorModifyUpdate.Operation.REPLACE, "mixed_tensor", """ { "operation": "replace", "blocks": { "a": [1,2,3] } }"""); } @Test public void tensor_modify_update_with_add_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.ADD, "mixed_tensor", """ { "operation": "add", "cells": [ { "address": { "x": "a", "y": "0" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_multiply_operation_mixed() { assertTensorModifyUpdate("{{x:a,y:0}:2.0}", TensorModifyUpdate.Operation.MULTIPLY, "mixed_tensor", """ { "operation": "multiply", "cells": [ { "address": { "x": "a", "y": "0" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws() { illegalTensorModifyUpdate("Error in 'dense_tensor': Dimension 'y' has label '3' but type is tensor(x[2],y[3])", "dense_tensor", """ { "operation": "replace", "cells": [ { "address": { "x": "0", "y": "3" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_out_of_bound_cells_throws_mixed() { illegalTensorModifyUpdate("Error in 'mixed_tensor': Dimension 'y' has label '3' but type is tensor(x{},y[3])", "mixed_tensor", """ { "operation": "replace", "cells": [ { "address": { "x": "0", "y": "3" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_with_unknown_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown operation 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", """ { "operation": "unknown", "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 } ] }"""); } @Test public void tensor_modify_update_without_operation_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain an operation", "sparse_tensor", """ { "cells": [] }"""); } @Test public void tensor_modify_update_without_cells_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Modify update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", """ { "operation": "replace" }"""); } @Test public void tensor_modify_update_with_unknown_content_throws() { illegalTensorModifyUpdate("Error in 'sparse_tensor': Unknown JSON string 'unknown' in modify update for field 'sparse_tensor'", "sparse_tensor", """ { "unknown": "here" }"""); } @Test public void tensor_add_update_on_sparse_tensor() { assertTensorAddUpdate("{{x:a,y:b}:2.0, {x:c,y:d}: 3.0}", "sparse_tensor", """ { "cells": [ { "address": { "x": "a", "y": "b" }, "value": 2.0 }, { "address": { "x": "c", "y": "d" }, "value": 3.0 } ] }"""); } @Test public void tensor_add_update_on_sparse_tensor_with_single_dimension_short_form() { assertTensorAddUpdate("{{x:a}:2.0, {x:c}: 3.0}", "sparse_single_dimension_tensor", """ { "cells": { "a": 2.0, "c": 3.0 } }"""); } @Test public void tensor_add_update_on_mixed_tensor() { assertTensorAddUpdate("{{x:a,y:0}:2.0, {x:a,y:1}:3.0, {x:a,y:2}:0.0}", "mixed_tensor", """ { "cells": [ { "address": { "x": "a", "y": "0" }, "value": 2.0 }, { "address": { "x": "a", "y": "1" }, "value": 3.0 } ] }"""); } @Test public void tensor_add_update_on_mixed_with_out_of_bound_dense_cells_throws() { illegalTensorAddUpdate("Error in 'mixed_tensor': Index 3 out of bounds for length 3", "mixed_tensor", """ { "cells": [ { "address": { "x": "0", "y": "3" }, "value": 2.0 } ] }"""); } @Test public void tensor_add_update_on_dense_tensor_throws() { illegalTensorAddUpdate("Error in 'dense_tensor': An add update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", """ { "cells": [ ] }"""); } @Test public void tensor_add_update_on_not_fully_specified_cell_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Missing a label for dimension 'y' for tensor(x{},y{})", "sparse_tensor", """ { "cells": [ { "address": { "x": "a" }, "value": 2.0 } ] }"""); } @Test public void tensor_add_update_without_cells_throws() { illegalTensorAddUpdate("Error in 'sparse_tensor': Add update for field 'sparse_tensor' does not contain tensor cells", "sparse_tensor", "{}"); illegalTensorAddUpdate("Error in 'mixed_tensor': Add update for field 'mixed_tensor' does not contain tensor cells", "mixed_tensor", "{}"); } @Test public void tensor_remove_update_on_sparse_tensor() { assertTensorRemoveUpdate("{{x:a,y:b}:1.0,{x:c,y:d}:1.0}", "sparse_tensor", """ { "addresses": [ { "x": "a", "y": "b" }, { "x": "c", "y": "d" } ] }"""); } @Test public void tensor_remove_update_on_mixed_tensor() { assertTensorRemoveUpdate("{{x:1}:1.0,{x:2}:1.0}", "mixed_tensor", """ { "addresses": [ { "x": "1" }, { "x": "2" } ] }"""); } @Test public void tensor_remove_update_on_sparse_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{y:b}:1.0,{y:d}:1.0}", "sparse_tensor", """ { "addresses": [ { "y": "b" }, { "y": "d" } ] }"""); } @Test public void tensor_remove_update_on_mixed_tensor_with_not_fully_specified_address() { assertTensorRemoveUpdate("{{x:1,z:a}:1.0,{x:2,z:b}:1.0}", "mixed_tensor_adv", """ { "addresses": [ { "x": "1", "z": "a" }, { "x": "2", "z": "b" } ] }"""); } @Test public void tensor_remove_update_on_mixed_tensor_with_dense_addresses_throws() { illegalTensorRemoveUpdate("Error in 'mixed_tensor': Indexed dimension address 'y' should not be specified in remove update", "mixed_tensor", """ { "addresses": [ { "x": "1", "y": "0" }, { "x": "2", "y": "0" } ] }"""); } @Test public void tensor_remove_update_on_dense_tensor_throws() { illegalTensorRemoveUpdate("Error in 'dense_tensor': A remove update can only be applied to tensors with at least one sparse dimension. Field 'dense_tensor' has unsupported tensor type 'tensor(x[2],y[3])'", "dense_tensor", """ { "addresses": [] }"""); } @Test public void tensor_remove_update_with_stray_dimension_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{},y{}) does not contain dimension 'foo'", "sparse_tensor", """ { "addresses": [ { "x": "a", "foo": "b" } ] }"""); illegalTensorRemoveUpdate("Error in 'sparse_tensor': tensor(x{}) does not contain dimension 'foo'", "sparse_tensor", """ { "addresses": [ { "x": "c" }, { "x": "a", "foo": "b" } ] }"""); } @Test public void tensor_remove_update_without_cells_throws() { illegalTensorRemoveUpdate("Error in 'sparse_tensor': Remove update for field 'sparse_tensor' does not contain tensor addresses", "sparse_tensor", """ { "addresses": [] }"""); illegalTensorRemoveUpdate("Error in 'mixed_tensor': Remove update for field 'mixed_tensor' does not contain tensor addresses", "mixed_tensor", """ { "addresses": [] }"""); } @Test public void require_that_parser_propagates_datatype_parser_errors_predicate() { assertParserErrorMatches( "Error in document 'id:unittest:testpredicate::0' - could not parse field 'boolean' of type 'predicate': " + "line 1:10 no viable alternative at character '>'", """ [ { "fields": { "boolean": "timestamp > 9000" }, "put": "id:unittest:testpredicate::0" } ] """); } @Test public void require_that_parser_propagates_datatype_parser_errors_string_as_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \" 1\"", """ [ { "fields": { "integerfield": " 1" }, "put": "id:unittest:testint::0" } ] """); } @Test public void require_that_parser_propagates_datatype_parser_errors_overflowing_int() { assertParserErrorMatches( "Error in document 'id:unittest:testint::0' - could not parse field 'integerfield' of type 'int': " + "For input string: \"281474976710656\"", """ [ { "fields": { "integerfield": 281474976710656 }, "put": "id:unittest:testint::0" } ] """); } @Test public void requireThatUnknownDocTypeThrowsIllegalArgumentException() { String jsonData = """ [ { "put": "id:ns:walrus::walrus1", "fields": { "aField": 42 } } ] """; try { new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail(); } catch (IllegalArgumentException e) { assertEquals("Document type walrus does not exist", e.getMessage()); } } private static final String TENSOR_DOC_ID = "id:unittest:testtensor::0"; private void illegalTensorModifyUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorModifyUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorAddUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorAddUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private void illegalTensorRemoveUpdate(String expectedMessage, String field, String ... jsonLines) { try { createTensorRemoveUpdate(inputJson(jsonLines), field); fail("Expected exception"); } catch (IllegalArgumentException expected) { assertEquals(expectedMessage, Exceptions.toMessageString(expected)); } } private DocumentPut createPutWithoutTensor() { JsonReader reader = createReader(inputJson("[ { 'put': '" + TENSOR_DOC_ID + "', 'fields': { } } ]")); return (DocumentPut) reader.next(); } private DocumentPut createPutWithSparseTensor(String inputTensor) { return createPutWithTensor(inputTensor, "sparse_tensor"); } private DocumentPut createPutWithTensor(String inputTensor, String tensorFieldName) { JsonReader streaming = createReader(""" { "fields": { "%s": %s } } """.formatted(tensorFieldName, inputTensor)); DocumentPut lazyParsed = (DocumentPut) streaming.readSingleDocumentStreaming(DocumentOperationType.PUT, TENSOR_DOC_ID).operation(); JsonReader reader = createReader(""" [ { "put": "%s", "fields": { "%s": %s } } ]""".formatted(TENSOR_DOC_ID, tensorFieldName, inputTensor)); DocumentPut bufferParsed = (DocumentPut) reader.next(); assertEquals(lazyParsed, bufferParsed); return bufferParsed; } private DocumentUpdate createAssignUpdateWithSparseTensor(String inputTensor) { return createAssignUpdateWithTensor(inputTensor, "sparse_tensor"); } private DocumentUpdate createAssignUpdateWithTensor(String inputTensor, String tensorFieldName) { return createTensorUpdate("assign", inputTensor, tensorFieldName); } private static Tensor assertSparseTensorField(String expectedTensor, DocumentPut put) { return assertTensorField(expectedTensor, put, "sparse_tensor"); } private Tensor assertTensorField(String expectedTensor, String fieldName, String inputJson) { return assertTensorField(expectedTensor, createPutWithTensor(inputJson(inputJson), fieldName), fieldName); } private static Tensor assertTensorField(String expectedTensor, DocumentPut put, String tensorFieldName) { return assertTensorField(Tensor.from(expectedTensor), put, tensorFieldName); } private static Tensor assertTensorField(Tensor expectedTensor, DocumentPut put, String tensorFieldName) { Document doc = put.getDocument(); assertEquals("testtensor", doc.getId().getDocType()); assertEquals(TENSOR_DOC_ID, doc.getId().toString()); TensorFieldValue fieldValue = (TensorFieldValue)doc.getFieldValue(doc.getField(tensorFieldName)); assertEquals(expectedTensor, fieldValue.getTensor().get()); return fieldValue.getTensor().get(); } private static void assertTensorFieldUpdate(DocumentUpdate update, String tensorFieldName) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); assertEquals(1, update.fieldUpdates().size()); assertEquals(1, update.getFieldUpdate(tensorFieldName).size()); } private static void assertTensorAssignUpdateSparseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "sparse_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private static void assertTensorAssignUpdateDenseField(String expectedTensor, DocumentUpdate update) { assertEquals("testtensor", update.getId().getDocType()); assertEquals(TENSOR_DOC_ID, update.getId().toString()); AssignValueUpdate assignUpdate = (AssignValueUpdate) getTensorField(update, "dense_tensor").getValueUpdate(0); TensorFieldValue fieldValue = (TensorFieldValue) assignUpdate.getValue(); assertEquals(Tensor.from(expectedTensor), fieldValue.getTensor().get()); } private void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, String tensorFieldName, String modifyJson) { assertTensorModifyUpdate(expectedTensor, expectedOperation, false, tensorFieldName, createTensorModifyUpdate(modifyJson, tensorFieldName)); } private void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, boolean expectedCreateNonExistingCells, String tensorFieldName, String modifyJson) { assertTensorModifyUpdate(expectedTensor, expectedOperation, expectedCreateNonExistingCells, tensorFieldName, createTensorModifyUpdate(modifyJson, tensorFieldName)); } private static void assertTensorModifyUpdate(String expectedTensor, TensorModifyUpdate.Operation expectedOperation, boolean expectedCreateNonExistingCells, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorModifyUpdate modifyUpdate = (TensorModifyUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(expectedOperation, modifyUpdate.getOperation()); assertEquals(Tensor.from(expectedTensor), modifyUpdate.getValue().getTensor().get()); assertEquals(expectedCreateNonExistingCells, modifyUpdate.getCreateNonExistingCells()); } private DocumentUpdate createTensorModifyUpdate(String modifyJson, String tensorFieldName) { return createTensorUpdate("modify", modifyJson, tensorFieldName); } private DocumentUpdate createTensorAddUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("add", tensorJson, tensorFieldName); } private DocumentUpdate createTensorRemoveUpdate(String tensorJson, String tensorFieldName) { return createTensorUpdate("remove", tensorJson, tensorFieldName); } private DocumentUpdate createTensorUpdate(String operation, String tensorJson, String tensorFieldName) { JsonReader streaming = createReader(""" { "fields": { "%s": { "%s": %s } } }""".formatted(tensorFieldName, operation, tensorJson)); DocumentUpdate lazyParsed = (DocumentUpdate) streaming.readSingleDocumentStreaming(DocumentOperationType.UPDATE, TENSOR_DOC_ID).operation(); JsonReader reader = createReader(""" [ { "update": "%s", "fields": { "%s": { "%s": %s } } } ]""".formatted(TENSOR_DOC_ID, tensorFieldName, operation, tensorJson)); DocumentUpdate bufferParsed = (DocumentUpdate) reader.next(); assertEquals(lazyParsed, bufferParsed); return bufferParsed; } private void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorAddUpdate(expectedTensor, tensorFieldName, createTensorAddUpdate(tensorJson, tensorFieldName)); } private static void assertTensorAddUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorAddUpdate addUpdate = (TensorAddUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), addUpdate.getValue().getTensor().get()); } private void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, String tensorJson) { assertTensorRemoveUpdate(expectedTensor, tensorFieldName, createTensorRemoveUpdate(tensorJson, tensorFieldName)); } private static void assertTensorRemoveUpdate(String expectedTensor, String tensorFieldName, DocumentUpdate update) { assertTensorFieldUpdate(update, tensorFieldName); TensorRemoveUpdate removeUpdate = (TensorRemoveUpdate) update.getFieldUpdate(tensorFieldName).getValueUpdate(0); assertEquals(Tensor.from(expectedTensor), removeUpdate.getValue().getTensor().get()); } private static FieldUpdate getTensorField(DocumentUpdate update) { return getTensorField(update, "sparse_tensor"); } private static FieldUpdate getTensorField(DocumentUpdate update, String fieldName) { FieldUpdate fieldUpdate = update.getFieldUpdate(fieldName); assertEquals(1, fieldUpdate.size()); return fieldUpdate; } // NOTE: Do not call this method multiple times from a test method as it's using the ExpectedException rule private void assertParserErrorMatches(String expectedError, String... json) { String jsonData = inputJson(json); try { new JsonReader(types, jsonToInputStream(jsonData), parserFactory).next(); fail(); } catch (JsonReaderException e) { assertEquals(expectedError, e.getMessage()); } } private void assertCreatePutFails(String tensor, String name, String msg) { try { createPutWithTensor(inputJson(tensor), name); fail("Expected exception"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains(msg)); } } }
michaelcizmar/vespa
document/src/test/java/com/yahoo/document/json/JsonReaderTestCase.java
213,295
/* * Copyright (c) 2018, 2019 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.helidon.security.abac.role; import java.util.Optional; import javax.annotation.security.DenyAll; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import io.helidon.common.CollectionsHelper; import io.helidon.common.Errors; import io.helidon.config.Config; import io.helidon.security.EndpointConfig; import io.helidon.security.Principal; import io.helidon.security.ProviderRequest; import io.helidon.security.Role; import io.helidon.security.Subject; import io.helidon.security.SubjectType; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Unit test for {@link RoleValidator}. */ class RoleValidatorTest { static Config config; @BeforeAll static void beforeAll() { config = Config.create(); } @Test void testRolesAllowedPermit() { RoleValidator validator = RoleValidator.create(); RolesAllowed annot = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); EndpointConfig ep = mock(EndpointConfig.class); when(ep.combineAnnotations(RolesAllowed.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testRolesAllowedDeny() { RoleValidator validator = RoleValidator.create(); RolesAllowed annot = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); EndpointConfig ep = mock(EndpointConfig.class); when(ep.combineAnnotations(RolesAllowed.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("User is not in admin role, should have failed"); } } @Test void testUserRoles() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); when(annot.subjectType()).thenReturn(SubjectType.USER); EndpointConfig ep = mock(EndpointConfig.class); when(ep.combineAnnotations(RoleValidator.Roles.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testUserRolesDeny() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.subjectType()).thenReturn(SubjectType.USER); when(annot.value()).thenReturn(roleArray); EndpointConfig ep = mock(EndpointConfig.class); when(ep.combineAnnotations(RoleValidator.Roles.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("User is not in admin role, should have failed"); } } @Test void testServiceRoles() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); when(annot.subjectType()).thenReturn(SubjectType.SERVICE); EndpointConfig ep = mock(EndpointConfig.class); when(ep.combineAnnotations(RoleValidator.Roles.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.service()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("service")) .addGrant(Role.create("admin")) .build())); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testServiceRolesDeny() { RoleValidator validator = RoleValidator.create(); RoleValidator.Roles annot = mock(RoleValidator.Roles.class); String[] roleArray = new String[] {"admin"}; when(annot.value()).thenReturn(roleArray); when(annot.subjectType()).thenReturn(SubjectType.SERVICE); EndpointConfig ep = mock(EndpointConfig.class); when(ep.combineAnnotations(RoleValidator.Roles.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("service")) .addGrant(Role.create("user")) .build())); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("Service is not in admin role, should have failed"); } } @Test void testDenyAll() { RoleValidator validator = RoleValidator.create(); DenyAll annot = mock(DenyAll.class); EndpointConfig ep = mock(EndpointConfig.class); when(ep.combineAnnotations(DenyAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("DenyAll is set on this method, this should have failed"); } } @Test void testPermitAll() { RoleValidator validator = RoleValidator.create(); PermitAll annot = mock(PermitAll.class); EndpointConfig ep = mock(EndpointConfig.class); when(ep.combineAnnotations(PermitAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(annot)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testDenyAllAndPermitAll() { RoleValidator validator = RoleValidator.create(); PermitAll permitAll = mock(PermitAll.class); DenyAll denyAll = mock(DenyAll.class); EndpointConfig ep = mock(EndpointConfig.class); when(ep.combineAnnotations(DenyAll.class, EndpointConfig.AnnotationScope.CLASS)) .thenReturn(CollectionsHelper.listOf(denyAll)); when(ep.combineAnnotations(PermitAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(permitAll)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("user")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testDenyAllAndRoles() { RoleValidator validator = RoleValidator.create(); DenyAll denyAll = mock(DenyAll.class); RolesAllowed rolesAllowed = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(rolesAllowed.value()).thenReturn(roleArray); EndpointConfig ep = mock(EndpointConfig.class); when(ep.combineAnnotations(DenyAll.class, EndpointConfig.AnnotationScope.CLASS)) .thenReturn(CollectionsHelper.listOf(denyAll)); when(ep.combineAnnotations(RolesAllowed.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(rolesAllowed)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); collector.collect().checkValid(); } @Test void testPermitAllAndRolesAndDenyAll() { RoleValidator validator = RoleValidator.create(); PermitAll permitAll = mock(PermitAll.class); DenyAll denyAll = mock(DenyAll.class); RolesAllowed rolesAllowed = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(rolesAllowed.value()).thenReturn(roleArray); EndpointConfig ep = mock(EndpointConfig.class); when(ep.combineAnnotations(PermitAll.class, EndpointConfig.AnnotationScope.CLASS)) .thenReturn(CollectionsHelper.listOf(permitAll)); when(ep.combineAnnotations(DenyAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(denyAll)); when(ep.combineAnnotations(RolesAllowed.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(rolesAllowed)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("DenyAll is set on this method, this should have failed"); } } @Test void testAllAccessAnnotationsOnTheSameLevel() { RoleValidator validator = RoleValidator.create(); PermitAll permitAll = mock(PermitAll.class); DenyAll denyAll = mock(DenyAll.class); RolesAllowed rolesAllowed = mock(RolesAllowed.class); String[] roleArray = new String[] {"admin"}; when(rolesAllowed.value()).thenReturn(roleArray); EndpointConfig ep = mock(EndpointConfig.class); when(ep.combineAnnotations(PermitAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(permitAll)); when(ep.combineAnnotations(DenyAll.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(denyAll)); when(ep.combineAnnotations(RolesAllowed.class, EndpointConfig.AnnotationScope.METHOD)) .thenReturn(CollectionsHelper.listOf(rolesAllowed)); RoleValidator.RoleConfig rConfig = validator.fromAnnotations(ep); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); when(request.service()).thenReturn(Optional.empty()); validator.validate(rConfig, collector, request); if (collector.collect().isValid()) { fail("DenyAll is set on this method, this should have failed"); } } @Test void testRolesFromConfig() { RoleValidator roleValidator = RoleValidator.create(); RoleValidator.RoleConfig roleConfig = roleValidator.fromConfig(config.get("test1")); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("admin")) .build())); roleValidator.validate(roleConfig, collector, request); collector.collect().checkValid(); } @Test void testRolesAndPermitAllFromConfig() { RoleValidator roleValidator = RoleValidator.create(); RoleValidator.RoleConfig roleConfig = roleValidator.fromConfig(config.get("test2")); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("test")) .build())); roleValidator.validate(roleConfig, collector, request); collector.collect().checkValid(); } @Test void testRolesAndDenyAllFromConfig() { RoleValidator roleValidator = RoleValidator.create(); RoleValidator.RoleConfig roleConfig = roleValidator.fromConfig(config.get("test3")); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("test")) .build())); roleValidator.validate(roleConfig, collector, request); if (collector.collect().isValid()) { fail("DenyAll is set on this method, this should have failed"); } } @Test void testAllAccessModificationsOnTheSameLevelFromConfig() { RoleValidator roleValidator = RoleValidator.create(); RoleValidator.RoleConfig roleConfig = roleValidator.fromConfig(config.get("test4")); Errors.Collector collector = Errors.collector(); ProviderRequest request = mock(ProviderRequest.class); when(request.subject()).thenReturn(Optional.of(Subject.builder() .principal(Principal.create("myAdmin")) .addGrant(Role.create("test")) .build())); roleValidator.validate(roleConfig, collector, request); if (collector.collect().isValid()) { fail("DenyAll is set on this method, this should have failed"); } } }
fastso/helidon
security/abac/role/src/test/java/io/helidon/security/abac/role/RoleValidatorTest.java
213,296
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.dpi.cts; import android.content.Context; import android.test.AndroidTestCase; import android.util.DisplayMetrics; import android.view.Display; import android.view.WindowManager; import java.util.HashSet; import java.util.Set; /** * Test for verifying a device's screen configuration. */ public class ConfigurationTest extends AndroidTestCase { public void testScreenConfiguration() { WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); Display display = windowManager.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); double xInches = (double) metrics.widthPixels / metrics.xdpi; double yInches = (double) metrics.heightPixels / metrics.ydpi; double diagonalInches = Math.sqrt(Math.pow(xInches, 2) + Math.pow(yInches, 2)); assertTrue("Screen diagonal must be at least 2.5 inches: " + diagonalInches, diagonalInches >= 2.5d); double density = 160.0d * metrics.density; assertTrue("Screen density must be at least 100 dpi: " + density, density >= 100.0d); Set<Integer> allowedDensities = new HashSet<Integer>(); allowedDensities.add(DisplayMetrics.DENSITY_LOW); allowedDensities.add(DisplayMetrics.DENSITY_MEDIUM); allowedDensities.add(DisplayMetrics.DENSITY_TV); allowedDensities.add(DisplayMetrics.DENSITY_HIGH); allowedDensities.add(DisplayMetrics.DENSITY_XHIGH); assertTrue("DisplayMetrics#densityDpi must be one of the DisplayMetrics.DENSITY_* values: " + allowedDensities, allowedDensities.contains(metrics.densityDpi)); assertEquals(metrics.density, (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT, 0.5f / DisplayMetrics.DENSITY_DEFAULT); } }
andr3jx/MTK6577
cts/tests/tests/dpi/src/android/dpi/cts/ConfigurationTest.java
213,297
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.dpi.cts; import android.content.Context; import android.content.pm.PackageManager; import android.test.AndroidTestCase; import android.util.DisplayMetrics; import android.view.Display; import android.view.WindowManager; import java.util.HashSet; import java.util.Set; /** * Test for verifying a device's screen configuration. */ public class ConfigurationTest extends AndroidTestCase { public void testScreenConfiguration() { WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); Display display = windowManager.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); double xInches = (double) metrics.widthPixels / metrics.xdpi; double yInches = (double) metrics.heightPixels / metrics.ydpi; double diagonalInches = Math.sqrt(Math.pow(xInches, 2) + Math.pow(yInches, 2)); double minSize = 2.5d; if (getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) { // Watches have a different minimum diagonal. minSize = 1.0d; } assertTrue("Screen diagonal must be at least " + minSize + " inches: " + diagonalInches, diagonalInches >= minSize); double density = 160.0d * metrics.density; assertTrue("Screen density must be at least 100 dpi: " + density, density >= 100.0d); Set<Integer> allowedDensities = new HashSet<Integer>(); allowedDensities.add(DisplayMetrics.DENSITY_LOW); allowedDensities.add(DisplayMetrics.DENSITY_MEDIUM); allowedDensities.add(DisplayMetrics.DENSITY_TV); allowedDensities.add(DisplayMetrics.DENSITY_HIGH); allowedDensities.add(DisplayMetrics.DENSITY_280); allowedDensities.add(DisplayMetrics.DENSITY_XHIGH); allowedDensities.add(DisplayMetrics.DENSITY_360); allowedDensities.add(DisplayMetrics.DENSITY_400); allowedDensities.add(DisplayMetrics.DENSITY_420); allowedDensities.add(DisplayMetrics.DENSITY_XXHIGH); allowedDensities.add(DisplayMetrics.DENSITY_560); allowedDensities.add(DisplayMetrics.DENSITY_XXXHIGH); assertTrue("DisplayMetrics#densityDpi must be one of the DisplayMetrics.DENSITY_* values: " + allowedDensities, allowedDensities.contains(metrics.densityDpi)); assertEquals(metrics.density, (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT, 0.5f / DisplayMetrics.DENSITY_DEFAULT); } }
archermind/MTK_X20_BASE_AOSP
cts/tests/tests/dpi/src/android/dpi/cts/ConfigurationTest.java
213,298
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.dpi.cts; import android.content.Context; import android.content.pm.PackageManager; import android.platform.test.annotations.Presubmit; import android.test.AndroidTestCase; import android.util.DisplayMetrics; import android.view.Display; import android.view.WindowManager; import java.util.HashSet; import java.util.Set; /** * Test for verifying a device's screen configuration. */ public class ConfigurationTest extends AndroidTestCase { @Presubmit public void testScreenConfiguration() { WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); Display display = windowManager.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); double xInches = (double) metrics.widthPixels / metrics.xdpi; double yInches = (double) metrics.heightPixels / metrics.ydpi; double diagonalInches = Math.sqrt(Math.pow(xInches, 2) + Math.pow(yInches, 2)); double minSize = 2.5d; if (getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) { // Watches have a different minimum diagonal. minSize = 1.0d; } assertTrue("Screen diagonal must be at least " + minSize + " inches: " + diagonalInches, diagonalInches >= minSize); double density = 160.0d * metrics.density; assertTrue("Screen density must be at least 100 dpi: " + density, density >= 100.0d); Set<Integer> allowedDensities = new HashSet<Integer>(); allowedDensities.add(DisplayMetrics.DENSITY_LOW); allowedDensities.add(DisplayMetrics.DENSITY_MEDIUM); allowedDensities.add(DisplayMetrics.DENSITY_TV); allowedDensities.add(DisplayMetrics.DENSITY_HIGH); allowedDensities.add(DisplayMetrics.DENSITY_280); allowedDensities.add(DisplayMetrics.DENSITY_XHIGH); allowedDensities.add(DisplayMetrics.DENSITY_360); allowedDensities.add(DisplayMetrics.DENSITY_400); allowedDensities.add(DisplayMetrics.DENSITY_420); allowedDensities.add(DisplayMetrics.DENSITY_XXHIGH); allowedDensities.add(DisplayMetrics.DENSITY_560); allowedDensities.add(DisplayMetrics.DENSITY_XXXHIGH); assertTrue("DisplayMetrics#densityDpi must be one of the DisplayMetrics.DENSITY_* values: " + allowedDensities, allowedDensities.contains(metrics.densityDpi)); assertEquals(metrics.density, (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT, 0.5f / DisplayMetrics.DENSITY_DEFAULT); } }
xdtianyu/android-7.0.0_r1
cts/tests/tests/dpi/src/android/dpi/cts/ConfigurationTest.java
213,300
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.dpi.cts; import android.content.Context; import android.content.pm.PackageManager; import android.platform.test.annotations.Presubmit; import android.test.AndroidTestCase; import android.util.DisplayMetrics; import android.view.Display; import android.view.WindowManager; import java.util.HashSet; import java.util.Set; /** * Test for verifying a device's screen configuration. */ public class ConfigurationTest extends AndroidTestCase { @Presubmit public void testScreenConfiguration() { WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); Display display = windowManager.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); double xInches = (double) metrics.widthPixels / metrics.xdpi; double yInches = (double) metrics.heightPixels / metrics.ydpi; double diagonalInches = Math.sqrt(Math.pow(xInches, 2) + Math.pow(yInches, 2)); double minSize = 2.5d; if (getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) { // Watches have a different minimum diagonal. minSize = 1.0d; } assertTrue("Screen diagonal must be at least " + minSize + " inches: " + diagonalInches, diagonalInches >= minSize); double density = 160.0d * metrics.density; assertTrue("Screen density must be at least 100 dpi: " + density, density >= 100.0d); Set<Integer> allowedDensities = new HashSet<Integer>(); allowedDensities.add(DisplayMetrics.DENSITY_LOW); allowedDensities.add(DisplayMetrics.DENSITY_MEDIUM); allowedDensities.add(DisplayMetrics.DENSITY_TV); allowedDensities.add(DisplayMetrics.DENSITY_HIGH); allowedDensities.add(DisplayMetrics.DENSITY_260); allowedDensities.add(DisplayMetrics.DENSITY_280); allowedDensities.add(DisplayMetrics.DENSITY_300); allowedDensities.add(DisplayMetrics.DENSITY_XHIGH); allowedDensities.add(DisplayMetrics.DENSITY_340); allowedDensities.add(DisplayMetrics.DENSITY_360); allowedDensities.add(DisplayMetrics.DENSITY_400); allowedDensities.add(DisplayMetrics.DENSITY_420); allowedDensities.add(DisplayMetrics.DENSITY_XXHIGH); allowedDensities.add(DisplayMetrics.DENSITY_560); allowedDensities.add(DisplayMetrics.DENSITY_XXXHIGH); assertTrue("DisplayMetrics#densityDpi must be one of the DisplayMetrics.DENSITY_* values: " + allowedDensities, allowedDensities.contains(metrics.densityDpi)); assertEquals(metrics.density, (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT, 0.5f / DisplayMetrics.DENSITY_DEFAULT); } }
xdtianyu/android-8.0.0_r4
cts/tests/tests/dpi/src/android/dpi/cts/ConfigurationTest.java
213,301
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.dpi.cts; import android.content.Context; import android.content.pm.PackageManager; import android.test.AndroidTestCase; import android.util.DisplayMetrics; import android.view.Display; import android.view.WindowManager; import java.util.HashSet; import java.util.Set; /** * Test for verifying a device's screen configuration. */ public class ConfigurationTest extends AndroidTestCase { public void testScreenConfiguration() { WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); Display display = windowManager.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); double xInches = (double) metrics.widthPixels / metrics.xdpi; double yInches = (double) metrics.heightPixels / metrics.ydpi; double diagonalInches = Math.sqrt(Math.pow(xInches, 2) + Math.pow(yInches, 2)); double minSize = 2.5d; if (getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) { // Watches have a different minimum diagonal. minSize = 1.0d; } assertTrue("Screen diagonal must be at least " + minSize + " inches: " + diagonalInches, diagonalInches >= minSize); double density = 160.0d * metrics.density; assertTrue("Screen density must be at least 100 dpi: " + density, density >= 100.0d); Set<Integer> allowedDensities = new HashSet<Integer>(); allowedDensities.add(DisplayMetrics.DENSITY_LOW); allowedDensities.add(DisplayMetrics.DENSITY_MEDIUM); allowedDensities.add(DisplayMetrics.DENSITY_TV); allowedDensities.add(DisplayMetrics.DENSITY_HIGH); allowedDensities.add(DisplayMetrics.DENSITY_XHIGH); allowedDensities.add(DisplayMetrics.DENSITY_400); allowedDensities.add(DisplayMetrics.DENSITY_XXHIGH); allowedDensities.add(DisplayMetrics.DENSITY_560); allowedDensities.add(DisplayMetrics.DENSITY_XXXHIGH); assertTrue("DisplayMetrics#densityDpi must be one of the DisplayMetrics.DENSITY_* values: " + allowedDensities, allowedDensities.contains(metrics.densityDpi)); assertEquals(metrics.density, (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT, 0.5f / DisplayMetrics.DENSITY_DEFAULT); } }
mirek190/x86-android-5.0
cts/tests/tests/dpi/src/android/dpi/cts/ConfigurationTest.java
213,302
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.dpi.cts; import android.content.Context; import android.test.AndroidTestCase; import android.util.DisplayMetrics; import android.view.Display; import android.view.WindowManager; import java.util.HashSet; import java.util.Set; /** * Test for verifying a device's screen configuration. */ public class ConfigurationTest extends AndroidTestCase { public void testScreenConfiguration() { WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); Display display = windowManager.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); double xInches = (double) metrics.widthPixels / metrics.xdpi; double yInches = (double) metrics.heightPixels / metrics.ydpi; double diagonalInches = Math.sqrt(Math.pow(xInches, 2) + Math.pow(yInches, 2)); assertTrue("Screen diagonal must be at least 2.5 inches: " + diagonalInches, diagonalInches >= 2.5d); double density = 160.0d * metrics.density; assertTrue("Screen density must be at least 100 dpi: " + density, density >= 100.0d); Set<Integer> allowedDensities = new HashSet<Integer>(); allowedDensities.add(DisplayMetrics.DENSITY_LOW); allowedDensities.add(DisplayMetrics.DENSITY_MEDIUM); allowedDensities.add(DisplayMetrics.DENSITY_TV); allowedDensities.add(DisplayMetrics.DENSITY_HIGH); allowedDensities.add(DisplayMetrics.DENSITY_XHIGH); allowedDensities.add(DisplayMetrics.DENSITY_400); allowedDensities.add(DisplayMetrics.DENSITY_XXHIGH); allowedDensities.add(DisplayMetrics.DENSITY_XXXHIGH); assertTrue("DisplayMetrics#densityDpi must be one of the DisplayMetrics.DENSITY_* values: " + allowedDensities, allowedDensities.contains(metrics.densityDpi)); assertEquals(metrics.density, (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT, 0.5f / DisplayMetrics.DENSITY_DEFAULT); } }
xdtianyu/android-4.4.4
cts/tests/tests/dpi/src/android/dpi/cts/ConfigurationTest.java
213,303
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.dpi.cts; import android.content.Context; import android.test.AndroidTestCase; import android.util.DisplayMetrics; import android.view.Display; import android.view.WindowManager; import java.util.HashSet; import java.util.Set; /** * Test for verifying a device's screen configuration. */ public class ConfigurationTest extends AndroidTestCase { public void testScreenConfiguration() { WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); Display display = windowManager.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); double xInches = (double) metrics.widthPixels / metrics.xdpi; double yInches = (double) metrics.heightPixels / metrics.ydpi; double diagonalInches = Math.sqrt(Math.pow(xInches, 2) + Math.pow(yInches, 2)); assertTrue("Screen diagonal must be at least 2.5 inches: " + diagonalInches, diagonalInches >= 2.5d); double density = 160.0d * metrics.density; assertTrue("Screen density must be at least 100 dpi: " + density, density >= 100.0d); Set<Integer> allowedDensities = new HashSet<Integer>(); allowedDensities.add(DisplayMetrics.DENSITY_LOW); allowedDensities.add(DisplayMetrics.DENSITY_MEDIUM); allowedDensities.add(DisplayMetrics.DENSITY_TV); allowedDensities.add(DisplayMetrics.DENSITY_HIGH); allowedDensities.add(DisplayMetrics.DENSITY_XHIGH); allowedDensities.add(DisplayMetrics.DENSITY_XXHIGH); assertTrue("DisplayMetrics#densityDpi must be one of the DisplayMetrics.DENSITY_* values: " + allowedDensities, allowedDensities.contains(metrics.densityDpi)); assertEquals(metrics.density, (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT, 0.5f / DisplayMetrics.DENSITY_DEFAULT); } }
xdtianyu/android-4.3
cts/tests/tests/dpi/src/android/dpi/cts/ConfigurationTest.java
213,304
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.dpi.cts; import android.content.Context; import android.content.pm.PackageManager; import android.platform.test.annotations.Presubmit; import android.test.AndroidTestCase; import android.util.DisplayMetrics; import android.view.Display; import android.view.WindowManager; import com.android.compatibility.common.util.CddTest; import com.android.compatibility.common.util.FeatureUtil; import java.util.HashSet; import java.util.Set; /** * Test for verifying a device's screen configuration. */ public class ConfigurationTest extends AndroidTestCase { private DisplayMetrics mMetrics; @Override protected void setUp() throws Exception { super.setUp(); WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); Display display = windowManager.getDefaultDisplay(); mMetrics = new DisplayMetrics(); display.getRealMetrics(mMetrics); } @Presubmit public void testScreenConfiguration() { double xInches = (double) mMetrics.widthPixels / mMetrics.xdpi; double yInches = (double) mMetrics.heightPixels / mMetrics.ydpi; double diagonalInches = Math.sqrt(Math.pow(xInches, 2) + Math.pow(yInches, 2)); double minSize = 2.5d; if (FeatureUtil.isWatch()) { // Watches have a different minimum diagonal. minSize = 1.0d; } else if (FeatureUtil.isAutomotive()) { // Cars have a different minimum diagonal. minSize = 6.0d; } assertTrue("Screen diagonal must be at least " + minSize + " inches: " + diagonalInches, diagonalInches >= minSize); double density = 160.0d * mMetrics.density; assertTrue("Screen density must be at least 100 dpi: " + density, density >= 100.0d); Set<Integer> allowedDensities = new HashSet<Integer>(); allowedDensities.add(DisplayMetrics.DENSITY_LOW); allowedDensities.add(DisplayMetrics.DENSITY_140); allowedDensities.add(DisplayMetrics.DENSITY_MEDIUM); allowedDensities.add(DisplayMetrics.DENSITY_180); allowedDensities.add(DisplayMetrics.DENSITY_200); allowedDensities.add(DisplayMetrics.DENSITY_TV); allowedDensities.add(DisplayMetrics.DENSITY_220); allowedDensities.add(DisplayMetrics.DENSITY_HIGH); allowedDensities.add(DisplayMetrics.DENSITY_260); allowedDensities.add(DisplayMetrics.DENSITY_280); allowedDensities.add(DisplayMetrics.DENSITY_300); allowedDensities.add(DisplayMetrics.DENSITY_XHIGH); allowedDensities.add(DisplayMetrics.DENSITY_340); allowedDensities.add(DisplayMetrics.DENSITY_360); allowedDensities.add(DisplayMetrics.DENSITY_400); allowedDensities.add(DisplayMetrics.DENSITY_420); allowedDensities.add(DisplayMetrics.DENSITY_440); allowedDensities.add(DisplayMetrics.DENSITY_450); allowedDensities.add(DisplayMetrics.DENSITY_XXHIGH); allowedDensities.add(DisplayMetrics.DENSITY_560); allowedDensities.add(DisplayMetrics.DENSITY_600); allowedDensities.add(DisplayMetrics.DENSITY_XXXHIGH); assertTrue("DisplayMetrics.DENSITY_DEVICE_STABLE must be one of the DisplayMetrics.DENSITY_* values: " + allowedDensities, allowedDensities.contains(DisplayMetrics.DENSITY_DEVICE_STABLE)); assertEquals(mMetrics.density, (float) mMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT, 0.5f / DisplayMetrics.DENSITY_DEFAULT); } @CddTest(requirement="2.5.1") public void testAutomotiveMinimumScreenSize() { if (!FeatureUtil.isAutomotive()) { return; } float dpHeight = mMetrics.heightPixels / mMetrics.density; float dpWidth = mMetrics.widthPixels / mMetrics.density; assertTrue("Height must be >= 480dp, found: " + dpHeight, dpHeight >= 480); assertTrue("Width must be >= 750dp, found: " + dpWidth, dpWidth >= 750); } }
TeamWin/android_cts
tests/tests/dpi/src/android/dpi/cts/ConfigurationTest.java
213,305
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.dpi.cts; import android.content.Context; import android.test.AndroidTestCase; import android.util.DisplayMetrics; import android.view.Display; import android.view.WindowManager; import java.util.HashSet; import java.util.Set; /** * Test for verifying a device's screen configuration. */ public class ConfigurationTest extends AndroidTestCase { public void testScreenConfiguration() { WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); Display display = windowManager.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); double xInches = (double) metrics.widthPixels / metrics.xdpi; double yInches = (double) metrics.heightPixels / metrics.ydpi; double diagonalInches = Math.sqrt(Math.pow(xInches, 2) + Math.pow(yInches, 2)); assertTrue("Screen diagonal must be at least 2.5 inches: " + diagonalInches, diagonalInches >= 2.5d); double density = 160.0d * metrics.density; assertTrue("Screen density must be at least 100 dpi: " + density, density >= 100.0d); int max = Math.max(metrics.widthPixels, metrics.heightPixels); int min = Math.min(metrics.widthPixels, metrics.heightPixels); double aspectRatio = (double) max / min; assertTrue("Aspect ratio must be between 1.333 and 1.86. It was " + aspectRatio, aspectRatio >= 1.333 && aspectRatio <= 1.86); Set<Integer> allowedDensities = new HashSet<Integer>(); allowedDensities.add(DisplayMetrics.DENSITY_LOW); allowedDensities.add(DisplayMetrics.DENSITY_MEDIUM); allowedDensities.add(DisplayMetrics.DENSITY_TV); allowedDensities.add(DisplayMetrics.DENSITY_HIGH); allowedDensities.add(DisplayMetrics.DENSITY_XHIGH); assertTrue("DisplayMetrics#densityDpi must be one of the DisplayMetrics.DENSITY_* values: " + allowedDensities, allowedDensities.contains(metrics.densityDpi)); assertEquals(metrics.density, (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT, 0.5f / DisplayMetrics.DENSITY_DEFAULT); } }
zhxzhxustc/AFrame
ANDROID_SOURCE_CODE/cts/tests/tests/dpi/src/android/dpi/cts/ConfigurationTest.java
213,306
package net.athion.athionplots.Commands; import java.util.List; import net.athion.athionplots.AthionPlots; import net.athion.athionplots.Core.AthionCommands; import net.athion.athionplots.Core.AthionCore; import net.athion.athionplots.Core.AthionMaps; import net.athion.athionplots.Core.AthionPlot; import net.milkbowl.vault.economy.EconomyResponse; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.World; import org.bukkit.entity.Player; public class CommandBlock { public CommandBlock(final Player p, final String[] args) { if (AthionPlots.cPerms(p, "plotme.admin.block") || AthionPlots.cPerms(p, "plotme.use.block")) { if (!AthionCore.isPlotWorld(p)) { AthionCommands.SendMsg(p, ChatColor.RED + AthionCommands.C("MsgNotPlotWorld")); } else { final String id = AthionCore.getPlotID(p.getLocation()); if (id.equals("")) { AthionCommands.SendMsg(p, ChatColor.RED + AthionCommands.C("MsgNoPlotFound")); } else if (!AthionCore.isPlotAvailable(id, p)) { if ((args.length < 2) || args[1].equalsIgnoreCase("")) { AthionCommands.SendMsg(p, AthionCommands.C("WordUsage") + " " + ChatColor.RED + "/ap " + AthionCommands.C("CommandDeny") + " <" + AthionCommands.C("WordPlayer") + ">"); } else { final AthionPlot plot = AthionCore.getPlotById(p, id); final String playername = p.getName(); final String denied = args[1]; if (plot.owner.equalsIgnoreCase(playername) || AthionPlots.cPerms(p, "plotme.admin.block")) { if (plot.isDeniedConsulting(denied) || plot.isGroupDenied(denied)) { AthionCommands.SendMsg(p, AthionCommands.C("WordPlayer") + " " + ChatColor.RED + args[1] + ChatColor.RESET + " " + AthionCommands.C("MsgAlreadyDenied")); } else { final World w = p.getWorld(); final AthionMaps pmi = AthionCore.getMap(w); double price = 0; if (AthionCore.isEconomyEnabled(w)) { price = pmi.DenyPlayerPrice; final double balance = AthionPlots.economy.getBalance(p); if (balance >= price) { final EconomyResponse er = AthionPlots.economy.withdrawPlayer(p, price); if (!er.transactionSuccess()) { AthionCommands.SendMsg(p, ChatColor.RED + er.errorMessage); AthionCommands.warn(er.errorMessage); } } else { AthionCommands .SendMsg(p, ChatColor.RED + AthionCommands.C("MsgNotEnoughDeny") + " " + AthionCommands.C("WordMissing") + " " + ChatColor.RESET + AthionCommands.f(price - balance, false)); } } plot.addDenied(denied); plot.removeAllowed(denied); if (denied.equals("*")) { final List<Player> deniedplayers = AthionCore.getPlayersInPlot(w, id); for (final Player deniedplayer : deniedplayers) { if (!plot.isAllowed(deniedplayer.getUniqueId())) { deniedplayer.teleport(AthionCore.getPlotHome(w, plot)); } } } else { @SuppressWarnings("deprecation") final Player deniedplayer = Bukkit.getPlayerExact(denied); if (deniedplayer != null) { if (deniedplayer.getWorld().equals(w)) { final String deniedid = AthionCore.getPlotId(deniedplayer); if (deniedid.equalsIgnoreCase(id)) { deniedplayer.teleport(AthionCore.getPlotHome(w, plot)); } } } } AthionCommands.SendMsg(p, AthionCommands.C("WordPlayer") + " " + ChatColor.RED + denied + ChatColor.RESET + " " + AthionCommands.C("MsgNowDenied") + " " + AthionCommands.f(-price)); } } else { AthionCommands.SendMsg(p, ChatColor.RED + AthionCommands.C("MsgThisPlot") + "(" + id + ") " + AthionCommands.C("MsgNotYoursNotAllowedDeny")); } } } else { AthionCommands.SendMsg(p, ChatColor.RED + AthionCommands.C("MsgThisPlot") + "(" + id + ") " + AthionCommands.C("MsgHasNoOwner")); } } } else { AthionCommands.SendMsg(p, ChatColor.RED + AthionCommands.C("MsgPermissionDenied")); } } }
AthionOfficial/AthionPlots
src/main/java/net/athion/athionplots/Commands/CommandBlock.java
213,307
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.dpi.cts; import android.content.Context; import android.content.pm.PackageManager; import android.platform.test.annotations.Presubmit; import android.test.AndroidTestCase; import android.util.DisplayMetrics; import android.view.Display; import android.view.WindowManager; import com.android.compatibility.common.util.CddTest; import com.android.compatibility.common.util.FeatureUtil; import java.util.HashSet; import java.util.Set; /** * Test for verifying a device's screen configuration. */ public class ConfigurationTest extends AndroidTestCase { private DisplayMetrics mMetrics; @Override protected void setUp() throws Exception { super.setUp(); WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); Display display = windowManager.getDefaultDisplay(); mMetrics = new DisplayMetrics(); display.getMetrics(mMetrics); } @Presubmit public void testScreenConfiguration() { double xInches = (double) mMetrics.widthPixels / mMetrics.xdpi; double yInches = (double) mMetrics.heightPixels / mMetrics.ydpi; double diagonalInches = Math.sqrt(Math.pow(xInches, 2) + Math.pow(yInches, 2)); double minSize = 2.5d; if (FeatureUtil.isWatch()) { // Watches have a different minimum diagonal. minSize = 1.0d; } else if (FeatureUtil.isAutomotive()) { // Cars have a different minimum diagonal. minSize = 6.0d; } assertTrue("Screen diagonal must be at least " + minSize + " inches: " + diagonalInches, diagonalInches >= minSize); double density = 160.0d * mMetrics.density; assertTrue("Screen density must be at least 100 dpi: " + density, density >= 100.0d); Set<Integer> allowedDensities = new HashSet<Integer>(); allowedDensities.add(DisplayMetrics.DENSITY_LOW); allowedDensities.add(DisplayMetrics.DENSITY_140); allowedDensities.add(DisplayMetrics.DENSITY_MEDIUM); allowedDensities.add(DisplayMetrics.DENSITY_180); allowedDensities.add(DisplayMetrics.DENSITY_200); allowedDensities.add(DisplayMetrics.DENSITY_TV); allowedDensities.add(DisplayMetrics.DENSITY_220); allowedDensities.add(DisplayMetrics.DENSITY_HIGH); allowedDensities.add(DisplayMetrics.DENSITY_260); allowedDensities.add(DisplayMetrics.DENSITY_280); allowedDensities.add(DisplayMetrics.DENSITY_300); allowedDensities.add(DisplayMetrics.DENSITY_XHIGH); allowedDensities.add(DisplayMetrics.DENSITY_340); allowedDensities.add(DisplayMetrics.DENSITY_360); allowedDensities.add(DisplayMetrics.DENSITY_400); allowedDensities.add(DisplayMetrics.DENSITY_420); allowedDensities.add(DisplayMetrics.DENSITY_440); allowedDensities.add(DisplayMetrics.DENSITY_450); allowedDensities.add(DisplayMetrics.DENSITY_XXHIGH); allowedDensities.add(DisplayMetrics.DENSITY_560); allowedDensities.add(DisplayMetrics.DENSITY_600); allowedDensities.add(DisplayMetrics.DENSITY_XXXHIGH); assertTrue("DisplayMetrics.DENSITY_DEVICE_STABLE must be one of the DisplayMetrics.DENSITY_* values: " + allowedDensities, allowedDensities.contains(DisplayMetrics.DENSITY_DEVICE_STABLE)); assertEquals(mMetrics.density, (float) mMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT, 0.5f / DisplayMetrics.DENSITY_DEFAULT); } @CddTest(requirement="2.5.1") public void testAutomotiveMinimumScreenSize() { if (!FeatureUtil.isAutomotive()) { return; } float dpHeight = mMetrics.heightPixels / mMetrics.density; float dpWidth = mMetrics.widthPixels / mMetrics.density; assertTrue("Height must be >= 480dp, found: " + dpHeight, dpHeight >= 480); assertTrue("Width must be >= 750dp, found: " + dpWidth, dpWidth >= 750); } }
riscv-android-src/platform-cts
tests/tests/dpi/src/android/dpi/cts/ConfigurationTest.java
213,308
package edu.stanford.nlp.sempre.tables; import java.util.*; import edu.stanford.nlp.sempre.*; import fig.basic.*; import gnu.trove.map.hash.TObjectDoubleHashMap; /** * A DPParser parses utterances like a FloatingParser, * but the dynamic programming states are derivations instead of formulas. * * DPParser makes 2 passes: * - Pass 1: Find the set of denotations that lead to the correct value. * - Pass 2: Use regular beam search (from FloatingParser), but only restrict * the formulas to the ones found in Pass 1. * * @author ppasupat */ public class DPParser extends FloatingParser { public static class Options { @Option(gloss = "Use the targetValue at test time") public boolean cheat = false; @Option(gloss = "During training, combine the derivation list from FloatingParser") public boolean combineFromFloatingParser = false; @Option(gloss = "Random object for shuffling the derivation list") public Random shuffleRandom = new Random(1); @Option(gloss = "Custom maximum depth for DPParser (default = FloatingParser's maxDepth)") public int dpParserMaxDepth = -1; @Option(gloss = "Custom beam size for DPParser (default = FloatingParser's beamSize)") public int dpParserBeamSize = -1; @Option(gloss = "During the first pass, try add floating derivation to the cell with the lowest depth first") public boolean collapseFirstPass = false; @Option(gloss = "Use all pruners regardless of correctness") public boolean useAllPruners = false; } public static Options opts = new Options(); public DPParser(Spec spec) { super(spec); } @Override public ParserState newParserState(Params params, Example ex, boolean computeExpectedCounts) { // Test time (not cheated) --> use FloatingParser if (!computeExpectedCounts && !opts.cheat) return super.newParserState(params, ex, computeExpectedCounts); // Training time (regardless of cheating) --> use mixture if (computeExpectedCounts && opts.combineFromFloatingParser) return new DPParserState(this, params, ex, computeExpectedCounts, super.newParserState(params, ex, computeExpectedCounts)); // Cheated test OR training without mixture --> use DPParser return new DPParserState(this, params, ex, computeExpectedCounts); } } /** * Actual parsing logic. */ class DPParserState extends ParserState { private final DerivationPruner pruner; private final int maxDepth, beamSize; private final ParserState backoffParserState; public DPParserState(DPParser parser, Params params, Example ex, boolean computeExpectedCounts) { this(parser, params, ex, computeExpectedCounts, null); } public DPParserState(DPParser parser, Params params, Example ex, boolean computeExpectedCounts, ParserState backoff) { super(parser, params, ex, computeExpectedCounts); pruner = new DerivationPruner(this); maxDepth = DPParser.opts.dpParserMaxDepth > 0 ? DPParser.opts.dpParserMaxDepth : FloatingParser.opts.maxDepth; beamSize = DPParser.opts.dpParserBeamSize > 0 ? DPParser.opts.dpParserBeamSize : Parser.opts.beamSize; backoffParserState = backoff; } @Override protected int getBeamSize() { return beamSize; } protected void ensureExecuted(Derivation deriv) { deriv.ensureExecuted(parser.executor, ex.context); if (!deriv.isFeaturizedAndScored() && currentPass != ParsingPass.FIRST) featurizeAndScoreDerivation(deriv); } // ============================================================ // Dynamic programming cells // ============================================================ // Pass 1: Just try to reach the correct denotation // state name => denotation => FirstPassData private final Map<String, Map<Value, Metadata>> firstPassCells = new HashMap<>(); // Pass 2: Using results from Pass 1 to prune the possible formulas // state name => denotation => SecondPassData private final Map<String, Map<Value, Metadata>> secondPassCells = new HashMap<>(); enum ParsingPass { FIRST, SECOND, DONE }; ParsingPass currentPass = ParsingPass.FIRST; private Map<String, Map<Value, Metadata>> getCellsForCurrentPass() { return currentPass == ParsingPass.FIRST ? firstPassCells : secondPassCells; } // ============================================================ // DenotationIngredient // ============================================================ // Represents a possible method for creating a particular denotation. class DenotationIngredient { public final Rule rule; public final Value denotation1, denotation2; private int hashCode; public DenotationIngredient() { this.rule = null; this.denotation1 = null; this.denotation2 = null; computeHashCode(); } public DenotationIngredient(Rule rule, Derivation deriv1, Derivation deriv2) { this.rule = rule; if (deriv1 == null) { this.denotation1 = null; } else { ensureExecuted(deriv1); this.denotation1 = deriv1.value; } if (deriv2 == null) { this.denotation2 = null; } else { ensureExecuted(deriv1); this.denotation2 = deriv1.value; } computeHashCode(); } @Override public boolean equals(Object o) { if (!(o instanceof DenotationIngredient)) return false; DenotationIngredient that = (DenotationIngredient) o; if (rule != that.rule) return false; // Rules must be the same object if (denotation1 == null) { if (that.denotation1 != null) return false; } else { if (!denotation1.equals(that.denotation1)) return false; } if (denotation2 == null) { if (that.denotation2 != null) return false; } else { if (!denotation2.equals(that.denotation2)) return false; } return true; } private void computeHashCode() { hashCode = ((rule == null) ? 0 : rule.hashCode() * 1729) + ((denotation1 == null) ? 0 : denotation1.hashCode() * 42) + ((denotation2 == null) ? 0 : denotation2.hashCode()); } @Override public int hashCode() { return hashCode; } @Override public String toString() { return "[" + rule + " | " + denotation1 + " | " + denotation2 + "]"; } } private final Set<DenotationIngredient> allowedDenotationIngredients = new HashSet<>(); // ============================================================ // BackPointer // ============================================================ // Back pointers for dynamic programming. Points to previous cells. class BackPointer { public final String cell; public final Value denotation; public BackPointer(String cell, Value denotation) { this.cell = cell; this.denotation = denotation; } @Override public boolean equals(Object o) { if (!(o instanceof BackPointer)) return false; BackPointer that = (BackPointer) o; return cell.equals(that.cell) && denotation.equals(that.denotation); } @Override public int hashCode() { return cell.hashCode() * 100 + denotation.hashCode(); } @Override public String toString() { return cell + " " + denotation; } } public BackPointer getBackPointer(String cell, Derivation child) { if (cell == null || child == null) return null; ensureExecuted(child); return new BackPointer(cell, child.value); } // ============================================================ // Metadata // ============================================================ // Stores derivations and other data class Metadata { public final Value denotation; // List of possible methods to create this denotation public Set<DenotationIngredient> possibleIngredients = new HashSet<>(); // Backpointers for backtracking after the first pass public Set<BackPointer> backpointers = new HashSet<>(); // All derivations containing formulas that execute to the denotation. // For the FIRST pass, this has only 1 formula. // For the SECOND pass, this will eventually be pruned to the beam size. public List<Derivation> derivations = new ArrayList<>(); public Metadata(Value denotation) { this.denotation = denotation; } public void add(Derivation deriv, DenotationIngredient ingredient, BackPointer bp1, BackPointer bp2) { if (currentPass == ParsingPass.FIRST) { if (derivations.isEmpty()) { if (Parser.opts.verbose >= 3) LogInfo.logs("Metadata.add: %s %s", denotation, deriv); derivations.add(deriv); } if (Parser.opts.verbose >= 3) { LogInfo.logs("possibleIngredients.add: %s", ingredient); } possibleIngredients.add(ingredient); if (bp1 != null) backpointers.add(bp1); if (bp2 != null) backpointers.add(bp2); } else if (currentPass == ParsingPass.SECOND) { derivations.add(deriv); } } } // ============================================================ // Add to Chart // ============================================================ private void addToChart(String name, Derivation deriv, DenotationIngredient ingredient, BackPointer bp1, BackPointer bp2) { if (Parser.opts.verbose >= 3) LogInfo.logs("addToChart %s %s: %s", name, deriv.value, deriv); ensureExecuted(deriv); Map<String, Map<Value, Metadata>> cells = getCellsForCurrentPass(); Map<Value, Metadata> denotationToData = cells.get(name); if (denotationToData == null) cells.put(name, denotationToData = new HashMap<>()); Metadata metadata = denotationToData.get(deriv.value); if (metadata == null) denotationToData.put(deriv.value, metadata = new Metadata(deriv.value)); metadata.add(deriv, ingredient, bp1, bp2); } private String anchoredCell(String cat, int start, int end) { return cat + "[" + start + "," + end + "]"; } private String floatingCell(String cat, int depth) { return cat + ":" + depth; } private int getDepth(String cell) { String[] tokens = cell.split(":"); return tokens.length == 2 ? Integer.parseInt(tokens[1]) : 0; } // ============================================================ // Apply Rule // ============================================================ private void applyRule(Rule rule, int start, int end, int depth, String cell1, Derivation child1, String cell2, Derivation child2) { if (Parser.opts.verbose >= 5) LogInfo.logs("applyRule %s [%s:%s] depth=%s, %s %s", rule, start, end, depth, child1, child2); DenotationIngredient ingredient = new DenotationIngredient(rule, child1, child2); if (currentPass == ParsingPass.SECOND) { // Prune invalid ingredient if (!allowedDenotationIngredients.contains(ingredient)) return; } BackPointer bp1 = getBackPointer(cell1, child1), bp2 = getBackPointer(cell2, child2); List<Derivation> children; if (child1 == null) // 0-ary children = Collections.emptyList(); else if (child2 == null) // 1-ary children = Collections.singletonList(child1); else { children = ListUtils.newList(child1, child2); // optionally: ensure that specific anchors are only used once per final derivation // TODO(ice): can we impose useAnchorsOnce on the first pass without dropping correct derivations? if (FloatingParser.opts.useAnchorsOnce && currentPass != ParsingPass.FIRST && FloatingRuleUtils.derivationAnchorsOverlap(child1, child2)) return; } // Call the semantic function on the children and read the results DerivationStream results = rule.sem.call(ex, new SemanticFn.CallInfo(rule.lhs, start, end, rule, children)); while (results.hasNext()) { Derivation newDeriv = results.next(); if (pruner.isPruned(newDeriv)) continue; if (depth == -1) { // Anchored rule addToChart(anchoredCell(rule.lhs, start, end), newDeriv, ingredient, bp1, bp2); addToChart(floatingCell(rule.lhs, 0), newDeriv, ingredient, bp1, bp2); } else { // Floating rule if (DPParser.opts.collapseFirstPass && currentPass == ParsingPass.FIRST) { for (int lowerDepth = 0; lowerDepth <= depth; lowerDepth++) { Map<Value, Metadata> denotationToData = getCellsForCurrentPass().get(floatingCell(rule.lhs, lowerDepth)); if (lowerDepth == depth || (denotationToData != null && denotationToData.containsKey(newDeriv.value))) { addToChart(floatingCell(rule.lhs, lowerDepth), newDeriv, ingredient, bp1, bp2); break; } } } else { addToChart(floatingCell(rule.lhs, depth), newDeriv, ingredient, bp1, bp2); } } } } private void applyAnchoredRule(Rule rule, int start, int end) { applyRule(rule, start, end, -1, null, null, null, null); } private void applyAnchoredRule(Rule rule, int start, int end, String cell1, Derivation child1) { applyRule(rule, start, end, -1, cell1, child1, null, null); } private void applyAnchoredRule(Rule rule, int start, int end, String cell1, Derivation child1, String cell2, Derivation child2) { applyRule(rule, start, end, -1, cell1, child1, cell2, child2); } private void applyFloatingRule(Rule rule, int depth) { applyRule(rule, -1, -1, depth, null, null, null, null); } private void applyFloatingRule(Rule rule, int depth, String cell1, Derivation child1) { applyRule(rule, -1, -1, depth, cell1, child1, null, null); } private void applyFloatingRule(Rule rule, int depth, String cell1, Derivation child1, String cell2, Derivation child2) { applyRule(rule, -1, -1, depth, cell1, child1, cell2, child2); } // ============================================================ // Get rules and derivations // ============================================================ private List<Derivation> getDerivations(Object cell) { Map<String, Map<Value, Metadata>> cells = getCellsForCurrentPass(); Map<Value, Metadata> denotationToData = cells.get(cell); if (denotationToData == null) return Collections.emptyList(); List<Derivation> derivations = new ArrayList<>(); for (Metadata metadata : denotationToData.values()) { derivations.addAll(metadata.derivations); } return derivations; } // ============================================================ // Build Anchored // ============================================================ // Build derivations over span |start|, |end|. private void buildAnchored(int start, int end) { // Apply unary tokens on spans (rule $A (a)) for (Rule rule : parser.grammar.getRules()) { if (!rule.isAnchored()) continue; if (rule.rhs.size() != 1 || rule.isCatUnary()) continue; boolean match = (end - start == 1) && ex.token(start).equals(rule.rhs.get(0)); if (match) applyAnchoredRule(rule, start, end); } // Apply binaries on spans (rule $A ($B $C)), ... for (int mid = start + 1; mid < end; mid++) { for (Rule rule : parser.grammar.getRules()) { if (!rule.isAnchored()) continue; if (rule.rhs.size() != 2) continue; String rhs1 = rule.rhs.get(0); String rhs2 = rule.rhs.get(1); boolean match1 = (mid - start == 1) && ex.token(start).equals(rhs1); boolean match2 = (end - mid == 1) && ex.token(mid).equals(rhs2); if (!Rule.isCat(rhs1) && Rule.isCat(rhs2)) { // token $Cat if (match1) { String cell = anchoredCell(rhs2, mid, end); List<Derivation> derivations = getDerivations(cell); for (Derivation deriv : derivations) applyAnchoredRule(rule, start, end, cell, deriv); } } else if (Rule.isCat(rhs1) && !Rule.isCat(rhs2)) { // $Cat token if (match2) { String cell = anchoredCell(rhs1, start, mid); List<Derivation> derivations = getDerivations(cell); for (Derivation deriv : derivations) applyAnchoredRule(rule, start, end, cell, deriv); } } else if (!Rule.isCat(rhs1) && !Rule.isCat(rhs2)) { // token token if (match1 && match2) applyAnchoredRule(rule, start, end); } else { // $Cat $Cat String cell1 = anchoredCell(rhs1, start, mid); String cell2 = anchoredCell(rhs2, mid, end); List<Derivation> derivations1 = getDerivations(cell1); List<Derivation> derivations2 = getDerivations(cell2); for (Derivation deriv1 : derivations1) for (Derivation deriv2 : derivations2) applyAnchoredRule(rule, start, end, cell1, deriv1, cell2, deriv2); } } } // Apply unary categories on spans (rule $A ($B)) // Important: do this in topologically sorted order and after all the binaries are done. for (Rule rule : parser.getCatUnaryRules()) { if (!rule.isAnchored()) continue; String cell = anchoredCell(rule.rhs.get(0), start, end); List<Derivation> derivations = getDerivations(cell); for (Derivation deriv : derivations) { applyAnchoredRule(rule, start, end, cell, deriv); } } } // ============================================================ // Build Floating // ============================================================ // Build floating derivations of exactly depth |depth|. private void buildFloating(int depth) { // Apply unary tokens on spans (rule $A (a)) if (depth == 1) { for (Rule rule : parser.grammar.getRules()) { if (!rule.isFloating()) continue; if (rule.rhs.size() != 1 || rule.isCatUnary()) continue; applyFloatingRule(rule, depth); } } // Apply binaries on spans (rule $A ($B $C)), ... for (Rule rule : parser.grammar.getRules()) { if (!rule.isFloating()) continue; if (rule.rhs.size() != 2) continue; String rhs1 = rule.rhs.get(0); String rhs2 = rule.rhs.get(1); if (!Rule.isCat(rhs1) && !Rule.isCat(rhs2)) { // token token if (depth == 1) applyFloatingRule(rule, depth); } else if (!Rule.isCat(rhs1) && Rule.isCat(rhs2)) { // token $Cat String cell = floatingCell(rhs2, depth - 1); List<Derivation> derivations = getDerivations(cell); for (Derivation deriv : derivations) applyFloatingRule(rule, depth, cell, deriv); } else if (Rule.isCat(rhs1) && !Rule.isCat(rhs2)) { // $Cat token String cell = floatingCell(rhs1, depth - 1); List<Derivation> derivations = getDerivations(cell); for (Derivation deriv : derivations) applyFloatingRule(rule, depth, cell, deriv); } else { // $Cat $Cat if (FloatingParser.opts.useSizeInsteadOfDepth) { for (int depth1 = 0; depth1 < depth; depth1++) { int depth2 = depth - 1 - depth1; String cell1 = floatingCell(rhs1, depth1); String cell2 = floatingCell(rhs2, depth2); List<Derivation> derivations1 = getDerivations(cell1); List<Derivation> derivations2 = getDerivations(cell2); for (Derivation deriv1 : derivations1) for (Derivation deriv2 : derivations2) applyFloatingRule(rule, depth, cell1, deriv1, cell2, deriv2); } } else { for (int subDepth = 0; subDepth < depth; subDepth++) { // depth-1 <=depth-1 String cell1 = floatingCell(rhs1, depth - 1); String cell2 = floatingCell(rhs2, subDepth); List<Derivation> derivations1 = getDerivations(cell1); List<Derivation> derivations2 = getDerivations(cell2); for (Derivation deriv1 : derivations1) for (Derivation deriv2 : derivations2) applyFloatingRule(rule, depth, cell1, deriv1, cell2, deriv2); } for (int subDepth = 0; subDepth < depth - 1; subDepth++) { // <depth-1 depth-1 String cell1 = floatingCell(rhs1, subDepth); String cell2 = floatingCell(rhs2, depth - 1); List<Derivation> derivations1 = getDerivations(cell1); List<Derivation> derivations2 = getDerivations(cell2); for (Derivation deriv1 : derivations1) for (Derivation deriv2 : derivations2) applyFloatingRule(rule, depth, cell1, deriv1, cell2, deriv2); } } } } // Apply unary categories on spans (rule $A ($B)) // Important: do this in topologically sorted order and after all the binaries are done. for (Rule rule : parser.getCatUnaryRules()) { if (!rule.isFloating()) continue; String cell = floatingCell(rule.rhs.get(0), depth - 1); List<Derivation> derivations = getDerivations(cell); for (Derivation deriv : derivations) applyFloatingRule(rule, depth, cell, deriv); } } // ============================================================ // Infer (main entry) // ============================================================ @Override public void infer() { LogInfo.begin_track("DPParser.infer()"); // First pass LogInfo.begin_track("First pass"); StopWatchSet.begin("DPParser.firstPass"); currentPass = ParsingPass.FIRST; runParsingPass(); collectPossibleIngredients(); StopWatchSet.end(); LogInfo.end_track(); // Second pass LogInfo.begin_track("Second pass"); StopWatchSet.begin("DPParser.secondPass"); currentPass = ParsingPass.SECOND; runParsingPass(); StopWatchSet.end(); LogInfo.end_track(); // Compile StopWatchSet.begin("DPParser.final"); currentPass = ParsingPass.DONE; collectFinalDerivations(); ensureExecuted(); if (computeExpectedCounts) { expectedCounts = new TObjectDoubleHashMap<>(); ParserState.computeExpectedCounts(predDerivations, expectedCounts); } StopWatchSet.end(); LogInfo.end_track(); } private void runParsingPass() { Set<String> categories = new HashSet<>(); for (Rule rule : parser.grammar.getRules()) categories.add(rule.lhs); // Set the pruner if (currentPass == ParsingPass.FIRST && !DPParser.opts.useAllPruners) pruner.setCustomAllowedDomains(Arrays.asList( "emptyDenotation", "nonLambdaError", "badSuperlativeHead", "sameMerge", "mistypedMerge")); else pruner.setCustomAllowedDomains(null); // Base case ($TOKEN, $PHRASE, $LEMMA_PHRASE) // Denotations are StringValue for (Derivation deriv : gatherTokenAndPhraseDerivations()) { ensureExecuted(deriv); addToChart(anchoredCell(deriv.cat, deriv.start, deriv.end), deriv, new DenotationIngredient(), null, null); } // Build up anchored derivations int numTokens = ex.numTokens(); for (int len = 1; len <= numTokens; len++) { for (int i = 0; i + len <= numTokens; i++) { buildAnchored(i, i + len); for (String cat : categories) { pruneBeam(anchoredCell(cat, i, i + len)); } } } // Build up floating derivations for (int depth = 1; depth <= maxDepth; depth++) { buildFloating(depth); for (String cat : categories) { pruneBeam(floatingCell(cat, depth)); } } } // Prune to the beam size during Pass 2 private void pruneBeam(String cell) { if (currentPass == ParsingPass.SECOND) { Map<String, Map<Value, Metadata>> cells = getCellsForCurrentPass(); Map<Value, Metadata> denotationToData = cells.get(cell); if (denotationToData == null) return; for (Metadata metadata : denotationToData.values()) { pruneCell(cell, metadata.derivations); } } } private void collectPossibleIngredients() { if (Parser.opts.verbose >= 4) LogInfo.logs("DPParserState.collectPossibleIngredients()"); Set<BackPointer> usedBps = new HashSet<>(); collectPossibleIngredients(anchoredCell(Rule.rootCat, 0, numTokens), usedBps); for (int depth = 1; depth <= maxDepth; depth++) collectPossibleIngredients(floatingCell(Rule.rootCat, depth), usedBps); if (Parser.opts.verbose >= 5) { for (DenotationIngredient ingredient : allowedDenotationIngredients) LogInfo.logs("%s", ingredient); } } private void collectPossibleIngredients(String cell, Set<BackPointer> usedBps) { if (Parser.opts.verbose >= 4) LogInfo.logs("DPParserState.collectPossibleIngredients(%s)", cell); Map<Value, Metadata> denotationToMetadata = firstPassCells.get(cell); if (denotationToMetadata == null) return; for (Value denotation : denotationToMetadata.keySet()) { double compatibility = parser.valueEvaluator.getCompatibility(ex.targetValue, denotation); if (Parser.opts.verbose >= 2) LogInfo.logs("[%f] %s", compatibility, denotationToMetadata.get(denotation).derivations.get(0)); if (compatibility != 1) continue; BackPointer bp = new BackPointer(cell, denotation); if (!usedBps.contains(bp)) collectPossibleIngredients(bp, usedBps, 0); } } private void collectPossibleIngredients(BackPointer bp, Set<BackPointer> usedBps, int depth) { if (Parser.opts.verbose >= 4) LogInfo.logs("DPParserState.collectPossibleIngredients(%s)", bp); if (DPParser.opts.collapseFirstPass && depth + getDepth(bp.cell) > maxDepth) { if (Parser.opts.verbose >= 2) LogInfo.logs("Too deep: [%d] [%d] [%d] %s", depth, getDepth(bp.cell), maxDepth, bp.cell); return; } usedBps.add(bp); Map<Value, Metadata> denotationToMetadata = firstPassCells.get(bp.cell); if (denotationToMetadata == null) return; Metadata metadata = denotationToMetadata.get(bp.denotation); if (metadata == null) return; allowedDenotationIngredients.addAll(metadata.possibleIngredients); // Recurse for (BackPointer childBp : metadata.backpointers) { if (!usedBps.contains(childBp)) collectPossibleIngredients(childBp, usedBps, depth + 1); } } // Collect final predicted derivations private void collectFinalDerivations() { predDerivations.addAll(getDerivations(anchoredCell(Rule.rootCat, 0, numTokens))); for (int depth = 1; depth <= maxDepth; depth++) predDerivations.addAll(getDerivations(floatingCell(Rule.rootCat, depth))); if (backoffParserState != null) { // Also combine derivations from the backoff parser state LogInfo.begin_track("Backoff ParserState"); backoffParserState.infer(); predDerivations.addAll(backoffParserState.predDerivations); // Prevent oracles from always being at the front. Collections.shuffle(predDerivations, DPParser.opts.shuffleRandom); LogInfo.end_track(); } } // Collect the statistics and put them into the Evaluation object @Override protected void setEvaluation() { super.setEvaluation(); // Number of cells countNumCells(firstPassCells, "firstPass"); countNumCells(secondPassCells, "secondPass"); // Number of possible ingredients evaluation.add("allowedIngredients", allowedDenotationIngredients.size()); } private void countNumCells(Map<String, Map<Value, Metadata>> cells, String prefix) { int numAnchored = 0, numFloating = 0, numDenotations = 0, numErrorDenotations = 0, numUniqueErrorDenotations = 0, numDerivations = 0; Set<Value> uniqueDenotations = new HashSet<>(); for (Map.Entry<String, Map<Value, Metadata>> entry : cells.entrySet()) { if (entry.getKey().contains(",")) numAnchored++; else numFloating++; for (Map.Entry<Value, Metadata> subentry : entry.getValue().entrySet()) { Value denotation = subentry.getKey(); numDenotations++; uniqueDenotations.add(denotation); if (denotation instanceof ErrorValue) numErrorDenotations++; numDerivations += subentry.getValue().derivations.size(); } } for (Value denotation : uniqueDenotations) { if (denotation instanceof ErrorValue) numUniqueErrorDenotations++; } evaluation.add(prefix + "Cells", cells.size()); evaluation.add(prefix + "Anchored", numAnchored); evaluation.add(prefix + "Floating", numFloating); evaluation.add(prefix + "CellDenotations", numDenotations); evaluation.add(prefix + "ErrorDenotations", numErrorDenotations); evaluation.add(prefix + "UniqueDenotations", uniqueDenotations.size()); evaluation.add(prefix + "UniqueErrorDenotations", numUniqueErrorDenotations); evaluation.add(prefix + "Derivations", numDerivations); } }
stanford-oval/sempre
src/edu/stanford/nlp/sempre/tables/DPParser.java
213,309
package net.athion.athionplots; /** * AthionPlots * Author: Travis506 @ PlotMe by ZachBora * Source: Used Code by ZachBora @ PlotMe * Description: AthionPlots was intended to be a replica, exactly, of PlotMe, with modifications, changes and other features added. These features were * provided by Travis506, for a paid-project or paid-for-services project. This plugin was never sold, nor shall be distributed, and will remain private use. */ import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Calendar; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map.Entry; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; import net.athion.athionplots.Core.AthionCommands; import net.athion.athionplots.Core.AthionCore; import net.athion.athionplots.Core.AthionGen; import net.athion.athionplots.Core.AthionMaps; import net.athion.athionplots.Core.AthionSQL; import net.athion.athionplots.Listeners.AthionListenerBlock; import net.athion.athionplots.Listeners.AthionListenerMain; import net.athion.athionplots.Listeners.AthionListenerWE; import net.athion.athionplots.WorldEdit.AthionWorldEdit; import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.generator.ChunkGenerator; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.yaml.snakeyaml.Yaml; import com.sk89q.worldedit.bukkit.WorldEditPlugin; public class AthionPlots extends JavaPlugin { public static Logger logger = null; public static String NAME; public static String PREFIX; public static Boolean usemySQL; public static String mySQLuname; public static String mySQLpass; public static String mySQLconn; public static String configpath; public static Boolean globalUseEconomy; public static Boolean advancedlogging; public static String language; public static Boolean allowWorldTeleport; public static Boolean autoUpdate; public static Boolean allowToBlock; public static Boolean allowToMerge; public static Boolean allowToSchematic; public static AthionPlots self = null; public static WorldEditPlugin worldeditplugin = null; public static AthionWorldEdit athionworldedit = null; public static Economy economy = null; public static Boolean usinglwc = false; public static ConcurrentHashMap<String, AthionMaps> AthionMaps = null; public static World worldcurrentlyprocessingexpired; public static CommandSender cscurrentlyprocessingexpired; public static Integer counterexpired; public static Integer nbperdeletionprocessingexpired; public static Boolean defaultWEAnywhere; private static HashSet<String> playersignoringwelimit = null; private static HashMap<String, String> captions; public Boolean initialized = false; PluginManager pm; public static void initialize() { updateWorldYml("bukkit.yml"); updateWorldYml("plugins/Multiverse-Core/worlds.yml"); final PluginDescriptionFile pdfFile = self.getDescription(); NAME = pdfFile.getName(); PREFIX = ChatColor.DARK_PURPLE + "[" + ChatColor.BOLD + NAME + ChatColor.RESET + ChatColor.DARK_PURPLE + "] " + ChatColor.RESET; configpath = self.getDataFolder().getAbsolutePath(); playersignoringwelimit = new HashSet<>(); if (!self.getDataFolder().exists()) { self.getDataFolder().mkdirs(); } final File configfile = new File(configpath, "config.yml"); final FileConfiguration config = new YamlConfiguration(); try { config.load(configfile); } catch (final FileNotFoundException e) {} catch (final IOException e) { logger.severe("Can't read the Configuration File."); e.printStackTrace(); } catch (final InvalidConfigurationException e) { logger.severe("Invalid Configuration Format."); e.printStackTrace(); } config.set("version", self.getDescription().getVersion()); usemySQL = config.getBoolean("usemySQL", false); mySQLconn = config.getString("mySQLconn", "jdbc:mysql://localhost:3306/minecraft"); mySQLuname = config.getString("mySQLuname", "root"); mySQLpass = config.getString("mySQLpass", "password"); globalUseEconomy = config.getBoolean("globalUseEconomy", false); advancedlogging = config.getBoolean("AdvancedLogging", false); language = config.getString("Language", "english"); allowWorldTeleport = config.getBoolean("allowWorldTeleport", true); defaultWEAnywhere = config.getBoolean("defaultWEAnywhere", false); autoUpdate = config.getBoolean("auto-update", false); allowToBlock = config.getBoolean("allowToBlock", true); allowToMerge = config.getBoolean("allowToMerge", true); allowToSchematic = config.getBoolean("allowToSchematic", true); ConfigurationSection worlds; if (!config.contains("worlds")) { worlds = config.createSection("worlds"); final ConfigurationSection apworld = worlds.createSection("plotworld"); // Default AP World Configuration Settings // Plot Settings apworld.set("AutoLimit", 100); apworld.set("PathWidth", 7); apworld.set("PlotSize", 32); // Generation Settings apworld.set("BottomBlockID", "7"); apworld.set("WallBlockID", "44"); apworld.set("PlotFloorBLockID", "2"); apworld.set("PlotFillBlockID", "3"); apworld.set("RoadMainBlockID", "5"); apworld.set("RoadStripeBlockID", "5:2"); // AthionPlots World Settings apworld.set("RoadHeight", 64); apworld.set("DaysToExpiration", 7); apworld.set("ProtectedBlocks", ""); apworld.set("PreventedItems", ""); apworld.set("ProtectedWallBlockID", "44:4"); apworld.set("ForSaleWallBlockID", "44:1"); apworld.set("AuctionWallBlockID", "44:1"); apworld.set("AutoLinkPlots", true); apworld.set("DisableExplosion", true); apworld.set("DisableIgnition", true); final ConfigurationSection economysection = apworld.createSection("economy"); economysection.set("UseEconomy", false); economysection.set("CanPutOnSale", false); economysection.set("CanSellToBank", false); economysection.set("RefundClaimPriceOnReset", false); economysection.set("RefundClaimPriceOnSetOwner", false); economysection.set("ClaimPrice", 0); economysection.set("ClearPrice", 0); economysection.set("AddPlayerPrice", 0); economysection.set("DenyPlayerPrice", 0); economysection.set("RemovePlayerPrice", 0); economysection.set("UndenyPlayerPrice", 0); economysection.set("PlotHomePrice", 0); economysection.set("CanCustomizeSellPrice", false); economysection.set("SellToPlayerPrice", 0); economysection.set("SellToBankPrice", 0); economysection.set("BuyFromBankPrice", 0); economysection.set("AddCommentPrice", 0); economysection.set("BiomeChangePrice", 0); economysection.set("ProtectPrice", 0); economysection.set("DisposePrice", 0); apworld.set("economy", economysection); worlds.set("apworld", apworld); config.set("worlds", worlds); } else { worlds = config.getConfigurationSection("worlds"); } AthionMaps = new ConcurrentHashMap<String, AthionMaps>(); for (final String worldname : worlds.getKeys(false)) { final AthionMaps AthionPlotInfo = new AthionMaps(); final ConfigurationSection CurrentWorld = worlds.getConfigurationSection(worldname); AthionPlotInfo.PlotAutoLimit = CurrentWorld.getInt("PlotAutoLimit", 100); AthionPlotInfo.PathWidth = CurrentWorld.getInt("PathWidth", 7); AthionPlotInfo.PlotSize = CurrentWorld.getInt("PlotSize", 32); AthionPlotInfo.BottomBlockId = self.getBlockId(CurrentWorld, "BottomBlockId", "7:0"); AthionPlotInfo.BottomBlockValue = self.getBlockValue(CurrentWorld, "BottomBlockId", "7:0"); AthionPlotInfo.WallBlockId = self.getBlockId(CurrentWorld, "WallBlockId", "44:0"); AthionPlotInfo.WallBlockValue = self.getBlockValue(CurrentWorld, "WallBlockId", "44:0"); AthionPlotInfo.PlotFloorBlockId = self.getBlockId(CurrentWorld, "PlotFloorBlockId", "2:0"); AthionPlotInfo.PlotFloorBlockValue = self.getBlockValue(CurrentWorld, "PlotFloorBlockId", "2:0"); AthionPlotInfo.PlotFillingBlockId = self.getBlockId(CurrentWorld, "PlotFillingBlockId", "3:0"); AthionPlotInfo.PlotFillingBlockValue = self.getBlockValue(CurrentWorld, "PlotFillingBlockId", "3:0"); AthionPlotInfo.RoadMainBlockId = self.getBlockId(CurrentWorld, "RoadMainBlockId", "5:0"); AthionPlotInfo.RoadMainBlockValue = self.getBlockValue(CurrentWorld, "RoadMainBlockId", "5:0"); AthionPlotInfo.RoadStripeBlockId = self.getBlockId(CurrentWorld, "RoadStripeBlockId", "5:2"); AthionPlotInfo.RoadStripeBlockValue = self.getBlockValue(CurrentWorld, "RoadStripeBlockId", "5:2"); AthionPlotInfo.RoadHeight = CurrentWorld.getInt("RoadHeight", CurrentWorld.getInt("WorldHeight", 64)); if (AthionPlotInfo.RoadHeight > 250) { logger.severe("RoadHeight above 250 is unsafe. This is the height at which your road is located. Setting it to 64."); AthionPlotInfo.RoadHeight = 64; } AthionPlotInfo.DaysToExpiration = CurrentWorld.getInt("DaysToExpiration", 7); if (CurrentWorld.contains("ProtectedBlocks")) { AthionPlotInfo.ProtectedBlocks = CurrentWorld.getIntegerList("ProtectedBlocks"); } else { //tempPlotInfo.ProtectedBlocks = getDefaultProtectedBlocks(); } if (CurrentWorld.contains("PreventedItems")) { AthionPlotInfo.PreventedItems = CurrentWorld.getStringList("PreventedItems"); } else { //tempPlotInfo.PreventedItems = getDefaultPreventedItems(); } AthionPlotInfo.ProtectedWallBlockId = CurrentWorld.getString("ProtectedWallBlockId", "44:4"); AthionPlotInfo.ForSaleWallBlockId = CurrentWorld.getString("ForSaleWallBlockId", "44:1"); AthionPlotInfo.AuctionWallBlockId = CurrentWorld.getString("AuctionWallBlockId", "44:1"); AthionPlotInfo.AutoLinkPlots = CurrentWorld.getBoolean("AutoLinkPlots", true); AthionPlotInfo.DisableExplosion = CurrentWorld.getBoolean("DisableExplosion", true); AthionPlotInfo.DisableIgnition = CurrentWorld.getBoolean("DisableIgnition", true); CurrentWorld.set("PlotAutoLimit", AthionPlotInfo.PlotAutoLimit); CurrentWorld.set("PathWidth", AthionPlotInfo.PathWidth); CurrentWorld.set("PlotSize", AthionPlotInfo.PlotSize); CurrentWorld.set("BottomBlockId", self.getBlockValueId(AthionPlotInfo.BottomBlockId, AthionPlotInfo.BottomBlockValue)); CurrentWorld.set("WallBlockId", self.getBlockValueId(AthionPlotInfo.WallBlockId, AthionPlotInfo.WallBlockValue)); CurrentWorld.set("PlotFloorBlockId", self.getBlockValueId(AthionPlotInfo.PlotFloorBlockId, AthionPlotInfo.PlotFloorBlockValue)); CurrentWorld.set("PlotFillingBlockId", self.getBlockValueId(AthionPlotInfo.PlotFillingBlockId, AthionPlotInfo.PlotFillingBlockValue)); CurrentWorld.set("RoadMainBlockId", self.getBlockValueId(AthionPlotInfo.RoadMainBlockId, AthionPlotInfo.RoadMainBlockValue)); CurrentWorld.set("RoadStripeBlockId", self.getBlockValueId(AthionPlotInfo.RoadStripeBlockId, AthionPlotInfo.RoadStripeBlockValue)); CurrentWorld.set("RoadHeight", AthionPlotInfo.RoadHeight); CurrentWorld.set("WorldHeight", null); CurrentWorld.set("DaysToExpiration", AthionPlotInfo.DaysToExpiration); CurrentWorld.set("ProtectedBlocks", AthionPlotInfo.ProtectedBlocks); CurrentWorld.set("PreventedItems", AthionPlotInfo.PreventedItems); CurrentWorld.set("ProtectedWallBlockId", AthionPlotInfo.ProtectedWallBlockId); CurrentWorld.set("ForSaleWallBlockId", AthionPlotInfo.ForSaleWallBlockId); CurrentWorld.set("AuctionWallBlockId", AthionPlotInfo.AuctionWallBlockId); CurrentWorld.set("AutoLinkPlots", AthionPlotInfo.AutoLinkPlots); CurrentWorld.set("DisableExplosion", AthionPlotInfo.DisableExplosion); CurrentWorld.set("DisableIgnition", AthionPlotInfo.DisableIgnition); worlds.set(worldname, CurrentWorld); AthionPlotInfo.plots = AthionSQL.getPlots(worldname.toLowerCase()); AthionMaps.put(worldname.toLowerCase(), AthionPlotInfo); logger.info("World: " + worldname.toLowerCase() + " addedd!"); logger.info("Worlds Enabled: " + AthionMaps.toString()); } config.set("usemySQL", usemySQL); config.set("mySQLconn", mySQLconn); config.set("mySQLuname", mySQLuname); config.set("mySQLpass", mySQLpass); config.set("globalUseEconomy", globalUseEconomy); config.set("AdvancedLogging", advancedlogging); config.set("Language", language); config.set("allowWorldTeleport", allowWorldTeleport); config.set("defaultWEAnywhere", defaultWEAnywhere); config.set("auto-update", autoUpdate); config.set("allowToBlock", allowToBlock); config.set("allowToMerge", allowToMerge); config.set("allowToSchematic", allowToSchematic); try { config.save(configfile); } catch (final IOException e) { logger.severe("Configuration Could Not Be Written."); } self.loadCaptions(); } public static void updateWorldYml(final String location) { try { final Path path = Paths.get(location); final File file = new File(location); if (!file.exists()) { return; } final Charset charset = StandardCharsets.UTF_8; String content = new String(Files.readAllBytes(path), charset); content = content.replaceAll("PlotMe-DefaultGenerator", "PlotMe"); Files.write(path, content.getBytes(charset)); } catch (final Exception e) {} } public static int getPlotLimit(final Player p) { int max = -2; final int maxlimit = 5; if (p.hasPermission("plotme.limit.*")) { return -1; } else { for (int ctr = 0; ctr < maxlimit; ctr++) { if (p.hasPermission("plotme.limit." + ctr)) { max = ctr; } } } if (max == -2) { if (cPerms(p, "plotme.admin")) { return -1; } else if (cPerms(p, "plotme.use")) { return 1; } else { return 0; } } return max; } public static String getDate() { return getDate(Calendar.getInstance()); } private static String getDate(final Calendar cal) { final int imonth = cal.get(Calendar.MONTH) + 1; final int iday = cal.get(Calendar.DAY_OF_MONTH) + 1; String month = ""; String day = ""; if (imonth < 10) { month = "0" + imonth; } else { month = "" + imonth; } if (iday < 10) { day = "0" + iday; } else { day = "" + iday; } return "" + cal.get(Calendar.YEAR) + "-" + month + "-" + day; } public static String getDate(final java.sql.Date expireddate) { return expireddate.toString(); } public static boolean isIgnoringWELimit(final Player p) { if (defaultWEAnywhere && cPerms(p, "plotme.admin.weanywhere")) { return !playersignoringwelimit.contains(p.getName()); } else { return playersignoringwelimit.contains(p.getName()); } } public static void addIgnoreWELimit(final Player p) { if (!playersignoringwelimit.contains(p.getName())) { playersignoringwelimit.add(p.getName()); if (worldeditplugin != null) { AthionPlots.athionworldedit.removeMask(p); } } } public static void removeIgnoreWELimit(final Player p) { if (playersignoringwelimit.contains(p.getName())) { playersignoringwelimit.remove(p.getName()); if (worldeditplugin != null) { AthionPlots.athionworldedit.setMask(p); } } } public static String caption(final String s) { if (captions.containsKey(s)) { return addColor(captions.get(s)); } else { logger.warning("Missing caption: " + s); return "ERROR:Missing caption '" + s + "'"; } } public static String addColor(final String string) { return ChatColor.translateAlternateColorCodes('&', string); } public static boolean cPerms(final CommandSender sender, final String node) { return sender.hasPermission(node); } @Override public void onEnable() { self = this; logger = getLogger(); initialize(); final PluginManager pm = getServer().getPluginManager(); pm.registerEvents(new AthionListenerMain(), this); if (pm.getPlugin("WorldEdit") != null) { worldeditplugin = (WorldEditPlugin) pm.getPlugin("WorldEdit"); try { Class.forName("com.sk89q.worldedit.function.mask.Mask"); AthionPlots.athionworldedit = (AthionWorldEdit) Class.forName("net.athion.athionplots.WorldEdit.AthionWorldEdit6_0_0").getConstructor().newInstance(); } catch (final Exception e) { try { AthionPlots.athionworldedit = (AthionWorldEdit) Class.forName("net.athion.athionplots.WorldEdit.AthionWorldEdit5_7").getConstructor().newInstance(); } catch (final Exception e2) { logger.warning("Unable to hook to WorldEdit properly, please contact the developper of AthionPlots with your WorldEdit version."); AthionPlots.athionworldedit = null; } } pm.registerEvents(new AthionListenerWE(), this); } if (allowToBlock) { pm.registerEvents(new AthionListenerBlock(), this); } final AthionCommands command = new AthionCommands(this); getCommand("ap").setExecutor(command); getCommand("plotme").setExecutor(command); getCommand("plots").setExecutor(command); getCommand("plot").setExecutor(command); initialized = true; AthionSQL.plotConvertToUUIDAsynchronously(); } @Override public void onDisable() { AthionSQL.closeConnection(); NAME = null; PREFIX = null; logger = null; usemySQL = null; mySQLuname = null; mySQLpass = null; mySQLconn = null; globalUseEconomy = null; advancedlogging = null; language = null; allowWorldTeleport = null; autoUpdate = null; AthionMaps = null; configpath = null; worldeditplugin = null; economy = null; usinglwc = null; playersignoringwelimit = null; captions = null; worldcurrentlyprocessingexpired = null; cscurrentlyprocessingexpired = null; counterexpired = null; nbperdeletionprocessingexpired = null; defaultWEAnywhere = null; self = null; allowToBlock = null; allowToMerge = null; allowToSchematic = null; initialized = null; } private void loadCaptions() { File filelang = new File(getDataFolder(), "plotme-english.yml"); final TreeMap<String, String> properties = new TreeMap<String, String>(); properties.put("MsgStartDeleteSession", "Starting to delete."); properties.put("MsgDeletedExpiredPlots", "The expired plot has been deleted."); properties.put("MsgDeleteSessionFinished", "Delete was succesful. Run again to delete more."); properties.put("MsgAlreadyProcessingPlots", "this is already being deleted."); properties.put("MsgDoesNotExistOrNotLoaded", "does not exist or is not loaded."); properties.put("MsgNotPlotWorld", "Hey, you're not in an AthionPlots world."); properties.put("MsgPermissionDenied", "Sorry, you don't have permission to do that."); properties.put("MsgNoPlotFound", "No Plots."); properties.put("MsgCannotBidOwnPlot", "You cannot bid on your own plot."); properties.put("MsgCannotBuyOwnPlot", "You cannot buy your own plot."); properties.put("MsgCannotClaimRoad", "You cannot claim the road."); properties.put("MsgInvalidBidMustBeAbove", "Invalid bid. Must be above"); properties.put("MsgOutbidOnPlot", "Outbid on plot"); properties.put("MsgOwnedBy", "plot owned by"); properties.put("MsgBidAccepted", "Bid accepted."); properties.put("MsgPlotNotAuctionned", "This plot isn't being auctionned."); properties.put("MsgThisPlot", "This plot"); properties.put("MsgThisPlotYours", "This plot is now yours."); properties.put("MsgThisPlotIsNow", "This plot is now "); properties.put("MsgThisPlotOwned", "This plot is already owned."); properties.put("MsgHasNoOwner", "has no owners."); properties.put("MsgEconomyDisabledWorld", "Economy is disabled for this world."); properties.put("MsgPlotNotForSale", "Plot isn't for sale."); properties.put("MsgAlreadyReachedMaxPlots", "You have already reached your maximum amount of plots"); properties.put("MsgToGetToIt", "to get to it"); properties.put("MsgNotEnoughBid", "You do not have enough to bid this much."); properties.put("MsgNotEnoughBuy", "You do not have enough to buy this plot."); properties.put("MsgNotEnoughAuto", "You do not have enough to buy a plot."); properties.put("MsgNotEnoughComment", "You do not have enough to comment on a plot."); properties.put("MsgNotEnoughBiome", "You do not have enough to change the biome."); properties.put("MsgNotEnoughClear", "You do not have enough to clear the plot."); properties.put("MsgNotEnoughDispose", "You do not have enough to dispose of this plot."); properties.put("MsgNotEnoughProtectPlot", "You do not have enough to protect this plot."); properties.put("MsgNotEnoughTp", "You do not have enough to teleport home."); properties.put("MsgNotEnoughAdd", "You do not have enough to add a player."); properties.put("MsgNotEnoughDeny", "You do not have enough to deny a player."); properties.put("MsgNotEnoughRemove", "You do not have enough to remove a player."); properties.put("MsgNotEnoughUndeny", "You do not have enough to undeny a player."); properties.put("MsgSoldTo", "sold to"); properties.put("MsgPlotBought", "Plot bought."); properties.put("MsgBoughtPlot", "bought plot"); properties.put("MsgClaimedPlot", "claimed plot"); properties.put("MsgPlotHasBidsAskAdmin", "Plot is being auctionned and has bids. Ask an admin to cancel it."); properties.put("MsgAuctionCancelledOnPlot", "Auction cancelled on plot"); properties.put("MsgAuctionCancelled", "Auction cancelled."); properties.put("MsgStoppedTheAuctionOnPlot", "stopped the auction on plot"); properties.put("MsgInvalidAmount", "Invalid amount. Must be above or equal to 0."); properties.put("MsgAuctionStarted", "Auction started."); properties.put("MsgStartedAuctionOnPlot", "started an auction on plot"); properties.put("MsgDoNotOwnPlot", "You do not own this plot."); properties.put("MsgSellingPlotsIsDisabledWorld", "Selling plots is disabled in this world."); properties.put("MsgPlotProtectedNotDisposed", "Plot is protected and cannot be disposed."); properties.put("MsgWasDisposed", "was disposed."); properties.put("MsgPlotDisposedAnyoneClaim", "Plot disposed. Anyone can claim it."); properties.put("MsgDisposedPlot", "disposed of plot"); properties.put("MsgNotYoursCannotDispose", "is not yours. You are not allowed to dispose it."); properties.put("MsgPlotNoLongerSale", "Plot no longer for sale."); properties.put("MsgRemovedPlot", "removed the plot"); properties.put("MsgFromBeingSold", "from being sold"); properties.put("MsgCannotCustomPriceDefault", "You cannot customize the price. Default price is :"); properties.put("MsgCannotSellToBank", "Plots cannot be sold to the bank in this world."); properties.put("MsgSoldToBank", "sold to bank."); properties.put("MsgPlotSold", "Plot sold."); properties.put("MsgSoldToBankPlot", "sold to bank plot"); properties.put("MsgPlotForSale", "Plot now for sale."); properties.put("MsgPutOnSalePlot", "put on sale plot"); properties.put("MsgPlotNoLongerProtected", "Plot is no longer protected. It is now possible to Clear or Reset it."); properties.put("MsgUnprotectedPlot", "unprotected plot"); properties.put("MsgPlotNowProtected", "Plot is now protected. It won't be possible to Clear or Reset it."); properties.put("MsgProtectedPlot", "protected plot"); properties.put("MsgNoPlotsFinished", "No plots are finished"); properties.put("MsgFinishedPlotsPage", "Finished plots page"); properties.put("MsgUnmarkFinished", "Plot is no longer marked finished."); properties.put("MsgMarkFinished", "Plot is now marked finished."); properties.put("MsgPlotExpirationReset", "Plot expiration reset"); properties.put("MsgNoPlotExpired", "No plots are expired"); properties.put("MsgExpiredPlotsPage", "Expired plots page"); properties.put("MsgListOfPlotsWhere", "List of plots where"); properties.put("MsgCanBuild", "can build:"); properties.put("MsgListOfPlotsWhereYou", "List of plots where you can build:"); properties.put("MsgWorldEditInYourPlots", "You can now only WorldEdit in your plots"); properties.put("MsgWorldEditAnywhere", "You can now WorldEdit anywhere"); properties.put("MsgNoPlotFound1", "No plot found within"); properties.put("MsgNoPlotFound2", "plots. Contact an admin."); properties.put("MsgDoesNotHavePlot", "does not have a plot"); properties.put("MsgPlotNotFound", "Could not find plot"); properties.put("MsgYouHaveNoPlot", "You don't have a plot."); properties.put("MsgCommentAdded", "Comment added."); properties.put("MsgCommentedPlot", "commented on plot"); properties.put("MsgNoComments", "No comments"); properties.put("MsgYouHave", "You have"); properties.put("MsgComments", "comments."); properties.put("MsgNotYoursNotAllowedViewComments", "is not yours. You are not allowed to view the comments."); properties.put("MsgIsInvalidBiome", "is not a valid biome."); properties.put("MsgBiomeSet", "Biome set to"); properties.put("MsgChangedBiome", "changed the biome of plot"); properties.put("MsgNotYoursNotAllowedBiome", "is not yours. You are not allowed to change it's biome."); properties.put("MsgPlotUsingBiome", "This plot is using the biome"); properties.put("MsgPlotProtectedCannotReset", "Plot is protected and cannot be reset."); properties.put("MsgPlotProtectedCannotClear", "Plot is protected and cannot be cleared."); properties.put("MsgOwnedBy", "owned by"); properties.put("MsgWasReset", "was reset."); properties.put("MsgPlotReset", "Plot has been reset."); properties.put("MsgResetPlot", "reset plot"); properties.put("MsgPlotCleared", "Plot cleared."); properties.put("MsgClearedPlot", "cleared plot"); properties.put("MsgNotYoursNotAllowedClear", "is not yours. You are not allowed to clear it."); properties.put("MsgAlreadyAllowed", "was already allowed"); properties.put("MsgAlreadyDenied", "was already denied"); properties.put("MsgWasNotAllowed", "was not allowed"); properties.put("MsgWasNotDenied", "was not denied"); properties.put("MsgNowUndenied", "now undenied."); properties.put("MsgNowDenied", "now denied."); properties.put("MsgNowAllowed", "now allowed."); properties.put("MsgAddedPlayer", "added player"); properties.put("MsgDeniedPlayer", "denied player"); properties.put("MsgRemovedPlayer", "removed player"); properties.put("MsgUndeniedPlayer", "undenied player"); properties.put("MsgToPlot", "to plot"); properties.put("MsgFromPlot", "from plot"); properties.put("MsgNotYoursNotAllowedAdd", "is not yours. You are not allowed to add someone to it."); properties.put("MsgNotYoursNotAllowedDeny", "is not yours. You are not allowed to deny someone from it."); properties.put("MsgNotYoursNotAllowedRemove", "is not yours. You are not allowed to remove someone from it."); properties.put("MsgNotYoursNotAllowedUndeny", "is not yours. You are not allowed to undeny someone to it."); properties.put("MsgNowOwnedBy", "is now owned by"); properties.put("MsgChangedOwnerFrom", "changed owner from"); properties.put("MsgChangedOwnerOf", "changed owner of"); properties.put("MsgOwnerChangedTo", "Plot Owner has been set to"); properties.put("MsgPlotMovedSuccess", "Plot moved successfully"); properties.put("MsgExchangedPlot", "exchanged plot"); properties.put("MsgAndPlot", "and plot"); properties.put("MsgReloadedSuccess", "reloaded successfully"); properties.put("MsgReloadedConfigurations", "reloaded configurations"); properties.put("MsgNoPlotworldFound", "No Plot world found."); properties.put("MsgWorldNotPlot", "does not exist or is not a plot world."); properties.put("MsgCredit", "Credit: Empire92, Travis506, ZachBora, Athion.net"); properties.put("ConsoleHelpMain", "[AthionPlots Console Help]"); properties.put("ConsoleHelpReload", " - Reloads the plugin and its configuration files"); properties.put("HelpTitle", "AthionPlots"); properties.put("WordWorld", "World"); properties.put("WordUsage", "Usage"); properties.put("WordExample", "Example"); properties.put("WordAmount", "amount"); properties.put("WordUse", "Use"); properties.put("WordPlot", "Plot"); properties.put("WordFor", "for"); properties.put("WordAt", "at"); properties.put("WordMarked", "marked"); properties.put("WordFinished", "finished"); properties.put("WordUnfinished", "unfinished"); properties.put("WordAuction", "Auction"); properties.put("WordSell", "Sell"); properties.put("WordYours", "Yours"); properties.put("WordHelpers", "Helpers"); properties.put("WordInfinite", "Infinite"); properties.put("WordPrice", "Price"); properties.put("WordPlayer", "Player"); properties.put("WordComment", "comment"); properties.put("WordBiome", "biome"); properties.put("WordId", "id"); properties.put("WordIdFrom", "id-from"); properties.put("WordIdTo", "id-to"); properties.put("WordNever", "Never"); properties.put("WordDefault", "Default"); properties.put("WordMissing", "Missing"); properties.put("WordYes", "Yes"); properties.put("WordNo", "No"); properties.put("WordText", "text"); properties.put("WordFrom", "From"); properties.put("WordTo", "to"); properties.put("WordBiomes", "Biomes"); properties.put("WordNotApplicable", "N/A"); properties.put("WordBottom", "Bottom"); properties.put("WordTop", "Top"); properties.put("WordPossessive", "'s"); properties.put("WordRemoved", "removed"); properties.put("SignOwner", "Owner:"); properties.put("SignId", "ID:"); properties.put("SignForSale", "&9&lFOR SALE"); properties.put("SignPrice", "Price :"); properties.put("SignPriceColor", "&9"); properties.put("SignOnAuction", "&9&lON AUCTION"); properties.put("SignMinimumBid", "Minimum bid :"); properties.put("SignCurrentBid", "Current bid :"); properties.put("SignCurrentBidColor", "&9"); properties.put("InfoId", "ID"); properties.put("InfoOwner", "Owner"); properties.put("InfoBiome", "Biome"); properties.put("InfoExpire", "Expire date"); properties.put("InfoFinished", "Finished"); properties.put("InfoProtected", "Protected"); properties.put("InfoHelpers", "Helpers"); properties.put("InfoDenied", "Denied"); properties.put("InfoAuctionned", "Auctionned"); properties.put("InfoBidder", "Bidder"); properties.put("InfoBid", "Bid"); properties.put("InfoForSale", "For sale"); properties.put("InfoMinimumBid", "Minimum bid"); properties.put("CommandBuy", "buy"); properties.put("CommandBid", "bid"); properties.put("CommandResetExpired", "resetexpired"); properties.put("CommandHelp", "help"); properties.put("CommandClaim", "claim"); properties.put("CommandAuto", "auto"); properties.put("CommandInfo", "info"); properties.put("CommandComment", "comment"); properties.put("CommandComments", "comments"); properties.put("CommandBiome", "biome"); properties.put("CommandBiomelist", "biomelist"); properties.put("CommandId", "id"); properties.put("CommandTp", "tp"); properties.put("CommandClear", "clear"); properties.put("CommandReset", "reset"); properties.put("CommandAdd", "add"); properties.put("CommandDeny", "deny"); properties.put("CommandRemove", "remove"); properties.put("CommandUndeny", "undeny"); properties.put("CommandSetowner", "setowner"); properties.put("CommandMove", "move"); properties.put("CommandWEAnywhere", "weanywhere"); properties.put("CommandList", "list"); properties.put("CommandExpired", "expired"); properties.put("CommandAddtime", "addtime"); properties.put("CommandDone", "done"); properties.put("CommandDoneList", "donelist"); properties.put("CommandProtect", "protect"); properties.put("CommandSell", "sell"); properties.put("CommandSellBank", "sell bank"); properties.put("CommandDispose", "dispose"); properties.put("CommandAuction", "auction"); properties.put("CommandHome", "home"); properties.put("ErrCannotBuild", "You cannot build here."); properties.put("ErrCannotUseEggs", "You cannot use eggs here."); properties.put("ErrCannotUse", "You cannot use that."); properties.put("ErrCreatingPlotAt", "An error occured while creating the plot at"); properties.put("ErrMovingPlot", "Error moving plot"); CreateConfig(filelang, properties, "AthionPlots Caption configuration αω"); if (language != "english") { filelang = new File(getDataFolder(), "plotme-english.yml"); CreateConfig(filelang, properties, "AthionPlots Caption configuration"); } InputStream input = null; try { input = new FileInputStream(filelang); final Yaml yaml = new Yaml(); final Object obj = yaml.load(input); if (obj instanceof LinkedHashMap<?, ?>) { @SuppressWarnings("unchecked") final LinkedHashMap<String, String> data = (LinkedHashMap<String, String>) obj; captions = new HashMap<String, String>(); for (final String key : data.keySet()) { captions.put(key, data.get(key)); } } } catch (final FileNotFoundException e) { logger.severe("File not found: " + e.getMessage()); e.printStackTrace(); } catch (final Exception e) { logger.severe("Error with configuration: " + e.getMessage()); e.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (final IOException e) {} } } } private void CreateConfig(final File file, final TreeMap<String, String> properties, final String Title) { if (!file.exists()) { BufferedWriter writer = null; try { final File dir = new File(getDataFolder(), ""); dir.mkdirs(); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8")); writer.write("# " + Title + "\n"); for (final Entry<String, String> e : properties.entrySet()) { writer.write(e.getKey() + ": '" + e.getValue().replace("'", "''") + "'\n"); } writer.close(); } catch (final IOException e) { logger.severe("Unable to create config file : " + Title + "!"); logger.severe(e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (final IOException e2) {} } } } else { OutputStreamWriter writer = null; InputStream input = null; try { input = new FileInputStream(file); final Yaml yaml = new Yaml(); final Object obj = yaml.load(input); if (obj instanceof LinkedHashMap<?, ?>) { @SuppressWarnings("unchecked") final LinkedHashMap<String, String> data = (LinkedHashMap<String, String>) obj; writer = new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8"); for (final Entry<String, String> e : properties.entrySet()) { if (!data.containsKey(e.getKey())) { writer.write("\n" + e.getKey() + ": '" + e.getValue().replace("'", "''") + "'"); } } writer.close(); input.close(); } } catch (final FileNotFoundException e) { logger.severe("File not found: " + e.getMessage()); e.printStackTrace(); } catch (final Exception e) { logger.severe("Error with configuration: " + e.getMessage()); e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); } catch (final IOException e2) {} } if (input != null) { try { input.close(); } catch (final IOException e) {} } } } } public void scheduleTask(final Runnable task, final int eachseconds, final int howmanytimes) { AthionPlots.cscurrentlyprocessingexpired.sendMessage("" + AthionPlots.PREFIX + ChatColor.RESET); for (int ctr = 0; ctr < (howmanytimes / nbperdeletionprocessingexpired); ctr++) { Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, task, ctr * eachseconds * 20); } } private short getBlockId(final ConfigurationSection cs, final String section, final String def) { final String idvalue = cs.getString(section, def.toString()); if (idvalue.indexOf(":") > 0) { return Short.parseShort(idvalue.split(":")[0]); } else { return Short.parseShort(idvalue); } } private byte getBlockValue(final ConfigurationSection cs, final String section, final String def) { final String idvalue = cs.getString(section, def.toString()); if (idvalue.indexOf(":") > 0) { return Byte.parseByte(idvalue.split(":")[1]); } else { return 0; } } private String getBlockValueId(final Short id, final Byte value) { return (value == 0) ? id.toString() : id.toString() + ":" + value.toString(); } @Override public ChunkGenerator getDefaultWorldGenerator(final String worldName, final String id) { if (AthionCore.isPlotWorld(worldName)) { // Configuration found for this worldName, creating the world // with the settings for this world. return new AthionGen(AthionCore.getMap(worldName)); } else { // Configuration could not be found, or the world config information was not found. // Resulting in creation by default return new AthionGen(); } } }
AthionOfficial/AthionPlots
src/main/java/net/athion/athionplots/AthionPlots.java
213,311
/* * Logisim-evolution - digital logic design tool and simulator * Copyright by the Logisim-evolution developers * * https://github.com/logisim-evolution/ * * This is free software released under GNU GPLv3 license */ package com.cburch.logisim.util; import static com.cburch.logisim.util.Strings.S; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dialog; import java.awt.KeyboardFocusManager; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.KeyStroke; public abstract class JDialogOk extends JDialog { private class MyListener extends WindowAdapter implements ActionListener { @Override public void actionPerformed(ActionEvent e) { final var src = e.getSource(); if (src == ok) { okClicked(); dispose(); } else if (src == cancel) { cancelClicked(); dispose(); } } @Override public void windowClosing(WindowEvent e) { JDialogOk.this.removeWindowListener(this); cancelClicked(); dispose(); } } private static final long serialVersionUID = 1L; private final JPanel contents = new JPanel(new BorderLayout()); protected final JButton ok = new JButton(S.get("dlogOkButton")); protected final JButton cancel = new JButton(S.get("dlogCancelButton")); protected Window parent; public JDialogOk(String title) { this(title, true); } public JDialogOk(String title, boolean withCancel) { super( KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow(), title, Dialog.ModalityType.APPLICATION_MODAL); parent = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow(); configure(withCancel); } public void cancelClicked() {} private void configure(boolean withCancel) { final var listener = new MyListener(); this.addWindowListener(listener); ok.addActionListener(listener); cancel.addActionListener(listener); final var buttons = Box.createHorizontalBox(); buttons.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); buttons.add(Box.createHorizontalGlue()); buttons.add(ok); if (withCancel) { buttons.add(Box.createHorizontalStrut(10)); buttons.add(cancel); } buttons.add(Box.createHorizontalGlue()); final var pane = super.getContentPane(); pane.add(contents, BorderLayout.CENTER); pane.add(buttons, BorderLayout.SOUTH); getRootPane() .registerKeyboardAction( e -> { setVisible(false); cancelClicked(); dispose(); }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); addWindowListener( new WindowAdapter() { @Override public void windowOpened(WindowEvent e) { ok.requestFocus(); e.getWindow().removeWindowListener(this); } }); } @Override public Container getContentPane() { return contents; } @Override public void pack() { super.pack(); while (parent != null && !parent.isShowing()) parent = parent.getOwner(); setLocationRelativeTo(parent); parent = null; } public abstract void okClicked(); }
logisim-evolution/logisim-evolution
src/main/java/com/cburch/logisim/util/JDialogOk.java
213,312
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package docking.dnd; import java.awt.Point; import java.awt.datatransfer.Transferable; import java.awt.dnd.*; /** * Interface to define a drag source. */ public interface Draggable { /** * Return true if the object at the location in the DragGesture * event is draggable. * * @param e event passed to a DragGestureListener via its * dragGestureRecognized() method when a particular DragGestureRecognizer * detects a platform dependent Drag and Drop action initiating * gesture has occurred on the Component it is tracking. * @see docking.dnd.DragGestureAdapter */ public boolean isStartDragOk(DragGestureEvent e); /** * Called by the DragGestureAdapter to start the drag. */ public DragSourceListener getDragSourceListener(); /** * Do the move operation; called when the drag and drop operation * completes. * @see docking.dnd.DragSrcAdapter#dragDropEnd */ public void move(); /** * Method called when the drag operation exits the drop target * without dropping. * @param event TODO */ public void dragCanceled(DragSourceDropEvent event); /** * Get the drag actions supported by this drag source: * <UL> * <li>DnDConstants.ACTION_MOVE * <li>DnDConstants.ACTION_COPY * <li>DnDConstants.ACTION_COPY_OR_MOVE * </UL> * * @return the drag actions */ public int getDragAction(); /** * Get the object to transfer. * @param p location of object to transfer * @return object to transfer */ public Transferable getTransferable(Point p); }
NationalSecurityAgency/ghidra
Ghidra/Framework/Docking/src/main/java/docking/dnd/Draggable.java
213,313
package mediathek.gui.dialog; import mediathek.tool.EscapeKeyHandler; import javax.swing.*; import java.awt.*; @SuppressWarnings("serial") public class DialogOk extends JDialog { public DialogOk(Frame parent, boolean modal, JPanel panel, String titel) { super(parent, modal); initComponents(); this.setTitle(titel); jPanelExtra.setLayout(new BorderLayout()); jPanelExtra.add(panel); this.pack(); if (parent != null) { setLocationRelativeTo(parent); } jButtonBeenden.addActionListener(e -> dispose()); EscapeKeyHandler.installHandler(this, this::dispose); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jButtonBeenden = new javax.swing.JButton(); jPanelExtra = new javax.swing.JPanel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jButtonBeenden.setText("Ok"); jPanelExtra.setBorder(javax.swing.BorderFactory.createEtchedBorder()); javax.swing.GroupLayout jPanelExtraLayout = new javax.swing.GroupLayout(jPanelExtra); jPanelExtra.setLayout(jPanelExtraLayout); jPanelExtraLayout.setHorizontalGroup( jPanelExtraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanelExtraLayout.setVerticalGroup( jPanelExtraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 265, Short.MAX_VALUE) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jPanelExtra, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGap(0, 414, Short.MAX_VALUE) .addComponent(jButtonBeenden, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jPanelExtra, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonBeenden) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonBeenden; private javax.swing.JPanel jPanelExtra; // End of variables declaration//GEN-END:variables }
mediathekview/MediathekView
src/main/java/mediathek/gui/dialog/DialogOk.java
213,314
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.rocketmq.common.message; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class Message implements Serializable { private static final long serialVersionUID = 8445773977080406428L; private String topic; private int flag; private Map<String, String> properties; private byte[] body; private String transactionId; public Message() { } public Message(String topic, byte[] body) { this(topic, "", "", 0, body, true); } public Message(String topic, String tags, String keys, int flag, byte[] body, boolean waitStoreMsgOK) { this.topic = topic; this.flag = flag; this.body = body; if (tags != null && tags.length() > 0) { this.setTags(tags); } if (keys != null && keys.length() > 0) { this.setKeys(keys); } this.setWaitStoreMsgOK(waitStoreMsgOK); } public Message(String topic, String tags, byte[] body) { this(topic, tags, "", 0, body, true); } public Message(String topic, String tags, String keys, byte[] body) { this(topic, tags, keys, 0, body, true); } public void setKeys(String keys) { this.putProperty(MessageConst.PROPERTY_KEYS, keys); } void putProperty(final String name, final String value) { if (null == this.properties) { this.properties = new HashMap<>(); } this.properties.put(name, value); } void clearProperty(final String name) { if (null != this.properties) { this.properties.remove(name); } } public void putUserProperty(final String name, final String value) { if (MessageConst.STRING_HASH_SET.contains(name)) { throw new RuntimeException(String.format( "The Property<%s> is used by system, input another please", name)); } if (value == null || value.trim().isEmpty() || name == null || name.trim().isEmpty()) { throw new IllegalArgumentException( "The name or value of property can not be null or blank string!" ); } this.putProperty(name, value); } public String getUserProperty(final String name) { return this.getProperty(name); } public String getProperty(final String name) { if (null == this.properties) { this.properties = new HashMap<>(); } return this.properties.get(name); } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public String getTags() { return this.getProperty(MessageConst.PROPERTY_TAGS); } public void setTags(String tags) { this.putProperty(MessageConst.PROPERTY_TAGS, tags); } public String getKeys() { return this.getProperty(MessageConst.PROPERTY_KEYS); } public void setKeys(Collection<String> keyCollection) { String keys = String.join(MessageConst.KEY_SEPARATOR, keyCollection); this.setKeys(keys); } public int getDelayTimeLevel() { String t = this.getProperty(MessageConst.PROPERTY_DELAY_TIME_LEVEL); if (t != null) { return Integer.parseInt(t); } return 0; } public void setDelayTimeLevel(int level) { this.putProperty(MessageConst.PROPERTY_DELAY_TIME_LEVEL, String.valueOf(level)); } public boolean isWaitStoreMsgOK() { String result = this.getProperty(MessageConst.PROPERTY_WAIT_STORE_MSG_OK); if (null == result) { return true; } return Boolean.parseBoolean(result); } public void setWaitStoreMsgOK(boolean waitStoreMsgOK) { this.putProperty(MessageConst.PROPERTY_WAIT_STORE_MSG_OK, Boolean.toString(waitStoreMsgOK)); } public void setInstanceId(String instanceId) { this.putProperty(MessageConst.PROPERTY_INSTANCE_ID, instanceId); } public int getFlag() { return flag; } public void setFlag(int flag) { this.flag = flag; } public byte[] getBody() { return body; } public void setBody(byte[] body) { this.body = body; } public Map<String, String> getProperties() { return properties; } void setProperties(Map<String, String> properties) { this.properties = properties; } public String getBuyerId() { return getProperty(MessageConst.PROPERTY_BUYER_ID); } public void setBuyerId(String buyerId) { putProperty(MessageConst.PROPERTY_BUYER_ID, buyerId); } public String getTransactionId() { return transactionId; } public void setTransactionId(String transactionId) { this.transactionId = transactionId; } @Override public String toString() { return "Message{" + "topic='" + topic + '\'' + ", flag=" + flag + ", properties=" + properties + ", body=" + Arrays.toString(body) + ", transactionId='" + transactionId + '\'' + '}'; } public void setDelayTimeSec(long sec) { this.putProperty(MessageConst.PROPERTY_TIMER_DELAY_SEC, String.valueOf(sec)); } public long getDelayTimeSec() { String t = this.getProperty(MessageConst.PROPERTY_TIMER_DELAY_SEC); if (t != null) { return Long.parseLong(t); } return 0; } public void setDelayTimeMs(long timeMs) { this.putProperty(MessageConst.PROPERTY_TIMER_DELAY_MS, String.valueOf(timeMs)); } public long getDelayTimeMs() { String t = this.getProperty(MessageConst.PROPERTY_TIMER_DELAY_MS); if (t != null) { return Long.parseLong(t); } return 0; } public void setDeliverTimeMs(long timeMs) { this.putProperty(MessageConst.PROPERTY_TIMER_DELIVER_MS, String.valueOf(timeMs)); } public long getDeliverTimeMs() { String t = this.getProperty(MessageConst.PROPERTY_TIMER_DELIVER_MS); if (t != null) { return Long.parseLong(t); } return 0; } }
apache/rocketmq
common/src/main/java/org/apache/rocketmq/common/message/Message.java
213,315
package sfBugsNew; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import edu.umd.cs.findbugs.annotations.ExpectWarning; import edu.umd.cs.findbugs.annotations.NoWarning; public class Feature314 { @ExpectWarning("DMI_HARDCODED_ABSOLUTE_FILENAME") public void testHardCoded() throws FileNotFoundException { openFile("c:\\file.txt"); } @ExpectWarning("DMI_HARDCODED_ABSOLUTE_FILENAME") public void testHardCodedSafe() throws FileNotFoundException { openFileSafe("c:\\file.txt"); } @ExpectWarning("DMI_HARDCODED_ABSOLUTE_FILENAME") public void testHardCodedPuzzling() throws FileNotFoundException { openFilePuzzling4("ok", "c:\\file.txt", "ok", "ok"); } @NoWarning("DMI_HARDCODED_ABSOLUTE_FILENAME") public void testHardCodedPuzzlingOk() throws FileNotFoundException { openFilePuzzling4("c:\\file.txt", "ok", "c:\\file.txt", "c:\\file.txt"); } @ExpectWarning("DMI_HARDCODED_ABSOLUTE_FILENAME") public void testHardCodedLong() throws FileNotFoundException { openFilePuzzlingLong(1L, "c:\\file.txt", "ok", 0.0); } @NoWarning("DMI_HARDCODED_ABSOLUTE_FILENAME") public void testHardCodedLongOk() throws FileNotFoundException { openFilePuzzlingLong(1L, "ok", "c:\\file.txt", 0.0); } private FileOutputStream openFile(String name) throws FileNotFoundException { return new FileOutputStream(name); } private FileOutputStream openFileSafe(String name) throws FileNotFoundException { if(name == null) return null; return openFile(name); } private FileOutputStream openFilePuzzling(String arg1, String arg2, String name, String arg3) throws FileNotFoundException { return openFileSafe(name); } private static FileOutputStream openFilePuzzling2(String arg1, String arg3, String arg2, String name) throws FileNotFoundException { return new Feature314().openFilePuzzling(arg1, arg2, name, arg3); } private FileOutputStream openFilePuzzling3(String name, String arg3, String arg2, String arg1) throws FileNotFoundException { return openFilePuzzling2(arg1, arg2, arg3, name); } private FileOutputStream openFilePuzzling4(String arg1, String name, String arg2, String arg3) throws FileNotFoundException { return openFilePuzzling3(name, arg1, arg2, arg3); } private FileOutputStream openFilePuzzlingLong(long arg1, String name, String arg2, double arg3) throws FileNotFoundException { return openFilePuzzling3(name, String.valueOf(arg1), arg2, String.valueOf(arg3)); } @ExpectWarning("SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE") public boolean test(Connection c, String code) throws SQLException { return Sql.hasResult(c, "SELECT 1 FROM myTable WHERE code='"+code+"'"); } @ExpectWarning("SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE") public boolean testSqlLong(Connection c, String code) throws SQLException { return Sql.hasResult(c, 1L, "SELECT 1 FROM myTable WHERE code='"+code+"'", 2L, "blahblah"); } @NoWarning("SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE") public boolean testSqlLongOk(Connection c, String code) throws SQLException { return Sql.hasResult(c, 1L, "SELECT COUNT(*) FROM myTable", 2L, "Code: "+code); } public static class Sql { // passthru method: warning is generated on call site @NoWarning("SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE") public static boolean hasResult(Connection c, String query) throws SQLException { try (Statement st = c.createStatement(); ResultSet rs = st.executeQuery(query)) { return rs.next(); } } // passthru method: warning is generated on call site @NoWarning("SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE") public static boolean hasResult(Connection c, long l1, String query, long l2, String somethingElse) throws SQLException { System.out.println(somethingElse+": "+l1+":"+l2); try (Statement st = c.createStatement(); ResultSet rs = st.executeQuery(query)) { return rs.next(); } } } }
spotbugs/spotbugs
spotbugsTestCases/src/java/sfBugsNew/Feature314.java
213,316
/** * Copyright (c) 2016-2023, Michael Yang 杨福海 ([email protected]). * <p> * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.gnu.org/licenses/lgpl-3.0.txt * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.jpress.commons.email; import com.jfinal.log.Log; import io.jboot.utils.StrUtil; import io.jpress.JPressConsts; import io.jpress.JPressOptions; import javax.mail.*; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility; import java.util.HashSet; import java.util.Properties; import java.util.Set; public class SimpleEmailSender extends Authenticator implements EmailSender { private static final Log logger = Log.getLog(SimpleEmailSender.class); private String host; private String name; private String password; private boolean useSSL = true; private boolean enable = false; public SimpleEmailSender() { this.host = JPressOptions.get(JPressConsts.OPTION_CONNECTION_EMAIL_SMTP); this.name = JPressOptions.get(JPressConsts.OPTION_CONNECTION_EMAIL_ACCOUNT); this.password = JPressOptions.get(JPressConsts.OPTION_CONNECTION_EMAIL_PASSWORD); this.useSSL = JPressOptions.getAsBool(JPressConsts.OPTION_CONNECTION_EMAIL_SSL_ENABLE); this.enable = JPressOptions.getAsBool(JPressConsts.OPTION_CONNECTION_EMAIL_ENABLE); } private Message createMessage() { Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.smtp.host", host); props.setProperty("mail.smtp.port", "25"); if (useSSL) { props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.port", "465"); } // error:javax.mail.MessagingException: 501 Syntax: HELO hostname props.setProperty("mail.smtp.localhost", "127.0.0.1"); Session session = Session.getInstance(props, this); Message message = new MimeMessage(session); try { message.setFrom(new InternetAddress(MimeUtility.encodeText(name) + "<" + name + ">")); } catch (Exception e) { logger.error(e.getMessage(), e); } return message; } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(name, password); } private static Address[] toAddress(String... emails) { if (emails == null || emails.length == 0) { return null; } Set<Address> addresses = new HashSet<>(); for (String email : emails) { if (StrUtil.isNotBlank(email)) { try { addresses.add(new InternetAddress(email)); } catch (AddressException e) { continue; } } } return addresses.toArray(new Address[0]); } @Override public boolean send(Email email) { if (enable == false) { //do nothing return false; } Message message = createMessage(); try { message.setSubject(email.getSubject()); message.setContent(email.getContent(), "text/html;charset=utf-8"); message.setRecipients(Message.RecipientType.TO, toAddress(email.getTo())); message.setRecipients(Message.RecipientType.CC, toAddress(email.getCc())); Transport.send(message); return true; } catch (MessagingException e) { logger.error("SimpleEmailSender send error", e); } return false; } public String getHost() { return host; } public String getName() { return name; } public String getPassword() { return password; } public boolean isUseSSL() { return useSSL; } public boolean isEnable() { return enable; } public boolean isConfigOk() { return StrUtil.areNotEmpty(host, name, password); } }
JPressProjects/jpress
jpress-commons/src/main/java/io/jpress/commons/email/SimpleEmailSender.java
213,318
/** * Copyright (c) 2015-2022, Michael Yang 杨福海 ([email protected]). * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.jboot.support.jwt; import io.jboot.app.config.annotation.ConfigModel; import io.jboot.utils.StrUtil; /** * @author Michael Yang 杨福海 ([email protected]) * @version V1.0 */ @ConfigModel(prefix = "jboot.web.jwt") public class JwtConfig { private String httpHeaderName = "Jwt"; private String httpParameterKey; private String secret; /** * 有效期,单位毫秒, * 不配置时,或者 小于等于 0 时,永久有效 */ private long validityPeriod = 0; public String getHttpHeaderName() { return httpHeaderName; } public void setHttpHeaderName(String httpHeaderName) { this.httpHeaderName = httpHeaderName; } public String getHttpParameterKey() { return httpParameterKey; } public void setHttpParameterKey(String httpParameterKey) { this.httpParameterKey = httpParameterKey; } public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } public long getValidityPeriod() { return validityPeriod; } public void setValidityPeriod(long validityPeriod) { this.validityPeriod = validityPeriod; } public boolean isConfigOk() { return StrUtil.isNotBlank(secret); } }
yangfuhai/jboot
src/main/java/io/jboot/support/jwt/JwtConfig.java
213,319
package com.lenovo.safecenter.utils; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AnimationUtils; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.lenovo.safecenter.MainTab.FirstUsePasswordSettingActivity; import com.lenovo.safecenter.R; import com.lenovo.safecenter.dialog.CustomDialog; import com.lenovo.safecenter.safemode.SofeModeMain; import com.lenovo.safecenter.utils.updateLab.AutoUpdateLabManager; public class DialogUtil { public static final int ID_MANUAL_OPTIMIZATION_PROTECT_THIEF = 0; public static final int ID_NO_ACTION = 2; public static final int NOTICE_DIALOG_DOWNLOAD_LECLOUD = 3; public static final int NOTICE_DIALOG_KILL_VIRUS = 1; private static CustomDialog a; private static CustomDialog b = null; private static int c = 0; public interface ModifyPasswordDialogListener { void onModifyPasswordCancel(int i); void onModifyPasswordOk(int i, String str); } public interface SettingFloatNumberDialogListener { void onSettingFloatNumberDialogCancel(int i, Float f); void onSettingFloatNumberDialogOK(int i, Float f); } public interface SettingNumberDialogListener { void onSettingNumberDialogCancel(int i, int i2); void onSettingNumberDialogOK(int i, int i2); } public interface WarnDialogListener { void onWarnDialogCancel(int i); void onWarnDialogOk(int i); } public static void dismissShowPwdDialog() { if (a != null) { a.dismiss(); } } public static void showPwdDialog(final String action, final Context context) { dismissShowPwdDialog(); if (PwdUtil.hasPassword(context)) { View view = LayoutInflater.from(context).inflate(R.layout.input_password_content, (ViewGroup) null); final TextView message = (TextView) view.findViewById(R.id.txt_message); message.setText(R.string.input_privacy_pwd); final EditText edit = (EditText) view.findViewById(R.id.edt_input_pwd); a = new CustomDialog.Builder(context).setTitle(R.string.input_pwd).setContentView(view).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { /* class com.lenovo.safecenter.utils.DialogUtil.AnonymousClass9 */ public final void onClick(DialogInterface dialog, int which) { String newPwd = edit.getText().toString(); if (PwdUtil.checkPassword(context, newPwd)) { if (action.equals(Const.ACTION_MODIFY_PASSWORD_USE_PRE_PASSWORD)) { WflUtils.startSettingPasswordActivity(context, Const.ACTION_MODIFY_PASSWORD_USE_PRE_PASSWORD); DialogUtil.a.dismiss(); return; } Intent i = new Intent(action); if (action.equals(Const.ACTION_JUMP_RPIVACY_SAFE)) { WflUtils.jumpPrivatezoneOrDownloadpage(context); DialogUtil.a.dismiss(); } else if (action.equals(Const.ACTION_JUMP_APP_LOCK)) { WflUtils.jumpAppLockOrDownloadpage(context); DialogUtil.a.dismiss(); } else if (action.equals(Const.ACTION_JUMP_KID_MODE)) { WflUtils.jumpKidModeOrDownloadpage(context); DialogUtil.a.dismiss(); } else { context.startActivity(i); DialogUtil.a.dismiss(); } } else if (newPwd.length() == 0) { message.setText(R.string.error_tips_null); edit.startAnimation(AnimationUtils.loadAnimation(context, R.anim.shake)); } else if (!action.equals(Const.ACTION_JUMP_RPIVACY_SAFE) || !DataHelpUtils.execService("pwd", context).equals(newPwd)) { edit.startAnimation(AnimationUtils.loadAnimation(context, R.anim.shake)); edit.setText(""); message.setText(R.string.pwd_error_tips); } else { Intent i2 = new Intent(context, SofeModeMain.class); i2.putExtra("pwd", newPwd); i2.addFlags(8388608); context.startActivity(i2); DialogUtil.a.dismiss(); } } }, false).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { /* class com.lenovo.safecenter.utils.DialogUtil.AnonymousClass1 */ public final void onClick(DialogInterface dialog, int which) { DialogUtil.a.dismiss(); } }).show(); } } public static void showPasswordQuestionDialog(final Context context, final int id, String question, String answer) { View view = LayoutInflater.from(context).inflate(R.layout.dialog_retrieve_password, (ViewGroup) null); TextView questionTv = (TextView) view.findViewById(R.id.tv_retrieve_question); final EditText answerEt = (EditText) view.findViewById(R.id.et_retrieve_answer); String title = null; switch (id) { case 1: title = context.getString(R.string.retrieve_password_text); break; } questionTv.setText(question); b = new CustomDialog.Builder(context).setTitle(title).setContentView(view).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { /* class com.lenovo.safecenter.utils.DialogUtil.AnonymousClass11 */ public final void onClick(DialogInterface dialog, int which) { DialogUtil.b.dismiss(); } }).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { /* class com.lenovo.safecenter.utils.DialogUtil.AnonymousClass10 */ public final void onClick(DialogInterface dialog, int which) { String newAnser; if (answerEt.getText() == null) { newAnser = null; } else { newAnser = answerEt.getText().toString(); } if (TextUtils.isEmpty(newAnser)) { Toast.makeText(context, (int) R.string.password_answer_no_null_text, 0).show(); answerEt.startAnimation(AnimationUtils.loadAnimation(context, R.anim.shake)); } else if (!PwdUtil.checkPasswordAnswer(context, newAnser)) { Toast.makeText(context, (int) R.string.input_password_answer_error, 0).show(); answerEt.startAnimation(AnimationUtils.loadAnimation(context, R.anim.shake)); } else { switch (id) { case 1: WflUtils.startSettingPasswordActivity(context, Const.ACTION_MODIFY_PASSWORD_USE_ANSWER); DialogUtil.b.dismiss(); return; default: return; } } } }, false).show(); } public static Dialog createManualUpdateDialog(final Context context, final int id, final WarnDialogListener listener) { View view = LayoutInflater.from(context).inflate(R.layout.dialog_manual_update, (ViewGroup) null); TextView note1 = (TextView) view.findViewById(R.id.note1_manual_update); switch (id) { case 2: note1.setText(R.string.update_note_text); ((TextView) view.findViewById(R.id.note2_manual_update)).setVisibility(0); return new CustomDialog.Builder(context).setTitle(R.string.update_lab_notice_text).setContentView(view).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { /* class com.lenovo.safecenter.utils.DialogUtil.AnonymousClass16 */ public final void onClick(DialogInterface dialog, int which) { listener.onWarnDialogOk(id); } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { /* class com.lenovo.safecenter.utils.DialogUtil.AnonymousClass15 */ public final void onClick(DialogInterface dialog, int which) { } }).show(); case 3: note1.setText(R.string.all_update_lab_is_new_text); return new CustomDialog.Builder(context).setTitle(R.string.update_lab_notice_text).setContentView(view).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { /* class com.lenovo.safecenter.utils.DialogUtil.AnonymousClass14 */ public final void onClick(DialogInterface dialog, int which) { } }).show(); case 4: note1.setText(R.string.no_net_update_failure); return new CustomDialog.Builder(context).setTitle(R.string.update_lab_notice_text).setContentView(view).setPositiveButton(R.string.set_net_text, new DialogInterface.OnClickListener() { /* class com.lenovo.safecenter.utils.DialogUtil.AnonymousClass13 */ public final void onClick(DialogInterface dialog, int which) { WflUtils.startWirelessSettingsActivity(context); } }).setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() { /* class com.lenovo.safecenter.utils.DialogUtil.AnonymousClass12 */ public final void onClick(DialogInterface dialog, int which) { } }).show(); default: return null; } } public static Dialog createAutoUpdateRatechoice(Context context, final int id, final SettingNumberDialogListener listener) { return new CustomDialog.Builder(context).setTitle(R.string.title_auto_update).setSingleChoiceItems(AutoUpdateLabManager.getUpdateModeStringArray(context), AutoUpdateLabManager.getAutoUpdateMode(context), new DialogInterface.OnClickListener() { /* class com.lenovo.safecenter.utils.DialogUtil.AnonymousClass3 */ public final void onClick(DialogInterface dialog, int whichButton) { int unused = DialogUtil.c = whichButton; } }).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { /* class com.lenovo.safecenter.utils.DialogUtil.AnonymousClass2 */ public final void onClick(DialogInterface dialog, int whichButton) { listener.onSettingNumberDialogOK(id, DialogUtil.c); } }).show(); } public static Dialog NoticeDialog(final Context context, final int id, String title, String content, String positiveText, final WarnDialogListener listener) { return new CustomDialog.Builder(context).setTitle(title).setMessage(content).setPositiveButton(positiveText, new DialogInterface.OnClickListener() { /* class com.lenovo.safecenter.utils.DialogUtil.AnonymousClass5 */ public final void onClick(DialogInterface dialog, int which) { switch (id) { case 0: Intent intent = new Intent(context, FirstUsePasswordSettingActivity.class); intent.setAction(Const.ACTION_JUMP_PROTECT_THIEF); intent.setFlags(268435456); context.startActivity(intent); return; case 1: case 2: default: return; case 3: listener.onWarnDialogOk(3); return; } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { /* class com.lenovo.safecenter.utils.DialogUtil.AnonymousClass4 */ public final void onClick(DialogInterface dialog, int which) { } }).show(); } public static Dialog NoticePositiveDialog(Context context, final int id, String title, String content, final WarnDialogListener listener) { return new CustomDialog.Builder(context).setTitle(title).setMessage(content).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { /* class com.lenovo.safecenter.utils.DialogUtil.AnonymousClass6 */ public final void onClick(DialogInterface dialog, int which) { switch (id) { case 1: listener.onWarnDialogOk(1); return; default: return; } } }).show(); } public static Dialog createSettingNumberDialog(final Context context, final int id, final SettingNumberDialogListener listener) { View view = LayoutInflater.from(context).inflate(R.layout.dialog_setting_number, (ViewGroup) null); TextView note1 = (TextView) view.findViewById(R.id.note1_input_number); switch (id) { case 2: note1.setText(R.string.input_sms_month_num_text); break; } final EditText editText = (EditText) view.findViewById(R.id.et_setting_number_comment); int sms = Const.getMonthLimitSMS(); if (sms != 0) { editText.setText("" + sms); } return new CustomDialog.Builder(context).setTitle(R.string.input_notice_text).setContentView(view).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { /* class com.lenovo.safecenter.utils.DialogUtil.AnonymousClass8 */ public final void onClick(DialogInterface dialog, int which) { String number = editText.getText().toString(); if (TextUtils.isEmpty(number)) { Toast.makeText(context, context.getString(R.string.no_null_limit_input_num_text), 1).show(); } else if (Integer.parseInt(number) == 0) { Toast.makeText(context, context.getString(R.string.no_zero_limit_input_num_text), 1).show(); } else { listener.onSettingNumberDialogOK(id, Integer.valueOf(number).intValue()); } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { /* class com.lenovo.safecenter.utils.DialogUtil.AnonymousClass7 */ public final void onClick(DialogInterface dialog, int which) { } }).show(); } }
jonathandata1/pegasus_spyware
sample4/recompiled_java/sources/com/lenovo/safecenter/utils/DialogUtil.java
213,320
package sfBugsNew; import edu.umd.cs.findbugs.annotations.ExpectWarning; import edu.umd.cs.findbugs.annotations.NoWarning; public class Feature327 { @ExpectWarning("RpC_REPEATED_CONDITIONAL_TEST") public int test(int a, int b, int c) { if((a % 2 == 0 && b % 2 == 0 && c % 2 != 0) || (a % 2 == 0 && b % 2 == 0 && c % 2 != 0)) { return 1; } return 0; } @NoWarning("RpC_REPEATED_CONDITIONAL_TEST") public int testOk(int a, int b, int c) { if((a % 2 == 0 && b % 2 == 0 && c % 2 != 0) || (a % 2 == 0 && b % 2 == 0 && c % 2 == 0)) { return 1; } return 0; } @ExpectWarning("RpC_REPEATED_CONDITIONAL_TEST") public int testJmol(String line) { if (line.length() > 37 && (line.charAt(36) == 0 && line.charAt(37) == 100 || line.charAt(36) == 0 && line.charAt(37) == 100)) { return 1; } return 0; } @ExpectWarning("RpC_REPEATED_CONDITIONAL_TEST") public int testOr(int a, int b) { if((a > 0 && b > 0) || (a > 0 && b > 0)) { return 1; } return 0; } @ExpectWarning("RpC_REPEATED_CONDITIONAL_TEST") public int testAnd(int a, int b) { if((a > 0 || b > 0) && (a > 0 || b > 0)) { return 1; } return 0; } @ExpectWarning("RpC_REPEATED_CONDITIONAL_TEST") public int testRepeatingAnd(int a, int b, int c) { if ((a % 2 == 0 && b % 2 == 0 && c % 2 != 0) || (a % 2 == 0 && b % 2 != 0 && c % 2 == 0) || (a % 2 != 0 && b % 2 == 0 && c % 2 == 0) || (a % 2 != 0 && b % 2 != 0 && c % 2 == 0) || (a % 2 == 0 && b % 2 != 0 && c % 2 != 0) && (a % 2 == 0 && b % 2 != 0 && c % 2 != 0)) { return 1; } return 0; } @NoWarning("RpC_REPEATED_CONDITIONAL_TEST") public int testRepeatingOk(int a, int b, int c) { if ((a % 2 == 0 && b % 2 == 0 && c % 2 != 0) || (a % 2 == 0 && b % 2 != 0 && c % 2 == 0) || (a % 2 != 0 && b % 2 == 0 && c % 2 == 0) || (a % 2 == 0 && b % 2 != 0 && c % 2 != 0) || (a % 2 != 0 && b % 2 != 0 && c % 2 == 0) && (a % 2 == 0 && b % 2 != 0 && c % 2 != 0)) { return 1; } return 0; } @NoWarning("RpC_REPEATED_CONDITIONAL_TEST") public int testRepeatingConfusingOk(String s1, String s2) { if(s1.equals("a") && s2.equals("b") || s1.equals("c") && s2.equals("b") || s1.equals("c") && s2.equals("d")) { return 1; } return 0; } @ExpectWarning("RpC_REPEATED_CONDITIONAL_TEST") public void testRepeatingMiddle(int a, int b, int c) { if ((a % 2 == 0 && b % 2 == 0 && c % 2 != 0) || (a % 2 == 0 && b % 2 != 0 && c % 2 == 0) || (a % 2 == 0 && b % 2 != 0 && c % 2 != 0) || (a % 2 == 0 && b % 2 != 0 && c % 2 != 0) || (a % 2 != 0 && b % 2 == 0 && c % 2 == 0) || (a % 2 != 0 && b % 2 != 0 && c % 2 == 0)) System.out.println("qqq"); } @ExpectWarning("RpC_REPEATED_CONDITIONAL_TEST") public void testRepeatingBegin(int a, int b, int c) { if ((a % 2 == 0 && b % 2 != 0 && c % 2 != 0) || (a % 2 == 0 && b % 2 != 0 && c % 2 != 0) || (a % 2 == 0 && b % 2 == 0 && c % 2 != 0) || (a % 2 == 0 && b % 2 != 0 && c % 2 == 0) || (a % 2 != 0 && b % 2 == 0 && c % 2 == 0) || (a % 2 != 0 && b % 2 != 0 && c % 2 == 0)) System.out.println("qqq"); } @ExpectWarning("RpC_REPEATED_CONDITIONAL_TEST") public int testTernaryOr(int a) { if(((a % 2 == 0 ? 2 : 3) > 2) || ((a % 2 == 0 ? 2 : 3) > 2)) { return 1; } return 0; } @ExpectWarning("RpC_REPEATED_CONDITIONAL_TEST") public int testTernaryAnd(int a) { if(((a % 2 == 0 ? 2 : 3) > 2) && ((a % 2 == 0 ? 2 : 3) > 2)) { return 1; } return 0; } }
findbugsproject/findbugs
findbugsTestCases/src/java/sfBugsNew/Feature327.java
213,321
/* SmartPGP : JavaCard implementation of OpenPGP card v3 specification https://github.com/ANSSI-FR/SmartPGP Copyright (C) 2016 ANSSI This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package fr.anssi.smartpgp; import javacard.framework.*; public final class Transients { protected final byte[] buffer; private final short[] shorts; private static final byte SHORT_OFFSET_CURRENT_TAG = 0; private static final byte SHORT_OFFSET_OUTPUT_START = SHORT_OFFSET_CURRENT_TAG + 1; private static final byte SHORT_OFFSET_OUTPUT_LENGTH = SHORT_OFFSET_OUTPUT_START + 1; private static final byte SHORT_OFFSET_CHAINING_INPUT_LENGTH = SHORT_OFFSET_OUTPUT_LENGTH + 1; private static final byte SHORT_OFFSET_SECURE_MESSAGING_ENCRYPTION_COUNTER = SHORT_OFFSET_CHAINING_INPUT_LENGTH + 1; private static final byte SHORTS_SIZE = SHORT_OFFSET_SECURE_MESSAGING_ENCRYPTION_COUNTER + 1; private final byte[] bytes; private static final byte BYTE_OFFSET_CHAINING_INPUT_INS = 0; private static final byte BYTE_OFFSET_CHAINING_INPUT_P1 = BYTE_OFFSET_CHAINING_INPUT_INS + 1; private static final byte BYTE_OFFSET_CHAINING_INPUT_P2 = BYTE_OFFSET_CHAINING_INPUT_P1 + 1; private static final byte BYTE_OFFSET_CURRENT_TAG_OCCURRENCE = BYTE_OFFSET_CHAINING_INPUT_P2 + 1; private static final byte BYTES_SIZE = BYTE_OFFSET_CURRENT_TAG_OCCURRENCE + 1; private final boolean[] booleans; private static final byte BOOLEAN_OFFSET_CHAINING_OUTPUT = 0; private static final byte BOOLEAN_OFFSET_CHAINING_INPUT = BOOLEAN_OFFSET_CHAINING_OUTPUT + 1; private static final byte BOOLEAN_OFFSET_USER_PIN_MODE_81 = BOOLEAN_OFFSET_CHAINING_INPUT + 1; private static final byte BOOLEAN_OFFSET_USER_PIN_MODE_82 = BOOLEAN_OFFSET_USER_PIN_MODE_81 + 1; private static final byte BOOLEAN_OFFSET_SECURE_MESSAGING_OK = BOOLEAN_OFFSET_USER_PIN_MODE_82 + 1; private static final byte BOOLEANS_SIZE = BOOLEAN_OFFSET_SECURE_MESSAGING_OK + 1; protected Transients() { buffer = JCSystem.makeTransientByteArray(Constants.INTERNAL_BUFFER_MAX_LENGTH, JCSystem.CLEAR_ON_DESELECT); shorts = JCSystem.makeTransientShortArray(SHORTS_SIZE, JCSystem.CLEAR_ON_DESELECT); bytes = JCSystem.makeTransientByteArray(BYTES_SIZE, JCSystem.CLEAR_ON_DESELECT); booleans = JCSystem.makeTransientBooleanArray(BOOLEANS_SIZE, JCSystem.CLEAR_ON_DESELECT); } protected final void clear() { for(byte i = 0; i < shorts.length; ++i) { shorts[i] = (short)0; } for(byte i = 0; i < bytes.length; ++i) { bytes[i] = (byte)0; } for(byte i = 0; i < booleans.length; ++i) { booleans[i] = false; } } protected final void setCurrentTag(final short tag) { shorts[SHORT_OFFSET_CURRENT_TAG] = tag; } protected final short currentTag() { return shorts[SHORT_OFFSET_CURRENT_TAG]; } protected final void setChainingInputLength(final short len) { shorts[SHORT_OFFSET_CHAINING_INPUT_LENGTH] = len; } protected final short chainingInputLength() { return shorts[SHORT_OFFSET_CHAINING_INPUT_LENGTH]; } protected final void setSecureMessagingEncryptionCounter(final short val) { shorts[SHORT_OFFSET_SECURE_MESSAGING_ENCRYPTION_COUNTER] = val; } protected final short secureMessagingEncryptionCounter() { return shorts[SHORT_OFFSET_SECURE_MESSAGING_ENCRYPTION_COUNTER]; } protected final void setOutputStart(final short off) { shorts[SHORT_OFFSET_OUTPUT_START] = off; } protected final short outputStart() { return shorts[SHORT_OFFSET_OUTPUT_START]; } protected final void setOutputLength(final short len) { shorts[SHORT_OFFSET_OUTPUT_LENGTH] = len; } protected final short outputLength() { return shorts[SHORT_OFFSET_OUTPUT_LENGTH]; } protected final void setChainingInputIns(final byte ins) { bytes[BYTE_OFFSET_CHAINING_INPUT_INS] = ins; } protected final byte chainingInputIns() { return bytes[BYTE_OFFSET_CHAINING_INPUT_INS]; } protected final void setChainingInputP1(final byte p1) { bytes[BYTE_OFFSET_CHAINING_INPUT_P1] = p1; } protected final byte chainingInputP1() { return bytes[BYTE_OFFSET_CHAINING_INPUT_P1]; } protected final void setChainingInputP2(final byte p2) { bytes[BYTE_OFFSET_CHAINING_INPUT_P2] = p2; } protected final byte chainingInputP2() { return bytes[BYTE_OFFSET_CHAINING_INPUT_P2]; } protected final void setCurrentTagOccurrence(final byte occ) { bytes[BYTE_OFFSET_CURRENT_TAG_OCCURRENCE] = occ; } protected final byte currentTagOccurrence() { return bytes[BYTE_OFFSET_CURRENT_TAG_OCCURRENCE]; } protected final void setChainingOutput(final boolean chaining) { booleans[BOOLEAN_OFFSET_CHAINING_OUTPUT] = chaining; } protected final boolean chainingOutput() { return booleans[BOOLEAN_OFFSET_CHAINING_OUTPUT]; } protected final void setChainingInput(final boolean chaining) { booleans[BOOLEAN_OFFSET_CHAINING_INPUT] = chaining; } protected final boolean chainingInput() { return booleans[BOOLEAN_OFFSET_CHAINING_INPUT]; } protected final void setUserPinMode81(final boolean is81) { booleans[BOOLEAN_OFFSET_USER_PIN_MODE_81] = is81; } protected final boolean userPinMode81() { return booleans[BOOLEAN_OFFSET_USER_PIN_MODE_81]; } protected final void setUserPinMode82(final boolean is82) { booleans[BOOLEAN_OFFSET_USER_PIN_MODE_82] = is82; } protected final boolean userPinMode82() { return booleans[BOOLEAN_OFFSET_USER_PIN_MODE_82]; } protected final void setSecureMessagingOk(final boolean ok) { booleans[BOOLEAN_OFFSET_SECURE_MESSAGING_OK] = ok; } protected final boolean secureMessagingOk() { return booleans[BOOLEAN_OFFSET_SECURE_MESSAGING_OK]; } }
github-af/SmartPGP
src/fr/anssi/smartpgp/Transients.java
213,322
package org.infinispan.server.hotrod.logging; import java.net.InetSocketAddress; import java.time.Instant; import java.time.temporal.ChronoUnit; import org.infinispan.commons.util.Util; import org.infinispan.server.hotrod.AccessLoggingHeader; import org.infinispan.server.hotrod.HotRodVersion; import org.infinispan.util.logging.LogFactory; import org.jboss.logging.Logger; import org.jboss.logging.MDC; import io.netty.channel.ChannelFuture; /** * Logging handler for Hot Rod to log what requests have come into the server * * @author wburns * @since 9.0 */ public class HotRodAccessLogging { private final static Logger log = LogFactory.getLogger("HOTROD_ACCESS_LOG"); public static boolean isEnabled() { return log.isTraceEnabled(); } public void logOK(ChannelFuture future, AccessLoggingHeader header, int responseBytes) { logAfterComplete(future, header, responseBytes, "OK"); } public void logException(ChannelFuture future, AccessLoggingHeader header, String exception, int responseBytes) { logAfterComplete(future, header, responseBytes, exception); } private void logAfterComplete(ChannelFuture future, AccessLoggingHeader header, int responseBytes, String status) { String remoteAddress = ((InetSocketAddress)future.channel().remoteAddress()).getHostString(); future.addListener(f -> { // Duration long duration; if (header.requestStart == null) { duration = -1; } else { duration = ChronoUnit.MILLIS.between(header.requestStart, Instant.now()); } MDC.clear(); MDC.put("address", remoteAddress); MDC.put("user", checkForNull(header.principalName)); MDC.put("method", checkForNull(header.getOp())); MDC.put("protocol", checkForNull(HotRodVersion.forVersion(header.getVersion()))); MDC.put("status", checkForNull(status)); MDC.put("responseSize", responseBytes); MDC.put("requestSize", header.requestBytes); MDC.put("duration", duration); log.tracef("/%s/%s", checkForNull(header.getCacheName()), checkForNull(header.key)); }); } String checkForNull(Object obj) { if (obj == null || obj instanceof String && ((String) obj).isEmpty()) { return "-"; } else if (obj instanceof byte[]) { return Util.printArray((byte[]) obj); } else { return obj.toString(); } } }
infinispan/infinispan
server/hotrod/src/main/java/org/infinispan/server/hotrod/logging/HotRodAccessLogging.java
213,323
package org.wysaid.cgeDemo; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.hardware.Camera; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.SeekBar; import androidx.appcompat.app.AppCompatActivity; import org.wysaid.camera.CameraInstance; import org.wysaid.library.BuildConfig; import org.wysaid.myUtils.FileUtil; import org.wysaid.myUtils.ImageUtil; import org.wysaid.myUtils.MsgUtil; import org.wysaid.myUtils.PermissionUtil; import org.wysaid.nativePort.CGENativeLibrary; import org.wysaid.view.CameraRecordGLSurfaceView; public class CameraDemoActivity extends AppCompatActivity { public static String lastVideoPathFileName = FileUtil.getPath() + "/lastVideoPath.txt"; private String mCurrentConfig; private CameraRecordGLSurfaceView mCameraView; public final static String LOG_TAG = CameraRecordGLSurfaceView.LOG_TAG; public static CameraDemoActivity mCurrentInstance = null; public static CameraDemoActivity getInstance() { return mCurrentInstance; } private void showText(final String s) { mCameraView.post(new Runnable() { @Override public void run() { MsgUtil.toastMsg(CameraDemoActivity.this, s); } }); } public static class MyButtons extends androidx.appcompat.widget.AppCompatButton { public String filterConfig; public MyButtons(Context context, String config) { super(context); filterConfig = config; } } class RecordListener implements View.OnClickListener { boolean isValid = true; String recordFilename; @Override public void onClick(View v) { if (!BuildConfig.CGE_USE_VIDEO_MODULE) { MsgUtil.toastMsg(CameraDemoActivity.this, "gradle.ext.disableVideoModule is defined to true, video module disabled!!"); return; } Button btn = (Button) v; if (!isValid) { Log.e(LOG_TAG, "Please wait for the call..."); return; } isValid = false; if (!mCameraView.isRecording()) { btn.setText("Recording"); Log.i(LOG_TAG, "Start recording..."); recordFilename = ImageUtil.getPath() + "/rec_" + System.currentTimeMillis() + ".mp4"; // recordFilename = ImageUtil.getPath(CameraDemoActivity.this, false) + "/rec_1.mp4"; mCameraView.startRecording(recordFilename, new CameraRecordGLSurfaceView.StartRecordingCallback() { @Override public void startRecordingOver(boolean success) { if (success) { showText("Start recording OK"); FileUtil.saveTextContent(recordFilename, lastVideoPathFileName); } else { showText("Start recording failed"); } isValid = true; } }); } else { showText("Recorded as: " + recordFilename); btn.setText("Recorded"); Log.i(LOG_TAG, "End recording..."); mCameraView.endRecording(new CameraRecordGLSurfaceView.EndRecordingCallback() { @Override public void endRecordingOK() { Log.i(LOG_TAG, "End recording OK"); isValid = true; } }); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera_demo); PermissionUtil.verifyStoragePermissions(this); // lastVideoPathFileName = FileUtil.getPathInPackage(CameraDemoActivity.this, true) + "/lastVideoPath.txt"; Button takePicBtn = (Button) findViewById(R.id.takePicBtn); Button takeShotBtn = (Button) findViewById(R.id.takeShotBtn); Button recordBtn = (Button) findViewById(R.id.recordBtn); mCameraView = (CameraRecordGLSurfaceView) findViewById(R.id.myGLSurfaceView); mCameraView.presetCameraForward(false); SeekBar seekBar = (SeekBar) findViewById(R.id.globalRestoreSeekBar); takePicBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showText("Taking Picture..."); mCameraView.takePicture(new CameraRecordGLSurfaceView.TakePictureCallback() { @Override public void takePictureOK(Bitmap bmp) { if (bmp != null) { String s = ImageUtil.saveBitmap(bmp); bmp.recycle(); showText("Take picture success!"); sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + s))); } else showText("Take picture failed!"); } }, null, mCurrentConfig, 1.0f, true); } }); takeShotBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showText("Taking Shot..."); mCameraView.takeShot(new CameraRecordGLSurfaceView.TakePictureCallback() { @Override public void takePictureOK(Bitmap bmp) { if (bmp != null) { String s = ImageUtil.saveBitmap(bmp); bmp.recycle(); showText("Take Shot success!"); sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + s))); } else showText("Take Shot failed!"); } }); } }); recordBtn.setOnClickListener(new RecordListener()); LinearLayout layout = (LinearLayout) findViewById(R.id.menuLinearLayout); for (int i = 0; i != MainActivity.EFFECT_CONFIGS.length; ++i) { MyButtons button = new MyButtons(this, MainActivity.EFFECT_CONFIGS[i]); button.setAllCaps(false); if (i == 0) button.setText("None"); else button.setText("Filter" + i); button.setOnClickListener(mFilterSwitchListener); layout.addView(button); } seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { float intensity = progress / 100.0f; mCameraView.setFilterIntensity(intensity); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); mCurrentInstance = this; Button switchBtn = (Button) findViewById(R.id.switchCameraBtn); switchBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCameraView.switchCamera(); } }); Button flashBtn = (Button) findViewById(R.id.flashBtn); flashBtn.setOnClickListener(new View.OnClickListener() { int flashIndex = 0; String[] flashModes = { Camera.Parameters.FLASH_MODE_AUTO, Camera.Parameters.FLASH_MODE_ON, Camera.Parameters.FLASH_MODE_OFF, Camera.Parameters.FLASH_MODE_TORCH, Camera.Parameters.FLASH_MODE_RED_EYE, }; @Override public void onClick(View v) { mCameraView.setFlashLightMode(flashModes[flashIndex]); ++flashIndex; flashIndex %= flashModes.length; } }); //Recording video size // mCameraView.presetRecordingSize(480, 640); mCameraView.presetRecordingSize(1080, 1920); //Taking picture size. mCameraView.setPictureSize(2048, 2048, true); // > 4MP mCameraView.setZOrderOnTop(false); mCameraView.setZOrderMediaOverlay(true); mCameraView.setOnCreateCallback(new CameraRecordGLSurfaceView.OnCreateCallback() { @Override public void createOver() { Log.i(LOG_TAG, "view onCreate"); } }); Button pauseBtn = (Button) findViewById(R.id.pauseBtn); Button resumeBtn = (Button) findViewById(R.id.resumeBtn); pauseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCameraView.stopPreview(); } }); resumeBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCameraView.resumePreview(); } }); Button fitViewBtn = (Button) findViewById(R.id.fitViewBtn); fitViewBtn.setOnClickListener(new View.OnClickListener() { boolean shouldFit = false; @Override public void onClick(View v) { shouldFit = !shouldFit; mCameraView.setFitFullView(shouldFit); } }); mCameraView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, final MotionEvent event) { switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: { Log.i(LOG_TAG, String.format("Tap to focus: %g, %g", event.getX(), event.getY())); final float focusX = event.getX() / mCameraView.getWidth(); final float focusY = event.getY() / mCameraView.getHeight(); mCameraView.focusAtPoint(focusX, focusY, new Camera.AutoFocusCallback() { @Override public void onAutoFocus(boolean success, Camera camera) { if (success) { Log.e(LOG_TAG, String.format("Focus OK, pos: %g, %g", focusX, focusY)); } else { Log.e(LOG_TAG, String.format("Focus failed, pos: %g, %g", focusX, focusY)); mCameraView.cameraInstance().setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO); } } }); } break; default: break; } return true; } }); } private View.OnClickListener mFilterSwitchListener = new View.OnClickListener() { @Override public void onClick(View v) { MyButtons btn = (MyButtons) v; mCameraView.setFilterWithConfig(btn.filterConfig); mCurrentConfig = btn.filterConfig; } }; int customFilterIndex = 0; public void customFilterClicked(View view) { ++customFilterIndex; customFilterIndex %= CGENativeLibrary.cgeGetCustomFilterNum(); mCameraView.queueEvent(new Runnable() { @Override public void run() { long customFilter = CGENativeLibrary.cgeCreateCustomNativeFilter(customFilterIndex, 1.0f, true); mCameraView.getRecorder().setNativeFilter(customFilter); } }); } public void dynamicFilterClicked(View view) { mCameraView.setFilterWithConfig("#unpack @dynamic mf 10 0"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_camera_demo, menu); return true; } @Override public void onDestroy() { super.onDestroy(); } @Override public void onPause() { super.onPause(); CameraInstance.getInstance().stopCamera(); Log.i(LOG_TAG, "activity onPause..."); mCameraView.release(null); mCameraView.onPause(); } @Override public void onResume() { super.onResume(); mCameraView.onResume(); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
wysaid/android-gpuimage-plus
cgeDemo/src/main/java/org/wysaid/cgeDemo/CameraDemoActivity.java
213,325
package examples.tpcc; import javax.sip.*; import javax.sip.address.*; import javax.sip.header.*; import javax.sip.message.*; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.FileAppender; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import java.util.*; import java.io.IOException; import java.text.ParseException; /** * The Click to dial third party call controller flow IV application. * * @author Kathleen McCallum * * <pre> * main () -&gt; init() * init() * createSipStack * createInvite() -&gt; First * processResponse() * if (OK) first * ack() first * createInvite() -&gt; second no SDP * else if (OK) second * ack() -&gt; second * ack() -&gt; first * </pre> * * * */ public class Controller4 implements SipListener { private static SipProvider sipProvider; private static AddressFactory addressFactory; private static MessageFactory messageFactory; private static HeaderFactory headerFactory; private static SipStack sipStack; private ContactHeader contactHeader; private ListeningPoint udpListeningPoint; protected ClientTransaction inviteFirst; protected ClientTransaction inviteSecond; private String currentState; String transport = "udp"; protected static final String usageString = "java " + "examples.ctd.ctdControll \n" + ">>>> is your class path set to the root?"; private Dialog firstDialog; private Dialog secondDialog; private static Logger logger = Logger.getLogger(Controller4.class); private String auser = "AGuy"; private String aSipAddressDomain = "Afirst.com"; private String aDisplayName = "The A first"; private String buser = "BGuy"; private String bSipAddressDomain = "BSecond.com"; private String bDisplayName = "The B second"; private String peerHostPortA = "127.0.0.1:5070"; private String peerHostPortB = "127.0.0.1:5080"; int first = 0, second = 0; private Response secondDialogOK; public void processRequest(RequestEvent requestReceivedEvent) { Request request = requestReceivedEvent.getRequest(); ServerTransaction serverTransactionId = requestReceivedEvent .getServerTransaction(); logger.info("\n\nRequest " + request.getMethod() + " received at " + sipStack.getStackName() + " with server transaction id " + serverTransactionId); // We are the Controller so the only request we get is the BYE. if (request.getMethod().equals(Request.BYE)) processBye(request, serverTransactionId); } public void processBye(Request request, ServerTransaction serverTransactionId) { try { logger.info("Controller4: got a bye ."); if (serverTransactionId == null) { logger.info("Controller4: null TID."); return; } logger.info("Create OK para BYE: "); // 1: OK BYE Response ok = messageFactory.createResponse(Response.OK, request); serverTransactionId.sendResponse(ok); // 2do: BYE for the other side (send a new clientTransaction) logger.info("Send BYE in new clientTransaction"); Dialog secondBye = (Dialog) (serverTransactionId.getDialog() .getApplicationData()); Request requestBye = secondBye.createRequest(Request.BYE); ClientTransaction clientTransaction = null; clientTransaction = sipProvider.getNewClientTransaction(requestBye); secondBye.sendRequest(clientTransaction); } catch (Exception ex) { ex.printStackTrace(); junit.framework.TestCase.fail("Exit JVM"); } } public synchronized void processResponse(ResponseEvent responseReceivedEvent) { logger.info("Got a response"); Response response = (Response) responseReceivedEvent.getResponse(); ClientTransaction tid = responseReceivedEvent.getClientTransaction(); CSeqHeader cseq = (CSeqHeader) response.getHeader(CSeqHeader.NAME); logger.info("Response received : Status Code = " + response.getStatusCode() + " " + cseq); if (tid == null) { logger.info("Stray response -- dropping "); return; } logger.info("transaction state is " + tid.getState()); logger.info("Dialog = " + tid.getDialog()); logger.info("Dialog State is " + tid.getDialog().getState()); try { if (response.getStatusCode() == Response.OK) { if (cseq.getMethod().equals(Request.INVITE)) { if (currentState.equals("first")) { logger.info("processResponse FIRST"); // send ACK this.firstDialog = tid.getDialog(); Request ackRequest = firstDialog.createAck(cseq .getSeqNumber()); logger.info("Sending ACK firtInvite no media"); firstDialog.sendAck(ackRequest); // invite second no SDP // get call-id String callId = ((CallIdHeader) response .getHeader(CallIdHeader.NAME)).getCallId(); // Create second Invite second++; currentState = "second"; Request requestSecond = this.createInvite(currentState, String.valueOf(second), callId, null, peerHostPortB); inviteSecond = sipProvider .getNewClientTransaction(requestSecond); inviteSecond.sendRequest(); logger.info("INVITE second sent:\n" + requestSecond); } else if (currentState.equals("second")) { logger.info("processResponse SECOND"); // get offer of second byte[] content = response.getRawContent(); ContentTypeHeader cth = (ContentTypeHeader) response .getHeader(ContentTypeHeader.NAME); // reinvite First Request reinvite = firstDialog.createRequest(Request.INVITE); reinvite.removeContent(); reinvite.setContent(content, cth); // Re-Invte offer2' ClientTransaction ct = sipProvider .getNewClientTransaction(reinvite); firstDialog.sendRequest(ct); this.secondDialog = tid.getDialog(); this.secondDialogOK = response; logger.info("RE-INVITE sent:\n" + reinvite); currentState = "re-invite"; } else if (currentState.equals("re-invite")) { logger.info("processResponse re-invite"); // send ack CSeqHeader cseq2 = (CSeqHeader) this.secondDialogOK.getHeader(CSeqHeader.NAME); Request ackRequest = secondDialog.createAck(cseq2 .getSeqNumber());// secondDialog.createRequest(Request.ACK); logger.info("Sending ACK second " + secondDialog); secondDialog.sendAck(ackRequest);// secondDialog.sendAck(ackRequest); Request ackRequestFirst = this.firstDialog.createAck( cseq.getSeqNumber()); ackRequestFirst.setContent(response.getContent(), (ContentTypeHeader) (response .getHeader("Content-Type"))); logger.info("Sending ACK first"); firstDialog.sendAck(ackRequestFirst); // save the dialog of the other side, for the bye... firstDialog.setApplicationData(secondDialog); secondDialog.setApplicationData(firstDialog); currentState = "fin"; } } } } catch (Exception ex) { ex.printStackTrace(); junit.framework.TestCase.fail("Exit JVM"); } } public Request createInvite(String headerName, String headerValue, String callerId, String tagVal, String peerHostPort) throws ParseException, InvalidArgumentException { String fromSipAddressDomain = "", toSipAddressDomain = ""; String fromDisplayName = ""; String toDisplayName = ""; String fromVal = "", toVal = ""; if (headerName.equals("first")) { fromVal = auser; fromSipAddressDomain = aSipAddressDomain; fromDisplayName = aDisplayName; toVal = buser; toSipAddressDomain = bSipAddressDomain; toDisplayName = bDisplayName; } else if (headerName.equals("second")) { fromVal = buser; fromSipAddressDomain = bSipAddressDomain; fromDisplayName = bDisplayName; toVal = auser; toSipAddressDomain = aSipAddressDomain; toDisplayName = aDisplayName; } logger.info("CreateInvite "); // create >From Header SipURI fromAddress = addressFactory.createSipURI(fromVal, fromSipAddressDomain); Address fromNameAddress = addressFactory.createAddress(fromAddress); fromNameAddress.setDisplayName(fromDisplayName); FromHeader fromHeader = headerFactory.createFromHeader(fromNameAddress, new Integer((int) (Math.random() * 10000)).toString()); // create To Header SipURI toAddress = addressFactory.createSipURI(toVal, toSipAddressDomain); Address toNameAddress = addressFactory.createAddress(toAddress); toNameAddress.setDisplayName(toDisplayName); ToHeader toHeader = headerFactory.createToHeader(toNameAddress, null); // create Request URI SipURI requestURI = addressFactory.createSipURI(toVal, peerHostPort); // Create ViaHeaders ArrayList viaHeaders = new ArrayList(); ViaHeader viaHeader = headerFactory.createViaHeader("127.0.0.1", sipProvider.getListeningPoint(transport).getPort(), transport, null); viaHeaders.add(viaHeader); // Create a new CallId header CallIdHeader callIdHeader = null; if (callerId == null) { callIdHeader = sipProvider.getNewCallId(); } else { callIdHeader = headerFactory.createCallIdHeader(callerId); } // Create a new Cseq header CSeqHeader cSeqHeader = headerFactory.createCSeqHeader(Long .parseLong(headerValue), Request.INVITE); // Create a new MaxForwardsHeader MaxForwardsHeader maxForwards = headerFactory .createMaxForwardsHeader(70); // Create the request. Request request = messageFactory.createRequest(requestURI, Request.INVITE, callIdHeader, cSeqHeader, fromHeader, toHeader, viaHeaders, maxForwards); // Create contact headers String host = "127.0.0.1"; SipURI contactUrl = addressFactory.createSipURI(fromVal, host); contactUrl.setPort(udpListeningPoint.getPort()); // Create the contact name address. SipURI contactURI = addressFactory.createSipURI(fromVal, host); contactURI.setPort(sipProvider.getListeningPoint(transport).getPort()); Address contactAddress = addressFactory.createAddress(contactURI); // Add the contact address. contactAddress.setDisplayName(fromVal); contactHeader = headerFactory.createContactHeader(contactAddress); request.addHeader(contactHeader); // Allow header. With PUBLISH, to indicate that we'd like to have an // server-sided PA String methods = Request.INVITE + ", " + Request.ACK + ", " + Request.OPTIONS + ", " + Request.CANCEL + ", " + Request.BYE + ", " + Request.INFO + ", " + Request.REFER + ", " + Request.MESSAGE + ", " + Request.NOTIFY + ", " + Request.SUBSCRIBE; AllowHeader allowHeader = headerFactory.createAllowHeader(methods); request.addHeader(allowHeader); return request; } public void init() throws IOException { SipFactory sipFactory = null; sipStack = null; sipFactory = SipFactory.getInstance(); sipFactory.setPathName("gov.nist"); Properties properties = new Properties(); // This one is optional so I remove it, since I will call 2 parts // properties.setProperty("javax.sip.OUTBOUND_PROXY", peerHostPort + "/" // + transport); properties.setProperty("javax.sip.STACK_NAME", "Controller"); properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", "controllerdebug.txt"); properties.setProperty("gov.nist.javax.sip.SERVER_LOG", "controllerlog.txt"); properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "DEBUG"); properties.setProperty("gov.nist.javax.sip.LOG_MESSAGE_CONTENT", "true"); logger.addAppender(new ConsoleAppender(new SimpleLayout())); logger.addAppender(new FileAppender(new SimpleLayout(), "controllerconsolelog.txt")); try { sipStack = sipFactory.createSipStack(properties); logger.info("createSipStack " + sipStack); headerFactory = sipFactory.createHeaderFactory(); addressFactory = sipFactory.createAddressFactory(); messageFactory = sipFactory.createMessageFactory(); udpListeningPoint = sipStack.createListeningPoint("127.0.0.1", 5050, "udp"); sipProvider = sipStack.createSipProvider(udpListeningPoint); Controller4 listener = this; sipProvider.addSipListener(listener); } catch (PeerUnavailableException e) { e.printStackTrace(); System.err.println(e.getMessage()); junit.framework.TestCase.fail("Exit JVM"); } catch (Exception e) { logger.info("Creating Listener Points"); logger.info(e.getMessage()); e.printStackTrace(); } try { logger.info("ProcessCTD "); first++; this.currentState = "first"; Request request = this.createInvite(currentState, String .valueOf(first), null, null, peerHostPortA); // Create ContentTypeHeader, !no media type! ContentTypeHeader contentTypeHeader = headerFactory .createContentTypeHeader("application", "sdp"); String sdpData = "v=0\r\n" + "o=4855 13760799956958020 13760799956958020" + " IN IP4 129.6.55.78\r\n" + "s=mysession session\r\n" + "p=+46 8 52018010\r\n" + "c=IN IP4 129.6.55.78\r\n" + "t=0 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:4 G723/8000\r\n" + "a=rtpmap:18 G729A/8000\r\n" + "a=ptime:20\r\n"; byte[] contents = sdpData.getBytes(); request.setContent(contents, contentTypeHeader); // Create the client transaction. inviteFirst = sipProvider.getNewClientTransaction(request); // send the request out. inviteFirst.sendRequest(); logger.info("INVITE first sent:\n" + request); } catch (Exception e) { logger.info("Creating call CreateInvite()"); logger.info(e.getMessage()); e.printStackTrace(); } } public static void main(String args[]) throws Exception { new Controller4().init(); } public void processTimeout(javax.sip.TimeoutEvent timeoutEvent) { logger.info("Transaction Time out"); } public void processIOException(IOExceptionEvent exceptionEvent) { logger.info("IOException happened for " + exceptionEvent.getHost() + " port = " + exceptionEvent.getPort()); } public void processTransactionTerminated( TransactionTerminatedEvent transactionTerminatedEvent) { logger.info("Transaction terminated event recieved"); } public void processDialogTerminated( DialogTerminatedEvent dialogTerminatedEvent) { logger.info("dialogTerminatedEvent"); } }
RestComm/jain-sip
src/examples/tpcc/Controller4.java
213,326
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.html.palette.items; import java.awt.Dialog; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.DefaultComboBoxModel; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import org.netbeans.api.project.SourceGroup; import org.netbeans.modules.html.palette.BrowseFolders; import org.netbeans.modules.html.palette.HtmlPaletteUtilities; import org.netbeans.modules.editor.NbEditorUtilities; import org.openide.DialogDescriptor; import org.openide.DialogDisplayer; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.util.NbBundle; /** * * @author Libor Kotouc */ public class ACustomizer extends javax.swing.JPanel { private Dialog dialog = null; private DialogDescriptor descriptor = null; private boolean dialogOK = false; A a; JTextComponent target; public ACustomizer(A a, JTextComponent target) { this.a = a; this.target = target; initComponents(); jComboBox1.setModel(new DefaultComboBoxModel(A.protocols)); jComboBox1.setSelectedIndex(a.getProtocolIndex()); jComboBox2.setModel(new DefaultComboBoxModel(A.targets)); jComboBox2.setSelectedIndex(a.getTargetIndex()); } public boolean showDialog() { dialogOK = false; String displayName = ""; try { displayName = NbBundle.getBundle("org.netbeans.modules.html.palette.items.resources.Bundle").getString("NAME_html-A"); // NOI18N } catch (Exception e) {} descriptor = new DialogDescriptor (this, NbBundle.getMessage(ACustomizer.class, "LBL_Customizer_InsertPrefix") + " " + displayName, true, DialogDescriptor.OK_CANCEL_OPTION, DialogDescriptor.OK_OPTION, new ActionListener() { public void actionPerformed(ActionEvent e) { if (descriptor.getValue().equals(DialogDescriptor.OK_OPTION)) { evaluateInput(); dialogOK = true; } dialog.dispose(); } } ); dialog = DialogDisplayer.getDefault().createDialog(descriptor); dialog.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(ACustomizer.class, "ACSN_A_Dialog")); dialog.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(ACustomizer.class, "ACSD_A_Dialog")); dialog.setVisible(true); repaint(); return dialogOK; } private void evaluateInput() { int protocolIndex = jComboBox1.getSelectedIndex(); a.setProtocolIndex(protocolIndex); String url = jTextField1.getText(); a.setUrl(url); String text = jTextField2.getText(); a.setText(text); int targetIndex = jComboBox2.getSelectedIndex(); a.setTargetIndex(targetIndex); if (targetIndex == -1) // new or no value selected a.setTarget(jComboBox2.getSelectedItem().toString()); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jFileChooser1 = new javax.swing.JFileChooser(); jLabel4 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jTextField2 = new javax.swing.JTextField(); jComboBox1 = new javax.swing.JComboBox(); jComboBox2 = new javax.swing.JComboBox(); jFileChooser1.setCurrentDirectory(null); setLayout(new java.awt.GridBagLayout()); jLabel4.setLabelFor(jComboBox2); org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle.getMessage(ACustomizer.class, "LBL_A_Target")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(12, 12, 12, 0); add(jLabel4, gridBagConstraints); jLabel4.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(ACustomizer.class, "ACSN_A_Target")); // NOI18N jLabel4.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(ACustomizer.class, "ACSD_A_Target")); // NOI18N jTextField1.setColumns(35); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 12, 0, 0); add(jTextField1, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(jButton1, org.openide.util.NbBundle.getMessage(ACustomizer.class, "LBL_A_Browse")); // NOI18N jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 12, 0, 12); add(jButton1, gridBagConstraints); jButton1.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(ACustomizer.class, "ACSN_A_Browse")); // NOI18N jButton1.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(ACustomizer.class, "ACSD_A_Browse")); // NOI18N jLabel1.setLabelFor(jComboBox1); org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(ACustomizer.class, "LBL_A_Protocol")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(12, 12, 0, 0); add(jLabel1, gridBagConstraints); jLabel1.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(ACustomizer.class, "ACSN_A_Protocol")); // NOI18N jLabel1.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(ACustomizer.class, "ACSD_A_Protocol")); // NOI18N jLabel2.setLabelFor(jTextField1); org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(ACustomizer.class, "LBL_A_URL")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 12, 0, 0); add(jLabel2, gridBagConstraints); jLabel2.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(ACustomizer.class, "ACSN_A_URL")); // NOI18N jLabel2.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(ACustomizer.class, "ACSD_A_URL")); // NOI18N jLabel3.setLabelFor(jTextField2); org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(ACustomizer.class, "LBL_A_Text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(12, 12, 0, 0); add(jLabel3, gridBagConstraints); jLabel3.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(ACustomizer.class, "ACSN_A_Text")); // NOI18N jLabel3.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(ACustomizer.class, "ACSD_A_Text")); // NOI18N jTextField2.setColumns(35); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(12, 12, 0, 0); add(jTextField2, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(12, 12, 0, 0); add(jComboBox1, gridBagConstraints); jComboBox2.setEditable(true); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(12, 12, 12, 0); add(jComboBox2, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed Document targetDoc = target.getDocument(); FileObject targetDocFO = NbEditorUtilities.getFileObject(targetDoc); SourceGroup[] sg = HtmlPaletteUtilities.getSourceGroups(targetDocFO); File file = null; if (sg.length > 0) { FileObject fo = BrowseFolders.showDialog(sg); if (fo != null) file = FileUtil.toFile(fo); } else { jFileChooser1.setCurrentDirectory(FileUtil.toFile(targetDocFO.getParent())); int returnVal = jFileChooser1.showOpenDialog(this); if (returnVal == jFileChooser1.APPROVE_OPTION) file = jFileChooser1.getSelectedFile(); } if (file != null) { String path = file.getAbsolutePath(); FileObject aFO = FileUtil.toFileObject(file); try { String relPathToFile = HtmlPaletteUtilities.getRelativePath(targetDocFO, aFO); if (relPathToFile.length() > 0) path = relPathToFile; } catch (Exception e) { //eventual exceptions imply the absolute path to be used } jTextField1.setText(path); } }//GEN-LAST:event_jButton1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JComboBox jComboBox1; private javax.swing.JComboBox jComboBox2; private javax.swing.JFileChooser jFileChooser1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; // End of variables declaration//GEN-END:variables }
apache/netbeans
ide/html/src/org/netbeans/modules/html/palette/items/ACustomizer.java
213,327
package com.ilscipio.scipio.solr; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.transaction.Transaction; import org.apache.solr.client.solrj.SolrRequest; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.client.solrj.request.SolrPing; import org.apache.solr.client.solrj.response.SolrPingResponse; import org.ofbiz.base.component.ComponentConfig; import org.ofbiz.base.component.ComponentConfig.WebappInfo; import org.ofbiz.base.component.ComponentException; import org.ofbiz.base.start.Start; import org.ofbiz.base.start.Start.ServerState; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilProperties; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.catalina.container.ScipioConnectorInfo; import org.ofbiz.entity.Delegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.transaction.GenericTransactionException; import org.ofbiz.entity.transaction.TransactionUtil; import org.ofbiz.entity.util.EntityQuery; import org.ofbiz.entity.util.EntityUtilProperties; import com.ilscipio.scipio.solr.util.ScipioHttpSolrClient; /** * Generic Solr utility class, and helpers to get HttpSolrClient for the Scipio Solr instance. */ public abstract class SolrUtil { private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass()); public static final String solrConfigName = "solrconfig"; public static final boolean DEBUG = UtilProperties.getPropertyAsBoolean("solr", "solr.debug", false) || UtilValidate.booleanValueVersatile(System.getProperty("scipio.solr.debug"), false); // SCIPIO private static final Boolean solrEnabledSysProp = getSolrSysPropBool("enabled", null); private static final boolean solrEnabledCfg = getSolrCfgBool("enabled", true); private static final boolean solrEnabled = (solrEnabledSysProp != null) ? solrEnabledSysProp : solrEnabledCfg; private static final Boolean solrEcaEnabledSysProp = getSolrSysPropBool("eca.enabled", null); private static final boolean solrEcaEnabledCfg = getSolrCfgBool("eca.enabled", false); private static final Boolean solrWebappCheckEnabledSysProp = getSolrSysPropBool("eca.useSolrWebappLoadedCheck", null); private static final boolean solrWebappCheckEnabledCfg = getSolrCfgBool("eca.useSolrWebappLoadedCheck", true); private static final boolean solrWebappCheckEnabled = (solrWebappCheckEnabledSysProp != null) ? solrWebappCheckEnabledSysProp : solrWebappCheckEnabledCfg; private static final String solrWebappProtocol = UtilProperties.getPropertyValue(solrConfigName, "solr.webapp.protocol"); private static final String solrWebappHost = UtilProperties.getPropertyValue(solrConfigName, "solr.webapp.domainName"); private static final Integer solrWebappPort = readSolrWebappPort(); private static final String solrWebappPath = UtilProperties.getPropertyValue(solrConfigName, "solr.webapp.path", "/solr"); private static final String solrWebappServer = UtilProperties.getPropertyValue(solrConfigName, "solr.webapp.server", "default-server"); private static final String solrDefaultCore = UtilProperties.getPropertyValue(solrConfigName, "solr.core.default"); private static final String effectiveConfigVersion = determineSolrConfigVersion( UtilProperties.getPropertyValue(solrConfigName, "solr.config.version"), UtilProperties.getPropertyValue(solrConfigName, "solr.config.version.custom"), UtilProperties.getPropertyValue(solrConfigName, "solr.config.version.extra")); /** * @deprecated use {@link #getSolrWebappUrl} instead. */ @Deprecated public static final String solrUrl = makeSolrWebappUrl(); /** * @deprecated use {@link #getSolrDefaultCoreUrl} instead. */ @Deprecated public static final String solrFullUrl = makeSolrDefaultCoreUrl(); public static String getSolrConfigName() { return solrConfigName; } /** * Returns the EFFECTIVE Solr config version, which is a combination * of the solrconfig.properties values * <code>solr.config.version</code>, * <code>solr.config.version.custom</code> and * <code>solr.config.version.extra</code>. */ public static String getSolrConfigVersionStatic() { return effectiveConfigVersion; } public static String determineSolrConfigVersion(String baseVersion, String customVersion, String extraVersion) { String version = baseVersion; if (UtilValidate.isNotEmpty(customVersion)) { version = customVersion; } if (UtilValidate.isNotEmpty(extraVersion)) { if (extraVersion.startsWith(".")) version += extraVersion; else version += "." + extraVersion; } return version; } public static String getSolrDefaultCore() { return solrDefaultCore; } public static String getSolrWebappProtocol() { return solrWebappProtocol; } public static String getSolrWebappHost() { return solrWebappHost; } public static int getSolrWebappPort() { return solrWebappPort; } private static int readSolrWebappPort() { Integer solrPort = UtilProperties.getPropertyAsInteger(solrConfigName, "solr.webapp.portOverride", null); if (solrPort != null) { return solrPort; } solrPort = LocalUrlUtil.getWebappContainerPort(solrWebappProtocol); if (solrPort != null) { return solrPort; } solrPort = LocalUrlUtil.getStandardPort(solrWebappProtocol); Debug.logWarning("Solr: Could not determine a solr webapp port from " + solrConfigName + " or webapp container; using default: " + solrPort, module); return solrPort; } public static boolean isSolrWebappLocal() { if (!LocalUrlUtil.isLocalhost(getSolrWebappHost())) { return false; } return LocalUrlUtil.isWebappContainerPort(getSolrWebappPort()); } public static String getSolrWebappPath() { return solrWebappPath; } public static String getSolrWebappUrl() { return solrUrl; } private static String makeSolrWebappUrl() { StringBuilder sb = new StringBuilder(); sb.append(getSolrWebappProtocol()); sb.append("://"); sb.append(getSolrWebappHost()); if (!LocalUrlUtil.isStandardPort(getSolrWebappPort(), getSolrWebappProtocol())) { sb.append(":"); sb.append(getSolrWebappPort()); } sb.append(getSolrWebappPath()); if (sb.charAt(sb.length() - 1) == '/') { sb.setLength(sb.length() - 1); } Debug.logInfo("Solr: Determined Solr webapp URL: " + sb.toString(), module); return sb.toString(); } public static String getSolrCoreUrl(String core) { return getSolrWebappUrl() + "/" + core; } public static String getSolrDefaultCoreUrl() { return solrFullUrl; } private static String makeSolrDefaultCoreUrl() { return getSolrCoreUrl(solrDefaultCore); } /** * @deprecated bad name; use {@link #getSolrDefaultCoreUrl()} instead. */ @Deprecated public static String makeFullSolrWebappUrl() { return makeSolrDefaultCoreUrl(); } public static WebappInfo getSolrWebappInfo() { WebappInfo solrApp = null; try { ComponentConfig cc = ComponentConfig.getComponentConfig("solr"); for(WebappInfo currApp : cc.getWebappInfos()) { if ("solr".equals(currApp.getName())) { solrApp = currApp; break; } } } catch(ComponentException e) { throw new IllegalStateException(e); } return solrApp; } private static Boolean getSolrSysPropBool(String name, Boolean defaultValue) { Boolean value = UtilMisc.booleanValueVersatile(System.getProperty("scipio.solr."+name)); if (value == null) { value = UtilMisc.booleanValueVersatile(System.getProperty("ofbiz.solr."+name)); } return (value != null) ? value : defaultValue; } private static Boolean getSolrCfgBool(String name, Boolean defaultValue) { return UtilProperties.getPropertyAsBoolean(SolrUtil.solrConfigName, "solr."+name, defaultValue); } public static boolean isSolrEnabled() { return solrEnabled; } public static boolean isSolrEcaEnabled(Delegator delegator) { if (solrEcaEnabledSysProp != null) { return solrEcaEnabledSysProp; } Boolean ecaEnabled = getSolrEcaEnabledEntityProperty(delegator); return (ecaEnabled != null) ? ecaEnabled : solrEcaEnabledCfg; } public static Boolean getSolrEcaEnabledEntityProperty(Delegator delegator) { // Need without the fallback (special case) //return EntityUtilProperties.getPropertyAsBoolean(solrConfigName, "solr.eca.enabled", null, delegator); return UtilProperties.asBoolean(EntityUtilProperties.getEntityPropertyValueOrNull(solrConfigName, "solr.eca.enabled", delegator)); } /** * @deprecated Use {@link #getSolrEcaEnabledEntityProperty}. */ @Deprecated public static String getSolrEcaEnabledSystemProperty(Delegator delegator) { return EntityUtilProperties.getEntityPropertyValueOrNull(solrConfigName, "solr.eca.enabled", delegator); } /** * Checks if solr is enabled and scipio is initialized for solr and the system/server * is in a running state in which queries may be attempted against the solr webapp. * <p> * NOTE: true does NOT mean that solr webapp is fully loaded and pingable, * because the webapp may be remote and such a check must be done physically using * waitSolrReady service, {@link #isSolrWebappPingOk(HttpSolrClient)} or {@link #isSolrWebappReady(HttpSolrClient)}. */ public static boolean isSystemInitialized() { return isSolrEnabled() && (Start.getInstance().getCurrentState() == ServerState.RUNNING); } /** * Same as {@link #isSystemInitialized()} but assumes solr is enabled. */ public static boolean isSystemInitializedAssumeEnabled() { return (Start.getInstance().getCurrentState() == ServerState.RUNNING); } /** * Returns true if the LOCAL Solr webapp has reached initialization. */ public static boolean isSolrLocalWebappStarted() { return ScipioSolrInfoServlet.isServletInitStatusReached(); } /** * Returns true if the LOCAL Solr webapp is initialized. * @deprecated 2018-05-25: ambiguous; use {@link #isSystemInitialized()} or {@link #isSolrLocalWebappStarted()}. */ @Deprecated public static boolean isSolrWebappInitialized() { return isSolrLocalWebappStarted(); } /** * If the solr webapp/initialization check if enabled in config, * returns {@link #isSystemInitialized()}, otherwise returns true. */ public static boolean isSolrEcaWebappInitCheckPassed() { return (solrWebappCheckEnabled) ? isSystemInitialized() : true; } public static boolean isEcaTreatConnectErrorNonFatal() { Boolean treatConnectErrorNonFatal = UtilProperties.getPropertyAsBoolean(solrConfigName, "solr.eca.treatConnectErrorNonFatal", true); return Boolean.TRUE.equals(treatConnectErrorNonFatal); } /** * Returns true if the LOCAL Solr webapp is present in the system (by context root), * as defined in applications/solr/scipio-component.xml. * <p> * For stock Scipio configuration, this always returns true. * It only returns false if the webapp is disabled/commented in scipio-component.xml. * <p> * WARN: Do not call this before or while components are being read. */ public static boolean isSolrLocalWebappPresent() { return (ComponentConfig.getWebAppInfo(solrWebappServer, solrWebappPath) != null); } /** * Returns true if the LOCAL Solr webapp is present in the system (by context root). * @deprecated 2018-05-25: ambiguous; use {@link #isSystemInitialized()} or {@link #isSolrLocalWebappPresent()}. */ @Deprecated public static boolean isSolrWebappPresent() { return isSolrLocalWebappPresent(); } /** * Returns true if the LOCAL Solr webapp is present in the system (by context root) and running state. * @deprecated 2018-05-25: ambiguous; use {@link #isSystemInitialized()} or {@link #isSolrLocalWebappPresent()}. */ @Deprecated public static boolean isSolrWebappEnabled() { return isSolrEnabled() && isSolrLocalWebappPresent(); } public static boolean isSolrWebappPingOk(HttpSolrClient client) throws Exception { try { return isSolrWebappPingOkRaw(client); } catch(Exception e) { // FIXME: we are not supposed to catch this, but in current setup with Tomcat // solr can't handle the incomplete loading 503 and throws exception, so have no choice // but because this is only a Ping, we can usually assume this means not yet loaded... // NOTE: This case also occurs currently if connect/socket timeout Debug.logInfo("Solr: isSolrWebappPingOk: Solr webapp not pingable. Cause: " + e.toString(), module); return false; } } public static boolean isSolrWebappPingOkRaw(HttpSolrClient client) throws Exception { SolrPing solrPing = new SolrPing(); SolrPingResponse rsp = solrPing.process(client); int status = rsp.getStatus(); if (status == 0) { if (Debug.verboseOn()) Debug.logVerbose("isSolrWebappPingOk: ping response status: " + status, module); return true; } else { Debug.logInfo("Solr: isSolrWebappPingOk: Solr webapp not pingable; status: " + status, module); return false; } } /** * Returns true if Solr is loaded and available for queries. */ public static boolean isSolrWebappReady(HttpSolrClient client) throws Exception { return isSystemInitialized() && isSolrWebappPingOk(client); } /** * Returns true if Solr is loaded and available for queries, using default core and client. */ public static boolean isSolrWebappReady() throws Exception { return isSolrWebappReady(getQueryHttpSolrClient(null)); } public static boolean isSolrWebappReadyRaw(HttpSolrClient client) throws Exception { return isSystemInitialized() && isSolrWebappPingOkRaw(client); } public static boolean isSolrWebappReadyRaw() throws Exception { return isSolrWebappReadyRaw(getQueryHttpSolrClient(null)); } /** * Returns the SolrStatus data status from DB. NOTE: useCache=true should usually not be used. */ public static GenericValue getSolrStatus(Delegator delegator, boolean useCache) { GenericValue solrStatus; try { solrStatus = EntityQuery.use(delegator).from("SolrStatus") .where("solrId", "SOLR-MAIN").cache(useCache).queryOne(); if (solrStatus == null) { Debug.logWarning("Could not get SolrStatus for SOLR-MAIN - seed data missing?", module); } else { return solrStatus; } } catch (GenericEntityException e) { Debug.logError(e, module); } return null; } public static GenericValue getSolrStatus(Delegator delegator) { return getSolrStatus(delegator, false); } /** * Returns the SolrStatus data status ID from DB. NOTE: useCache=true should usually not be used. */ public static String getSolrDataStatusId(Delegator delegator, boolean useCache) { GenericValue solrStatus = getSolrStatus(delegator, useCache); return solrStatus != null ? solrStatus.getString("dataStatusId") : null; } public static String getSolrDataStatusId(Delegator delegator) { return getSolrDataStatusId(delegator, false); } public static void setSolrDataStatusId(Delegator delegator, String dataStatusId, boolean updateVersion) throws GenericEntityException { GenericValue solrStatus = EntityQuery.use(delegator).from("SolrStatus") .where("solrId", "SOLR-MAIN").cache(false).queryOne(); //solrStatus = delegator.findOne("SolrStatus", UtilMisc.toMap("solrId", "SOLR-MAIN"), false); if (solrStatus == null) { Debug.logWarning("Could not get SolrStatus for SOLR-MAIN - creating new", module); solrStatus = delegator.create("SolrStatus", "solrId", "SOLR-MAIN", "dataStatusId", dataStatusId, "dataCfgVersion", getSolrConfigVersionStatic()); } else { solrStatus.setString("dataStatusId", dataStatusId); if (updateVersion) { solrStatus.setString("dataCfgVersion", getSolrConfigVersionStatic()); } solrStatus.store(); } } public static void setSolrDataStatusIdSafe(Delegator delegator, String dataStatusId, boolean updateVersion) { try { setSolrDataStatusId(delegator, dataStatusId, updateVersion); } catch (Exception t) { final String errMsg = "Error while trying to mark Solr data status (" + dataStatusId + "): " + t.getMessage(); Debug.logError(t, "Solr: " + errMsg, module); } } public static void setSolrDataStatusId(Delegator delegator, String dataStatusId) throws GenericEntityException { setSolrDataStatusId(delegator, dataStatusId, false); } // DEV NOTE: could have done this with service call, but just in case need fine-grained control... public static boolean setSolrDataStatusIdSepTxSafe(Delegator delegator, String dataStatusId, boolean updateVersion) { Transaction parentTransaction = null; boolean beganTrans = false; try { try { if (TransactionUtil.isTransactionInPlace()) { parentTransaction = TransactionUtil.suspend(); // now start a new transaction beganTrans = TransactionUtil.begin(); } else { beganTrans = TransactionUtil.begin(); } } catch (GenericTransactionException t) { Debug.logError(t, "Solr: Cannot create transaction to mark Solr data status (" + dataStatusId + ")", module); } try { SolrUtil.setSolrDataStatusId(delegator, dataStatusId, updateVersion); return true; } catch (Throwable t) { final String errMsg = "Error while trying to mark Solr data status (" + dataStatusId + "): " + t.getMessage(); Debug.logError(t, "Solr: " + errMsg, module); try { TransactionUtil.rollback(beganTrans, errMsg, t); } catch (GenericTransactionException te) { Debug.logError(te, "Solr: Cannot rollback transaction to mark Solr data status (" + dataStatusId + ")", module); } } finally { try { TransactionUtil.commit(beganTrans); } catch (GenericTransactionException e) { Debug.logError(e, "Solr: Could not commit transaction to mark Solr data status (" + dataStatusId + ")", module); } } } finally { if (parentTransaction != null) { try { TransactionUtil.resume(parentTransaction); } catch (GenericTransactionException t) { Debug.logError(t, "Solr: Error resuming parent transaction after marking Solr data status (" + dataStatusId + ")", module); } } } return false; } /** * Returns a Solr client for making read-only queries, for given core or default core (if null). * <p> * Supports explicit solr basic auth username/password, if not empty; otherwise * includes the basic auth defined in solrconfig.properties/solr.query.login.*, * which can be further overridden on individual requests (using QueryRequest). */ public static HttpSolrClient getQueryHttpSolrClient(String core, String solrUsername, String solrPassword) { return SolrClientFactory.queryClientFactory.getClientForCore(core, solrUsername, solrPassword); } /** * Returns a Solr client for making read-only queries, for given core or default core (if null). * <p> * This client includes the basic auth defined in solrconfig.properties/solr.query.login.*, * which can be overridden on individual requests (using QueryRequest). */ public static HttpSolrClient getQueryHttpSolrClient(String core) { return SolrClientFactory.queryClientFactory.getClientForCore(core, null, null); } public static HttpSolrClient getQueryHttpSolrClientFromUrl(String url, String solrUsername, String solrPassword) { return SolrClientFactory.queryClientFactory.getClientFromUrl(url, solrUsername, solrPassword); } public static HttpSolrClient getQueryHttpSolrClientFromUrl(String url) { return SolrClientFactory.queryClientFactory.getClientFromUrl(url, null, null); } /** * Returns a Solr client for making update/indexing queries, for given core or default core (if null). * <p> * Supports explicit solr basic auth username/password, if not empty; otherwise * includes the basic auth defined in solrconfig.properties/solr.update.login.*, * which can be further overridden on individual requests (using QueryRequest). */ public static HttpSolrClient getUpdateHttpSolrClient(String core, String solrUsername, String solrPassword) { return SolrClientFactory.updateClientFactory.getClientForCore(core, solrUsername, solrPassword); } /** * Returns a Solr client for making update/indexing queries, for given core or default core (if null). * <p> * This client includes the basic auth defined in solrconfig.properties/solr.update.login.*, * which can be overridden on individual requests (using UpdateRequest). */ public static HttpSolrClient getUpdateHttpSolrClient(String core) { return SolrClientFactory.updateClientFactory.getClientForCore(core, null, null); } public static HttpSolrClient getUpdateHttpSolrClientFromUrl(String url, String solrUsername, String solrPassword) { return SolrClientFactory.updateClientFactory.getClientFromUrl(url, solrUsername, solrPassword); } public static HttpSolrClient getUpdateHttpSolrClientFromUrl(String url) { return SolrClientFactory.updateClientFactory.getClientFromUrl(url, null, null); } /** * Returns a Solr client for making admin queries, for given core or default core (if null). * <p> * Supports explicit solr basic auth username/password, if not empty; otherwise * includes the basic auth defined in solrconfig.properties/solr.admin.login.*, * which can be further overridden on individual requests. */ public static HttpSolrClient getAdminHttpSolrClient(String core, String solrUsername, String solrPassword) { return SolrClientFactory.adminClientFactory.getClientForCore(core, solrUsername, solrPassword); } /** * Returns a Solr client for making admin queries, for given core or default core (if null). * <p> * This client includes the basic auth defined in solrconfig.properties/solr.admin.login.*, * which can be overridden on individual requests. */ public static HttpSolrClient getAdminHttpSolrClient(String core) { return SolrClientFactory.adminClientFactory.getClientForCore(core, null, null); } public static HttpSolrClient getAdminHttpSolrClientFromUrl(String url, String solrUsername, String solrPassword) { return SolrClientFactory.adminClientFactory.getClientFromUrl(url, solrUsername, solrPassword); } public static HttpSolrClient getAdminHttpSolrClientFromUrl(String url) { return SolrClientFactory.adminClientFactory.getClientFromUrl(url, null, null); } /** * Returns a Solr client for making read-only queries. * @deprecated 2018-04-17: now ambiguous; use {@link #getQueryHttpSolrClient(String) instead */ @Deprecated public static HttpSolrClient getHttpSolrClient(String core) { return getQueryHttpSolrClient(core); } /** * Returns a Solr client for making read-only queries. * @deprecated 2018-04-17: now ambiguous; use {@link #getQueryHttpSolrClient(String) instead */ @Deprecated public static HttpSolrClient getHttpSolrClient() { return getQueryHttpSolrClient(null); } /** * Returns a new Solr client for making read-only queries. * @deprecated 2018-04-27: now ambiguous; use {@link #makeQueryHttpSolrClientFromUrl} or other instead */ @Deprecated public static HttpSolrClient makeHttpSolrClientFromUrl(String url) { // use query username/password for backward compat, but this is not guaranteed to work return makeQueryHttpSolrClientFromUrl(url, getSolrQueryConnectConfig().getSolrUsername(), getSolrQueryConnectConfig().getSolrPassword()); } public static HttpSolrClient makeQueryHttpSolrClientFromUrl(String url, String solrUsername, String solrPassword) { return SolrClientFactory.NewSolrClientFactory.newQueryClientFactory.getClientFromUrl(url, solrUsername, solrPassword); } public static HttpSolrClient makeUpdateHttpSolrClientFromUrl(String url, String solrUsername, String solrPassword) { return SolrClientFactory.NewSolrClientFactory.newUpdateClientFactory.getClientFromUrl(url, solrUsername, solrPassword); } public static HttpSolrClient makeAdminHttpSolrClientFromUrl(String url, String solrUsername, String solrPassword) { return SolrClientFactory.NewSolrClientFactory.newAdminClientFactory.getClientFromUrl(url, solrUsername, solrPassword); } static SolrConnectConfig getSolrQueryConnectConfig() { return SolrConnectConfig.queryConnectConfig; } static SolrConnectConfig getSolrUpdateConnectConfig() { return SolrConnectConfig.updateConnectConfig; } static SolrConnectConfig getSolrAdminConnectConfig() { return SolrConnectConfig.adminConnectConfig; } public enum SolrClientMode { QUERY("query"), UPDATE("update"), ADMIN("admin"); private final String name; private SolrClientMode(String name) { this.name = name; } public String getName() { return name; } } public static class SolrConnectConfig { private static final SolrConnectConfig queryConnectConfig = SolrConnectConfig.fromProperties(SolrClientMode.QUERY, solrConfigName, "solr.query.connect."); private static final SolrConnectConfig updateConnectConfig = SolrConnectConfig.fromProperties(SolrClientMode.UPDATE, solrConfigName, "solr.update.connect."); private static final SolrConnectConfig adminConnectConfig = SolrConnectConfig.fromProperties(SolrClientMode.ADMIN, solrConfigName, "solr.admin.connect."); private final SolrClientMode clientMode; private final String solrUsername; private final String solrPassword; private final boolean reuseClient; private final Integer connectTimeout; private final Integer socketTimeout; //private final Boolean noDelay; // TODO: FLAG NOT IMPLEMENTED (client building issue) private final Integer maxConnections; private final Integer maxConnectionsPerHost; public SolrConnectConfig(SolrClientMode clientMode, Map<String, ?> configMap) { this.clientMode = clientMode; this.solrUsername = UtilProperties.valueOrNull((String) configMap.get("login.username")); this.solrPassword = UtilProperties.valueOrNull((String) configMap.get("login.password")); this.reuseClient = UtilProperties.asBoolean(configMap.get("reuseClient"), false); this.connectTimeout = UtilProperties.asInteger(configMap.get("connectTimeout")); this.socketTimeout = UtilProperties.asInteger(configMap.get("socketTimeout")); //this.noDelay = UtilProperties.asBoolean(configMap.get("noDelay")); // NOTE: Defaults are based on Solr 7 (not 6) - see org.apache.solr.client.solrj.impl.HttpClientUtil source // For Solr 6, the defaults were 128 and 32, respectively this.maxConnections = UtilProperties.asInteger(configMap.get("maxConnections"), 10000); this.maxConnectionsPerHost = UtilProperties.asInteger(configMap.get("maxConnectionsPerHost"), 10000); } public static SolrConnectConfig fromProperties(SolrClientMode clientMode, String resource, String prefix) { return new SolrConnectConfig(clientMode, UtilProperties.getPropertiesWithPrefix(UtilProperties.getProperties(resource), prefix)); } public SolrClientMode getClientMode() { return clientMode; } public String getSolrUsername() { return solrUsername; } public String getSolrPassword() { return solrPassword; } public boolean isReuseClient() { return reuseClient; } public String getSolrCore() { return SolrUtil.getSolrDefaultCore(); } public String getSolrCoreUrl() { return SolrUtil.getSolrDefaultCoreUrl(); } public Integer getConnectTimeout() { return connectTimeout; } public Integer getSocketTimeout() { return socketTimeout; } //public Boolean getNoDelay() { return noDelay; } public Integer getMaxConnections() { return maxConnections; } public Integer getMaxConnectionsPerHost() { return maxConnectionsPerHost; } /** * Sets basic Solr auth on the given request. * <p> * NOTE: 2018-04-17: This should largely not be needed now; it should be * already handled in ScipioHttpSolrClient returned by {@link #getQueryHttpSolrClient}, * although doing it in double here on the SolrRequest will not cause any problems. */ public void setSolrRequestAuth(SolrRequest<?> req, String solrUsername, String solrPassword) { if (solrUsername == null) { solrUsername = this.getSolrUsername(); solrPassword = this.getSolrPassword(); } if (solrUsername != null) { req.setBasicAuthCredentials(solrUsername, solrPassword); } } public void setSolrRequestAuth(SolrRequest<?> req) { String solrUsername = this.getSolrUsername(); if (solrUsername != null) { String solrPassword = this.getSolrPassword(); req.setBasicAuthCredentials(solrUsername, solrPassword); } } private String makeClientLogDesc(String url, String solrUsername) { return getClientMode().getName() + " client: " + (solrUsername != null ? solrUsername + "@" : "") + url + (connectTimeout != null ? " (timeout: " + connectTimeout + ")" : "") + (socketTimeout != null ? " (sotimeout: " + socketTimeout + ")" : "") + (maxConnections != null ? " (maxconn: " + maxConnections + ")" : "") + (maxConnectionsPerHost != null ? " (hostmaxconn: " + maxConnectionsPerHost + ")" : ""); } } private static abstract class SolrClientFactory { /** * Abstracted factory that gets a cached or new client. */ static final SolrClientFactory queryClientFactory = create(SolrConnectConfig.queryConnectConfig); static final SolrClientFactory updateClientFactory = create(SolrConnectConfig.updateConnectConfig); static final SolrClientFactory adminClientFactory = create(SolrConnectConfig.adminConnectConfig); public static SolrClientFactory create(SolrConnectConfig connectConfig) { if (connectConfig.isReuseClient()) return CachedSolrClientFactory.create(connectConfig); else return NewSolrClientFactory.create(connectConfig); } public abstract HttpSolrClient getClientFromUrlRaw(String url, String solrUsername, String solrPassword); public HttpSolrClient getClientFromUrl(String url, String solrUsername, String solrPassword) { if (UtilValidate.isEmpty(solrUsername)) { solrUsername = getConnectConfig().getSolrUsername(); solrPassword = getConnectConfig().getSolrPassword(); } else if ("_none_".equals(solrUsername)) { solrUsername = null; solrPassword = null; } return getClientFromUrlRaw(url, solrUsername, solrPassword); } public HttpSolrClient getClientForCore(String core, String solrUsername, String solrPassword) { if (UtilValidate.isEmpty(solrUsername)) { solrUsername = getConnectConfig().getSolrUsername(); solrPassword = getConnectConfig().getSolrPassword(); } else if ("_none_".equals(solrUsername)) { solrUsername = null; solrPassword = null; } if (UtilValidate.isNotEmpty(core)) { return getClientFromUrlRaw(getSolrCoreUrl(core), solrUsername, solrPassword); } else { return getClientFromUrlRaw(getSolrDefaultCoreUrl(), solrUsername, solrPassword); } } public abstract SolrConnectConfig getConnectConfig(); static class NewSolrClientFactory extends SolrClientFactory { private final SolrConnectConfig connectConfig; /** * Factory that always creates a new client. */ static final SolrClientFactory newQueryClientFactory = NewSolrClientFactory.create(SolrConnectConfig.queryConnectConfig); static final SolrClientFactory newUpdateClientFactory = NewSolrClientFactory.create(SolrConnectConfig.updateConnectConfig); static final SolrClientFactory newAdminClientFactory = NewSolrClientFactory.create(SolrConnectConfig.adminConnectConfig); NewSolrClientFactory(SolrConnectConfig connectConfig) { this.connectConfig = connectConfig; } public static NewSolrClientFactory create(SolrConnectConfig connectConfig) { return new NewSolrClientFactory(connectConfig); } @Override public HttpSolrClient getClientFromUrlRaw(String url, String solrUsername, String solrPassword) { return makeClient(connectConfig, url, solrUsername, solrPassword); } public static HttpSolrClient makeClient(SolrConnectConfig connectConfig, String url, String solrUsername, String solrPassword) { if (Debug.verboseOn()) Debug.logVerbose("Solr: Creating new solr " + connectConfig.makeClientLogDesc(url, solrUsername), module); return ScipioHttpSolrClient.create(url, null, solrUsername, solrPassword, connectConfig.getMaxConnections(), connectConfig.getMaxConnectionsPerHost(), connectConfig.getConnectTimeout(), connectConfig.getSocketTimeout()); } @Override public SolrConnectConfig getConnectConfig() { return connectConfig; } } /** * Special client cache, optimized using read-only map for thread safety and default clients. */ static class CachedSolrClientFactory extends SolrClientFactory { private final SolrConnectConfig connectConfig; private final String defaultClientCacheKey; private final HttpSolrClient defaultClient; private Map<String, HttpSolrClient> clientCache; CachedSolrClientFactory(SolrConnectConfig connectConfig, String defaultClientCacheKey, HttpSolrClient defaultClient) { this.connectConfig = connectConfig; this.defaultClientCacheKey = defaultClientCacheKey; this.defaultClient = defaultClient; Map<String, HttpSolrClient> clientCache = new HashMap<>(); clientCache.put(defaultClientCacheKey, defaultClient); this.clientCache = Collections.unmodifiableMap(clientCache); } public static CachedSolrClientFactory create(SolrConnectConfig connectConfig) { String defaultClientCacheKey = (connectConfig.getSolrUsername() != null) ? (connectConfig.getSolrCoreUrl() + ":" + connectConfig.getSolrUsername() + ":" + connectConfig.getSolrPassword()) : connectConfig.getSolrCoreUrl(); HttpSolrClient defaultClient = NewSolrClientFactory.makeClient(connectConfig, connectConfig.getSolrCoreUrl(), connectConfig.getSolrUsername(), connectConfig.getSolrPassword()); return new CachedSolrClientFactory(connectConfig, defaultClientCacheKey, defaultClient); } @Override public HttpSolrClient getClientFromUrlRaw(String url, String solrUsername, String solrPassword) { final String cacheKey = (solrUsername != null) ? (url + ":" + solrUsername + ":" + solrPassword) : url; if (defaultClientCacheKey.equals(cacheKey)) { if (Debug.verboseOn()) Debug.logVerbose("Solr: Using default solr " + connectConfig.makeClientLogDesc(url, solrUsername), module); return defaultClient; } HttpSolrClient client = clientCache.get(cacheKey); if (client == null) { synchronized(this) { client = clientCache.get(cacheKey); if (client == null) { client = NewSolrClientFactory.makeClient(connectConfig, url, solrUsername, solrPassword); // use immutable map pattern for performance (the map only ever contains a few entries) Map<String, HttpSolrClient> newCache = new HashMap<>(clientCache); newCache.put(cacheKey, client); clientCache = Collections.unmodifiableMap(newCache); } else { if (Debug.verboseOn()) Debug.logVerbose("Solr: Using cached solr " + connectConfig.makeClientLogDesc(url, solrUsername), module); } } } else { if (Debug.verboseOn()) Debug.logVerbose("Solr: Using cached solr " + connectConfig.makeClientLogDesc(url, solrUsername), module); } return client; } @Override public SolrConnectConfig getConnectConfig() { return connectConfig; } } } static class LocalUrlUtil { public static boolean isLocalhost(String host) { return "localhost".equals(host) || "127.0.0.1".equals(host); } public static int getStandardPort(String protocol) { return ("https".equals(protocol)) ? 443 : 80; } public static boolean isStandardPort(int port, String protocol) { return ("https".equals(protocol) && port == 443) || ("http".equals(protocol) && port == 80); } public static Integer getWebappContainerPort(String protocol) { ScipioConnectorInfo connectorInfo = ScipioConnectorInfo.getWebContainer(protocol); return (connectorInfo != null) ? connectorInfo.getPort() : null; } public static boolean isWebappContainerPort(int port) { ScipioConnectorInfo httpConnectorInfo = ScipioConnectorInfo.getWebContainer(false); if (httpConnectorInfo != null && port == httpConnectorInfo.getPort()) { return true; } ScipioConnectorInfo httpsConnectorInfo = ScipioConnectorInfo.getWebContainer(true); if (httpConnectorInfo != null && port == httpsConnectorInfo.getPort()) { return true; } return false; } public static Integer getFrontendServerPort(String protocol) { Integer port = UtilProperties.getPropertyAsInteger("url", "https".equals(protocol) ? "port.https" : "port.http", null); return port; } public static boolean isFrontendServerPort(int port) { if (port == UtilProperties.getPropertyAsInteger("url", "port.https", -1)) { return true; } if (port == UtilProperties.getPropertyAsInteger("url", "port.http", -1)) { return true; } return false; } } /** * Returns true if either solr.debug is true or verbose logging is on. */ public static boolean verboseOn() { return (SolrUtil.DEBUG || Debug.verboseOn()); } }
ilscipio/scipio-erp
applications/solr/src/com/ilscipio/scipio/solr/SolrUtil.java
213,328
/* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.goide.completion; import com.intellij.codeInsight.completion.*; import com.intellij.codeInsight.lookup.AutoCompletionPolicy; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.codeInsight.template.Template; import com.intellij.codeInsight.template.TemplateManager; import com.intellij.codeInsight.template.impl.TemplateSettings; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorModificationUtil; import com.intellij.util.ObjectUtils; import com.intellij.util.ProcessingContext; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoKeywordCompletionProvider extends CompletionProvider<CompletionParameters> { public static final InsertHandler<LookupElement> EMPTY_INSERT_HANDLER = (context, element) -> { }; private final int myPriority; @Nullable private final InsertHandler<LookupElement> myInsertHandler; @Nullable private final AutoCompletionPolicy myCompletionPolicy; @NotNull private final String[] myKeywords; public GoKeywordCompletionProvider(int priority, String... keywords) { this(priority, null, null, keywords); } public GoKeywordCompletionProvider(int priority, @Nullable AutoCompletionPolicy completionPolicy, @NotNull String... keywords) { this(priority, null, completionPolicy, keywords); } public GoKeywordCompletionProvider(int priority, @Nullable InsertHandler<LookupElement> insertHandler, @NotNull String... keywords) { this(priority, insertHandler, null, keywords); } private GoKeywordCompletionProvider(int priority, @Nullable InsertHandler<LookupElement> insertHandler, @Nullable AutoCompletionPolicy completionPolicy, @NotNull String... keywords) { myPriority = priority; myInsertHandler = insertHandler; myCompletionPolicy = completionPolicy; myKeywords = keywords; } @Override protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) { for (String keyword : myKeywords) { result.addElement(createKeywordLookupElement(keyword)); } } @NotNull private LookupElement createKeywordLookupElement(@NotNull String keyword) { InsertHandler<LookupElement> insertHandler = ObjectUtils.chooseNotNull(myInsertHandler, createTemplateBasedInsertHandler("go_lang_" + keyword)); LookupElement result = createKeywordLookupElement(keyword, myPriority, insertHandler); return myCompletionPolicy != null ? myCompletionPolicy.applyPolicy(result) : result; } public static LookupElement createKeywordLookupElement(@NotNull String keyword, int priority, @Nullable InsertHandler<LookupElement> insertHandler) { LookupElementBuilder builder = LookupElementBuilder.create(keyword).withBoldness(true).withInsertHandler(insertHandler); return PrioritizedLookupElement.withPriority(builder, priority); } @Nullable public static InsertHandler<LookupElement> createTemplateBasedInsertHandler(@NotNull String templateId) { return (context, item) -> { Template template = TemplateSettings.getInstance().getTemplateById(templateId); Editor editor = context.getEditor(); if (template != null) { editor.getDocument().deleteString(context.getStartOffset(), context.getTailOffset()); TemplateManager.getInstance(context.getProject()).startTemplate(editor, template); } else { int currentOffset = editor.getCaretModel().getOffset(); CharSequence documentText = editor.getDocument().getImmutableCharSequence(); if (documentText.length() <= currentOffset || documentText.charAt(currentOffset) != ' ') { EditorModificationUtil.insertStringAtCaret(editor, " "); } else { EditorModificationUtil.moveCaretRelatively(editor, 1); } } }; } }
go-lang-plugin-org/go-lang-idea-plugin
src/com/goide/completion/GoKeywordCompletionProvider.java
213,329
/* * Zettelkasten - nach Luhmann * Copyright (C) 2001-2015 by Daniel Lüdecke (http://www.danielluedecke.de) * * Homepage: http://zettelkasten.danielluedecke.de * * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program; * if not, see <http://www.gnu.org/licenses/>. * * * Dieses Programm ist freie Software. Sie können es unter den Bedingungen der GNU * General Public License, wie von der Free Software Foundation veröffentlicht, weitergeben * und/oder modifizieren, entweder gemäß Version 3 der Lizenz oder (wenn Sie möchten) * jeder späteren Version. * * Die Veröffentlichung dieses Programms erfolgt in der Hoffnung, daß es Ihnen von Nutzen sein * wird, aber OHNE IRGENDEINE GARANTIE, sogar ohne die implizite Garantie der MARKTREIFE oder * der VERWENDBARKEIT FÜR EINEN BESTIMMTEN ZWECK. Details finden Sie in der * GNU General Public License. * * Sie sollten ein Exemplar der GNU General Public License zusammen mit diesem Programm * erhalten haben. Falls nicht, siehe <http://www.gnu.org/licenses/>. */ package de.danielluedecke.zettelkasten; import static java.awt.event.KeyEvent.VK_ESCAPE; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.SystemTray; import java.awt.event.ActionListener; import java.io.File; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.Level; import javax.swing.JColorChooser; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.KeyStroke; import javax.swing.UIManager; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import org.jdesktop.application.Action; import at.jta.Key; import at.jta.NotSupportedOSException; import at.jta.RegistryErrorException; import at.jta.Regor; import de.danielluedecke.zettelkasten.database.AutoKorrektur; import de.danielluedecke.zettelkasten.database.Daten; import de.danielluedecke.zettelkasten.database.Settings; import de.danielluedecke.zettelkasten.database.StenoData; import de.danielluedecke.zettelkasten.database.Synonyms; import de.danielluedecke.zettelkasten.util.Constants; import de.danielluedecke.zettelkasten.util.HtmlUbbUtil; import de.danielluedecke.zettelkasten.util.PlatformUtil; /** * * @author danielludecke */ public class CSettingsDlg extends javax.swing.JDialog { /** * Reference to the settings-class */ private final Settings settings; /** * */ private final Daten dataObj; /** * A reference to the auto-correction class */ private final AutoKorrektur autokorrekt; /** * A reference to the steno-data class */ private final StenoData stenoObj; /** * */ private final Synonyms synonyms; // LookAndFeelInfo maintains the class name of the LookAndFeel class, not the actual LookAndFeel instance. /** * Provide information about installed LookAndFeel * for the sake of configuring a menu or * for initial application set up */ private final UIManager.LookAndFeelInfo[] installed_laf = UIManager.getInstalledLookAndFeels(); /** * get the strings for file descriptions from the resource map */ private final org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application .getInstance(de.danielluedecke.zettelkasten.ZettelkastenApp.class).getContext() .getResourceMap(CSettingsDlg.class); /** * The different fonts, used to retrieve the font settings and for the * font-chooser-dialog */ private Font mainfont; private Font quotefont; private Font entryheaderfont; private Font authorfont; private Font remarksfont; private Font titlefont; private Font headerfont1; private Font headerfont2; private Font desktopheaderfont; private Font desktopcommentfont; private Font desktopitemheaderfont; private Font desktopitemfont; private Font tableFont; private Font desktopfont; private Font codefont; private Font appendixheaderfont; /** * The different font-colors, used to retrieve the font colors and for the * color-chooser-dialog */ private String mainfontcolor; private String codefontcolor; private String quotefontcolor; private String entryheaderfontcolor; private String authorfontcolor; private String remarksfontcolor; private String titlefontcolor; private String appendixheaderfontcolor; private String headerfont1color; private String headerfont2color; private String desktopheaderfontcolor; private String desktopcommentfontcolor; private String desktopitemheaderfontcolor; private String desktopitemfontcolor; private String tableheadercolor; private String tablerowevencolor; private String tablerowoddcolor; private String linkscolor; private String manlinkscolor; private String fnlinkscolor; private String entryheadingscolor; private String reflistbgcolor; private String quotecolor; private String mainbgcolor; private String contentbgcolor; /** * Stores the current selection of the look'n'feel combobox */ private int lafselection = 0; /** * return value for the main window so we know whether we have to update the * display */ private boolean needsupdate = false; /** * return value for the main window so we know whether we have to update the * display */ private boolean displayupdate = false; /** * return value for the main window so we know whether we have to update the laf */ private boolean lafupdate = false; /** * */ private boolean savesettingok = true; /** * */ private boolean registryChanges = false; /** * */ private boolean userPathChanges = false; private boolean pandocPathChanges = false; /** * * @param parent * @param s * @param d * @param ac * @param sy * @param stn */ public CSettingsDlg(java.awt.Frame parent, Settings s, Daten d, AutoKorrektur ac, Synonyms sy, StenoData stn) { super(parent); // set application icon setIconImage(Constants.zknicon.getImage()); // get reference to settings-class settings = s; dataObj = d; autokorrekt = ac; synonyms = sy; stenoObj = stn; initComponents(); // make extra style for combo-boxes if (settings.isSeaGlass()) { jButtonApply.putClientProperty("JComponent.sizeVariant", "small"); jButtonBrowseAttachmentPath.putClientProperty("JComponent.sizeVariant", "small"); jButtonBrowseBackup.putClientProperty("JComponent.sizeVariant", "small"); jButtonBrowseImagePath.putClientProperty("JComponent.sizeVariant", "small"); jButtonBrowsePandoc.putClientProperty("JComponent.sizeVariant", "small"); jButtonCancel.putClientProperty("JComponent.sizeVariant", "small"); jButtonDesktopCSS.putClientProperty("JComponent.sizeVariant", "small"); jButtonEditAutokorrekt.putClientProperty("JComponent.sizeVariant", "small"); jButtonEditSteno.putClientProperty("JComponent.sizeVariant", "small"); jButtonEntryCss.putClientProperty("JComponent.sizeVariant", "small"); jButtonHighlightKeywordStyle.putClientProperty("JComponent.sizeVariant", "small"); jButtonHighlightLivesearchStyle.putClientProperty("JComponent.sizeVariant", "small"); jButtonHighlightStyle.putClientProperty("JComponent.sizeVariant", "small"); jButtonListFont.putClientProperty("JComponent.sizeVariant", "small"); jButtonDesktopFont.putClientProperty("JComponent.sizeVariant", "small"); jButtonResetDesktopCSS.putClientProperty("JComponent.sizeVariant", "small"); jButtonResetEntryCSS.putClientProperty("JComponent.sizeVariant", "small"); jButtonSynonymEdit.putClientProperty("JComponent.sizeVariant", "small"); } if (!SystemTray.isSupported() || PlatformUtil.isMacOS()) { jCheckBoxSystray.setText(jCheckBoxSystray.getText() + resourceMap.getString("systrayNotSupported")); jCheckBoxSystray.setEnabled(false); jCheckBoxSystray.setSelected(false); } else { jCheckBoxSystray.setSelected(settings.getMinimizeToTray()); } // en- and disable checkboxes depending on the os jCheckBoxRegistry.setEnabled(System.getProperty("os.name").toLowerCase().startsWith("windows")); // init mainfont mainfont = settings.getMainFont(); mainfontcolor = settings.getMainfont(Settings.FONTCOLOR); // init code font codefont = settings.getCodeFont(); codefontcolor = settings.getCodeFont(Settings.FONTCOLOR); // init quote quotefont = settings.getQuoteFont(); quotefontcolor = settings.getQuoteFont(Settings.FONTCOLOR); // init entryheaderfont entryheaderfont = settings.getEntryHeaderFont(); entryheaderfontcolor = settings.getEntryHeaderFont(Settings.FONTCOLOR); // init authorfont authorfont = settings.getAuthorFont(); authorfontcolor = settings.getAuthorFont(Settings.FONTCOLOR); // init remarksfont remarksfont = settings.getRemarksFont(); remarksfontcolor = settings.getRemarksFont(Settings.FONTCOLOR); // init titlefont titlefont = settings.getTitleFont(); titlefontcolor = settings.getTitleFont(Settings.FONTCOLOR); // init appendixheaderfont appendixheaderfont = settings.getAppendixHeaderFont(); appendixheaderfontcolor = settings.getAppendixHeaderFont(Settings.FONTCOLOR); // init header1-font headerfont1 = settings.getHeaderFont1(); headerfont1color = settings.getHeaderfont1(Settings.FONTCOLOR); // init header2-font headerfont2 = settings.getHeaderFont2(); headerfont2color = settings.getHeaderfont2(Settings.FONTCOLOR); // init desktopheader-font desktopheaderfont = settings.getDesktopHeaderFont(); desktopheaderfontcolor = settings.getDesktopHeaderfont(Settings.FONTCOLOR); // init desktopcomment-font desktopcommentfont = settings.getDesktopCommentFont(); desktopcommentfontcolor = settings.getDesktopCommentfont(Settings.FONTCOLOR); // init desktopitemheader-font desktopitemheaderfont = settings.getDesktopItemHeaderFont(); desktopitemheaderfontcolor = settings.getDesktopItemHeaderfont(Settings.FONTCOLOR); // init desktopitem-font desktopitemfont = settings.getDesktopItemFont(); desktopitemfontcolor = settings.getDesktopItemfont(Settings.FONTCOLOR); tableFont = settings.getTableFont(); desktopfont = settings.getDesktopOutlineFont(); // get bg colors tableheadercolor = settings.getTableHeaderColor(); tablerowevencolor = settings.getTableRowEvenColor(); tablerowoddcolor = settings.getTableRowOddColor(); linkscolor = settings.getLinkColor(); manlinkscolor = settings.getManlinkColor(); fnlinkscolor = settings.getFootnoteLinkColor(); entryheadingscolor = settings.getEntryHeadingBackgroundColor(); reflistbgcolor = settings.getAppendixBackgroundColor(); quotecolor = settings.getQuoteBackgroundColor(); mainbgcolor = settings.getMainBackgroundColor(); contentbgcolor = settings.getContentBackgroundColor(); // init checkboxex jCheckBoxEntryCSS.setSelected(settings.getUseCustomCSS(Settings.CUSTOM_CSS_ENTRY)); jCheckBoxDesktopCSS.setSelected(settings.getUseCustomCSS(Settings.CUSTOM_CSS_DESKTOP)); jCheckBoxShowHorGrid.setSelected(settings.getShowGridHorizontal()); jCheckBoxShowVerGrid.setSelected(settings.getShowGridVertical()); jCheckBoxAutocorrect.setSelected(settings.getSpellCorrect()); jCheckBoxSteno.setSelected(settings.getStenoActivated()); jCheckBoxImgResize.setSelected(settings.getImageResize()); jCheckBoxUseMacBackgroundColor.setSelected(settings.getUseMacBackgroundColor()); jCheckBoxAutobackup.setSelected(settings.getAutoBackup()); jCheckBoxFootnote.setSelected(settings.getSupFootnote()); jCheckBoxJumpToTab.setSelected(settings.getJumpFootnote()); jCheckBoxSynonym.setSelected(settings.getSearchAlwaysSynonyms()); jCheckBoxFillNewEntries.setSelected(settings.getInsertNewEntryAtEmpty()); jCheckBoxExtraBackup.setSelected(settings.getExtraBackup()); jCheckBoxAllToHist.setSelected(settings.getAddAllToHistory()); jTextFieldBackupPath .setText((settings.getExtraBackupDir() != null) ? settings.getExtraBackupDir().toString() : ""); jTextFieldBackupPath.setEnabled(settings.getExtraBackup()); jTextFieldPandoc.setText(settings.getPandocPath()); jButtonBrowseBackup.setEnabled(settings.getExtraBackup()); jCheckBoxIconText.setSelected(settings.getShowIconText()); jCheckBoxShowToolbar.setSelected(settings.getShowIcons()); jCheckBoxShowAllIcons.setSelected(settings.getShowAllIcons()); jCheckBoxAutoUpdate.setSelected(settings.getAutoUpdate()); jCheckBoxCheckNightly.setSelected(settings.getAutoNightlyUpdate()); jCheckBoxUseXDGOpen.setSelected(settings.getUseXDGOpen()); jCheckBoxAutoCompleteTags.setSelected(settings.getAutoCompleteTags()); jCheckBoxUseMarkdown.setSelected(settings.getMarkdownActivated()); jCheckBoxShowTableBorder.setSelected(settings.getShowTableBorder()); jCheckBoxShowEntryHeadline.setSelected(settings.getShowEntryHeadline()); jCheckBoxFootnoteBraces.setSelected(settings.getFootnoteBraces()); jCheckBoxSearchWithoutFormatTags.setSelected(!settings.getSearchRemovesFormatTags()); // get user attachment and image paths File attpath = dataObj.getUserAttachmentPath(); if (attpath != null) { jTextFieldAttachmentPath.setText(attpath.toString()); } File imgpath = dataObj.getUserImagePath(); if (imgpath != null) { jTextFieldImagePath.setText(imgpath.toString()); } // init formatted textfields with resize-preferences jFormattedTextFieldImgWidth.setValue(settings.getImageResizeWidth()); jFormattedTextFieldImgHeight.setValue(settings.getImageResizeHeight()); jCheckBoxRegistry.setSelected(initRegCheckBox()); // get value for cell spacing Dimension cellspacing = settings.getCellSpacing(); jSpinnerDistHor.setValue(cellspacing.width); jSpinnerDistVer.setValue(cellspacing.height); // init the slider for the default table and list fontsize jSliderFontSize.setValue(settings.getTableFontSize()); jSliderDesktopFontSize.setValue(settings.getDesktopOutlineFontSize()); jSliderTextfields.setValue(settings.getTextfieldFontSize()); // set language setting String lang = settings.getLanguage(); try { if (lang.equalsIgnoreCase("de")) { jComboBoxLocale.setSelectedIndex(1); } else if (lang.equalsIgnoreCase("es")) { jComboBoxLocale.setSelectedIndex(2); } else if (lang.equalsIgnoreCase("pt")) { jComboBoxLocale.setSelectedIndex(3); } else { jComboBoxLocale.setSelectedIndex(0); } } catch (IllegalArgumentException e) { Constants.zknlogger.log(Level.WARNING, e.getLocalizedMessage()); } initComboboxLAF(); initComboboxFonts(); initComboBoxBackgroundColors(); initComboboxManualTimestamp(); initComboBoxIconThemes(); initComboboxStartup(); initListeners(); setModified(false); lafupdate = false; } private void initListeners() { // Add an escape-key listener to the dialog. When fired, it performs // cancelWindows() (same as cancel button). KeyStroke stroke = KeyStroke.getKeyStroke(VK_ESCAPE, 0); ActionListener cancelAction = evt -> cancelWindow(); getRootPane().registerKeyboardAction(cancelAction, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); // init selection jComboBoxShowAtStartup.setSelectedIndex(settings.getStartupEntryNumberMode()); jComboBoxShowAtStartup.addActionListener(evt -> setModified(true)); jComboBoxIconTheme.addActionListener(evt -> { setModified(true); needsupdate = true; }); jComboBoxLocale.addActionListener(evt -> { setModified(true); lafupdate = true; }); jComboBoxLAF.addActionListener(evt -> { setModified(true); lafupdate = true; }); jComboBoxManualTimestamp.addActionListener(evt -> setModified(true)); jComboBoxFonts.addActionListener(evt -> jLabelColor.setBackground(getFontColor())); jComboBoxFonts.setSelectedIndex(0); jComboBoxBackgroundColors.addActionListener(evt -> jLabelTableColor.setBackground(getBackgroundColor())); jComboBoxBackgroundColors.setSelectedIndex(0); jTextFieldAttachmentPath.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { checkPath(jTextFieldAttachmentPath); } @Override public void insertUpdate(DocumentEvent e) { checkPath(jTextFieldAttachmentPath); } @Override public void removeUpdate(DocumentEvent e) { checkPath(jTextFieldAttachmentPath); } }); jTextFieldImagePath.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { checkPath(jTextFieldImagePath); } @Override public void insertUpdate(DocumentEvent e) { checkPath(jTextFieldImagePath); } @Override public void removeUpdate(DocumentEvent e) { checkPath(jTextFieldImagePath); } }); jTextFieldPandoc.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { pandocPathChanges = true; setModified(true); } @Override public void insertUpdate(DocumentEvent e) { pandocPathChanges = true; setModified(true); } @Override public void removeUpdate(DocumentEvent e) { pandocPathChanges = true; setModified(true); } }); jCheckBoxAutobackup.addActionListener(evt -> setModified(true)); jCheckBoxShowTableBorder.addActionListener(evt -> { setModified(true); displayupdate = true; }); jCheckBoxAutocorrect.addActionListener(evt -> setModified(true)); jCheckBoxSteno.addActionListener(evt -> setModified(true)); jCheckBoxShowEntryHeadline.addActionListener(evt -> { setModified(true); displayupdate = true; }); jCheckBoxSynonym.addActionListener(evt -> setModified(true)); jCheckBoxSystray.addActionListener(evt -> setModified(true)); jCheckBoxFillNewEntries.addActionListener(evt -> setModified(true)); jCheckBoxAutoUpdate.addActionListener(evt -> { setModified(true); jCheckBoxCheckNightly.setEnabled(jCheckBoxAutoUpdate.isSelected()); }); jCheckBoxCheckNightly.addActionListener(evt -> setModified(true)); jCheckBoxJumpToTab.addActionListener(evt -> setModified(true)); jCheckBoxUseMarkdown.addActionListener(evt -> { displayupdate = true; setModified(true); }); jCheckBoxUseMacBackgroundColor.addActionListener(evt -> { displayupdate = true; setModified(true); }); jCheckBoxShowHorGrid.addActionListener(evt -> setModified(true)); jCheckBoxShowVerGrid.addActionListener(evt -> setModified(true)); jCheckBoxAllToHist.addActionListener(evt -> setModified(true)); jSpinnerDistHor.addChangeListener(evt -> { needsupdate = true; setModified(true); }); jSpinnerDistVer.addChangeListener(evt -> { needsupdate = true; setModified(true); }); jSliderFontSize.addChangeListener(evt -> { needsupdate = true; float newFontSize = jSliderFontSize.getValue(); tableFont = tableFont.deriveFont(newFontSize); setModified(true); lafupdate = true; }); jSliderDesktopFontSize.addChangeListener(evt -> { needsupdate = true; setModified(true); lafupdate = true; }); jFormattedTextFieldImgWidth.addKeyListener(new java.awt.event.KeyAdapter() { @Override public void keyReleased(java.awt.event.KeyEvent evt) { displayupdate = true; setModified(true); } }); jFormattedTextFieldImgHeight.addKeyListener(new java.awt.event.KeyAdapter() { @Override public void keyReleased(java.awt.event.KeyEvent evt) { displayupdate = true; setModified(true); } }); jCheckBoxFootnote.addActionListener(evt -> { displayupdate = true; setModified(true); }); jCheckBoxFootnoteBraces.addActionListener(evt -> setModified(true)); jCheckBoxSearchWithoutFormatTags.addActionListener(evt -> setModified(true)); jCheckBoxUseXDGOpen.addActionListener(evt -> setModified(true)); jCheckBoxAutoCompleteTags.addActionListener(evt -> setModified(true)); jCheckBoxIconText.addActionListener(evt -> { needsupdate = true; setModified(true); }); jCheckBoxShowToolbar.addActionListener(evt -> { needsupdate = true; setModified(true); jCheckBoxShowAllIcons.setEnabled(jCheckBoxShowToolbar.isSelected()); }); jCheckBoxShowAllIcons.addActionListener(evt -> { needsupdate = true; setModified(true); }); jCheckBoxEntryCSS.addActionListener(evt -> { lafupdate = true; setModified(true); }); jCheckBoxDesktopCSS.addActionListener(evt -> { lafupdate = true; setModified(true); }); jButtonEditAutokorrekt.addActionListener(evt -> { // the button for editing the spellchecking-words was pressed, // so open the window for editing them... if (null == autoKorrektEdit) { // get parent und init window autoKorrektEdit = new CAutoKorrekturEdit(null, autokorrekt, settings); // center window autoKorrektEdit.setLocationRelativeTo(null); } ZettelkastenApp.getApplication().show(autoKorrektEdit); // change modified state and enable apply-button if (autoKorrektEdit.isModified()) { setModified(true); } autoKorrektEdit.dispose(); autoKorrektEdit = null; }); jButtonListFont.addActionListener(evt -> { // Create font-chooser dialog. if (fontDlg == null) { fontDlg = new CFontChooser(null, tableFont); fontDlg.setLocationRelativeTo(null); } // Show and wait on user. ZettelkastenApp.getApplication().show(fontDlg); // If the user has chosen a font, prepare to save. if (fontDlg.selectedFont != null) { tableFont = fontDlg.selectedFont; setModified(true); lafupdate = true; } // Close and dispose the font-dialog. fontDlg.dispose(); fontDlg = null; }); jButtonDesktopFont.addActionListener(evt -> { // get the selected font Font f = desktopfont; // create font-chooser dialog if (null == fontDlg) { fontDlg = new CFontChooser(null, f); fontDlg.setLocationRelativeTo(null); } ZettelkastenApp.getApplication().show(fontDlg); // if the user has chosen a font, set it if (fontDlg.selectedFont != null) { desktopfont = fontDlg.selectedFont; setModified(true); lafupdate = true; } // close and dispose the font-dialog fontDlg.dispose(); fontDlg = null; }); jButtonBrowseBackup.addActionListener(evt -> { JFileChooser fc = new JFileChooser(); // set dialog's title fc.setDialogTitle(resourceMap.getString("fileChooserTitle")); // restrict all files as selectable fc.setAcceptAllFileFilterUsed(false); // only directories should be selected fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int option = fc.showOpenDialog(null); // if a file was chosen, set the file path if (JFileChooser.APPROVE_OPTION == option) { // get the file path... jTextFieldBackupPath.setText(fc.getSelectedFile().toString()); setModified(true); } }); jButtonBrowseAttachmentPath.addActionListener(evt -> { JFileChooser fc = new JFileChooser(); // set dialog's title fc.setDialogTitle(resourceMap.getString("fileChooserTitle")); // restrict all files as chooseable fc.setAcceptAllFileFilterUsed(false); // only directories should be selected fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int option = fc.showOpenDialog(null); // if a file was chosen, set the file path if (JFileChooser.APPROVE_OPTION == option) { // get the file path... jTextFieldAttachmentPath.setText(fc.getSelectedFile().toString()); setModified(true); } }); jButtonBrowsePandoc.addActionListener(evt -> { JFileChooser fc = new JFileChooser(); // set dialog's title fc.setDialogTitle(resourceMap.getString("fileChooserTitle")); // restrict all files as chooseable fc.setAcceptAllFileFilterUsed(false); // only directories should be selected fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int option = fc.showOpenDialog(null); // if a file was chosen, set the file path if (JFileChooser.APPROVE_OPTION == option) { // get the file path... jTextFieldPandoc.setText(fc.getSelectedFile().toString()); setModified(true); } }); jButtonBrowseImagePath.addActionListener(evt -> { JFileChooser fc = new JFileChooser(); // set dialog's title fc.setDialogTitle(resourceMap.getString("fileChooserTitle")); // restrict all files as chooseable fc.setAcceptAllFileFilterUsed(false); // only directories should be selected fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int option = fc.showOpenDialog(null); // if a file was chosen, set the file path if (JFileChooser.APPROVE_OPTION == option) { // get the file path... jTextFieldImagePath.setText(fc.getSelectedFile().toString()); setModified(true); } }); jButtonCancel.addActionListener(evt -> cancelWindow()); jButtonEntryCss.addActionListener(evt -> editCSS(Settings.CUSTOM_CSS_ENTRY)); jButtonDesktopCSS.addActionListener(evt -> editCSS(Settings.CUSTOM_CSS_DESKTOP)); jButtonResetEntryCSS.addActionListener(evt -> resetCSS(Settings.CUSTOM_CSS_ENTRY)); jButtonResetDesktopCSS.addActionListener(evt -> resetCSS(Settings.CUSTOM_CSS_DESKTOP)); jCheckBoxImgResize.addActionListener(evt -> { setModified(true); displayupdate = true; jFormattedTextFieldImgWidth.setEnabled(jCheckBoxImgResize.isSelected()); jFormattedTextFieldImgHeight.setEnabled(jCheckBoxImgResize.isSelected()); }); jCheckBoxExtraBackup.addActionListener(evt -> { jTextFieldBackupPath.setEnabled(jCheckBoxExtraBackup.isSelected()); jButtonBrowseBackup.setEnabled(jCheckBoxExtraBackup.isSelected()); setModified(true); }); jCheckBoxRegistry.addActionListener(evt -> { setModified(true); registryChanges = true; }); jButtonEditSteno.addActionListener(evt -> { // the button for editing the spellchecking-words was pressed, // so open the window for editing them... if (null == stenoEdit) { // get parent und init window stenoEdit = new CStenoEdit(null, stenoObj, settings); // center window stenoEdit.setLocationRelativeTo(null); } ZettelkastenApp.getApplication().show(stenoEdit); // change modified state and enable apply-button if (stenoEdit.isModified()) { setModified(true); } stenoEdit.dispose(); stenoEdit = null; }); jButtonHighlightStyle.addActionListener(evt -> { if (null == highlightSettingsDlg) { highlightSettingsDlg = new CHighlightSearchSettings(null, settings, HtmlUbbUtil.HIGHLIGHT_STYLE_SEARCHRESULTS); highlightSettingsDlg.setLocationRelativeTo(null); } ZettelkastenApp.getApplication().show(highlightSettingsDlg); if (!highlightSettingsDlg.isCancelled()) { setModified(true); lafupdate = true; } highlightSettingsDlg.dispose(); highlightSettingsDlg = null; }); jButtonHighlightKeywordStyle.addActionListener(evt -> { if (null == highlightSettingsDlg) { highlightSettingsDlg = new CHighlightSearchSettings(null, settings, HtmlUbbUtil.HIGHLIGHT_STYLE_KEYWORDS); highlightSettingsDlg.setLocationRelativeTo(null); } ZettelkastenApp.getApplication().show(highlightSettingsDlg); if (!highlightSettingsDlg.isCancelled()) { setModified(true); lafupdate = true; } highlightSettingsDlg.dispose(); highlightSettingsDlg = null; }); jButtonHighlightLivesearchStyle.addActionListener(evt -> { if (null == highlightSettingsDlg) { highlightSettingsDlg = new CHighlightSearchSettings(null, settings, HtmlUbbUtil.HIGHLIGHT_STYLE_LIVESEARCH); highlightSettingsDlg.setLocationRelativeTo(null); } ZettelkastenApp.getApplication().show(highlightSettingsDlg); if (!highlightSettingsDlg.isCancelled()) { setModified(true); lafupdate = true; } highlightSettingsDlg.dispose(); highlightSettingsDlg = null; }); jButtonSynonymEdit.addActionListener(evt -> { if (null == synonymsDlg) { synonymsDlg = new CSynonymsEdit(null, synonyms, settings, dataObj); synonymsDlg.setLocationRelativeTo(null); } ZettelkastenApp.getApplication().show(synonymsDlg); // change modified state and enable apply-button if (synonymsDlg.isModified()) { setModified(true); setSynModified(true); } synonymsDlg.dispose(); synonymsDlg = null; }); } /** * Initialize the combo box * Look and feel class names are added to the combo box. */ private void initComboboxLAF() { jComboBoxLAF.removeAllItems(); lafselection = 0; for (int cnt = 0; cnt < installed_laf.length; cnt++) { jComboBoxLAF.addItem(installed_laf[cnt].getName()); if (installed_laf[cnt].getClassName().equals(settings.getLookAndFeel())) { lafselection = cnt; } } jComboBoxLAF.setSelectedIndex(lafselection); } /** * Initiates the combo-box that hold the values for the manual timestamps that * can be inserted when editing new entries (CNewEntry-dialog). */ private void initComboboxManualTimestamp() { // remove all items from the combobox jComboBoxManualTimestamp.removeAllItems(); // iterate constant-array that holds all date-format-strings for (String item : Constants.manualTimestamp) { // create a new dateformat out of that string DateFormat df = new SimpleDateFormat(item); // and convert it to a string-item String timestamp = df.format(new Date()); // add it to combobox jComboBoxManualTimestamp.addItem(timestamp); } // select initial value jComboBoxManualTimestamp.setSelectedIndex(settings.getManualTimestamp()); } private void initComboBoxIconThemes() { // clear combobox jComboBoxIconTheme.removeAllItems(); // set themes for (String theme : Constants.iconThemesNames) { jComboBoxIconTheme.addItem(theme); } jComboBoxIconTheme.setSelectedIndex(settings.getIconTheme()); } /** * * @param what Use one of * <ul> * <li>Settings.CUSTOM_CSS_ENTRY</li> * <li>Settings.CUSTOM_CSS_DESKTOP</li> * </ul> */ private void editCSS(int what) { // get css String css = settings.getCustomCSS(what); switch (what) { case Settings.CUSTOM_CSS_ENTRY: if (null == css || css.isEmpty()) { css = HtmlUbbUtil.getCommonStyleDefinition(settings, false, false, false); } break; case Settings.CUSTOM_CSS_DESKTOP: if (null == css || css.isEmpty()) { css = HtmlUbbUtil.getCommonStyleDefinition(settings, true, false, false); } break; default: if (null == css || css.isEmpty()) { css = HtmlUbbUtil.getCommonStyleDefinition(settings, false, false, false); } break; } // open an input-dialog, setting the selected value as default-value if (null == biggerEditDlg) { // create a new dialog with the bigger edit-field, passing some initial values biggerEditDlg = new CBiggerEditField(null, settings, resourceMap.getString("editCSS.text"), css, "", Constants.EDIT_STYLESHEET); // center window biggerEditDlg.setLocationRelativeTo(this); } // show window ZettelkastenApp.getApplication().show(biggerEditDlg); // after closing the window, get the new value String newCss = biggerEditDlg.getNewValue(); // delete the input-dialog biggerEditDlg.dispose(); biggerEditDlg = null; // check for valid value if (newCss != null && !newCss.isEmpty()) { // set custom style sheet settings.setCustomCSS(what, newCss); lafupdate = true; setModified(true); } } /** * * @param what Use one of * <ul> * <li>Settings.CUSTOM_CSS_ENTRY</li> * <li>Settings.CUSTOM_CSS_DESKTOP</li> * </ul> */ private void resetCSS(int what) { // remember state boolean useCustomCSS = settings.getUseCustomCSS(what); // disable custom css, otherwise we would we retrieve just // that custom style when resetting it settings.setUseCustomCSS(what, false); // get css String css; switch (what) { case Settings.CUSTOM_CSS_ENTRY: css = HtmlUbbUtil.getCommonStyleDefinition(settings, false, false, false); break; case Settings.CUSTOM_CSS_DESKTOP: css = HtmlUbbUtil.getCommonStyleDefinition(settings, true, false, false); break; default: css = HtmlUbbUtil.getCommonStyleDefinition(settings, false, false, false); break; } // remember state settings.setUseCustomCSS(what, useCustomCSS); // set custom style sheet settings.setCustomCSS(what, css); lafupdate = true; setModified(true); } private void initComboBoxBackgroundColors() { jComboBoxBackgroundColors.removeAllItems(); jComboBoxBackgroundColors.addItem(resourceMap.getString("bgCol1")); jComboBoxBackgroundColors.addItem(resourceMap.getString("bgCol2")); jComboBoxBackgroundColors.addItem(resourceMap.getString("bgCol3")); jComboBoxBackgroundColors.addItem(resourceMap.getString("bgCol4")); jComboBoxBackgroundColors.addItem(resourceMap.getString("bgCol5")); jComboBoxBackgroundColors.addItem(resourceMap.getString("bgCol6")); jComboBoxBackgroundColors.addItem(resourceMap.getString("bgCol7")); jComboBoxBackgroundColors.addItem(resourceMap.getString("bgCol8")); jComboBoxBackgroundColors.addItem(resourceMap.getString("bgCol9")); jComboBoxBackgroundColors.addItem(resourceMap.getString("bgCol10")); jComboBoxBackgroundColors.addItem(resourceMap.getString("bgCol11")); // make all items visible jComboBoxBackgroundColors.setMaximumRowCount(jComboBoxBackgroundColors.getItemCount()); } /** * This method initiates the combobox with the font settings. here the user can * choose which type of font (main-font, font for authors, for lists, for tables * etc.) he or she wants to change. */ private void initComboboxFonts() { // clear combobox jComboBoxFonts.removeAllItems(); // add all font-items jComboBoxFonts.addItem(resourceMap.getString("mainfontText") + ": " + getFontDataForCombobox(mainfont)); jComboBoxFonts.addItem(resourceMap.getString("authorfontText") + ": " + getFontDataForCombobox(authorfont)); jComboBoxFonts.addItem(resourceMap.getString("remarksfontText") + ": " + getFontDataForCombobox(remarksfont)); jComboBoxFonts.addItem(resourceMap.getString("titlefontText") + ": " + getFontDataForCombobox(titlefont)); jComboBoxFonts.addItem(resourceMap.getString("headerfont1Text") + ": " + getFontDataForCombobox(headerfont1)); jComboBoxFonts.addItem(resourceMap.getString("headerfont2Text") + ": " + getFontDataForCombobox(headerfont2)); jComboBoxFonts.addItem( resourceMap.getString("desktopheaderfontText") + ": " + getFontDataForCombobox(desktopheaderfont)); jComboBoxFonts.addItem( resourceMap.getString("desktopcommentfontText") + ": " + getFontDataForCombobox(desktopcommentfont)); jComboBoxFonts.addItem(resourceMap.getString("desktopitemheaderfontText") + ": " + getFontDataForCombobox(desktopitemheaderfont)); jComboBoxFonts .addItem(resourceMap.getString("desktopitemfontText") + ": " + getFontDataForCombobox(desktopitemfont)); jComboBoxFonts.addItem(resourceMap.getString("quotefontText") + ": " + getFontDataForCombobox(quotefont)); jComboBoxFonts .addItem(resourceMap.getString("entryheaderfontText") + ": " + getFontDataForCombobox(entryheaderfont)); jComboBoxFonts.addItem( resourceMap.getString("appendixheaderfontText") + ": " + getFontDataForCombobox(appendixheaderfont)); jComboBoxFonts.addItem(resourceMap.getString("codefontText") + ": " + getFontDataForCombobox(codefont)); // make all items visible jComboBoxFonts.setMaximumRowCount(jComboBoxFonts.getItemCount()); } private void initComboboxStartup() { jComboBoxShowAtStartup.removeAllItems(); jComboBoxShowAtStartup.addItem(resourceMap.getString("cbStartup1.text")); jComboBoxShowAtStartup.addItem(resourceMap.getString("cbStartup2.text")); jComboBoxShowAtStartup.addItem(resourceMap.getString("cbStartup3.text")); } private void checkPath(javax.swing.JTextField tf) { // retrieve file path from textfield String fps = tf.getText(); // check whether path exists if (!fps.isEmpty()) { // create file-variable File fp = new File(fps); // check for existence tf.setForeground((fp.exists()) ? Color.black : Color.red); } else { // indicate that path is OK tf.setForeground(Color.black); } // enable apply button setModified(true); // indicate that path has been changed userPathChanges = true; } private boolean initRegCheckBox() { try { Regor winreg = new Regor(); return (winreg.openKey(Regor.HKEY_CLASSES_ROOT, ".zkn3") != null && winreg.openKey(Regor.HKEY_CLASSES_ROOT, "zkn3_auto_file\\shell\\Open\\command") != null); } catch (NotSupportedOSException e) { Constants.zknlogger.log(Level.WARNING, e.getLocalizedMessage()); } catch (Exception e) { Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage()); } return false; } private void registerFileExtension() { try { Regor winreg = new Regor(); if (jCheckBoxRegistry.isSelected()) { Key regkey = winreg.openKey(Regor.HKEY_CLASSES_ROOT, ".zkn3"); if (null == regkey) { regkey = winreg.createKey(Regor.HKEY_CLASSES_ROOT, ".zkn3"); winreg.closeKey(regkey); regkey = winreg.openKey(Regor.HKEY_CLASSES_ROOT, ".zkn3"); } if (regkey != null) { winreg.saveValue(regkey, "", "zkn3_auto_file"); winreg.closeKey(regkey); regkey = winreg.openKey(Regor.HKEY_CLASSES_ROOT, "zkn3_auto_file\\shell\\Open\\command"); if (null == regkey) { regkey = winreg.createKey(Regor.HKEY_CLASSES_ROOT, "zkn3_auto_file\\shell\\Open\\command"); winreg.closeKey(regkey); regkey = winreg.openKey(Regor.HKEY_CLASSES_ROOT, "zkn3_auto_file\\shell\\Open\\command"); } if (regkey != null) { winreg.saveValue(regkey, "", "\"" + System.getProperty("java.class.path") + "\" \"%1\""); winreg.closeKey(regkey); } } } else { winreg.delKey(Regor.HKEY_CLASSES_ROOT, ".zkn3"); winreg.delKey(Regor.HKEY_CLASSES_ROOT, "zkn3_auto_file\\shell\\Open\\command"); } } catch (RegistryErrorException e) { Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage()); // show warning message box JOptionPane.showMessageDialog(null, resourceMap.getString("errorRegistryMsg"), resourceMap.getString("errorRegistryTitle"), JOptionPane.PLAIN_MESSAGE); } catch (NotSupportedOSException e) { Constants.zknlogger.log(Level.WARNING, e.getLocalizedMessage()); } } /** * This method creates a string-description for the font-settings, which are * used for the font's combobox. * * @param name * @param size * @param style * @return a prepared string containing a description of the font-settings */ private String getFontDataForCombobox(Font f) { StringBuilder item = new StringBuilder(); // first, set the font's name item.append(f.getFamily()); // add additional information item.append(" ("); // add the font-size item.append(f.getSize()); item.append("px, "); // get the style-information switch (f.getStyle()) { case Font.PLAIN: item.append(resourceMap.getString("fontStylePlain")); break; case Font.BOLD: item.append(resourceMap.getString("fontStyleBold")); break; case Font.ITALIC: item.append(resourceMap.getString("fontStyleItalic")); break; case Font.BOLD + Font.ITALIC: item.append(resourceMap.getString("fontStyleBoldItalic")); break; default: item.append(resourceMap.getString("fontStylePlain")); break; } item.append(")"); return item.toString(); } /** * This methods gets the color-value of the selected font. while the original * value is stored as string, this method converts the hex-string into a * rgb-Color-value. * * @return the font-color, converted to Color-format */ private Color getFontColor() { // init string String c; // get the color-value from the selectet font switch (jComboBoxFonts.getSelectedIndex()) { case 0: c = mainfontcolor; break; case 1: c = authorfontcolor; break; case 2: c = remarksfontcolor; break; case 3: c = titlefontcolor; break; case 4: c = headerfont1color; break; case 5: c = headerfont2color; break; case 6: c = desktopheaderfontcolor; break; case 7: c = desktopcommentfontcolor; break; case 8: c = desktopitemheaderfontcolor; break; case 9: c = desktopitemfontcolor; break; case 10: c = quotefontcolor; break; case 11: c = entryheaderfontcolor; break; case 12: c = appendixheaderfontcolor; break; case 13: c = codefontcolor; break; default: c = mainfontcolor; break; } // if we found a color value, go on... if (c != null) { return new Color(Integer.parseInt(c, 16)); } return Color.BLACK; } /** * This methods gets the color-value of the selected font. while the original * value is stored as string, this method converts the hex-string into a * rgb-Color-value. * * @return the font-color, converted to Color-format */ private Color getBackgroundColor() { // init string String c; // get the color-value from the selectet font switch (jComboBoxBackgroundColors.getSelectedIndex()) { case 0: c = tableheadercolor; break; case 1: c = tablerowevencolor; break; case 2: c = tablerowoddcolor; break; case 3: c = entryheadingscolor; break; case 4: c = quotecolor; break; case 5: c = reflistbgcolor; break; case 6: c = mainbgcolor; break; case 7: c = contentbgcolor; break; case 8: c = linkscolor; break; case 9: c = manlinkscolor; break; case 10: c = fnlinkscolor; break; default: c = tableheadercolor; break; } // if we found a color value, go on... if (c != null) { return new Color(Integer.parseInt(c, 16)); } return Color.BLACK; } /** * Sets the font color for the chosen font * * @param c the new color value, received from the color-chooser and converted * to a hex-string */ private void setFontColor(String c) { // get the color-value from the selectet font switch (jComboBoxFonts.getSelectedIndex()) { case 0: mainfontcolor = c; break; case 1: authorfontcolor = c; break; case 2: remarksfontcolor = c; break; case 3: titlefontcolor = c; break; case 4: headerfont1color = c; break; case 5: headerfont2color = c; break; case 6: desktopheaderfontcolor = c; break; case 7: desktopcommentfontcolor = c; break; case 8: desktopitemheaderfontcolor = c; break; case 9: desktopitemfontcolor = c; break; case 10: quotefontcolor = c; break; case 11: entryheaderfontcolor = c; break; case 12: appendixheaderfontcolor = c; break; case 13: codefontcolor = c; break; default: mainfontcolor = c; break; } setModified(true); displayupdate = true; } /** * Sets the font color for the chosen font * * @param c the new color value, received from the color-chooser and converted * to a hex-string */ private void setBackgroundColor(String c) { // get the color-value from the selectet font switch (jComboBoxBackgroundColors.getSelectedIndex()) { case 0: tableheadercolor = c; break; case 1: tablerowevencolor = c; break; case 2: tablerowoddcolor = c; break; case 3: entryheadingscolor = c; break; case 4: quotecolor = c; break; case 5: reflistbgcolor = c; break; case 6: mainbgcolor = c; break; case 7: contentbgcolor = c; break; case 8: linkscolor = c; break; case 9: manlinkscolor = c; break; case 10: fnlinkscolor = c; break; default: tableheadercolor = c; break; } setModified(true); displayupdate = true; } /** * When the user presses the cancel button, no update needed, close window */ private void cancelWindow() { needsupdate = false; displayupdate = false; closeWindow(); } /** * Occurs when the user closes the window or presses the ok button. the * settings-file is then saved and the window disposed. */ private void closeWindow() { dispose(); setVisible(false); } /** * This method opens the font-choose-dialog, passing the selected font from the * combobox as parameter to set as initial values. */ @Action public void chooseMainfont() { // get the selected font Font f; // the order depends on the item-order of the jcombobox switch (jComboBoxFonts.getSelectedIndex()) { case 0: f = mainfont; break; case 1: f = authorfont; break; case 2: f = remarksfont; break; case 3: f = titlefont; break; case 4: f = headerfont1; break; case 5: f = headerfont2; break; case 6: f = desktopheaderfont; break; case 7: f = desktopcommentfont; break; case 8: f = desktopitemheaderfont; break; case 9: f = desktopitemfont; break; case 10: f = quotefont; break; case 11: f = entryheaderfont; break; case 12: f = appendixheaderfont; break; case 13: f = codefont; break; default: f = mainfont; break; } // create font-chooser dialog if (null == fontDlg) { fontDlg = new CFontChooser(null, f); fontDlg.setLocationRelativeTo(this); } ZettelkastenApp.getApplication().show(fontDlg); // if the user has chosen a font, set it if (fontDlg.selectedFont != null) { // the order depends on the item-order of the jcombobox switch (jComboBoxFonts.getSelectedIndex()) { case 0: mainfont = fontDlg.selectedFont; break; case 1: authorfont = fontDlg.selectedFont; break; case 2: remarksfont = fontDlg.selectedFont; break; case 3: titlefont = fontDlg.selectedFont; break; case 4: headerfont1 = fontDlg.selectedFont; break; case 5: headerfont2 = fontDlg.selectedFont; break; case 6: desktopheaderfont = fontDlg.selectedFont; break; case 7: desktopcommentfont = fontDlg.selectedFont; break; case 8: desktopitemheaderfont = fontDlg.selectedFont; break; case 9: desktopitemfont = fontDlg.selectedFont; break; case 10: quotefont = fontDlg.selectedFont; break; case 11: entryheaderfont = fontDlg.selectedFont; break; case 12: appendixheaderfont = fontDlg.selectedFont; break; case 13: codefont = fontDlg.selectedFont; break; default: mainfont = fontDlg.selectedFont; break; } // and show new item-texts in combobox initComboboxFonts(); // whenever the user changes something, set "modifedLook" state to true // so the apply-button becomes enabled (this variable is connected to // the button's action) setModified(true); displayupdate = true; } // close and dispose the font-dialog fontDlg.dispose(); fontDlg = null; } /** * This method opens a color-chooser-dialog and let's the user choose a font * color for the selected font... */ @Action public void chooseMainfontColor() { // first, show an color-chooser-dialog and let the user choose the color Color color = JColorChooser.showDialog(this, resourceMap.getString("chooseColorMsg"), getFontColor()); // if the user chose a color, proceed if (color != null) { // set color to jLabel jLabelColor.setBackground(color); // convert the color-rgb-values into a hexa-decimal-string // we need the format option to keep the leeding zero of hex-values // from 00 to 0F. String output = String.format("%02x", color.getRed()) + String.format("%02x", color.getGreen()) + String.format("%02x", color.getBlue()); // setFontColor(Integer.toHexString(color.getRed())+Integer.toHexString(color.getGreen())+Integer.toHexString(color.getBlue())); // convert the color-rgb-values into a hexa-decimal-string and save the new font // color setFontColor(output); } } /** * This method opens a color-chooser-dialog and let's the user choose a font * color for the selected font... */ @Action public void chooseBackgroundColor() { // first, show an color-chooser-dialog and let the user choose the color Color color = JColorChooser.showDialog(this, resourceMap.getString("chooseColorMsg"), getBackgroundColor()); // if the user chose a color, proceed if (color != null) { // set color to jLabel jLabelTableColor.setBackground(color); // convert the color-rgb-values into a hexa-decimal-string // we need the format option to keep the leeding zero of hex-values // from 00 to 0F. String output = String.format("%02x", color.getRed()) + String.format("%02x", color.getGreen()) + String.format("%02x", color.getBlue()); // setFontColor(Integer.toHexString(color.getRed())+Integer.toHexString(color.getGreen())+Integer.toHexString(color.getBlue())); // convert the color-rgb-values into a hexa-decimal-string and save the new font // color setBackgroundColor(output); } } /** * Finally, when the user presses the apply-button, all settings are saved. this * is done in this method. when all changes have been saved, the window will be * closed and disposed. */ @Action(enabledProperty = "modified") public void applyChanges() { // check for correct settings // get the value for the image width and check for valid input String val_x = jFormattedTextFieldImgWidth.getValue().toString(); // get the value for the image height and check for valid input String val_y = jFormattedTextFieldImgHeight.getValue().toString(); // init variables int imgresizewidth = 300; int imgresizeheight = 300; try { // convert input-values to integer imgresizewidth = Integer.parseInt(val_x); imgresizeheight = Integer.parseInt(val_y); // check whether values are inside valid boundaries... if ((imgresizewidth < 5) || (imgresizewidth > 9999) || (imgresizeheight < 5) || (imgresizeheight > 9999)) { // tell the user which setting is wrong JOptionPane.showMessageDialog(null, resourceMap.getString("errImgSizeMsg"), resourceMap.getString("errImgSizeTitle"), JOptionPane.PLAIN_MESSAGE); // select the appropriate tabbed pane jTabbedPane1.setSelectedIndex(1); // and set input focus to textfield jFormattedTextFieldImgWidth.requestFocusInWindow(); return; } } catch (NumberFormatException e) { } // get the value for the cell spacing and check for valid input val_x = jSpinnerDistHor.getValue().toString(); // get the value for the cell spacing and check for valid input val_y = jSpinnerDistVer.getValue().toString(); // init variables int spacinghor = 1; int spacingver = 1; try { // convert input-values to integer spacinghor = Integer.parseInt(val_x); spacingver = Integer.parseInt(val_y); // check whether values are inside valid boundaries... if ((spacinghor < 0) || (spacinghor > 25) || (spacingver < 0) || (spacingver > 25)) { // tell the user which setting is wrong JOptionPane.showMessageDialog(null, resourceMap.getString("errSpacingSizeMsg"), resourceMap.getString("errSpacingSizeTitle"), JOptionPane.PLAIN_MESSAGE); // select the appropriate tabbed pane jTabbedPane1.setSelectedIndex(1); // and set input focus to textfield jSpinnerDistHor.requestFocusInWindow(); return; } } catch (NumberFormatException e) { } // check whether changes to winreg have been made if (registryChanges) { registerFileExtension(); } // save all the settings int selectedlaf = jComboBoxLAF.getSelectedIndex(); String laf; if (selectedlaf >= installed_laf.length) laf = Constants.seaGlassLookAndFeelClassName; else laf = installed_laf[jComboBoxLAF.getSelectedIndex()].getClassName(); settings.setLookAndFeel(laf); settings.setShowAtStartup(jComboBoxShowAtStartup.getSelectedIndex()); settings.setManualTimestamp(jComboBoxManualTimestamp.getSelectedIndex()); settings.setShowGridHorizontal(jCheckBoxShowHorGrid.isSelected()); settings.setShowGridVertical(jCheckBoxShowVerGrid.isSelected()); settings.setSpellCorrect(jCheckBoxAutocorrect.isSelected()); settings.setStenoActivated(jCheckBoxSteno.isSelected()); settings.setImageResize(jCheckBoxImgResize.isSelected()); settings.setImageResizeHeight(imgresizeheight); settings.setImageResizeWidth(imgresizewidth); settings.setCellSpacing(spacinghor, spacingver); settings.setDesktopOutlineFontSize(jSliderDesktopFontSize.getValue()); settings.setTextfieldFontSize(jSliderTextfields.getValue()); settings.setAutoBackup(jCheckBoxAutobackup.isSelected()); settings.setSupFootnote(jCheckBoxFootnote.isSelected()); settings.setFootnoteBraces(jCheckBoxFootnoteBraces.isSelected()); settings.setSearchRemovesFormatTags(!jCheckBoxSearchWithoutFormatTags.isSelected()); settings.setJumpFootnote(jCheckBoxJumpToTab.isSelected()); settings.setUseCustomCSS(Settings.CUSTOM_CSS_ENTRY, jCheckBoxEntryCSS.isSelected()); settings.setUseCustomCSS(Settings.CUSTOM_CSS_DESKTOP, jCheckBoxDesktopCSS.isSelected()); settings.setShowIcons(jCheckBoxShowToolbar.isSelected()); settings.setShowAllIcons(jCheckBoxShowAllIcons.isSelected()); settings.setSearchAlwaysSynonyms(jCheckBoxSynonym.isSelected()); settings.setInsertNewEntryAtEmpty(jCheckBoxFillNewEntries.isSelected()); settings.setExtraBackup(jCheckBoxExtraBackup.isSelected()); settings.setAddAllToHistory(jCheckBoxAllToHist.isSelected()); settings.setShowIconText(jCheckBoxIconText.isSelected()); settings.setAutoUpdate(jCheckBoxAutoUpdate.isSelected()); settings.setAutoNightlyUpdate(jCheckBoxCheckNightly.isSelected()); settings.setMinimizeToTray(jCheckBoxSystray.isSelected()); settings.setIconTheme(jComboBoxIconTheme.getSelectedIndex()); settings.setUseXDGOpen(jCheckBoxUseXDGOpen.isSelected()); settings.setAutoCompleteTags(jCheckBoxAutoCompleteTags.isSelected()); settings.setMarkdownActivated(jCheckBoxUseMarkdown.isSelected()); settings.setTableHeaderColor(tableheadercolor); settings.setTableRowEvenColor(tablerowevencolor); settings.setShowTableBorder(jCheckBoxShowTableBorder.isSelected()); settings.setUseMacBackgroundColor(jCheckBoxUseMacBackgroundColor.isSelected()); settings.setShowEntryHeadline(jCheckBoxShowEntryHeadline.isSelected()); settings.setEntryHeadingBackgroundColor(entryheadingscolor); settings.setReflistBackgroundColor(reflistbgcolor); settings.setLinkColor(linkscolor); settings.setManlinkColor(manlinkscolor); settings.setFootnoteLinkColor(fnlinkscolor); settings.setQuoteBackgroundColor(quotecolor); settings.setTableRowOddColor(tablerowoddcolor); settings.setContentBackgroundColor(contentbgcolor); settings.setMainBackgroundColor(mainbgcolor); if (jCheckBoxExtraBackup.isSelected()) { settings.setExtraBackupPath(jTextFieldBackupPath.getText()); } // only save settings to user paths if changes have been made if (userPathChanges) { dataObj.setUserAttachmentPath(jTextFieldAttachmentPath.getText()); dataObj.setUserImagePath(jTextFieldImagePath.getText()); } if (pandocPathChanges) { settings.setPandocPath(jTextFieldPandoc.getText()); } switch (jComboBoxLocale.getSelectedIndex()) { case 0: settings.setLanguage("en"); break; case 1: settings.setLanguage("de"); break; case 2: settings.setLanguage("es"); break; case 3: settings.setLanguage("pt"); break; default: settings.setLanguage("en"); break; } settings.setTableFont(tableFont); settings.setDesktopOutlineFont(desktopfont.getFamily()); // save mainfont String[] styleandweight = getStyleAndWeight(mainfont); settings.setMainfont(mainfont.getFamily(), Settings.FONTNAME); settings.setMainfont(String.valueOf(mainfont.getSize()), Settings.FONTSIZE); settings.setMainfont(styleandweight[0], Settings.FONTSTYLE); settings.setMainfont(styleandweight[1], Settings.FONTWEIGHT); settings.setMainfont(mainfontcolor, Settings.FONTCOLOR); // save quotefont settings.setQuoteFont(quotefont.getFamily(), Settings.FONTNAME); settings.setQuoteFont(String.valueOf(quotefont.getSize()), Settings.FONTSIZE); settings.setQuoteFont(quotefontcolor, Settings.FONTCOLOR); // save entryheaderfont settings.setEntryHeadeFont(entryheaderfont.getFamily(), Settings.FONTNAME); settings.setEntryHeadeFont(String.valueOf(entryheaderfont.getSize()), Settings.FONTSIZE); settings.setEntryHeadeFont(entryheaderfontcolor, Settings.FONTCOLOR); // save authorfont styleandweight = getStyleAndWeight(authorfont); settings.setAuthorFont(authorfont.getFamily(), Settings.FONTNAME); settings.setAuthorFont(String.valueOf(authorfont.getSize()), Settings.FONTSIZE); settings.setAuthorFont(styleandweight[0], Settings.FONTSTYLE); settings.setAuthorFont(styleandweight[1], Settings.FONTWEIGHT); settings.setAuthorFont(authorfontcolor, Settings.FONTCOLOR); // save codefont styleandweight = getStyleAndWeight(codefont); settings.setCodeFont(codefont.getFamily(), Settings.FONTNAME); settings.setCodeFont(String.valueOf(codefont.getSize()), Settings.FONTSIZE); settings.setCodeFont(styleandweight[0], Settings.FONTSTYLE); settings.setCodeFont(styleandweight[1], Settings.FONTWEIGHT); settings.setCodeFont(codefontcolor, Settings.FONTCOLOR); // save remarksfont styleandweight = getStyleAndWeight(remarksfont); settings.setRemarksFont(remarksfont.getFamily(), Settings.FONTNAME); settings.setRemarksFont(String.valueOf(remarksfont.getSize()), Settings.FONTSIZE); settings.setRemarksFont(styleandweight[0], Settings.FONTSTYLE); settings.setRemarksFont(styleandweight[1], Settings.FONTWEIGHT); settings.setRemarksFont(remarksfontcolor, Settings.FONTCOLOR); // save titlefont styleandweight = getStyleAndWeight(titlefont); settings.setTitleFont(titlefont.getFamily(), Settings.FONTNAME); settings.setTitleFont(String.valueOf(titlefont.getSize()), Settings.FONTSIZE); settings.setTitleFont(styleandweight[0], Settings.FONTSTYLE); settings.setTitleFont(styleandweight[1], Settings.FONTWEIGHT); settings.setTitleFont(titlefontcolor, Settings.FONTCOLOR); // save titlefont styleandweight = getStyleAndWeight(appendixheaderfont); settings.setAppendixHeaderFont(appendixheaderfont.getFamily(), Settings.FONTNAME); settings.setAppendixHeaderFont(String.valueOf(appendixheaderfont.getSize()), Settings.FONTSIZE); settings.setAppendixHeaderFont(styleandweight[0], Settings.FONTSTYLE); settings.setAppendixHeaderFont(styleandweight[1], Settings.FONTWEIGHT); settings.setAppendixHeaderFont(appendixheaderfontcolor, Settings.FONTCOLOR); // save header1-font styleandweight = getStyleAndWeight(headerfont1); settings.setHeaderfont1(headerfont1.getFamily(), Settings.FONTNAME); settings.setHeaderfont1(String.valueOf(headerfont1.getSize()), Settings.FONTSIZE); settings.setHeaderfont1(styleandweight[0], Settings.FONTSTYLE); settings.setHeaderfont1(styleandweight[1], Settings.FONTWEIGHT); settings.setHeaderfont1(headerfont1color, Settings.FONTCOLOR); // save header2-font styleandweight = getStyleAndWeight(headerfont2); settings.setHeaderfont2(headerfont2.getFamily(), Settings.FONTNAME); settings.setHeaderfont2(String.valueOf(headerfont2.getSize()), Settings.FONTSIZE); settings.setHeaderfont2(styleandweight[0], Settings.FONTSTYLE); settings.setHeaderfont2(styleandweight[1], Settings.FONTWEIGHT); settings.setHeaderfont2(headerfont2color, Settings.FONTCOLOR); // save desktopheader-font styleandweight = getStyleAndWeight(desktopheaderfont); settings.setDesktopHeaderfont(desktopheaderfont.getFamily(), Settings.FONTNAME); settings.setDesktopHeaderfont(String.valueOf(desktopheaderfont.getSize()), Settings.FONTSIZE); settings.setDesktopHeaderfont(styleandweight[0], Settings.FONTSTYLE); settings.setDesktopHeaderfont(styleandweight[1], Settings.FONTWEIGHT); settings.setDesktopHeaderfont(desktopheaderfontcolor, Settings.FONTCOLOR); // save desktopcomment-font styleandweight = getStyleAndWeight(desktopcommentfont); settings.setDesktopCommentfont(desktopcommentfont.getFamily(), Settings.FONTNAME); settings.setDesktopCommentfont(String.valueOf(desktopcommentfont.getSize()), Settings.FONTSIZE); settings.setDesktopCommentfont(styleandweight[0], Settings.FONTSTYLE); settings.setDesktopCommentfont(styleandweight[1], Settings.FONTWEIGHT); settings.setDesktopCommentfont(desktopcommentfontcolor, Settings.FONTCOLOR); // save desktopitemheader-font styleandweight = getStyleAndWeight(desktopitemheaderfont); settings.setDesktopItemHeaderfont(desktopitemheaderfont.getFamily(), Settings.FONTNAME); settings.setDesktopItemHeaderfont(String.valueOf(desktopitemheaderfont.getSize()), Settings.FONTSIZE); settings.setDesktopItemHeaderfont(styleandweight[0], Settings.FONTSTYLE); settings.setDesktopItemHeaderfont(styleandweight[1], Settings.FONTWEIGHT); settings.setDesktopItemHeaderfont(desktopitemheaderfontcolor, Settings.FONTCOLOR); // save desktopitem-font styleandweight = getStyleAndWeight(desktopitemfont); settings.setDesktopItemfont(desktopitemfont.getFamily(), Settings.FONTNAME); settings.setDesktopItemfont(String.valueOf(desktopitemfont.getSize()), Settings.FONTSIZE); settings.setDesktopItemfont(styleandweight[0], Settings.FONTSTYLE); settings.setDesktopItemfont(styleandweight[1], Settings.FONTWEIGHT); settings.setDesktopItemfont(desktopitemfontcolor, Settings.FONTCOLOR); // save the changes to the settings-file savesettingok = settings.saveSettingsToFiles(); // finally disable button again setModified(false); // and close window closeWindow(); } /** * Since the font-properties like plain, bold etc. are different in * CSS-definitions, we convert the Font-properties to CSS-properties here. We * need this for setting up the HTML-page that displays entries. The formatting * is done via style-tags and CSS, so we need the CSS-definitions... * * @param f the font from which we want to retrieve the style-properties in * CSS-values * @return a string array with two fields: field one holding the * css-font-style-property, and the second field holding the the * css-font-weight-property. */ private String[] getStyleAndWeight(Font f) { String style = "normal"; String weight = "normal"; if (Font.PLAIN == f.getStyle()) { style = "normal"; weight = "normal"; } else if (Font.BOLD == f.getStyle()) { style = "normal"; weight = "bold"; } else if (Font.ITALIC == f.getStyle()) { style = "italic"; weight = "normal"; } else if ((Font.BOLD + Font.ITALIC) == f.getStyle()) { style = "italic"; weight = "bold"; } // prepare return value String[] retval = new String[2]; retval[0] = style; retval[1] = weight; return retval; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated // Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jButtonApply = new javax.swing.JButton(); jButtonCancel = new javax.swing.JButton(); jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel3 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); jComboBoxShowAtStartup = new javax.swing.JComboBox<String>(); jCheckBoxAutobackup = new javax.swing.JCheckBox(); jCheckBoxAutocorrect = new javax.swing.JCheckBox(); jCheckBoxSteno = new javax.swing.JCheckBox(); jButtonEditAutokorrekt = new javax.swing.JButton(); jButtonSynonymEdit = new javax.swing.JButton(); jCheckBoxSynonym = new javax.swing.JCheckBox(); jCheckBoxFillNewEntries = new javax.swing.JCheckBox(); jButtonEditSteno = new javax.swing.JButton(); jCheckBoxExtraBackup = new javax.swing.JCheckBox(); jTextFieldBackupPath = new javax.swing.JTextField(); jButtonBrowseBackup = new javax.swing.JButton(); jLabel13 = new javax.swing.JLabel(); jCheckBoxAllToHist = new javax.swing.JCheckBox(); jCheckBoxRegistry = new javax.swing.JCheckBox(); jCheckBoxSystray = new javax.swing.JCheckBox(); jCheckBoxAutoCompleteTags = new javax.swing.JCheckBox(); jCheckBoxUseMarkdown = new javax.swing.JCheckBox(); jCheckBoxSearchWithoutFormatTags = new javax.swing.JCheckBox(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jComboBoxLAF = new javax.swing.JComboBox<String>(); jCheckBoxImgResize = new javax.swing.JCheckBox(); jLabel4 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jFormattedTextFieldImgWidth = new javax.swing.JFormattedTextField(); jFormattedTextFieldImgHeight = new javax.swing.JFormattedTextField(); jCheckBoxFootnote = new javax.swing.JCheckBox(); jCheckBoxJumpToTab = new javax.swing.JCheckBox(); jCheckBoxIconText = new javax.swing.JCheckBox(); jLabel12 = new javax.swing.JLabel(); jComboBoxManualTimestamp = new javax.swing.JComboBox<String>(); jComboBoxLocale = new JComboBox<String>(); jLabel15 = new javax.swing.JLabel(); jCheckBoxShowToolbar = new javax.swing.JCheckBox(); jCheckBoxShowAllIcons = new javax.swing.JCheckBox(); jLabel10 = new javax.swing.JLabel(); jComboBoxIconTheme = new javax.swing.JComboBox<String>(); jCheckBoxShowTableBorder = new javax.swing.JCheckBox(); jCheckBoxShowEntryHeadline = new javax.swing.JCheckBox(); jCheckBoxUseMacBackgroundColor = new javax.swing.JCheckBox(); jCheckBoxFootnoteBraces = new javax.swing.JCheckBox(); jPanel5 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jComboBoxFonts = new javax.swing.JComboBox<String>(); jButtonFont = new javax.swing.JButton(); jLabelColor = new javax.swing.JLabel(); jButtonFontcolor = new javax.swing.JButton(); jLabel19 = new javax.swing.JLabel(); jComboBoxBackgroundColors = new javax.swing.JComboBox<String>(); jLabelTableColor = new javax.swing.JLabel(); jButtonTableBackgroundColor = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); jButtonHighlightStyle = new javax.swing.JButton(); jLabel20 = new javax.swing.JLabel(); jButtonHighlightKeywordStyle = new javax.swing.JButton(); jLabel21 = new javax.swing.JLabel(); jButtonHighlightLivesearchStyle = new javax.swing.JButton(); jCheckBoxEntryCSS = new javax.swing.JCheckBox(); jButtonEntryCss = new javax.swing.JButton(); jCheckBoxDesktopCSS = new javax.swing.JCheckBox(); jButtonDesktopCSS = new javax.swing.JButton(); jButtonResetEntryCSS = new javax.swing.JButton(); jButtonResetDesktopCSS = new javax.swing.JButton(); jPanel11 = new javax.swing.JPanel(); jCheckBoxShowHorGrid = new javax.swing.JCheckBox(); jCheckBoxShowVerGrid = new javax.swing.JCheckBox(); jSpinnerDistHor = new javax.swing.JSpinner(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jSpinnerDistVer = new javax.swing.JSpinner(); jLabel9 = new javax.swing.JLabel(); jSliderFontSize = new javax.swing.JSlider(); jLabel11 = new javax.swing.JLabel(); jSliderTextfields = new javax.swing.JSlider(); jLabel16 = new javax.swing.JLabel(); jButtonListFont = new javax.swing.JButton(); jButtonDesktopFont = new javax.swing.JButton(); jLabel23 = new javax.swing.JLabel(); jSliderDesktopFontSize = new javax.swing.JSlider(); jLabelFontDeskLayout = new javax.swing.JLabel(); jPanel7 = new javax.swing.JPanel(); jLabel17 = new javax.swing.JLabel(); jTextFieldAttachmentPath = new javax.swing.JTextField(); jButtonBrowseAttachmentPath = new javax.swing.JButton(); jLabel18 = new javax.swing.JLabel(); jTextFieldImagePath = new javax.swing.JTextField(); jButtonBrowseImagePath = new javax.swing.JButton(); jCheckBoxUseXDGOpen = new javax.swing.JCheckBox(); jLabel14 = new javax.swing.JLabel(); jTextFieldPandoc = new javax.swing.JTextField(); jButtonBrowsePandoc = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); jCheckBoxAutoUpdate = new javax.swing.JCheckBox(); jCheckBoxCheckNightly = new javax.swing.JCheckBox(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance() .getContext().getResourceMap(CSettingsDlg.class); setTitle(resourceMap.getString("FormSettingsDlg.title")); // NOI18N setModal(true); setName("FormSettingsDlg"); // NOI18N setResizable(false); jPanel1.setName("jPanel1"); // NOI18N javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance().getContext() .getActionMap(CSettingsDlg.class, this); jButtonApply.setAction(actionMap.get("applyChanges")); // NOI18N jButtonApply.setName("jButtonApply"); // NOI18N jButtonCancel.setText(resourceMap.getString("jButtonCancel.text")); // NOI18N jButtonCancel.setName("jButtonCancel"); // NOI18N jTabbedPane1.setTabLayoutPolicy(javax.swing.JTabbedPane.SCROLL_TAB_LAYOUT); jTabbedPane1.setName("jTabbedPane1"); // NOI18N jPanel3.setName("jPanel3"); // NOI18N jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N jLabel3.setName("jLabel3"); // NOI18N jComboBoxShowAtStartup.setName("jComboBoxShowAtStartup"); // NOI18N jCheckBoxAutobackup.setText(resourceMap.getString("jCheckBoxAutobackup.text")); // NOI18N jCheckBoxAutobackup.setName("jCheckBoxAutobackup"); // NOI18N jCheckBoxAutocorrect.setText(resourceMap.getString("jCheckBoxAutocorrect.text")); // NOI18N jCheckBoxAutocorrect.setName("jCheckBoxAutocorrect"); // NOI18N jCheckBoxSteno.setText(resourceMap.getString("jCheckBoxSteno.text")); // NOI18N jCheckBoxSteno.setName("jCheckBoxSteno"); // NOI18N jButtonEditAutokorrekt.setText(resourceMap.getString("jButtonEditAutokorrekt.text")); // NOI18N jButtonEditAutokorrekt.setName("jButtonEditAutokorrekt"); // NOI18N jButtonSynonymEdit.setText(resourceMap.getString("jButtonSynonymEdit.text")); // NOI18N jButtonSynonymEdit.setName("jButtonSynonymEdit"); // NOI18N jCheckBoxSynonym.setText(resourceMap.getString("jCheckBoxSynonym.text")); // NOI18N jCheckBoxSynonym.setToolTipText(resourceMap.getString("jCheckBoxSynonym.toolTipText")); // NOI18N jCheckBoxSynonym.setName("jCheckBoxSynonym"); // NOI18N jCheckBoxFillNewEntries.setText(resourceMap.getString("jCheckBoxFillNewEntries.text")); // NOI18N jCheckBoxFillNewEntries.setToolTipText(resourceMap.getString("jCheckBoxFillNewEntries.toolTipText")); // NOI18N jCheckBoxFillNewEntries.setName("jCheckBoxFillNewEntries"); // NOI18N jButtonEditSteno.setText(resourceMap.getString("jButtonEditSteno.text")); // NOI18N jButtonEditSteno.setName("jButtonEditSteno"); // NOI18N jCheckBoxExtraBackup.setText(resourceMap.getString("jCheckBoxExtraBackup.text")); // NOI18N jCheckBoxExtraBackup.setName("jCheckBoxExtraBackup"); // NOI18N jTextFieldBackupPath.setName("jTextFieldBackupPath"); // NOI18N jButtonBrowseBackup.setText(resourceMap.getString("jButtonBrowseBackup.text")); // NOI18N jButtonBrowseBackup.setName("jButtonBrowseBackup"); // NOI18N jLabel13.setText(resourceMap.getString("jLabel13.text")); // NOI18N jLabel13.setName("jLabel13"); // NOI18N jCheckBoxAllToHist.setText(resourceMap.getString("jCheckBoxAllToHist.text")); // NOI18N jCheckBoxAllToHist.setToolTipText(resourceMap.getString("jCheckBoxAllToHist.toolTipText")); // NOI18N jCheckBoxAllToHist.setName("jCheckBoxAllToHist"); // NOI18N jCheckBoxRegistry.setText(resourceMap.getString("jCheckBoxRegistry.text")); // NOI18N jCheckBoxRegistry.setName("jCheckBoxRegistry"); // NOI18N jCheckBoxSystray.setText(resourceMap.getString("jCheckBoxSystray.text")); // NOI18N jCheckBoxSystray.setName("jCheckBoxSystray"); // NOI18N jCheckBoxAutoCompleteTags.setText(resourceMap.getString("jCheckBoxAutoCompleteTags.text")); // NOI18N jCheckBoxAutoCompleteTags.setName("jCheckBoxAutoCompleteTags"); // NOI18N jCheckBoxUseMarkdown.setText(resourceMap.getString("jCheckBoxUseMarkdown.text")); // NOI18N jCheckBoxUseMarkdown.setName("jCheckBoxUseMarkdown"); // NOI18N jCheckBoxSearchWithoutFormatTags.setText(resourceMap.getString("jCheckBoxSearchWithoutFormatTags.text")); // NOI18N jCheckBoxSearchWithoutFormatTags .setToolTipText(resourceMap.getString("jCheckBoxSearchWithoutFormatTags.toolTipText")); // NOI18N jCheckBoxSearchWithoutFormatTags.setName("jCheckBoxSearchWithoutFormatTags"); // NOI18N javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup().addContainerGap().addGroup(jPanel3Layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jCheckBoxSystray) .addComponent(jCheckBoxRegistry) .addGroup(jPanel3Layout.createSequentialGroup().addGroup(jPanel3Layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jCheckBoxSteno).addComponent(jCheckBoxAutocorrect) .addGroup(jPanel3Layout.createSequentialGroup().addGap(21, 21, 21) .addComponent(jLabel13) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextFieldBackupPath, javax.swing.GroupLayout.PREFERRED_SIZE, 261, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButtonEditAutokorrekt, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButtonEditSteno, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButtonBrowseBackup, javax.swing.GroupLayout.Alignment.TRAILING))) .addComponent(jCheckBoxExtraBackup).addComponent(jCheckBoxAutobackup) .addGroup(jPanel3Layout.createSequentialGroup().addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBoxShowAtStartup, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel3Layout.createSequentialGroup().addComponent(jCheckBoxSynonym) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonSynonymEdit)) .addComponent(jCheckBoxFillNewEntries).addComponent(jCheckBoxSearchWithoutFormatTags) .addComponent(jCheckBoxAllToHist).addComponent(jCheckBoxAutoCompleteTags) .addComponent(jCheckBoxUseMarkdown)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))); jPanel3Layout.setVerticalGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup().addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3).addComponent(jComboBoxShowAtStartup, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18).addComponent(jCheckBoxAutobackup) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxExtraBackup) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldBackupPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel13).addComponent(jButtonBrowseBackup)) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCheckBoxAutocorrect).addComponent(jButtonEditAutokorrekt)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCheckBoxSteno).addComponent(jButtonEditSteno)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxAutoCompleteTags) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxUseMarkdown).addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCheckBoxSynonym).addComponent(jButtonSynonymEdit)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxSearchWithoutFormatTags) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxFillNewEntries) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxAllToHist) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxRegistry) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxSystray) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))); jTabbedPane1.addTab(resourceMap.getString("jPanel3.TabConstraints.tabTitle"), jPanel3); // NOI18N jPanel2.setName("jPanel2"); // NOI18N jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N jLabel1.setName("jLabel1"); // NOI18N jComboBoxLAF.setName("jComboBoxLAF"); // NOI18N jCheckBoxImgResize.setText(resourceMap.getString("jCheckBoxImgResize.text")); // NOI18N jCheckBoxImgResize.setName("jCheckBoxImgResize"); // NOI18N jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N jLabel4.setName("jLabel4"); // NOI18N jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N jLabel6.setName("jLabel6"); // NOI18N jFormattedTextFieldImgWidth.setColumns(5); jFormattedTextFieldImgWidth.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory( new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("####")))); jFormattedTextFieldImgWidth.setName("jFormattedTextFieldImgWidth"); // NOI18N jFormattedTextFieldImgHeight.setColumns(5); jFormattedTextFieldImgHeight.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory( new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("####")))); jFormattedTextFieldImgHeight.setName("jFormattedTextFieldImgHeight"); // NOI18N jCheckBoxFootnote.setText(resourceMap.getString("jCheckBoxFootnote.text")); // NOI18N jCheckBoxFootnote.setName("jCheckBoxFootnote"); // NOI18N jCheckBoxJumpToTab.setText(resourceMap.getString("jCheckBoxJumpToTab.text")); // NOI18N jCheckBoxJumpToTab.setName("jCheckBoxJumpToTab"); // NOI18N jCheckBoxIconText.setText(resourceMap.getString("jCheckBoxIconText.text")); // NOI18N jCheckBoxIconText.setName("jCheckBoxIconText"); // NOI18N jLabel12.setText(resourceMap.getString("jLabel12.text")); // NOI18N jLabel12.setName("jLabel12"); // NOI18N jComboBoxManualTimestamp.setName("jComboBoxManualTimestamp"); // NOI18N jComboBoxLocale.setModel(new javax.swing.DefaultComboBoxModel<String>( new String[] { "English", "German (Deutsch)", "Spanish (Espanol)", "Portuguese (Brazil)" })); jComboBoxLocale.setName("jComboBoxLocale"); // NOI18N jLabel15.setText(resourceMap.getString("jLabel15.text")); // NOI18N jLabel15.setName("jLabel15"); // NOI18N jCheckBoxShowToolbar.setText(resourceMap.getString("jCheckBoxShowToolbar.text")); // NOI18N jCheckBoxShowToolbar.setName("jCheckBoxShowToolbar"); // NOI18N jCheckBoxShowAllIcons.setText(resourceMap.getString("jCheckBoxShowAllIcons.text")); // NOI18N jCheckBoxShowAllIcons.setName("jCheckBoxShowAllIcons"); // NOI18N jLabel10.setText(resourceMap.getString("jLabel10.text")); // NOI18N jLabel10.setName("jLabel10"); // NOI18N jComboBoxIconTheme.setName("jComboBoxIconTheme"); // NOI18N jCheckBoxShowTableBorder.setText(resourceMap.getString("jCheckBoxShowTableBorder.text")); // NOI18N jCheckBoxShowTableBorder.setName("jCheckBoxShowTableBorder"); // NOI18N jCheckBoxShowEntryHeadline.setText(resourceMap.getString("jCheckBoxShowEntryHeadline.text")); // NOI18N jCheckBoxShowEntryHeadline.setName("jCheckBoxShowEntryHeadline"); // NOI18N jCheckBoxUseMacBackgroundColor.setText(resourceMap.getString("jCheckBoxUseMacBackgroundColor.text")); // NOI18N jCheckBoxUseMacBackgroundColor.setName("jCheckBoxUseMacBackgroundColor"); // NOI18N jCheckBoxFootnoteBraces.setText(resourceMap.getString("jCheckBoxFootnoteBraces.text")); // NOI18N jCheckBoxFootnoteBraces.setName("jCheckBoxFootnoteBraces"); // NOI18N javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup().addContainerGap().addGroup(jPanel2Layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jCheckBoxFootnoteBraces) .addGroup(jPanel2Layout.createSequentialGroup().addGap(29, 29, 29) .addComponent(jCheckBoxShowAllIcons)) .addGroup(jPanel2Layout.createSequentialGroup().addComponent(jLabel12) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBoxManualTimestamp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jCheckBoxIconText).addComponent(jCheckBoxShowToolbar) .addGroup(jPanel2Layout.createSequentialGroup().addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBoxIconTheme, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup().addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBoxLAF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup().addComponent(jLabel15) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBoxLocale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jCheckBoxShowTableBorder).addComponent(jCheckBoxFootnote) .addComponent(jCheckBoxJumpToTab)) .addGroup(jPanel2Layout.createSequentialGroup().addGap(27, 27, 27) .addGroup(jPanel2Layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4).addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jFormattedTextFieldImgWidth, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jFormattedTextFieldImgHeight, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(jCheckBoxImgResize)) .addComponent(jCheckBoxShowEntryHeadline).addComponent(jCheckBoxUseMacBackgroundColor)) .addContainerGap())); jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup().addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel15).addComponent(jComboBoxLocale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1).addComponent(jComboBoxLAF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxUseMacBackgroundColor) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel12).addComponent(jComboBoxManualTimestamp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxShowToolbar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxShowAllIcons) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxIconText) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10).addComponent(jComboBoxIconTheme, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxImgResize) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4).addComponent(jFormattedTextFieldImgWidth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6).addComponent(jFormattedTextFieldImgHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxShowEntryHeadline) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxShowTableBorder) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxFootnote) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxFootnoteBraces) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxJumpToTab).addContainerGap())); jTabbedPane1.addTab(resourceMap.getString("jPanel2.TabConstraints.tabTitle"), jPanel2); // NOI18N jPanel5.setName("jPanel5"); // NOI18N jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N jLabel2.setName("jLabel2"); // NOI18N jComboBoxFonts.setName("jComboBoxFonts"); // NOI18N jButtonFont.setAction(actionMap.get("chooseMainfont")); // NOI18N jButtonFont.setText(resourceMap.getString("jButtonFont.text")); // NOI18N jButtonFont.setBorderPainted(false); jButtonFont.setContentAreaFilled(false); jButtonFont.setFocusPainted(false); jButtonFont.setName("jButtonFont"); // NOI18N jLabelColor.setText(resourceMap.getString("jLabelColor.text")); // NOI18N jLabelColor.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jLabelColor.setName("jLabelColor"); // NOI18N jLabelColor.setOpaque(true); jButtonFontcolor.setAction(actionMap.get("chooseMainfontColor")); // NOI18N jButtonFontcolor.setBorderPainted(false); jButtonFontcolor.setContentAreaFilled(false); jButtonFontcolor.setFocusPainted(false); jButtonFontcolor.setName("jButtonFontcolor"); // NOI18N jLabel19.setText(resourceMap.getString("jLabel19.text")); // NOI18N jLabel19.setName("jLabel19"); // NOI18N jComboBoxBackgroundColors.setName("jComboBoxBackgroundColors"); // NOI18N jLabelTableColor.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jLabelTableColor.setName("jLabelTableColor"); // NOI18N jLabelTableColor.setOpaque(true); jButtonTableBackgroundColor.setAction(actionMap.get("chooseBackgroundColor")); // NOI18N jButtonTableBackgroundColor.setBorderPainted(false); jButtonTableBackgroundColor.setContentAreaFilled(false); jButtonTableBackgroundColor.setFocusPainted(false); jButtonTableBackgroundColor.setName("jButtonTableBackgroundColor"); // NOI18N jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N jLabel5.setName("jLabel5"); // NOI18N jButtonHighlightStyle.setText(resourceMap.getString("jButtonHighlightStyle.text")); // NOI18N jButtonHighlightStyle.setName("jButtonHighlightStyle"); // NOI18N jLabel20.setText(resourceMap.getString("jLabel20.text")); // NOI18N jLabel20.setName("jLabel20"); // NOI18N jButtonHighlightKeywordStyle.setText(resourceMap.getString("jButtonHighlightKeywordStyle.text")); // NOI18N jButtonHighlightKeywordStyle.setName("jButtonHighlightKeywordStyle"); // NOI18N jLabel21.setText(resourceMap.getString("jLabel21.text")); // NOI18N jLabel21.setName("jLabel21"); // NOI18N jButtonHighlightLivesearchStyle.setText(resourceMap.getString("jButtonHighlightLivesearchStyle.text")); // NOI18N jButtonHighlightLivesearchStyle.setName("jButtonHighlightLivesearchStyle"); // NOI18N jCheckBoxEntryCSS.setText(resourceMap.getString("jCheckBoxEntryCSS.text")); // NOI18N jCheckBoxEntryCSS.setName("jCheckBoxEntryCSS"); // NOI18N jButtonEntryCss.setText(resourceMap.getString("jButtonEntryCss.text")); // NOI18N jButtonEntryCss.setName("jButtonEntryCss"); // NOI18N jCheckBoxDesktopCSS.setText(resourceMap.getString("jCheckBoxDesktopCSS.text")); // NOI18N jCheckBoxDesktopCSS.setName("jCheckBoxDesktopCSS"); // NOI18N jButtonDesktopCSS.setText(resourceMap.getString("jButtonDesktopCSS.text")); // NOI18N jButtonDesktopCSS.setName("jButtonDesktopCSS"); // NOI18N jButtonResetEntryCSS.setText(resourceMap.getString("jButtonResetEntryCSS.text")); // NOI18N jButtonResetEntryCSS.setName("jButtonResetEntryCSS"); // NOI18N jButtonResetDesktopCSS.setText(resourceMap.getString("jButtonResetDesktopCSS.text")); // NOI18N jButtonResetDesktopCSS.setName("jButtonResetDesktopCSS"); // NOI18N javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup().addGroup(jPanel5Layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup().addGap(10, 10, 10).addComponent(jLabel19) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBoxBackgroundColors, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelTableColor, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonTableBackgroundColor, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel5Layout.createSequentialGroup().addGap(10, 10, 10).addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBoxFonts, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelColor, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonFont, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonFontcolor, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel5Layout.createSequentialGroup().addContainerGap() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5).addComponent(jLabel20).addComponent(jLabel21) .addComponent(jCheckBoxEntryCSS).addComponent(jCheckBoxDesktopCSS)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButtonDesktopCSS).addComponent(jButtonEntryCss) .addComponent(jButtonHighlightStyle).addComponent(jButtonHighlightKeywordStyle) .addComponent(jButtonHighlightLivesearchStyle) .addComponent(jButtonResetEntryCSS).addComponent(jButtonResetDesktopCSS)))) .addContainerGap())); jPanel5Layout .setVerticalGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup().addContainerGap().addGroup(jPanel5Layout .createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER).addComponent(jLabel2) .addComponent(jComboBoxFonts, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonFont).addComponent(jButtonFontcolor) .addComponent(jLabelColor, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(jPanel5Layout .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel19).addComponent(jComboBoxBackgroundColors, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabelTableColor, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonTableBackgroundColor, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5).addComponent(jButtonHighlightStyle)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel20).addComponent(jButtonHighlightKeywordStyle)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel21).addComponent(jButtonHighlightLivesearchStyle)) .addGap(18, 18, 18) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCheckBoxEntryCSS).addComponent(jButtonEntryCss)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonResetEntryCSS).addGap(18, 18, 18) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCheckBoxDesktopCSS).addComponent(jButtonDesktopCSS)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonResetDesktopCSS).addContainerGap())); jTabbedPane1.addTab(resourceMap.getString("jPanel5.TabConstraints.tabTitle"), jPanel5); // NOI18N jPanel11.setName("jPanel11"); // NOI18N jCheckBoxShowHorGrid.setText(resourceMap.getString("jCheckBoxShowHorGrid.text")); // NOI18N jCheckBoxShowHorGrid.setName("jCheckBoxShowHorGrid"); // NOI18N jCheckBoxShowVerGrid.setText(resourceMap.getString("jCheckBoxShowVerGrid.text")); // NOI18N jCheckBoxShowVerGrid.setName("jCheckBoxShowVerGrid"); // NOI18N jSpinnerDistHor.setModel(new javax.swing.SpinnerNumberModel(1, 0, 25, 1)); jSpinnerDistHor.setName("jSpinnerDistHor"); // NOI18N jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N jLabel7.setName("jLabel7"); // NOI18N jLabel8.setText(resourceMap.getString("jLabel8.text")); // NOI18N jLabel8.setName("jLabel8"); // NOI18N jSpinnerDistVer.setModel(new javax.swing.SpinnerNumberModel(1, 0, 25, 1)); jSpinnerDistVer.setName("jSpinnerDistVer"); // NOI18N jLabel9.setText(resourceMap.getString("jLabel9.text")); // NOI18N jLabel9.setName("jLabel9"); // NOI18N jSliderFontSize.setMajorTickSpacing(1); jSliderFontSize.setMaximum(18); jSliderFontSize.setMinorTickSpacing(1); jSliderFontSize.setPaintTicks(true); jSliderFontSize.setSnapToTicks(true); jSliderFontSize.setName("jSliderFontSize"); // NOI18N jLabel11.setText(resourceMap.getString("jLabel11.text")); // NOI18N jLabel11.setName("jLabel11"); // NOI18N jSliderTextfields.setMajorTickSpacing(1); jSliderTextfields.setMaximum(8); jSliderTextfields.setMinorTickSpacing(1); jSliderTextfields.setPaintTicks(true); jSliderTextfields.setSnapToTicks(true); jSliderTextfields.setName("jSliderTextfields"); // NOI18N jLabel16.setText(resourceMap.getString("jLabel16.text")); // NOI18N jLabel16.setName("jLabel16"); // NOI18N jButtonListFont.setText(resourceMap.getString("jButtonListFont.text")); // NOI18N jButtonListFont.setName("jButtonListFont"); // NOI18N jButtonDesktopFont.setText(resourceMap.getString("jButtonDesktopFont.text")); // NOI18N jButtonDesktopFont.setName("jButtonDesktopFont"); // NOI18N jLabel23.setText(resourceMap.getString("jLabel23.text")); // NOI18N jLabel23.setName("jLabel23"); // NOI18N jSliderDesktopFontSize.setMajorTickSpacing(1); jSliderDesktopFontSize.setMaximum(8); jSliderDesktopFontSize.setMinorTickSpacing(1); jSliderDesktopFontSize.setPaintTicks(true); jSliderDesktopFontSize.setSnapToTicks(true); jSliderDesktopFontSize.setName("jSliderDesktopFontSize"); // NOI18N jLabelFontDeskLayout.setText(resourceMap.getString("jLabelFontDeskLayout.text")); // NOI18N jLabelFontDeskLayout.setName("jLabelFontDeskLayout"); // NOI18N javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11); jPanel11.setLayout(jPanel11Layout); jPanel11Layout.setHorizontalGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel11Layout.createSequentialGroup().addContainerGap().addGroup(jPanel11Layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jLabel9) .addComponent(jLabel23) .addGroup(jPanel11Layout.createSequentialGroup() .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel8).addComponent(jLabel7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSpinnerDistHor, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jSpinnerDistVer, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(jCheckBoxShowHorGrid).addComponent(jCheckBoxShowVerGrid) .addComponent(jSliderFontSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jSliderTextfields, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel11) .addComponent(jSliderDesktopFontSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel11Layout.createSequentialGroup() .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelFontDeskLayout).addComponent(jLabel16)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel11Layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButtonDesktopFont, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonListFont, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addContainerGap())); jPanel11Layout.setVerticalGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel11Layout.createSequentialGroup().addContainerGap().addComponent(jCheckBoxShowHorGrid) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxShowVerGrid) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGap(18, 18, 18) .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jSpinnerDistHor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jSpinnerDistVer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18).addComponent(jLabel9).addGap(0, 0, 0) .addComponent(jSliderFontSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18).addComponent(jLabel23) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSliderDesktopFontSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18).addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSliderTextfields, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel16).addComponent(jButtonListFont)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelFontDeskLayout).addComponent(jButtonDesktopFont)) .addContainerGap())); jTabbedPane1.addTab(resourceMap.getString("jPanel11.TabConstraints.tabTitle"), jPanel11); // NOI18N jPanel7.setName("jPanel7"); // NOI18N jLabel17.setText(resourceMap.getString("jLabel17.text")); // NOI18N jLabel17.setName("jLabel17"); // NOI18N jTextFieldAttachmentPath.setName("jTextFieldAttachmentPath"); // NOI18N jButtonBrowseAttachmentPath.setText(resourceMap.getString("jButtonBrowseAttachmentPath.text")); // NOI18N jButtonBrowseAttachmentPath.setName("jButtonBrowseAttachmentPath"); // NOI18N jLabel18.setText(resourceMap.getString("jLabel18.text")); // NOI18N jLabel18.setName("jLabel18"); // NOI18N jTextFieldImagePath.setName("jTextFieldImagePath"); // NOI18N jButtonBrowseImagePath.setText(resourceMap.getString("jButtonBrowseImagePath.text")); // NOI18N jButtonBrowseImagePath.setName("jButtonBrowseImagePath"); // NOI18N jCheckBoxUseXDGOpen.setText(resourceMap.getString("jCheckBoxUseXDGOpen.text")); // NOI18N jCheckBoxUseXDGOpen.setName("jCheckBoxUseXDGOpen"); // NOI18N jLabel14.setText(resourceMap.getString("jLabel14.text")); // NOI18N jLabel14.setName("jLabel14"); // NOI18N jTextFieldPandoc.setName("jTextFieldPandoc"); // NOI18N jButtonBrowsePandoc.setText(resourceMap.getString("jButtonBrowsePandoc.text")); // NOI18N jButtonBrowsePandoc.setName("jButtonBrowsePandoc"); // NOI18N javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7); jPanel7.setLayout(jPanel7Layout); jPanel7Layout.setHorizontalGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup().addContainerGap().addGroup(jPanel7Layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup( jPanel7Layout.createSequentialGroup().addGap(6, 6, 6).addComponent(jCheckBoxUseXDGOpen)) .addGroup(jPanel7Layout.createSequentialGroup() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel17).addComponent(jLabel14).addComponent(jLabel18)) .addGap(18, 18, 18) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextFieldAttachmentPath, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE) .addComponent(jTextFieldImagePath, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextFieldPandoc, javax.swing.GroupLayout.Alignment.TRAILING)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButtonBrowseAttachmentPath, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButtonBrowseImagePath, javax.swing.GroupLayout.Alignment.TRAILING)) .addComponent(jButtonBrowsePandoc)))) .addContainerGap())); jPanel7Layout.setVerticalGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup().addContainerGap() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldAttachmentPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel17).addComponent(jButtonBrowseAttachmentPath)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldImagePath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel18).addComponent(jButtonBrowseImagePath)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel14) .addComponent(jTextFieldPandoc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonBrowsePandoc)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxUseXDGOpen).addContainerGap())); jTabbedPane1.addTab(resourceMap.getString("jPanel7.TabConstraints.tabTitle"), jPanel7); // NOI18N jPanel4.setName("jPanel4"); // NOI18N jCheckBoxAutoUpdate.setText(resourceMap.getString("jCheckBoxAutoUpdate.text")); // NOI18N jCheckBoxAutoUpdate.setName("jCheckBoxAutoUpdate"); // NOI18N jCheckBoxCheckNightly.setText(resourceMap.getString("jCheckBoxCheckNightly.text")); // NOI18N jCheckBoxCheckNightly.setName("jCheckBoxCheckNightly"); // NOI18N javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup().addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup().addGap(27, 27, 27) .addComponent(jCheckBoxCheckNightly)) .addComponent(jCheckBoxAutoUpdate)) .addContainerGap())); jPanel4Layout.setVerticalGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup().addContainerGap().addComponent(jCheckBoxAutoUpdate) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxCheckNightly).addContainerGap())); jTabbedPane1.addTab(resourceMap.getString("jPanel4.TabConstraints.tabTitle"), jPanel4); // NOI18N javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup().addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTabbedPane1).addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup().addGap(0, 0, Short.MAX_VALUE) .addComponent(jButtonCancel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonApply))) .addContainerGap())); jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonCancel).addComponent(jButtonApply)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap())); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))); pack(); }// </editor-fold>//GEN-END:initComponents private boolean modified = false; public boolean isModified() { return modified; } public final void setModified(boolean b) { boolean old = isModified(); this.modified = b; firePropertyChange("modified", old, isModified()); } private boolean synmodified = false; public boolean isSynModified() { return synmodified; } public final void setSynModified(boolean b) { synmodified = b; } /** * * @return */ public boolean isSaveSettingsOk() { return savesettingok; } /** * return value for the main window so we know whether we have to update the * display. * * @return */ public boolean getNeedsUpdate() { return needsupdate; } public boolean getDisplayUpdate() { return displayupdate; } /** * * @return */ public boolean getNeedsLafUpdate() { return lafupdate; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonApply; private javax.swing.JButton jButtonBrowseAttachmentPath; private javax.swing.JButton jButtonBrowseBackup; private javax.swing.JButton jButtonBrowseImagePath; private javax.swing.JButton jButtonBrowsePandoc; private javax.swing.JButton jButtonCancel; private javax.swing.JButton jButtonDesktopCSS; private javax.swing.JButton jButtonDesktopFont; private javax.swing.JButton jButtonEditAutokorrekt; private javax.swing.JButton jButtonEditSteno; private javax.swing.JButton jButtonEntryCss; private javax.swing.JButton jButtonFont; private javax.swing.JButton jButtonFontcolor; private javax.swing.JButton jButtonHighlightKeywordStyle; private javax.swing.JButton jButtonHighlightLivesearchStyle; private javax.swing.JButton jButtonHighlightStyle; private javax.swing.JButton jButtonListFont; private javax.swing.JButton jButtonResetDesktopCSS; private javax.swing.JButton jButtonResetEntryCSS; private javax.swing.JButton jButtonSynonymEdit; private javax.swing.JButton jButtonTableBackgroundColor; private javax.swing.JCheckBox jCheckBoxAllToHist; private javax.swing.JCheckBox jCheckBoxAutoCompleteTags; private javax.swing.JCheckBox jCheckBoxAutoUpdate; private javax.swing.JCheckBox jCheckBoxAutobackup; private javax.swing.JCheckBox jCheckBoxAutocorrect; private javax.swing.JCheckBox jCheckBoxCheckNightly; private javax.swing.JCheckBox jCheckBoxDesktopCSS; private javax.swing.JCheckBox jCheckBoxEntryCSS; private javax.swing.JCheckBox jCheckBoxExtraBackup; private javax.swing.JCheckBox jCheckBoxFillNewEntries; private javax.swing.JCheckBox jCheckBoxFootnote; private javax.swing.JCheckBox jCheckBoxFootnoteBraces; private javax.swing.JCheckBox jCheckBoxIconText; private javax.swing.JCheckBox jCheckBoxImgResize; private javax.swing.JCheckBox jCheckBoxJumpToTab; private javax.swing.JCheckBox jCheckBoxRegistry; private javax.swing.JCheckBox jCheckBoxSearchWithoutFormatTags; private javax.swing.JCheckBox jCheckBoxShowAllIcons; private javax.swing.JCheckBox jCheckBoxShowEntryHeadline; private javax.swing.JCheckBox jCheckBoxShowHorGrid; private javax.swing.JCheckBox jCheckBoxShowTableBorder; private javax.swing.JCheckBox jCheckBoxShowToolbar; private javax.swing.JCheckBox jCheckBoxShowVerGrid; private javax.swing.JCheckBox jCheckBoxSteno; private javax.swing.JCheckBox jCheckBoxSynonym; private javax.swing.JCheckBox jCheckBoxSystray; private javax.swing.JCheckBox jCheckBoxUseMacBackgroundColor; private javax.swing.JCheckBox jCheckBoxUseMarkdown; private javax.swing.JCheckBox jCheckBoxUseXDGOpen; private javax.swing.JComboBox<String> jComboBoxBackgroundColors; private javax.swing.JComboBox<String> jComboBoxFonts; private javax.swing.JComboBox<String> jComboBoxIconTheme; private javax.swing.JComboBox<String> jComboBoxLAF; private javax.swing.JComboBox<String> jComboBoxLocale; private javax.swing.JComboBox<String> jComboBoxManualTimestamp; private javax.swing.JComboBox<String> jComboBoxShowAtStartup; private javax.swing.JFormattedTextField jFormattedTextFieldImgHeight; private javax.swing.JFormattedTextField jFormattedTextFieldImgWidth; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel23; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JLabel jLabelColor; private javax.swing.JLabel jLabelFontDeskLayout; private javax.swing.JLabel jLabelTableColor; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel11; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel7; private javax.swing.JSlider jSliderDesktopFontSize; private javax.swing.JSlider jSliderFontSize; private javax.swing.JSlider jSliderTextfields; private javax.swing.JSpinner jSpinnerDistHor; private javax.swing.JSpinner jSpinnerDistVer; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JTextField jTextFieldAttachmentPath; private javax.swing.JTextField jTextFieldBackupPath; private javax.swing.JTextField jTextFieldImagePath; private javax.swing.JTextField jTextFieldPandoc; // End of variables declaration//GEN-END:variables private CFontChooser fontDlg; private CAutoKorrekturEdit autoKorrektEdit; private CStenoEdit stenoEdit; private CHighlightSearchSettings highlightSettingsDlg; private CSynonymsEdit synonymsDlg; private CBiggerEditField biggerEditDlg; }
Zettelkasten-Team/Zettelkasten
src/main/java/de/danielluedecke/zettelkasten/CSettingsDlg.java
213,330
package org.knowm.xchange.lgo.service; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Comparator; import org.knowm.xchange.ExchangeSpecification; import org.knowm.xchange.client.ExchangeRestProxyBuilder; import org.knowm.xchange.exceptions.ExchangeException; import org.knowm.xchange.lgo.CertificateAuthority; import org.knowm.xchange.lgo.LgoAdapters; import org.knowm.xchange.lgo.LgoEnv; import org.knowm.xchange.lgo.dto.key.LgoKey; public class LgoKeyService { private final CertificateAuthority proxy; private LgoKey currentKey; public LgoKeyService(ExchangeSpecification exchangeSpecification) { final String baseUrl = exchangeSpecification.getExchangeSpecificParametersItem(LgoEnv.KEYS_URL).toString(); proxy = ExchangeRestProxyBuilder.forInterface(CertificateAuthority.class, exchangeSpecification) .baseUrl(baseUrl) .build(); } public LgoKey selectKey() { if (mustFetchNewKey()) { fetchKey(); } return currentKey; } private boolean mustFetchNewKey() { return currentKey == null || Instant.now().minus(10, ChronoUnit.MINUTES).isAfter(currentKey.getDisabledAt()); } private void fetchKey() { currentKey = LgoAdapters.adaptKeysIndex(proxy.fetchIndex()) .filter( k -> { Instant now = Instant.now(); return now.isBefore(k.getDisabledAt()) && now.isAfter(k.getEnabledAt()); }) .max(Comparator.comparing(LgoKey::getDisabledAt)) .orElseThrow(() -> new ExchangeException("Can't find a proper key")); String value = proxy.fetchKey(currentKey.getId()); currentKey.setValue(CryptoUtils.parsePublicKey(value)); } }
knowm/XChange
xchange-lgo/src/main/java/org/knowm/xchange/lgo/service/LgoKeyService.java
213,331
/** * $Id: Timeline.java,v 1.36 2007/08/16 14:09:56 jeffmc Exp $ * * Copyright 1997-2024 Unidata Program Center/University Corporation for * Atmospheric Research, P.O. Box 3000, Boulder, CO 80307, * [email protected]. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at * your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package ucar.unidata.ui; import ucar.unidata.util.DateSelection; import ucar.unidata.util.DateUtil; import ucar.unidata.util.DatedThing; import ucar.unidata.util.DatedObject; import ucar.unidata.util.DatedThing; import ucar.unidata.util.LayoutUtil; import ucar.unidata.util.MenuUtil; import ucar.unidata.util.StringUtil; import java.awt.*; import java.awt.event.*; import java.io.*; import java.text.DateFormat; import java.text.FieldPosition; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Hashtable; import java.util.List; import java.util.TimeZone; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; /** * Widget for selecting dates and times * * * @author IDV Development Team * @version $Revision: 1.36 $ */ public class Timeline extends JPanel implements MouseListener, MouseMotionListener { /** Action command used for the Apply button */ public static String CMD_APPLY = "Apply"; /** Action command used for the Cancel button */ public static String CMD_CANCEL = "Cancel"; /** Action command used for the Cancel button */ public static String CMD_OK = "Ok"; /** The normal cursor_ */ public static final Cursor CURSOR_NORMAL = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR); /** The normal cursor_ */ public static final Cursor CURSOR_MOVE = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); /** The normal cursor_ */ public static final Cursor CURSOR_LEFT = Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR); /** The normal cursor_ */ public static final Cursor CURSOR_RIGHT = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR); /** font */ private static String FONT_FACE = "Monospaced"; /** font */ private static final Font FONT_MAIN = new Font(FONT_FACE, Font.BOLD, 10); /** font */ private static final Font FONT_AXIS_MINOR = new Font(FONT_FACE, Font.ITALIC, 10); /** font */ private static final Font FONT_AXIS_MAJOR = new Font(FONT_FACE, Font.BOLD, 10); /** For formatting dates */ private FieldPosition FP = new FieldPosition(0); /** drawing size */ private static final int DIM_SELECTION_BOX = 10; /** drawing size */ private static final int DIM_TIME_WIDTH = 4; /** drawing size */ public static final int DIM_TIME_HEIGHT = 10; /** drawing size */ private static final int DIM_INTERVAL_HEIGHT = 15; /** stroke */ private static final Stroke STROKE_DASHED_ONEPIXEL = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.0f, new float[] { 1.0f, 1.0f }, 0.0f); /** stroke */ private static final Stroke STROKE_DASHED_TWOPIXEL = new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.0f, new float[] { 1.0f, 1.0f }, 0.0f); /** stroke */ private static final Stroke STROKE_SOLID_ONEPIXEL = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.0f, new float[] { Float.MAX_VALUE }, 0.0f); /** stroke */ private static final Stroke STROKE_SOLID_TWOPIXEL = new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.0f, new float[] { Float.MAX_VALUE }, 0.0f); /** color */ private static final Color COLOR_BACKGROUND = Color.white; /** color */ private static final Color COLOR_BACKGROUND_DISABLED = new Color(230, 230, 230); /** color */ private static final Color COLOR_LINE = Color.black; /** color */ private static final Color COLOR_RANGE = Color.black; // private static final Color COLOR_RANGE_DART = COLOR_RANGE; /** _more_ */ private static final Color COLOR_RANGE_DART = Color.gray; /** highlight color for when we drag the date selection */ private static final Color COLOR_HIGHLIGHT_SELECTION = Color.cyan.darker(); //Color.yellow; /** highlight color for the date object we're over */ private static final Color COLOR_HIGHLIGHT_DATE = Color.cyan; //Color.yellow; /** color */ private static final Color COLOR_TIME_SELECTED = Color.red; /** color */ private static final Color COLOR_TIME_UNSELECTED = Color.blue; // private static final Color COLOR_INTERVAL_FILL = Color.cyan.brighter().brighter(); /** color */ private static final Color COLOR_INTERVAL_FILL = new Color(237, 237, 237); /** color */ private static final Color COLOR_INTERVAL_LINE = COLOR_INTERVAL_FILL.darker(); /** color */ private static final Color COLOR_AXIS_MINOR = Color.gray; /** color */ private static final Color COLOR_AXIS_MAJOR = Color.black; /** How close to a date to pick it */ private static final int PICK_THRESHOLD = 10; /** when dragging the date selection box what are we dragging */ public static final int DRAGMODE_LEFT = 0; /** when dragging the date selection box what are we dragging */ public static final int DRAGMODE_RIGHT = 1; /** when dragging the date selection box what are we dragging */ public static final int DRAGMODE_CENTER = 2; /** formats */ private static AxisFormat[] FORMATS = { new AxisFormat(1 * 100, "ss:SS", new AxisFormat(Calendar.MILLISECOND, 500, "mm:ss:SS")), // new AxisFormat(DateUtil.MILLIS*100, "ss:SS", // new AxisFormat(Calendar.MILLISECOND, 500,"mm:ss:SS")), new AxisFormat(1 * 500, "ss:SS", new AxisFormat(Calendar.SECOND, 2, "mm:ss:SS")), new AxisFormat(DateUtil.MILLIS_SECOND, "ss", new AxisFormat(Calendar.SECOND, 10, "HH:mm:ss")), new AxisFormat(DateUtil.MILLIS_SECOND * 5, "ss", new AxisFormat(Calendar.SECOND, 30, "HH:mm:ss")), new AxisFormat(DateUtil.MILLIS_SECOND * 15, "ss", new AxisFormat(Calendar.MINUTE, 1, "HH:mm:ss")), new AxisFormat(DateUtil.MILLIS_SECOND * 30, "ss", new AxisFormat(Calendar.MINUTE, 2, "HH:mm:ss")), new AxisFormat(DateUtil.MILLIS_MINUTE, "mm", new AxisFormat(Calendar.MINUTE, 5, "dd/HH:mm")), new AxisFormat(DateUtil.MILLIS_MINUTE * 5, "mm", new AxisFormat(Calendar.MINUTE, 30, "dd/HH:mm")), new AxisFormat(DateUtil.MILLIS_MINUTE * 10, "m", new AxisFormat(Calendar.MINUTE, 60, "dd/HH:mm")), new AxisFormat(DateUtil.MILLIS_MINUTE * 15, "mm", new AxisFormat(Calendar.HOUR, 1, "dd/HH:mm")), new AxisFormat(DateUtil.MILLIS_MINUTE * 30, "mm", new AxisFormat(Calendar.HOUR, 2, "dd/HH")), new AxisFormat(DateUtil.MILLIS_HOUR, "HH:mm", new AxisFormat(Calendar.HOUR, 3, "dd/HH")), new AxisFormat(DateUtil.MILLIS_HOUR * 2, "HH:mm", new AxisFormat(Calendar.HOUR, 6, "dd/HH")), new AxisFormat(DateUtil.MILLIS_HOUR * 3, "HH:mm", new AxisFormat(Calendar.HOUR, 6, "dd/HH")), new AxisFormat(DateUtil.MILLIS_HOUR * 4, "HH:mm", new AxisFormat(Calendar.HOUR, 6, "dd/HH")), new AxisFormat(DateUtil.MILLIS_HOUR * 5, "HH:mm", new AxisFormat(Calendar.HOUR, 12, "dd/HH")), new AxisFormat(DateUtil.MILLIS_HOUR * 6, "HH:mm", new AxisFormat(Calendar.HOUR, 12, "dd/HH")), new AxisFormat(DateUtil.MILLIS_HOUR * 12, "HH:mm", new AxisFormat(Calendar.DAY_OF_MONTH, 1, "dd/HH")), new AxisFormat(DateUtil.MILLIS_DAY, "dd", new AxisFormat(Calendar.DAY_OF_MONTH, 1, "dd/HH")), new AxisFormat(DateUtil.MILLIS_DAY * 2, "dd", new AxisFormat(Calendar.DAY_OF_MONTH, 7, "MM-dd")), new AxisFormat(DateUtil.MILLIS_DAY * 3, "dd", new AxisFormat(Calendar.DAY_OF_MONTH, 14, "MM-dd")), new AxisFormat(DateUtil.MILLIS_DAY * 4, "dd", new AxisFormat(Calendar.DAY_OF_MONTH, 14, "MM-dd")), new AxisFormat(DateUtil.MILLIS_DAY * 5, "dd", new AxisFormat(Calendar.DAY_OF_MONTH, 14, "MM-dd")), new AxisFormat(DateUtil.MILLIS_DAY * 6, "dd", new AxisFormat(Calendar.DAY_OF_MONTH, 30, "MM-dd")), new AxisFormat(DateUtil.MILLIS_DAY * 7, "MM-dd", new AxisFormat(Calendar.DAY_OF_MONTH, 30, "MM-dd")), new AxisFormat(DateUtil.MILLIS_MONTH, "MM-dd", new AxisFormat(Calendar.MONTH, 4, "yyyy-MM")), new AxisFormat(DateUtil.MILLIS_MONTH * 6, "MM-dd", new AxisFormat(Calendar.YEAR, 2, "yyyy")), new AxisFormat(DateUtil.MILLIS_YEAR, "yyyy-MM"), new AxisFormat(DateUtil.MILLIS_YEAR * 5, "yyyy"), new AxisFormat(DateUtil.MILLIS_YEAR * 10, "yyyy"), new AxisFormat(DateUtil.MILLIS_YEAR * 100, "yyyy"), new AxisFormat(DateUtil.MILLIS_MILLENIUM, "yyyy"), new AxisFormat(DateUtil.MILLIS_MILLENIUM * 10, "yyyy"), new AxisFormat(DateUtil.MILLIS_MILLENIUM * 100, "yyyy"), new AxisFormat(DateUtil.MILLIS_MILLENIUM * 1000, "yyyy"), new AxisFormat(DateUtil.MILLIS_MILLENIUM * 10000, "yyyy"), new AxisFormat(DateUtil.MILLIS_MILLENIUM * 100000, "yyyy") }; /** * Class AxisFormat Holds info to do date range size sensitive axis painting * * * @author IDV Development Team * @version $Revision: 1.36 $ */ private static class AxisFormat { /** Calendar field */ int field; /** offset */ int offset; /** step */ long step; /** date format */ String format; /** sub-axis info */ AxisFormat subFormat; /** * ctor * * @param field field * @param offset offset * @param fmt format */ public AxisFormat(int field, int offset, String fmt) { this.field = field; this.offset = offset; this.format = fmt; } /** * ctor * * @param step step * @param fmt format */ public AxisFormat(long step, String fmt) { this(step, fmt, null); } /** * ctor * * @param step step * @param fmt format * @param subFormat sub axis format */ public AxisFormat(long step, String fmt, AxisFormat subFormat) { this.step = step; this.format = fmt; this.subFormat = subFormat; } /** * make a date formatter * * @param tz timezone * * @return formatter */ SimpleDateFormat getSDF(TimeZone tz) { SimpleDateFormat sdf = new SimpleDateFormat(format); if (tz != null) { sdf.setTimeZone(tz); } return sdf; } } /** Does this timeline support selection */ private boolean isCapableOfSelection = true; /** _more_ */ private boolean justShowSelected = false; /** are we dragging a selection range */ private boolean doingDragSelect = false; /** for dragging */ private Date dragStartDate; /** for dragging */ private Date dragEndDate; /** for dragging */ private MouseEvent dragStartEvent; /** for dragging */ private boolean draggingDateSelection = false; /** date selection rectangle */ private Rectangle selectionBox; /** what are we dragging */ private int dragMode; /** for dragging */ private long initDragDeltaStart; /** for dragging */ private long initDragDeltaEnd; /** for properties dialog */ private JCheckBox useDateSelectionCbx; /** for properties dialog */ private JCheckBox showIntervalsCbx; /** for properties dialog */ private JCheckBox stickyCbx; /** for properties dialog */ // private DateTimePicker startTimePicker; /** for properties dialog */ // private DateTimePicker endTimePicker; /** for properties dialog */ private DateSelectionGui dateSelectionGui; /** for properties dialog */ private JDialog propertiesDialog; /** for properties dialog */ private JDialog dialog; /** for properties dialog */ private boolean dialogOK = false; /** the date selection */ private DateSelection dateSelection = new DateSelection(); /** are we using the date selection */ private boolean useDateSelection = true; /** first one when we got created. Use this for doing a control-r */ private DateSelection originalDateSelection; /** Do we paint the intervals */ private boolean paintIntervals = true; /** the default time zone */ private static TimeZone defaultTimeZone; /** date format */ private static String defaultFormat = "yyyy-MM-dd HH:mm:ss"; /** for painting */ private int horizontalPadding = 0; /** for painting */ private int verticalPadding = 0; /** visible start date */ private Date startDate; /** visible end date */ private Date endDate; /** first start date. Use this for dthe reset */ private Date originalStartDate; /** first end date. Use this for dthe reset */ private Date originalEndDate; /** The thigns we draw */ private List datedThings; /** last thing selected. Keep around for doing a shift-click range select */ private DatedThing lastSelectedThing; /** selected things */ private List selected = new ArrayList(); /** thing we're mousing over */ private DatedThing mouseHighlighted; /** gui */ private JComponent contents; /** show intervals */ private boolean showIntervals = true; /** Is the date selection range automatically changed to match the visible range */ private boolean sticky = false; /** _more_ */ protected List sunriseDates = new ArrayList(); /** Holds other timelines that we share start/end range with */ private List timelineGroup; /** do we show an abbreviated display */ private boolean shortDisplay = false; /** color */ private Color colorTimeSelected = COLOR_TIME_SELECTED; /** color */ private Color colorTimeUnselected = COLOR_TIME_UNSELECTED; /** * Default ctor */ public Timeline() { this(new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24), new Date(System.currentTimeMillis())); } /** * ctor. start and end date is the min/max of the times * * @param times List of DatedThings * @param initDimension initial width */ public Timeline(List times, int initDimension) { this(times, initDimension, 100); } /** * ctor. start and end date is the min/max of the times * * @param times List of DatedThings * @param width init width * @param height init height */ public Timeline(List times, int width, int height) { setPreferredSize(new Dimension(width, height)); setDatedThings(times, true); initGui(); } /** * Create a Timeline with the initial date range * * @param start start * @param end end */ public Timeline(Date start, Date end) { this(start, end, 600); } /** * ctor * * @param start start * @param end end * @param initDimension width */ public Timeline(Date start, Date end, int initDimension) { setPreferredSize(new Dimension(initDimension, 100)); init(start, end); initGui(); } /** * get default time zone * * @return time zone */ public static TimeZone getTimeZone() { if (defaultTimeZone == null) { defaultTimeZone = TimeZone.getTimeZone("GMT"); } return defaultTimeZone; } /** * set the format * * @param format format */ public static void setDateFormat(String format) { defaultFormat = format; } /** * set timezone * * @param tz timezone */ public static void setTimeZone(TimeZone tz) { defaultTimeZone = tz; } /** * make gui */ protected void initGui() { this.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { double smallStep = 0.05; double bigStep = 0.5; boolean doDateSelection = e.isControlDown() && (dateSelectionActive()); if (e.getKeyCode() == KeyEvent.VK_RIGHT) { shiftByPercent((e.isShiftDown() ? bigStep : smallStep), doDateSelection); } else if (e.getKeyCode() == KeyEvent.VK_LEFT) { shiftByPercent((e.isShiftDown() ? -bigStep : -smallStep), doDateSelection); } else if (e.getKeyCode() == KeyEvent.VK_UP) { expandByPercent((e.isShiftDown() ? 0.5 : 0.9), doDateSelection); } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { expandByPercent((e.isShiftDown() ? 1.5 : 1.1), doDateSelection); } else if ((e.getKeyCode() == KeyEvent.VK_R)) { reset(e.isControlDown()); } else if ((e.getKeyCode() == KeyEvent.VK_P) && e.isControlDown()) { showProperties(); } else if ( !dateSelectionActive()) { if (isCapableOfSelection && (e.getKeyCode() == KeyEvent.VK_A) && e.isControlDown()) { setSelected(new ArrayList(datedThings)); repaint(); } } } }); this.addMouseWheelListener(new MouseWheelListener() { public void mouseWheelMoved(MouseWheelEvent event) { boolean doDateSelection = event.isControlDown() && dateSelectionActive(); int notches = event.getWheelRotation(); if (notches < 0) { expandByPercent((event.isShiftDown() ? 0.5 : 0.9), doDateSelection); } else { expandByPercent((event.isShiftDown() ? 1.5 : 1.1), doDateSelection); } } }); this.addMouseListener(this); this.addMouseMotionListener(this); setToolTipText(""); } /** * handle mouse event * * @param me mouse event */ public void mouseMoved(MouseEvent me) { if ((startDate == null) || (endDate == null)) { return; } DatedThing closest = findClosest(new Point(me.getX(), me.getY())); boolean changed = (closest != mouseHighlighted); setHighlightedDate(closest); setCursor(CURSOR_NORMAL); if ((selectionBox != null) && dateSelectionActive()) { Rectangle r = new Rectangle(selectionBox); r.grow(PICK_THRESHOLD, PICK_THRESHOLD); if (r.contains(new Point(me.getX(), me.getY()))) { double d1 = Math.abs(selectionBox.getX() - me.getX()); double d2 = Math.abs(selectionBox.getX() + selectionBox.getWidth() - me.getX()); if ((d1 > 10) && (d2 > 10)) { setCursor(CURSOR_MOVE); } else if (d1 < d2) { setCursor(CURSOR_LEFT); } else { setCursor(CURSOR_RIGHT); } } } if (changed) { repaint(); } } /** * handle mouse event * * @param e mouse event */ public void mouseDragged(MouseEvent e) { if ((startDate == null) || (endDate == null)) { return; } if (SwingUtilities.isRightMouseButton(e)) { return; } if (doingDragSelect) { if (e.isShiftDown()) { dragEndDate = toDate(e.getX()); int w = getWidth(); int x = e.getX(); if (x > w) { shiftByPercent(1.2 * (x - w) / (double) w, false); } else if (x < 0) { shiftByPercent(1.2 * x / (double) w, false); } setSelected(DatedObject.select(dragStartDate, dragEndDate, datedThings)); repaint(); return; } else { doingDragSelect = false; } } int mouseLoc = e.getX(); int left = toLocation(startDate.getTime()); int right = toLocation(endDate.getTime()); int delta = mouseLoc - dragStartEvent.getX(); double percent = delta / ((double) right - left); // System.err.println("percent:" + percent); if (draggingDateSelection) { Date d = toDate(mouseLoc); long newTime = d.getTime(); double d1 = Math.abs(selectionBox.getX() - mouseLoc); double d2 = Math.abs(selectionBox.getX() + selectionBox.getWidth() - mouseLoc); if (dragMode == DRAGMODE_CENTER) { dateSelection.setStartFixedTime(newTime + initDragDeltaStart); dateSelection.setEndFixedTime(newTime + initDragDeltaEnd); } else { if ((dragMode == DRAGMODE_LEFT) && (mouseLoc >= selectionBox.getX() + selectionBox.getWidth())) { dragMode = DRAGMODE_RIGHT; } else { if ((dragMode == DRAGMODE_RIGHT) && (mouseLoc <= selectionBox.getX())) { dragMode = DRAGMODE_LEFT; } } if (dragMode == DRAGMODE_LEFT) { dateSelection.setStartFixedTime(newTime); } else { dateSelection.setEndFixedTime(newTime); } } if (mouseLoc < 0) { long diff = startDate.getTime() - d.getTime(); startDate = d; endDate = new Date(endDate.getTime() - diff); timelineChanged(); } else if (mouseLoc > getBounds().width) { long diff = d.getTime() - endDate.getTime(); endDate = d; startDate = new Date(startDate.getTime() + diff); timelineChanged(); } dateSelectionChanged(); } else { shiftByPercent(-percent, false); } dragStartEvent = e; } /** * handle mouse event * * @param e mouse event */ public void mouseExited(MouseEvent e) { if (mouseHighlighted != null) { setHighlightedDate(null); repaint(); } } /** * handle mouse event * * @param e mouse event */ public void mouseEntered(MouseEvent e) {} /** * handle mouse event * * @param e mouse event */ public void mouseClicked(MouseEvent e) { if ((startDate == null) || (endDate == null)) { return; } if (e.getClickCount() > 1) { return; } if (SwingUtilities.isRightMouseButton(e)) { showPopupMenu(e.getX(), e.getY()); return; } //If we arent in date selection mode then we are in direct selection mode if (dateSelectionActive()) { //For now don't do this // return; } if ( !isCapableOfSelection) { return; } if ( !e.isShiftDown() && !e.isControlDown()) { setSelected(new ArrayList()); } DatedThing closest = findClosest(new Point(e.getX(), e.getY())); if (closest != null) { if (e.isShiftDown() && (lastSelectedThing != null)) { long t1 = lastSelectedThing.getDate().getTime(); long t2 = closest.getDate().getTime(); if (t1 > t2) { long tmp = t1; t1 = t2; t2 = tmp; } for (int i = 0; i < datedThings.size(); i++) { DatedThing datedThing = (DatedThing) datedThings.get(i); long time = datedThing.getDate().getTime(); if ((time >= t1) && (time <= t2) && !selected.contains(datedThing)) { selected.add(datedThing); selectedDatesChanged(); } } } else { if (selected.contains(closest)) { selected.remove(closest); } else { selected.add(closest); } selectedDatesChanged(); } } lastSelectedThing = closest; repaint(); } /** * handle mouse event * * @param e mouse event */ public void mousePressed(MouseEvent e) { if ((startDate == null) || (endDate == null)) { return; } requestFocus(); if (SwingUtilities.isRightMouseButton(e)) { return; } draggingDateSelection = false; dragStartEvent = e; doingDragSelect = false; if (isCapableOfSelection && !dateSelectionActive() && e.isShiftDown()) { doingDragSelect = true; dragStartDate = dragEndDate = toDate(e.getX()); setSelected(new ArrayList()); repaint(); return; } if ( !dateSelectionActive()) { // return; } if (selectionBox == null) { return; } Rectangle r = new Rectangle(selectionBox); r.grow(PICK_THRESHOLD, PICK_THRESHOLD); if (r.contains(new Point(e.getX(), e.getY()))) { draggingDateSelection = true; double d1 = Math.abs(selectionBox.getX() - e.getX()); double d2 = Math.abs(selectionBox.getX() + selectionBox.getWidth() - e.getX()); if ((d1 > 10) && (d2 > 10)) { dragMode = DRAGMODE_CENTER; } else if (d1 < d2) { dragMode = DRAGMODE_LEFT; } else { dragMode = DRAGMODE_RIGHT; } long time = toDate(e.getX()).getTime(); initDragDeltaStart = dateSelection.getStartFixedTime() - time; initDragDeltaEnd = dateSelection.getEndFixedTime() - time; } } /** * handle mouse event * * @param e mouse event */ public void mouseReleased(MouseEvent e) { setCursor(CURSOR_NORMAL); dragStartEvent = null; dragStartDate = null; dragEndDate = null; doingDragSelect = false; if ((startDate == null) || (endDate == null)) { return; } draggingDateSelection = false; repaint(); } /** * Set the date selection * * @param dateSelection The date selection */ public void setDateSelection(DateSelection dateSelection) { this.dateSelection = dateSelection; originalDateSelection = new DateSelection(dateSelection); dateSelectionChanged(); } /** * Get the DateSelection property. * * @return The DateSelection */ public DateSelection getDateSelection() { return dateSelection; } /** * Get the list of dated things we are displaying * * @return List of dated things */ public List getDatedThings() { return datedThings; } /** * Set the list of selected items * * @param l List of selected items */ public void setSelected(List l) { if (l == null) { selected = new ArrayList(); } else { selected = new ArrayList(l); } selectedDatesChanged(); repaint(); } /** _more_ */ private Hashtable selectedMap = new Hashtable(); /** * _more_ */ public void selectedDatesChanged() { selectedMap = new Hashtable(); if ((datedThings == null) || (selected == null)) { return; } for (int i = 0; i < selected.size(); i++) { DatedThing datedThing = (DatedThing) selected.get(i); selectedMap.put(datedThing, datedThing); } } /** * Get the list of selected DatedThing-s * * @return The Selected things */ public List getSelected() { return new ArrayList(selected); } /** * initialize start/end time * * @param start start * @param end end */ protected void init(Date start, Date end) { this.startDate = start; this.endDate = end; this.originalStartDate = start; this.originalEndDate = end; } /** * popup menu at * * @param x x * @param y y */ protected void showPopupMenu(int x, int y) { List items = new ArrayList(); getMenuItems(items); JPopupMenu popup = MenuUtil.makePopupMenu(items); popup.show(this, x, y); } /** * reset to original date range */ public void resetDateRange() { reset(false); } /** * reset to original date selection */ public void resetDateSelection() { reset(true); } /** * set the range of the date selection * * @param r range */ public void setDateSelection(Date[] r) { dateSelection.setStartFixedTime(r[0]); dateSelection.setEndFixedTime(r[1]); startDate = r[0]; endDate = r[1]; dateSelectionChanged(); expandByPercent(1.1, false); } /** * set the visible range * * @param r The date range */ public void setVisibleRange(Date[] r) { startDate = r[0]; endDate = r[1]; expandByPercent(1.1, false); // timelineChanged(); } /** * make menu items * * @param items items */ protected void getMenuItems(List items) { List subItems; JMenuItem mi; items.add(mi = MenuUtil.makeMenuItem("Properties", this, "showProperties")); subItems = new ArrayList(); long now = System.currentTimeMillis(); Calendar cal = Calendar.getInstance(getTimeZone()); cal.setTimeInMillis(now); cal.clear(Calendar.MILLISECOND); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR, 0); cal.add(Calendar.DAY_OF_YEAR, 1); now = cal.getTimeInMillis(); subItems.add(MenuUtil.makeMenuItem("Reset", this, "resetDateRange")); subItems.add( MenuUtil.makeMenuItem( "Today", this, "setVisibleRange", new Date[] { new Date(now - DateUtil.daysToMillis(1)), new Date(now) })); subItems.add( MenuUtil.makeMenuItem( "Past Week", this, "setVisibleRange", new Date[] { new Date(now - DateUtil.daysToMillis(7)), new Date(now) })); subItems.add( MenuUtil.makeMenuItem( "Past Month", this, "setVisibleRange", new Date[] { new Date(now - DateUtil.daysToMillis(30)), new Date(now) })); subItems.add( MenuUtil.makeMenuItem( "Past Year", this, "setVisibleRange", new Date[] { new Date(now - DateUtil.daysToMillis(365)), new Date(now) })); if (dateSelectionActive()) { subItems.add(MenuUtil.makeMenuItem("Selection Range", this, "setVisibleRange", new Date[] { dateSelection.getStartFixedDate(), dateSelection.getEndFixedDate() })); } items.add(MenuUtil.makeMenu("Set Visible Range", subItems)); if (dateSelectionActive()) { subItems = new ArrayList(); subItems.add(MenuUtil.makeMenuItem("View", this, "setVisibleRange", new Date[] { dateSelection.getStartFixedDate(), dateSelection.getEndFixedDate() })); subItems.add(MenuUtil.makeMenuItem("Reset", this, "resetDateSelection")); subItems.add(MenuUtil.makeMenuItem("Today", this, "setDateSelection", new Date[] { new Date(now - DateUtil.daysToMillis(1)), new Date(now) })); subItems.add(MenuUtil.makeMenuItem("Past Week", this, "setDateSelection", new Date[] { new Date(now - DateUtil.daysToMillis(7)), new Date(now) })); subItems.add(MenuUtil.makeMenuItem("Past Month", this, "setDateSelection", new Date[] { new Date(now - DateUtil.daysToMillis(30)), new Date(now) })); items.add(MenuUtil.makeMenu("Set Date Selection", subItems)); } if (isCapableOfSelection) { items.add(MenuUtil.makeCheckboxMenuItem("Use Date Selection", this, "useDateSelection", null)); } if ( !dateSelectionActive()) { return; } items.add(MenuUtil.makeCheckboxMenuItem("Use Visible Range", this, "sticky", null)); mi.setToolTipText("Make the selection range be the visible range"); double[] intervals = { Double.NaN, 0, DateUtil.minutesToMillis(5), DateUtil.minutesToMillis(10), DateUtil.minutesToMillis(15), DateUtil.minutesToMillis(30), DateUtil.hoursToMillis(1), DateUtil.hoursToMillis(2), DateUtil.hoursToMillis(3), DateUtil.hoursToMillis(4), DateUtil.hoursToMillis(5), DateUtil.hoursToMillis(6), DateUtil.hoursToMillis(12), DateUtil.daysToMillis(1), DateUtil.daysToMillis(2), DateUtil.daysToMillis(7) }; String[] intervalNames = { "Default", "0 minutes", "5 minutes", "10 minutes", "15 minutes", "30 minutes", "1 hour", "2 hours", "3 hours", "4 hours", "5 hours", "6 hours", "12 hours", "1 day", "2 days", "7 days", }; subItems = new ArrayList(); double currentInterval = dateSelection.getInterval(); for (int i = 0; i < intervals.length; i++) { if (intervals[i] != intervals[i]) { continue; } String lbl = intervalNames[i]; if (intervals[i] == 0) { lbl = "None"; } subItems.add(MenuUtil.makeMenuItem(((intervals[i] == currentInterval) ? "-" + lbl + "-" : " " + lbl + " "), this, "setInterval", new Double(intervals[i]))); } items.add(MenuUtil.makeMenu("Interval", subItems)); if (dateSelection.hasInterval()) { subItems = new ArrayList(); double range; range = dateSelection.getPreRange(); for (int i = 0; i < intervals.length; i++) { boolean isCurrent = intervals[i] == range; if ((range != range) && (intervals[i] != intervals[i])) { isCurrent = true; } String lbl = intervalNames[i]; subItems.add(MenuUtil.makeMenuItem((isCurrent ? "-" + lbl + "-" : " " + lbl + " "), this, "setPreRange", new Double(intervals[i]))); } items.add(MenuUtil.makeMenu("Before Range", subItems)); subItems = new ArrayList(); range = dateSelection.getPostRange(); for (int i = 0; i < intervals.length; i++) { boolean isCurrent = intervals[i] == range; if ((range != range) && (intervals[i] != intervals[i])) { isCurrent = true; } String lbl = intervalNames[i]; subItems.add(MenuUtil.makeMenuItem((isCurrent ? "-" + lbl + "-" : " " + lbl + " "), this, "setPostRange", new Double(intervals[i]))); } items.add(MenuUtil.makeMenu("After Range", subItems)); } subItems = new ArrayList(); int currentSkip = dateSelection.getSkip(); int[] skips = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 40, 50, 75, 100 }; for (int i = 0; i < skips.length; i++) { subItems.add(MenuUtil.makeMenuItem(((skips[i] == currentSkip) ? "-" + skips[i] + "-" : " " + skips[i] + " "), this, "setSkipFactor", new Integer(skips[i]))); } items.add(MenuUtil.makeMenu("Skip Factor", subItems)); subItems = new ArrayList(); int[] counts = { DateSelection.MAX_COUNT, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 40, 50, 75, 100 }; int currentCount = dateSelection.getCount(); for (int i = 0; i < counts.length; i++) { int cnt = counts[i]; String lbl; if (cnt == DateSelection.MAX_COUNT) { lbl = "All"; } else { lbl = "" + cnt; } subItems.add(MenuUtil.makeMenuItem(((cnt == currentCount) ? "-" + lbl + "-" : " " + lbl + " "), this, "setCount", new Integer(cnt))); } items.add(MenuUtil.makeMenu("Count", subItems)); } /** * clear intervals */ public void removeIntervals() { dateSelection.setInterval(0); dateSelectionChanged(); } /** * set skip * * @param i skip */ public void setSkipFactor(Integer i) { dateSelection.setSkip(i.intValue()); dateSelectionChanged(); } /** * set interval * * @param i interval */ public void setInterval(Double i) { dateSelection.setInterval(i.doubleValue()); dateSelectionChanged(); } /** * set pre range * * @param i range */ public void setPreRange(Double i) { dateSelection.setPreRange(i.doubleValue()); dateSelectionChanged(); } /** * set post range * * @param i range_ */ public void setPostRange(Double i) { dateSelection.setPostRange(i.doubleValue()); dateSelectionChanged(); } /** * set count * * @param i count */ public void setCount(Integer i) { dateSelection.setCount(i.intValue()); dateSelectionChanged(); } /** * show properties dialog */ public void showProperties() { if (propertiesDialog == null) { useDateSelectionCbx = new JCheckBox("Use Date Selection:", useDateSelection); showIntervalsCbx = new JCheckBox("Show Intervals", showIntervals); stickyCbx = new JCheckBox("Use Visible Range", sticky); // startTimePicker = new DateTimePicker(getStartDate()); // endTimePicker = new DateTimePicker(getEndDate()); dateSelectionGui = new DateSelectionGui(dateSelection); JComponent timeRangePanel = new JPanel(); /* JComponent timeRangePanel = LayoutUtil.hbox(GuiUtils.rLabel("Time Range: "), startTimePicker, new JLabel(" -- "), endTimePicker);*/ JComponent flagsPanel = LayoutUtil.hbox(stickyCbx, showIntervalsCbx); JComponent contents; if(isCapableOfSelection) { contents = LayoutUtil.vbox(timeRangePanel, LayoutUtil.filler(10, 10), useDateSelectionCbx, LayoutUtil.inset(dateSelectionGui, new Insets(0, 20, 0, 0))); } else { contents = timeRangePanel; } contents = LayoutUtil.inset(contents, 5); propertiesDialog = new JDialog((JFrame) null, "Date Selection", true); propertiesDialog.setLocation(new Point(200, 200)); ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent ae) { String cmd = ae.getActionCommand(); if (cmd.equals(CMD_APPLY) || cmd.equals(CMD_OK)) { if ( !applyProperties()) { return; } } if (cmd.equals(CMD_CANCEL) || cmd.equals(CMD_OK)) { propertiesDialog.setVisible(false); } } }; JComponent buttons = makeButtons(listener, new String[]{CMD_APPLY, CMD_OK,CMD_CANCEL}); propertiesDialog.getContentPane().add( LayoutUtil.inset(LayoutUtil.centerBottom(contents, buttons), 5)); propertiesDialog.pack(); } // startTimePicker.setDate(getStartDate()); // endTimePicker.setDate(getEndDate()); dateSelectionGui.setDateSelection(dateSelection); propertiesDialog.setVisible(true); } public static JPanel makeButtons(ActionListener l, String[] labels) { return makeButtons(l, labels, labels); } public static JPanel makeButtons(ActionListener listener, String[] labels, String[] cmds) { JPanel p = new JPanel(); List buttons = new ArrayList(); p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS)); for (int i = 0; i < cmds.length; i++) { String cmd = ((cmds[i] != null) ? cmds[i] : ((labels != null) ? labels[i] : "")); String label = ((labels != null) ? labels[i] : cmd); if (label == null) { label = cmd; } JButton button = new JButton(label); button.addActionListener(listener); button.setActionCommand(cmd); if (cmd.equals(CMD_OK)) { button.setDefaultCapable(true); } buttons.add(button); } return LayoutUtil.doLayout(p, LayoutUtil.getComponentArray(buttons), buttons.size(), LayoutUtil.WT_N, LayoutUtil.WT_N, null, null, new Insets(5, 5, 5, 5)); } /** * apply the properties * * @return success */ private boolean applyProperties() { if (isCapableOfSelection) { if ( !dateSelectionGui.applyProperties()) { return false; } useDateSelection = useDateSelectionCbx.isSelected(); showIntervals = showIntervalsCbx.isSelected(); sticky = stickyCbx.isSelected(); } // setStartDate(startTimePicker.getDate()); // setEndDate(endTimePicker.getDate()); timelineChanged(); dateSelectionChanged(); return true; } /** * Set the Sticky property. * * @param sticky The new value for Sticky */ public void setSticky(boolean sticky) { this.sticky = sticky; timelineChanged(); } /** * Get the Sticky property. * * @return The Sticky */ public boolean getSticky() { return sticky; } /** * are we using the date selection * * @return using the date selection */ protected boolean dateSelectionActive() { return isCapableOfSelection && (dateSelection != null) && useDateSelection; } /** * Set the UseDateSelection property. * * @param value The new value for UseDateSelection */ public void setUseDateSelection(boolean value) { useDateSelection = value; if (useDateSelection) { dateSelectionChanged(); } repaint(); } /** * Get the UseDateSelection property. * * @return The UseDateSelection */ public boolean getUseDateSelection() { return useDateSelection; } /** * Set the ShowIntervals property. * * @param value The new value for ShowIntervals */ public void setShowIntervals(boolean value) { showIntervals = value; repaint(); } /** * Get the ShowIntervals property. * * @return The ShowIntervals */ public boolean getShowIntervals() { return showIntervals; } /** * handle changed date selection */ protected void dateSelectionChanged() { if (dateSelectionActive()) { if(datedThings!=null) { setSelected(dateSelection.apply(datedThings)); } } repaint(); } /** * handle synchronization * * @param timeline the timeline that changed */ private void rangeChanged(Timeline timeline) { startDate = timeline.startDate; endDate = timeline.endDate; setHighlightedDate(mouseHighlighted); repaint(); } /** * The timeline changed. repaint, etc. */ public void timelineChanged() { if (dateSelectionActive()) { if (getSticky()) { dateSelection.setStartFixedTime(startDate); dateSelection.setEndFixedTime(endDate); dateSelectionChanged(); } } if (timelineGroup != null) { for (int i = 0; i < timelineGroup.size(); i++) { Timeline timeline = (Timeline) timelineGroup.get(i); if (timeline == this) { continue; } timeline.rangeChanged(this); } } makeSunriseDates(); setHighlightedDate(null); repaint(); } public void makeSunriseDates() { } /** * _more_ */ public void selectDaytime() { if (datedThings == null) { return; } List selected = new ArrayList(); List visibleDates = new ArrayList(); long start = startDate.getTime(); long end = endDate.getTime(); for (int i = 0; i < datedThings.size(); i++) { DatedThing datedThing = (DatedThing) datedThings.get(i); Date date = datedThing.getDate(); long time = date.getTime(); if ((time >= start) && (time <= end)) { visibleDates.add(datedThing); } } for (int datedThingIdx = 0; datedThingIdx < visibleDates.size(); datedThingIdx++) { DatedThing datedThing = (DatedThing) visibleDates.get(datedThingIdx); Date date = datedThing.getDate(); long time = date.getTime(); for (int i = 0; i < sunriseDates.size(); i += 2) { Date d1 = (Date) sunriseDates.get(i); Date d2 = (Date) sunriseDates.get(i+1); if ((time >= d1.getTime()) && (time <= d2.getTime())) { selected.add(datedThing); break; } } } setSelected(selected); } /** * find closest thing * * @param p location * * @return closest thing */ protected DatedThing findClosest(Point p) { return findClosest(p, PICK_THRESHOLD); } /** * find closest thing * * @param p location * @param minimumDistance within * * @return closest thing */ protected DatedThing findClosest(Point p, int minimumDistance) { if (p == null) { return null; } Dimension dim = getSize(); int middle = getBaseLine(); if (p.y > middle + 10) { return null; } if (p.y < middle - 10) { return null; } if (datedThings == null) { return null; } DatedThing closest = null; double minDistance = minimumDistance; for (int i = 0; i < datedThings.size(); i++) { DatedThing datedThing = (DatedThing) datedThings.get(i); int location = toLocation(datedThing.getDate()); double distance = Math.abs(p.getX() - location); if (distance < minDistance) { minDistance = distance; closest = datedThing; } } return closest; } /** * _more_ * * @param e _more_ * * @return _more_ */ public Point getToolTipLocation(MouseEvent e) { int height = getBounds().height; return new Point(e.getX(), height); } /** * get tooltip * * * @param event event * @return tooltip */ public String getToolTipText(MouseEvent event) { if ((startDate == null) || (endDate == null)) { return null; } Date dttm; if (mouseHighlighted != null) { dttm = mouseHighlighted.getDate(); } else { dttm = toDate((int) event.getX()); } SimpleDateFormat sdf = new SimpleDateFormat(defaultFormat); sdf.setTimeZone(getTimeZone()); String tt = sdf.format(dttm.getTime(), new StringBuffer(), FP).toString() + "<br>"; if (mouseHighlighted != null) { String tmp = mouseHighlighted.toString(); if ((tmp != null) && (tmp.length() > 0)) { tt += tmp + "<br>"; } } tt += "Control-P to show properties;<br>Arrow keys to shift/zoom;<br>"; if (dateSelectionActive()) { tt += "Use Control-Arrow to change selection;"; } else { if (isCapableOfSelection) { tt += "Click to select; Control or Shift Click to select multiples; Shift-drag to select;"; } } return "<html>" + tt + "</html>"; } /** * make gui * * * @param withButtons add dialog buttons * @return gui */ public JComponent getContents(boolean withButtons) { return getContents(withButtons, true); } public JComponent getContents(boolean withButtons, boolean withBorder) { if (contents == null) { doMakeContents(withButtons, withBorder); } return contents; } /** * make gui * * @param withButtons with dialog buttons */ protected void doMakeContents(boolean withButtons) { doMakeContents(withButtons, true); } protected void doMakeContents(boolean withButtons, boolean withBorder) { JPanel thisContainer = LayoutUtil.inset(this, 0); if(withBorder) { thisContainer.setBorder( BorderFactory.createBevelBorder(BevelBorder.LOWERED)); } if ( !withButtons) { contents = thisContainer; return; } ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent ae) { String cmd = ae.getActionCommand(); dialogOK = cmd.equals(CMD_OK); if(dialog!=null) { dialog.setVisible(false); } } }; JComponent bottom = makeButtons(listener,new String[]{CMD_OK,CMD_CANCEL}); contents = LayoutUtil.centerBottom(thisContainer, bottom); } /** * paint * * @param g graphics * @param dateSelection the date selection */ protected void paintDateSelection(Graphics2D g, DateSelection dateSelection) { Dimension dim = getSize(); int width = (int) dim.getWidth(); int height = (int) dim.getHeight(); int top = 0 + verticalPadding; int bottom = height - verticalPadding * 2; int middle = top + (bottom - top) / 2; Date[] range = dateSelection.getRange(); int left = toLocation(range[0]); int right = toLocation(range[1]); // System.err.println (left + " " + right + " " + range[0] + " " + range[1]); if (dateSelection.hasInterval() && (Math.abs(right - left) > 5)) { paintIntervals((Graphics2D) g); } selectionBox = new Rectangle(left, middle - DIM_SELECTION_BOX, (right - left), DIM_SELECTION_BOX * 2); g.setStroke(STROKE_SOLID_TWOPIXEL); if (draggingDateSelection) { g.setColor(COLOR_HIGHLIGHT_SELECTION); } else { g.setColor(COLOR_LINE); } g.drawPolyline(new int[] { selectionBox.x, selectionBox.x, selectionBox.x + selectionBox.width, selectionBox.x + selectionBox.width, selectionBox.x }, new int[] { selectionBox.y + selectionBox.height, selectionBox.y, selectionBox.y, selectionBox.y + selectionBox.height, selectionBox.y + selectionBox.height }, 5); FontMetrics fm = g.getFontMetrics(); String s1 = format(range[0]); String s2 = format(range[1]); int w1 = fm.stringWidth(s1); int w2 = fm.stringWidth(s2); int x1 = selectionBox.x; int x2 = selectionBox.x + selectionBox.width - w2; int y1 = selectionBox.y - 2; int y2 = selectionBox.y - 2; //If the labels are colliding then offset the right one up a bit if (draggingDateSelection) { if (x1 + w1 >= x2) { y2 -= fm.getHeight(); g.drawLine(selectionBox.x + selectionBox.width, y1 + 2, selectionBox.x + selectionBox.width, y2); } g.setStroke(STROKE_SOLID_ONEPIXEL); g.drawString(s1, x1, y1); g.drawString(s2, x2, y2); } } /** * paint intervals * * @param g graphics */ protected void paintIntervals(Graphics2D g) { if ( !paintIntervals || !showIntervals) { return; } double[] ticks = dateSelection.getIntervalTicks(); if (ticks == null) { return; } long start = startDate.getTime(); long end = endDate.getTime(); Date[] range = dateSelection.getRange(); long intervalStart = range[0].getTime(); long intervalEnd = range[1].getTime(); Dimension dim = getSize(); int width = (int) dim.getWidth(); int height = (int) dim.getHeight(); int top = 0 + verticalPadding; int bottom = height - verticalPadding * 2; int middle = top + (bottom - top) / 2; int left = 0 + horizontalPadding; int right = width - horizontalPadding; int[] xs = new int[5]; int[] ys = new int[5]; for (int i = 0; i < ticks.length; i++) { g.setStroke(STROKE_SOLID_ONEPIXEL); long time = (long) ticks[i]; int location = toLocation(time); int leftRange = toLocation((long) (time - dateSelection.getPreRangeToUse())); int rightRange = toLocation((long) (time + dateSelection.getPostRangeToUse())); if ((time + dateSelection.getPostRangeToUse() < intervalStart) || (time - dateSelection.getPreRangeToUse() > intervalEnd)) { continue; } xs[0] = leftRange; xs[1] = leftRange; xs[2] = location; xs[3] = rightRange; xs[4] = rightRange; int y = middle - DIM_SELECTION_BOX; ys[0] = y; ys[1] = y + (middle - y) / 2; ys[2] = middle; ys[3] = y + (middle - y) / 2; ys[4] = y; g.setColor(COLOR_INTERVAL_FILL); g.fillPolygon(xs, ys, 5); g.setColor(COLOR_INTERVAL_LINE); // g.drawPolyline(xs, ys, 5); // g.setStroke(STROKE_DASHED_ONEPIXEL); g.drawLine(leftRange, y, leftRange, y + (middle - y) / 2); g.drawLine(rightRange, y, rightRange, y + (middle - y) / 2); // g.setStroke(STROKE_DASHED_TWOPIXEL); g.drawLine(location, y, location, middle); } g.setStroke(STROKE_SOLID_ONEPIXEL); } /** * get the axis line * * @return axis line location */ protected int getBaseLine() { if (shortDisplay) { return DIM_TIME_HEIGHT; } int height = (int) getSize().getHeight(); int top = verticalPadding; int bottom = height - verticalPadding; return height / 2; } /** * bottom of drawing area * * @return bottom */ protected int getBottom() { int height = (int) getSize().getHeight(); return height - verticalPadding; } /** * left of drawing area * * @return left */ protected int getLeft() { return horizontalPadding; } /** * right of drawing area * * @return right */ protected int getRight() { return (int) (getSize().getWidth() - horizontalPadding); } /** * paint axis * * @param g graphics */ protected void paintAxis(Graphics2D g) { g.setFont(FONT_AXIS_MINOR); FontMetrics fm = g.getFontMetrics(); long start = startDate.getTime(); long leftTime = startDate.getTime(); long end = endDate.getTime(); int baseLine = getBaseLine(); int minorY = baseLine + DIM_TIME_HEIGHT + fm.getHeight(); int left = getLeft(); int right = getRight(); int bottom = getBottom(); Calendar cal = Calendar.getInstance(getTimeZone()); cal.setTimeInMillis(start); cal.clear(Calendar.MILLISECOND); long range = end - start; int field2 = Calendar.MONTH; int width = (int) getSize().getWidth(); AxisFormat format = null; int maxTicks = width / 40; for (int i = 0; i < FORMATS.length; i++) { format = FORMATS[i]; if (format.step > DateUtil.MILLIS_SECOND) { cal.set(Calendar.SECOND, 0); } if (format.step > DateUtil.MILLIS_MINUTE) { cal.set(Calendar.MINUTE, 0); } if (format.step > DateUtil.MILLIS_HOUR) { cal.set(Calendar.HOUR, 0); } if (format.step > DateUtil.MILLIS_DAY * 7) { cal.set(Calendar.DAY_OF_MONTH, 0); } if (format.step > DateUtil.MILLIS_MONTH) { cal.set(Calendar.MONTH, 0); } if (range / format.step <= maxTicks) { // System.err.println ("fmt:" + i + " range: " + range + " " + format.step); break; } } SimpleDateFormat sdf = format.getSDF(getTimeZone()); g.setStroke(STROKE_DASHED_ONEPIXEL); g.setColor(COLOR_AXIS_MINOR); int majorValue = -1; start = cal.getTimeInMillis(); int x = 0; int cnt = 0; int limit = 100; while ((x <= width) && (cnt < limit)) { cnt++; x = toLocation(start); if (x < 0) { start += format.step; continue; } String s = sdf.format(start, new StringBuffer(), FP).toString(); // if(s.startsWith("0")) s = " " + s.substring(1); g.drawLine(x, minorY, x, baseLine); int sw = fm.stringWidth(s); // g.drawString(s, x-sw-2, minorY); g.drawString(s, x + 2, minorY); start += format.step; } //If we are looking at billions of years just return //since the universe is only 4000 years old no since showing //anything if (cnt >= limit) { return; } g.setFont(FONT_AXIS_MAJOR); fm = g.getFontMetrics(); g.setColor(COLOR_AXIS_MAJOR); g.setStroke(STROKE_SOLID_ONEPIXEL); if (format.subFormat != null) { cal.set(Calendar.MILLISECOND, 0); if (format.subFormat.field != Calendar.MILLISECOND) { cal.set(Calendar.SECOND, 0); if (format.subFormat.field != Calendar.SECOND) { cal.set(Calendar.MINUTE, 0); if (format.subFormat.field != Calendar.MINUTE) { cal.set(Calendar.HOUR, 0); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.DAY_OF_MONTH, 0); } } } // cal.clear(Calendar.DAY_OF_YEAR); // cal.clear(Calendar.DATE); start = cal.getTimeInMillis(); int y = baseLine + DIM_TIME_HEIGHT + fm.getHeight() * 2; sdf = format.subFormat.getSDF(getTimeZone()); x = 0; while ((start = cal.getTimeInMillis()) < leftTime) { cal.add(format.subFormat.field, format.subFormat.offset); } while (x <= width) { x = toLocation(start); if (x < 0) { cal.add(format.subFormat.field, format.subFormat.offset); start = cal.getTimeInMillis(); continue; } String s = sdf.format(start, new StringBuffer(), FP).toString(); if (s.startsWith("0")) { s = " " + s.substring(1); } // g.drawLine(x, y, x, baseLine); g.drawLine(x, minorY + 4, x, baseLine); int sw = fm.stringWidth(s); // g.drawString(s, x-sw-2, y); // g.drawString(s, x + 2, y); g.drawString(s, x - sw / 2, y); cal.add(format.subFormat.field, format.subFormat.offset); start = cal.getTimeInMillis(); } } g.setStroke(STROKE_SOLID_ONEPIXEL); } /** * paint after we filled the background but before we do anything else * * @param g graphics */ public void paintBackgroundDecoration(Graphics2D g) { if (sunriseDates.size() > 0) { g.setColor(Color.yellow); int height = (int) getSize().getHeight(); for (int i = 0; i < sunriseDates.size(); i += 2) { Date d1 = (Date) sunriseDates.get(i); Date d2 = (Date) sunriseDates.get(i+1); int x1 = toLocation(d1); int x2 = toLocation(d2); g.fillRect(x1, 0, (x2 - x1), height); } } } /** * paint * * @param g graphics */ public void paint(Graphics g) { super.paint(g); Graphics2D g2 = (Graphics2D) g; g.setFont(FONT_MAIN); int width = (int) getSize().getWidth(); int height = (int) getSize().getHeight(); int baseLine = getBaseLine(); int left = getLeft(); int right = getRight(); if (isEnabled()) { g.setColor(COLOR_BACKGROUND); } else { g.setColor(COLOR_BACKGROUND_DISABLED); } g.fillRect(0, 0, width, height); paintBackgroundDecoration(g2); if (doingDragSelect && (dragStartDate != null) && (dragEndDate != null)) { int dx1 = toLocation(dragStartDate); int dx2 = toLocation(dragEndDate); int x = Math.min(dx1, dx2); int h = 40; int y = baseLine - h / 2; int w = Math.abs(dx1 - dx2); g2.setStroke(STROKE_DASHED_ONEPIXEL); g2.setColor(Color.lightGray); g2.fillRect(x, y, w, h); g2.setColor(Color.black); g2.drawRect(x, y, w, h); } //Draw the axis line g.setColor(COLOR_LINE); g.drawLine(left, baseLine, right, baseLine); if ((startDate == null) || (endDate == null)) { return; } long start = startDate.getTime(); long end = endDate.getTime(); if ( !shortDisplay) { paintAxis(g2); } if (dateSelectionActive()) { paintDateSelection((Graphics2D) g, dateSelection); } g2.setStroke(STROKE_SOLID_ONEPIXEL); g2.setColor(COLOR_LINE); FontMetrics fm = g.getFontMetrics(); String s1 = format(startDate); String s2 = format(endDate); int w1 = fm.stringWidth(s1); int w2 = fm.stringWidth(s2); int s2x = right - w2 - 2; if ( !shortDisplay) { int dart = 6; s2x -= dart; int bottomy = verticalPadding + fm.getHeight(); g.setColor(COLOR_RANGE_DART); g.fillPolygon(new int[] { 0, dart, dart, 0 }, new int[] { 0 + 1, 0 + 1, dart + 1, 0 + 1 }, 4); g2.setColor(COLOR_RANGE); g.drawString(s1, left + dart + 2, bottomy); g.setColor(COLOR_RANGE_DART); if (s2x <= left + 2 + w1) { bottomy = getBottom(); g.fillPolygon(new int[] { right - dart, right, right - dart, right - dart }, new int[] { bottomy - 1, bottomy - 1, bottomy - dart - 1, bottomy - 1 }, 4); } else { g.fillPolygon(new int[] { right - dart, right, right - dart, right - dart }, new int[] { 0 + 1, 0 + 1, dart + 1, 0 + 1 }, 4); } g2.setColor(COLOR_RANGE); g.drawString(s2, s2x, bottomy); } Hashtable seenLocations = new Hashtable(); if (datedThings != null) { for (int selectIdx = 0; selectIdx < 2; selectIdx++) { for (int i = 0; i < datedThings.size(); i++) { DatedThing datedThing = (DatedThing) datedThings.get(i); Date date = datedThing.getDate(); long time = date.getTime(); if ((time < start) || (time > end)) { continue; } int location = toLocation(date); boolean isSelected = selectedMap.get(datedThing) != null; if (isSelected && (selectIdx == 0)) { continue; } if ( !isSelected && (selectIdx == 1)) { continue; } if (justShowSelected && !isSelected) { continue; } // Object key = new Integer(location); // if(seenLocations.get(key)!=null) continue; // seenLocations.put(key,key); if (datedThing == mouseHighlighted) { if (isSelected) { g.setColor(getColorTimeSelected()); g.fillRect(location - DIM_TIME_WIDTH / 2 - 1, baseLine - DIM_TIME_HEIGHT / 2 - 1, DIM_TIME_WIDTH + 2, DIM_TIME_HEIGHT + 2); } g.setColor(COLOR_HIGHLIGHT_DATE); } else { if (isSelected) { g.setColor(getColorTimeSelected()); } else { g.setColor(getColorTimeUnselected()); } } g.fillRect(location - DIM_TIME_WIDTH / 2, baseLine - DIM_TIME_HEIGHT / 2, DIM_TIME_WIDTH, DIM_TIME_HEIGHT); //g.fillRect(location - DIM_TIME_WIDTH / 2, baseLine, // DIM_TIME_WIDTH, DIM_TIME_HEIGHT); } } } } public void setHighlightedDate(DatedThing d) { mouseHighlighted = d; } public DatedThing getHighlightedDate() { return mouseHighlighted; } /** * set list of things * * @param l list of DatedThings */ public void setDatedThings(List l) { setDatedThings(l, false); } /** * set the group we're linked to * * @param group group of Timelines */ public void setGroup(List group) { timelineGroup = group; } /** * set list of things * * @param l list of DatedThings * @param andSetRange also set the start/end visible range */ public void setDatedThings(List l, boolean andSetRange) { this.datedThings = DatedObject.sort(l, true); if (andSetRange) { if (this.datedThings.size() >= 2) { //Pad the initial bounds a little bit Date d1 = ((DatedThing) this.datedThings.get(0)).getDate(); Date d2 = ((DatedThing) this.datedThings.get( this.datedThings.size() - 1)).getDate(); long middle = d1.getTime() + (d2.getTime() - d1.getTime()) / 2; long timeDelta = (long) ((d2.getTime() - d1.getTime()) * 1.1); init(new Date(middle - timeDelta / 2), new Date(middle + timeDelta / 2)); } else { startDate = new Date(System.currentTimeMillis() - DateUtil.MILLIS_DAY); startDate = new Date(System.currentTimeMillis()); } } repaint(); } /** * format date * * @param date date * * @return date formatted */ public String format(Date date) { return format(date.getTime()); } /** * get the format to use given the size of the visible range * * @return format */ public String getFormat() { long start = startDate.getTime(); long end = endDate.getTime(); long diff = end - start; if (diff < DateUtil.MILLIS_SECOND * 20) { return "yyyy-MM-dd HH:mm:ss:SS z"; } if (diff < 5 * DateUtil.MILLIS_MINUTE) { return "yyyy-MM-dd HH:mm:ss z"; } if (diff < DateUtil.MILLIS_HOUR) { return "yyyy-MM-dd HH:mm z"; } if (diff < DateUtil.MILLIS_DAY) { return "yyyy-MM-dd HH:mm z"; } if (diff < 3 * DateUtil.MILLIS_DAY) { return "yyyy-MM-dd HH:00 z"; } if (diff < DateUtil.MILLIS_WEEK) { return "yyyy-MM-dd"; } if (diff < DateUtil.MILLIS_MONTH) { return "yyyy-MM-dd"; } if (diff < DateUtil.MILLIS_YEAR) { return "yyyy-MM-dd"; } if (diff < DateUtil.MILLIS_DECADE) { return "yyyy-MM"; } if (diff > DateUtil.MILLIS_MILLENIUM) { return "yyyy G"; } return "yyyy"; } /** * format time * * @param time time * * @return formatted time */ public String format(long time) { return format(time, getFormat()); } /** * format time * * @param time time * @param pattern date format * * @return formatted time */ public String format(long time, String pattern) { long now = System.currentTimeMillis(); double diff = now - time; if (diff > DateUtil.MILLIS_MILLENIUM * 1000) { diff = diff / (DateUtil.MILLIS_MILLENIUM * 1000); diff *= 100; diff = (int) diff; diff /= 100; return diff + " mya"; } diff = Math.abs(diff); if (diff > DateUtil.MILLIS_MILLENIUM * 1000) { diff = diff / (DateUtil.MILLIS_MILLENIUM * 1000); diff *= 100; diff = (int) diff; diff /= 100; return diff + " my"; } // System.err.println("format:" + pattern); StringBuffer buf = new StringBuffer(); DateFormat sdf = new SimpleDateFormat(); sdf.setTimeZone(getTimeZone()); if ((pattern != null) && (sdf instanceof SimpleDateFormat)) { ((SimpleDateFormat) sdf).applyPattern(pattern); } return (sdf.format(time, buf, new FieldPosition(0))).toString(); } /** * reset range * * @param doDateSelection determines whether we reset the date selection range or the visible range */ protected void reset(boolean doDateSelection) { if (doDateSelection) { if (originalDateSelection != null) { dateSelection = new DateSelection(originalDateSelection); } else { dateSelection = new DateSelection(); } dateSelectionChanged(); } else { startDate = originalStartDate; endDate = originalEndDate; timelineChanged(); } } /** * shift left/right a percentage * * @param percent how much * @param doDateSelection visible or date selection */ protected void shiftByPercent(double percent, boolean doDateSelection) { long start = (doDateSelection ? dateSelection.getStartFixedTime() : startDate.getTime()); long end = (doDateSelection ? dateSelection.getEndFixedTime() : endDate.getTime()); long timeDelta = (long) ((end - start) * percent); if (doDateSelection) { dateSelection.setStartFixedTime(start + timeDelta); dateSelection.setEndFixedTime(end + timeDelta); dateSelectionChanged(); } else { startDate = new Date(start + timeDelta); endDate = new Date(end + timeDelta); timelineChanged(); } } /** * zoom * * @param percent how much * @param doDateSelection visible or date selection */ public void expandByPercent(double percent, boolean doDateSelection) { long start = (doDateSelection ? dateSelection.getStartFixedTime() : startDate.getTime()); long end = (doDateSelection ? dateSelection.getEndFixedTime() : endDate.getTime()); long middle = start + (end - start) / 2; long timeDelta = (long) ((end - start) * percent); if (timeDelta <= 1) { timeDelta = 2; } long half = timeDelta / 2; while (half <= 2) { half++; } long t1 = middle - half; long t2 = middle + half; if (t2 <= t1) { t1 -= (t1 - t2) + 1; t2++; } if (doDateSelection) { dateSelection.setStartFixedTime(t1); dateSelection.setEndFixedTime(t2); dateSelectionChanged(); } else { startDate = new Date(t1); endDate = new Date(t2); timelineChanged(); } } /** * map x location to date * * @param location x * * @return date */ public Date toDate(int location) { Dimension dim = getSize(); long start = startDate.getTime(); long end = endDate.getTime(); int width = (int) dim.getWidth(); int left = horizontalPadding; int right = width - horizontalPadding; double percent = location / (double) (right - left); return new Date(start + (long) (percent * (end - start))); } /** * map date to x location * * @param date location * * @return x */ public int toLocation(Date date) { return toLocation(date.getTime()); } /** * map date to x * * @param date date * * @return x */ public int toLocation(long date) { if (startDate == null) { return 0; } Dimension dim = getSize(); long start = startDate.getTime(); long end = endDate.getTime(); if (start == end) { return -1; } double percent = (date - start) / (double) (end - start); // System.err.println(date+" " + percent); int width = (int) dim.getWidth(); int innerWidth = width - horizontalPadding * 2; return horizontalPadding + (int) (percent * (innerWidth)); } /** * Set the StartDate property. * * * @param start start * @param end end */ public void setRange(Date start, Date end) { setRange(start, end, false); } /** * _more_ */ public void makeCurrentRangeOriginal() { originalStartDate = startDate; originalEndDate = endDate; } /** * _more_ * * @param start _more_ * @param end _more_ * @param makeTheseTheOriginal _more_ */ public void setRange(Date start, Date end, boolean makeTheseTheOriginal) { startDate = start; endDate = end; if (makeTheseTheOriginal) { originalStartDate = startDate; originalEndDate = endDate; } timelineChanged(); } /** * Set the StartDate property. * * @param value The new value for StartDate */ public void setStartDate(Date value) { startDate = value; timelineChanged(); } /** * Get the StartDate property. * * @return The StartDate */ public Date getStartDate() { return startDate; } /** * Set the EndDate property. * * @param value The new value for EndDate */ public void setEndDate(Date value) { endDate = value; timelineChanged(); } /** * Get the EndDate property. * * @return The EndDate */ public Date getEndDate() { return endDate; } /** * popup timeline in a dialog * * * @return ok */ public boolean popup() { if (dialog == null) { dialog = new JDialog((JFrame) null, "Date Selection", true); dialog.getContentPane().add(getContents(true)); dialog.pack(); dialog.setLocation(new Point(200, 200)); } dialogOK = false; dialog.setVisible(true); return dialogOK; } /** * main * * @param args args * * @throws Exception _more_ */ public static void main(String[] args) throws Exception { boolean useDateSelection = true; try { final List dates = new ArrayList(); if (args.length == 0) { long now = System.currentTimeMillis(); for (int i = 0; i < 30; i++) { DatedObject datedObject = new DatedObject(new Date((long) (now + DateUtil.minutesToMillis(20) - i * Math.random() * 60 * 60 * 1000))); dates.add(datedObject); } } else { useDateSelection = false; String fmt = "EEE MMM dd hh:mm:ss yyyy"; String file; if (args.length > 1) { fmt = args[0]; file = args[1]; } else { file = args[0]; } BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream(file))); String line; //[Sat Jul 28 03:14:46 2007] [error] [client 74.6.26.164] Directory index forbidden by rule: /content/software/idv/release/stable/webstart/ SimpleDateFormat dateFormat = new java.text.SimpleDateFormat(fmt); java.text.ParsePosition pp = new java.text.ParsePosition(0); while ((line = reader.readLine()) != null) { int idx1 = line.indexOf("["); int idx2 = line.indexOf("]", idx1); if ((idx1 < 0) || (idx2 <= idx1)) { continue; } String dateString = line.substring(idx1 + 1, idx2); // Date date = dateFormat.parse(dateString, new ParsePosition(0)); pp.setIndex(0); Date date = dateFormat.parse(dateString, pp); if (date != null) { // System.err.println("date:" + date); dates.add(new DatedObject(date, line)); } else { System.err.println("failed to parse:" + dateString); System.err.println("fmt:" + fmt); return; } } } if (dates.size() == 0) { System.err.println("no dates"); return; } final Timeline timeline = new Timeline(dates, 400); timeline.setUseDateSelection(useDateSelection); DateSelection dateSelection = new DateSelection(timeline.getStartDate(), timeline.getEndDate()); dateSelection.setRoundTo(DateUtil.minutesToMillis(15)); dateSelection.setInterval(DateUtil.minutesToMillis(120)); // dateSelection.setPreRange(DateUtil.minutesToMillis(15)); timeline.setDateSelection(dateSelection); // dateSelection.setPostRange(0); // dateSelection.setIntervalRange(DateUtil.minutesToMillis(30)); final JCheckBox justShowSelectedCbx = new JCheckBox("Just show selected", false); justShowSelectedCbx.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { timeline.justShowSelected = justShowSelectedCbx.isSelected(); timeline.repaint(); } }); final JButton useSelectedBtn = new JButton("Use selected"); useSelectedBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { timeline.setDatedThings(timeline.getSelected()); } }); final JButton resetBtn = new JButton("Reset"); resetBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { timeline.setDatedThings(dates); } }); final JTextField searchFld = new JTextField(); searchFld.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { List toks = StringUtil.split(searchFld.getText().trim(), ",", true, true); List selected = new ArrayList(); for (int i = 0; i < dates.size(); i++) { DatedObject datedObject = (DatedObject) dates.get(i); boolean ok = true; for (int tokIdx = 0; tokIdx < toks.size(); tokIdx++) { String s = (String) toks.get(tokIdx); boolean not = s.startsWith("!"); if (not) { s = s.substring(0); } boolean contains = datedObject.getObject().toString().indexOf(s) >= 0; if (not) { contains = !contains; } // if(i==0) System.err.println ("s:" + s + " " + not); if ( !contains) { ok = false; break; } } if (ok) { selected.add(datedObject); } } timeline.setSelected(selected); } }); JComponent bottom = LayoutUtil.centerRight(searchFld, LayoutUtil.hbox(useSelectedBtn, resetBtn)); // JComponent bottom = searchFld; JDialog dialog = new JDialog((JFrame) null, "Date Selection", true); dialog.getContentPane().add( LayoutUtil.centerBottom(timeline.getContents(true), bottom)); dialog.pack(); dialog.setLocation(new Point(200, 200)); dialog.setVisible(true); } catch (Throwable thr) { thr.printStackTrace(); return; } } /** * Set the IsCapableOfSelection property. * * @param value The new value for IsCapableOfSelection */ public void setIsCapableOfSelection(boolean value) { isCapableOfSelection = value; } /** * Get the IsCapableOfSelection property. * * @return The IsCapableOfSelection */ public boolean getIsCapableOfSelection() { return isCapableOfSelection; } /** * Set the ShortDisplay property. * * @param value The new value for ShortDisplay */ public void setShortDisplay(boolean value) { shortDisplay = value; Dimension dim = getPreferredSize(); if (shortDisplay) { setPreferredSize(new Dimension((int) dim.getWidth(), 20)); } else { setPreferredSize(new Dimension((int) dim.getWidth(), 100)); } } /** * Get the ShortDisplay property. * * @return The ShortDisplay */ public boolean getShortDisplay() { return shortDisplay; } /** * Set the ColorTimeSelected property. * * @param value The new value for ColorTimeSelected */ public void setColorTimeSelected(Color value) { colorTimeSelected = value; } /** * Get the ColorTimeSelected property. * * @return The ColorTimeSelected */ public Color getColorTimeSelected() { return colorTimeSelected; } /** * Set the ColorTimeUnselected property. * * @param value The new value for ColorTimeUnselected */ public void setColorTimeUnselected(Color value) { colorTimeUnselected = value; } /** * Get the ColorTimeUnselected property. * * @return The ColorTimeUnselected */ public Color getColorTimeUnselected() { return colorTimeUnselected; } }
Unidata/IDV
src/ucar/unidata/ui/Timeline.java
213,335
/** * SPDX-FileCopyrightText: (c) 2000 Liferay, Inc. https://liferay.com * SPDX-License-Identifier: LGPL-2.1-or-later OR LicenseRef-Liferay-DXP-EULA-2.0.0-2023-06 */ package com.liferay.portal.upgrade.v7_0_0; import com.liferay.petra.string.StringBundler; import com.liferay.petra.string.StringPool; import com.liferay.portal.kernel.dao.jdbc.AutoBatchPreparedStatementUtil; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.model.PortletConstants; import com.liferay.portal.kernel.upgrade.UpgradeProcess; import com.liferay.portal.kernel.util.LoggingTimer; import com.liferay.portal.kernel.xml.Document; import com.liferay.portal.kernel.xml.DocumentException; import com.liferay.portal.kernel.xml.Element; import com.liferay.portal.kernel.xml.SAXReaderUtil; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Iterator; import java.util.Objects; /** * @author Joshua Gok */ public class UpgradePortalPreferences extends UpgradeProcess { protected String convertStagingPreferencesToJSON(String preferences) throws Exception { Document newDocument = SAXReaderUtil.createDocument(); Element newRootElement = SAXReaderUtil.createElement( "portlet-preferences"); newDocument.add(newRootElement); Document document = SAXReaderUtil.read(preferences); Element rootElement = document.getRootElement(); Iterator<Element> iterator = rootElement.elementIterator(); while (iterator.hasNext()) { Element preferenceElement = iterator.next(); String preferenceName = preferenceElement.elementText("name"); if (!preferenceName.contains( "com.liferay.portal.kernel.staging.Staging")) { newRootElement.add(preferenceElement.createCopy()); } } return newDocument.formattedString(StringPool.DOUBLE_SPACE); } @Override protected void doUpgrade() throws Exception { upgradeStagingPortalPreferences(); } protected void upgradeStagingPortalPreferences() throws Exception { try (LoggingTimer loggingTimer = new LoggingTimer(); PreparedStatement preparedStatement1 = connection.prepareStatement( "select portalPreferencesId, preferences from " + "PortalPreferences"); ResultSet resultSet = preparedStatement1.executeQuery(); PreparedStatement preparedStatement2 = AutoBatchPreparedStatementUtil.concurrentAutoBatch( connection, "update PortalPreferences set preferences = ? where " + "portalPreferencesId = ?")) { while (resultSet.next()) { long portalPreferencesId = resultSet.getLong( "portalPreferencesId"); String oldPreferences = resultSet.getString("preferences"); String newPreferences = null; try { newPreferences = convertStagingPreferencesToJSON( oldPreferences); } catch (DocumentException documentException) { if (_log.isWarnEnabled()) { _log.warn( StringBundler.concat( "Portal preferences ", portalPreferencesId, " contains invalid XML, resetting to default"), documentException); } newPreferences = PortletConstants.DEFAULT_PREFERENCES; } if (Objects.equals(oldPreferences, newPreferences)) { continue; } preparedStatement2.setString(1, newPreferences); preparedStatement2.setLong(2, portalPreferencesId); preparedStatement2.addBatch(); } preparedStatement2.executeBatch(); } } private static final Log _log = LogFactoryUtil.getLog( UpgradePortalPreferences.class); }
liferay/liferay-portal
portal-impl/src/com/liferay/portal/upgrade/v7_0_0/UpgradePortalPreferences.java
213,336
package com.sohu.index.tv.mq.common; import org.apache.rocketmq.common.message.Message; import org.apache.rocketmq.common.message.MessageClientExt; import org.apache.rocketmq.common.message.MessageExt; /** * 批量消息 * * @author yongfeigao * @date 2019年10月18日 * @param <T> * @param <MessageExt> */ public class MQMessage<T> { public static final String IDEMPOTENT_ID = "IDEMPOTENT_ID"; // 发送的原始对象 private T message; // 可以重试的次数 private int retryTimes = -1; // rocketmq 消息 private Message innerMessage; // 发送异常,测试用 private boolean exceptionForTest; public MQMessage() { } public MQMessage(T message, Message innerMessage) { this.message = message; this.innerMessage = innerMessage; } public T getMessage() { return message; } public void setMessage(T message) { this.message = message; } public MessageExt getMessageExt() { return (MessageExt) innerMessage; } public void setMessageExt(MessageExt messageExt) { setInnerMessage(messageExt); } public Message getInnerMessage() { return innerMessage; } public void setInnerMessage(Message innerMessage) { this.innerMessage = innerMessage; } public MQMessage<T> setKeys(String keys) { if (keys != null && keys.length() > 0) { innerMessage.setKeys(keys); } return this; } public String getKeys() { return innerMessage.getKeys(); } public String getTags() { return innerMessage.getTags(); } public MQMessage<T> setTags(String tags) { innerMessage.setTags(tags); return this; } public MQMessage<T> setDelayTimeLevel(int level) { innerMessage.setDelayTimeLevel(level); return this; } public int getDelayTimeLevel() { return innerMessage.getDelayTimeLevel(); } public byte[] getBody() { return innerMessage.getBody(); } public MQMessage<T> setBody(byte[] body) { innerMessage.setBody(body); return this; } public boolean isWaitStoreMsgOK() { return innerMessage.isWaitStoreMsgOK(); } public MQMessage<T> setWaitStoreMsgOK(boolean waitStoreMsgOK) { innerMessage.setWaitStoreMsgOK(waitStoreMsgOK); return this; } public MQMessage<T> setTopic(String topic) { innerMessage.setTopic(topic); return this; } public String getTopic() { return innerMessage.getTopic(); } public int getRetryTimes() { return retryTimes; } public MQMessage<T> setRetryTimes(int retryTimes) { this.retryTimes = retryTimes; return this; } public MQMessage<T> resetRetryTimes(int retryTimes) { if (this.retryTimes == -1) { this.retryTimes = retryTimes; } return this; } /** * 构建offsetMsgId * * @return */ public String buildOffsetMsgId() { return innerMessage instanceof MessageClientExt ? ((MessageClientExt)innerMessage).getOffsetMsgId() : null; } public String getMsgId() { String msgId = buildOffsetMsgId(); if (msgId == null) { msgId = getMessageExt().getMsgId(); } return msgId; } public static <T> MQMessage<T> build(T message) { MQMessage<T> mqMessage = new MQMessage<>(); mqMessage.setMessage(message); mqMessage.innerMessage = new Message(); mqMessage.setWaitStoreMsgOK(true); return mqMessage; } /** * 设置幂等id * * @param idempotentId */ public MQMessage<T> setIdempotentID(String idempotentId) { innerMessage.putUserProperty(IDEMPOTENT_ID, idempotentId); return this; } /** * 设置延迟投递的时间戳 * * @param idempotentId * @return */ public MQMessage<T> setDeliveryTimestamp(long deliveryTimestamp) { innerMessage.setDeliverTimeMs(deliveryTimestamp); return this; } public MQMessage<T> setExceptionForTest(boolean exceptionForTest) { this.exceptionForTest = exceptionForTest; return this; } public boolean isExceptionForTest() { return exceptionForTest; } @Override public String toString() { return "[topic=" + getTopic() + ", message=" + message + ", retryTimes=" + retryTimes + "]"; } }
sohutv/mqcloud
mq-client-common-open/src/main/java/com/sohu/index/tv/mq/common/MQMessage.java
213,337
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.rocketmq.common.message; import java.io.Serializable; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class Message implements Serializable { private static final long serialVersionUID = 8445773977080406428L; private String topic; private int flag; private Map<String, String> properties; private byte[] body; public Message() { } public Message(String topic, byte[] body) { this(topic, "", "", 0, body, true); } public Message(String topic, String tags, String keys, int flag, byte[] body, boolean waitStoreMsgOK) { this.topic = topic; this.flag = flag; this.body = body; if (tags != null && tags.length() > 0) this.setTags(tags); if (keys != null && keys.length() > 0) this.setKeys(keys); this.setWaitStoreMsgOK(waitStoreMsgOK); } public Message(String topic, String tags, byte[] body) { this(topic, tags, "", 0, body, true); } public Message(String topic, String tags, String keys, byte[] body) { this(topic, tags, keys, 0, body, true); } public void setKeys(String keys) { this.putProperty(MessageConst.PROPERTY_KEYS, keys); } void putProperty(final String name, final String value) { if (null == this.properties) { this.properties = new HashMap<String, String>(); } this.properties.put(name, value); } void clearProperty(final String name) { if (null != this.properties) { this.properties.remove(name); } } public void putUserProperty(final String name, final String value) { if (MessageConst.STRING_HASH_SET.contains(name)) { throw new RuntimeException(String.format( "The Property<%s> is used by system, input another please", name)); } if (value == null || value.trim().isEmpty() || name == null || name.trim().isEmpty()) { throw new IllegalArgumentException( "The name or value of property can not be null or blank string!" ); } this.putProperty(name, value); } public String getUserProperty(final String name) { return this.getProperty(name); } public String getProperty(final String name) { if (null == this.properties) { this.properties = new HashMap<String, String>(); } return this.properties.get(name); } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public String getTags() { return this.getProperty(MessageConst.PROPERTY_TAGS); } public void setTags(String tags) { this.putProperty(MessageConst.PROPERTY_TAGS, tags); } public String getKeys() { return this.getProperty(MessageConst.PROPERTY_KEYS); } public void setKeys(Collection<String> keys) { StringBuffer sb = new StringBuffer(); for (String k : keys) { sb.append(k); sb.append(MessageConst.KEY_SEPARATOR); } this.setKeys(sb.toString().trim()); } public int getDelayTimeLevel() { String t = this.getProperty(MessageConst.PROPERTY_DELAY_TIME_LEVEL); if (t != null) { return Integer.parseInt(t); } return 0; } public void setDelayTimeLevel(int level) { this.putProperty(MessageConst.PROPERTY_DELAY_TIME_LEVEL, String.valueOf(level)); } public boolean isWaitStoreMsgOK() { String result = this.getProperty(MessageConst.PROPERTY_WAIT_STORE_MSG_OK); if (null == result) return true; return Boolean.parseBoolean(result); } public void setWaitStoreMsgOK(boolean waitStoreMsgOK) { this.putProperty(MessageConst.PROPERTY_WAIT_STORE_MSG_OK, Boolean.toString(waitStoreMsgOK)); } public int getFlag() { return flag; } public void setFlag(int flag) { this.flag = flag; } public byte[] getBody() { return body; } public void setBody(byte[] body) { this.body = body; } public Map<String, String> getProperties() { return properties; } void setProperties(Map<String, String> properties) { this.properties = properties; } public String getBuyerId() { return getProperty(MessageConst.PROPERTY_BUYER_ID); } public void setBuyerId(String buyerId) { putProperty(MessageConst.PROPERTY_BUYER_ID, buyerId); } @Override public String toString() { return "Message [topic=" + topic + ", flag=" + flag + ", properties=" + properties + ", body=" + (body != null ? body.length : 0) + "]"; } }
didi/DDMQ
rocketmq/common/src/main/java/org/apache/rocketmq/common/message/Message.java
213,338
/* ### * IP: GHIDRA * REVIEWED: YES * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package docking.dnd; import java.awt.Point; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.dnd.DropTargetDragEvent; /** * Interface used by the DragDropTree to know how to handle the * drag and drop operations. */ public interface DragDropManager { /** * Return true if the dragNode can be dragged. * @param dragNode node where user is initiating the drag operation * @param dragAction user action for the drag operation */ public boolean isStartDragOk(DragDropNode dragNode, int dragAction); /** * Return true if the drop site is valid for the given target and drag event. * @param destNode destination for node being dragged * @param e the drag event * */ public boolean isDropSiteOk(DragDropNode destNode, DropTargetDragEvent e); /** * Add the given data to the destination node. * @param destNode destination node for the data. * @param data data to add * @param chosen data flavor for the data being added * @param dropAction user action for drop operation */ public void add(DragDropNode destNode, Object data, DataFlavor chosen, int dropAction); /** * Remove the given sourceNodes. (It got moved, so remove it at the source) * @param sourceNodes nodes to remove. */ public void move(DragDropNode[] sourceNodes); /** * Return the data flavors that can be dragged and dropped. */ public DataFlavor[] getAcceptableFlavors(); /** * Get the transferable at the given point. * @param p point where the mouse pointer is when the drag begins */ public Transferable getTransferable(Point p); }
NationalSecurityAgency/ghidra
Ghidra/Framework/Docking/src/main/java/docking/dnd/DragDropManager.java
213,339
/* * Copyright (C) 2020 Graylog, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. */ package org.graylog.datanode.configuration.variants; import jakarta.inject.Inject; import jakarta.inject.Named; import jakarta.validation.constraints.NotNull; import org.graylog.datanode.Configuration; import org.graylog.datanode.configuration.DatanodeConfiguration; import org.graylog.security.certutil.ca.exceptions.KeyStoreStorageException; import org.graylog.security.certutil.keystore.storage.KeystoreFileStorage; import org.graylog.security.certutil.keystore.storage.KeystoreMongoStorage; import org.graylog.security.certutil.keystore.storage.location.KeystoreMongoLocation; import org.graylog2.cluster.certificates.CertificatesService; import org.graylog2.plugin.system.NodeId; import java.io.IOException; import java.nio.file.Path; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.util.Optional; public final class MongoCertSecureConfiguration extends SecureConfiguration { private final NodeId nodeId; private final CertificatesService certificatesService; private final char[] secret; private final char[] mongoKeystorePassword; private final KeystoreMongoStorage mongoKeyStorage; private final KeystoreFileStorage fileKeyStorage; @Inject public MongoCertSecureConfiguration(final DatanodeConfiguration datanodeConfiguration, final NodeId nodeId, final @Named("password_secret") String passwordSecret, final CertificatesService certificatesService, KeystoreMongoStorage mongoKeyStore, KeystoreFileStorage fileKeyStore ) { super(datanodeConfiguration); this.nodeId = nodeId; this.certificatesService = certificatesService; this.secret = passwordSecret.toCharArray(); this.mongoKeyStorage = mongoKeyStore; this.fileKeyStorage = fileKeyStore; //TODO: matches line 123 of DataNodePreflightGeneratePeriodical, but both need to be changed this.mongoKeystorePassword = secret; } @Override public boolean isConfigured(Configuration localConfiguration) { return certificatesService.hasCert(getMongoKeystoreLocation()); } @Override public OpensearchSecurityConfiguration build() throws KeyStoreStorageException, IOException, GeneralSecurityException { final Path targetTransportKeystoreLocation = getTransportKeystoreLocation(); final Path targetHttpKeystoreLocation = getHttpKeystoreLocation(); // this will take the mongodb-stored keys and persist them on a disk, in the opensearch configuration directory final KeystoreMongoLocation mongoKeystoreLocation = getMongoKeystoreLocation(); reEncypt(mongoKeystoreLocation, mongoKeystorePassword, targetTransportKeystoreLocation, secret); reEncypt(mongoKeystoreLocation, mongoKeystorePassword, targetHttpKeystoreLocation, secret); return new OpensearchSecurityConfiguration( new KeystoreInformation(targetTransportKeystoreLocation.toAbsolutePath(), secret), new KeystoreInformation(targetHttpKeystoreLocation.toAbsolutePath(), secret) ); } @NotNull private KeystoreMongoLocation getMongoKeystoreLocation() { return KeystoreMongoLocation.datanode(nodeId); } private void reEncypt(final KeystoreMongoLocation originalLocation, final char[] originalPassword, final Path targetLocation, final char[] newPassword ) throws KeyStoreStorageException { final Optional<KeyStore> keyStore = mongoKeyStorage.readKeyStore(originalLocation, originalPassword); if (keyStore.isPresent()) { final KeyStore originalKeystore = keyStore.get(); fileKeyStorage.writeKeyStore(targetLocation, originalKeystore, originalPassword, newPassword); } else { throw new KeyStoreStorageException("No keystore present in : " + originalLocation); } } }
Graylog2/graylog2-server
data-node/src/main/java/org/graylog/datanode/configuration/variants/MongoCertSecureConfiguration.java
213,340
/* * Copyright (C) 2020 Graylog, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. */ package org.graylog.datanode.bootstrap.preflight; import com.google.common.collect.ImmutableList; import jakarta.inject.Inject; import jakarta.inject.Named; import jakarta.inject.Singleton; import org.bouncycastle.operator.OperatorException; import org.graylog.datanode.configuration.DatanodeConfiguration; import org.graylog.security.certutil.CertConstants; import org.graylog.security.certutil.cert.CertificateChain; import org.graylog.security.certutil.cert.storage.CertChainMongoStorage; import org.graylog.security.certutil.cert.storage.CertChainStorage; import org.graylog.security.certutil.csr.CertificateAndPrivateKeyMerger; import org.graylog.security.certutil.csr.CsrGenerator; import org.graylog.security.certutil.csr.exceptions.CSRGenerationException; import org.graylog.security.certutil.csr.storage.CsrMongoStorage; import org.graylog.security.certutil.keystore.storage.KeystoreMongoStorage; import org.graylog.security.certutil.keystore.storage.location.KeystoreMongoCollections; import org.graylog.security.certutil.keystore.storage.location.KeystoreMongoLocation; import org.graylog.security.certutil.privatekey.PrivateKeyEncryptedFileStorage; import org.graylog2.cluster.NodeNotFoundException; import org.graylog2.cluster.nodes.DataNodeDto; import org.graylog2.cluster.nodes.NodeService; import org.graylog2.cluster.preflight.DataNodeProvisioningConfig; import org.graylog2.cluster.preflight.DataNodeProvisioningService; import org.graylog2.plugin.periodical.Periodical; import org.graylog2.plugin.system.NodeId; import org.graylog2.shared.SuppressForbidden; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetAddress; import java.nio.file.Path; import java.security.KeyStore; import java.util.Collections; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; @Singleton public class DataNodeConfigurationPeriodical extends Periodical { private static final Logger LOG = LoggerFactory.getLogger(DataNodeConfigurationPeriodical.class); private final DataNodeProvisioningService dataNodeProvisioningService; private final NodeService<DataNodeDto> nodeService; private final NodeId nodeId; private final PrivateKeyEncryptedFileStorage privateKeyEncryptedStorage; private final CsrMongoStorage csrStorage; private final CsrGenerator csrGenerator; private final CertChainStorage certMongoStorage; private final CertificateAndPrivateKeyMerger certificateAndPrivateKeyMerger; private final char[] passwordSecret; private final KeystoreMongoStorage mongoKeyStorage; @Inject public DataNodeConfigurationPeriodical(final DataNodeProvisioningService dataNodeProvisioningService, final NodeService<DataNodeDto> nodeService, final NodeId nodeId, final CsrMongoStorage csrStorage, final CsrGenerator csrGenerator, final CertChainMongoStorage certMongoStorage, final CertificateAndPrivateKeyMerger certificateAndPrivateKeyMerger, final @Named("password_secret") String passwordSecret, final DatanodeConfiguration datanodeConfiguration, KeystoreMongoStorage mongoKeyStorage) throws IOException { this.dataNodeProvisioningService = dataNodeProvisioningService; this.nodeService = nodeService; this.nodeId = nodeId; this.csrStorage = csrStorage; this.csrGenerator = csrGenerator; this.certMongoStorage = certMongoStorage; this.certificateAndPrivateKeyMerger = certificateAndPrivateKeyMerger; // TODO: merge with real storage this.privateKeyEncryptedStorage = new PrivateKeyEncryptedFileStorage(datanodeConfiguration.datanodeDirectories().createConfigurationFile(Path.of("privateKey.cert"))); this.passwordSecret = passwordSecret.toCharArray(); this.mongoKeyStorage = mongoKeyStorage; } @Override public void doRun() { LOG.debug("checking if this DataNode is supposed to take configuration steps."); var cfg = dataNodeProvisioningService.getPreflightConfigFor(nodeId.getNodeId()); if (cfg.isEmpty()) { // write default config if none exists for this node writeInitialProvisioningConfig(); return; } cfg.ifPresent(c -> { final var state = c.state(); if (state == null) { return; } switch (state) { case CONFIGURED -> writeCsr(c); case SIGNED -> readSignedCertificate(c); case STARTUP_TRIGGER -> dataNodeProvisioningService.changeState(nodeId.getNodeId(), DataNodeProvisioningConfig.State.STARTUP_REQUESTED); } }); } private void readSignedCertificate(DataNodeProvisioningConfig cfg) { if (cfg.certificate() == null) { LOG.error("Config entry in signed state, but no certificate data present in Mongo"); } else { try { final Optional<CertificateChain> certificateChain = certMongoStorage.readCertChain(nodeId.getNodeId()); if (certificateChain.isPresent()) { final char[] secret = passwordSecret; KeyStore nodeKeystore = certificateAndPrivateKeyMerger.merge( certificateChain.get(), privateKeyEncryptedStorage, secret, secret, CertConstants.DATANODE_KEY_ALIAS ); mongoKeyStorage.writeKeyStore(KeystoreMongoLocation.datanode(nodeId), nodeKeystore, secret, secret); //should be in one transaction, but we miss transactions... dataNodeProvisioningService.changeState(nodeId.getNodeId(), DataNodeProvisioningConfig.State.STORED); } } catch (Exception ex) { LOG.error("Config entry in signed state, but wrong certificate data present in Mongo"); } } } private void writeCsr(DataNodeProvisioningConfig cfg) { try { final var node = nodeService.byNodeId(nodeId); final var altNames = ImmutableList.<String>builder() .addAll(Optional.ofNullable(cfg.altNames()).orElse(Collections.emptyList())) .addAll(determineAltNames()) .build(); final var csr = csrGenerator.generateCSR(passwordSecret, node.getHostname(), altNames, privateKeyEncryptedStorage); csrStorage.writeCsr(csr, nodeId.getNodeId()); LOG.info("created CSR for this node"); } catch (CSRGenerationException | IOException | NodeNotFoundException | OperatorException ex) { LOG.error("error generating a CSR: " + ex.getMessage(), ex); dataNodeProvisioningService.save(cfg.asError(ex.getMessage())); } } private void writeInitialProvisioningConfig() { dataNodeProvisioningService.save(DataNodeProvisioningConfig.builder() .nodeId(nodeId.getNodeId()) .state(DataNodeProvisioningConfig.State.UNCONFIGURED) .build()); } private Iterable<String> determineAltNames() { return Stream.of("127.0.0.1", "::1") .map(this::reverseLookup) .filter(Objects::nonNull) .collect(Collectors.toSet()); } @SuppressForbidden("Deliberate use of InetAddress#getHostName") private String reverseLookup(String ipAddress) { try { final var inetAddress = InetAddress.getByName(ipAddress); final var reverseLookup = inetAddress.getHostName(); return reverseLookup.equals(ipAddress) ? null : reverseLookup; } catch (Exception e) { return null; } } @Override protected Logger getLogger() { return LOG; } @Override public boolean runsForever() { return false; } @Override public boolean stopOnGracefulShutdown() { return true; } @Override public boolean leaderOnly() { return false; } @Override public boolean startOnThisNode() { return true; } @Override public boolean isDaemon() { return true; } @Override public int getInitialDelaySeconds() { return 0; } @Override public int getPeriodSeconds() { return 2; } }
Graylog2/graylog2-server
data-node/src/main/java/org/graylog/datanode/bootstrap/preflight/DataNodeConfigurationPeriodical.java
213,341
package com.rhomobile.rhodes; import com.rhomobile.rhodes.extmanager.RhoExtManager; import com.rhomobile.rhodes.RhodesActivity; import com.rhomobile.rhodes.util.PerformOnUiThread; import android.app.Activity; import android.R; import android.app.Dialog; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class PasswordDialog { private static EditText mEditText; private static TextView text; private static Button dialogOKButton; private static Button dialogCancelButton; public static void createpopup() { // custom dialog final Dialog dialog = new Dialog(RhodesActivity.getContext()); dialog.setContentView(RhoExtManager.getResourceId("layout","password_prompt")); dialog.setTitle("Please enter password"); dialog.setCanceledOnTouchOutside(false); // set the custom dialog components - text, view and button mEditText = (EditText) dialog.findViewById(RhoExtManager.getResourceId("id","edit_text")); text = (TextView) dialog.findViewById(RhoExtManager.getResourceId("id","text")); dialogOKButton = (Button) dialog.findViewById(RhoExtManager.getResourceId("id","dialogButtonOK")); dialogCancelButton = (Button) dialog.findViewById(RhoExtManager.getResourceId("id","dialogButtoncancel")); dialogOKButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { checkpassword(); } }); dialogCancelButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); } private static void checkpassword(){ if(mEditText.getText().toString().equals(RhodesService.getExitPasswordValue())) RhodesService.PerformRealExit(); else { text.setText("Invalid Password"); mEditText.setText(""); } } }
rhomobile/rhodes
platform/android/Rhodes/src/com/rhomobile/rhodes/PasswordDialog.java
213,342
package org.matthiaszimmermann.location.egm96; import org.matthiaszimmermann.location.Location; import java.io.BufferedInputStream; import java.io.InputStream; /** * offline <a href="https://en.wikipedia.org/wiki/Geoid">geoid</a> implementation based on the data provided * by the <a href="http://earth-info.nga.mil/GandG/wgs84/gravitymod/egm96/intpt.html">online caluclator</a>. * * @author matthiaszimmermann * */ public class Geoid { private static final short OFFSET_INVALID = -0x8000; private static final int ROWS = 719; // (89.75 + 89.75)/0.25 + 1 = 719 private static final int COLS = 1440; // 359.75/0.25 + 1 = 1440 private static final double LATITUDE_MAX = 90.0; private static final double LATITUDE_MAX_GRID = 89.74; private static final double LATITUDE_ROW_FIRST = 89.50; private static final double LATITUDE_ROW_LAST = -89.50; private static final double LATITUDE_MIN_GRID = -89.74; private static final double LATITUDE_MIN = -90.0; public static final double LATITUDE_STEP = 0.25; private static final double LONGITIDE_MIN = 0.0; private static final double LONGITIDE_MIN_GRID = 0.0; private static final double LONGITIDE_MAX_GRID = 359.75; private static final double LONGITIDE_MAX = 360.0; private static final double LONGITIDE_STEP = 0.25; //Store in 'fixed point format' 16-bit short (in 1/100m (cm)) instead of 64-bit double private static final short [][] offset = new short[ROWS][COLS]; private static short offset_north_pole = 0; private static short offset_south_pole = 0; private static boolean s_model_ok = false; @SuppressWarnings("UnusedReturnValue") public static boolean init(InputStream is) { if(s_model_ok) { return true; } try { s_model_ok = readGeoidOffsetsD(new BufferedInputStream(is)); } catch (Exception e) { s_model_ok = false; System.err.println("failed to read stream "+e); } return s_model_ok; } public static double getOffset(double lat, double lon) { Location location = new Location(lat, lon); return getOffset(location); } private static double getOffset(Location location) { double lat = location.getLatitude(); double lng = location.getLongitude(); // special case for exact grid positions if(latIsGridPoint(lat) && lngIsGridPoint(lng)) { return getGridOffset(lat, lng); } Location [][] q = new Location[4][4]; // get four grid locations surrounding the target location // used for bilinear interpolation q[1][1] = getGridFloorLocation(lat, lng); q[1][2] = getUpperLocation(q[1][1]); q[2][1] = getRightLocation(q[1][1]); q[2][2] = getUpperLocation(q[2][1]); // check if we can get points for bicubic interpolation if(q[1][1].getLatitude() >= LATITUDE_MIN_GRID && q[1][2].getLatitude() <= LATITUDE_MAX_GRID) { // left column q[0][1] = getLeftLocation(q[1][1]); q[0][2] = getUpperLocation(q[0][1]); q[0][3] = getUpperLocation(q[0][2]); // top row q[1][3] = getRightLocation(q[0][3]); q[2][3] = getRightLocation(q[1][3]); q[3][3] = getRightLocation(q[2][3]); // bottom row q[0][0] = getLowerLocation(q[0][1]); q[1][0] = getRightLocation(q[0][0]); q[2][0] = getRightLocation(q[1][0]); // right column q[3][0] = getRightLocation(q[2][0]); q[3][1] = getUpperLocation(q[3][0]); q[3][2] = getUpperLocation(q[3][1]); // return bilinearInterpolation(location, q[1][1], q[1][2], q[2][1], q[2][2]); return bicubicSplineInterpolation(location, q); } else { return bilinearInterpolation(location, q[1][1], q[1][2], q[2][1], q[2][2]); } } /** * bilinearInterpolation according to description on wikipedia * @see <a href="https://en.wikipedia.org/wiki/Bilinear_interpolation">wikipedia Bilinear_interpolation</a> * @return the lineary interpolated value */ private static double bilinearInterpolation(Location target, Location q11, Location q12, Location q21, Location q22) { double fq11 = getGridOffset(q11); // lower left double fq12 = getGridOffset(q12); // upper left double fq21 = getGridOffset(q21); // lower right double fq22 = getGridOffset(q22); // upper right double x1 = q11.getLongitude(); double x2 = q22.getLongitude(); double y1 = q22.getLatitude(); double y2 = q11.getLatitude(); // special case for latitude moving from 359.75 -> 0 if(x1 == 359.75 && x2 == 0.0) { x2 = 360.0; } double x = target.getLongitude(); double y = target.getLatitude(); double f11 = fq11 * (x2 - x) * (y2 - y); double f12 = fq12 * (x2 - x) * (y - y1); double f21 = fq21 * (x - x1) * (y2 - y); double f22 = fq22 * (x - x1) * (y - y1); return (f11 + f12 + f21 + f22) / ((x2 - x1) * (y2 - y1)); } /** * Bicubic spline: If you provide a 4x4 grid of values for geometric quantities in u and v, * this class creates an object that will interpolate a Bicubic spline to give you the value * within any point of a unit tile in (u,v) space. * If you want to create a spline surface, you can make a two dimensional array of such objects. * * @see <a href="http://mrl.nyu.edu/~perlin/cubic/Cubic_java.html">Gubic</a> * @return bicubic spline */ private static double bicubicSplineInterpolation(Location target, Location[][] grid) { double[][] G = new double [4][4]; for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { G[i][j] = getGridOffset(grid[i][j]); } } double u1 = grid[1][1].getLatitude(); double v1 = grid[1][1].getLongitude(); double u = (target.getLatitude() - u1 + LATITUDE_STEP) / (4 * LATITUDE_STEP); double v = (target.getLongitude() - v1 + LONGITIDE_STEP) / (4 * LONGITIDE_STEP); Cubic c = new Cubic(G); return c.eval(u, v); } private static Location getUpperLocation(Location location) { double lat = location.getLatitude(); double lng = location.getLongitude(); if(lat == LATITUDE_MAX_GRID) { lat = LATITUDE_MAX; } else if(lat == LATITUDE_ROW_FIRST) { lat = LATITUDE_MAX_GRID; } else if(lat == LATITUDE_MIN) { lat = LATITUDE_MIN_GRID; } else if(lat == LATITUDE_MIN_GRID) { lat = LATITUDE_ROW_LAST; } else { lat += LATITUDE_STEP; } return new Location(lat, lng); } private static Location getLowerLocation(Location location) { double lat = location.getLatitude(); double lng = location.getLongitude(); if(lat == LATITUDE_MIN_GRID) { lat = LATITUDE_MIN; } else if(lat == LATITUDE_ROW_FIRST) { lat = LATITUDE_MIN_GRID; } else if(lat == LATITUDE_MAX) { lat = LATITUDE_MAX_GRID; } else if(lat == LATITUDE_MAX_GRID) { lat = LATITUDE_ROW_FIRST; } else { lat -= LATITUDE_STEP; } return new Location(lat, lng); } private static Location getLeftLocation(Location location) { double lat = location.getLatitude(); double lng = location.getLongitude(); return new Location(lat, lng - LATITUDE_STEP); } private static Location getRightLocation(Location location) { double lat = location.getLatitude(); double lng = location.getLongitude(); return new Location(lat, lng + LATITUDE_STEP); } private static Location getGridFloorLocation(double lat, double lng) { Location floor = (new Location(lat, lng)).floor(); double latFloor = floor.getLatitude(); if(lat >= LATITUDE_MAX_GRID && lat < LATITUDE_MAX) { latFloor = LATITUDE_MAX_GRID; } else if(lat < LATITUDE_MIN_GRID) { latFloor = LATITUDE_MIN; } else if(lat < LATITUDE_ROW_LAST) { latFloor = LATITUDE_MIN_GRID; } return new Location(latFloor, floor.getLongitude()); } private static double getGridOffset(Location location) { return getGridOffset(location.getLatitude(), location.getLongitude()); } private static double getGridOffset(double lat, double lng) { return getGridOffsetS(lat, lng)/100.0d; } private static short getGridOffsetS(double lat, double lng) { if(!s_model_ok) { return OFFSET_INVALID; } if(!latIsGridPoint(lat) || !lngIsGridPoint(lng)) { return OFFSET_INVALID; } if(latIsPole(lat)) { if(lat == LATITUDE_MAX) { return offset_north_pole; } else { return offset_south_pole; } } int i = latToI(lat); int j = lngToJ(lng); return offset[i][j]; } //Get offsets from a definition file where the data is stored in a compressed format //The file is created from the standard file with the following snippet: // cat /cygdrive/f/temp/EGM96complete.dat | perl -ne 'BEGIN{open F,">egm96-delta.dat";$e0=0;} \ //; if(/^\s*([-\d.]+)\s+([-\d.]+)\s+([-\d.]+)/){$e1=sprintf "%.0f", $3*100;$e=$e1-$e0; $e0=$e1; \ //; if(-0x40<=$e && $e <0x40){$e+=0x40; print F pack "C",$e; \ //; }elsif (-0x4000<=$e && $e<0x4000){$e+=0xc000; print F pack "n",$e;}else{die "offset out of bounds";}} \ //; END{print F pack "n",0xc000-$e1; close F}' //Only the offset is stored, assuming coordinates are OK //Data is stored in 'fixed point', resolution 1/100m (cm) //The data is stored as difference to the previous value (as the values are correlated and can be fit in one byte normally) //If the difference is more than fit in 7 bits (+/-0.64m), two bytes are used //One byte data is stored with an offset of 64, so the first bit is never set //For two bytes, the data is stored as 0xc000+offset, so first bit is always set //Last, the south pole offset is added negatively, to get last offset as 0 (used as a check) private static boolean readGeoidOffsetsD(BufferedInputStream is) throws Exception { //BufferedReader _may_ increase the performance final byte[] buf = new byte[1000]; int bufRead = 0; byte prevByte=0; int off = 0; int offsetCount = -1; //NorthPole is first boolean allRead = false; boolean prevIsTwo=false; do { int i = 0; while (i < bufRead) { byte c = buf[i]; i++; if (prevIsTwo) { off += ((((prevByte&0xff) <<8) |(c&0xff))-0xc000); prevIsTwo=false; } else if ((c & 0x80) == 0) { off += ((c&0xff) - 0x40); } else { prevIsTwo = true; } prevByte=c; if (!prevIsTwo) { if (offsetCount < 0) { offset_north_pole = (short) off; } else if (offsetCount == ROWS * COLS) { offset_south_pole = (short) off; } else if (offsetCount == 1 + ROWS * COLS) { if (off == 0) { allRead = true; } else { System.err.println("Offset is not 0 at southpole "+offsetCount / COLS + " "+offsetCount % COLS + " "+off+" "+c); } } else if (offsetCount > ROWS * COLS) { //Should not occur allRead = false; System.err.println("Unexpected data "+offsetCount / COLS + " "+offsetCount % COLS + " "+off+" "+c); } else { offset[offsetCount / COLS][offsetCount % COLS] = (short) off; } offsetCount++; } } bufRead = is.read(buf); } while (bufRead > 0); return allRead; } private static boolean latOk(double lat) { return lat >= LATITUDE_MIN && lat <= LATITUDE_MAX; } @SuppressWarnings("unused") private static boolean lngOk(double lng) { return lng >= LONGITIDE_MIN && lng <= LONGITIDE_MAX; } private static boolean lngOkGrid(double lng) { return lng >= LONGITIDE_MIN_GRID && lng <= LONGITIDE_MAX_GRID; } private static boolean latIsGridPoint(double lat) { return latOk(lat) && (latIsPole(lat) || lat == LATITUDE_MAX_GRID || lat == LATITUDE_MIN_GRID || lat <= LATITUDE_ROW_FIRST && lat >= LATITUDE_ROW_LAST && lat / LATITUDE_STEP == Math.round(lat / LATITUDE_STEP)); } private static boolean lngIsGridPoint(double lng) { return lngOkGrid(lng) && lng / LONGITIDE_STEP == Math.round(lng / LONGITIDE_STEP); } private static boolean latIsPole(double lat) { return lat == LATITUDE_MAX || lat == LATITUDE_MIN; } private static int latToI(double lat) { if(lat == LATITUDE_MAX_GRID) { return 0; } if(lat == LATITUDE_MIN_GRID) { return ROWS - 1; } else { return (int)((LATITUDE_ROW_FIRST - lat) / LATITUDE_STEP) + 1; } } private static int lngToJ(double lng) { return (int)(lng / LONGITIDE_STEP); } }
jonasoreland/runnerup
app/src/main/org/matthiaszimmermann/location/egm96/Geoid.java
213,343
/* GeoGebra - Dynamic Mathematics for Everyone http://www.geogebra.org This file is part of GeoGebra. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation. */ package org.geogebra.common.kernel.algos; import org.geogebra.common.kernel.Construction; import org.geogebra.common.kernel.StringTemplate; import org.geogebra.common.kernel.arithmetic.ExpressionNode; import org.geogebra.common.kernel.arithmetic.FunctionVariable; import org.geogebra.common.kernel.arithmetic.MyBoolean; import org.geogebra.common.kernel.commands.Commands; import org.geogebra.common.kernel.geos.GeoElement; import org.geogebra.common.kernel.geos.GeoFunction; import org.geogebra.common.kernel.geos.GeoList; import org.geogebra.common.kernel.geos.GeoNumeric; import org.geogebra.common.main.MyError; import org.geogebra.common.util.debug.Log; /** * Take objects from the middle of a list * * @author Michael Borcherds */ public class AlgoKeepIf extends AlgoElement { private GeoList inputList; // input private GeoList outputList; // output private GeoFunction boolFun; // input private int size; /** * @param cons * construction * @param label * label * @param boolFun * boolean filter * @param inputList * list */ public AlgoKeepIf(Construction cons, String label, GeoFunction boolFun, GeoList inputList) { super(cons); this.inputList = inputList; this.boolFun = boolFun; outputList = new GeoList(cons); setInputOutput(); compute(); outputList.setLabel(label); } @Override public Commands getClassName() { return Commands.KeepIf; } @Override protected void setInputOutput() { outputList.setTypeStringForXML(inputList.getTypeStringForXML()); input = new GeoElement[2]; input[0] = boolFun; input[1] = inputList; setOnlyOutput(outputList); setDependencies(); // done by AlgoElement } /** * @return resulting list */ public GeoList getResult() { return outputList; } @Override public final void compute() { size = inputList.size(); if (!inputList.isDefined() || !boolFun.isBooleanFunction()) { outputList.setUndefined(); return; } outputList.setDefined(true); outputList.clear(); if (size == 0) { return; } /* * If val is not numeric, we use the underlying Expression of the * function and plug the list element as variable. Deep copy is needed * so that we can plug the value repeatedly. */ FunctionVariable var = boolFun.getFunction().getFunctionVariable(); try { for (int i = 0; i < size; i++) { GeoElement geo = inputList.get(i); if (geo.isGeoNumeric()) { if (boolFun .evaluateBoolean(((GeoNumeric) geo).getValue())) { outputList.add(geo.copyInternal(cons)); } } else { ExpressionNode ex = boolFun.getFunction().getExpression() .deepCopy(kernel); ex = ex.replace(var, geo.evaluate(StringTemplate.defaultTemplate)) .wrap(); if (((MyBoolean) ex .evaluate(StringTemplate.defaultTemplate)) .getBoolean()) { outputList.add(geo.copyInternal(cons)); } } } } catch (MyError e) { // eg KeepIf[x<3,{1,2,(4,4)}] Log.debug(e); outputList.setUndefined(); return; } } }
geogebra/geogebra
common/src/main/java/org/geogebra/common/kernel/algos/AlgoKeepIf.java
213,345
/* GeoGebra - Dynamic Mathematics for Everyone http://www.geogebra.org This file is part of GeoGebra. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation. */ package org.geogebra.common.kernel.algos; import org.geogebra.common.kernel.Construction; import org.geogebra.common.kernel.commands.Commands; import org.geogebra.common.kernel.geos.GeoBoolean; import org.geogebra.common.kernel.geos.GeoElement; import org.geogebra.common.kernel.geos.GeoList; import org.geogebra.common.main.MyError; import org.geogebra.common.util.debug.Log; /** * Take objects from the middle of a list adapted from AlgoKeepIf * * @author Michael Borcherds */ public class AlgoKeepIf3 extends AlgoElement { private GeoList inputList; // input private GeoList outputList; // output private GeoBoolean bool; // input private GeoElement var; private int size; /** * @param cons * construction * @param label * label * @param bool * boolean filter (dependent on var) * @param var * variable to be substituted * @param inputList * list */ public AlgoKeepIf3(Construction cons, String label, GeoBoolean bool, GeoElement var, GeoList inputList) { super(cons); this.inputList = inputList; this.var = var; this.bool = bool; outputList = new GeoList(cons); setInputOutput(); compute(); outputList.setLabel(label); } @Override public Commands getClassName() { return Commands.KeepIf; } @Override protected void setInputOutput() { outputList.setTypeStringForXML(inputList.getTypeStringForXML()); input = new GeoElement[3]; input[0] = bool; input[1] = var; input[2] = inputList; setOnlyOutput(outputList); setDependencies(); // done by AlgoElement } /** * @return resulting list */ public GeoList getResult() { return outputList; } @Override public final void compute() { size = inputList.size(); if (!inputList.isDefined()) { outputList.setUndefined(); return; } outputList.setDefined(true); outputList.clear(); if (size == 0) { return; } try { for (int i = 0; i < size; i++) { GeoElement geo = inputList.get(i); var.set(geo); this.setStopUpdateCascade(true); var.getAlgoUpdateSet() .updateAllUntil(bool.getParentAlgorithm()); if (bool.getBoolean()) { outputList.add(geo.copyInternal(cons)); } this.setStopUpdateCascade(false); } } catch (MyError e) { // eg KeepIf[x(A)<2,A,{(1,1),(2,2),(3,3),1}] Log.debug(e); outputList.setUndefined(); return; } } }
geogebra/geogebra
common/src/main/java/org/geogebra/common/kernel/algos/AlgoKeepIf3.java
213,346
// © 2022 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html // // Internal static data tables used by ICUResourceBundle.java // WARNING: This file is mechanically generated by the CLDR-to-ICU tool // (see tools/cldr/cldr-to-icu/src/main/java/org/unicode/tool/cldrtoicu/generator/ResourcFallbackCodeGenerator.java). // DO NOT HAND EDIT!!! package com.ibm.icu.impl; import java.util.Collections; import java.util.HashMap; import java.util.Map; class LocaleFallbackData { //====================================================================== // Default script table public static final Map<String, String> DEFAULT_SCRIPT_TABLE = buildDefaultScriptTable(); private static Map<String, String> buildDefaultScriptTable() { Map<String, String> t = new HashMap<>(); t.put("aaf", "Mlym"); t.put("aao", "Arab"); t.put("aat", "Grek"); t.put("ab", "Cyrl"); t.put("abh", "Arab"); t.put("abl", "Rjng"); t.put("abv", "Arab"); t.put("acm", "Arab"); t.put("acq", "Arab"); t.put("acw", "Arab"); t.put("acx", "Arab"); t.put("adf", "Arab"); t.put("adx", "Tibt"); t.put("ady", "Cyrl"); t.put("ae", "Avst"); t.put("aeb", "Arab"); t.put("aec", "Arab"); t.put("aee", "Arab"); t.put("aeq", "Arab"); t.put("afb", "Arab"); t.put("agi", "Deva"); t.put("agj", "Ethi"); t.put("agx", "Cyrl"); t.put("ahg", "Ethi"); t.put("aho", "Ahom"); t.put("ahr", "Deva"); t.put("aib", "Arab"); t.put("aij", "Hebr"); t.put("ain", "Kana"); t.put("aio", "Mymr"); t.put("aiq", "Arab"); t.put("akk", "Xsux"); t.put("akv", "Cyrl"); t.put("alk", "Laoo"); t.put("all", "Mlym"); t.put("alr", "Cyrl"); t.put("alt", "Cyrl"); t.put("alw", "Ethi"); t.put("am", "Ethi"); t.put("ams", "Jpan"); t.put("amw", "Syrc"); t.put("ani", "Cyrl"); t.put("anp", "Deva"); t.put("anr", "Deva"); t.put("anu", "Ethi"); t.put("aot", "Beng"); t.put("apc", "Arab"); t.put("apd", "Arab"); t.put("aph", "Deva"); t.put("aqc", "Cyrl"); t.put("ar", "Arab"); t.put("arc", "Armi"); t.put("arq", "Arab"); t.put("ars", "Arab"); t.put("ary", "Arab"); t.put("arz", "Arab"); t.put("as", "Beng"); t.put("ase", "Sgnw"); t.put("ask", "Arab"); t.put("atn", "Arab"); t.put("atv", "Cyrl"); t.put("auj", "Arab"); t.put("auz", "Arab"); t.put("av", "Cyrl"); t.put("avd", "Arab"); t.put("avl", "Arab"); t.put("awa", "Deva"); t.put("awn", "Ethi"); t.put("axm", "Armn"); t.put("ayh", "Arab"); t.put("ayl", "Arab"); t.put("ayn", "Arab"); t.put("ayp", "Arab"); t.put("az_IQ", "Arab"); t.put("az_IR", "Arab"); t.put("az_RU", "Cyrl"); t.put("azb", "Arab"); t.put("ba", "Cyrl"); t.put("bal", "Arab"); t.put("bap", "Deva"); t.put("bax", "Bamu"); t.put("bbl", "Geor"); t.put("bcq", "Ethi"); t.put("bdv", "Orya"); t.put("bdz", "Arab"); t.put("be", "Cyrl"); t.put("bee", "Deva"); t.put("bej", "Arab"); t.put("bfb", "Deva"); t.put("bfq", "Taml"); t.put("bft", "Arab"); t.put("bfu", "Tibt"); t.put("bfw", "Orya"); t.put("bfy", "Deva"); t.put("bfz", "Deva"); t.put("bg", "Cyrl"); t.put("bgc", "Deva"); t.put("bgd", "Deva"); t.put("bgn", "Arab"); t.put("bgp", "Arab"); t.put("bgq", "Deva"); t.put("bgw", "Deva"); t.put("bgx", "Grek"); t.put("bha", "Deva"); t.put("bhb", "Deva"); t.put("bhd", "Deva"); t.put("bhe", "Arab"); t.put("bhh", "Cyrl"); t.put("bhi", "Deva"); t.put("bhj", "Deva"); t.put("bhm", "Arab"); t.put("bhn", "Syrc"); t.put("bho", "Deva"); t.put("bht", "Takr"); t.put("bhu", "Deva"); t.put("biy", "Deva"); t.put("bjf", "Syrc"); t.put("bjj", "Deva"); t.put("bjm", "Arab"); t.put("blk", "Mymr"); t.put("blt", "Tavt"); t.put("bmj", "Deva"); t.put("bn", "Beng"); t.put("bns", "Deva"); t.put("bo", "Tibt"); t.put("bph", "Cyrl"); t.put("bpx", "Deva"); t.put("bpy", "Beng"); t.put("bqi", "Arab"); t.put("bra", "Deva"); t.put("brb", "Khmr"); t.put("brd", "Deva"); t.put("brh", "Arab"); t.put("brk", "Arab"); t.put("brv", "Laoo"); t.put("brx", "Deva"); t.put("bsh", "Arab"); t.put("bsk", "Arab"); t.put("bsq", "Bass"); t.put("bst", "Ethi"); t.put("btd", "Batk"); t.put("btm", "Batk"); t.put("btv", "Deva"); t.put("bua", "Cyrl"); t.put("bwe", "Mymr"); t.put("bxm", "Cyrl"); t.put("bxu", "Mong"); t.put("byh", "Deva"); t.put("byn", "Ethi"); t.put("byw", "Deva"); t.put("bzi", "Thai"); t.put("cbn", "Thai"); t.put("ccp", "Cakm"); t.put("cde", "Telu"); t.put("cdh", "Deva"); t.put("cdi", "Gujr"); t.put("cdj", "Deva"); t.put("cdm", "Deva"); t.put("cdo", "Hans"); t.put("cdz", "Beng"); t.put("ce", "Cyrl"); t.put("cgk", "Tibt"); t.put("chg", "Arab"); t.put("chm", "Cyrl"); t.put("chr", "Cher"); t.put("chx", "Deva"); t.put("cih", "Deva"); t.put("cja", "Arab"); t.put("cji", "Cyrl"); t.put("cjm", "Cham"); t.put("cjy", "Hans"); t.put("ckb", "Arab"); t.put("ckt", "Cyrl"); t.put("clh", "Arab"); t.put("clw", "Cyrl"); t.put("cmg", "Soyo"); t.put("cna", "Tibt"); t.put("cnp", "Hans"); t.put("cog", "Thai"); t.put("cop", "Copt"); t.put("cpg", "Grek"); t.put("cr", "Cans"); t.put("crh", "Cyrl"); t.put("crj", "Cans"); t.put("crk", "Cans"); t.put("crl", "Cans"); t.put("crm", "Cans"); t.put("csh", "Mymr"); t.put("csp", "Hans"); t.put("csw", "Cans"); t.put("ctd", "Pauc"); t.put("ctg", "Beng"); t.put("ctn", "Deva"); t.put("ctt", "Taml"); t.put("cu", "Cyrl"); t.put("cuu", "Lana"); t.put("cv", "Cyrl"); t.put("czh", "Hans"); t.put("czk", "Hebr"); t.put("daq", "Deva"); t.put("dar", "Cyrl"); t.put("dcc", "Arab"); t.put("ddo", "Cyrl"); t.put("def", "Arab"); t.put("deh", "Arab"); t.put("der", "Beng"); t.put("dhi", "Deva"); t.put("dhn", "Gujr"); t.put("dho", "Deva"); t.put("dhw", "Deva"); t.put("dka", "Tibt"); t.put("dlg", "Cyrl"); t.put("dmf", "Medf"); t.put("dmk", "Arab"); t.put("dml", "Arab"); t.put("dng", "Cyrl"); t.put("dnu", "Mymr"); t.put("dnv", "Mymr"); t.put("doi", "Deva"); t.put("dox", "Ethi"); t.put("dre", "Tibt"); t.put("drq", "Deva"); t.put("drs", "Ethi"); t.put("dry", "Deva"); t.put("dso", "Orya"); t.put("dty", "Deva"); t.put("dub", "Gujr"); t.put("duh", "Deva"); t.put("dus", "Deva"); t.put("dv", "Thaa"); t.put("dwk", "Orya"); t.put("dwz", "Deva"); t.put("dz", "Tibt"); t.put("dzl", "Tibt"); t.put("ecr", "Grek"); t.put("ecy", "Cprt"); t.put("egy", "Egyp"); t.put("eky", "Kali"); t.put("el", "Grek"); t.put("emg", "Deva"); t.put("emu", "Deva"); t.put("enf", "Cyrl"); t.put("enh", "Cyrl"); t.put("era", "Taml"); t.put("esg", "Gonm"); t.put("esh", "Arab"); t.put("ett", "Ital"); t.put("eve", "Cyrl"); t.put("evn", "Cyrl"); t.put("fa", "Arab"); t.put("fay", "Arab"); t.put("faz", "Arab"); t.put("fia", "Arab"); t.put("fmu", "Deva"); t.put("fub", "Arab"); t.put("gan", "Hans"); t.put("gaq", "Orya"); t.put("gas", "Gujr"); t.put("gau", "Telu"); t.put("gbj", "Orya"); t.put("gbk", "Deva"); t.put("gbl", "Gujr"); t.put("gbm", "Deva"); t.put("gbz", "Arab"); t.put("gdb", "Orya"); t.put("gdo", "Cyrl"); t.put("gdx", "Deva"); t.put("gez", "Ethi"); t.put("ggg", "Arab"); t.put("gha", "Arab"); t.put("ghe", "Deva"); t.put("ghr", "Arab"); t.put("ght", "Tibt"); t.put("gig", "Arab"); t.put("gin", "Cyrl"); t.put("gjk", "Arab"); t.put("gju", "Arab"); t.put("gld", "Cyrl"); t.put("glh", "Arab"); t.put("glk", "Arab"); t.put("gmv", "Ethi"); t.put("gmy", "Linb"); t.put("goe", "Tibt"); t.put("gof", "Ethi"); t.put("gok", "Deva"); t.put("gom", "Deva"); t.put("gon", "Telu"); t.put("got", "Goth"); t.put("gra", "Deva"); t.put("grc", "Cprt"); t.put("grt", "Beng"); t.put("gru", "Ethi"); t.put("gu", "Gujr"); t.put("gvr", "Deva"); t.put("gwc", "Arab"); t.put("gwf", "Arab"); t.put("gwt", "Arab"); t.put("gyo", "Deva"); t.put("gzi", "Arab"); t.put("ha_CM", "Arab"); t.put("ha_SD", "Arab"); t.put("hac", "Arab"); t.put("hak", "Hans"); t.put("har", "Ethi"); t.put("haz", "Arab"); t.put("hbo", "Hebr"); t.put("hdy", "Ethi"); t.put("he", "Hebr"); t.put("hi", "Deva"); t.put("hii", "Takr"); t.put("hit", "Xsux"); t.put("hkh", "Arab"); t.put("hlb", "Deva"); t.put("hlu", "Hluw"); t.put("hmd", "Plrd"); t.put("hmj", "Bopo"); t.put("hmq", "Bopo"); t.put("hnd", "Arab"); t.put("hne", "Deva"); t.put("hnj", "Hmnp"); t.put("hnj_AU", "Laoo"); t.put("hnj_CN", "Laoo"); t.put("hnj_FR", "Laoo"); t.put("hnj_GF", "Laoo"); t.put("hnj_LA", "Laoo"); t.put("hnj_MM", "Laoo"); t.put("hnj_SR", "Laoo"); t.put("hnj_TH", "Laoo"); t.put("hnj_VN", "Laoo"); t.put("hno", "Arab"); t.put("hoc", "Deva"); t.put("hoh", "Arab"); t.put("hoj", "Deva"); t.put("how", "Hani"); t.put("hoy", "Deva"); t.put("hpo", "Mymr"); t.put("hrt", "Syrc"); t.put("hrz", "Arab"); t.put("hsn", "Hans"); t.put("hss", "Arab"); t.put("htx", "Xsux"); t.put("hut", "Deva"); t.put("huy", "Hebr"); t.put("huz", "Cyrl"); t.put("hy", "Armn"); t.put("hyw", "Armn"); t.put("ii", "Yiii"); t.put("imy", "Lyci"); t.put("inh", "Cyrl"); t.put("int", "Mymr"); t.put("ior", "Ethi"); t.put("iru", "Taml"); t.put("isk", "Arab"); t.put("itk", "Hebr"); t.put("itl", "Cyrl"); t.put("iu", "Cans"); t.put("iw", "Hebr"); t.put("ja", "Jpan"); t.put("jad", "Arab"); t.put("jat", "Arab"); t.put("jbe", "Hebr"); t.put("jbn", "Arab"); t.put("jct", "Cyrl"); t.put("jda", "Tibt"); t.put("jdg", "Arab"); t.put("jdt", "Cyrl"); t.put("jee", "Deva"); t.put("jge", "Geor"); t.put("ji", "Hebr"); t.put("jje", "Hang"); t.put("jkm", "Mymr"); t.put("jml", "Deva"); t.put("jna", "Takr"); t.put("jnd", "Arab"); t.put("jnl", "Deva"); t.put("jns", "Deva"); t.put("jog", "Arab"); t.put("jpa", "Hebr"); t.put("jpr", "Hebr"); t.put("jrb", "Hebr"); t.put("jrb_MA", "Arab"); t.put("jul", "Deva"); t.put("jun", "Orya"); t.put("juy", "Orya"); t.put("jya", "Tibt"); t.put("jye", "Hebr"); t.put("ka", "Geor"); t.put("kaa", "Cyrl"); t.put("kap", "Cyrl"); t.put("kaw", "Kawi"); t.put("kbd", "Cyrl"); t.put("kbu", "Arab"); t.put("kby", "Arab"); t.put("kca", "Cyrl"); t.put("kdq", "Beng"); t.put("kdt", "Thai"); t.put("ket", "Cyrl"); t.put("kex", "Deva"); t.put("key", "Telu"); t.put("kfa", "Knda"); t.put("kfb", "Deva"); t.put("kfc", "Telu"); t.put("kfd", "Knda"); t.put("kfe", "Taml"); t.put("kfh", "Mlym"); t.put("kfi", "Taml"); t.put("kfk", "Deva"); t.put("kfm", "Arab"); t.put("kfp", "Deva"); t.put("kfq", "Deva"); t.put("kfr", "Deva"); t.put("kfs", "Deva"); t.put("kfx", "Deva"); t.put("kfy", "Deva"); t.put("kgj", "Deva"); t.put("kgy", "Deva"); t.put("khb", "Talu"); t.put("khf", "Thai"); t.put("khg", "Tibt"); t.put("khn", "Deva"); t.put("kht", "Mymr"); t.put("khv", "Cyrl"); t.put("khw", "Arab"); t.put("kif", "Deva"); t.put("kim", "Cyrl"); t.put("kip", "Deva"); t.put("kjg", "Laoo"); t.put("kjh", "Cyrl"); t.put("kjl", "Deva"); t.put("kjo", "Deva"); t.put("kjp", "Mymr"); t.put("kjt", "Thai"); t.put("kk", "Cyrl"); t.put("kk_AF", "Arab"); t.put("kk_CN", "Arab"); t.put("kk_IR", "Arab"); t.put("kk_MN", "Arab"); t.put("kkf", "Tibt"); t.put("kkh", "Lana"); t.put("kkt", "Deva"); t.put("kle", "Deva"); t.put("klj", "Arab"); t.put("klr", "Deva"); t.put("km", "Khmr"); t.put("kmj", "Deva"); t.put("kmz", "Arab"); t.put("kn", "Knda"); t.put("ko", "Kore"); t.put("koi", "Cyrl"); t.put("kok", "Deva"); t.put("kpt", "Cyrl"); t.put("kpy", "Cyrl"); t.put("kqd", "Syrc"); t.put("kqy", "Ethi"); t.put("kra", "Deva"); t.put("krc", "Cyrl"); t.put("krk", "Cyrl"); t.put("krr", "Khmr"); t.put("kru", "Deva"); t.put("krv", "Khmr"); t.put("ks", "Arab"); t.put("ksu", "Mymr"); t.put("ksw", "Mymr"); t.put("ksz", "Deva"); t.put("ktb", "Ethi"); t.put("ktl", "Arab"); t.put("ktp", "Plrd"); t.put("ku_LB", "Arab"); t.put("kuf", "Laoo"); t.put("kum", "Cyrl"); t.put("kv", "Cyrl"); t.put("kva", "Cyrl"); t.put("kvq", "Mymr"); t.put("kvt", "Mymr"); t.put("kvx", "Arab"); t.put("kvy", "Kali"); t.put("kxf", "Mymr"); t.put("kxk", "Mymr"); t.put("kxm", "Thai"); t.put("kxp", "Arab"); t.put("ky", "Cyrl"); t.put("ky_CN", "Arab"); t.put("kyu", "Kali"); t.put("kyv", "Deva"); t.put("kyw", "Deva"); t.put("lab", "Lina"); t.put("lad", "Hebr"); t.put("lae", "Deva"); t.put("lah", "Arab"); t.put("lbc", "Lisu"); t.put("lbe", "Cyrl"); t.put("lbf", "Deva"); t.put("lbj", "Tibt"); t.put("lbm", "Deva"); t.put("lbo", "Laoo"); t.put("lbr", "Deva"); t.put("lcp", "Thai"); t.put("lep", "Lepc"); t.put("lez", "Cyrl"); t.put("lhm", "Deva"); t.put("lhs", "Syrc"); t.put("lif", "Deva"); t.put("lis", "Lisu"); t.put("lkh", "Tibt"); t.put("lki", "Arab"); t.put("lmh", "Deva"); t.put("lmn", "Telu"); t.put("lo", "Laoo"); t.put("loy", "Deva"); t.put("lpo", "Plrd"); t.put("lrc", "Arab"); t.put("lrk", "Arab"); t.put("lrl", "Arab"); t.put("lsa", "Arab"); t.put("lsd", "Hebr"); t.put("lss", "Arab"); t.put("luk", "Tibt"); t.put("luu", "Deva"); t.put("luv", "Arab"); t.put("luz", "Arab"); t.put("lwl", "Thai"); t.put("lwm", "Thai"); t.put("lya", "Tibt"); t.put("lzh", "Hans"); t.put("mag", "Deva"); t.put("mai", "Deva"); t.put("man_GN", "Nkoo"); t.put("mby", "Arab"); t.put("mde", "Arab"); t.put("mdf", "Cyrl"); t.put("mdx", "Ethi"); t.put("mdy", "Ethi"); t.put("mfa", "Arab"); t.put("mfi", "Arab"); t.put("mgp", "Deva"); t.put("mhj", "Arab"); t.put("mid", "Mand"); t.put("mjl", "Deva"); t.put("mjq", "Mlym"); t.put("mjr", "Mlym"); t.put("mjt", "Deva"); t.put("mju", "Telu"); t.put("mjv", "Mlym"); t.put("mjz", "Deva"); t.put("mk", "Cyrl"); t.put("mkb", "Deva"); t.put("mke", "Deva"); t.put("mki", "Arab"); t.put("mkm", "Thai"); t.put("ml", "Mlym"); t.put("mlf", "Thai"); t.put("mn", "Cyrl"); t.put("mn_CN", "Mong"); t.put("mni", "Beng"); t.put("mnj", "Arab"); t.put("mns", "Cyrl"); t.put("mnw", "Mymr"); t.put("mpz", "Thai"); t.put("mr", "Deva"); t.put("mra", "Thai"); t.put("mrd", "Deva"); t.put("mrj", "Cyrl"); t.put("mro", "Mroo"); t.put("mrr", "Deva"); t.put("ms_CC", "Arab"); t.put("mtm", "Cyrl"); t.put("mtr", "Deva"); t.put("mud", "Cyrl"); t.put("muk", "Tibt"); t.put("mut", "Deva"); t.put("muv", "Taml"); t.put("muz", "Ethi"); t.put("mvf", "Mong"); t.put("mvy", "Arab"); t.put("mvz", "Ethi"); t.put("mwr", "Deva"); t.put("mwt", "Mymr"); t.put("mww", "Hmnp"); t.put("my", "Mymr"); t.put("mym", "Ethi"); t.put("myv", "Cyrl"); t.put("myz", "Mand"); t.put("mzn", "Arab"); t.put("nan", "Hans"); t.put("nao", "Deva"); t.put("ncd", "Deva"); t.put("ncq", "Laoo"); t.put("ndf", "Cyrl"); t.put("ne", "Deva"); t.put("neg", "Cyrl"); t.put("neh", "Tibt"); t.put("nei", "Xsux"); t.put("new", "Deva"); t.put("ngt", "Laoo"); t.put("nio", "Cyrl"); t.put("nit", "Telu"); t.put("niv", "Cyrl"); t.put("nli", "Arab"); t.put("nlm", "Arab"); t.put("nlx", "Deva"); t.put("nmm", "Deva"); t.put("nnp", "Wcho"); t.put("nod", "Lana"); t.put("noe", "Deva"); t.put("nog", "Cyrl"); t.put("noi", "Deva"); t.put("non", "Runr"); t.put("nos", "Yiii"); t.put("npb", "Tibt"); t.put("nqo", "Nkoo"); t.put("nsd", "Yiii"); t.put("nsf", "Yiii"); t.put("nsk", "Cans"); t.put("nst", "Tnsa"); t.put("nsv", "Yiii"); t.put("nty", "Yiii"); t.put("ntz", "Arab"); t.put("nwc", "Newa"); t.put("nwx", "Deva"); t.put("nyl", "Thai"); t.put("nyq", "Arab"); t.put("oaa", "Cyrl"); t.put("oac", "Cyrl"); t.put("oar", "Syrc"); t.put("oav", "Geor"); t.put("obm", "Phnx"); t.put("obr", "Mymr"); t.put("odk", "Arab"); t.put("oht", "Xsux"); t.put("oj", "Cans"); t.put("ojs", "Cans"); t.put("okm", "Hang"); t.put("oko", "Hani"); t.put("okz", "Khmr"); t.put("ola", "Deva"); t.put("ole", "Tibt"); t.put("omk", "Cyrl"); t.put("omp", "Mtei"); t.put("omr", "Modi"); t.put("oon", "Deva"); t.put("or", "Orya"); t.put("ort", "Telu"); t.put("oru", "Arab"); t.put("orv", "Cyrl"); t.put("os", "Cyrl"); t.put("osa", "Osge"); t.put("osc", "Ital"); t.put("osi", "Java"); t.put("ota", "Arab"); t.put("otb", "Tibt"); t.put("otk", "Orkh"); t.put("oty", "Gran"); t.put("pa", "Guru"); t.put("pa_PK", "Arab"); t.put("pal", "Phli"); t.put("paq", "Cyrl"); t.put("pbt", "Arab"); t.put("pcb", "Khmr"); t.put("pce", "Mymr"); t.put("pcf", "Mlym"); t.put("pcg", "Mlym"); t.put("pch", "Deva"); t.put("pci", "Deva"); t.put("pcj", "Telu"); t.put("peg", "Orya"); t.put("peo", "Xpeo"); t.put("pgd", "Khar"); t.put("pgg", "Deva"); t.put("pgl", "Ogam"); t.put("pgn", "Ital"); t.put("phd", "Deva"); t.put("phk", "Mymr"); t.put("phl", "Arab"); t.put("phn", "Phnx"); t.put("pho", "Laoo"); t.put("phr", "Arab"); t.put("pht", "Thai"); t.put("phv", "Arab"); t.put("phw", "Deva"); t.put("pi", "Sinh"); t.put("pka", "Brah"); t.put("pkr", "Mlym"); t.put("plk", "Arab"); t.put("pll", "Mymr"); t.put("pmh", "Brah"); t.put("pnt", "Grek"); t.put("pra", "Khar"); t.put("prc", "Arab"); t.put("prd", "Arab"); t.put("prt", "Thai"); t.put("prx", "Arab"); t.put("ps", "Arab"); t.put("psh", "Arab"); t.put("psi", "Arab"); t.put("pst", "Arab"); t.put("pum", "Deva"); t.put("pwo", "Mymr"); t.put("pwr", "Deva"); t.put("pww", "Thai"); t.put("pyx", "Mymr"); t.put("qxq", "Arab"); t.put("raa", "Deva"); t.put("rab", "Deva"); t.put("raf", "Deva"); t.put("rah", "Beng"); t.put("raj", "Deva"); t.put("rav", "Deva"); t.put("rbb", "Mymr"); t.put("rdb", "Arab"); t.put("rei", "Orya"); t.put("rhg", "Rohg"); t.put("rji", "Deva"); t.put("rjs", "Deva"); t.put("rka", "Khmr"); t.put("rki", "Mymr"); t.put("rkt", "Beng"); t.put("rmi", "Armn"); t.put("rmt", "Arab"); t.put("rmz", "Mymr"); t.put("rom_BG", "Cyrl"); t.put("rsk", "Cyrl"); t.put("rtw", "Deva"); t.put("ru", "Cyrl"); t.put("rue", "Cyrl"); t.put("rut", "Cyrl"); t.put("rwr", "Deva"); t.put("ryu", "Kana"); t.put("sa", "Deva"); t.put("sah", "Cyrl"); t.put("sam", "Samr"); t.put("sat", "Olck"); t.put("saz", "Saur"); t.put("sbn", "Arab"); t.put("sbu", "Tibt"); t.put("sck", "Deva"); t.put("scl", "Arab"); t.put("scl_IN", "Arab"); t.put("scp", "Deva"); t.put("sct", "Laoo"); t.put("scu", "Takr"); t.put("scx", "Grek"); t.put("sd", "Arab"); t.put("sd_IN", "Deva"); t.put("sdb", "Arab"); t.put("sdf", "Arab"); t.put("sdg", "Arab"); t.put("sdh", "Arab"); t.put("sds", "Arab"); t.put("sel", "Cyrl"); t.put("sfm", "Plrd"); t.put("sga", "Ogam"); t.put("sgh", "Cyrl"); t.put("sgj", "Deva"); t.put("sgr", "Arab"); t.put("sgt", "Tibt"); t.put("sgw", "Ethi"); t.put("sgy", "Arab"); t.put("shd", "Arab"); t.put("shi", "Tfng"); t.put("shm", "Arab"); t.put("shn", "Mymr"); t.put("shu", "Arab"); t.put("shv", "Arab"); t.put("si", "Sinh"); t.put("sia", "Cyrl"); t.put("sip", "Tibt"); t.put("siy", "Arab"); t.put("siz", "Arab"); t.put("sjd", "Cyrl"); t.put("sjp", "Deva"); t.put("sjt", "Cyrl"); t.put("skb", "Thai"); t.put("skj", "Deva"); t.put("skr", "Arab"); t.put("smh", "Yiii"); t.put("smp", "Samr"); t.put("smu", "Khmr"); t.put("smy", "Arab"); t.put("soa", "Tavt"); t.put("sog", "Sogd"); t.put("soi", "Deva"); t.put("sou", "Thai"); t.put("spt", "Tibt"); t.put("spv", "Orya"); t.put("sqo", "Arab"); t.put("sqq", "Laoo"); t.put("sqt", "Arab"); t.put("sr", "Cyrl"); t.put("srb", "Sora"); t.put("srh", "Arab"); t.put("srx", "Deva"); t.put("srz", "Arab"); t.put("ssh", "Arab"); t.put("sss", "Laoo"); t.put("sts", "Arab"); t.put("stv", "Ethi"); t.put("sty", "Cyrl"); t.put("suz", "Deva"); t.put("sva", "Geor"); t.put("swb", "Arab"); t.put("swi", "Hani"); t.put("swv", "Deva"); t.put("syc", "Syrc"); t.put("syl", "Beng"); t.put("syn", "Syrc"); t.put("syr", "Syrc"); t.put("syw", "Deva"); t.put("ta", "Taml"); t.put("tab", "Cyrl"); t.put("taj", "Deva"); t.put("tbk", "Tagb"); t.put("tcn", "Tibt"); t.put("tco", "Mymr"); t.put("tcx", "Taml"); t.put("tcy", "Knda"); t.put("tda", "Tfng"); t.put("tdb", "Deva"); t.put("tdd", "Tale"); t.put("tdg", "Deva"); t.put("tdh", "Deva"); t.put("te", "Telu"); t.put("tes", "Java"); t.put("tg", "Cyrl"); t.put("tg_PK", "Arab"); t.put("tge", "Deva"); t.put("tgf", "Tibt"); t.put("th", "Thai"); t.put("the", "Deva"); t.put("thf", "Deva"); t.put("thi", "Tale"); t.put("thl", "Deva"); t.put("thm", "Thai"); t.put("thq", "Deva"); t.put("thr", "Deva"); t.put("ths", "Deva"); t.put("ti", "Ethi"); t.put("tig", "Ethi"); t.put("tij", "Deva"); t.put("tin", "Cyrl"); t.put("tjl", "Mymr"); t.put("tjo", "Arab"); t.put("tkb", "Deva"); t.put("tks", "Arab"); t.put("tkt", "Deva"); t.put("tmr", "Syrc"); t.put("tnv", "Cakm"); t.put("tov", "Arab"); t.put("tpu", "Khmr"); t.put("tra", "Arab"); t.put("trg", "Hebr"); t.put("trm", "Arab"); t.put("trw", "Arab"); t.put("tsd", "Grek"); t.put("tsj", "Tibt"); t.put("tt", "Cyrl"); t.put("tth", "Laoo"); t.put("tto", "Laoo"); t.put("tts", "Thai"); t.put("tvn", "Mymr"); t.put("twm", "Deva"); t.put("txg", "Tang"); t.put("txo", "Toto"); t.put("tyr", "Tavt"); t.put("tyv", "Cyrl"); t.put("ude", "Cyrl"); t.put("udg", "Mlym"); t.put("udi", "Aghb"); t.put("udm", "Cyrl"); t.put("ug", "Arab"); t.put("ug_KZ", "Cyrl"); t.put("ug_MN", "Cyrl"); t.put("uga", "Ugar"); t.put("ugh", "Cyrl"); t.put("ugo", "Thai"); t.put("uk", "Cyrl"); t.put("uki", "Orya"); t.put("ulc", "Cyrl"); t.put("unr", "Beng"); t.put("unr_NP", "Deva"); t.put("unx", "Beng"); t.put("ur", "Arab"); t.put("urk", "Thai"); t.put("ush", "Arab"); t.put("uum", "Grek"); t.put("uz_AF", "Arab"); t.put("uz_CN", "Cyrl"); t.put("uzs", "Arab"); t.put("vaa", "Taml"); t.put("vaf", "Arab"); t.put("vah", "Deva"); t.put("vai", "Vaii"); t.put("vas", "Deva"); t.put("vav", "Deva"); t.put("vay", "Deva"); t.put("vgr", "Arab"); t.put("vmd", "Knda"); t.put("vmh", "Arab"); t.put("wal", "Ethi"); t.put("wbk", "Arab"); t.put("wbq", "Telu"); t.put("wbr", "Deva"); t.put("wlo", "Arab"); t.put("wme", "Deva"); t.put("wne", "Arab"); t.put("wni", "Arab"); t.put("wsg", "Gong"); t.put("wsv", "Arab"); t.put("wtm", "Deva"); t.put("wuu", "Hans"); t.put("xal", "Cyrl"); t.put("xan", "Ethi"); t.put("xas", "Cyrl"); t.put("xco", "Chrs"); t.put("xcr", "Cari"); t.put("xdq", "Cyrl"); t.put("xhe", "Arab"); t.put("xhm", "Khmr"); t.put("xis", "Orya"); t.put("xka", "Arab"); t.put("xkc", "Arab"); t.put("xkj", "Arab"); t.put("xkp", "Arab"); t.put("xlc", "Lyci"); t.put("xld", "Lydi"); t.put("xly", "Elym"); t.put("xmf", "Geor"); t.put("xmn", "Mani"); t.put("xmr", "Merc"); t.put("xna", "Narb"); t.put("xnr", "Deva"); t.put("xpg", "Grek"); t.put("xpi", "Ogam"); t.put("xpm", "Cyrl"); t.put("xpr", "Prti"); t.put("xrm", "Cyrl"); t.put("xrn", "Cyrl"); t.put("xsa", "Sarb"); t.put("xsr", "Deva"); t.put("xub", "Taml"); t.put("xuj", "Taml"); t.put("xve", "Ital"); t.put("xvi", "Arab"); t.put("xwo", "Cyrl"); t.put("xzh", "Marc"); t.put("yai", "Cyrl"); t.put("ybh", "Deva"); t.put("ybi", "Deva"); t.put("ydg", "Arab"); t.put("yea", "Mlym"); t.put("yej", "Grek"); t.put("yeu", "Telu"); t.put("ygp", "Plrd"); t.put("yhd", "Hebr"); t.put("yi", "Hebr"); t.put("yig", "Yiii"); t.put("yih", "Hebr"); t.put("yiv", "Yiii"); t.put("ykg", "Cyrl"); t.put("yna", "Plrd"); t.put("ynk", "Cyrl"); t.put("yoi", "Jpan"); t.put("yoy", "Thai"); t.put("yrk", "Cyrl"); t.put("ysd", "Yiii"); t.put("ysn", "Yiii"); t.put("ysp", "Yiii"); t.put("ysr", "Cyrl"); t.put("ysy", "Plrd"); t.put("yud", "Hebr"); t.put("yue", "Hant"); t.put("yue_CN", "Hans"); t.put("yug", "Cyrl"); t.put("yux", "Cyrl"); t.put("ywq", "Plrd"); t.put("ywu", "Plrd"); t.put("zau", "Tibt"); t.put("zba", "Arab"); t.put("zch", "Hani"); t.put("zdj", "Arab"); t.put("zeh", "Hani"); t.put("zen", "Tfng"); t.put("zgb", "Hani"); t.put("zgh", "Tfng"); t.put("zgm", "Hani"); t.put("zgn", "Hani"); t.put("zh", "Hans"); t.put("zh_AU", "Hant"); t.put("zh_BN", "Hant"); t.put("zh_GB", "Hant"); t.put("zh_GF", "Hant"); t.put("zh_HK", "Hant"); t.put("zh_ID", "Hant"); t.put("zh_MO", "Hant"); t.put("zh_PA", "Hant"); t.put("zh_PF", "Hant"); t.put("zh_PH", "Hant"); t.put("zh_SR", "Hant"); t.put("zh_TH", "Hant"); t.put("zh_TW", "Hant"); t.put("zh_US", "Hant"); t.put("zh_VN", "Hant"); t.put("zhd", "Hani"); t.put("zhx", "Nshu"); t.put("zko", "Cyrl"); t.put("zkt", "Kits"); t.put("zkz", "Cyrl"); t.put("zlj", "Hani"); t.put("zln", "Hani"); t.put("zlq", "Hani"); t.put("zqe", "Hani"); t.put("zrp", "Hebr"); t.put("zum", "Arab"); t.put("zyg", "Hani"); t.put("zyn", "Hani"); t.put("zzj", "Hani"); return Collections.unmodifiableMap(t); } //====================================================================== // Parent locale table public static final Map<String, String> PARENT_LOCALE_TABLE = buildParentLocaleTable(); private static Map<String, String> buildParentLocaleTable() { Map<String, String> t = new HashMap<>(); t.put("az_Arab", "root"); t.put("az_Cyrl", "root"); t.put("bal_Latn", "root"); t.put("blt_Latn", "root"); t.put("bm_Nkoo", "root"); t.put("bs_Cyrl", "root"); t.put("byn_Latn", "root"); t.put("cu_Glag", "root"); t.put("dje_Arab", "root"); t.put("dyo_Arab", "root"); t.put("en_150", "en_001"); t.put("en_AG", "en_001"); t.put("en_AI", "en_001"); t.put("en_AT", "en_150"); t.put("en_AU", "en_001"); t.put("en_BB", "en_001"); t.put("en_BE", "en_150"); t.put("en_BM", "en_001"); t.put("en_BS", "en_001"); t.put("en_BW", "en_001"); t.put("en_BZ", "en_001"); t.put("en_CC", "en_001"); t.put("en_CH", "en_150"); t.put("en_CK", "en_001"); t.put("en_CM", "en_001"); t.put("en_CX", "en_001"); t.put("en_CY", "en_001"); t.put("en_DE", "en_150"); t.put("en_DG", "en_001"); t.put("en_DK", "en_150"); t.put("en_DM", "en_001"); t.put("en_Dsrt", "root"); t.put("en_ER", "en_001"); t.put("en_FI", "en_150"); t.put("en_FJ", "en_001"); t.put("en_FK", "en_001"); t.put("en_FM", "en_001"); t.put("en_GB", "en_001"); t.put("en_GD", "en_001"); t.put("en_GG", "en_001"); t.put("en_GH", "en_001"); t.put("en_GI", "en_001"); t.put("en_GM", "en_001"); t.put("en_GY", "en_001"); t.put("en_HK", "en_001"); t.put("en_ID", "en_001"); t.put("en_IE", "en_001"); t.put("en_IL", "en_001"); t.put("en_IM", "en_001"); t.put("en_IN", "en_001"); t.put("en_IO", "en_001"); t.put("en_JE", "en_001"); t.put("en_JM", "en_001"); t.put("en_KE", "en_001"); t.put("en_KI", "en_001"); t.put("en_KN", "en_001"); t.put("en_KY", "en_001"); t.put("en_LC", "en_001"); t.put("en_LR", "en_001"); t.put("en_LS", "en_001"); t.put("en_MG", "en_001"); t.put("en_MO", "en_001"); t.put("en_MS", "en_001"); t.put("en_MT", "en_001"); t.put("en_MU", "en_001"); t.put("en_MV", "en_001"); t.put("en_MW", "en_001"); t.put("en_MY", "en_001"); t.put("en_NA", "en_001"); t.put("en_NF", "en_001"); t.put("en_NG", "en_001"); t.put("en_NL", "en_150"); t.put("en_NR", "en_001"); t.put("en_NU", "en_001"); t.put("en_NZ", "en_001"); t.put("en_PG", "en_001"); t.put("en_PK", "en_001"); t.put("en_PN", "en_001"); t.put("en_PW", "en_001"); t.put("en_RW", "en_001"); t.put("en_SB", "en_001"); t.put("en_SC", "en_001"); t.put("en_SD", "en_001"); t.put("en_SE", "en_150"); t.put("en_SG", "en_001"); t.put("en_SH", "en_001"); t.put("en_SI", "en_150"); t.put("en_SL", "en_001"); t.put("en_SS", "en_001"); t.put("en_SX", "en_001"); t.put("en_SZ", "en_001"); t.put("en_Shaw", "root"); t.put("en_TC", "en_001"); t.put("en_TK", "en_001"); t.put("en_TO", "en_001"); t.put("en_TT", "en_001"); t.put("en_TV", "en_001"); t.put("en_TZ", "en_001"); t.put("en_UG", "en_001"); t.put("en_VC", "en_001"); t.put("en_VG", "en_001"); t.put("en_VU", "en_001"); t.put("en_WS", "en_001"); t.put("en_ZA", "en_001"); t.put("en_ZM", "en_001"); t.put("en_ZW", "en_001"); t.put("es_AR", "es_419"); t.put("es_BO", "es_419"); t.put("es_BR", "es_419"); t.put("es_BZ", "es_419"); t.put("es_CL", "es_419"); t.put("es_CO", "es_419"); t.put("es_CR", "es_419"); t.put("es_CU", "es_419"); t.put("es_DO", "es_419"); t.put("es_EC", "es_419"); t.put("es_GT", "es_419"); t.put("es_HN", "es_419"); t.put("es_JP", "es_419"); t.put("es_MX", "es_419"); t.put("es_NI", "es_419"); t.put("es_PA", "es_419"); t.put("es_PE", "es_419"); t.put("es_PR", "es_419"); t.put("es_PY", "es_419"); t.put("es_SV", "es_419"); t.put("es_US", "es_419"); t.put("es_UY", "es_419"); t.put("es_VE", "es_419"); t.put("ff_Adlm", "root"); t.put("ff_Arab", "root"); t.put("ha_Arab", "root"); t.put("hi_Latn", "en_IN"); t.put("ht", "fr_HT"); t.put("iu_Latn", "root"); t.put("kk_Arab", "root"); t.put("ks_Deva", "root"); t.put("ku_Arab", "root"); t.put("kxv_Deva", "root"); t.put("kxv_Orya", "root"); t.put("kxv_Telu", "root"); t.put("ky_Arab", "root"); t.put("ky_Latn", "root"); t.put("ml_Arab", "root"); t.put("mn_Mong", "root"); t.put("mni_Mtei", "root"); t.put("ms_Arab", "root"); t.put("nb", "no"); t.put("nn", "no"); t.put("no_NO", "no"); t.put("pa_Arab", "root"); t.put("pt_AO", "pt_PT"); t.put("pt_CH", "pt_PT"); t.put("pt_CV", "pt_PT"); t.put("pt_FR", "pt_PT"); t.put("pt_GQ", "pt_PT"); t.put("pt_GW", "pt_PT"); t.put("pt_LU", "pt_PT"); t.put("pt_MO", "pt_PT"); t.put("pt_MZ", "pt_PT"); t.put("pt_ST", "pt_PT"); t.put("pt_TL", "pt_PT"); t.put("sat_Deva", "root"); t.put("sd_Deva", "root"); t.put("sd_Khoj", "root"); t.put("sd_Sind", "root"); t.put("shi_Latn", "root"); t.put("so_Arab", "root"); t.put("sr_Latn", "root"); t.put("sw_Arab", "root"); t.put("tg_Arab", "root"); t.put("ug_Cyrl", "root"); t.put("uz_Arab", "root"); t.put("uz_Cyrl", "root"); t.put("vai_Latn", "root"); t.put("wo_Arab", "root"); t.put("yo_Arab", "root"); t.put("yue_Hans", "root"); t.put("zh_Hant", "root"); t.put("zh_Hant_MO", "zh_Hant_HK"); return Collections.unmodifiableMap(t); } }
unicode-org/icu
icu4j/main/core/src/main/java/com/ibm/icu/impl/LocaleFallbackData.java
213,347
package io.ray.serve.api; import com.google.protobuf.ByteString; import io.ray.api.ActorHandle; import io.ray.api.BaseActorHandle; import io.ray.api.PyActorHandle; import io.ray.api.Ray; import io.ray.api.exception.RayActorException; import io.ray.api.exception.RayTimeoutException; import io.ray.api.function.PyActorMethod; import io.ray.serve.common.Constants; import io.ray.serve.controller.ServeController; import io.ray.serve.deployment.Deployment; import io.ray.serve.deployment.DeploymentRoute; import io.ray.serve.exception.RayServeException; import io.ray.serve.generated.ApplicationStatus; import io.ray.serve.generated.DeploymentArgs; import io.ray.serve.generated.EndpointInfo; import io.ray.serve.generated.StatusOverview; import io.ray.serve.handle.DeploymentHandle; import io.ray.serve.util.CollectionUtil; import io.ray.serve.util.MessageFormatter; import io.ray.serve.util.ServeProtoUtil; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ServeControllerClient { private static final Logger LOGGER = LoggerFactory.getLogger(ServeControllerClient.class); private static long CLIENT_POLLING_INTERVAL_S = 1; private BaseActorHandle controller; // TODO change to PyActorHandle private boolean shutdown; private Map<String, DeploymentHandle> handleCache = new ConcurrentHashMap<>(); private String rootUrl; @SuppressWarnings("unchecked") public ServeControllerClient(BaseActorHandle controller) { this.controller = controller; this.rootUrl = controller instanceof PyActorHandle ? (String) ((PyActorHandle) controller).task(PyActorMethod.of("get_root_url")).remote().get() : ((ActorHandle<ServeController>) controller) .task(ServeController::getRootUrl) .remote() .get(); } /** * Retrieve DeploymentHandle for service deployment to invoke it from Java. * * @param deploymentName A registered service deployment. * @param appName application name * @param missingOk If true, then Serve won't check the deployment is registered. * @return */ @SuppressWarnings("unchecked") public DeploymentHandle getDeploymentHandle( String deploymentName, String appName, boolean missingOk) { String cacheKey = StringUtils.join( new Object[] {deploymentName, appName, missingOk}, Constants.SEPARATOR_HASH); if (handleCache.containsKey(cacheKey)) { return handleCache.get(cacheKey); } Map<String, EndpointInfo> endpoints = null; if (controller instanceof PyActorHandle) { endpoints = ServeProtoUtil.parseEndpointSet( (byte[]) ((PyActorHandle) controller) .task(PyActorMethod.of(Constants.CONTROLLER_GET_ALL_ENDPOINTS_METHOD)) .remote() .get()); } else { LOGGER.warn("Client currently only supports the Python controller."); endpoints = ServeProtoUtil.parseEndpointSet( ((ActorHandle<? extends ServeController>) controller) .task(ServeController::getAllEndpoints) .remote() .get()); } if (!missingOk && (endpoints == null || !endpoints.containsKey(deploymentName))) { throw new RayServeException( MessageFormatter.format("Deployment {} does not exist.", deploymentName)); } DeploymentHandle handle = new DeploymentHandle(deploymentName, appName); handleCache.put(cacheKey, handle); return handle; } /** * Completely shut down the connected Serve instance. * * <p>Shuts down all processes and deletes all state associated with the instance. * * @param timeoutS The unit is second. */ public synchronized void shutdown(Long timeoutS) { if (Ray.isInitialized() && !shutdown) { if (timeoutS == null) { timeoutS = 30L; } try { ((PyActorHandle) controller) .task(PyActorMethod.of("graceful_shutdown")) .remote() .get(timeoutS * 1000); } catch (RayActorException e) { // Controller has been shut down. return; } catch (RayTimeoutException e) { LOGGER.warn( "Controller failed to shut down within {}s. Check controller logs for more details.", timeoutS); } shutdown = true; } } public String getRootUrl() { return rootUrl; } /** * @deprecated {@value Constants#MIGRATION_MESSAGE} * @param name * @return */ @Deprecated public DeploymentRoute getDeploymentInfo(String name) { return DeploymentRoute.fromProtoBytes( (byte[]) ((PyActorHandle) controller) .task(PyActorMethod.of("get_deployment_info"), name) .remote() .get()); } public BaseActorHandle getController() { return controller; } /** * Deployment an application with deployment list. * * @param name application name * @param deployments deployment list * @param blocking Wait for the applications to be deployed or not. */ public void deployApplication(String name, List<Deployment> deployments, boolean blocking) { Object[] deploymentArgsArray = new Object[deployments.size()]; for (int i = 0; i < deployments.size(); i++) { Deployment deployment = deployments.get(i); DeploymentArgs.Builder deploymentArgs = DeploymentArgs.newBuilder() .setDeploymentName(deployment.getName()) .setReplicaConfig(ByteString.copyFrom(deployment.getReplicaConfig().toProtoBytes())) .setDeploymentConfig( ByteString.copyFrom(deployment.getDeploymentConfig().toProtoBytes())) .setIngress(deployment.isIngress()) .setDeployerJobId(Ray.getRuntimeContext().getCurrentJobId().toString()); if (deployment.getRoutePrefix() != null) { deploymentArgs.setRoutePrefix(deployment.getRoutePrefix()); } deploymentArgsArray[i] = deploymentArgs.build().toByteArray(); } ((PyActorHandle) controller) .task(PyActorMethod.of("deploy_application"), name, deploymentArgsArray) .remote() .get(); if (blocking) { waitForApplicationRunning(name, null); for (Deployment deployment : deployments) { logDeploymentReady( deployment.getName(), deployment.getVersion(), deployment.getUrl(), "component=serve deployment=" + deployment.getName()); } } } /** * Waits for the named application to enter "RUNNING" status. * * @param name application name * @param timeoutS unit: second */ private void waitForApplicationRunning(String name, Long timeoutS) { long start = System.currentTimeMillis(); while (timeoutS == null || System.currentTimeMillis() - start < timeoutS * 1000) { StatusOverview status = getServeStatus(name); if (status.getAppStatus().getStatus() == ApplicationStatus.APPLICATION_STATUS_RUNNING) { return; } else if (status.getAppStatus().getStatus() == ApplicationStatus.APPLICATION_STATUS_DEPLOY_FAILED) { throw new RayServeException( MessageFormatter.format( "Deploying application {} is failed: {}", name, status.getAppStatus().getMessage())); } LOGGER.debug( "Waiting for {} to be RUNNING, current status: {}.", name, status.getAppStatus().getStatus()); try { Thread.sleep(CLIENT_POLLING_INTERVAL_S * 1000); } catch (InterruptedException e) { } } throw new RayServeException( MessageFormatter.format( "Application {} did not become RUNNING after {}s.", name, timeoutS)); } private void logDeploymentReady(String name, String version, String url, String tag) { String urlPart = url != null ? MessageFormatter.format(" at `{}`", url) : ""; LOGGER.info( "Deployment '{}{}' is ready {}. {}", name, StringUtils.isNotBlank(version) ? "':'" + version : "", urlPart, tag); } /** * Delete the specified applications. * * @param names application names * @param blocking Wait for the applications to be deleted or not. */ public void deleteApps(List<String> names, boolean blocking) { if (CollectionUtil.isEmpty(names)) { return; } LOGGER.info("Deleting app {}", names); ((PyActorHandle) controller) .task(PyActorMethod.of("delete_apps"), names.toArray()) .remote() .get(); if (blocking) { long start = System.currentTimeMillis(); List<String> undeleted = new ArrayList<>(names); while (System.currentTimeMillis() - start < 60 * 1000) { Iterator<String> iterator = undeleted.iterator(); while (iterator.hasNext()) { String name = iterator.next(); StatusOverview status = getServeStatus(name); if (status.getAppStatus().getStatus() == ApplicationStatus.APPLICATION_STATUS_NOT_STARTED) { iterator.remove(); } } if (undeleted.isEmpty()) { return; } try { Thread.sleep(CLIENT_POLLING_INTERVAL_S * 1000); } catch (InterruptedException e) { } } throw new RayServeException( MessageFormatter.format( "Some of these applications weren't deleted after 60s: {}", names)); } } /** * Return the status of the specified application. * * @param name application name * @return */ public StatusOverview getServeStatus(String name) { byte[] statusBytes = (byte[]) ((PyActorHandle) controller) .task(PyActorMethod.of("get_serve_status"), name) .remote() .get(); return ServeProtoUtil.bytesToProto(statusBytes, StatusOverview::parseFrom); } }
ray-project/ray
java/serve/src/main/java/io/ray/serve/api/ServeControllerClient.java
213,349
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.app.plugin.core.script; import java.awt.Point; import java.awt.datatransfer.Transferable; import java.awt.dnd.*; import java.util.ArrayList; import javax.swing.table.TableModel; import docking.dnd.*; import generic.jar.ResourceFile; import ghidra.util.table.GhidraTable; public class DraggableScriptTable extends GhidraTable implements Draggable { private DragSrcAdapter dragSourceAdapter; private DragGestureAdapter dragGestureAdapter; private DragSource dragSource; private final GhidraScriptComponentProvider provider; /** * Constructs a new DraggableGhidraTable. * @param provider the provider, from which getTableModel and getScriptAt are used * @param model provider's table model */ public DraggableScriptTable(GhidraScriptComponentProvider provider, TableModel model) { super(model); this.provider = provider; initDragNDrop(); } private void initDragNDrop() { // set up drag stuff dragSource = DragSource.getDefaultDragSource(); dragGestureAdapter = new DragGestureAdapter(this); dragSourceAdapter = new DragSrcAdapter(this); dragSource.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, dragGestureAdapter); } /** * Return true if the location in the event is draggable. */ @Override public boolean isStartDragOk(DragGestureEvent e) { return true; } /** * Called by the DragGestureAdapter to start the drag. */ @Override public DragSourceListener getDragSourceListener() { return dragSourceAdapter; } /** * Called by the DragGestureAdapter and the DragSourceAdapter to * know what actions this component allows. */ @Override public int getDragAction() { return DnDConstants.ACTION_COPY_OR_MOVE; } /** * Called by the DragGestureAdapter when the drag is about to * start. */ @Override public Transferable getTransferable(Point p) { ArrayList<ResourceFile> arrayList = new ArrayList<>(); int[] selectedRows = getSelectedRows(); for (int element : selectedRows) { arrayList.add(provider.getScriptAt(element)); } return new GhidraTransferable(arrayList); } /** * Do the move operation. Called from the DragSourceAdapter * when the drop completes and the user action was a * DnDConstants.MOVE. */ @Override public void move() { // } /** * Called from the DragSourceAdapter when the drag operation exits the * drop target without dropping. */ @Override public void dragCanceled(DragSourceDropEvent event) { // } }
NationalSecurityAgency/ghidra
Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/DraggableScriptTable.java
213,350
package com.danikula.videocache; import java.io.IOException; import java.io.OutputStream; import java.net.Proxy; import java.net.ProxySelector; import java.net.Socket; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeoutException; import static com.danikula.videocache.Preconditions.checkArgument; import static com.danikula.videocache.Preconditions.checkNotNull; import static java.util.concurrent.TimeUnit.MILLISECONDS; /** * Pings {@link HttpProxyCacheServer} to make sure it works. * * @author Alexey Danilov ([email protected]). */ class Pinger { private static final String PING_REQUEST = "ping"; private static final String PING_RESPONSE = "ping ok"; private final ExecutorService pingExecutor = Executors.newSingleThreadExecutor(); private final String host; private final int port; Pinger(String host, int port) { this.host = checkNotNull(host); this.port = port; } boolean ping(int maxAttempts, int startTimeout) { checkArgument(maxAttempts >= 1); checkArgument(startTimeout > 0); int timeout = startTimeout; int attempts = 0; while (attempts < maxAttempts) { try { Future<Boolean> pingFuture = pingExecutor.submit(new PingCallable()); boolean pinged = pingFuture.get(timeout, MILLISECONDS); if (pinged) { return true; } } catch (TimeoutException e) { HttpProxyCacheDebuger.printfWarning("Error pinging server (attempt: " + attempts + ", timeout: " + timeout + "). "); } catch (InterruptedException | ExecutionException e) { HttpProxyCacheDebuger.printfError("Error pinging server due to unexpected error", e); } attempts++; timeout *= 2; } String error = String.format(Locale.US, "Error pinging server (attempts: %d, max timeout: %d). " + "If you see this message, please, report at https://github.com/danikula/AndroidVideoCache/issues/134. " + "Default proxies are: %s" , attempts, timeout / 2, getDefaultProxies()); HttpProxyCacheDebuger.printfError(error, new ProxyCacheException(error)); return false; } private List<Proxy> getDefaultProxies() { try { ProxySelector defaultProxySelector = ProxySelector.getDefault(); return defaultProxySelector.select(new URI(getPingUrl())); } catch (URISyntaxException e) { throw new IllegalStateException(e); } } boolean isPingRequest(String request) { return PING_REQUEST.equals(request); } void responseToPing(Socket socket) throws IOException { OutputStream out = socket.getOutputStream(); out.write("HTTP/1.1 200 OK\n\n".getBytes()); out.write(PING_RESPONSE.getBytes()); } private boolean pingServer() throws ProxyCacheException { String pingUrl = getPingUrl(); HttpUrlSource source = new HttpUrlSource(pingUrl, null, null); try { byte[] expectedResponse = PING_RESPONSE.getBytes(); source.open(0); byte[] response = new byte[expectedResponse.length]; source.read(response); boolean pingOk = Arrays.equals(expectedResponse, response); HttpProxyCacheDebuger.printfLog("Ping response: `" + new String(response) + "`, pinged? " + pingOk); return pingOk; } catch (ProxyCacheException e) { HttpProxyCacheDebuger.printfError("Error reading ping response", e); return false; } finally { source.close(); } } private String getPingUrl() { return String.format(Locale.US, "http://%s:%d/%s", host, port, PING_REQUEST); } private class PingCallable implements Callable<Boolean> { @Override public Boolean call() throws Exception { return pingServer(); } } }
CarGuo/GSYVideoPlayer
gsyVideoPlayer-proxy_cache/src/main/java/com/danikula/videocache/Pinger.java
213,351
/* ### * IP: GHIDRA * REVIEWED: YES * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package docking.widgets.tree.support; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.dnd.DnDConstants; import java.util.List; import docking.widgets.tree.GTreeNode; public interface GTreeDragNDropHandler extends GTreeTransferHandler { /** * Return true if the dragUserData can be dragged. * @param dragUserData data where user is initiating the drag operation * @param dragAction user action for the drag operation */ public boolean isStartDragOk(List<GTreeNode> dragUserData, int dragAction); /** * Returns the supported Drag actions for this tree. For available actions see * {@link DnDConstants}. * @return the supported Drag actions. */ public int getSupportedDragActions(); /** * Return true if the drop site is valid for the given target. * @param destUserData destination for node being dragged * @param flavors flavor(s) being dragged * @param dropAction user action for drop operation */ boolean isDropSiteOk(GTreeNode destUserData, DataFlavor[] flavors, int dropAction); /** * Add the given transferable's data to the destination user data. * @param destUserData destination node for the data. * @param transferable the transferable being dragged whose data will be dropped. * @param dropAction user action for drop operation */ void drop(GTreeNode destUserData, Transferable transferable, int dropAction); }
NationalSecurityAgency/ghidra
Ghidra/Framework/Docking/src/main/java/docking/widgets/tree/support/GTreeDragNDropHandler.java
213,352
package apps; import apps.gui3.tabbedpreferences.TabbedPreferences; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.*; import java.lang.reflect.InvocationTargetException; import javax.swing.SwingUtilities; import jmri.*; import jmri.jmrit.logixng.LogixNGPreferences; import jmri.jmrit.revhistory.FileHistory; import jmri.profile.Profile; import jmri.profile.ProfileManager; import jmri.script.JmriScriptEngineManager; import jmri.util.FileUtil; import jmri.util.ThreadingUtil; import jmri.util.prefs.JmriPreferencesActionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import apps.util.Log4JUtil; /** * Base class for the core of JMRI applications. * <p> * This provides a non-GUI base for applications. Below this is the * {@link apps.gui3.Apps3} subclass which provides basic Swing GUI support. * <p> * There are a series of steps in the configuration: * <dl> * <dt>preInit<dd>Initialize log4j, invoked from the main() * <dt>ctor<dd>Construct the basic application object * </dl> * * @author Bob Jacobsen Copyright 2009, 2010 */ public abstract class AppsBase { private final static String CONFIG_FILENAME = System.getProperty("org.jmri.Apps.configFilename", "/JmriConfig3.xml"); protected boolean configOK; protected boolean configDeferredLoadOK; protected boolean preferenceFileExists; static boolean preInit = false; private final static Logger log = LoggerFactory.getLogger(AppsBase.class); /** * Initial actions before frame is created, invoked in the applications * main() routine. * <ul> * <li> Initialize logging * <li> Set application name * </ul> * * @param applicationName The application name as presented to the user */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( value="SLF4J_FORMAT_SHOULD_BE_CONST", justification="Info String always needs to be evaluated") static public void preInit(String applicationName) { Log4JUtil.initLogging(); try { Application.setApplicationName(applicationName); } catch (IllegalAccessException | IllegalArgumentException ex) { log.error("Unable to set application name", ex); } log.info(Log4JUtil.startupInfo(applicationName)); preInit = true; } /** * Create and initialize the application object. * * @param applicationName user-visible name of application * @param configFileDef default config filename * @param args arguments passed to application at launch */ @SuppressFBWarnings(value = "SC_START_IN_CTOR", justification = "The thread is only called to help improve user experiance when opening the preferences, it is not critical for it to be run at this stage") public AppsBase(String applicationName, String configFileDef, String[] args) { if (!preInit) { preInit(applicationName); setConfigFilename(configFileDef, args); } Log4JUtil.initLogging(); configureProfile(); installConfigurationManager(); installManagers(); setAndLoadPreferenceFile(); FileUtil.logFilePaths(); if (Boolean.getBoolean("org.jmri.python.preload")) { new Thread(() -> { try { JmriScriptEngineManager.getDefault().initializeAllEngines(); } catch (Exception ex) { log.error("Error initializing python interpreter", ex); } }, "initialize python interpreter").start(); } // all loaded, initialize objects as necessary InstanceManager.getDefault(jmri.LogixManager.class).activateAllLogixs(); InstanceManager.getDefault(jmri.jmrit.display.layoutEditor.LayoutBlockManager.class).initializeLayoutBlockPaths(); jmri.jmrit.logixng.LogixNG_Manager logixNG_Manager = InstanceManager.getDefault(jmri.jmrit.logixng.LogixNG_Manager.class); logixNG_Manager.setupAllLogixNGs(); if (InstanceManager.getDefault(LogixNGPreferences.class).getStartLogixNGOnStartup() && InstanceManager.getDefault(jmri.jmrit.logixng.LogixNG_Manager.class).isStartLogixNGsOnLoad()) { logixNG_Manager.activateAllLogixNGs(); } } /** * Configure the {@link jmri.profile.Profile} to use for this application. * <p> * Note that GUI-based applications must override this method, since this * method does not provide user feedback. */ protected void configureProfile() { String profileFilename; FileUtil.createDirectory(FileUtil.getPreferencesPath()); // Needs to be declared final as we might need to // refer to this on the Swing thread File profileFile; profileFilename = getConfigFileName().replaceFirst(".xml", ".properties"); // decide whether name is absolute or relative if (!new File(profileFilename).isAbsolute()) { // must be relative, but we want it to // be relative to the preferences directory profileFile = new File(FileUtil.getPreferencesPath() + profileFilename); } else { profileFile = new File(profileFilename); } ProfileManager.getDefault().setConfigFile(profileFile); // See if the profile to use has been specified on the command line as // a system property org.jmri.profile as a profile id. if (System.getProperties().containsKey(ProfileManager.SYSTEM_PROPERTY)) { ProfileManager.getDefault().setActiveProfile(System.getProperty(ProfileManager.SYSTEM_PROPERTY)); } // @see jmri.profile.ProfileManager#migrateToProfiles Javadoc for conditions handled here if (!profileFile.exists()) { // no profile config for this app try { if (ProfileManager.getDefault().migrateToProfiles(getConfigFileName())) { // migration or first use // GUI should show message here log.info("Migrated {}",Bundle.getMessage("ConfigMigratedToProfile")); } } catch (IOException | IllegalArgumentException ex) { // GUI should show message here log.error("Profiles not configurable. Using fallback per-application configuration. Error: {}", ex.getMessage()); } } try { // GUI should use ProfileManagerDialog.getStartingProfile here if (ProfileManager.getStartingProfile() != null) { // Manually setting the configFilename property since calling // Apps.setConfigFilename() does not reset the system property System.setProperty("org.jmri.Apps.configFilename", Profile.CONFIG_FILENAME); Profile profile = ProfileManager.getDefault().getActiveProfile(); if (profile != null) { log.info("Starting with profile {}", profile.getId()); } else { log.info("Starting without a profile"); } } else { log.error("Specify profile to use as command line argument."); log.error("If starting with saved profile configuration, ensure the autoStart property is set to \"true\""); log.error("Profiles not configurable. Using fallback per-application configuration."); } } catch (IOException ex) { log.info("Profiles not configurable. Using fallback per-application configuration. Error: {}", ex.getMessage()); } } protected void installConfigurationManager() { // install a Preferences Action Factory InstanceManager.store(new AppsPreferencesActionFactory(), JmriPreferencesActionFactory.class); ConfigureManager cm = new AppsConfigurationManager(); FileUtil.createDirectory(FileUtil.getUserFilesPath()); InstanceManager.store(cm, ConfigureManager.class); InstanceManager.setDefault(ConfigureManager.class, cm); log.debug("config manager installed"); } protected void installManagers() { // record startup String appString = String.format("%s (v%s)", Application.getApplicationName(), Version.getCanonicalVersion()); InstanceManager.getDefault(FileHistory.class).addOperation("app", appString, null); // install the abstract action model that allows items to be added to the, both // CreateButton and Perform Action Model use a common Abstract class InstanceManager.store(new CreateButtonModel(), CreateButtonModel.class); } /** * Invoked to load the preferences information, and in the process configure * the system. The high-level steps are: * <ul> * <li>Locate the preferences file based through * {@link FileUtil#getFile(String)} * <li>See if the preferences file exists, and handle it if it doesn't * <li>Obtain a {@link jmri.ConfigureManager} from the * {@link jmri.InstanceManager} * <li>Ask that ConfigureManager to load the file, in the process loading * information into existing and new managers. * <li>Do any deferred loads that are needed * <li>If needed, migrate older formats * </ul> * (There's additional handling for shared configurations) */ protected void setAndLoadPreferenceFile() { FileUtil.createDirectory(FileUtil.getUserFilesPath()); final File file; File sharedConfig = null; try { sharedConfig = FileUtil.getFile(FileUtil.PROFILE + Profile.SHARED_CONFIG); if (!sharedConfig.canRead()) { sharedConfig = null; } } catch (FileNotFoundException ex) { // ignore - this only means that sharedConfig does not exist. } if (sharedConfig != null) { file = sharedConfig; } else if (!new File(getConfigFileName()).isAbsolute()) { // must be relative, but we want it to // be relative to the preferences directory file = new File(FileUtil.getUserFilesPath() + getConfigFileName()); } else { file = new File(getConfigFileName()); } // don't try to load if doesn't exist, but mark as not OK if (!file.exists()) { preferenceFileExists = false; configOK = false; log.info("No pre-existing config file found, searched for '{}'", file.getPath()); return; } preferenceFileExists = true; // ensure the UserPreferencesManager has loaded. Done on GUI // thread as it can modify GUI objects ThreadingUtil.runOnGUI(() -> { InstanceManager.getDefault(jmri.UserPreferencesManager.class); }); // now (attempt to) load the config file try { ConfigureManager cm = InstanceManager.getNullableDefault(jmri.ConfigureManager.class); if (cm != null) { configOK = cm.load(file); } else { configOK = false; } log.debug("end load config file {}, OK={}", file.getName(), configOK); } catch (JmriException e) { configOK = false; } if (sharedConfig != null) { // sharedConfigs do not need deferred loads configDeferredLoadOK = true; } else if (SwingUtilities.isEventDispatchThread()) { // To avoid possible locks, deferred load should be // performed on the Swing thread configDeferredLoadOK = doDeferredLoad(file); } else { try { // Use invokeAndWait method as we don't want to // return until deferred load is completed SwingUtilities.invokeAndWait(() -> { configDeferredLoadOK = doDeferredLoad(file); }); } catch (InterruptedException | InvocationTargetException ex) { log.error("Exception creating system console frame:", ex); } } if (sharedConfig == null && configOK == true && configDeferredLoadOK == true) { log.info("Migrating preferences to new format..."); // migrate preferences InstanceManager.getOptionalDefault(TabbedPreferences.class).ifPresent(tp -> { //tp.init(); tp.saveContents(); InstanceManager.getOptionalDefault(ConfigureManager.class).ifPresent(cm -> { cm.storePrefs(); }); // notify user of change log.info("Preferences have been migrated to new format."); log.info("New preferences format will be used after JMRI is restarted."); }); } } private boolean doDeferredLoad(File file) { boolean result; log.debug("start deferred load from config file {}", file.getName()); try { ConfigureManager cm = InstanceManager.getNullableDefault(jmri.ConfigureManager.class); if (cm != null) { result = cm.loadDeferred(file); } else { log.error("Failed to get default configure manager"); result = false; } } catch (JmriException e) { log.error("Unhandled problem loading deferred configuration:", e); result = false; } log.debug("end deferred load from config file {}, OK={}", file.getName(), result); return result; } /** * Final actions before releasing control of the application to the user, * invoked explicitly after object has been constructed in main(). */ protected void start() { log.debug("main initialization done"); } /** * Set up the configuration file name at startup. * <p> * The Configuration File name variable holds the name used to load the * configuration file during later startup processing. Applications invoke * this method to handle the usual startup hierarchy: * <ul> * <li>If an absolute filename was provided on the command line, use it * <li>If a filename was provided that's not absolute, consider it to be in * the preferences directory * <li>If no filename provided, use a default name (that's application specific) * </ul> * This name will be used for reading and writing the preferences. It need * not exist when the program first starts up. This name may be proceeded * with <em>config=</em>. * * @param def Default value if no other is provided * @param args Argument array from the main routine */ static protected void setConfigFilename(String def, String[] args) { // skip if org.jmri.Apps.configFilename is set if (System.getProperty("org.jmri.Apps.configFilename") != null) { return; } // save the configuration filename if present on the command line if (args.length >= 1 && args[0] != null && !args[0].equals("") && !args[0].contains("=")) { def = args[0]; log.debug("Config file was specified as: {}", args[0]); } for (String arg : args) { String[] split = arg.split("=", 2); if (split[0].equalsIgnoreCase("config")) { def = split[1]; log.debug("Config file was specified as: {}", arg); } } if (def != null) { setJmriSystemProperty("configFilename", def); log.debug("Config file set to: {}", def); } } // We will use the value stored in the system property static public String getConfigFileName() { if (System.getProperty("org.jmri.Apps.configFilename") != null) { return System.getProperty("org.jmri.Apps.configFilename"); } return CONFIG_FILENAME; } static protected void setJmriSystemProperty(String key, String value) { try { String current = System.getProperty("org.jmri.Apps." + key); if (current == null) { System.setProperty("org.jmri.Apps." + key, value); } else if (!current.equals(value)) { log.warn("JMRI property {} already set to {}, skipping reset to {}", key, current, value); } } catch (Exception e) { log.error("Unable to set JMRI property {} to {}due to exception", key, value, e); } } /** * The application decided to quit, handle that. * * @return always returns false */ static public boolean handleQuit() { log.debug("Start handleQuit"); try { InstanceManager.getDefault(jmri.ShutDownManager.class).shutdown(); } catch (Exception e) { log.error("Continuing after error in handleQuit", e); } return false; } /** * The application decided to restart, handle that. */ static public void handleRestart() { log.debug("Start handleRestart"); try { InstanceManager.getDefault(jmri.ShutDownManager.class).restart(); } catch (Exception e) { log.error("Continuing after error in handleRestart", e); } } }
bobjacobsen/JMRI
java/src/apps/AppsBase.java
213,354
/* * Copyright 2013 Klaus Reimer <[email protected]> * Copyright 2013 Luca Longinotti <[email protected]> * See LICENSE.md for licensing information. * * Based on libusb <http://libusb.info/>: * * Copyright 2001 Johannes Erdfelt <[email protected]> * Copyright 2007-2009 Daniel Drake <[email protected]> * Copyright 2010-2012 Peter Stuge <[email protected]> * Copyright 2008-2013 Nathan Hjelm <[email protected]> * Copyright 2009-2013 Pete Batard <[email protected]> * Copyright 2009-2013 Ludovic Rousseau <[email protected]> * Copyright 2010-2012 Michael Plante <[email protected]> * Copyright 2011-2013 Hans de Goede <[email protected]> * Copyright 2012-2013 Martin Pieuchot <[email protected]> * Copyright 2012-2013 Toby Gray <[email protected]> */ package org.usb4java; import java.io.FileDescriptor; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.commons.lang3.tuple.ImmutablePair; /** * Static class providing the constants and functions of libusb. * * @author Klaus Reimer ([email protected]) * @author Luca Longinotti ([email protected]) */ public final class LibUsb { // Log message levels. /** No messages ever printed by the library (default). */ public static final int LOG_LEVEL_NONE = 0; /** Error messages are printed to stderr. */ public static final int LOG_LEVEL_ERROR = 1; /** Warning and error messages are printed to stderr. */ public static final int LOG_LEVEL_WARNING = 2; /** * Informational messages are printed to stdout, warning and error messages * are printed to stderr. */ public static final int LOG_LEVEL_INFO = 3; /** * Debug and informational messages are printed to stdout, warnings and * errors to stderr. */ public static final int LOG_LEVEL_DEBUG = 4; // Available option values for {@link #setOption()} /** * Set the log message verbosity. * * The default level is {@link #LOG_LEVEL_NONE}, which means no messages are ever * printed. If you choose to increase the message verbosity level, ensure * that your application does not close the stderr file descriptor. * * You are advised to use level {@link #LOG_LEVEL_WARNING}. libusb is conservative * with its message logging and most of the time, will only log messages that * explain error conditions and other oddities. This will help you debug * your software. * * If the LIBUSB_DEBUG environment variable was set when libusb was * initialized, this function does nothing: the message verbosity is fixed * to the value in the environment variable. * * If libusb was compiled without any message logging, this function does * nothing: you'll never get any messages. * * If libusb was compiled with verbose debug message logging, this function * does nothing: you'll always get messages from all levels. */ public static final int OPTION_LOG_LEVEL = 0; /** * Use the UsbDk backend for a specific context, if available. * * This option should be set immediately after calling {@link #init(Context)}, otherwise * unspecified behavior may occur. * * Only valid on Windows. */ public static final int OPTION_USE_USBDK = 1; // Error codes. Most libusb functions return 0 on success or one of these // codes on failure. You can call errorName() to retrieve a string // representation of an error code. /** Success (no error). */ public static final int SUCCESS = 0; /** Input/output error. */ public static final int ERROR_IO = -1; /** Invalid parameter. */ public static final int ERROR_INVALID_PARAM = -2; /** Access denied (insufficient permissions). */ public static final int ERROR_ACCESS = -3; /** No such device (it may have been disconnected). */ public static final int ERROR_NO_DEVICE = -4; /** Entity not found. */ public static final int ERROR_NOT_FOUND = -5; /** Resource busy. */ public static final int ERROR_BUSY = -6; /** Operation timed out. */ public static final int ERROR_TIMEOUT = -7; /** Overflow. */ public static final int ERROR_OVERFLOW = -8; /** Pipe error. */ public static final int ERROR_PIPE = -9; /** System call interrupted (perhaps due to signal). */ public static final int ERROR_INTERRUPTED = -10; /** Insufficient memory. */ public static final int ERROR_NO_MEM = -11; /** Operation not supported or unimplemented on this platform. */ public static final int ERROR_NOT_SUPPORTED = -12; /** Other error. */ public static final int ERROR_OTHER = -99; /** Total number of error codes. */ public static final int ERROR_COUNT = 14; // Speed codes. Indicates the speed at which the device is operating. /** The OS doesn't report or know the device speed. */ public static final int SPEED_UNKNOWN = 0; /** The device is operating at low speed (1.5MBit/s). */ public static final int SPEED_LOW = 1; /** The device is operating at full speed (12MBit/s). */ public static final int SPEED_FULL = 2; /** The device is operating at high speed (480MBit/s). */ public static final int SPEED_HIGH = 3; /** The device is operating at super speed (5000MBit/s). */ public static final int SPEED_SUPER = 4; /** The device is operating at super speed plus (10000MBit/s). */ public static final int SPEED_SUPER_PLUS = 5; // Supported speeds (wSpeedSupported) bitfield. Indicates what speeds the // device supports. /** Low speed operation supported (1.5MBit/s). */ public static final short LOW_SPEED_OPERATION = 1; /** Full speed operation supported (12MBit/s). */ public static final short FULL_SPEED_OPERATION = 2; /** High speed operation supported (480MBit/s). */ public static final short HIGH_SPEED_OPERATION = 4; /** Superspeed operation supported (5000MBit/s). */ public static final short SUPER_SPEED_OPERATION = 8; // Masks for the bits of the bmAttributes field of the USB 2.0 Extension // descriptor. /** Supports Link Power Management (LPM). */ public static final int BM_LPM_SUPPORT = 2; // Masks for the bits of the bmAttributes field field of the SuperSpeed USB // Device Capability descriptor. /** Supports Latency Tolerance Messages (LTM). */ public static final byte BM_LTM_SUPPORT = 2; // USB capability types. /** Wireless USB device capability. */ public static final byte BT_WIRELESS_USB_DEVICE_CAPABILITY = 1; /** USB 2.0 extensions. */ public static final byte BT_USB_2_0_EXTENSION = 2; /** SuperSpeed USB device capability. */ public static final byte BT_SS_USB_DEVICE_CAPABILITY = 3; /** Container ID type. */ public static final byte BT_CONTAINER_ID = 4; // Standard requests, as defined in table 9-5 of the USB 3.0 specifications. /** Request status of the specific recipient. */ public static final byte REQUEST_GET_STATUS = 0x00; /** Clear or disable a specific feature. */ public static final byte REQUEST_CLEAR_FEATURE = 0x01; /** Set or enable a specific feature. */ public static final byte REQUEST_SET_FEATURE = 0x03; /** Set device address for all future accesses. */ public static final byte REQUEST_SET_ADDRESS = 0x05; /** Set device address for all future accesses. */ public static final byte REQUEST_GET_DESCRIPTOR = 0x06; /** Set device address for all future accesses. */ public static final byte REQUEST_SET_DESCRIPTOR = 0x07; /** Get the current device configuration value. */ public static final byte REQUEST_GET_CONFIGURATION = 0x08; /** Get the current device configuration value. */ public static final byte REQUEST_SET_CONFIGURATION = 0x09; /** Return the selected alternate setting for the specified interface. */ public static final byte REQUEST_GET_INTERFACE = 0x0A; /** Select an alternate interface for the specified interface. */ public static final byte REQUEST_SET_INTERFACE = 0x0B; /** Set then report an endpoint's synchronization frame. */ public static final byte REQUEST_SYNCH_FRAME = 0x0C; /** Sets both the U1 and U2 Exit Latency. */ public static final byte REQUEST_SET_SEL = 0x30; /** * Delay from the time a host transmits a packet to the time it is received * by the device. */ public static final byte SET_ISOCH_DELAY = 0x31; // Request type bits of the bmRequestType field in control transfers. /** Standard. */ public static final byte REQUEST_TYPE_STANDARD = 0; /** Class. */ public static final byte REQUEST_TYPE_CLASS = 32; /** Vendor. */ public static final byte REQUEST_TYPE_VENDOR = 64; /** Reserved. */ public static final byte REQUEST_TYPE_RESERVED = 96; // Recipient bits of the bmRequestType field in control transfers. // Values 4 through 31 are reserved. /** Device. */ public static final byte RECIPIENT_DEVICE = 0x00; /** Interface. */ public static final byte RECIPIENT_INTERFACE = 0x01; /** Endpoint. */ public static final byte RECIPIENT_ENDPOINT = 0x02; /** Other. */ public static final byte RECIPIENT_OTHER = 0x03; // Capabilities supported by an instance of libusb on the current running // platform. Test if the loaded library supports a given capability by // calling hasCapability. /** The {@link #hasCapability(int)} API is available. */ public static final int CAP_HAS_CAPABILITY = 0x0000; /** Hotplug support is available on this platform. */ public static final int CAP_HAS_HOTPLUG = 0x0001; /** * The library can access HID devices without requiring user intervention. * Note that before being able to actually access an HID device, you may * still have to call additional libusb functions such as * {@link #detachKernelDriver(DeviceHandle, int)}. */ public static final int CAP_HAS_HID_ACCESS = 0x0100; /** * The library supports detaching of the default USB driver, using * {@link #detachKernelDriver(DeviceHandle, int)}, if one is set by the OS * kernel. */ public static final int CAP_SUPPORTS_DETACH_KERNEL_DRIVER = 0x0101; /** The size of a control setup packet. */ public static final short CONTROL_SETUP_SIZE = 8; // Device and/or Interface Class codes. /** * In the context of a device descriptor, this bDeviceClass value indicates * that each interface specifies its own class information and all * interfaces operate independently. */ public static final byte CLASS_PER_INTERFACE = 0; /** Audio class. */ public static final byte CLASS_AUDIO = 1; /** Communications class. */ public static final byte CLASS_COMM = 2; /** Human Interface Device class. */ public static final byte CLASS_HID = 3; /** Physical. */ public static final byte CLASS_PHYSICAL = 5; /** Image class. */ public static final byte CLASS_PTP = 6; /** Image class. */ public static final byte CLASS_IMAGE = 6; /** Printer class. */ public static final byte CLASS_PRINTER = 7; /** Mass storage class. */ public static final byte CLASS_MASS_STORAGE = 8; /** Hub class. */ public static final byte CLASS_HUB = 9; /** Data class. */ public static final byte CLASS_DATA = 10; /** Smart Card. */ public static final byte CLASS_SMART_CARD = 0x0B; /** Content Security. */ public static final byte CLASS_CONTENT_SECURITY = 0x0D; /** Video. */ public static final byte CLASS_VIDEO = 0x0E; /** Personal Healthcare. */ public static final byte CLASS_PERSONAL_HEALTHCARE = 0x0F; /** Diagnostic Device. */ public static final byte CLASS_DIAGNOSTIC_DEVICE = (byte) 0xDC; /** Wireless class. */ public static final byte CLASS_WIRELESS = (byte) 0xE0; /** Application class. */ public static final byte CLASS_APPLICATION = (byte) 0xFE; /** Class is vendor-specific. */ public static final byte CLASS_VENDOR_SPEC = (byte) 0xFF; // Descriptor types as defined by the USB specification. /** * Device descriptor. * * @see DeviceDescriptor */ public static final byte DT_DEVICE = 0x01; /** * Configuration descriptor. * * @see ConfigDescriptor */ public static final byte DT_CONFIG = 0x02; /** String descriptor. */ public static final byte DT_STRING = 0x03; /** * Interface descriptor. * * @see InterfaceDescriptor */ public static final byte DT_INTERFACE = 0x04; /** * Endpoint descriptor. * * @see EndpointDescriptor */ public static final byte DT_ENDPOINT = 0x05; /** * BOS descriptor. * * @see BosDescriptor */ public static final byte DT_BOS = 0x0F; /** * Device Capability descriptor. * * @see BosDevCapabilityDescriptor */ public static final byte DT_DEVICE_CAPABILITY = 0x10; /** HID descriptor. */ public static final byte DT_HID = 0x21; /** HID report descriptor. */ public static final byte DT_REPORT = 0x22; /** Physical descriptor. */ public static final byte DT_PHYSICAL = 0x23; /** Hub descriptor. */ public static final byte DT_HUB = 0x29; /** SuperSpeed Hub descriptor. */ public static final byte DT_SUPERSPEED_HUB = 0x2A; /** * SuperSpeed Endpoint Companion descriptor. * * @see SsEndpointCompanionDescriptor */ public static final byte DT_SS_ENDPOINT_COMPANION = 0x30; // Descriptor sizes per descriptor type /** Size of a device descriptor. */ public static final byte DT_DEVICE_SIZE = 18; /** Size of a config descriptor. */ public static final byte DT_CONFIG_SIZE = 9; /** Size of an interface descriptor. */ public static final byte DT_INTERFACE_SIZE = 9; /** Size of an endpoint descriptor. */ public static final byte DT_ENDPOINT_SIZE = 7; /** Size of an endpoint descriptor with audio extension. */ public static final byte DT_ENDPOINT_AUDIO_SIZE = 9; /** Size of a hub descriptor. */ public static final byte DT_HUB_NONVAR_SIZE = 7; /** Size of a SuperSpeed endpoint companion descriptor. */ public static final byte DT_SS_ENDPOINT_COMPANION_SIZE = 6; /** Size of a BOS descriptor. */ public static final byte DT_BOS_SIZE = 5; /** Size of a device capability descriptor. */ public static final byte DT_DEVICE_CAPABILITY_SIZE = 3; // BOS descriptor sizes /** Size of a BOS descriptor. */ public static final byte BT_USB_2_0_EXTENSION_SIZE = 7; /** Size of a BOS descriptor. */ public static final byte BT_SS_USB_DEVICE_CAPABILITY_SIZE = 10; /** Size of a BOS descriptor. */ public static final byte BT_CONTAINER_ID_SIZE = 20; /** We unwrap the BOS => define its maximum size. */ public static final byte DT_BOS_MAX_SIZE = DT_BOS_SIZE + BT_USB_2_0_EXTENSION_SIZE + BT_SS_USB_DEVICE_CAPABILITY_SIZE + BT_CONTAINER_ID_SIZE; // Endpoint direction. Values for bit 7 of the endpoint address scheme. /** In: device-to-host. */ public static final byte ENDPOINT_IN = (byte) 0x80; /** Out: host-to-device. */ public static final byte ENDPOINT_OUT = 0x00; // === Masks ============================================================= /** Endpoint address mask. */ public static final byte ENDPOINT_ADDRESS_MASK = 0x0F; /** Endpoint direction mask. */ public static final byte ENDPOINT_DIR_MASK = (byte) 0x80; /** Transfer type mask. */ public static final byte TRANSFER_TYPE_MASK = 0x03; // Endpoint transfer type. Values for bits 0:1 of the endpoint attributes // field. /** Control endpoint. */ public static final byte TRANSFER_TYPE_CONTROL = 0; /** Isochronous endpoint. */ public static final byte TRANSFER_TYPE_ISOCHRONOUS = 1; /** Bulk endpoint. */ public static final byte TRANSFER_TYPE_BULK = 2; /** Interrupt endpoint. */ public static final byte TRANSFER_TYPE_INTERRUPT = 3; /** Stream endpoint. */ public static final byte TRANSFER_TYPE_BULK_STREAM = 4; // Synchronization type for isochronous endpoints. // Values for bits 2:3 of the bmAttributes field in // EndpointDescriptor. /** The mask used to filter out sync types from attributes. */ public static final byte ISO_SYNC_TYPE_MASK = 0x0C; /** No synchronization. */ public static final byte ISO_SYNC_TYPE_NONE = 0; /** Asynchronous. */ public static final byte ISO_SYNC_TYPE_ASYNC = 1; /** Adaptive. */ public static final byte ISO_SYNC_TYPE_ADAPTIVE = 2; /** Synchronous. */ public static final byte ISO_SYNC_TYPE_SYNC = 3; // Usage type for isochronous endpoints. Values for bits 4:5 of the // bmAttributes field in EndpointDescriptor. /** The mask used to filter out usage types from attributes. */ public static final byte ISO_USAGE_TYPE_MASK = 0x30; /** Data endpoint. */ public static final byte ISO_USAGE_TYPE_DATA = 0; /** Feedback endpoint. */ public static final byte ISO_USAGE_TYPE_FEEDBACK = 1; /** Implicit feedback Data endpoint. */ public static final byte ISO_USAGE_TYPE_IMPLICIT = 2; /** Report short frames as errors. */ public static final byte TRANSFER_SHORT_NOT_OK = 1; // Transfer flags /** * Automatically free transfer buffer during {@link #freeTransfer(Transfer)} * * Please note that this flag (which is originally 2) is effectively a no-op * (set to zero) here in the Java wrapper, since the ByteBuffer that acts as * a buffer for transfers is allocated by the JVM and is subject to garbage * collection like any other object at some point. Nulling the reference is * the only needed action to take, and it is already done by the * TRANSFER_FREE_TRANSFER flag. */ public static final byte TRANSFER_FREE_BUFFER = 0; /** * Automatically call {@link #freeTransfer(Transfer)} after callback * returns. * * If this flag is set, it is illegal to call * {@link #freeTransfer(Transfer)} from your transfer callback, as this will * result in a double-free when this flag is acted upon. */ public static final byte TRANSFER_FREE_TRANSFER = 4; /** * Terminate transfers that are a multiple of the endpoint's wMaxPacketSize * with an extra zero length packet. * * This is useful when a device protocol mandates that each logical request * is terminated by an incomplete packet (i.e. the logical requests are not * separated by other means). * * This flag only affects host-to-device transfers to bulk and interrupt * endpoints. In other situations, it is ignored. * * This flag only affects transfers with a length that is a multiple of the * endpoint's wMaxPacketSize. On transfers of other lengths, this flag has * no effect. Therefore, if you are working with a device that needs a ZLP * whenever the end of the logical request falls on a packet boundary, then * it is sensible to set this flag on every transfer (you do not have to * worry about only setting it on transfers that end on the boundary). * * This flag is currently only supported on Linux. On other systems, * libusb_submit_transfer() will return {@link #ERROR_NOT_SUPPORTED} for * every transfer where this flag is set. */ public static final byte TRANSFER_ADD_ZERO_PACKET = 8; // Transfer status codes /** * Transfer completed without error. Note that this does not indicate that * the entire amount of requested data was transferred. */ public static final int TRANSFER_COMPLETED = 0; /** Transfer failed. */ public static final int TRANSFER_ERROR = 1; /** Transfer timed out. */ public static final int TRANSFER_TIMED_OUT = 2; /** Transfer was cancelled. */ public static final int TRANSFER_CANCELLED = 3; /** * For bulk/interrupt endpoints: halt condition detected (endpoint stalled). * For control endpoints: control request not supported. */ public static final int TRANSFER_STALL = 4; /** Device was disconnected. */ public static final int TRANSFER_NO_DEVICE = 5; /** Device sent more data than requested. */ public static final int TRANSFER_OVERFLOW = 6; // Flags for hotplug events /** * Default value when not using any flags. */ public static final int HOTPLUG_NO_FLAGS = 0; /** * Arm the callback and fire it for all matching currently attached devices. */ public static final int HOTPLUG_ENUMERATE = 1; // Hotplug events /** A device has been plugged in and is ready to use. */ public static final int HOTPLUG_EVENT_DEVICE_ARRIVED = 0x01; /** * A device has left and is no longer available. * It is the user's responsibility to call {@link #close(DeviceHandle)} on * any handle associated with a disconnected device. * It is safe to call {@link #getDeviceDescriptor(Device, DeviceDescriptor)} * on a device that has left. */ public static final int HOTPLUG_EVENT_DEVICE_LEFT = 0x02; // Wildcard matching for hotplug events /** Match any vendorId or productId or deviceClass. */ public static final int HOTPLUG_MATCH_ANY = -1; /** The next global hotplug ID to use. */ private static long globalHotplugId = 1; /** * Hotplug callbacks (to correctly manage calls and additional data). */ private static final ConcurrentMap<Long, ImmutablePair<HotplugCallback, Object>> hotplugCallbacks = new ConcurrentHashMap<Long, ImmutablePair<HotplugCallback, Object>>(); /** * Pollfd listeners (to support different listeners for different contexts). */ private static final ConcurrentMap<Long, ImmutablePair<PollfdListener, Object>> pollfdListeners = new ConcurrentHashMap<Long, ImmutablePair<PollfdListener, Object>>(); static { Loader.load(); } /** * Private constructor to prevent instantiation. */ private LibUsb() { // Empty } /** * Returns the API version of the underlying libusb library. It is defined * as follows: (major << 24) | (minor << 16) | (16 bit incremental) * * @return The API version of the underlying libusb library. */ public static native int getApiVersion(); /** * Initialize libusb. * * This function must be called before calling any other libusb function. * * If you do not provide an output location for a {@link Context}, a default * context will be created. If there was already a default context, it will * be reused (and nothing will be initialized/reinitialized). * * @param context * Optional output location for context pointer. Null to use * default context. Only valid on return code 0. * @return 0 on success or a error code on failure. */ public static synchronized native int init(final Context context); /** * Deinitialize libusb. * * Should be called after closing all open devices and before your * application terminates. * * @param context * The {@link Context} to deinitialize, or NULL for the default * context. */ public static synchronized native void exit(final Context context); /** * Set log message verbosity. * * The default level is {@link #LOG_LEVEL_NONE}, which means no messages are * ever printed. If you choose to increase the message verbosity level, * ensure that your application does not close the stdout/stderr file * descriptors. * * You are advised to use level {@link #LOG_LEVEL_WARNING}. libusb is * conservative with its message logging and most of the time, will only log * messages that explain error conditions and other oddities. This will help * you debug your software. * * If the {@link #LOG_LEVEL_DEBUG} environment variable was set when libusb * was initialized, this function does nothing: the message verbosity is * fixed to the value in the environment variable. * * If libusb was compiled without any message logging, this function does * nothing: you'll never get any messages. * * If libusb was compiled with verbose debug message logging, this function * does nothing: you'll always get messages from all levels. * * @param context * The {@link Context} to operate on, or NULL for the default * context. * @param level * The log level to set. * * @deprecated Use {@link #setOption(Context, int, int)} instead using the {@link #OPTION_LOG_LEVEL} option. */ public static native void setDebug(final Context context, final int level); /** * Set an option in the library. * * Use this function to configure a specific option within the library. * * Some options require one or more arguments to be provided. Consult each option's documentation for specific * requirements. * * @param context * The {@link Context} on which to operate. * @param option * Which option to set. * @return {@link #SUCCESS} on success, {@link #ERROR_INVALID_PARAM} if the option or arguments are invalid, * {@link #ERROR_NOT_SUPPORTED} if the option is valid but not supported on this platform. */ public static int setOption(final Context context, final int option) { return setOption(context, option, 0); } /** * Set an option in the library. * * Use this function to configure a specific option within the library. * * Some options require one or more arguments to be provided. Consult each option's documentation for specific * requirements. * * @param context * The {@link Context} on which to operate. * @param option * Which option to set. * @param value * Required argument for the specified option. * @return {@link #SUCCESS} on success, {@link #ERROR_INVALID_PARAM} if the option or arguments are invalid, * {@link #ERROR_NOT_SUPPORTED} if the option is valid but not supported on this platform. */ public static native int setOption(final Context context, final int option, final int value); /** * Returns the version of the libusb runtime. * * @return The version of the libusb runtime. */ public static native Version getVersion(); /** * Returns a list of USB devices currently attached to the system. * * This is your entry point into finding a USB device to operate. * * You are expected to unreference all the devices when you are done with * them, and then free the list with * {@link #freeDeviceList(DeviceList, boolean)}. Note that * {@link #freeDeviceList(DeviceList, boolean)} can unref all the devices * for you. Be careful not to unreference a device you are about to open * until after you have opened it. * * @param context * The context to operate on, or NULL for the default context. * @param list * Output location for a list of devices. Must be later freed * with {@link #freeDeviceList(DeviceList, boolean)}. * @return The number of devices in the outputted list, or any ERROR code * according to errors encountered by the backend. */ public static native int getDeviceList(final Context context, final DeviceList list); /** * Frees a list of devices previously discovered using * {@link #getDeviceList(Context, DeviceList)}. * * If the unref_devices parameter is set, the reference count of each device * in the list is decremented by 1. * * @param list * The list to free. * @param unrefDevices * Whether to unref the devices in the list. */ public static native void freeDeviceList(final DeviceList list, final boolean unrefDevices); /** * Get the number of the bus that a device is connected to. * * @param device * A device. * @return The bus number */ public static native int getBusNumber(final Device device); /** * Get the number of the port that a device is connected to. * * @param device * A device * @return The port number (0 if not available). */ public static native int getPortNumber(final Device device); /** * Get the list of all port numbers from root for the specified device. * * @param device * A device. * @param path * The array that should contain the port numbers. As per the USB * 3.0 specs, the current maximum limit for the depth is 7. * @return The number of elements filled, {@link #ERROR_OVERFLOW} if the * array is too small */ public static native int getPortNumbers(final Device device, final ByteBuffer path); /** * Get the list of all port numbers from root for the specified device. * * @deprecated Please use {@link #getPortNumbers(Device, ByteBuffer)} * instead. * * @param context * The context. * @param device * A device. * @param path * The array that should contain the port numbers. As per the USB * 3.0 specs, the current maximum limit for the depth is 7. * @return The number of elements filled, {@link #ERROR_OVERFLOW} if the * array is too small */ @Deprecated public static int getPortPath(final Context context, final Device device, final ByteBuffer path) { return getPortNumbers(device, path); } /** * Get the the parent from the specified device [EXPERIMENTAL]. * * Please note that the reference count of the returned device is not * increased. As such, do not *ever* call {@link #unrefDevice(Device)} * directly on the returned Device. * * @param device * A device * @return The device parent or NULL if not available. You should issue a * {@link #getDeviceList(Context, DeviceList)} before calling this * function and make sure that you only access the parent before * issuing {@link #freeDeviceList(DeviceList, boolean)}. The reason * is that libusb currently does not maintain a permanent list of * device instances, and therefore can only guarantee that parents * are fully instantiated within a * {@link #getDeviceList(Context, DeviceList)} - * {@link #freeDeviceList(DeviceList, boolean)} block. */ public static native Device getParent(final Device device); /** * Get the address of the device on the bus it is connected to. * * @param device * A device. * @return The device address */ public static native int getDeviceAddress(final Device device); /** * Get the negotiated connection speed for a device. * * @param device * A device. * @return A SPEED code, where {@link #SPEED_UNKNOWN} means that the OS * doesn't know or doesn't support returning the negotiated speed. */ public static native int getDeviceSpeed(final Device device); /** * Convenience function to retrieve the wMaxPacketSize value for a * particular endpoint in the active device configuration. * * This function was originally intended to be of assistance when setting up * isochronous transfers, but a design mistake resulted in this function * instead. It simply returns the wMaxPacketSize value without considering * its contents. If you're dealing with isochronous transfers, you probably * want {@link #getMaxIsoPacketSize(Device, byte)} instead. * * @param device * A device. * @param endpoint * Address of the endpoint in question. * @return the wMaxPacketSize value {@link #ERROR_NOT_FOUND} if the endpoint * does not exist {@link #ERROR_OTHER} on other failure */ public static native int getMaxPacketSize(final Device device, final byte endpoint); /** * Calculate the maximum packet size which a specific endpoint is capable * sending or receiving in the duration of 1 microframe. * * Only the active configuration is examined. The calculation is based on * the wMaxPacketSize field in the endpoint descriptor as described in * section 9.6.6 in the USB 2.0 specifications. * * If acting on an isochronous or interrupt endpoint, this function will * multiply the value found in bits 0:10 by the number of transactions per * microframe (determined by bits 11:12). Otherwise, this function just * returns the numeric value found in bits 0:10. * * This function is useful for setting up isochronous transfers, for example * you might pass the return value from this function to * {@link #setIsoPacketLengths(Transfer, int)} in order to set the length * field of every isochronous packet in a transfer. * * @param device * A device. * @param endpoint * Address of the endpoint in question. * @return The maximum packet size which can be sent/received on this * endpoint {@link #ERROR_NOT_FOUND} if the endpoint does not exist * {@link #ERROR_OTHER} on other failure. */ public static native int getMaxIsoPacketSize(final Device device, final byte endpoint); /** * Increment the reference count of a device. * * @param device * The device to reference. * @return The same device. */ public static native Device refDevice(final Device device); /** * Decrement the reference count of a device. * * If the decrement operation causes the reference count to reach zero, the * device shall be destroyed. * * @param device * the device to unreference. */ public static native void unrefDevice(final Device device); /** * Open a device and obtain a device handle. * * A handle allows you to perform I/O on the device in question. * * Internally, this function adds a reference to the device and makes it * available to you through {@link #getDevice(DeviceHandle)}. This reference * is removed during {@link #close(DeviceHandle)}. * * This is a non-blocking function; no requests are sent over the bus. * * @param device * The device to open. * @param handle * Output location for the returned device handle pointer. Only * populated when the return code is 0. * @return 0 on success, {@link #ERROR_NO_MEM} on memory allocation failure, * {@link #ERROR_ACCESS} if the user has insufficient permissions, * {@link #ERROR_NO_DEVICE} if the device has been disconnected, * another error on other failure */ public static native int open(final Device device, final DeviceHandle handle); /** * Convenience function for finding a device with a particular * idVendor/idProduct combination. * * This function is intended for those scenarios where you are using libusb * to knock up a quick test application - it allows you to avoid calling * {@link #getDeviceList(Context, DeviceList)} and worrying about * traversing/freeing the list. * * This function has limitations and is hence not intended for use in real * applications: if multiple devices have the same IDs it will only give you * the first one, etc. * * @param context * The context to operate on, or NULL for the default context. * @param vendorId * The idVendor value to search for. * @param productId * The idProduct value to search for. * @return A handle for the first found device or NULL on error or if the * device could not be found. */ public static native DeviceHandle openDeviceWithVidPid( final Context context, final short vendorId, final short productId); /** * Close a device handle. * * Should be called on all open handles before your application exits. * * Internally, this function destroys the reference that was added by * {@link #open(Device, DeviceHandle)} on the given device. * * This is a non-blocking function; no requests are sent over the bus. * * @param handle * The handle to close. */ public static native void close(final DeviceHandle handle); /** * Get the underlying device for a handle. * * Please note that the reference count of the returned device is not * increased. As such, do not *ever* call {@link #unrefDevice(Device)} * directly on the returned Device. * * @param handle * a device handle. * @return The underlying device. */ public static native Device getDevice(final DeviceHandle handle); /** * Determine the bConfigurationValue of the currently active configuration. * * You could formulate your own control request to obtain this information, * but this function has the advantage that it may be able to retrieve the * information from operating system caches (no I/O involved). * * If the OS does not cache this information, then this function will block * while a control transfer is submitted to retrieve the information. * * This function will return a value of 0 in the config output parameter if * the device is in unconfigured state. * * @param handle * a device handle. * @param config * output location for the bConfigurationValue of the active * configuration (only valid for return code 0) * @return 0 on success {@link #ERROR_NO_DEVICE} if the device has been * disconnected another error code on other failure */ public static native int getConfiguration(final DeviceHandle handle, final IntBuffer config); /** * Set the active configuration for a device. * * The operating system may or may not have already set an active * configuration on the device. It is up to your application to ensure the * correct configuration is selected before you attempt to claim interfaces * and perform other operations. * * If you call this function on a device already configured with the * selected configuration, then this function will act as a lightweight * device reset: it will issue a SET_CONFIGURATION request using the current * configuration, causing most USB-related device state to be reset * (altsetting reset to zero, endpoint halts cleared, toggles reset). * * You cannot change/reset configuration if your application has claimed * interfaces - you should free them with * {@link #releaseInterface(DeviceHandle, int)} first. You cannot * change/reset configuration if other applications or drivers have claimed * interfaces. * * A configuration value of -1 will put the device in unconfigured state. * The USB specifications state that a configuration value of 0 does this, * however buggy devices exist which actually have a configuration 0. * * You should always use this function rather than formulating your own * SET_CONFIGURATION control request. This is because the underlying * operating system needs to know when such changes happen. * * This is a blocking function. * * @param handle * a device handle. * @param config * the bConfigurationValue of the configuration you wish to * activate, or -1 if you wish to put the device in unconfigured * state * @return 0 on success, {@link #ERROR_NOT_FOUND} if the requested * configuration does not exist, {@link #ERROR_BUSY} if interfaces * are currently claimed, {@link #ERROR_NO_DEVICE} if the device has * been disconnected, another error code on other failure */ public static native int setConfiguration(final DeviceHandle handle, final int config); /** * Claim an interface on a given device handle. * * You must claim the interface you wish to use before you can perform I/O * on any of its endpoints. * * It is legal to attempt to claim an already-claimed interface, in which * case libusb just returns 0 without doing anything. * * Claiming of interfaces is a purely logical operation; it does not cause * any requests to be sent over the bus. Interface claiming is used to * instruct the underlying operating system that your application wishes to * take ownership of the interface. * * This is a non-blocking function. * * @param handle * A device handle. * @param iface * The bInterfaceNumber of the interface you wish to claim. * @return 0 on success, {@link #ERROR_NOT_FOUND} if the requested interface * does not exist, {@link #ERROR_BUSY} if another program or driver * has claimed the interface, {@link #ERROR_NO_DEVICE} if the device * has been disconnected, another error code on other failure */ public static native int claimInterface(final DeviceHandle handle, final int iface); /** * Release an interface previously claimed with * {@link #claimInterface(DeviceHandle, int)}. * * You should release all claimed interfaces before closing a device handle. * * This is a blocking function. A SET_INTERFACE control request will be sent * to the device, resetting interface state to the first alternate setting. * * @param handle * a device handle. * @param iface * The bInterfaceNumber of the previously-claimed interface * @return 0 on success, {@link #ERROR_NOT_FOUND} if the interface was not * claimed, {@link #ERROR_NO_DEVICE} if the device has been * disconnected, another ERROR code on other failure */ public static native int releaseInterface(final DeviceHandle handle, final int iface); /** * Activate an alternate setting for an interface. * * The interface must have been previously claimed with * {@link #claimInterface(DeviceHandle, int)}. * * You should always use this function rather than formulating your own * SET_INTERFACE control request. This is because the underlying operating * system needs to know when such changes happen. * * This is a blocking function. * * @param handle * A device handle. * @param interfaceNumber * The bInterfaceNumber of the previously-claimed interface * @param alternateSetting * The bAlternateSetting of the alternate setting to activate * @return 0 on success, {@link #ERROR_NOT_FOUND} if the interface was not * claimed, or the requested alternate setting does not exist * {@link #ERROR_NO_DEVICE} if the device has been disconnected, * another ERROR code on other failure */ public static native int setInterfaceAltSetting(final DeviceHandle handle, final int interfaceNumber, final int alternateSetting); /** * Clear the halt/stall condition for an endpoint. * * Endpoints with halt status are unable to receive or transmit data until * the halt condition is stalled. * * You should cancel all pending transfers before attempting to clear the * halt condition. * * This is a blocking function. * * @param handle * A device handle. * @param endpoint * The endpoint to clear halt status * @return 0 on success, {@link #ERROR_NOT_FOUND} if the endpoint does not * exist, {@link #ERROR_NO_DEVICE} if the device has been * disconnected, another ERROR code on other failure. */ public static native int clearHalt(final DeviceHandle handle, final byte endpoint); /** * Perform a USB port reset to reinitialize a device. * * The system will attempt to restore the previous configuration and * alternate settings after the reset has completed. * * If the reset fails, the descriptors change, or the previous state cannot * be restored, the device will appear to be disconnected and reconnected. * This means that the device handle is no longer valid (you should close * it) and rediscover the device. A return code of {@link #ERROR_NOT_FOUND} * indicates when this is the case. * * This is a blocking function which usually incurs a noticeable delay. * * @param handle * a handle of the device to reset * @return 0 on success, {@link #ERROR_NOT_FOUND} if re-enumeration is * required, or if the device has been disconnected another ERROR * code on other failure */ public static native int resetDevice(final DeviceHandle handle); /** * Allocate up to numStreams USB bulk streams on the specified endpoints. * This function takes an array of endpoints rather then a single endpoint * because some protocols require that endpoints are setup with similar * stream ids. All endpoints passed in must belong to the same interface. * * Note that this function may return less streams then requested. * * Stream id 0 is reserved, and should not be used to communicate with * devices. If LibUsb.allocStreams() returns with a value of N, you may * use stream ids 1 to N. * * @param handle * a device handle * @param numStreams * number of streams to try to allocate * @param endpoints * array of endpoints to allocate streams on * @return The number of streams allocated, or a LIBUSB_ERROR code * on failure. */ public static native int allocStreams(final DeviceHandle handle, final int numStreams, final byte[] endpoints); /** * Free USB bulk streams allocated with LibUsb.allocStreams(). * * Note streams are automatically free-ed when releasing an interface. * * @param handle * a device handle * @param endpoints * array of endpoints to allocate streams on * @return 0 on success, or a LIBUSB_ERROR code on failure. */ public static native int freeStreams(final DeviceHandle handle, final byte[] endpoints); /** * Attempts to allocate a block of persistent DMA memory suitable for transfers against the given device. * * If successful, will return a block of memory that is suitable for use as "buffer" in {@link Transfer} * against this device. Using this memory instead of regular memory means that the host controller can use DMA * directly into the buffer to increase performance, and also that transfers can no longer fail due to kernel * memory fragmentation. * * Note that this means you should not modify this memory (or even data on the same cache lines) when a transfer * is in progress, although it is legal to have several transfers going on within the same memory block. * * Will return NULL on failure. Many systems do not support such zerocopy and will always return NULL. Memory * allocated with this function must be freed with {@link #devMemFree(DeviceHandle, ByteBuffer, int)}. * Specifically, this means that the flag {@link #TRANSFER_FREE_BUFFER} cannot be used to free memory * allocated with this function. * * @param handle * A device handle. * @param length * Size of desired data buffer. * @return The newly allocated memory, or NULL on failure. */ public static native ByteBuffer devMemAlloc(final DeviceHandle handle, final int length); /** * Free device memory allocated with {@link #devMemAlloc(DeviceHandle, int)}. * * @param handle * A device handle. * @param buffer * The previously allocated memory. * @param size * The size of the previously allocated memory. * @return {@link #SUCCESS}, or a LIBUSB_ERROR code on failure. */ public static native int devMemFree(final DeviceHandle handle, final ByteBuffer buffer, final int size); /** * Determine if a kernel driver is active on an interface. * * If a kernel driver is active, you cannot claim the interface, and libusb * will be unable to perform I/O. * * This functionality is not available on Windows. * * @param handle * A device handle. * @param interfaceNumber * The interface to check. * @return 0 if no kernel driver is active, 1 if a kernel driver is active, * {@link #ERROR_NO_DEVICE} if the device has been disconnected, * {@link #ERROR_NOT_SUPPORTED} on platforms where the functionality * is not available, another ERROR code on other failure * * @see #detachKernelDriver(DeviceHandle, int) */ public static native int kernelDriverActive(final DeviceHandle handle, final int interfaceNumber); /** * Detach a kernel driver from an interface. * * If successful, you will then be able to claim the interface and perform * I/O. * * This functionality is not available on Darwin or Windows. * * Note that libusb itself also talks to the device through a special * kernel driver, if this driver is already attached to the device, this * call will not detach it and return {@link #ERROR_NOT_FOUND}. * * @param handle * a device handle * @param interfaceNumber * the interface to detach the driver from * @return 0 on success, {@link #ERROR_NOT_FOUND} if no kernel driver was * active, {@link #ERROR_INVALID_PARAM} if the interface does not * exist, {@link #ERROR_NO_DEVICE} if the device has been * disconnected, {@link #ERROR_NOT_SUPPORTED} on platforms where the * functionality is not available, another ERROR code on other * failure * * @see #kernelDriverActive(DeviceHandle, int) */ public static native int detachKernelDriver(final DeviceHandle handle, final int interfaceNumber); /** * Re-attach an interface's kernel driver, which was previously detached * using {@link #detachKernelDriver(DeviceHandle, int)}. * * This call is only effective on Linux and returns * {@link #ERROR_NOT_SUPPORTED} on all other platforms. * * This functionality is not available on Darwin or Windows. * * @param handle * A device handle * @param interfaceNumber * the interface to attach the driver from * @return 0 on success, {@link #ERROR_NOT_FOUND} if no kernel driver was * active, {@link #ERROR_INVALID_PARAM} if the interface does not * exist, {@link #ERROR_NO_DEVICE} if the device has been * disconnected, {@link #ERROR_NOT_SUPPORTED} on platforms where the * functionality is not available, {@link #ERROR_BUSY} if the driver * cannot be attached because the interface is claimed by a program * or driver, anotherERROR code on other failure * * @see #kernelDriverActive(DeviceHandle, int) */ public static native int attachKernelDriver(final DeviceHandle handle, final int interfaceNumber); /** * Enable/disable libusb's automatic kernel driver detachment. * * When this is enabled libusb will automatically detach the kernel driver * on an interface when claiming the interface, and attach it when releasing * the interface. * * Automatic kernel driver detachment is disabled on newly opened device * handles by default. * * On platforms which do not have {@link #CAP_SUPPORTS_DETACH_KERNEL_DRIVER} * this function will return {@link #ERROR_NOT_SUPPORTED}, and libusb will * continue as if this function was never called. * * @param handle * A device handle. * @param enable * Whether to enable or disable auto kernel driver detachment * @return {@link #SUCCESS} on success, {@link #ERROR_NOT_SUPPORTED} on * platforms where the functionality is not available. */ public static native int setAutoDetachKernelDriver( final DeviceHandle handle, final boolean enable); /** * Check at runtime if the loaded library has a given capability. * * @param capability * The capability to check for. * @return True if the running library has the capability, false otherwise. */ public static native boolean hasCapability(final int capability); /** * Returns a string with the ASCII name of a libusb error or transfer status * code. * * @param errorCode * The libusb error or libusb transfer status code to return the * name of. * @return The error name, or the string **UNKNOWN** if the value of * errorCode is not a known error / status code. */ public static native String errorName(final int errorCode); /** * Set the language, and only the language, not the encoding! used for * translatable libusb messages. * * This takes a locale string in the default setlocale format: lang[-region] * or lang[_country_region][.codeset]. Only the lang part of the string is * used, and only 2 letter ISO 639-1 codes are accepted for it, such as * "de". The optional region, country_region or codeset parts are ignored. * This means that functions which return translatable strings will NOT * honor the specified encoding. All strings returned are encoded as UTF-8 * strings. * * If {@link #setLocale(String)} is not called, all messages will be in * English. * * The following functions return translatable strings: libusb_strerror(). * Note that the libusb log messages controlled through * {@link #setDebug(Context, int)} are not translated, they are always in * English. * * @param locale * locale-string in the form of lang[_country_region][.codeset] * or lang[-region], where lang is a 2 letter ISO 639-1 code. * @return {@link #SUCCESS} on success, {@link #ERROR_INVALID_PARAM} if the * locale doesn't meet the requirements, {@link #ERROR_NOT_FOUND} if * the requested language is not supported, a error code on other * errors. */ public static native int setLocale(final String locale); /** * Returns a string with a short description of the given error code, this * description is intended for displaying to the end user and will be in the * language set by {@link #setLocale(String)}. * * The messages always start with a capital letter and end without any dot. * * @param errcode * The error code whose description is desired. * @return A short description of the error code. */ public static native String strError(final int errcode); /** * Convert a 16-bit value from little-endian to host-endian format. * * On little endian systems, this function does nothing. On big endian * systems, the bytes are swapped. * * @param x * The little-endian value to convert * @return the value in host-endian byte order */ public static native short le16ToCpu(final short x); /** * Convert a 16-bit value from host-endian to little-endian format. * * On little endian systems, this function does nothing. On big endian * systems, the bytes are swapped. * * @param x * The host-endian value to convert * @return the value in little-endian byte order */ public static native short cpuToLe16(final short x); /** * Get the USB device descriptor for a given device. * * This is a non-blocking function; the device descriptor is cached in * memory. * * @param device * the device * @param descriptor * output location for the descriptor data * @return 0 on success or a ERROR code on failure */ public static native int getDeviceDescriptor(final Device device, final DeviceDescriptor descriptor); /** * Returns the size in bytes of the buffer that's required to hold all * of a device descriptor's data. * * @return buffer size in bytes */ static native int deviceDescriptorStructSize(); /** * Retrieve a string descriptor in C style ASCII. * * @param handle * A device handle. * @param index * The index of the descriptor to retrieve. * @param string * Output buffer for ASCII string descriptor. * @return Number of bytes returned in data, or ERROR code on failure. */ public static native int getStringDescriptorAscii( final DeviceHandle handle, final byte index, final StringBuffer string); /** * A simple wrapper around * {@link #getStringDescriptorAscii(DeviceHandle, byte, StringBuffer)}. * It simply returns the string (maximum length of 127) if possible. If not * possible (NULL handle or 0-index specified or error occurred) then null is * returned. * * This method is not part of libusb. * * @param handle * The device handle. * @param index * The string descriptor index. * @return The string or null if it could not be read. */ public static String getStringDescriptor(final DeviceHandle handle, final byte index) { if ((handle == null) || (index == 0)) { return null; } final StringBuffer buffer = new StringBuffer(); if (getStringDescriptorAscii(handle, index, buffer) >= 0) { return buffer.toString(); } return null; } /** * Get the USB configuration descriptor for the currently active * configuration. * * This is a non-blocking function which does not involve any requests being * sent to the device. * * @param device * A device. * @param descriptor * Output location for the USB configuration descriptor. Only * valid if 0 was returned. Must be freed with * {@link #freeConfigDescriptor(ConfigDescriptor)} after use. * @return 0 on success, {@link #ERROR_NOT_FOUND} if the device is in * unconfigured state another ERROR code on error * * @see #getConfigDescriptor(Device, byte, ConfigDescriptor) */ public static native int getActiveConfigDescriptor(final Device device, final ConfigDescriptor descriptor); /** * Get a USB configuration descriptor based on its index. * * This is a non-blocking function which does not involve any requests being * sent to the device. * * @param device * A device. * @param index * The index of the configuration you wish to retrieve * @param descriptor * Output location for the USB configuration descriptor. Only * valid if 0 was returned. Must be freed with * {@link #freeConfigDescriptor(ConfigDescriptor)} after use. * @return 0 on success {@link #ERROR_NOT_FOUND} if the configuration does * not exist another ERROR code on error. * * @see #getActiveConfigDescriptor(Device, ConfigDescriptor) * @see #getConfigDescriptorByValue(Device, byte, ConfigDescriptor) */ public static native int getConfigDescriptor(final Device device, final byte index, final ConfigDescriptor descriptor); /** * Get a USB configuration descriptor with a specific bConfigurationValue. * * This is a non-blocking function which does not involve any requests being * sent to the device. * * @param device * A device. * @param value * The bConfigurationValue of the configuration you wish to * retrieve. * @param descriptor * Output location for the USB configuration descriptor. Only * valid if 0 was returned. Must be freed with * {@link #freeConfigDescriptor(ConfigDescriptor)} after use. * @return 0 on success {@link #ERROR_NOT_FOUND} if the configuration does * not exist another ERROR code on error See also: * * @see #getActiveConfigDescriptor(Device, ConfigDescriptor) * @see #getConfigDescriptor(Device, byte, ConfigDescriptor) */ public static native int getConfigDescriptorByValue(final Device device, final byte value, final ConfigDescriptor descriptor); /** * Free a configuration descriptor obtained from * {@link #getConfigDescriptor(Device, byte, ConfigDescriptor)} or * {@link #getActiveConfigDescriptor(Device, ConfigDescriptor)}. * * It is safe to call this function with a NULL config parameter, in which * case the function simply returns. * * @param descriptor * The configuration descriptor to free */ public static native void freeConfigDescriptor( final ConfigDescriptor descriptor); /** * Get an endpoints superspeed endpoint companion descriptor (if any). * * @param context * The context to operate on, or NULL for the default context. * @param endpointDescriptor * Endpoint descriptor from which to get the superspeed endpoint * companion descriptor. * @param companionDescriptor * Output location for the superspeed endpoint companion * descriptor. Only valid if 0 was returned. Must be freed with * {@link #freeSsEndpointCompanionDescriptor * (SsEndpointCompanionDescriptor)} * after use. * @return {@link #SUCCESS} on success, {@link #ERROR_NOT_FOUND} if the * descriptor does not exist, another error code on error */ public static native int getSsEndpointCompanionDescriptor( final Context context, final EndpointDescriptor endpointDescriptor, final SsEndpointCompanionDescriptor companionDescriptor); /** * Free a superspeed endpoint companion descriptor obtained from * {@link #getSsEndpointCompanionDescriptor(Context, EndpointDescriptor, * SsEndpointCompanionDescriptor)}. * * It is safe to call this function with a NULL parameter, in which case the * function simply returns. * * @param companionDescriptor * The superspeed endpoint companion descriptor to free */ public static native void freeSsEndpointCompanionDescriptor( final SsEndpointCompanionDescriptor companionDescriptor); /** * Get a Binary Object Store (BOS) descriptor. This is a BLOCKING function, * which will send requests to the device. * * @param handle * The handle of an open libusb device. * @param descriptor * Output location for the BOS descriptor. Only valid if 0 was * returned. Must be freed with * {@link #freeBosDescriptor(BosDescriptor)} after use. * @return {@link #SUCCESS} on success, {@link #ERROR_NOT_FOUND} if the * device doesn't have a BOS descriptor, another error code on error */ public static native int getBosDescriptor(final DeviceHandle handle, final BosDescriptor descriptor); /** * Free a BOS descriptor obtained from * {@link #getBosDescriptor(DeviceHandle, BosDescriptor)}. * * It is safe to call this function with a NULL parameter, in which case the * function simply returns. * * @param descriptor * The BOS descriptor to free. */ public static native void freeBosDescriptor(final BosDescriptor descriptor); /** * Get an USB 2.0 Extension descriptor. * * @param context * The context to operate on, or NULL for the default context. * @param devCapDescriptor * Device Capability descriptor with a bDevCapabilityType of * {@link #BT_USB_2_0_EXTENSION}. * @param extensionDescriptor * Output location for the USB 2.0 Extension descriptor. Only * valid if 0 was returned. Must be freed with * {@link #freeUsb20ExtensionDescriptor( * Usb20ExtensionDescriptor)} after use. * @return 0 on success a LIBUSB_ERROR code on error */ public static native int getUsb20ExtensionDescriptor(final Context context, final BosDevCapabilityDescriptor devCapDescriptor, final Usb20ExtensionDescriptor extensionDescriptor); /** * Free a USB 2.0 Extension descriptor obtained from * {@link #getUsb20ExtensionDescriptor(Context, BosDevCapabilityDescriptor, * Usb20ExtensionDescriptor)}. * * It is safe to call this function with a NULL parameter, in which case * the function simply returns. * * @param extensionDescriptor * The USB 2.0 Extension descriptor to free. */ public static native void freeUsb20ExtensionDescriptor( final Usb20ExtensionDescriptor extensionDescriptor); /** * Get a SuperSpeed USB Device Capability descriptor. * * @param context * The context to operate on, or NULL for the default context. * @param devCapDescriptor * Device Capability descriptor with a bDevCapabilityType of * {@link #BT_SS_USB_DEVICE_CAPABILITY}. * @param ssUsbDeviceCapabilityDescriptor * Output location for the SuperSpeed USB Device Capability * descriptor. Only valid if {@link #SUCCESS} was returned. * Must be freed with * {@link #freeSsUsbDeviceCapabilityDescriptor( * SsUsbDeviceCapabilityDescriptor)} after use. * @return {@link #SUCCESS} on success, an error code on error. */ public static native int getSsUsbDeviceCapabilityDescriptor( final Context context, final BosDevCapabilityDescriptor devCapDescriptor, final SsUsbDeviceCapabilityDescriptor ssUsbDeviceCapabilityDescriptor); /** * Free a SuperSpeed USB Device Capability descriptor obtained from * {@link #getSsUsbDeviceCapabilityDescriptor(Context, * BosDevCapabilityDescriptor, SsUsbDeviceCapabilityDescriptor)}. * * It is safe to call this function with a NULL parameter, * in which case the function simply returns. * * @param ssUsbDeviceCapabilityDescriptor * The descriptor to free. */ public static native void freeSsUsbDeviceCapabilityDescriptor( final SsUsbDeviceCapabilityDescriptor ssUsbDeviceCapabilityDescriptor); /** * Get a Container ID descriptor. * * @param context * The context to operate on, or NULL for the default context. * @param devCapDescriptor * Device Capability descriptor with a bDevCapabilityType of * {@link #BT_CONTAINER_ID}. * @param containerIdDescriptor * Output location for the Container ID descriptor. Only valid if * {@link #SUCCESS} was returned. Must be freed with * {@link #freeContainerIdDescriptor(ContainerIdDescriptor)} * after use. * @return {@link #SUCCESS} on success or an error code on error */ public static native int getContainerIdDescriptor(final Context context, final BosDevCapabilityDescriptor devCapDescriptor, final ContainerIdDescriptor containerIdDescriptor); /** * Free a Container ID descriptor obtained from * {@link #getContainerIdDescriptor(Context, BosDevCapabilityDescriptor, * ContainerIdDescriptor)}. * * It is safe to call this function with a NULL parameter, in which case * the function simply returns. * * @param containerIdDescriptor * The descriptor to free. */ public static native void freeContainerIdDescriptor( final ContainerIdDescriptor containerIdDescriptor); /** * Retrieve a descriptor from the default control pipe. * * This is a convenience function which formulates the appropriate control * message to retrieve the descriptor. * * @param handle * A device handle. * @param type * The descriptor type, see DT_* constants. * @param index * The index of the descriptor to retrieve. * @param data * Output buffer for descriptor * @return number of bytes returned in data, or ERROR code on failure * */ public static int getDescriptor(final DeviceHandle handle, final byte type, final byte index, final ByteBuffer data) { return controlTransfer(handle, ENDPOINT_IN, REQUEST_GET_DESCRIPTOR, (short) (((type & 0xff) << 8) | (index & 0xff)), (short) 0, data, 1000); } /** * Retrieve a descriptor from a device. * * This is a convenience function which formulates the appropriate control * message to retrieve the descriptor. The string returned is Unicode, as * detailed in the USB specifications. * * @param handle * A device handle. * @param index * The index of the descriptor to retrieve. * @param langId * The language ID for the string descriptor. * @param data * Output buffer for descriptor. * @return number of bytes returned in data, or LIBUSB_ERROR code on failure * @see #getStringDescriptorAscii(DeviceHandle, byte, StringBuffer) */ public static int getStringDescriptor(final DeviceHandle handle, final byte index, final short langId, final ByteBuffer data) { return controlTransfer(handle, ENDPOINT_IN, REQUEST_GET_DESCRIPTOR, (short) ((DT_STRING << 8) | (index & 0xff)), langId, data, 1000); } /** * Perform a USB control transfer. * * The direction of the transfer is inferred from the bmRequestType field of * the setup packet. * * The wValue, wIndex and wLength fields values should be given in * host-endian byte order. * * @param handle * A handle for the device to communicate with. * @param bmRequestType * The request type field for the setup packet. * @param bRequest * The request field for the setup packet. * @param wValue * The value field for the setup packet. * @param wIndex * The index field for the setup packet. * @param data * A suitably-sized data buffer for either input or output * (depending on direction bits within bmRequestType). * @param timeout * Timeout (in milliseconds) that this function should wait before * giving up due to no response being received. For an unlimited * timeout, use value 0. * @return on success the number of bytes actually transferred, * {@link #ERROR_TIMEOUT} if the transfer timed out, * {@link #ERROR_PIPE} if the control request was not supported by the device, * {@link #ERROR_NO_DEVICE} if the device has been disconnected, * {@link #ERROR_BUSY} if called from event handling context, * {@link #ERROR_INVALID_PARAM} if the transfer size is larger than the operating system and/or * hardware can support. * Another ERROR code on other failures */ public static native int controlTransfer(final DeviceHandle handle, final byte bmRequestType, final byte bRequest, final short wValue, final short wIndex, final ByteBuffer data, final long timeout); /** * Perform a USB bulk transfer. * * The direction of the transfer is inferred from the direction bits of the * endpoint address. * * For bulk reads, the length field indicates the maximum length of data you * are expecting to receive. If less data arrives than expected, this * function will return that data, so be sure to check the transferred * output parameter. * * You should also check the transferred parameter for bulk writes. Not all * of the data may have been written. * * Also check transferred when dealing with a timeout error code. libusb * may have to split your transfer into a number of chunks to satisfy * underlying O/S requirements, meaning that the timeout may expire after * the first few chunks have completed. libusb is careful not to lose any * data that may have been transferred; do not assume that timeout * conditions indicate a complete lack of I/O. * * @param handle * A handle for the device to communicate with. * @param endpoint * The address of a valid endpoint to communicate with. * @param data * A suitably-sized data buffer for either input or output * (depending on endpoint). * @param transferred * Output location for the number of bytes actually transferred. * @param timeout * timeout (in milliseconds) that this function should wait before * giving up due to no response being received. For an unlimited * timeout, use value 0. * @return 0 on success (and populates transferred), {@link #ERROR_TIMEOUT} * if the transfer timed out (and populates transferred), * {@link #ERROR_PIPE} if the endpoint halted, * {@link #ERROR_OVERFLOW} if the device offered more data, see * Packets and overflows, {@link #ERROR_NO_DEVICE} if the device has * been disconnected, another ERROR code on other failures. */ public static native int bulkTransfer(final DeviceHandle handle, final byte endpoint, final ByteBuffer data, final IntBuffer transferred, final long timeout); /** * Perform a USB interrupt transfer. * * The direction of the transfer is inferred from the direction bits of the * endpoint address. * * For interrupt reads, the length field indicates the maximum length of * data you are expecting to receive. If less data arrives than expected, * this function will return that data, so be sure to check the transferred * output parameter. * * You should also check the transferred parameter for interrupt writes. Not * all of the data may have been written. * * Also check transferred when dealing with a timeout error code. libusb * may have to split your transfer into a number of chunks to satisfy * underlying O/S requirements, meaning that the timeout may expire after * the first few chunks have completed. libusb is careful not to lose any * data that may have been transferred; do not assume that timeout * conditions indicate a complete lack of I/O. * * The default endpoint bInterval value is used as the polling interval. * * @param handle * A handle for the device to communicate with. * @param endpoint * The address of a valid endpoint to communicate with. * @param data * A suitably-sized data buffer for either input or output * (depending on endpoint). * @param transferred * Output location for the number of bytes actually transferred. * @param timeout * Timeout (in milliseconds) that this function should wait before * giving up due to no response being received. For an unlimited * timeout, use value 0. * @return 0 on success (and populates transferred), {@link #ERROR_TIMEOUT} * if the transfer timed out, {@link #ERROR_PIPE} if the endpoint * halted, {@link #ERROR_OVERFLOW} if the device offered more data, * see Packets and overflows, {@link #ERROR_NO_DEVICE} if the device * has been disconnected, another ERROR code on other error */ public static native int interruptTransfer(final DeviceHandle handle, final byte endpoint, final ByteBuffer data, final IntBuffer transferred, final long timeout); /** * Attempt to acquire the event handling lock. * * This lock is used to ensure that only one thread is monitoring libusb * event sources at any one time. * * You only need to use this lock if you are developing an application which * calls poll() or select() on libusb's file descriptors directly. If you * stick to libusb's event handling loop functions (e.g. * {@link #handleEvents(Context)}) then you do not need to be concerned with * this locking. * * While holding this lock, you are trusted to actually be handling events. * If you are no longer handling events, you must call * {@link #unlockEvents(Context)} as soon as possible. * * @param context * The context to operate on, or NULL for the default context. * @return 0 if the lock was obtained successfully, 1 if the lock was not * obtained (i.e. another thread holds the lock) */ public static native int tryLockEvents(final Context context); /** * Acquire the event handling lock, blocking until successful acquisition if * it is contended. * * This lock is used to ensure that only one thread is monitoring libusb * event sources at any one time. * * You only need to use this lock if you are developing an application which * calls poll() or select() on libusb's file descriptors directly. If you * stick to libusb's event handling loop functions (e.g. * {@link #handleEvents(Context)}) then you do not need to be concerned with * this locking. * * While holding this lock, you are trusted to actually be handling events. * If you are no longer handling events, you must call * {@link #unlockEvents(Context)} as soon as possible. * * @param context * The context to operate on, or NULL for the default context. */ public static native void lockEvents(final Context context); /** * Release the lock previously acquired with {@link #tryLockEvents(Context)} * or {@link #lockEvents(Context)}. * * Releasing this lock will wake up any threads blocked on * {@link #waitForEvent(Context, long)}. * * @param context * The context to operate on, or NULL for the default context */ public static native void unlockEvents(final Context context); /** * Determine if it is still OK for this thread to be doing event handling. * * Sometimes, libusb needs to temporarily pause all event handlers, and * this is the function you should use before polling file descriptors to * see if this is the case. * * If this function instructs your thread to give up the events lock, you * should just continue the usual logic that is documented in Multi-threaded * applications and asynchronous I/O. On the next iteration, your thread * will fail to obtain the events lock, and will hence become an event * waiter. * * This function should be called while the events lock is held: you don't * need to worry about the results of this function if your thread is not * the current event handler. * * @param context * The context to operate on, or NULL for the default context. * @return 1 if event handling can start or continue, 0 if this thread must * give up the events lock */ public static native int eventHandlingOk(final Context context); /** * Determine if an active thread is handling events (i.e. if anyone is * holding the event handling lock). * * @param context * The context to operate on, or NULL for the default context. * @return 1 if a thread is handling events, 0 if there are no threads * currently handling events. */ public static native int eventHandlerActive(final Context context); /** * Interrupt any active thread that is handling events. * * This is mainly useful for interrupting a dedicated event handling thread when an application wishes to call * {@link #exit(Context)}. * * @param context * The context to operate on, or NULL for the default context. */ public static native void interruptEventHandler(final Context context); /** * Acquire the event waiters lock. * * This lock is designed to be obtained under the situation where you want * to be aware when events are completed, but some other thread is event * handling so calling {@link #handleEvents(Context)} is not allowed. * * You then obtain this lock, re-check that another thread is still handling * events, then call {@link #waitForEvent(Context, long)}. * * You only need to use this lock if you are developing an application which * calls poll() or select() on libusb's file descriptors directly, and may * potentially be handling events from 2 threads simultaneously. If you * stick to libusb's event handling loop functions (e.g. * {@link #handleEvents(Context)}) then you do not need to be concerned with * this locking. * * @param context * The context to operate on, or NULL for the default context. */ public static native void lockEventWaiters(final Context context); /** * Release the event waiters lock. * * @param context * The context to operate on, or NULL for the default context. */ public static native void unlockEventWaiters(final Context context); /** * Wait for another thread to signal completion of an event. * * Must be called with the event waiters lock held, see * {@link #lockEventWaiters(Context)}. * * This function will block until any of the following conditions are met: * * The timeout expires A transfer completes A thread releases the event * handling lock through {@link #unlockEvents(Context)} Condition 1 is * obvious. Condition 2 unblocks your thread after the callback for the * transfer has completed. Condition 3 is important because it means that * the thread that was previously handling events is no longer doing so, so * if any events are to complete, another thread needs to step up and start * event handling. * * This function releases the event waiters lock before putting your thread * to sleep, and reacquires the lock as it is being woken up. * * @param context * The context to operate on, or NULL for the default context. * @param timeout * Maximum timeout for this blocking function. A 0 value * indicates unlimited timeout. * * @return 0 after a transfer completes or another thread stops event * handling, 1 if the timeout expired */ public static native int waitForEvent(final Context context, final long timeout); /** * Handle any pending events. * * libusb determines "pending events" by checking if any timeouts have * expired and by checking the set of file descriptors for activity. * * If a zero timeval is passed, this function will handle any * already-pending events and then immediately return in non-blocking style. * * If a non-zero timeval is passed and no events are currently pending, this * function will block waiting for events to handle up until the specified * timeout. If an event arrives or a signal is raised, this function will * return early. * * If the parameter completed is not NULL then after obtaining the event * handling lock this function will return immediately if the integer * pointed to is not 0. This allows for race free waiting for the completion * of a specific transfer. * * The only way to implement this in Java is by passing a direct buffer, and * then accessing memory directly. IntBuffers can be direct, if they are * created as a view of a direct ByteBuffer, by using BufferUtils: * {@link BufferUtils#allocateIntBuffer()} * * @param context * the context to operate on, or NULL for the default context * @param timeout * the maximum time to block waiting for events, or 0 for * non-blocking mode. * @param completed * Buffer for completion integer to check, or NULL. * @return 0 on success, or a ERROR code on failure */ public static native int handleEventsTimeoutCompleted( final Context context, final long timeout, final IntBuffer completed); /** * Handle any pending events. * * Like {@link #handleEventsTimeoutCompleted(Context, long, IntBuffer)}, but * without the completed parameter, calling this function is equivalent to * calling {@link #handleEventsTimeoutCompleted(Context, long, IntBuffer)} * with a NULL completed parameter. * * This function is kept primarily for backwards compatibility. All new code * should call {@link #handleEventsCompleted(Context, IntBuffer)} or * {@link #handleEventsTimeoutCompleted(Context, long, IntBuffer)} to avoid * race conditions. * * @param context * The context to operate on, or NULL for the default context * @param timeout * The maximum time (In microseconds) to block waiting for * events, or an all zero timeval struct for non-blocking mode * @return 0 on success, or a ERROR code on failure */ public static native int handleEventsTimeout(final Context context, final long timeout); /** * Handle any pending events in blocking mode. * * There is currently a timeout hardcoded at 60 seconds but we plan to make * it unlimited in future. For finer control over whether this function is * blocking or non-blocking, or for control over the timeout, use * {@link #handleEventsTimeoutCompleted(Context, long, IntBuffer)} instead. * * This function is kept primarily for backwards compatibility. All new code * should call {@link #handleEventsCompleted(Context, IntBuffer)} or * {@link #handleEventsTimeoutCompleted(Context, long, IntBuffer)} to avoid * race conditions. * * @param context * The context to operate on, or NULL for the default context. * @return 0 on success, or a ERROR code on failure. */ public static native int handleEvents(final Context context); /** * Handle any pending events in blocking mode. * * Like {@link #handleEvents(Context)}, with the addition of a completed * parameter to allow for race free waiting for the completion of a specific * transfer. * * See {@link #handleEventsTimeoutCompleted(Context, long, IntBuffer)} for * details on the completed parameter. * * @param context * The context to operate on, or NULL for the default context. * @param completed * Buffer for completion integer to check, or NULL. * @return 0 on success, or a ERROR code on failure. */ public static native int handleEventsCompleted(final Context context, final IntBuffer completed); /** * Handle any pending events by polling file descriptors, without checking * if any other threads are already doing so. * * Must be called with the event lock held, see {@link #lockEvents(Context)} * . * * This function is designed to be called under the situation where you have * taken the event lock and are calling poll()/select() directly on libusb's * file descriptors (as opposed to using {@link #handleEvents(Context)} or * similar). You detect events on libusb's descriptors, so you then call * this function with a zero timeout value (while still holding the event * lock). * * @param context * The context to operate on, or NULL for the default context. * @param timeout * The maximum time (In microseconds) to block waiting for * events, or zero for non-blocking mode * @return 0 on success, or a ERROR code on failure. */ public static native int handleEventsLocked(final Context context, final long timeout); /** * Determines whether your application must apply special timing * considerations when monitoring libusb's file descriptors. * * This function is only useful for applications which retrieve and poll * libusb's file descriptors in their own main loop (The more advanced * option). * * Ordinarily, libusb's event handler needs to be called into at specific * moments in time (in addition to times when there is activity on the file * descriptor set). The usual approach is to use * {@link #getNextTimeout(Context, LongBuffer)} to learn about when the next * timeout occurs, and to adjust your poll()/select() timeout accordingly so * that you can make a call into the library at that time. * * Some platforms supported by libusb do not come with this baggage - any * events relevant to timing will be represented by activity on the file * descriptor set, and {@link #getNextTimeout(Context, LongBuffer)} will * always return 0. This function allows you to detect whether you are * running on such a platform. * * @param context * The context to operate on, or NULL for the default context * @return 0 if you must call into libusb at times determined by * {@link #getNextTimeout(Context, LongBuffer)}, or 1 if all timeout * events are handled internally or through regular activity on the * file descriptors. */ public static native int pollfdsHandleTimeouts(final Context context); /** * Determine the next internal timeout that libusb needs to handle. * * You only need to use this function if you are calling poll() or select() * or similar on libusb's file descriptors yourself - you do not need to * use it if you are calling {@link #handleEvents(Context)} or a variant * directly. * * You should call this function in your main loop in order to determine how * long to wait for select() or poll() to return results. libusb needs to * be called into at this timeout, so you should use it as an upper bound on * your select() or poll() call. * * When the timeout has expired, call into * {@link #handleEventsTimeout(Context, long)} (perhaps in non-blocking * mode) so that libusb can handle the timeout. * * This function may return 1 (success) and an all-zero timeval. If this is * the case, it indicates that libusb has a timeout that has already * expired so you should call {@link #handleEventsTimeout(Context, long)} or * similar immediately. A return code of 0 indicates that there are no * pending timeouts. * * On some platforms, this function will always returns 0 (no pending * timeouts). See Notes on time-based events. * * @param context * The context to operate on, or NULL for the default context * @param timeout * Output location for a relative time against the current clock * in which libusb must be called into in order to process * timeout events * @return 0 if there are no pending timeouts, 1 if a timeout was returned, * or {@link #ERROR_OTHER} failure */ public static native int getNextTimeout(final Context context, final LongBuffer timeout); /** * Register notification functions for file descriptor additions/removals. * * These functions will be invoked for every new or removed file descriptor * that libusb uses as an event source. * * To remove notifiers, pass NULL values for the function pointers. * * Note that file descriptors may have been added even before you register * these notifiers (e.g. at {@link #init(Context)} time). * * Additionally, note that the removal notifier may be called during * {@link #exit(Context)} (e.g. when it is closing file descriptors that * were opened and added to the poll set at {@link #init(Context)} time). If * you don't want this, remove the notifiers immediately before calling * {@link #exit(Context)}. * * @param context * The context to operate on, or NULL for the default context. * @param listener * The listener for addition and removal notifications. * @param userData * User data to be passed back to callbacks (useful for passing * context information). */ public static synchronized void setPollfdNotifiers(final Context context, final PollfdListener listener, final Object userData) { long contextId; if (context == null) { // NULL pointer has value 0 contextId = 0; } else { contextId = context.getPointer(); } if (listener == null) { unsetPollfdNotifiersNative(context); pollfdListeners.remove(contextId); } else { setPollfdNotifiersNative(context, contextId); pollfdListeners.put(contextId, new ImmutablePair<PollfdListener, Object>(listener, userData)); } } /** * Callback function, invoked when a new file descriptor should be added to * the set of file descriptors monitored for events. * * @param fd * The new file descriptor, * @param events * events to monitor for, see libusb_pollfd for a description * @param contextId * A unique identifier for the originating context. */ static void triggerPollfdAdded(final FileDescriptor fd, final int events, final long contextId) { final ImmutablePair<PollfdListener, Object> listener = pollfdListeners .get(contextId); if (listener != null) { listener.left.pollfdAdded(fd, events, listener.right); } } /** * Called internally from JNI when a pollfd was removed. * * @param fd * The removed file descriptor. * @param contextId * A unique identifier for the originating context. */ static void triggerPollfdRemoved(final FileDescriptor fd, final long contextId) { final ImmutablePair<PollfdListener, Object> listener = pollfdListeners .get(contextId); if (listener != null) { listener.left.pollfdRemoved(fd, listener.right); } } /** * Configures libusb to inform this class about pollfd additions and * removals. * * @param context * The context to operate on, or NULL for the default context * @param contextId * A unique identifier for the given context. */ static native void setPollfdNotifiersNative(final Context context, final long contextId); /** * Tells libusb to stop informing this class about pollfd additions and * removals. * * @param context * The context to operate on, or NULL for the default context */ static native void unsetPollfdNotifiersNative(final Context context); /** * Retrieve a list of file descriptors that should be polled by your main loop as libusb event sources. * * The returned list should be freed with {@link #freePollfds(Pollfds)} when done. The actual list contents must not be * touched. * * As file descriptors are a Unix-specific concept, this function is not available on Windows and will always * return NULL. * * @param context * The context to operate on, or NULL for the default context. * @return A list of libusb_pollfd structures, NULL on error, NULL on platforms where the functionality is not * available. */ public static native Pollfds getPollfds(final Context context); /** * Free a list of {@link Pollfd} structures. * * This should be called for all pollfd lists allocated with {@link #getPollfds(Context)}. * * It is legal to call this function with a NULL pollfd list. In this case, the function will simply return safely. */ public static native void freePollfds(final Pollfds pollfds); /** * Allocate a libusb transfer without support for isochronous transfers. * * The returned transfer is pre-initialized for you. When the new transfer * is no longer needed, it should be freed with * {@link #freeTransfer(Transfer)}. * * @return A newly allocated transfer, or NULL on error */ public static Transfer allocTransfer() { return allocTransfer(0); } /** * Allocate a libusb transfer with a specified number of isochronous packet * descriptors. * * The returned transfer is pre-initialized for you. When the new transfer * is no longer needed, it should be freed with * {@link #freeTransfer(Transfer)}. * * Transfers intended for non-isochronous endpoints (e.g. control, bulk, * interrupt) should specify an iso_packets count of zero. * * For transfers intended for isochronous endpoints, specify an appropriate * number of packet descriptors to be allocated as part of the transfer. The * returned transfer is not specially initialized for isochronous I/O; you * are still required to call the {@link Transfer#setNumIsoPackets(int)} a * {@link Transfer#setType(byte)} methods accordingly. * * It is safe to allocate a transfer with some isochronous packets and then * use it on a non-isochronous endpoint. If you do this, ensure that at time * of submission, numIsoPackets is 0 and that type is set appropriately. * * @param isoPackets * Number of isochronous packet descriptors to allocate. * @return A newly allocated transfer, or NULL on error */ public static native Transfer allocTransfer(final int isoPackets); /** * Free a transfer structure. * * This should be called for all transfers allocated with * {@link #allocTransfer(int)}. * * Please refer to {@link #TRANSFER_FREE_BUFFER} for an explanation * of how buffers are freed. * * It is legal to call this function with a NULL transfer. In this case, the * function will simply return safely. * * It is not legal to free an active transfer (one which has been submitted * and has not yet completed). * * @param transfer * The transfer to free */ public static native void freeTransfer(final Transfer transfer); /** * Submit a transfer. * * This function will fire off the USB transfer and then return immediately. * * @param transfer * The transfer to submit * @return 0 on success, {@link #ERROR_NO_DEVICE} if the device has * been * disconnected, {@link #ERROR_BUSY} if the transfer has * already been * submitted. {@link #ERROR_NOT_SUPPORTED} if the transfer * flags are * not supported by the operating system. Another LIBUSB_ERROR code * on failure. */ public static native int submitTransfer(final Transfer transfer); /** * Asynchronously cancel a previously submitted transfer. * * This function returns immediately, but this does not indicate * cancellation * is complete. Your callback function will be invoked at some later time * with a transfer status of {@link #TRANSFER_CANCELLED}. * * @param transfer * The transfer to cancel * @return 0 on success, {@link #ERROR_NOT_FOUND} if the transfer is * already complete or cancelled. Another LIBUSB_ERROR code on * failure. */ public static native int cancelTransfer(final Transfer transfer); /** * Get the data section of a control transfer. * * This convenience function is here to remind you that the data does not * start until 8 bytes into the actual buffer, as the setup packet comes * first. * * Calling this function only makes sense from a transfer callback function, * or situations where you have already allocated a suitably sized buffer at * {@link Transfer#buffer()}. * * @param transfer * A transfer. * @return The data section. */ public static ByteBuffer controlTransferGetData(final Transfer transfer) { return BufferUtils.slice(transfer.buffer(), CONTROL_SETUP_SIZE, transfer.buffer().limit() - CONTROL_SETUP_SIZE); } /** * Get the control setup packet of a control transfer. * * This convenience function is here to remind you that the control setup * occupies the first 8 bytes of the transfer data buffer. * * Calling this function only makes sense from a transfer callback function, * or situations where you have already allocated a suitably sized buffer at * {@link Transfer#buffer()}. * * @param transfer * A transfer. * @return The setup section. */ public static ControlSetup controlTransferGetSetup(final Transfer transfer) { return new ControlSetup(transfer.buffer()); } /** * Helper function to populate the setup packet (first 8 bytes of the data * buffer) for a control transfer. * * The wIndex, wValue and wLength values should be given in host-endian byte * order. * * @param buffer * Buffer to output the setup packet into. * @param bmRequestType * See {@link ControlSetup#bmRequestType()}. * @param bRequest * See {@link ControlSetup#bRequest()}. * @param wValue * See {@link ControlSetup#wValue()}. * @param wIndex * See {@link ControlSetup#wIndex()}. * @param wLength * See {@link ControlSetup#wLength()}. */ public static void fillControlSetup(final ByteBuffer buffer, final byte bmRequestType, final byte bRequest, final short wValue, final short wIndex, final short wLength) { final ControlSetup setup = new ControlSetup(buffer); setup.setBmRequestType(bmRequestType); setup.setBRequest(bRequest); setup.setWValue(wValue); setup.setWIndex(wIndex); setup.setWLength(wLength); } /** * Helper function to populate the required {@link Transfer} fields for a * control transfer. * * If you pass a transfer buffer to this function, the first 8 bytes will be * interpreted as a control setup packet, and the wLength field will be used * to automatically populate the length field of the transfer. Therefore the * recommended approach is: * * 1. Allocate a suitably sized data buffer (including space for control * setup). * * 2. Call * {@link #fillControlSetup(ByteBuffer, byte, byte, short, short, short)}. * * 3. If this is a host-to-device transfer with a data stage, put the data * in place after the setup packet. * * 4. Call this function. * * 5. Call {@link #submitTransfer(Transfer)}. * * It is also legal to pass a NULL buffer to this function, in which case * this function will not attempt to populate the length field. Remember * that you must then populate the buffer and length fields later. * * @param transfer * The transfer to populate. * @param handle * Handle of the device that will handle the transfer. * @param buffer * Data buffer. If provided, this function will interpret the * first 8 bytes as a setup packet and infer the transfer length * from that. * @param callback * callback function to be invoked on transfer completion. * @param userData * User data to pass to callback function. * @param timeout * Timeout for the transfer in milliseconds. */ public static void fillControlTransfer(final Transfer transfer, final DeviceHandle handle, final ByteBuffer buffer, final TransferCallback callback, final Object userData, final long timeout) { transfer.setDevHandle(handle); transfer.setEndpoint((byte) 0); transfer.setType(TRANSFER_TYPE_CONTROL); transfer.setTimeout(timeout); transfer.setBuffer(buffer); transfer.setUserData(userData); transfer.setCallback(callback); // Set length based on wLength from Control Setup. final ControlSetup setup = new ControlSetup(buffer); transfer.setLength(CONTROL_SETUP_SIZE + (setup.wLength() & 0xFFFF)); } /** * Helper function to populate the required {@link Transfer} fields for a * bulk transfer. * * @param transfer * The transfer to populate. * @param handle * Handle of the device that will handle the transfer. * @param endpoint * Address of the endpoint where this transfer will be sent. * @param buffer * Data buffer. * @param callback * Callback function to be invoked on transfer completion. * @param userData * User data to pass to callback function. * @param timeout * Timeout for the transfer in milliseconds. */ public static void fillBulkTransfer(final Transfer transfer, final DeviceHandle handle, final byte endpoint, final ByteBuffer buffer, final TransferCallback callback, final Object userData, final long timeout) { transfer.setDevHandle(handle); transfer.setEndpoint(endpoint); transfer.setType(TRANSFER_TYPE_BULK); transfer.setTimeout(timeout); transfer.setBuffer(buffer); transfer.setUserData(userData); transfer.setCallback(callback); } /** * Helper function to populate the required {@link Transfer} fields * for a bulk transfer using bulk streams. * * @param transfer * The transfer to populate. * @param handle * Handle of the device that will handle the transfer. * @param endpoint * Address of the endpoint where this transfer will be sent. * @param streamId * Bulk stream id for this transfer. * @param buffer * Data buffer. * @param callback * Callback function to be invoked on transfer completion. * @param userData * User data to pass to callback function. * @param timeout * Timeout for the transfer in milliseconds. */ public static void fillBulkStreamTransfer(final Transfer transfer, final DeviceHandle handle, final byte endpoint, final int streamId, final ByteBuffer buffer, final TransferCallback callback, final Object userData, final long timeout) { fillBulkTransfer(transfer, handle, endpoint, buffer, callback, userData, timeout); transfer.setType(TRANSFER_TYPE_BULK_STREAM); transfer.setStreamId(streamId); } /** * Helper function to populate the required {@link Transfer} fields for an * interrupt transfer. * * @param transfer * The transfer to populate. * @param handle * Handle of the device that will handle the transfer. * @param endpoint * Address of the endpoint where this transfer will be sent. * @param buffer * Data buffer. * @param callback * Callback function to be invoked on transfer completion. * @param userData * User data to pass to callback function. * @param timeout * Timeout for the transfer in milliseconds. */ public static void fillInterruptTransfer(final Transfer transfer, final DeviceHandle handle, final byte endpoint, final ByteBuffer buffer, final TransferCallback callback, final Object userData, final long timeout) { transfer.setDevHandle(handle); transfer.setEndpoint(endpoint); transfer.setType(TRANSFER_TYPE_INTERRUPT); transfer.setTimeout(timeout); transfer.setBuffer(buffer); transfer.setUserData(userData); transfer.setCallback(callback); } /** * Helper function to populate the required {@link Transfer} fields for an * isochronous transfer. * * @param transfer * The transfer to populate. * @param handle * Handle of the device that will handle the transfer. * @param endpoint * Address of the endpoint where this transfer will be sent. * @param buffer * Data buffer. * @param numIsoPackets * The number of isochronous packets. * @param callback * Callback function to be invoked on transfer completion. * @param userData * User data to pass to callback function. * @param timeout * Timeout for the transfer in milliseconds. */ public static void fillIsoTransfer(final Transfer transfer, final DeviceHandle handle, final byte endpoint, final ByteBuffer buffer, final int numIsoPackets, final TransferCallback callback, final Object userData, final long timeout) { transfer.setDevHandle(handle); transfer.setEndpoint(endpoint); transfer.setType(TRANSFER_TYPE_ISOCHRONOUS); transfer.setTimeout(timeout); transfer.setBuffer(buffer); transfer.setNumIsoPackets(numIsoPackets); transfer.setUserData(userData); transfer.setCallback(callback); } /** * Convenience function to set the length of all packets in an isochronous * transfer, based on the {@link Transfer#numIsoPackets()} field. * * @param transfer * A transfer. * @param length * The length to set in each isochronous packet descriptor. * @see #getMaxPacketSize(Device, byte) */ public static void setIsoPacketLengths(final Transfer transfer, final int length) { for (final IsoPacketDescriptor isoDesc : transfer.isoPacketDesc()) { isoDesc.setLength(length); } } /** * Convenience function to locate the position of an isochronous packet * within the buffer of an isochronous transfer. * * This is a thorough function which loops through all preceding packets, * accumulating their lengths to find the position of the specified packet. * Typically you will assign equal lengths to each packet in the transfer, * and hence the above method is sub-optimal. You may wish to use * {@link #getIsoPacketBufferSimple(Transfer, int)} instead. * * @param transfer * A transfer. * @param packet * The packet to return the address of. * @return The base address of the packet buffer inside the transfer buffer, * or NULL if the packet does not exist. * @see #getIsoPacketBufferSimple(Transfer, int) */ public static ByteBuffer getIsoPacketBuffer(final Transfer transfer, final int packet) { if (packet >= transfer.numIsoPackets()) { return null; } final IsoPacketDescriptor[] isoDescriptors = transfer.isoPacketDesc(); int offset = 0; for (int i = 0; i < packet; i++) { offset += isoDescriptors[i].length(); } return BufferUtils.slice(transfer.buffer(), offset, isoDescriptors[packet].length()); } /** * Convenience function to locate the position of an isochronous packet * within the buffer of an isochronous transfer, for transfers where each * packet is of identical size. * * This function relies on the assumption that every packet within the * transfer is of identical size to the first packet. Calculating the * location of the packet buffer is then just a simple calculation: buffer + * (packet_size * packet) * * Do not use this function on transfers other than those that have * identical packet lengths for each packet. * * @param transfer * A transfer. * @param packet * The packet to return the address of. * @return The base address of the packet buffer inside the transfer buffer, * or NULL if the packet does not exist. * @see #getIsoPacketBuffer(Transfer, int) */ public static ByteBuffer getIsoPacketBufferSimple(final Transfer transfer, final int packet) { if (packet >= transfer.numIsoPackets()) { return null; } final IsoPacketDescriptor[] isoDescriptors = transfer.isoPacketDesc(); final int offset = isoDescriptors[0].length() * packet; return BufferUtils.slice(transfer.buffer(), offset, isoDescriptors[packet].length()); } /** * Processes a hotplug event from native code. * * @param context * Context of this notification. * @param device * The device this event occurred on. * @param event * Event that occurred * @param hotplugId * The hotplug ID. * @return Whether this callback is finished processing events. Returning 1 * will cause this callback to be deregistered. */ static int hotplugCallback(final Context context, final Device device, final int event, final long hotplugId) { final ImmutablePair<HotplugCallback, Object> callback = hotplugCallbacks .get(hotplugId); int result = 0; if (callback != null) { result = callback.left.processEvent(context, device, event, callback.right); } // If callback indicates it is finished, it will get deregistered // automatically. As such, we have to remove it from the Java // map, like when deregistering manually. if (result == 1) { hotplugCallbacks.remove(hotplugId); } return result; } /** * Register a hotplug callback function. * * Register a callback with the {@link Context}. The callback will fire * when a matching event occurs on a matching device. The callback is * armed until either it is deregistered with * {@link #hotplugDeregisterCallback(Context, HotplugCallbackHandle)} or the * supplied callback returns 1 to indicate it is finished processing * events. * * @param context * Context to register this callback with. * @param events * Bitwise or of events that will trigger this callback. * @param flags * Hotplug callback flags. * @param vendorId * The vendor id to match or {@link #HOTPLUG_MATCH_ANY}. * @param productId * The product id to match or {@link #HOTPLUG_MATCH_ANY}. * @param deviceClass * The device class to match or {@link #HOTPLUG_MATCH_ANY}. * @param callback * The function to be invoked on a matching event/device * @param userData * User data to pass to the callback function. * @param callbackHandle * Hotplug callback handle of the allocated callback. Only needed * if you later want to deregister this callback, can be NULL. * @return {@link #SUCCESS} on success, some ERROR code on failure. */ public static synchronized int hotplugRegisterCallback( final Context context, final int events, final int flags, final int vendorId, final int productId, final int deviceClass, final HotplugCallback callback, final Object userData, final HotplugCallbackHandle callbackHandle) { if (callback == null) { throw new IllegalArgumentException("callback must not be null"); } // Callback must be added to our own list before registering it in // libusb because otherwise we won't get the enumeration events hotplugCallbacks.put(globalHotplugId, new ImmutablePair<HotplugCallback, Object>(callback, userData)); // Mask the values for conversion to int in libusb API. final int result = hotplugRegisterCallbackNative( context, events, flags, (vendorId == LibUsb.HOTPLUG_MATCH_ANY) ? (LibUsb.HOTPLUG_MATCH_ANY) : (vendorId & 0xFFFF), (productId == LibUsb.HOTPLUG_MATCH_ANY) ? (LibUsb.HOTPLUG_MATCH_ANY) : (productId & 0xFFFF), (deviceClass == LibUsb.HOTPLUG_MATCH_ANY) ? (LibUsb.HOTPLUG_MATCH_ANY) : (deviceClass & 0xFF), callbackHandle, globalHotplugId); if (result == LibUsb.SUCCESS) { // Increment globalHotplugId by one, like the libusb handle. globalHotplugId++; } else { // When registration failed then remove the hotplug callback from // our list. hotplugCallbacks.remove(globalHotplugId); } return result; } /** * Internally called native method for registering a hotplug callback. * * @param context * Context to register this callback with. * @param events * Bitwise or of events that will trigger this callback. * @param flags * Hotplug callback flags. * @param vendorId * The vendor id to match or {@link #HOTPLUG_MATCH_ANY}. * @param productId * The product id to match or {@link #HOTPLUG_MATCH_ANY}. * @param deviceClass * The device class to match or {@link #HOTPLUG_MATCH_ANY}. * @param callbackHandle * Hotplug callback handle of the allocated callback. Only needed * if you later want to deregister this callback, can be NULL. * @param hotplugId * The hotplug callback ID. * @return {@link #SUCCESS} on success, some ERROR code on failure. */ static native int hotplugRegisterCallbackNative(final Context context, final int events, final int flags, final int vendorId, final int productId, final int deviceClass, final HotplugCallbackHandle callbackHandle, final long hotplugId); /** * Deregisters a hotplug callback. * * Deregister a callback from a {@link Context}. This function is safe to * call from within a hotplug callback. * * @param context * context this callback is registered with * @param callbackHandle * the handle of the callback to deregister */ public static void hotplugDeregisterCallback(final Context context, final HotplugCallbackHandle callbackHandle) { final long handle = hotplugDeregisterCallbackNative(context, callbackHandle); // When a handle is assigned by a register call, its value is the same // as the one of globalHotplugId at that moment, which is what's used // to identify data in the hotplugCallbacks map. // This is because globalHotplugId pretty much mirrors the behavior of // the handle: integer starting at 1, incremented each time by one. // Problems could arise from concurrency, but are completely avoided by // fully serializing register calls. // As such, we can use the handle value from callbackHandle to // correctly remove the data from the hotplugCallbacks map. hotplugCallbacks.remove(handle); } /** * Internally called native method for unregistering a hotplug callback. * * Deregister a callback from a {@link Context}. This function is safe to * call from within a hotplug callback. * * @param context * context this callback is registered with * @param callbackHandle * the handle of the callback to deregister * @return The hotplug callback ID. */ static native long hotplugDeregisterCallbackNative(final Context context, final HotplugCallbackHandle callbackHandle); }
usb4java/usb4java
src/main/java/org/usb4java/LibUsb.java
213,355
package org.thoughtcrime.securesms.connect; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.Settings; import android.util.Log; import android.webkit.MimeTypeMap; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.core.content.FileProvider; import com.b44t.messenger.DcAccounts; import com.b44t.messenger.DcChat; import com.b44t.messenger.DcContext; import com.b44t.messenger.DcLot; import com.b44t.messenger.DcMsg; import com.b44t.messenger.rpc.Rpc; import org.thoughtcrime.securesms.ApplicationContext; import org.thoughtcrime.securesms.BuildConfig; import org.thoughtcrime.securesms.LocalHelpActivity; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.ShareActivity; import org.thoughtcrime.securesms.database.model.ThreadRecord; import org.thoughtcrime.securesms.notifications.NotificationCenter; import org.thoughtcrime.securesms.providers.PersistentBlobProvider; import org.thoughtcrime.securesms.qr.QrActivity; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.util.IntentUtils; import org.thoughtcrime.securesms.util.MediaUtil; import java.io.File; import java.util.Date; import java.util.HashMap; public class DcHelper { private static final String TAG = DcHelper.class.getSimpleName(); public static final String CONFIG_ADDRESS = "addr"; public static final String CONFIG_CONFIGURED_ADDRESS = "configured_addr"; public static final String CONFIG_MAIL_SERVER = "mail_server"; public static final String CONFIG_MAIL_USER = "mail_user"; public static final String CONFIG_MAIL_PASSWORD = "mail_pw"; public static final String CONFIG_MAIL_PORT = "mail_port"; public static final String CONFIG_MAIL_SECURITY = "mail_security"; public static final String CONFIG_SEND_SERVER = "send_server"; public static final String CONFIG_SEND_USER = "send_user"; public static final String CONFIG_SEND_PASSWORD = "send_pw"; public static final String CONFIG_SEND_PORT = "send_port"; public static final String CONFIG_SEND_SECURITY = "send_security"; public static final String CONFIG_SERVER_FLAGS = "server_flags"; public static final String CONFIG_DISPLAY_NAME = "displayname"; public static final String CONFIG_SELF_STATUS = "selfstatus"; public static final String CONFIG_SELF_AVATAR = "selfavatar"; public static final String CONFIG_E2EE_ENABLED = "e2ee_enabled"; public static final String CONFIG_QR_OVERLAY_LOGO = "qr_overlay_logo"; public static final String CONFIG_INBOX_WATCH = "inbox_watch"; public static final String CONFIG_SENTBOX_WATCH = "sentbox_watch"; public static final String CONFIG_MVBOX_WATCH = "mvbox_watch"; public static final String CONFIG_MVBOX_MOVE = "mvbox_move"; public static final String CONFIG_ONLY_FETCH_MVBOX = "only_fetch_mvbox"; public static final String CONFIG_BCC_SELF = "bcc_self"; public static final String CONFIG_SHOW_EMAILS = "show_emails"; public static final String CONFIG_MEDIA_QUALITY = "media_quality"; public static final String CONFIG_WEBRTC_INSTANCE = "webrtc_instance"; public static final String CONFIG_SOCKS5_ENABLED = "socks5_enabled"; public static final String CONFIG_SOCKS5_HOST = "socks5_host"; public static final String CONFIG_SOCKS5_PORT = "socks5_port"; public static final String CONFIG_SOCKS5_USER = "socks5_user"; public static final String CONFIG_SOCKS5_PASSWORD = "socks5_password"; public static final String CONFIG_VERIFIED_ONE_ON_ONE_CHATS = "verified_one_on_one_chats"; public static DcContext getContext(@NonNull Context context) { return ApplicationContext.getInstance(context).dcContext; } public static Rpc getRpc(@NonNull Context context) { return ApplicationContext.getInstance(context).rpc; } public static DcAccounts getAccounts(@NonNull Context context) { return ApplicationContext.getInstance(context).dcAccounts; } public static DcEventCenter getEventCenter(@NonNull Context context) { return ApplicationContext.getInstance(context).eventCenter; } public static NotificationCenter getNotificationCenter(@NonNull Context context) { return ApplicationContext.getInstance(context).notificationCenter; } public static boolean hasAnyConfiguredContext(Context context) { DcAccounts accounts = getAccounts(context); int[] accountIds = accounts.getAll(); for (int accountId : accountIds) { if (accounts.getAccount(accountId).isConfigured() == 1) { return true; } } return false; } public static boolean isConfigured(Context context) { DcContext dcContext = getContext(context); return dcContext.isConfigured() == 1; } public static String getSelfAddr(Context context) { DcContext dcContext = getContext(context); return dcContext.getConfig(CONFIG_CONFIGURED_ADDRESS); } public static int getInt(Context context, String key) { DcContext dcContext = getContext(context); return dcContext.getConfigInt(key); } public static String get(Context context, String key) { DcContext dcContext = getContext(context); return dcContext.getConfig(key); } @Deprecated public static int getInt(Context context, String key, int defaultValue) { return getInt(context, key); } @Deprecated public static String get(Context context, String key, String defaultValue) { return get(context, key); } public static void set(Context context, String key, String value) { DcContext dcContext = getContext(context); dcContext.setConfig(key, value); } public static void setStockTranslations(Context context) { DcContext dcContext = getContext(context); // the integers are defined in the core and used only here, an enum or sth. like that won't have a big benefit dcContext.setStockTranslation(1, context.getString(R.string.chat_no_messages)); dcContext.setStockTranslation(2, context.getString(R.string.self)); dcContext.setStockTranslation(3, context.getString(R.string.draft)); dcContext.setStockTranslation(7, context.getString(R.string.voice_message)); dcContext.setStockTranslation(9, context.getString(R.string.image)); dcContext.setStockTranslation(10, context.getString(R.string.video)); dcContext.setStockTranslation(11, context.getString(R.string.audio)); dcContext.setStockTranslation(12, context.getString(R.string.file)); dcContext.setStockTranslation(13, context.getString(R.string.pref_default_status_text)); dcContext.setStockTranslation(23, context.getString(R.string.gif)); dcContext.setStockTranslation(24, context.getString(R.string.encrypted_message)); dcContext.setStockTranslation(29, context.getString(R.string.systemmsg_cannot_decrypt)); dcContext.setStockTranslation(31, context.getString(R.string.systemmsg_read_receipt_subject)); dcContext.setStockTranslation(32, context.getString(R.string.systemmsg_read_receipt_body)); dcContext.setStockTranslation(35, context.getString(R.string.contact_verified)); dcContext.setStockTranslation(36, context.getString(R.string.contact_not_verified)); dcContext.setStockTranslation(37, context.getString(R.string.contact_setup_changed)); dcContext.setStockTranslation(40, context.getString(R.string.chat_archived_label)); dcContext.setStockTranslation(42, context.getString(R.string.autocrypt_asm_subject)); dcContext.setStockTranslation(43, context.getString(R.string.autocrypt_asm_general_body)); dcContext.setStockTranslation(60, context.getString(R.string.login_error_cannot_login)); dcContext.setStockTranslation(66, context.getString(R.string.location)); dcContext.setStockTranslation(67, context.getString(R.string.sticker)); dcContext.setStockTranslation(68, context.getString(R.string.device_talk)); dcContext.setStockTranslation(69, context.getString(R.string.saved_messages)); dcContext.setStockTranslation(70, context.getString(R.string.device_talk_explain)); dcContext.setStockTranslation(71, context.getString(R.string.device_talk_welcome_message)); dcContext.setStockTranslation(72, context.getString(R.string.systemmsg_unknown_sender_for_chat)); dcContext.setStockTranslation(73, context.getString(R.string.systemmsg_subject_for_new_contact)); dcContext.setStockTranslation(74, context.getString(R.string.systemmsg_failed_sending_to)); dcContext.setStockTranslation(82, context.getString(R.string.videochat_invitation)); dcContext.setStockTranslation(83, context.getString(R.string.videochat_invitation_body)); dcContext.setStockTranslation(84, context.getString(R.string.configuration_failed_with_error)); dcContext.setStockTranslation(85, context.getString(R.string.devicemsg_bad_time)); dcContext.setStockTranslation(86, context.getString(R.string.devicemsg_update_reminder)); dcContext.setStockTranslation(90, context.getString(R.string.reply_noun)); dcContext.setStockTranslation(91, context.getString(R.string.devicemsg_self_deleted)); dcContext.setStockTranslation(97, context.getString(R.string.forwarded)); dcContext.setStockTranslation(98, context.getString(R.string.devicemsg_storage_exceeding)); dcContext.setStockTranslation(99, context.getString(R.string.n_bytes_message)); dcContext.setStockTranslation(100, context.getString(R.string.download_max_available_until)); dcContext.setStockTranslation(103, context.getString(R.string.incoming_messages)); dcContext.setStockTranslation(104, context.getString(R.string.outgoing_messages)); dcContext.setStockTranslation(105, context.getString(R.string.storage_on_domain)); dcContext.setStockTranslation(107, context.getString(R.string.connectivity_connected)); dcContext.setStockTranslation(108, context.getString(R.string.connectivity_connecting)); dcContext.setStockTranslation(109, context.getString(R.string.connectivity_updating)); dcContext.setStockTranslation(110, context.getString(R.string.sending)); dcContext.setStockTranslation(111, context.getString(R.string.last_msg_sent_successfully)); dcContext.setStockTranslation(112, context.getString(R.string.error_x)); dcContext.setStockTranslation(113, context.getString(R.string.not_supported_by_provider)); dcContext.setStockTranslation(114, context.getString(R.string.messages)); dcContext.setStockTranslation(115, context.getString(R.string.broadcast_list)); dcContext.setStockTranslation(116, context.getString(R.string.part_of_total_used)); dcContext.setStockTranslation(117, context.getString(R.string.secure_join_started)); dcContext.setStockTranslation(118, context.getString(R.string.secure_join_replies)); dcContext.setStockTranslation(119, context.getString(R.string.qrshow_join_contact_hint)); dcContext.setStockTranslation(124, context.getString(R.string.group_name_changed_by_you)); dcContext.setStockTranslation(125, context.getString(R.string.group_name_changed_by_other)); dcContext.setStockTranslation(126, context.getString(R.string.group_image_changed_by_you)); dcContext.setStockTranslation(127, context.getString(R.string.group_image_changed_by_other)); dcContext.setStockTranslation(128, context.getString(R.string.add_member_by_you)); dcContext.setStockTranslation(129, context.getString(R.string.add_member_by_other)); dcContext.setStockTranslation(130, context.getString(R.string.remove_member_by_you)); dcContext.setStockTranslation(131, context.getString(R.string.remove_member_by_other)); dcContext.setStockTranslation(132, context.getString(R.string.group_left_by_you)); dcContext.setStockTranslation(133, context.getString(R.string.group_left_by_other)); dcContext.setStockTranslation(134, context.getString(R.string.group_image_deleted_by_you)); dcContext.setStockTranslation(135, context.getString(R.string.group_image_deleted_by_other)); dcContext.setStockTranslation(136, context.getString(R.string.location_enabled_by_you)); dcContext.setStockTranslation(137, context.getString(R.string.location_enabled_by_other)); dcContext.setStockTranslation(138, context.getString(R.string.ephemeral_timer_disabled_by_you)); dcContext.setStockTranslation(139, context.getString(R.string.ephemeral_timer_disabled_by_other)); dcContext.setStockTranslation(140, context.getString(R.string.ephemeral_timer_seconds_by_you)); dcContext.setStockTranslation(141, context.getString(R.string.ephemeral_timer_seconds_by_other)); dcContext.setStockTranslation(142, context.getString(R.string.ephemeral_timer_1_minute_by_you)); dcContext.setStockTranslation(143, context.getString(R.string.ephemeral_timer_1_minute_by_other)); dcContext.setStockTranslation(144, context.getString(R.string.ephemeral_timer_1_hour_by_you)); dcContext.setStockTranslation(145, context.getString(R.string.ephemeral_timer_1_hour_by_other)); dcContext.setStockTranslation(146, context.getString(R.string.ephemeral_timer_1_day_by_you)); dcContext.setStockTranslation(147, context.getString(R.string.ephemeral_timer_1_day_by_other)); dcContext.setStockTranslation(148, context.getString(R.string.ephemeral_timer_1_week_by_you)); dcContext.setStockTranslation(149, context.getString(R.string.ephemeral_timer_1_week_by_other)); dcContext.setStockTranslation(150, context.getString(R.string.ephemeral_timer_minutes_by_you)); dcContext.setStockTranslation(151, context.getString(R.string.ephemeral_timer_minutes_by_other)); dcContext.setStockTranslation(152, context.getString(R.string.ephemeral_timer_hours_by_you)); dcContext.setStockTranslation(153, context.getString(R.string.ephemeral_timer_hours_by_other)); dcContext.setStockTranslation(154, context.getString(R.string.ephemeral_timer_days_by_you)); dcContext.setStockTranslation(155, context.getString(R.string.ephemeral_timer_days_by_other)); dcContext.setStockTranslation(156, context.getString(R.string.ephemeral_timer_weeks_by_you)); dcContext.setStockTranslation(157, context.getString(R.string.ephemeral_timer_weeks_by_other)); // HACK: svg does not handle entities correctly and shows `&quot;` as the text `quot;`. // until that is fixed, we fix the most obvious errors (core uses encode_minimal, so this does not affect so many characters) // cmp. https://github.com/deltachat/deltachat-android/issues/2187 dcContext.setStockTranslation(120, context.getString(R.string.qrshow_join_group_hint).replace("\"", "")); dcContext.setStockTranslation(121, context.getString(R.string.connectivity_not_connected)); dcContext.setStockTranslation(122, context.getString(R.string.aeap_addr_changed)); dcContext.setStockTranslation(123, context.getString(R.string.aeap_explanation)); dcContext.setStockTranslation(162, context.getString(R.string.multidevice_qr_subtitle)); dcContext.setStockTranslation(163, context.getString(R.string.multidevice_transfer_done_devicemsg)); // The next two strings should only be set if the UI actually shows more info when the user clicks on the // DC_INFO_PROTECTION_{EN|DIS}ABLED info message dcContext.setStockTranslation(170, context.getString(R.string.chat_protection_enabled_tap_to_learn_more)); dcContext.setStockTranslation(171, context.getString(R.string.chat_protection_broken_tap_to_learn_more)); } public static File getImexDir() { // DIRECTORY_DOCUMENTS is only available since KitKat; // as we also support Ice Cream Sandwich and Jellybean (2017: 11% in total), this is no option. // Moreover, DIRECTORY_DOWNLOADS seems to be easier accessible by the user, // eg. "Download Managers" are nearly always installed. // CAVE: do not use DownloadManager to add the file as it is deleted on uninstall then ... return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); } public static HashMap<String, Integer> sharedFiles = new HashMap<>(); public static void openForViewOrShare(Context activity, int msg_id, String cmd) { DcContext dcContext = getContext(activity); if(!(activity instanceof Activity)) { // would be nicer to accepting only Activity objects, // however, typically in Android just Context objects are passed around (as this normally does not make a difference). // Accepting only Activity here would force callers to cast, which would easily result in even more ugliness. Toast.makeText(activity, "openForViewOrShare() expects an Activity object", Toast.LENGTH_LONG).show(); return; } DcMsg msg = dcContext.getMsg(msg_id); String path = msg.getFile(); String mimeType = msg.getFilemime(); try { File file = new File(path); if (!file.exists()) { Toast.makeText(activity, activity.getString(R.string.file_not_found, path), Toast.LENGTH_LONG).show(); return; } Uri uri; if (path.startsWith(dcContext.getBlobdir())) { uri = Uri.parse("content://" + BuildConfig.APPLICATION_ID + ".attachments/" + Uri.encode(file.getName())); sharedFiles.put("/" + file.getName(), 1); // as different Android version handle uris in putExtra differently, we also check them on our own } else { if (Build.VERSION.SDK_INT >= 24) { uri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".fileprovider", file); } else { uri = Uri.fromFile(file); } } if (cmd.equals(Intent.ACTION_VIEW)) { mimeType = checkMime(path, mimeType); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(uri, mimeType); intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity((Activity) activity, intent); } else { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType(mimeType); intent.putExtra(Intent.EXTRA_STREAM, uri); intent.putExtra(Intent.EXTRA_TEXT, msg.getText()); intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); activity.startActivity(Intent.createChooser(intent, activity.getString(R.string.chat_share_with_title))); } } catch (RuntimeException e) { Toast.makeText(activity, String.format("%s (%s)", activity.getString(R.string.no_app_to_handle_data), mimeType), Toast.LENGTH_LONG).show(); Log.i(TAG, "opening of external activity failed.", e); } } public static void share(Context activity, byte[] data, String mimeType, String fileName, String text) { Intent intent = new Intent(activity, ShareActivity.class); intent.setAction(Intent.ACTION_SEND); if (data != null) { Uri uri = PersistentBlobProvider.getInstance().create(activity, data, mimeType, fileName); intent.setType(mimeType); intent.putExtra(Intent.EXTRA_STREAM, uri); } if (text != null) { intent.putExtra(Intent.EXTRA_TEXT, text); } activity.startActivity(intent); } private static void startActivity(Activity activity, Intent intent) { // request for permission to install apks on API 26+ if intent mimetype is an apk if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && "application/vnd.android.package-archive".equals(intent.getType()) && !activity.getPackageManager().canRequestPackageInstalls()) { activity.startActivity(new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).setData(Uri.parse(String.format("package:%s", activity.getPackageName())))); return; } activity.startActivity(intent); } private static String checkMime(String path, String mimeType) { if(mimeType == null || mimeType.equals("application/octet-stream")) { path = path.replaceAll(" ", ""); String extension = MediaUtil.getFileExtensionFromUrl(path); String newType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); if(newType != null) return newType; } return mimeType; } public static String getBlobdirFile(DcContext dcContext, String filename, String ext) { String outPath = null; for (int i = 0; i < 1000; i++) { String test = dcContext.getBlobdir() + "/" + filename + (i == 0 ? "" : i < 100 ? "-" + i : "-" + (new Date().getTime() + i)) + ext; if (!new File(test).exists()) { outPath = test; break; } } if(outPath==null) { // should not happen outPath = dcContext.getBlobdir() + "/" + Math.random(); } return outPath; } public static String getBlobdirFile(DcContext dcContext, String path) { String filename = path.substring(path.lastIndexOf('/')+1); // is the whole path if '/' is not found (lastIndexOf() returns -1 then) String ext = ""; int point = filename.indexOf('.'); if(point!=-1) { ext = filename.substring(point); filename = filename.substring(0, point); } return getBlobdirFile(dcContext, filename, ext); } public static boolean isWebrtcConfigOk(DcContext dcContext) { String instance = dcContext.getConfig(DcHelper.CONFIG_WEBRTC_INSTANCE); return (instance != null && !instance.isEmpty()); } @NonNull public static ThreadRecord getThreadRecord(Context context, DcLot summary, DcChat chat) { // adapted from ThreadDatabase.getCurrent() int chatId = chat.getId(); String body = summary.getText1(); if (!body.isEmpty()) { body += ": "; } body += summary.getText2(); Recipient recipient = new Recipient(context, chat); long date = summary.getTimestamp(); int unreadCount = getContext(context).getFreshMsgCount(chatId); return new ThreadRecord(body, recipient, date, unreadCount, chatId, chat.getVisibility(), chat.isProtected(), chat.isSendingLocations(), chat.isMuted(), chat.isContactRequest(), summary); } public static boolean isNetworkConnected(Context context) { try { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnected()) { return true; } } catch (Exception e) { } return false; } /** * Gets a string you can show to the user with basic information about connectivity. * @param context * @param connectedString Usually "Connected", but when using this as the title in * ConversationListActivity, we want to write "Delta Chat" there instead. * @return */ public static String getConnectivitySummary(Context context, int connectedString) { int connectivity = getContext(context).getConnectivity(); if (connectivity >= DcContext.DC_CONNECTIVITY_CONNECTED) { return context.getString(connectedString); } else if (connectivity >= DcContext.DC_CONNECTIVITY_WORKING) { return context.getString(R.string.connectivity_updating); } else if (connectivity >= DcContext.DC_CONNECTIVITY_CONNECTING) { return context.getString(R.string.connectivity_connecting); } else { return context.getString(R.string.connectivity_not_connected); } } public static void showVerificationBrokenDialog(Context context, String name) { new AlertDialog.Builder(context) .setMessage(context.getString(R.string.chat_protection_broken_explanation, name)) .setNeutralButton(R.string.learn_more, (d, w) -> IntentUtils.showBrowserIntent(context, "https://staging.delta.chat/684/en/help#verificationbroken")) .setNegativeButton(R.string.qrscan_title, (d, w) -> context.startActivity(new Intent(context, QrActivity.class))) .setPositiveButton(R.string.ok, null) .setCancelable(true) .show(); } public static void showProtectionEnabledDialog(Context context) { IntentUtils.showBrowserIntent(context, "https://staging.delta.chat/684/en/help#whatdoesverifiedmean"); // One day, it would be nice to point the user to the local help: //context.startActivity(new Intent(context, LocalHelpActivity.class)); } }
deltachat/deltachat-android
src/org/thoughtcrime/securesms/connect/DcHelper.java
213,356
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package docking.widgets.tree.support; import java.awt.BorderLayout; import java.awt.Container; import java.awt.datatransfer.*; import java.awt.dnd.DnDConstants; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.util.*; import javax.swing.*; import javax.swing.tree.TreePath; import docking.widgets.tree.*; import ghidra.util.Msg; import ghidra.util.SystemUtilities; public class NewTestApp extends JPanel { private static final long serialVersionUID = 1L; public NewTestApp() { } public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e1) { } System.setProperty(SystemUtilities.HEADLESS_PROPERTY, Boolean.FALSE.toString()); JFrame frame = new JFrame("Test App"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container container = frame.getContentPane(); container.setLayout(new BorderLayout()); final RootNode root = new RootNode(new File("C:\\clear_svn\\Ghidra_trunk\\Ghidra")); final GTree tree = new GTree(root); tree.setDragNDropHandler(new DragNDropHandler()); container.add(tree, BorderLayout.CENTER); JButton button = new JButton("Push Me"); container.add(button, BorderLayout.SOUTH); frame.setSize(400, 600); frame.setVisible(true); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { TreePath selectionPath = tree.getSelectionPath(); if (selectionPath != null) { GTreeNode node = (GTreeNode) selectionPath.getLastPathComponent(); tree.collapseAll(node); } } }); } public static long getMemoryUsage() { Runtime rt = Runtime.getRuntime(); return rt.totalMemory() - rt.freeMemory(); } } interface FileData { File getFile(); } class FileNode extends GTreeNode implements FileData { protected File file; public String tempName; FileNode(File file) { this.file = file; } @Override public File getFile() { return file; } @Override public Icon getIcon(boolean expanded) { return null; } @Override public String getName() { if (tempName != null) { return tempName; } String name = file.getName(); if (name.length() > 0) { return name; } return file.getName(); } @Override public String getToolTip() { return file.getAbsolutePath(); } @Override public int compareTo(GTreeNode o) { if (o instanceof DirectoryNode) { return 1; } return getName().compareTo(o.getName()); } @Override public String toString() { return file.getAbsolutePath(); } @Override public boolean equals(Object obj) { if (obj instanceof FileNode) { return file.equals(((FileNode) obj).file); } return false; } @Override public int hashCode() { return file.getAbsolutePath().hashCode(); } @Override public boolean isLeaf() { return true; } } class DirectoryNode extends GTreeLazyNode implements FileData { private final File file; DirectoryNode(File file) { this.file = file; } @Override public boolean isLeaf() { return false; } @Override public File getFile() { return file; } @Override public List<GTreeNode> generateChildren() { List<GTreeNode> children = new ArrayList<GTreeNode>(); File[] files = file.listFiles(); if (files != null) { for (File directoryFile : files) { if (directoryFile.isDirectory()) { children.add(new DirectoryNode(directoryFile)); } else { children.add(new FileNode(directoryFile)); } } } Collections.sort(children); return children; } @Override public int compareTo(GTreeNode o) { if (!(o instanceof DirectoryNode)) { return -1; } return getName().compareTo(o.getName()); } @Override public Icon getIcon(boolean expanded) { return null; } @Override public String getName() { return file.getName(); } @Override public String getToolTip() { return file.getAbsolutePath(); } @Override public int hashCode() { return file.getAbsolutePath().hashCode(); } } class RootNode extends DirectoryNode { RootNode(File file) { super(file); } } class DragNDropHandler implements GTreeDragNDropHandler { public static DataFlavor[] supportedFlavors = { DataFlavor.stringFlavor, DataFlavor.javaFileListFlavor }; @Override public void drop(GTreeNode destUserData, Transferable transferable, int dropAction) { Msg.info(this, "Dropped the following Files onto " + destUserData); try { List<?> list = (List<?>) transferable.getTransferData(DataFlavor.javaFileListFlavor); Iterator<?> it = list.iterator(); while (it.hasNext()) { Msg.info(this, "\t" + it.next()); } } catch (UnsupportedFlavorException e) { } catch (IOException e) { } } @Override public DataFlavor[] getSupportedDataFlavors(List<GTreeNode> dragUserData) { return supportedFlavors; } @Override public int getSupportedDragActions() { return DnDConstants.ACTION_COPY; } @Override public Object getTransferData(List<GTreeNode> dragUserData, DataFlavor flavor) { if (flavor.equals(DataFlavor.javaFileListFlavor)) { List<File> fileList = new ArrayList<File>(); for (GTreeNode node : dragUserData) { FileData fileData = (FileData) node; fileList.add(fileData.getFile()); } return fileList; } else if (flavor.equals(DataFlavor.stringFlavor)) { StringBuffer buf = new StringBuffer(); Iterator<?> it = dragUserData.iterator(); while (it.hasNext()) { buf.append(it.next().toString()); buf.append("\n"); } return buf.toString(); } return null; } @Override public boolean isDropSiteOk(GTreeNode destUserData, DataFlavor[] flavors, int dropAction) { if (containsFlavor(flavors, DataFlavor.javaFileListFlavor)) { return (destUserData instanceof DirectoryNode); } return false; } private boolean containsFlavor(DataFlavor[] flavors, DataFlavor flavor) { for (DataFlavor flavor2 : flavors) { if (flavor2.equals(flavor)) { return true; } } return false; } @Override public boolean isStartDragOk(List<GTreeNode> dragUserData, int dragAction) { return true; } }
NationalSecurityAgency/ghidra
Ghidra/Framework/Docking/src/main/java/docking/widgets/tree/support/NewTestApp.java
213,357
package com.goka.sample; import android.app.Application; /** * Created by katsuyagoto on 15/06/25. */ public class SampleApp extends Application { @Override public void onCreate() { super.onCreate(); // BlurredGridMenuConfig // .build(new BlurredGridMenuConfig.Builder() // .radius(1) // .downsample(1) // .overlayColor(Color.parseColor("#AA000000"))); } }
gotokatsuya/BlurredGridMenu
app/src/main/java/com/goka/sample/SampleApp.java
213,358
/* * Copyright 2014 NAVER Corp. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.plugin.log4j; import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig; import com.navercorp.pinpoint.common.util.CollectionUtils; import com.navercorp.pinpoint.common.util.StringUtils; import java.util.List; /** * @author Minwoo Jung */ public class Log4jConfig { public static final String LOG4J_LOGGING_TRANSACTION_INFO = "profiler.log4j.logging.transactioninfo"; private final boolean log4jLoggingTransactionInfo; private static final String LOGGING_PATTERN_REPLACE_ENABLE = "profiler.log4j.logging.pattern.replace.enable"; private static final String LOGGING_PATTERN_REPLACE_SEARCH = "profiler.log4j.logging.pattern.replace.search"; private static final String LOGGING_PATTERN_REPLACE_WITH = "profiler.log4j.logging.pattern.replace.with"; private final boolean patternReplaceEnable; private final List<String> patternReplaceSearchList; private final String patternReplaceWith; public Log4jConfig(ProfilerConfig config) { this.log4jLoggingTransactionInfo = config.readBoolean(LOG4J_LOGGING_TRANSACTION_INFO, false); this.patternReplaceSearchList = config.readList(LOGGING_PATTERN_REPLACE_SEARCH); this.patternReplaceWith = config.readString(LOGGING_PATTERN_REPLACE_WITH, ""); boolean configEnabled = config.readBoolean(LOGGING_PATTERN_REPLACE_ENABLE, false); boolean configOk = !CollectionUtils.isEmpty(patternReplaceSearchList) && StringUtils.hasText(patternReplaceWith); this.patternReplaceEnable = configEnabled && configOk; } public boolean isLog4jLoggingTransactionInfo() { return log4jLoggingTransactionInfo; } public boolean isPatternReplaceEnable() { return patternReplaceEnable; } public List<String> getPatternReplaceSearchList() { return patternReplaceSearchList; } public String getPatternReplaceWith() { return patternReplaceWith; } @Override public String toString() { return "Log4jConfig{" + "log4jLoggingTransactionInfo=" + log4jLoggingTransactionInfo + ", patternReplaceEnable=" + patternReplaceEnable + ", patternReplaceSearchList=" + patternReplaceSearchList + ", patternReplaceWith='" + patternReplaceWith + '\'' + '}'; } }
pinpoint-apm/pinpoint
agent-module/plugins/log4j/src/main/java/com/navercorp/pinpoint/plugin/log4j/Log4jConfig.java
213,359
package com.goka.sample; import com.goka.blurredgridmenu.GridMenu; import com.goka.blurredgridmenu.GridMenuFragment; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private GridMenuFragment mGridMenuFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mGridMenuFragment = GridMenuFragment.newInstance(R.drawable.back); findViewById(R.id.show_menu_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { FragmentTransaction tx = getSupportFragmentManager().beginTransaction(); tx.replace(R.id.main_frame, mGridMenuFragment); tx.addToBackStack(null); tx.commit(); } }); setupGridMenu(); mGridMenuFragment.setOnClickMenuListener(new GridMenuFragment.OnClickMenuListener() { @Override public void onClickMenu(GridMenu gridMenu, int position) { Toast.makeText(MainActivity.this, "Title:" + gridMenu.getTitle() + ", Position:" + position, Toast.LENGTH_SHORT).show(); } }); } private void setupGridMenu() { List<GridMenu> menus = new ArrayList<>(); menus.add(new GridMenu("Home", R.drawable.home)); menus.add(new GridMenu("Calendar", R.drawable.calendar)); menus.add(new GridMenu("Overview", R.drawable.overview)); menus.add(new GridMenu("Groups", R.drawable.groups)); menus.add(new GridMenu("Lists", R.drawable.lists)); menus.add(new GridMenu("Profile", R.drawable.profile)); menus.add(new GridMenu("Timeline", R.drawable.timeline)); menus.add(new GridMenu("Setting", R.drawable.settings)); mGridMenuFragment.setupMenu(menus); } @Override public void onBackPressed() { if (0 == getSupportFragmentManager().getBackStackEntryCount()) { super.onBackPressed(); } else { getSupportFragmentManager().popBackStack(); } } }
gotokatsuya/BlurredGridMenu
app/src/main/java/com/goka/sample/MainActivity.java
213,361
package com.danikula.videocache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.OutputStream; import java.net.Proxy; import java.net.ProxySelector; import java.net.Socket; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeoutException; import static com.danikula.videocache.Preconditions.checkArgument; import static com.danikula.videocache.Preconditions.checkNotNull; import static java.util.concurrent.TimeUnit.MILLISECONDS; /** * Pings {@link HttpProxyCacheServer} to make sure it works. * * @author Alexey Danilov ([email protected]). */ class Pinger { private static final Logger LOG = LoggerFactory.getLogger("Pinger"); private static final String PING_REQUEST = "ping"; private static final String PING_RESPONSE = "ping ok"; private final ExecutorService pingExecutor = Executors.newSingleThreadExecutor(); private final String host; private final int port; Pinger(String host, int port) { this.host = checkNotNull(host); this.port = port; } boolean ping(int maxAttempts, int startTimeout) { checkArgument(maxAttempts >= 1); checkArgument(startTimeout > 0); int timeout = startTimeout; int attempts = 0; while (attempts < maxAttempts) { try { Future<Boolean> pingFuture = pingExecutor.submit(new PingCallable()); boolean pinged = pingFuture.get(timeout, MILLISECONDS); if (pinged) { return true; } } catch (TimeoutException e) { LOG.warn("Error pinging server (attempt: " + attempts + ", timeout: " + timeout + "). "); } catch (InterruptedException | ExecutionException e) { LOG.error("Error pinging server due to unexpected error", e); } attempts++; timeout *= 2; } String error = String.format(Locale.US, "Error pinging server (attempts: %d, max timeout: %d). " + "If you see this message, please, report at https://github.com/danikula/AndroidVideoCache/issues/134. " + "Default proxies are: %s" , attempts, timeout / 2, getDefaultProxies()); LOG.error(error, new ProxyCacheException(error)); return false; } private List<Proxy> getDefaultProxies() { try { ProxySelector defaultProxySelector = ProxySelector.getDefault(); return defaultProxySelector.select(new URI(getPingUrl())); } catch (URISyntaxException e) { throw new IllegalStateException(e); } } boolean isPingRequest(String request) { return PING_REQUEST.equals(request); } void responseToPing(Socket socket) throws IOException { OutputStream out = socket.getOutputStream(); out.write("HTTP/1.1 200 OK\n\n".getBytes()); out.write(PING_RESPONSE.getBytes()); } private boolean pingServer() throws ProxyCacheException { String pingUrl = getPingUrl(); HttpUrlSource source = new HttpUrlSource(pingUrl); try { byte[] expectedResponse = PING_RESPONSE.getBytes(); source.open(0); byte[] response = new byte[expectedResponse.length]; source.read(response); boolean pingOk = Arrays.equals(expectedResponse, response); LOG.info("Ping response: `" + new String(response) + "`, pinged? " + pingOk); return pingOk; } catch (ProxyCacheException e) { LOG.error("Error reading ping response", e); return false; } finally { source.close(); } } private String getPingUrl() { return String.format(Locale.US, "http://%s:%d/%s", host, port, PING_REQUEST); } private class PingCallable implements Callable<Boolean> { @Override public Boolean call() throws Exception { return pingServer(); } } }
danikula/AndroidVideoCache
library/src/main/java/com/danikula/videocache/Pinger.java
213,362
/* * Copyright 2019 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.plugin.log4j2; import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig; import com.navercorp.pinpoint.common.util.CollectionUtils; import com.navercorp.pinpoint.common.util.StringUtils; import java.util.List; /** * @author https://github.com/licoco/pinpoint */ public class Log4j2Config { public static final String LOG4J2_LOGGING_TRANSACTION_INFO = "profiler.log4j2.logging.transactioninfo"; public static final String REUSABLELOGEVENTFACTORY_SCOPE = "reusableLogEventFactoryScope"; private static final String LOGGING_PATTERN_REPLACE_ENABLE = "profiler.log4j2.logging.pattern.replace.enable"; private static final String LOGGING_PATTERN_REPLACE_SEARCH = "profiler.log4j2.logging.pattern.replace.search"; private static final String LOGGING_PATTERN_REPLACE_WITH = "profiler.log4j2.logging.pattern.replace.with"; private final boolean log4j2LoggingTransactionInfo; private final boolean patternReplaceEnable; private final List<String> patternReplaceSearchList; private final String patternReplaceWith; public Log4j2Config(ProfilerConfig config) { this.log4j2LoggingTransactionInfo = config.readBoolean(LOG4J2_LOGGING_TRANSACTION_INFO, false); this.patternReplaceSearchList = config.readList(LOGGING_PATTERN_REPLACE_SEARCH); this.patternReplaceWith = config.readString(LOGGING_PATTERN_REPLACE_WITH, ""); boolean configEnabled = config.readBoolean(LOGGING_PATTERN_REPLACE_ENABLE, false); boolean configOk = !CollectionUtils.isEmpty(patternReplaceSearchList) && StringUtils.hasText(patternReplaceWith); this.patternReplaceEnable = configEnabled && configOk; } public boolean isLog4j2LoggingTransactionInfo() { return log4j2LoggingTransactionInfo; } public boolean isPatternReplaceEnable() { return patternReplaceEnable; } public List<String> getPatternReplaceSearchList() { return patternReplaceSearchList; } public String getPatternReplaceWith() { return patternReplaceWith; } @Override public String toString() { return "Log4j2Config{" + "log4j2LoggingTransactionInfo=" + log4j2LoggingTransactionInfo + ", patternReplaceEnable=" + patternReplaceEnable + ", patternReplaceSearchList=" + patternReplaceSearchList + ", patternReplaceWith='" + patternReplaceWith + '\'' + '}'; } }
pinpoint-apm/pinpoint
agent-module/plugins/log4j2/src/main/java/com/navercorp/pinpoint/plugin/log4j2/Log4j2Config.java
213,363
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package bridging; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import fungsi.WarnaTable; import fungsi.batasInput; import fungsi.koneksiDB; import fungsi.sekuel; import fungsi.validasi; import fungsi.akses; import java.awt.Cursor; import java.awt.Dimension; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.HashMap; import java.util.Map; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.event.DocumentEvent; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import keuangan.DlgKamar; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import simrskhanza.DlgCariPoli; /** * * @author dosen */ public final class SatuSehatMapingLokasi extends javax.swing.JDialog { private final DefaultTableModel tabMode,tabModeKamar,tabModeRuangOK,tabModeRuangLabPK,tabModeRuangLabPA,tabModeRuangLabMB,tabModeRuangRadiologi,tabModeRuangFarmasi; private sekuel Sequel=new sekuel(); private validasi Valid=new validasi(); private Connection koneksi=koneksiDB.condb(); private PreparedStatement ps; private ResultSet rs; private int i=0,pilih=0; private SatuSehatCariOrganisasi organisasi=new SatuSehatCariOrganisasi(null,false); private DlgCariPoli poli=new DlgCariPoli(null,false); private DlgKamar kamar=new DlgKamar(null,false); private String link="",json=""; private ApiSatuSehat api=new ApiSatuSehat(); private HttpHeaders headers ; private HttpEntity requestEntity; private ObjectMapper mapper = new ObjectMapper(); private JsonNode root; private JsonNode response; /** Creates new form DlgJnsPerawatanRalan * @param parent * @param modal */ public SatuSehatMapingLokasi(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); this.setLocation(8,1); setSize(628,674); tabMode=new DefaultTableModel(null,new Object[]{ "Kode Unit","Nama Unit","ID Lokasi Satu Sehat","Longitude","Latitude","Altitude", "Kode Departemen","Nama Departemen","ID Organisasi Satu Sehat" }){ @Override public boolean isCellEditable(int rowIndex, int colIndex){return false;} }; tbJnsPerawatan.setModel(tabMode); tbJnsPerawatan.setPreferredScrollableViewportSize(new Dimension(500,500)); tbJnsPerawatan.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); for (i = 0; i < 9; i++) { TableColumn column = tbJnsPerawatan.getColumnModel().getColumn(i); if(i==0){ column.setPreferredWidth(80); }else if(i==1){ column.setPreferredWidth(180); }else if(i==2){ column.setPreferredWidth(215); }else if(i==3){ column.setPreferredWidth(110); }else if(i==4){ column.setPreferredWidth(110); }else if(i==5){ column.setPreferredWidth(110); }else if(i==6){ column.setPreferredWidth(100); }else if(i==7){ column.setPreferredWidth(180); }else if(i==8){ column.setPreferredWidth(215); } } tbJnsPerawatan.setDefaultRenderer(Object.class, new WarnaTable()); tabModeKamar=new DefaultTableModel(null,new Object[]{ "Nomor Ruang","Kamar/Ruang","ID Lokasi Satu Sehat","Longitude","Latitude","Altitude", "Kode Departemen","Nama Departemen","ID Organisasi Satu Sehat" }){ @Override public boolean isCellEditable(int rowIndex, int colIndex){return false;} }; tbLokasiKamar.setModel(tabModeKamar); tbLokasiKamar.setPreferredScrollableViewportSize(new Dimension(500,500)); tbLokasiKamar.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); for (i = 0; i < 9; i++) { TableColumn column = tbLokasiKamar.getColumnModel().getColumn(i); if(i==0){ column.setPreferredWidth(80); }else if(i==1){ column.setPreferredWidth(180); }else if(i==2){ column.setPreferredWidth(215); }else if(i==3){ column.setPreferredWidth(110); }else if(i==4){ column.setPreferredWidth(110); }else if(i==5){ column.setPreferredWidth(110); }else if(i==6){ column.setPreferredWidth(100); }else if(i==7){ column.setPreferredWidth(180); }else if(i==8){ column.setPreferredWidth(215); } } tbLokasiKamar.setDefaultRenderer(Object.class, new WarnaTable()); tabModeRuangOK=new DefaultTableModel(null,new Object[]{ "ID Lokasi Satu Sehat","Longitude","Latitude","Altitude","Kode Departemen","Nama Departemen","ID Organisasi Satu Sehat" }){ @Override public boolean isCellEditable(int rowIndex, int colIndex){return false;} }; tbLokasiRuangOK.setModel(tabModeRuangOK); tbLokasiRuangOK.setPreferredScrollableViewportSize(new Dimension(500,500)); tbLokasiRuangOK.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); for (i = 0; i < 7; i++) { TableColumn column = tbLokasiRuangOK.getColumnModel().getColumn(i); if(i==0){ column.setPreferredWidth(215); }else if(i==1){ column.setPreferredWidth(110); }else if(i==2){ column.setPreferredWidth(110); }else if(i==3){ column.setPreferredWidth(110); }else if(i==4){ column.setPreferredWidth(100); }else if(i==5){ column.setPreferredWidth(180); }else if(i==6){ column.setPreferredWidth(215); } } tbLokasiRuangOK.setDefaultRenderer(Object.class, new WarnaTable()); tabModeRuangLabPK=new DefaultTableModel(null,new Object[]{ "ID Lokasi Satu Sehat","Longitude","Latitude","Altitude","Kode Departemen","Nama Departemen","ID Organisasi Satu Sehat" }){ @Override public boolean isCellEditable(int rowIndex, int colIndex){return false;} }; tbLokasiRuangLabPK.setModel(tabModeRuangLabPK); tbLokasiRuangLabPK.setPreferredScrollableViewportSize(new Dimension(500,500)); tbLokasiRuangLabPK.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); for (i = 0; i < 7; i++) { TableColumn column = tbLokasiRuangLabPK.getColumnModel().getColumn(i); if(i==0){ column.setPreferredWidth(215); }else if(i==1){ column.setPreferredWidth(110); }else if(i==2){ column.setPreferredWidth(110); }else if(i==3){ column.setPreferredWidth(110); }else if(i==4){ column.setPreferredWidth(100); }else if(i==5){ column.setPreferredWidth(180); }else if(i==6){ column.setPreferredWidth(215); } } tbLokasiRuangLabPK.setDefaultRenderer(Object.class, new WarnaTable()); tabModeRuangLabPA=new DefaultTableModel(null,new Object[]{ "ID Lokasi Satu Sehat","Longitude","Latitude","Altitude","Kode Departemen","Nama Departemen","ID Organisasi Satu Sehat" }){ @Override public boolean isCellEditable(int rowIndex, int colIndex){return false;} }; tbLokasiRuangLabPA.setModel(tabModeRuangLabPA); tbLokasiRuangLabPA.setPreferredScrollableViewportSize(new Dimension(500,500)); tbLokasiRuangLabPA.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); for (i = 0; i < 7; i++) { TableColumn column = tbLokasiRuangLabPA.getColumnModel().getColumn(i); if(i==0){ column.setPreferredWidth(215); }else if(i==1){ column.setPreferredWidth(110); }else if(i==2){ column.setPreferredWidth(110); }else if(i==3){ column.setPreferredWidth(110); }else if(i==4){ column.setPreferredWidth(100); }else if(i==5){ column.setPreferredWidth(180); }else if(i==6){ column.setPreferredWidth(215); } } tbLokasiRuangLabPA.setDefaultRenderer(Object.class, new WarnaTable()); tabModeRuangLabMB=new DefaultTableModel(null,new Object[]{ "ID Lokasi Satu Sehat","Longitude","Latitude","Altitude","Kode Departemen","Nama Departemen","ID Organisasi Satu Sehat" }){ @Override public boolean isCellEditable(int rowIndex, int colIndex){return false;} }; tbLokasiRuangLabMB.setModel(tabModeRuangLabMB); tbLokasiRuangLabMB.setPreferredScrollableViewportSize(new Dimension(500,500)); tbLokasiRuangLabMB.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); for (i = 0; i < 7; i++) { TableColumn column = tbLokasiRuangLabMB.getColumnModel().getColumn(i); if(i==0){ column.setPreferredWidth(215); }else if(i==1){ column.setPreferredWidth(110); }else if(i==2){ column.setPreferredWidth(110); }else if(i==3){ column.setPreferredWidth(110); }else if(i==4){ column.setPreferredWidth(100); }else if(i==5){ column.setPreferredWidth(180); }else if(i==6){ column.setPreferredWidth(215); } } tbLokasiRuangLabMB.setDefaultRenderer(Object.class, new WarnaTable()); tabModeRuangRadiologi=new DefaultTableModel(null,new Object[]{ "ID Lokasi Satu Sehat","Longitude","Latitude","Altitude","Kode Departemen","Nama Departemen","ID Organisasi Satu Sehat" }){ @Override public boolean isCellEditable(int rowIndex, int colIndex){return false;} }; tbLokasiRuangRadiologi.setModel(tabModeRuangRadiologi); tbLokasiRuangRadiologi.setPreferredScrollableViewportSize(new Dimension(500,500)); tbLokasiRuangRadiologi.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); for (i = 0; i < 7; i++) { TableColumn column = tbLokasiRuangRadiologi.getColumnModel().getColumn(i); if(i==0){ column.setPreferredWidth(215); }else if(i==1){ column.setPreferredWidth(110); }else if(i==2){ column.setPreferredWidth(110); }else if(i==3){ column.setPreferredWidth(110); }else if(i==4){ column.setPreferredWidth(100); }else if(i==5){ column.setPreferredWidth(180); }else if(i==6){ column.setPreferredWidth(215); } } tbLokasiRuangRadiologi.setDefaultRenderer(Object.class, new WarnaTable()); tabModeRuangFarmasi=new DefaultTableModel(null,new Object[]{ "Kode Farmasi","Nama Depo Farmasi","ID Lokasi Satu Sehat","Longitude","Latitude","Altitude", "Kode Departemen","Nama Departemen","ID Organisasi Satu Sehat" }){ @Override public boolean isCellEditable(int rowIndex, int colIndex){return false;} }; tbLokasiFarmasi.setModel(tabModeRuangFarmasi); tbLokasiFarmasi.setPreferredScrollableViewportSize(new Dimension(500,500)); tbLokasiFarmasi.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); for (i = 0; i < 9; i++) { TableColumn column = tbLokasiFarmasi.getColumnModel().getColumn(i); if(i==0){ column.setPreferredWidth(80); }else if(i==1){ column.setPreferredWidth(180); }else if(i==2){ column.setPreferredWidth(215); }else if(i==3){ column.setPreferredWidth(110); }else if(i==4){ column.setPreferredWidth(110); }else if(i==5){ column.setPreferredWidth(110); }else if(i==6){ column.setPreferredWidth(100); }else if(i==7){ column.setPreferredWidth(180); }else if(i==8){ column.setPreferredWidth(215); } } tbLokasiFarmasi.setDefaultRenderer(Object.class, new WarnaTable()); KodeDepartemen.setDocument(new batasInput((byte)5).getKata(KodeDepartemen)); Longitude.setDocument(new batasInput((byte)30).getKata(Longitude)); Latitude.setDocument(new batasInput((byte)30).getKata(Latitude)); Altitude.setDocument(new batasInput((byte)30).getKata(Altitude)); TCari.setDocument(new batasInput((byte)100).getKata(TCari)); if(koneksiDB.CARICEPAT().equals("aktif")){ TCari.getDocument().addDocumentListener(new javax.swing.event.DocumentListener(){ @Override public void insertUpdate(DocumentEvent e) { if(TCari.getText().length()>2){ tampil(); } } @Override public void removeUpdate(DocumentEvent e) { if(TCari.getText().length()>2){ tampil(); } } @Override public void changedUpdate(DocumentEvent e) { if(TCari.getText().length()>2){ tampil(); } } }); } organisasi.addWindowListener(new WindowListener() { @Override public void windowOpened(WindowEvent e) {} @Override public void windowClosing(WindowEvent e) {} @Override public void windowClosed(WindowEvent e) { if(organisasi.getTable().getSelectedRow()!= -1){ if(pilih==1){ KodeDepartemen.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),0).toString()); NamaDepartemen.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),1).toString()); IDOrganisasi.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),2).toString()); KodeDepartemen.requestFocus(); }else if(pilih==2){ KodeDepartemenKamar.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),0).toString()); NamaDepartemenKamar.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),1).toString()); IDOrganisasiKamar.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),2).toString()); KodeDepartemenKamar.requestFocus(); }else if(pilih==3){ KodeDepartemenRuangOK.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),0).toString()); NamaDepartemenRuangOK.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),1).toString()); IDOrganisasiRuangOK.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),2).toString()); KodeDepartemenRuangOK.requestFocus(); }else if(pilih==4){ KodeDepartemenRuangLabPK.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),0).toString()); NamaDepartemenRuangLabPK.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),1).toString()); IDOrganisasiRuangLabPK.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),2).toString()); KodeDepartemenRuangLabPK.requestFocus(); }else if(pilih==5){ KodeDepartemenRuangLabPA.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),0).toString()); NamaDepartemenRuangLabPA.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),1).toString()); IDOrganisasiRuangLabPA.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),2).toString()); KodeDepartemenRuangLabPA.requestFocus(); }else if(pilih==6){ KodeDepartemenRuangLabMB.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),0).toString()); NamaDepartemenRuangLabMB.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),1).toString()); IDOrganisasiRuangLabMB.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),2).toString()); KodeDepartemenRuangLabMB.requestFocus(); }else if(pilih==7){ KodeDepartemenRuangRadiologi.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),0).toString()); NamaDepartemenRuangRadiologi.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),1).toString()); IDOrganisasiRuangRadiologi.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),2).toString()); KodeDepartemenRuangRadiologi.requestFocus(); }else if(pilih==8){ KodeDepartemenFarmasi.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),0).toString()); NamaDepartemenFarmasi.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),1).toString()); IDOrganisasiFarmasi.setText(organisasi.getTable().getValueAt(organisasi.getTable().getSelectedRow(),2).toString()); KodeDepartemenFarmasi.requestFocus(); } } } @Override public void windowIconified(WindowEvent e) {} @Override public void windowDeiconified(WindowEvent e) {} @Override public void windowActivated(WindowEvent e) {} @Override public void windowDeactivated(WindowEvent e) {} }); poli.addWindowListener(new WindowListener() { @Override public void windowOpened(WindowEvent e) {} @Override public void windowClosing(WindowEvent e) {} @Override public void windowClosed(WindowEvent e) { if(poli.getTable().getSelectedRow()!= -1){ KodePoli.setText(poli.getTable().getValueAt(poli.getTable().getSelectedRow(),0).toString()); NamaPoli.setText(poli.getTable().getValueAt(poli.getTable().getSelectedRow(),1).toString()); } KodePoli.requestFocus(); } @Override public void windowIconified(WindowEvent e) {} @Override public void windowDeiconified(WindowEvent e) {} @Override public void windowActivated(WindowEvent e) {} @Override public void windowDeactivated(WindowEvent e) {} }); kamar.addWindowListener(new WindowListener() { @Override public void windowOpened(WindowEvent e) {} @Override public void windowClosing(WindowEvent e) {} @Override public void windowClosed(WindowEvent e) { if(kamar.getTable().getSelectedRow()!= -1){ KodeKamar.setText(kamar.getTable().getValueAt(kamar.getTable().getSelectedRow(),1).toString()); NamaKamar.setText(kamar.getTable().getValueAt(kamar.getTable().getSelectedRow(),3).toString()); } KodeKamar.requestFocus(); } @Override public void windowIconified(WindowEvent e) {} @Override public void windowDeiconified(WindowEvent e) {} @Override public void windowActivated(WindowEvent e) {} @Override public void windowDeactivated(WindowEvent e) {} }); kamar.getTable().addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) {} @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode()==KeyEvent.VK_SPACE){ kamar.dispose(); } } @Override public void keyReleased(KeyEvent e) {} }); kamar.bangsal.addWindowListener(new WindowListener() { @Override public void windowOpened(WindowEvent e) {} @Override public void windowClosing(WindowEvent e) {} @Override public void windowClosed(WindowEvent e) { if(kamar.bangsal.getTable().getSelectedRow()!= -1){ KodeFarmasi.setText(kamar.bangsal.getTable().getValueAt(kamar.bangsal.getTable().getSelectedRow(),0).toString()); NamaFarmasi.setText(kamar.bangsal.getTable().getValueAt(kamar.bangsal.getTable().getSelectedRow(),1).toString()); } KodeFarmasi.requestFocus(); } @Override public void windowIconified(WindowEvent e) {} @Override public void windowDeiconified(WindowEvent e) {} @Override public void windowActivated(WindowEvent e) {} @Override public void windowDeactivated(WindowEvent e) {} }); try { link=koneksiDB.URLFHIRSATUSEHAT(); } catch (Exception e) { System.out.println("Notif : "+e); } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { internalFrame1 = new widget.InternalFrame(); jPanel3 = new javax.swing.JPanel(); panelGlass8 = new widget.panelisi(); BtnSimpan = new widget.Button(); BtnBatal = new widget.Button(); BtnHapus = new widget.Button(); BtnEdit = new widget.Button(); BtnPrint = new widget.Button(); BtnAll = new widget.Button(); BtnKeluar = new widget.Button(); panelGlass9 = new widget.panelisi(); jLabel6 = new widget.Label(); TCari = new widget.TextBox(); BtnCari = new widget.Button(); jLabel7 = new widget.Label(); LCount = new widget.Label(); TabRawat = new javax.swing.JTabbedPane(); internalFrame2 = new widget.InternalFrame(); FormInput = new widget.PanelBiasa(); jLabel4 = new widget.Label(); KodeDepartemen = new widget.TextBox(); NamaDepartemen = new widget.TextBox(); btnDepartemenRS = new widget.Button(); jLabel5 = new widget.Label(); KodePoli = new widget.TextBox(); NamaPoli = new widget.TextBox(); btnPoliRS = new widget.Button(); IDOrganisasi = new widget.TextBox(); Longitude = new widget.TextBox(); jLabel8 = new widget.Label(); jLabel9 = new widget.Label(); Latitude = new widget.TextBox(); jLabel10 = new widget.Label(); Altitude = new widget.TextBox(); Scroll = new widget.ScrollPane(); tbJnsPerawatan = new widget.Table(); internalFrame3 = new widget.InternalFrame(); FormInput1 = new widget.PanelBiasa(); jLabel11 = new widget.Label(); KodeDepartemenKamar = new widget.TextBox(); NamaDepartemenKamar = new widget.TextBox(); btnDepartemenKamar = new widget.Button(); jLabel12 = new widget.Label(); KodeKamar = new widget.TextBox(); NamaKamar = new widget.TextBox(); btnKamar = new widget.Button(); IDOrganisasiKamar = new widget.TextBox(); LongitudeKamar = new widget.TextBox(); jLabel13 = new widget.Label(); jLabel14 = new widget.Label(); LatitudeKamar = new widget.TextBox(); jLabel15 = new widget.Label(); AltitudeKamar = new widget.TextBox(); Scroll1 = new widget.ScrollPane(); tbLokasiKamar = new widget.Table(); internalFrame4 = new widget.InternalFrame(); FormInput2 = new widget.PanelBiasa(); jLabel16 = new widget.Label(); KodeDepartemenRuangOK = new widget.TextBox(); NamaDepartemenRuangOK = new widget.TextBox(); btnDepartemenRuangOK = new widget.Button(); IDOrganisasiRuangOK = new widget.TextBox(); LongitudeRuangOK = new widget.TextBox(); jLabel18 = new widget.Label(); jLabel19 = new widget.Label(); LatitudeRuangOK = new widget.TextBox(); jLabel20 = new widget.Label(); AltitudeRuangOK = new widget.TextBox(); Scroll2 = new widget.ScrollPane(); tbLokasiRuangOK = new widget.Table(); internalFrame5 = new widget.InternalFrame(); FormInput3 = new widget.PanelBiasa(); jLabel17 = new widget.Label(); KodeDepartemenRuangLabPK = new widget.TextBox(); NamaDepartemenRuangLabPK = new widget.TextBox(); btnDepartemenRuangLabPK = new widget.Button(); IDOrganisasiRuangLabPK = new widget.TextBox(); LongitudeRuangLabPK = new widget.TextBox(); jLabel21 = new widget.Label(); jLabel22 = new widget.Label(); LatitudeRuangLabPK = new widget.TextBox(); jLabel23 = new widget.Label(); AltitudeRuangLabPK = new widget.TextBox(); Scroll3 = new widget.ScrollPane(); tbLokasiRuangLabPK = new widget.Table(); internalFrame6 = new widget.InternalFrame(); FormInput4 = new widget.PanelBiasa(); jLabel24 = new widget.Label(); KodeDepartemenRuangLabPA = new widget.TextBox(); NamaDepartemenRuangLabPA = new widget.TextBox(); btnDepartemenRuangLabPA = new widget.Button(); IDOrganisasiRuangLabPA = new widget.TextBox(); LongitudeRuangLabPA = new widget.TextBox(); jLabel25 = new widget.Label(); jLabel26 = new widget.Label(); LatitudeRuangLabPA = new widget.TextBox(); jLabel27 = new widget.Label(); AltitudeRuangLabPA = new widget.TextBox(); Scroll4 = new widget.ScrollPane(); tbLokasiRuangLabPA = new widget.Table(); internalFrame7 = new widget.InternalFrame(); FormInput5 = new widget.PanelBiasa(); jLabel28 = new widget.Label(); KodeDepartemenRuangLabMB = new widget.TextBox(); NamaDepartemenRuangLabMB = new widget.TextBox(); btnDepartemenRuangLabMB = new widget.Button(); IDOrganisasiRuangLabMB = new widget.TextBox(); LongitudeRuangLabMB = new widget.TextBox(); jLabel29 = new widget.Label(); jLabel30 = new widget.Label(); LatitudeRuangLabMB = new widget.TextBox(); jLabel31 = new widget.Label(); AltitudeRuangLabMB = new widget.TextBox(); Scroll5 = new widget.ScrollPane(); tbLokasiRuangLabMB = new widget.Table(); internalFrame8 = new widget.InternalFrame(); FormInput6 = new widget.PanelBiasa(); jLabel32 = new widget.Label(); KodeDepartemenRuangRadiologi = new widget.TextBox(); NamaDepartemenRuangRadiologi = new widget.TextBox(); btnDepartemenRuangRadiologi = new widget.Button(); IDOrganisasiRuangRadiologi = new widget.TextBox(); LongitudeRuangRadiologi = new widget.TextBox(); jLabel33 = new widget.Label(); jLabel34 = new widget.Label(); LatitudeRuangRadiologi = new widget.TextBox(); jLabel35 = new widget.Label(); AltitudeRuangRadiologi = new widget.TextBox(); Scroll6 = new widget.ScrollPane(); tbLokasiRuangRadiologi = new widget.Table(); internalFrame9 = new widget.InternalFrame(); FormInput7 = new widget.PanelBiasa(); jLabel36 = new widget.Label(); KodeDepartemenFarmasi = new widget.TextBox(); NamaDepartemenFarmasi = new widget.TextBox(); btnDepartemenFarmasi = new widget.Button(); jLabel37 = new widget.Label(); KodeFarmasi = new widget.TextBox(); NamaFarmasi = new widget.TextBox(); btnFarmasi = new widget.Button(); IDOrganisasiFarmasi = new widget.TextBox(); LongitudeFarmasi = new widget.TextBox(); jLabel38 = new widget.Label(); jLabel39 = new widget.Label(); LatitudeFarmasi = new widget.TextBox(); jLabel40 = new widget.Label(); AltitudeFarmasi = new widget.TextBox(); Scroll7 = new widget.ScrollPane(); tbLokasiFarmasi = new widget.Table(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setUndecorated(true); setResizable(false); addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); internalFrame1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(240, 245, 235)), "::[ Data Mapping Lokasi Satu Sehat ]::", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(50, 50, 50))); // NOI18N internalFrame1.setName("internalFrame1"); // NOI18N internalFrame1.setLayout(new java.awt.BorderLayout(1, 1)); jPanel3.setName("jPanel3"); // NOI18N jPanel3.setOpaque(false); jPanel3.setPreferredSize(new java.awt.Dimension(44, 100)); jPanel3.setLayout(new java.awt.BorderLayout(1, 1)); panelGlass8.setName("panelGlass8"); // NOI18N panelGlass8.setPreferredSize(new java.awt.Dimension(44, 44)); panelGlass8.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 9)); BtnSimpan.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/save-16x16.png"))); // NOI18N BtnSimpan.setMnemonic('S'); BtnSimpan.setText("Simpan"); BtnSimpan.setToolTipText("Alt+S"); BtnSimpan.setName("BtnSimpan"); // NOI18N BtnSimpan.setPreferredSize(new java.awt.Dimension(100, 30)); BtnSimpan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnSimpanActionPerformed(evt); } }); BtnSimpan.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { BtnSimpanKeyPressed(evt); } }); panelGlass8.add(BtnSimpan); BtnBatal.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/Cancel-2-16x16.png"))); // NOI18N BtnBatal.setMnemonic('B'); BtnBatal.setText("Baru"); BtnBatal.setToolTipText("Alt+B"); BtnBatal.setName("BtnBatal"); // NOI18N BtnBatal.setPreferredSize(new java.awt.Dimension(100, 30)); BtnBatal.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnBatalActionPerformed(evt); } }); BtnBatal.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { BtnBatalKeyPressed(evt); } }); panelGlass8.add(BtnBatal); BtnHapus.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/stop_f2.png"))); // NOI18N BtnHapus.setMnemonic('H'); BtnHapus.setText("Hapus"); BtnHapus.setToolTipText("Alt+H"); BtnHapus.setName("BtnHapus"); // NOI18N BtnHapus.setPreferredSize(new java.awt.Dimension(100, 30)); BtnHapus.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnHapusActionPerformed(evt); } }); BtnHapus.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { BtnHapusKeyPressed(evt); } }); panelGlass8.add(BtnHapus); BtnEdit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/inventaris.png"))); // NOI18N BtnEdit.setMnemonic('G'); BtnEdit.setText("Ganti"); BtnEdit.setToolTipText("Alt+G"); BtnEdit.setName("BtnEdit"); // NOI18N BtnEdit.setPreferredSize(new java.awt.Dimension(100, 30)); BtnEdit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnEditActionPerformed(evt); } }); BtnEdit.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { BtnEditKeyPressed(evt); } }); panelGlass8.add(BtnEdit); BtnPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/b_print.png"))); // NOI18N BtnPrint.setMnemonic('T'); BtnPrint.setText("Cetak"); BtnPrint.setToolTipText("Alt+T"); BtnPrint.setName("BtnPrint"); // NOI18N BtnPrint.setPreferredSize(new java.awt.Dimension(100, 30)); BtnPrint.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnPrintActionPerformed(evt); } }); BtnPrint.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { BtnPrintKeyPressed(evt); } }); panelGlass8.add(BtnPrint); BtnAll.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/Search-16x16.png"))); // NOI18N BtnAll.setMnemonic('M'); BtnAll.setText("Semua"); BtnAll.setToolTipText("Alt+M"); BtnAll.setName("BtnAll"); // NOI18N BtnAll.setPreferredSize(new java.awt.Dimension(100, 30)); BtnAll.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnAllActionPerformed(evt); } }); BtnAll.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { BtnAllKeyPressed(evt); } }); panelGlass8.add(BtnAll); BtnKeluar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/exit.png"))); // NOI18N BtnKeluar.setMnemonic('K'); BtnKeluar.setText("Keluar"); BtnKeluar.setToolTipText("Alt+K"); BtnKeluar.setName("BtnKeluar"); // NOI18N BtnKeluar.setPreferredSize(new java.awt.Dimension(100, 30)); BtnKeluar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnKeluarActionPerformed(evt); } }); BtnKeluar.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { BtnKeluarKeyPressed(evt); } }); panelGlass8.add(BtnKeluar); jPanel3.add(panelGlass8, java.awt.BorderLayout.CENTER); panelGlass9.setName("panelGlass9"); // NOI18N panelGlass9.setPreferredSize(new java.awt.Dimension(44, 44)); panelGlass9.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 9)); jLabel6.setText("Key Word :"); jLabel6.setName("jLabel6"); // NOI18N jLabel6.setPreferredSize(new java.awt.Dimension(70, 23)); panelGlass9.add(jLabel6); TCari.setName("TCari"); // NOI18N TCari.setPreferredSize(new java.awt.Dimension(450, 23)); TCari.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { TCariKeyPressed(evt); } }); panelGlass9.add(TCari); BtnCari.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/accept.png"))); // NOI18N BtnCari.setMnemonic('2'); BtnCari.setToolTipText("Alt+2"); BtnCari.setName("BtnCari"); // NOI18N BtnCari.setPreferredSize(new java.awt.Dimension(28, 23)); BtnCari.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnCariActionPerformed(evt); } }); BtnCari.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { BtnCariKeyPressed(evt); } }); panelGlass9.add(BtnCari); jLabel7.setText("Record :"); jLabel7.setName("jLabel7"); // NOI18N jLabel7.setPreferredSize(new java.awt.Dimension(75, 23)); panelGlass9.add(jLabel7); LCount.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); LCount.setText("0"); LCount.setName("LCount"); // NOI18N LCount.setPreferredSize(new java.awt.Dimension(80, 23)); panelGlass9.add(LCount); jPanel3.add(panelGlass9, java.awt.BorderLayout.PAGE_START); internalFrame1.add(jPanel3, java.awt.BorderLayout.PAGE_END); TabRawat.setBackground(new java.awt.Color(255, 255, 254)); TabRawat.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(241, 246, 236))); TabRawat.setForeground(new java.awt.Color(50, 50, 50)); TabRawat.setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N TabRawat.setName("TabRawat"); // NOI18N TabRawat.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { TabRawatMouseClicked(evt); } }); internalFrame2.setBackground(new java.awt.Color(235, 255, 235)); internalFrame2.setBorder(null); internalFrame2.setName("internalFrame2"); // NOI18N internalFrame2.setLayout(new java.awt.BorderLayout(1, 1)); FormInput.setName("FormInput"); // NOI18N FormInput.setPreferredSize(new java.awt.Dimension(100, 74)); FormInput.setLayout(null); jLabel4.setText("Organisasi :"); jLabel4.setName("jLabel4"); // NOI18N FormInput.add(jLabel4); jLabel4.setBounds(170, 40, 74, 23); KodeDepartemen.setEditable(false); KodeDepartemen.setHighlighter(null); KodeDepartemen.setName("KodeDepartemen"); // NOI18N FormInput.add(KodeDepartemen); KodeDepartemen.setBounds(248, 40, 55, 23); NamaDepartemen.setEditable(false); NamaDepartemen.setHighlighter(null); NamaDepartemen.setName("NamaDepartemen"); // NOI18N FormInput.add(NamaDepartemen); NamaDepartemen.setBounds(305, 40, 176, 23); btnDepartemenRS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/190.png"))); // NOI18N btnDepartemenRS.setMnemonic('1'); btnDepartemenRS.setToolTipText("Alt+1"); btnDepartemenRS.setName("btnDepartemenRS"); // NOI18N btnDepartemenRS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDepartemenRSActionPerformed(evt); } }); btnDepartemenRS.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { btnDepartemenRSKeyPressed(evt); } }); FormInput.add(btnDepartemenRS); btnDepartemenRS.setBounds(705, 40, 28, 23); jLabel5.setText("Unit RS :"); jLabel5.setName("jLabel5"); // NOI18N FormInput.add(jLabel5); jLabel5.setBounds(0, 10, 59, 23); KodePoli.setEditable(false); KodePoli.setHighlighter(null); KodePoli.setName("KodePoli"); // NOI18N FormInput.add(KodePoli); KodePoli.setBounds(63, 10, 70, 23); NamaPoli.setEditable(false); NamaPoli.setHighlighter(null); NamaPoli.setName("NamaPoli"); // NOI18N FormInput.add(NamaPoli); NamaPoli.setBounds(135, 10, 195, 23); btnPoliRS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/190.png"))); // NOI18N btnPoliRS.setMnemonic('1'); btnPoliRS.setToolTipText("Alt+1"); btnPoliRS.setName("btnPoliRS"); // NOI18N btnPoliRS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPoliRSActionPerformed(evt); } }); btnPoliRS.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { btnPoliRSKeyPressed(evt); } }); FormInput.add(btnPoliRS); btnPoliRS.setBounds(332, 10, 28, 23); IDOrganisasi.setEditable(false); IDOrganisasi.setHighlighter(null); IDOrganisasi.setName("IDOrganisasi"); // NOI18N FormInput.add(IDOrganisasi); IDOrganisasi.setBounds(483, 40, 220, 23); Longitude.setHighlighter(null); Longitude.setName("Longitude"); // NOI18N Longitude.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { LongitudeKeyPressed(evt); } }); FormInput.add(Longitude); Longitude.setBounds(430, 10, 120, 23); jLabel8.setText("Longitude :"); jLabel8.setName("jLabel8"); // NOI18N FormInput.add(jLabel8); jLabel8.setBounds(357, 10, 69, 23); jLabel9.setText("Latitude :"); jLabel9.setName("jLabel9"); // NOI18N FormInput.add(jLabel9); jLabel9.setBounds(549, 10, 60, 23); Latitude.setHighlighter(null); Latitude.setName("Latitude"); // NOI18N Latitude.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { LatitudeKeyPressed(evt); } }); FormInput.add(Latitude); Latitude.setBounds(613, 10, 120, 23); jLabel10.setText("Altitude :"); jLabel10.setName("jLabel10"); // NOI18N FormInput.add(jLabel10); jLabel10.setBounds(0, 40, 59, 23); Altitude.setHighlighter(null); Altitude.setName("Altitude"); // NOI18N Altitude.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { AltitudeKeyPressed(evt); } }); FormInput.add(Altitude); Altitude.setBounds(63, 40, 110, 23); internalFrame2.add(FormInput, java.awt.BorderLayout.PAGE_START); Scroll.setName("Scroll"); // NOI18N Scroll.setOpaque(true); tbJnsPerawatan.setToolTipText("Silahkan klik untuk memilih data yang mau diedit ataupun dihapus"); tbJnsPerawatan.setName("tbJnsPerawatan"); // NOI18N tbJnsPerawatan.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tbJnsPerawatanMouseClicked(evt); } }); tbJnsPerawatan.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { tbJnsPerawatanKeyReleased(evt); } }); Scroll.setViewportView(tbJnsPerawatan); internalFrame2.add(Scroll, java.awt.BorderLayout.CENTER); TabRawat.addTab("Lokasi Ralan", internalFrame2); internalFrame3.setBackground(new java.awt.Color(235, 255, 235)); internalFrame3.setBorder(null); internalFrame3.setName("internalFrame3"); // NOI18N internalFrame3.setLayout(new java.awt.BorderLayout(1, 1)); FormInput1.setName("FormInput1"); // NOI18N FormInput1.setPreferredSize(new java.awt.Dimension(100, 74)); FormInput1.setLayout(null); jLabel11.setText("Organisasi :"); jLabel11.setName("jLabel11"); // NOI18N FormInput1.add(jLabel11); jLabel11.setBounds(170, 40, 74, 23); KodeDepartemenKamar.setEditable(false); KodeDepartemenKamar.setHighlighter(null); KodeDepartemenKamar.setName("KodeDepartemenKamar"); // NOI18N FormInput1.add(KodeDepartemenKamar); KodeDepartemenKamar.setBounds(248, 40, 55, 23); NamaDepartemenKamar.setEditable(false); NamaDepartemenKamar.setHighlighter(null); NamaDepartemenKamar.setName("NamaDepartemenKamar"); // NOI18N FormInput1.add(NamaDepartemenKamar); NamaDepartemenKamar.setBounds(305, 40, 176, 23); btnDepartemenKamar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/190.png"))); // NOI18N btnDepartemenKamar.setMnemonic('1'); btnDepartemenKamar.setToolTipText("Alt+1"); btnDepartemenKamar.setName("btnDepartemenKamar"); // NOI18N btnDepartemenKamar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDepartemenKamarActionPerformed(evt); } }); btnDepartemenKamar.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { btnDepartemenKamarKeyPressed(evt); } }); FormInput1.add(btnDepartemenKamar); btnDepartemenKamar.setBounds(705, 40, 28, 23); jLabel12.setText("Kamar :"); jLabel12.setName("jLabel12"); // NOI18N FormInput1.add(jLabel12); jLabel12.setBounds(0, 10, 59, 23); KodeKamar.setEditable(false); KodeKamar.setHighlighter(null); KodeKamar.setName("KodeKamar"); // NOI18N FormInput1.add(KodeKamar); KodeKamar.setBounds(63, 10, 70, 23); NamaKamar.setEditable(false); NamaKamar.setHighlighter(null); NamaKamar.setName("NamaKamar"); // NOI18N FormInput1.add(NamaKamar); NamaKamar.setBounds(135, 10, 195, 23); btnKamar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/190.png"))); // NOI18N btnKamar.setMnemonic('1'); btnKamar.setToolTipText("Alt+1"); btnKamar.setName("btnKamar"); // NOI18N btnKamar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnKamarActionPerformed(evt); } }); btnKamar.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { btnKamarKeyPressed(evt); } }); FormInput1.add(btnKamar); btnKamar.setBounds(332, 10, 28, 23); IDOrganisasiKamar.setEditable(false); IDOrganisasiKamar.setHighlighter(null); IDOrganisasiKamar.setName("IDOrganisasiKamar"); // NOI18N FormInput1.add(IDOrganisasiKamar); IDOrganisasiKamar.setBounds(483, 40, 220, 23); LongitudeKamar.setHighlighter(null); LongitudeKamar.setName("LongitudeKamar"); // NOI18N LongitudeKamar.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { LongitudeKamarKeyPressed(evt); } }); FormInput1.add(LongitudeKamar); LongitudeKamar.setBounds(430, 10, 120, 23); jLabel13.setText("Longitude :"); jLabel13.setName("jLabel13"); // NOI18N FormInput1.add(jLabel13); jLabel13.setBounds(357, 10, 69, 23); jLabel14.setText("Latitude :"); jLabel14.setName("jLabel14"); // NOI18N FormInput1.add(jLabel14); jLabel14.setBounds(549, 10, 60, 23); LatitudeKamar.setHighlighter(null); LatitudeKamar.setName("LatitudeKamar"); // NOI18N LatitudeKamar.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { LatitudeKamarKeyPressed(evt); } }); FormInput1.add(LatitudeKamar); LatitudeKamar.setBounds(613, 10, 120, 23); jLabel15.setText("Altitude :"); jLabel15.setName("jLabel15"); // NOI18N FormInput1.add(jLabel15); jLabel15.setBounds(0, 40, 59, 23); AltitudeKamar.setHighlighter(null); AltitudeKamar.setName("AltitudeKamar"); // NOI18N AltitudeKamar.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { AltitudeKamarKeyPressed(evt); } }); FormInput1.add(AltitudeKamar); AltitudeKamar.setBounds(63, 40, 110, 23); internalFrame3.add(FormInput1, java.awt.BorderLayout.PAGE_START); Scroll1.setName("Scroll1"); // NOI18N Scroll1.setOpaque(true); tbLokasiKamar.setToolTipText("Silahkan klik untuk memilih data yang mau diedit ataupun dihapus"); tbLokasiKamar.setName("tbLokasiKamar"); // NOI18N tbLokasiKamar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tbLokasiKamarMouseClicked(evt); } }); tbLokasiKamar.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { tbLokasiKamarKeyReleased(evt); } }); Scroll1.setViewportView(tbLokasiKamar); internalFrame3.add(Scroll1, java.awt.BorderLayout.CENTER); TabRawat.addTab("Lokasi Ranap", internalFrame3); internalFrame4.setBackground(new java.awt.Color(235, 255, 235)); internalFrame4.setBorder(null); internalFrame4.setName("internalFrame4"); // NOI18N internalFrame4.setLayout(new java.awt.BorderLayout(1, 1)); FormInput2.setName("FormInput2"); // NOI18N FormInput2.setPreferredSize(new java.awt.Dimension(100, 74)); FormInput2.setLayout(null); jLabel16.setText("Organisasi :"); jLabel16.setName("jLabel16"); // NOI18N FormInput2.add(jLabel16); jLabel16.setBounds(0, 40, 75, 23); KodeDepartemenRuangOK.setEditable(false); KodeDepartemenRuangOK.setHighlighter(null); KodeDepartemenRuangOK.setName("KodeDepartemenRuangOK"); // NOI18N FormInput2.add(KodeDepartemenRuangOK); KodeDepartemenRuangOK.setBounds(79, 40, 75, 23); NamaDepartemenRuangOK.setEditable(false); NamaDepartemenRuangOK.setHighlighter(null); NamaDepartemenRuangOK.setName("NamaDepartemenRuangOK"); // NOI18N FormInput2.add(NamaDepartemenRuangOK); NamaDepartemenRuangOK.setBounds(156, 40, 275, 23); btnDepartemenRuangOK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/190.png"))); // NOI18N btnDepartemenRuangOK.setMnemonic('1'); btnDepartemenRuangOK.setToolTipText("Alt+1"); btnDepartemenRuangOK.setName("btnDepartemenRuangOK"); // NOI18N btnDepartemenRuangOK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDepartemenRuangOKActionPerformed(evt); } }); btnDepartemenRuangOK.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { btnDepartemenRuangOKKeyPressed(evt); } }); FormInput2.add(btnDepartemenRuangOK); btnDepartemenRuangOK.setBounds(705, 40, 28, 23); IDOrganisasiRuangOK.setEditable(false); IDOrganisasiRuangOK.setHighlighter(null); IDOrganisasiRuangOK.setName("IDOrganisasiRuangOK"); // NOI18N FormInput2.add(IDOrganisasiRuangOK); IDOrganisasiRuangOK.setBounds(433, 40, 270, 23); LongitudeRuangOK.setHighlighter(null); LongitudeRuangOK.setName("LongitudeRuangOK"); // NOI18N LongitudeRuangOK.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { LongitudeRuangOKKeyPressed(evt); } }); FormInput2.add(LongitudeRuangOK); LongitudeRuangOK.setBounds(79, 10, 165, 23); jLabel18.setText("Longitude :"); jLabel18.setName("jLabel18"); // NOI18N FormInput2.add(jLabel18); jLabel18.setBounds(0, 10, 75, 23); jLabel19.setText("Latitude :"); jLabel19.setName("jLabel19"); // NOI18N FormInput2.add(jLabel19); jLabel19.setBounds(261, 10, 60, 23); LatitudeRuangOK.setHighlighter(null); LatitudeRuangOK.setName("LatitudeRuangOK"); // NOI18N LatitudeRuangOK.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { LatitudeRuangOKKeyPressed(evt); } }); FormInput2.add(LatitudeRuangOK); LatitudeRuangOK.setBounds(325, 10, 165, 23); jLabel20.setText("Altitude :"); jLabel20.setName("jLabel20"); // NOI18N FormInput2.add(jLabel20); jLabel20.setBounds(505, 10, 59, 23); AltitudeRuangOK.setHighlighter(null); AltitudeRuangOK.setName("AltitudeRuangOK"); // NOI18N AltitudeRuangOK.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { AltitudeRuangOKKeyPressed(evt); } }); FormInput2.add(AltitudeRuangOK); AltitudeRuangOK.setBounds(568, 10, 165, 23); internalFrame4.add(FormInput2, java.awt.BorderLayout.PAGE_START); Scroll2.setName("Scroll2"); // NOI18N Scroll2.setOpaque(true); tbLokasiRuangOK.setToolTipText("Silahkan klik untuk memilih data yang mau diedit ataupun dihapus"); tbLokasiRuangOK.setName("tbLokasiRuangOK"); // NOI18N tbLokasiRuangOK.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tbLokasiRuangOKMouseClicked(evt); } }); tbLokasiRuangOK.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { tbLokasiRuangOKKeyReleased(evt); } }); Scroll2.setViewportView(tbLokasiRuangOK); internalFrame4.add(Scroll2, java.awt.BorderLayout.CENTER); TabRawat.addTab("Lokasi OK", internalFrame4); internalFrame5.setBackground(new java.awt.Color(235, 255, 235)); internalFrame5.setBorder(null); internalFrame5.setName("internalFrame5"); // NOI18N internalFrame5.setLayout(new java.awt.BorderLayout(1, 1)); FormInput3.setName("FormInput3"); // NOI18N FormInput3.setPreferredSize(new java.awt.Dimension(100, 74)); FormInput3.setLayout(null); jLabel17.setText("Organisasi :"); jLabel17.setName("jLabel17"); // NOI18N FormInput3.add(jLabel17); jLabel17.setBounds(0, 40, 75, 23); KodeDepartemenRuangLabPK.setEditable(false); KodeDepartemenRuangLabPK.setHighlighter(null); KodeDepartemenRuangLabPK.setName("KodeDepartemenRuangLabPK"); // NOI18N FormInput3.add(KodeDepartemenRuangLabPK); KodeDepartemenRuangLabPK.setBounds(79, 40, 75, 23); NamaDepartemenRuangLabPK.setEditable(false); NamaDepartemenRuangLabPK.setHighlighter(null); NamaDepartemenRuangLabPK.setName("NamaDepartemenRuangLabPK"); // NOI18N FormInput3.add(NamaDepartemenRuangLabPK); NamaDepartemenRuangLabPK.setBounds(156, 40, 275, 23); btnDepartemenRuangLabPK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/190.png"))); // NOI18N btnDepartemenRuangLabPK.setMnemonic('1'); btnDepartemenRuangLabPK.setToolTipText("Alt+1"); btnDepartemenRuangLabPK.setName("btnDepartemenRuangLabPK"); // NOI18N btnDepartemenRuangLabPK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDepartemenRuangLabPKActionPerformed(evt); } }); btnDepartemenRuangLabPK.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { btnDepartemenRuangLabPKKeyPressed(evt); } }); FormInput3.add(btnDepartemenRuangLabPK); btnDepartemenRuangLabPK.setBounds(705, 40, 28, 23); IDOrganisasiRuangLabPK.setEditable(false); IDOrganisasiRuangLabPK.setHighlighter(null); IDOrganisasiRuangLabPK.setName("IDOrganisasiRuangLabPK"); // NOI18N FormInput3.add(IDOrganisasiRuangLabPK); IDOrganisasiRuangLabPK.setBounds(433, 40, 270, 23); LongitudeRuangLabPK.setHighlighter(null); LongitudeRuangLabPK.setName("LongitudeRuangLabPK"); // NOI18N LongitudeRuangLabPK.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { LongitudeRuangLabPKKeyPressed(evt); } }); FormInput3.add(LongitudeRuangLabPK); LongitudeRuangLabPK.setBounds(79, 10, 165, 23); jLabel21.setText("Longitude :"); jLabel21.setName("jLabel21"); // NOI18N FormInput3.add(jLabel21); jLabel21.setBounds(0, 10, 75, 23); jLabel22.setText("Latitude :"); jLabel22.setName("jLabel22"); // NOI18N FormInput3.add(jLabel22); jLabel22.setBounds(261, 10, 60, 23); LatitudeRuangLabPK.setHighlighter(null); LatitudeRuangLabPK.setName("LatitudeRuangLabPK"); // NOI18N LatitudeRuangLabPK.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { LatitudeRuangLabPKKeyPressed(evt); } }); FormInput3.add(LatitudeRuangLabPK); LatitudeRuangLabPK.setBounds(325, 10, 165, 23); jLabel23.setText("Altitude :"); jLabel23.setName("jLabel23"); // NOI18N FormInput3.add(jLabel23); jLabel23.setBounds(505, 10, 59, 23); AltitudeRuangLabPK.setHighlighter(null); AltitudeRuangLabPK.setName("AltitudeRuangLabPK"); // NOI18N AltitudeRuangLabPK.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { AltitudeRuangLabPKKeyPressed(evt); } }); FormInput3.add(AltitudeRuangLabPK); AltitudeRuangLabPK.setBounds(568, 10, 165, 23); internalFrame5.add(FormInput3, java.awt.BorderLayout.PAGE_START); Scroll3.setName("Scroll3"); // NOI18N Scroll3.setOpaque(true); tbLokasiRuangLabPK.setToolTipText("Silahkan klik untuk memilih data yang mau diedit ataupun dihapus"); tbLokasiRuangLabPK.setName("tbLokasiRuangLabPK"); // NOI18N tbLokasiRuangLabPK.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tbLokasiRuangLabPKMouseClicked(evt); } }); tbLokasiRuangLabPK.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { tbLokasiRuangLabPKKeyReleased(evt); } }); Scroll3.setViewportView(tbLokasiRuangLabPK); internalFrame5.add(Scroll3, java.awt.BorderLayout.CENTER); TabRawat.addTab("Lokasi Lab PK", internalFrame5); internalFrame6.setBackground(new java.awt.Color(235, 255, 235)); internalFrame6.setBorder(null); internalFrame6.setName("internalFrame6"); // NOI18N internalFrame6.setLayout(new java.awt.BorderLayout(1, 1)); FormInput4.setName("FormInput4"); // NOI18N FormInput4.setPreferredSize(new java.awt.Dimension(100, 74)); FormInput4.setLayout(null); jLabel24.setText("Organisasi :"); jLabel24.setName("jLabel24"); // NOI18N FormInput4.add(jLabel24); jLabel24.setBounds(0, 40, 75, 23); KodeDepartemenRuangLabPA.setEditable(false); KodeDepartemenRuangLabPA.setHighlighter(null); KodeDepartemenRuangLabPA.setName("KodeDepartemenRuangLabPA"); // NOI18N FormInput4.add(KodeDepartemenRuangLabPA); KodeDepartemenRuangLabPA.setBounds(79, 40, 75, 23); NamaDepartemenRuangLabPA.setEditable(false); NamaDepartemenRuangLabPA.setHighlighter(null); NamaDepartemenRuangLabPA.setName("NamaDepartemenRuangLabPA"); // NOI18N FormInput4.add(NamaDepartemenRuangLabPA); NamaDepartemenRuangLabPA.setBounds(156, 40, 275, 23); btnDepartemenRuangLabPA.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/190.png"))); // NOI18N btnDepartemenRuangLabPA.setMnemonic('1'); btnDepartemenRuangLabPA.setToolTipText("Alt+1"); btnDepartemenRuangLabPA.setName("btnDepartemenRuangLabPA"); // NOI18N btnDepartemenRuangLabPA.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDepartemenRuangLabPAActionPerformed(evt); } }); btnDepartemenRuangLabPA.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { btnDepartemenRuangLabPAKeyPressed(evt); } }); FormInput4.add(btnDepartemenRuangLabPA); btnDepartemenRuangLabPA.setBounds(705, 40, 28, 23); IDOrganisasiRuangLabPA.setEditable(false); IDOrganisasiRuangLabPA.setHighlighter(null); IDOrganisasiRuangLabPA.setName("IDOrganisasiRuangLabPA"); // NOI18N FormInput4.add(IDOrganisasiRuangLabPA); IDOrganisasiRuangLabPA.setBounds(433, 40, 270, 23); LongitudeRuangLabPA.setHighlighter(null); LongitudeRuangLabPA.setName("LongitudeRuangLabPA"); // NOI18N LongitudeRuangLabPA.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { LongitudeRuangLabPAKeyPressed(evt); } }); FormInput4.add(LongitudeRuangLabPA); LongitudeRuangLabPA.setBounds(79, 10, 165, 23); jLabel25.setText("Longitude :"); jLabel25.setName("jLabel25"); // NOI18N FormInput4.add(jLabel25); jLabel25.setBounds(0, 10, 75, 23); jLabel26.setText("Latitude :"); jLabel26.setName("jLabel26"); // NOI18N FormInput4.add(jLabel26); jLabel26.setBounds(261, 10, 60, 23); LatitudeRuangLabPA.setHighlighter(null); LatitudeRuangLabPA.setName("LatitudeRuangLabPA"); // NOI18N LatitudeRuangLabPA.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { LatitudeRuangLabPAKeyPressed(evt); } }); FormInput4.add(LatitudeRuangLabPA); LatitudeRuangLabPA.setBounds(325, 10, 165, 23); jLabel27.setText("Altitude :"); jLabel27.setName("jLabel27"); // NOI18N FormInput4.add(jLabel27); jLabel27.setBounds(505, 10, 59, 23); AltitudeRuangLabPA.setHighlighter(null); AltitudeRuangLabPA.setName("AltitudeRuangLabPA"); // NOI18N AltitudeRuangLabPA.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { AltitudeRuangLabPAKeyPressed(evt); } }); FormInput4.add(AltitudeRuangLabPA); AltitudeRuangLabPA.setBounds(568, 10, 165, 23); internalFrame6.add(FormInput4, java.awt.BorderLayout.PAGE_START); Scroll4.setName("Scroll4"); // NOI18N Scroll4.setOpaque(true); tbLokasiRuangLabPA.setToolTipText("Silahkan klik untuk memilih data yang mau diedit ataupun dihapus"); tbLokasiRuangLabPA.setName("tbLokasiRuangLabPA"); // NOI18N tbLokasiRuangLabPA.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tbLokasiRuangLabPAMouseClicked(evt); } }); tbLokasiRuangLabPA.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { tbLokasiRuangLabPAKeyReleased(evt); } }); Scroll4.setViewportView(tbLokasiRuangLabPA); internalFrame6.add(Scroll4, java.awt.BorderLayout.CENTER); TabRawat.addTab("Lokasi Lab PA", internalFrame6); internalFrame7.setBackground(new java.awt.Color(235, 255, 235)); internalFrame7.setBorder(null); internalFrame7.setName("internalFrame7"); // NOI18N internalFrame7.setLayout(new java.awt.BorderLayout(1, 1)); FormInput5.setName("FormInput5"); // NOI18N FormInput5.setPreferredSize(new java.awt.Dimension(100, 74)); FormInput5.setLayout(null); jLabel28.setText("Organisasi :"); jLabel28.setName("jLabel28"); // NOI18N FormInput5.add(jLabel28); jLabel28.setBounds(0, 40, 75, 23); KodeDepartemenRuangLabMB.setEditable(false); KodeDepartemenRuangLabMB.setHighlighter(null); KodeDepartemenRuangLabMB.setName("KodeDepartemenRuangLabMB"); // NOI18N FormInput5.add(KodeDepartemenRuangLabMB); KodeDepartemenRuangLabMB.setBounds(79, 40, 75, 23); NamaDepartemenRuangLabMB.setEditable(false); NamaDepartemenRuangLabMB.setHighlighter(null); NamaDepartemenRuangLabMB.setName("NamaDepartemenRuangLabMB"); // NOI18N FormInput5.add(NamaDepartemenRuangLabMB); NamaDepartemenRuangLabMB.setBounds(156, 40, 275, 23); btnDepartemenRuangLabMB.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/190.png"))); // NOI18N btnDepartemenRuangLabMB.setMnemonic('1'); btnDepartemenRuangLabMB.setToolTipText("Alt+1"); btnDepartemenRuangLabMB.setName("btnDepartemenRuangLabMB"); // NOI18N btnDepartemenRuangLabMB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDepartemenRuangLabMBActionPerformed(evt); } }); btnDepartemenRuangLabMB.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { btnDepartemenRuangLabMBKeyPressed(evt); } }); FormInput5.add(btnDepartemenRuangLabMB); btnDepartemenRuangLabMB.setBounds(705, 40, 28, 23); IDOrganisasiRuangLabMB.setEditable(false); IDOrganisasiRuangLabMB.setHighlighter(null); IDOrganisasiRuangLabMB.setName("IDOrganisasiRuangLabMB"); // NOI18N FormInput5.add(IDOrganisasiRuangLabMB); IDOrganisasiRuangLabMB.setBounds(433, 40, 270, 23); LongitudeRuangLabMB.setHighlighter(null); LongitudeRuangLabMB.setName("LongitudeRuangLabMB"); // NOI18N LongitudeRuangLabMB.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { LongitudeRuangLabMBKeyPressed(evt); } }); FormInput5.add(LongitudeRuangLabMB); LongitudeRuangLabMB.setBounds(79, 10, 165, 23); jLabel29.setText("Longitude :"); jLabel29.setName("jLabel29"); // NOI18N FormInput5.add(jLabel29); jLabel29.setBounds(0, 10, 75, 23); jLabel30.setText("Latitude :"); jLabel30.setName("jLabel30"); // NOI18N FormInput5.add(jLabel30); jLabel30.setBounds(261, 10, 60, 23); LatitudeRuangLabMB.setHighlighter(null); LatitudeRuangLabMB.setName("LatitudeRuangLabMB"); // NOI18N LatitudeRuangLabMB.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { LatitudeRuangLabMBKeyPressed(evt); } }); FormInput5.add(LatitudeRuangLabMB); LatitudeRuangLabMB.setBounds(325, 10, 165, 23); jLabel31.setText("Altitude :"); jLabel31.setName("jLabel31"); // NOI18N FormInput5.add(jLabel31); jLabel31.setBounds(505, 10, 59, 23); AltitudeRuangLabMB.setHighlighter(null); AltitudeRuangLabMB.setName("AltitudeRuangLabMB"); // NOI18N AltitudeRuangLabMB.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { AltitudeRuangLabMBKeyPressed(evt); } }); FormInput5.add(AltitudeRuangLabMB); AltitudeRuangLabMB.setBounds(568, 10, 165, 23); internalFrame7.add(FormInput5, java.awt.BorderLayout.PAGE_START); Scroll5.setName("Scroll5"); // NOI18N Scroll5.setOpaque(true); tbLokasiRuangLabMB.setToolTipText("Silahkan klik untuk memilih data yang mau diedit ataupun dihapus"); tbLokasiRuangLabMB.setName("tbLokasiRuangLabMB"); // NOI18N tbLokasiRuangLabMB.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tbLokasiRuangLabMBMouseClicked(evt); } }); tbLokasiRuangLabMB.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { tbLokasiRuangLabMBKeyReleased(evt); } }); Scroll5.setViewportView(tbLokasiRuangLabMB); internalFrame7.add(Scroll5, java.awt.BorderLayout.CENTER); TabRawat.addTab("Lokasi Lab MB", internalFrame7); internalFrame8.setBackground(new java.awt.Color(235, 255, 235)); internalFrame8.setBorder(null); internalFrame8.setName("internalFrame8"); // NOI18N internalFrame8.setLayout(new java.awt.BorderLayout(1, 1)); FormInput6.setName("FormInput6"); // NOI18N FormInput6.setPreferredSize(new java.awt.Dimension(100, 74)); FormInput6.setLayout(null); jLabel32.setText("Organisasi :"); jLabel32.setName("jLabel32"); // NOI18N FormInput6.add(jLabel32); jLabel32.setBounds(0, 40, 75, 23); KodeDepartemenRuangRadiologi.setEditable(false); KodeDepartemenRuangRadiologi.setHighlighter(null); KodeDepartemenRuangRadiologi.setName("KodeDepartemenRuangRadiologi"); // NOI18N FormInput6.add(KodeDepartemenRuangRadiologi); KodeDepartemenRuangRadiologi.setBounds(79, 40, 75, 23); NamaDepartemenRuangRadiologi.setEditable(false); NamaDepartemenRuangRadiologi.setHighlighter(null); NamaDepartemenRuangRadiologi.setName("NamaDepartemenRuangRadiologi"); // NOI18N FormInput6.add(NamaDepartemenRuangRadiologi); NamaDepartemenRuangRadiologi.setBounds(156, 40, 275, 23); btnDepartemenRuangRadiologi.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/190.png"))); // NOI18N btnDepartemenRuangRadiologi.setMnemonic('1'); btnDepartemenRuangRadiologi.setToolTipText("Alt+1"); btnDepartemenRuangRadiologi.setName("btnDepartemenRuangRadiologi"); // NOI18N btnDepartemenRuangRadiologi.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDepartemenRuangRadiologiActionPerformed(evt); } }); btnDepartemenRuangRadiologi.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { btnDepartemenRuangRadiologiKeyPressed(evt); } }); FormInput6.add(btnDepartemenRuangRadiologi); btnDepartemenRuangRadiologi.setBounds(705, 40, 28, 23); IDOrganisasiRuangRadiologi.setEditable(false); IDOrganisasiRuangRadiologi.setHighlighter(null); IDOrganisasiRuangRadiologi.setName("IDOrganisasiRuangRadiologi"); // NOI18N FormInput6.add(IDOrganisasiRuangRadiologi); IDOrganisasiRuangRadiologi.setBounds(433, 40, 270, 23); LongitudeRuangRadiologi.setHighlighter(null); LongitudeRuangRadiologi.setName("LongitudeRuangRadiologi"); // NOI18N LongitudeRuangRadiologi.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { LongitudeRuangRadiologiKeyPressed(evt); } }); FormInput6.add(LongitudeRuangRadiologi); LongitudeRuangRadiologi.setBounds(79, 10, 165, 23); jLabel33.setText("Longitude :"); jLabel33.setName("jLabel33"); // NOI18N FormInput6.add(jLabel33); jLabel33.setBounds(0, 10, 75, 23); jLabel34.setText("Latitude :"); jLabel34.setName("jLabel34"); // NOI18N FormInput6.add(jLabel34); jLabel34.setBounds(261, 10, 60, 23); LatitudeRuangRadiologi.setHighlighter(null); LatitudeRuangRadiologi.setName("LatitudeRuangRadiologi"); // NOI18N LatitudeRuangRadiologi.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { LatitudeRuangRadiologiKeyPressed(evt); } }); FormInput6.add(LatitudeRuangRadiologi); LatitudeRuangRadiologi.setBounds(325, 10, 165, 23); jLabel35.setText("Altitude :"); jLabel35.setName("jLabel35"); // NOI18N FormInput6.add(jLabel35); jLabel35.setBounds(505, 10, 59, 23); AltitudeRuangRadiologi.setHighlighter(null); AltitudeRuangRadiologi.setName("AltitudeRuangRadiologi"); // NOI18N AltitudeRuangRadiologi.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { AltitudeRuangRadiologiKeyPressed(evt); } }); FormInput6.add(AltitudeRuangRadiologi); AltitudeRuangRadiologi.setBounds(568, 10, 165, 23); internalFrame8.add(FormInput6, java.awt.BorderLayout.PAGE_START); Scroll6.setName("Scroll6"); // NOI18N Scroll6.setOpaque(true); tbLokasiRuangRadiologi.setToolTipText("Silahkan klik untuk memilih data yang mau diedit ataupun dihapus"); tbLokasiRuangRadiologi.setName("tbLokasiRuangRadiologi"); // NOI18N tbLokasiRuangRadiologi.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tbLokasiRuangRadiologiMouseClicked(evt); } }); tbLokasiRuangRadiologi.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { tbLokasiRuangRadiologiKeyReleased(evt); } }); Scroll6.setViewportView(tbLokasiRuangRadiologi); internalFrame8.add(Scroll6, java.awt.BorderLayout.CENTER); TabRawat.addTab("Lokasi Radiologi", internalFrame8); internalFrame9.setBackground(new java.awt.Color(235, 255, 235)); internalFrame9.setBorder(null); internalFrame9.setName("internalFrame9"); // NOI18N internalFrame9.setLayout(new java.awt.BorderLayout(1, 1)); FormInput7.setName("FormInput7"); // NOI18N FormInput7.setPreferredSize(new java.awt.Dimension(100, 74)); FormInput7.setLayout(null); jLabel36.setText("Organisasi :"); jLabel36.setName("jLabel36"); // NOI18N FormInput7.add(jLabel36); jLabel36.setBounds(170, 40, 74, 23); KodeDepartemenFarmasi.setEditable(false); KodeDepartemenFarmasi.setHighlighter(null); KodeDepartemenFarmasi.setName("KodeDepartemenFarmasi"); // NOI18N FormInput7.add(KodeDepartemenFarmasi); KodeDepartemenFarmasi.setBounds(248, 40, 55, 23); NamaDepartemenFarmasi.setEditable(false); NamaDepartemenFarmasi.setHighlighter(null); NamaDepartemenFarmasi.setName("NamaDepartemenFarmasi"); // NOI18N FormInput7.add(NamaDepartemenFarmasi); NamaDepartemenFarmasi.setBounds(305, 40, 176, 23); btnDepartemenFarmasi.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/190.png"))); // NOI18N btnDepartemenFarmasi.setMnemonic('1'); btnDepartemenFarmasi.setToolTipText("Alt+1"); btnDepartemenFarmasi.setName("btnDepartemenFarmasi"); // NOI18N btnDepartemenFarmasi.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDepartemenFarmasiActionPerformed(evt); } }); btnDepartemenFarmasi.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { btnDepartemenFarmasiKeyPressed(evt); } }); FormInput7.add(btnDepartemenFarmasi); btnDepartemenFarmasi.setBounds(705, 40, 28, 23); jLabel37.setText("Farmasi :"); jLabel37.setName("jLabel37"); // NOI18N FormInput7.add(jLabel37); jLabel37.setBounds(0, 10, 59, 23); KodeFarmasi.setEditable(false); KodeFarmasi.setHighlighter(null); KodeFarmasi.setName("KodeFarmasi"); // NOI18N FormInput7.add(KodeFarmasi); KodeFarmasi.setBounds(63, 10, 70, 23); NamaFarmasi.setEditable(false); NamaFarmasi.setHighlighter(null); NamaFarmasi.setName("NamaFarmasi"); // NOI18N FormInput7.add(NamaFarmasi); NamaFarmasi.setBounds(135, 10, 195, 23); btnFarmasi.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/190.png"))); // NOI18N btnFarmasi.setMnemonic('1'); btnFarmasi.setToolTipText("Alt+1"); btnFarmasi.setName("btnFarmasi"); // NOI18N btnFarmasi.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnFarmasiActionPerformed(evt); } }); btnFarmasi.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { btnFarmasiKeyPressed(evt); } }); FormInput7.add(btnFarmasi); btnFarmasi.setBounds(332, 10, 28, 23); IDOrganisasiFarmasi.setEditable(false); IDOrganisasiFarmasi.setHighlighter(null); IDOrganisasiFarmasi.setName("IDOrganisasiFarmasi"); // NOI18N FormInput7.add(IDOrganisasiFarmasi); IDOrganisasiFarmasi.setBounds(483, 40, 220, 23); LongitudeFarmasi.setHighlighter(null); LongitudeFarmasi.setName("LongitudeFarmasi"); // NOI18N LongitudeFarmasi.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { LongitudeFarmasiKeyPressed(evt); } }); FormInput7.add(LongitudeFarmasi); LongitudeFarmasi.setBounds(430, 10, 120, 23); jLabel38.setText("Longitude :"); jLabel38.setName("jLabel38"); // NOI18N FormInput7.add(jLabel38); jLabel38.setBounds(357, 10, 69, 23); jLabel39.setText("Latitude :"); jLabel39.setName("jLabel39"); // NOI18N FormInput7.add(jLabel39); jLabel39.setBounds(549, 10, 60, 23); LatitudeFarmasi.setHighlighter(null); LatitudeFarmasi.setName("LatitudeFarmasi"); // NOI18N LatitudeFarmasi.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { LatitudeFarmasiKeyPressed(evt); } }); FormInput7.add(LatitudeFarmasi); LatitudeFarmasi.setBounds(613, 10, 120, 23); jLabel40.setText("Altitude :"); jLabel40.setName("jLabel40"); // NOI18N FormInput7.add(jLabel40); jLabel40.setBounds(0, 40, 59, 23); AltitudeFarmasi.setHighlighter(null); AltitudeFarmasi.setName("AltitudeFarmasi"); // NOI18N AltitudeFarmasi.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { AltitudeFarmasiKeyPressed(evt); } }); FormInput7.add(AltitudeFarmasi); AltitudeFarmasi.setBounds(63, 40, 110, 23); internalFrame9.add(FormInput7, java.awt.BorderLayout.PAGE_START); Scroll7.setName("Scroll7"); // NOI18N Scroll7.setOpaque(true); tbLokasiFarmasi.setToolTipText("Silahkan klik untuk memilih data yang mau diedit ataupun dihapus"); tbLokasiFarmasi.setName("tbLokasiFarmasi"); // NOI18N tbLokasiFarmasi.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tbLokasiFarmasiMouseClicked(evt); } }); tbLokasiFarmasi.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { tbLokasiFarmasiKeyReleased(evt); } }); Scroll7.setViewportView(tbLokasiFarmasi); internalFrame9.add(Scroll7, java.awt.BorderLayout.CENTER); TabRawat.addTab("Lokasi Depo Farmasi", internalFrame9); internalFrame1.add(TabRawat, java.awt.BorderLayout.CENTER); getContentPane().add(internalFrame1, java.awt.BorderLayout.CENTER); pack(); }// </editor-fold>//GEN-END:initComponents private void btnDepartemenRSActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDepartemenRSActionPerformed pilih=1; organisasi.setSize(internalFrame1.getWidth()-20,internalFrame1.getHeight()-20); organisasi.setLocationRelativeTo(internalFrame1); organisasi.setVisible(true); }//GEN-LAST:event_btnDepartemenRSActionPerformed private void btnDepartemenRSKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnDepartemenRSKeyPressed Valid.pindah(evt, Altitude,BtnSimpan); }//GEN-LAST:event_btnDepartemenRSKeyPressed private void BtnSimpanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnSimpanActionPerformed if(TabRawat.getSelectedIndex()==0){ if(KodeDepartemen.getText().trim().equals("")||NamaDepartemen.getText().trim().equals("")){ Valid.textKosong(KodeDepartemen,"Departemen/Organisasi"); }else if(KodePoli.getText().trim().equals("")||NamaPoli.getText().trim().equals("")){ Valid.textKosong(KodePoli,"Poli/Unit"); }else if(Longitude.getText().trim().equals("")){ Valid.textKosong(Longitude,"Longitude"); }else if(Latitude.getText().trim().equals("")){ Valid.textKosong(Latitude,"Latitude"); }else if(Altitude.getText().trim().equals("")){ Valid.textKosong(Altitude,"Altitude"); }else{ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \""+KodePoli.getText()+"\"" + "}" + "]," + "\"status\": \"active\"," + "\"name\": \""+NamaPoli.getText()+"\"," + "\"description\": \""+NamaPoli.getText()+"\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+Longitude.getText()+"," + "\"latitude\": "+Latitude.getText()+"," + "\"altitude\": "+Altitude.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasi.getText()+"\"" + "}" + "}"; System.out.println("URL : "+link+"/Location"); System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location", HttpMethod.POST, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Sequel.menyimpantf("satu_sehat_mapping_lokasi_ralan","?,?,?,?,?,?","Kode Poli/Kode Unit/ID Lokasi",6,new String[]{ KodePoli.getText(),IDOrganisasi.getText(),response.asText(),Longitude.getText(),Latitude.getText(),Altitude.getText() })==true){ tabMode.addRow(new String[]{ KodePoli.getText(),NamaPoli.getText(),response.asText(),Longitude.getText(),Latitude.getText(), Altitude.getText(),KodeDepartemen.getText(),NamaDepartemen.getText(),IDOrganisasi.getText() }); emptTeks(); LCount.setText(""+tabMode.getRowCount()); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping organisasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } } }else if(TabRawat.getSelectedIndex()==1){ if(KodeDepartemenKamar.getText().trim().equals("")||NamaDepartemenKamar.getText().trim().equals("")){ Valid.textKosong(KodeDepartemenKamar,"Departemen/Organisasi"); }else if(KodeKamar.getText().trim().equals("")||NamaKamar.getText().trim().equals("")){ Valid.textKosong(KodeKamar,"Kamar/Ruang"); }else if(LongitudeKamar.getText().trim().equals("")){ Valid.textKosong(LongitudeKamar,"Longitude"); }else if(LatitudeKamar.getText().trim().equals("")){ Valid.textKosong(LatitudeKamar,"Latitude"); }else if(AltitudeKamar.getText().trim().equals("")){ Valid.textKosong(AltitudeKamar,"Altitude"); }else{ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \""+KodeKamar.getText()+"\"" + "}" + "]," + "\"status\": \"active\"," + "\"name\": \""+NamaKamar.getText()+"\"," + "\"description\": \""+NamaKamar.getText()+" Nomor "+KodeKamar.getText()+"\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+LongitudeKamar.getText()+"," + "\"latitude\": "+LatitudeKamar.getText()+"," + "\"altitude\": "+AltitudeKamar.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasiKamar.getText()+"\"" + "}" + "}"; System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location", HttpMethod.POST, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Sequel.menyimpantf("satu_sehat_mapping_lokasi_ranap","?,?,?,?,?,?","Kode Kamar/Kode Ruang/ID Lokasi",6,new String[]{ KodeKamar.getText(),IDOrganisasiKamar.getText(),response.asText(),LongitudeKamar.getText(),LatitudeKamar.getText(),AltitudeKamar.getText() })==true){ tabModeKamar.addRow(new String[]{ KodeKamar.getText(),NamaKamar.getText(),response.asText(),LongitudeKamar.getText(),LatitudeKamar.getText(), AltitudeKamar.getText(),KodeDepartemenKamar.getText(),NamaDepartemenKamar.getText(),IDOrganisasiKamar.getText() }); emptTeks(); LCount.setText(""+tabModeKamar.getRowCount()); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping organisasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } } }else if(TabRawat.getSelectedIndex()==2){ if(tabModeRuangOK.getRowCount()==0){ if(KodeDepartemenRuangOK.getText().trim().equals("")||NamaDepartemenRuangOK.getText().trim().equals("")){ Valid.textKosong(KodeDepartemenRuangOK,"Departemen/Organisasi"); }else if(LongitudeRuangOK.getText().trim().equals("")){ Valid.textKosong(LongitudeRuangOK,"Longitude"); }else if(LatitudeRuangOK.getText().trim().equals("")){ Valid.textKosong(LatitudeRuangOK,"Latitude"); }else if(AltitudeRuangOK.getText().trim().equals("")){ Valid.textKosong(AltitudeRuangOK,"Altitude"); }else{ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \"R.OK.FAS\"" + "}" + "]," + "\"status\": \"active\"," + "\"name\": \"Ruang Operasi\"," + "\"description\": \"Ruang Operasi\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+LongitudeRuangOK.getText()+"," + "\"latitude\": "+LatitudeRuangOK.getText()+"," + "\"altitude\": "+AltitudeRuangOK.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasiRuangOK.getText()+"\"" + "}" + "}"; System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location", HttpMethod.POST, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Sequel.menyimpantf("satu_sehat_mapping_lokasi_ruangok","?,?,?,?,?","ID Lokasi",5,new String[]{ IDOrganisasiRuangOK.getText(),response.asText(),LongitudeRuangOK.getText(),LatitudeRuangOK.getText(),AltitudeRuangOK.getText() })==true){ tabModeRuangOK.addRow(new String[]{ response.asText(),LongitudeRuangOK.getText(),LatitudeRuangOK.getText(),AltitudeRuangOK.getText(),KodeDepartemenRuangOK.getText(),NamaDepartemenRuangOK.getText(),IDOrganisasiRuangOK.getText() }); emptTeks(); LCount.setText(""+tabModeRuangOK.getRowCount()); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping organisasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } } }else{ JOptionPane.showMessageDialog(null,"Untuk Ruang OK hanya diijinkan satu mapping lokasi"); } }else if(TabRawat.getSelectedIndex()==3){ if(tabModeRuangLabPK.getRowCount()==0){ if(KodeDepartemenRuangLabPK.getText().trim().equals("")||NamaDepartemenRuangLabPK.getText().trim().equals("")){ Valid.textKosong(KodeDepartemenRuangLabPK,"Departemen/Organisasi"); }else if(LongitudeRuangLabPK.getText().trim().equals("")){ Valid.textKosong(LongitudeRuangLabPK,"Longitude"); }else if(LatitudeRuangLabPK.getText().trim().equals("")){ Valid.textKosong(LatitudeRuangLabPK,"Latitude"); }else if(AltitudeRuangLabPK.getText().trim().equals("")){ Valid.textKosong(AltitudeRuangLabPK,"Altitude"); }else{ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \"R.LABPK.FAS\"" + "}" + "]," + "\"status\": \"active\"," + "\"name\": \"Ruang Laboratorium Patologi Klinik\"," + "\"description\": \"Ruang Laboratorium Patologi Klinik\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+LongitudeRuangLabPK.getText()+"," + "\"latitude\": "+LatitudeRuangLabPK.getText()+"," + "\"altitude\": "+AltitudeRuangLabPK.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasiRuangLabPK.getText()+"\"" + "}" + "}"; System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location", HttpMethod.POST, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Sequel.menyimpantf("satu_sehat_mapping_lokasi_ruanglab","?,?,?,?,?","ID Lokasi",5,new String[]{ IDOrganisasiRuangLabPK.getText(),response.asText(),LongitudeRuangLabPK.getText(),LatitudeRuangLabPK.getText(),AltitudeRuangLabPK.getText() })==true){ tabModeRuangLabPK.addRow(new String[]{ response.asText(),LongitudeRuangLabPK.getText(),LatitudeRuangLabPK.getText(),AltitudeRuangLabPK.getText(),KodeDepartemenRuangLabPK.getText(),NamaDepartemenRuangLabPK.getText(),IDOrganisasiRuangLabPK.getText() }); emptTeks(); LCount.setText(""+tabModeRuangLabPK.getRowCount()); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping organisasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } } }else{ JOptionPane.showMessageDialog(null,"Untuk Ruang Lab PK hanya diijinkan satu mapping lokasi"); } }else if(TabRawat.getSelectedIndex()==4){ if(tabModeRuangLabPA.getRowCount()==0){ if(KodeDepartemenRuangLabPA.getText().trim().equals("")||NamaDepartemenRuangLabPA.getText().trim().equals("")){ Valid.textKosong(KodeDepartemenRuangLabPA,"Departemen/Organisasi"); }else if(LongitudeRuangLabPA.getText().trim().equals("")){ Valid.textKosong(LongitudeRuangLabPA,"Longitude"); }else if(LatitudeRuangLabPA.getText().trim().equals("")){ Valid.textKosong(LatitudeRuangLabPA,"Latitude"); }else if(AltitudeRuangLabPA.getText().trim().equals("")){ Valid.textKosong(AltitudeRuangLabPA,"Altitude"); }else{ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \"R.LABPA.FAS\"" + "}" + "]," + "\"status\": \"active\"," + "\"name\": \"Ruang Laboratorium Patologi Anatomi\"," + "\"description\": \"Ruang Laboratorium Patologi Anatomi\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+LongitudeRuangLabPA.getText()+"," + "\"latitude\": "+LatitudeRuangLabPA.getText()+"," + "\"altitude\": "+AltitudeRuangLabPA.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasiRuangLabPA.getText()+"\"" + "}" + "}"; System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location", HttpMethod.POST, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Sequel.menyimpantf("satu_sehat_mapping_lokasi_ruanglabpa","?,?,?,?,?","ID Lokasi",5,new String[]{ IDOrganisasiRuangLabPA.getText(),response.asText(),LongitudeRuangLabPA.getText(),LatitudeRuangLabPA.getText(),AltitudeRuangLabPA.getText() })==true){ tabModeRuangLabPA.addRow(new String[]{ response.asText(),LongitudeRuangLabPA.getText(),LatitudeRuangLabPA.getText(),AltitudeRuangLabPA.getText(),KodeDepartemenRuangLabPA.getText(),NamaDepartemenRuangLabPA.getText(),IDOrganisasiRuangLabPA.getText() }); emptTeks(); LCount.setText(""+tabModeRuangLabPA.getRowCount()); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping organisasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } } }else{ JOptionPane.showMessageDialog(null,"Untuk Ruang Lab PA hanya diijinkan satu mapping lokasi"); } }else if(TabRawat.getSelectedIndex()==5){ if(tabModeRuangLabMB.getRowCount()==0){ if(KodeDepartemenRuangLabMB.getText().trim().equals("")||NamaDepartemenRuangLabMB.getText().trim().equals("")){ Valid.textKosong(KodeDepartemenRuangLabMB,"Departemen/Organisasi"); }else if(LongitudeRuangLabMB.getText().trim().equals("")){ Valid.textKosong(LongitudeRuangLabMB,"Longitude"); }else if(LatitudeRuangLabMB.getText().trim().equals("")){ Valid.textKosong(LatitudeRuangLabMB,"Latitude"); }else if(AltitudeRuangLabMB.getText().trim().equals("")){ Valid.textKosong(AltitudeRuangLabMB,"Altitude"); }else{ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \"R.LABMB.FAS\"" + "}" + "]," + "\"status\": \"active\"," + "\"name\": \"Ruang Laboratorium Mikrobiologi & Bio Molekuler\"," + "\"description\": \"Ruang Laboratorium Mikrobiologi & Bio Molekuler\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+LongitudeRuangLabMB.getText()+"," + "\"latitude\": "+LatitudeRuangLabMB.getText()+"," + "\"altitude\": "+AltitudeRuangLabMB.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasiRuangLabMB.getText()+"\"" + "}" + "}"; System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location", HttpMethod.POST, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Sequel.menyimpantf("satu_sehat_mapping_lokasi_ruanglabmb","?,?,?,?,?","ID Lokasi",5,new String[]{ IDOrganisasiRuangLabMB.getText(),response.asText(),LongitudeRuangLabMB.getText(),LatitudeRuangLabMB.getText(),AltitudeRuangLabMB.getText() })==true){ tabModeRuangLabMB.addRow(new String[]{ response.asText(),LongitudeRuangLabMB.getText(),LatitudeRuangLabMB.getText(),AltitudeRuangLabMB.getText(),KodeDepartemenRuangLabMB.getText(),NamaDepartemenRuangLabMB.getText(),IDOrganisasiRuangLabMB.getText() }); emptTeks(); LCount.setText(""+tabModeRuangLabMB.getRowCount()); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping organisasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } } }else{ JOptionPane.showMessageDialog(null,"Untuk Ruang Lab MB hanya diijinkan satu mapping lokasi"); } }else if(TabRawat.getSelectedIndex()==6){ if(tabModeRuangRadiologi.getRowCount()==0){ if(KodeDepartemenRuangRadiologi.getText().trim().equals("")||NamaDepartemenRuangRadiologi.getText().trim().equals("")){ Valid.textKosong(KodeDepartemenRuangRadiologi,"Departemen/Organisasi"); }else if(LongitudeRuangRadiologi.getText().trim().equals("")){ Valid.textKosong(LongitudeRuangRadiologi,"Longitude"); }else if(LatitudeRuangRadiologi.getText().trim().equals("")){ Valid.textKosong(LatitudeRuangRadiologi,"Latitude"); }else if(AltitudeRuangRadiologi.getText().trim().equals("")){ Valid.textKosong(AltitudeRuangRadiologi,"Altitude"); }else{ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \"R.RAD.FAS\"" + "}" + "]," + "\"status\": \"active\"," + "\"name\": \"Ruang Radiologi\"," + "\"description\": \"Ruang Radiologi\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+LongitudeRuangRadiologi.getText()+"," + "\"latitude\": "+LatitudeRuangRadiologi.getText()+"," + "\"altitude\": "+AltitudeRuangRadiologi.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasiRuangRadiologi.getText()+"\"" + "}" + "}"; System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location", HttpMethod.POST, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Sequel.menyimpantf("satu_sehat_mapping_lokasi_ruangrad","?,?,?,?,?","ID Lokasi",5,new String[]{ IDOrganisasiRuangRadiologi.getText(),response.asText(),LongitudeRuangRadiologi.getText(),LatitudeRuangRadiologi.getText(),AltitudeRuangRadiologi.getText() })==true){ tabModeRuangRadiologi.addRow(new String[]{ response.asText(),LongitudeRuangRadiologi.getText(),LatitudeRuangRadiologi.getText(),AltitudeRuangRadiologi.getText(),KodeDepartemenRuangRadiologi.getText(),NamaDepartemenRuangRadiologi.getText(),IDOrganisasiRuangRadiologi.getText() }); emptTeks(); LCount.setText(""+tabModeRuangRadiologi.getRowCount()); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping organisasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } } }else{ JOptionPane.showMessageDialog(null,"Untuk Ruang Lab MB hanya diijinkan satu mapping lokasi"); } }else if(TabRawat.getSelectedIndex()==7){ if(KodeDepartemenFarmasi.getText().trim().equals("")||NamaDepartemenFarmasi.getText().trim().equals("")){ Valid.textKosong(KodeDepartemenFarmasi,"Departemen/Organisasi"); }else if(KodeFarmasi.getText().trim().equals("")||NamaFarmasi.getText().trim().equals("")){ Valid.textKosong(KodeFarmasi,"Farmasi/Depo"); }else if(LongitudeFarmasi.getText().trim().equals("")){ Valid.textKosong(LongitudeFarmasi,"Longitude"); }else if(LatitudeFarmasi.getText().trim().equals("")){ Valid.textKosong(LatitudeFarmasi,"Latitude"); }else if(AltitudeFarmasi.getText().trim().equals("")){ Valid.textKosong(AltitudeFarmasi,"Altitude"); }else{ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \""+KodeFarmasi.getText()+"\"" + "}" + "]," + "\"status\": \"active\"," + "\"name\": \""+NamaFarmasi.getText()+"\"," + "\"description\": \""+NamaFarmasi.getText()+"\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+LongitudeFarmasi.getText()+"," + "\"latitude\": "+LatitudeFarmasi.getText()+"," + "\"altitude\": "+AltitudeFarmasi.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasiFarmasi.getText()+"\"" + "}" + "}"; System.out.println("URL : "+link+"/Location"); System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location", HttpMethod.POST, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Sequel.menyimpantf("satu_sehat_mapping_lokasi_depo_farmasi","?,?,?,?,?,?","Kode Depo/Kode Farmasi",6,new String[]{ KodeFarmasi.getText(),IDOrganisasiFarmasi.getText(),response.asText(),LongitudeFarmasi.getText(),LatitudeFarmasi.getText(),AltitudeFarmasi.getText() })==true){ tabModeRuangFarmasi.addRow(new String[]{ KodeFarmasi.getText(),NamaFarmasi.getText(),response.asText(),LongitudeFarmasi.getText(),LatitudeFarmasi.getText(), AltitudeFarmasi.getText(),KodeDepartemenFarmasi.getText(),NamaDepartemenFarmasi.getText(),IDOrganisasiFarmasi.getText() }); emptTeks(); LCount.setText(""+tabModeRuangFarmasi.getRowCount()); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping organisasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } } } }//GEN-LAST:event_BtnSimpanActionPerformed private void BtnSimpanKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_BtnSimpanKeyPressed if(evt.getKeyCode()==KeyEvent.VK_SPACE){ BtnSimpanActionPerformed(null); }else{ if(TabRawat.getSelectedIndex()==0){ Valid.pindah(evt,btnDepartemenRS, BtnBatal); }else if(TabRawat.getSelectedIndex()==1){ Valid.pindah(evt,btnDepartemenKamar, BtnBatal); }else if(TabRawat.getSelectedIndex()==2){ Valid.pindah(evt,btnDepartemenRuangOK, BtnBatal); }else if(TabRawat.getSelectedIndex()==3){ Valid.pindah(evt,btnDepartemenRuangLabPK, BtnBatal); }else if(TabRawat.getSelectedIndex()==4){ Valid.pindah(evt,btnDepartemenRuangLabPA, BtnBatal); }else if(TabRawat.getSelectedIndex()==5){ Valid.pindah(evt,btnDepartemenRuangLabMB, BtnBatal); }else if(TabRawat.getSelectedIndex()==6){ Valid.pindah(evt,btnDepartemenRuangRadiologi, BtnBatal); }else if(TabRawat.getSelectedIndex()==7){ Valid.pindah(evt,btnDepartemenFarmasi, BtnBatal); } } }//GEN-LAST:event_BtnSimpanKeyPressed private void BtnBatalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnBatalActionPerformed emptTeks(); }//GEN-LAST:event_BtnBatalActionPerformed private void BtnBatalKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_BtnBatalKeyPressed if(evt.getKeyCode()==KeyEvent.VK_SPACE){ emptTeks(); }else{Valid.pindah(evt, BtnSimpan, BtnHapus);} }//GEN-LAST:event_BtnBatalKeyPressed private void BtnHapusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnHapusActionPerformed if(TabRawat.getSelectedIndex()==0){ if(tbJnsPerawatan.getSelectedRow()>-1){ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"id\": \""+tbJnsPerawatan.getValueAt(tbJnsPerawatan.getSelectedRow(),2).toString()+"\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \""+KodePoli.getText()+"\"" + "}" + "]," + "\"status\": \"inactive\"," + "\"name\": \""+NamaPoli.getText()+"\"," + "\"description\": \""+NamaPoli.getText()+"\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+Longitude.getText()+"," + "\"latitude\": "+Latitude.getText()+"," + "\"altitude\": "+Altitude.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasi.getText()+"\"" + "}" + "}"; System.out.println("URL : "+link+"/Location"); System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location/"+tbJnsPerawatan.getValueAt(tbJnsPerawatan.getSelectedRow(),2).toString(), HttpMethod.PUT, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Valid.hapusTabletf(tabMode,KodePoli,"satu_sehat_mapping_lokasi_ralan","kd_poli")==true){ tabMode.removeRow(tbJnsPerawatan.getSelectedRow()); emptTeks(); LCount.setText(""+tabMode.getRowCount()); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping lokasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } }else{ JOptionPane.showMessageDialog(null,"Silahkan pilih data terlebih dahulu..!!"); } }else if(TabRawat.getSelectedIndex()==1){ if(tbLokasiKamar.getSelectedRow()>-1){ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"id\": \""+tbLokasiKamar.getValueAt(tbLokasiKamar.getSelectedRow(),2).toString()+"\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \""+KodeKamar.getText()+"\"" + "}" + "]," + "\"status\": \"inactive\"," + "\"name\": \""+NamaKamar.getText()+"\"," + "\"description\": \""+NamaKamar.getText()+" Nomor "+KodeKamar.getText()+"\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+LongitudeKamar.getText()+"," + "\"latitude\": "+LatitudeKamar.getText()+"," + "\"altitude\": "+AltitudeKamar.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasiKamar.getText()+"\"" + "}" + "}"; System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location/"+tbLokasiKamar.getValueAt(tbLokasiKamar.getSelectedRow(),2).toString(), HttpMethod.PUT, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Valid.hapusTabletf(tabModeKamar,KodeKamar,"satu_sehat_mapping_lokasi_ranap","kd_kamar")==true){ tabModeKamar.removeRow(tbLokasiKamar.getSelectedRow()); emptTeks(); LCount.setText(""+tabModeKamar.getRowCount()); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping lokasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } }else{ JOptionPane.showMessageDialog(null,"Silahkan pilih data terlebih dahulu..!!"); } }else if(TabRawat.getSelectedIndex()==2){ if(KodeDepartemenRuangOK.getText().trim().equals("")||NamaDepartemenRuangOK.getText().trim().equals("")){ Valid.textKosong(KodeDepartemenRuangOK,"Departemen/Organisasi"); }else if(LongitudeRuangOK.getText().trim().equals("")){ Valid.textKosong(LongitudeRuangOK,"Longitude"); }else if(LatitudeRuangOK.getText().trim().equals("")){ Valid.textKosong(LatitudeRuangOK,"Latitude"); }else if(AltitudeRuangOK.getText().trim().equals("")){ Valid.textKosong(AltitudeRuangOK,"Altitude"); }else{ if(tbLokasiRuangOK.getSelectedRow()>-1){ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"id\": \""+tbLokasiRuangOK.getValueAt(tbLokasiRuangOK.getSelectedRow(),0).toString()+"\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \"R.OK.FAS\"" + "}" + "]," + "\"status\": \"inactive\"," + "\"name\": \"Ruang Operasi\"," + "\"description\": \"Ruang Operasi\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+LongitudeRuangOK.getText()+"," + "\"latitude\": "+LatitudeRuangOK.getText()+"," + "\"altitude\": "+AltitudeRuangOK.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasiRuangOK.getText()+"\"" + "}" + "}"; System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location/"+tbLokasiRuangOK.getValueAt(tbLokasiRuangOK.getSelectedRow(),0).toString(), HttpMethod.PUT, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Sequel.meghapustf("satu_sehat_mapping_lokasi_ruangok","id_lokasi_satusehat",tbLokasiRuangOK.getValueAt(tbLokasiRuangOK.getSelectedRow(),0).toString())==true){ tabModeRuangOK.removeRow(tbLokasiRuangOK.getSelectedRow()); emptTeks(); LCount.setText(""+tabModeRuangOK.getRowCount()); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping lokasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } } } }else if(TabRawat.getSelectedIndex()==3){ if(KodeDepartemenRuangLabPK.getText().trim().equals("")||NamaDepartemenRuangLabPK.getText().trim().equals("")){ Valid.textKosong(KodeDepartemenRuangLabPK,"Departemen/Organisasi"); }else if(LongitudeRuangLabPK.getText().trim().equals("")){ Valid.textKosong(LongitudeRuangLabPK,"Longitude"); }else if(LatitudeRuangLabPK.getText().trim().equals("")){ Valid.textKosong(LatitudeRuangLabPK,"Latitude"); }else if(AltitudeRuangLabPK.getText().trim().equals("")){ Valid.textKosong(AltitudeRuangLabPK,"Altitude"); }else{ if(tbLokasiRuangLabPK.getSelectedRow()>-1){ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"id\": \""+tbLokasiRuangLabPK.getValueAt(tbLokasiRuangLabPK.getSelectedRow(),0).toString()+"\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \"R.LABPK.FAS\"" + "}" + "]," + "\"status\": \"inactive\"," + "\"name\": \"Ruang Laboratorium Patologi Klinik\"," + "\"description\": \"Ruang Laboratorium Patologi Klinik\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+LongitudeRuangLabPK.getText()+"," + "\"latitude\": "+LatitudeRuangLabPK.getText()+"," + "\"altitude\": "+AltitudeRuangLabPK.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasiRuangLabPK.getText()+"\"" + "}" + "}"; System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location/"+tbLokasiRuangLabPK.getValueAt(tbLokasiRuangLabPK.getSelectedRow(),0).toString(), HttpMethod.PUT, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Sequel.meghapustf("satu_sehat_mapping_lokasi_ruanglab","id_lokasi_satusehat",tbLokasiRuangLabPK.getValueAt(tbLokasiRuangLabPK.getSelectedRow(),0).toString())==true){ tabModeRuangLabPK.removeRow(tbLokasiRuangLabPK.getSelectedRow()); emptTeks(); LCount.setText(""+tabModeRuangLabPK.getRowCount()); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping lokasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } } } }else if(TabRawat.getSelectedIndex()==4){ if(KodeDepartemenRuangLabPA.getText().trim().equals("")||NamaDepartemenRuangLabPA.getText().trim().equals("")){ Valid.textKosong(KodeDepartemenRuangLabPA,"Departemen/Organisasi"); }else if(LongitudeRuangLabPA.getText().trim().equals("")){ Valid.textKosong(LongitudeRuangLabPA,"Longitude"); }else if(LatitudeRuangLabPA.getText().trim().equals("")){ Valid.textKosong(LatitudeRuangLabPA,"Latitude"); }else if(AltitudeRuangLabPA.getText().trim().equals("")){ Valid.textKosong(AltitudeRuangLabPA,"Altitude"); }else{ if(tbLokasiRuangLabPA.getSelectedRow()>-1){ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"id\": \""+tbLokasiRuangLabPA.getValueAt(tbLokasiRuangLabPA.getSelectedRow(),0).toString()+"\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \"R.LABPA.FAS\"" + "}" + "]," + "\"status\": \"inactive\"," + "\"name\": \"Ruang Laboratorium Patologi Anatomi\"," + "\"description\": \"Ruang Laboratorium Patologi Anatomi\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+LongitudeRuangLabPA.getText()+"," + "\"latitude\": "+LatitudeRuangLabPA.getText()+"," + "\"altitude\": "+AltitudeRuangLabPA.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasiRuangLabPA.getText()+"\"" + "}" + "}"; System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location/"+tbLokasiRuangLabPA.getValueAt(tbLokasiRuangLabPA.getSelectedRow(),0).toString(), HttpMethod.PUT, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Sequel.meghapustf("satu_sehat_mapping_lokasi_ruanglabpa","id_lokasi_satusehat",tbLokasiRuangLabPA.getValueAt(tbLokasiRuangLabPA.getSelectedRow(),0).toString())==true){ tabModeRuangLabPA.removeRow(tbLokasiRuangLabPA.getSelectedRow()); emptTeks(); LCount.setText(""+tabModeRuangLabPA.getRowCount()); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping lokasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } } } }else if(TabRawat.getSelectedIndex()==5){ if(KodeDepartemenRuangLabMB.getText().trim().equals("")||NamaDepartemenRuangLabMB.getText().trim().equals("")){ Valid.textKosong(KodeDepartemenRuangLabMB,"Departemen/Organisasi"); }else if(LongitudeRuangLabMB.getText().trim().equals("")){ Valid.textKosong(LongitudeRuangLabMB,"Longitude"); }else if(LatitudeRuangLabMB.getText().trim().equals("")){ Valid.textKosong(LatitudeRuangLabMB,"Latitude"); }else if(AltitudeRuangLabMB.getText().trim().equals("")){ Valid.textKosong(AltitudeRuangLabMB,"Altitude"); }else{ if(tbLokasiRuangLabMB.getSelectedRow()>-1){ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"id\": \""+tbLokasiRuangLabMB.getValueAt(tbLokasiRuangLabMB.getSelectedRow(),0).toString()+"\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \"R.LABMB.FAS\"" + "}" + "]," + "\"status\": \"inactive\"," + "\"name\": \"Ruang Laboratorium Mikrobiologi & Bio Molekuler\"," + "\"description\": \"Ruang Laboratorium Mikrobiologi & Bio Molekuler\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+LongitudeRuangLabMB.getText()+"," + "\"latitude\": "+LatitudeRuangLabMB.getText()+"," + "\"altitude\": "+AltitudeRuangLabMB.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasiRuangLabMB.getText()+"\"" + "}" + "}"; System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location/"+tbLokasiRuangLabMB.getValueAt(tbLokasiRuangLabMB.getSelectedRow(),0).toString(), HttpMethod.PUT, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Sequel.meghapustf("satu_sehat_mapping_lokasi_ruanglabmb","id_lokasi_satusehat",tbLokasiRuangLabMB.getValueAt(tbLokasiRuangLabMB.getSelectedRow(),0).toString())==true){ tabModeRuangLabMB.removeRow(tbLokasiRuangLabMB.getSelectedRow()); emptTeks(); LCount.setText(""+tabModeRuangLabMB.getRowCount()); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping lokasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } } } }else if(TabRawat.getSelectedIndex()==6){ if(KodeDepartemenRuangRadiologi.getText().trim().equals("")||NamaDepartemenRuangRadiologi.getText().trim().equals("")){ Valid.textKosong(KodeDepartemenRuangRadiologi,"Departemen/Organisasi"); }else if(LongitudeRuangRadiologi.getText().trim().equals("")){ Valid.textKosong(LongitudeRuangRadiologi,"Longitude"); }else if(LatitudeRuangRadiologi.getText().trim().equals("")){ Valid.textKosong(LatitudeRuangRadiologi,"Latitude"); }else if(AltitudeRuangRadiologi.getText().trim().equals("")){ Valid.textKosong(AltitudeRuangRadiologi,"Altitude"); }else{ if(tbLokasiRuangRadiologi.getSelectedRow()>-1){ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"id\": \""+tbLokasiRuangRadiologi.getValueAt(tbLokasiRuangRadiologi.getSelectedRow(),0).toString()+"\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \"R.RAD.FAS\"" + "}" + "]," + "\"status\": \"inactive\"," + "\"name\": \"Ruang Radiologi\"," + "\"description\": \"Ruang Radiologi\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+LongitudeRuangRadiologi.getText()+"," + "\"latitude\": "+LatitudeRuangRadiologi.getText()+"," + "\"altitude\": "+AltitudeRuangRadiologi.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasiRuangRadiologi.getText()+"\"" + "}" + "}"; System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location/"+tbLokasiRuangRadiologi.getValueAt(tbLokasiRuangRadiologi.getSelectedRow(),0).toString(), HttpMethod.PUT, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Sequel.meghapustf("satu_sehat_mapping_lokasi_ruangrad","id_lokasi_satusehat",tbLokasiRuangRadiologi.getValueAt(tbLokasiRuangRadiologi.getSelectedRow(),0).toString())==true){ tabModeRuangRadiologi.removeRow(tbLokasiRuangRadiologi.getSelectedRow()); emptTeks(); LCount.setText(""+tabModeRuangRadiologi.getRowCount()); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping lokasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } } } }else if(TabRawat.getSelectedIndex()==7){ if(tbLokasiFarmasi.getSelectedRow()>-1){ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"id\": \""+tbLokasiFarmasi.getValueAt(tbLokasiFarmasi.getSelectedRow(),2).toString()+"\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \""+KodeFarmasi.getText()+"\"" + "}" + "]," + "\"status\": \"inactive\"," + "\"name\": \""+NamaFarmasi.getText()+"\"," + "\"description\": \""+NamaFarmasi.getText()+"\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+LongitudeFarmasi.getText()+"," + "\"latitude\": "+LatitudeFarmasi.getText()+"," + "\"altitude\": "+AltitudeFarmasi.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasiFarmasi.getText()+"\"" + "}" + "}"; System.out.println("URL : "+link+"/Location"); System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location/"+tbLokasiFarmasi.getValueAt(tbLokasiFarmasi.getSelectedRow(),2).toString(), HttpMethod.PUT, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Valid.hapusTabletf(tabModeRuangFarmasi,KodeFarmasi,"satu_sehat_mapping_lokasi_depo_farmasi","kd_bangsal")==true){ tabModeRuangFarmasi.removeRow(tbLokasiFarmasi.getSelectedRow()); emptTeks(); LCount.setText(""+tabModeRuangFarmasi.getRowCount()); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping lokasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } }else{ JOptionPane.showMessageDialog(null,"Silahkan pilih data terlebih dahulu..!!"); } } }//GEN-LAST:event_BtnHapusActionPerformed private void BtnHapusKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_BtnHapusKeyPressed if(evt.getKeyCode()==KeyEvent.VK_SPACE){ BtnHapusActionPerformed(null); }else{ Valid.pindah(evt, BtnBatal, BtnEdit); } }//GEN-LAST:event_BtnHapusKeyPressed private void BtnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnEditActionPerformed if(TabRawat.getSelectedIndex()==0){ if(KodeDepartemen.getText().trim().equals("")||NamaDepartemen.getText().trim().equals("")){ Valid.textKosong(KodeDepartemen,"Departemen/Organisasi"); }else if(KodePoli.getText().trim().equals("")||NamaPoli.getText().trim().equals("")){ Valid.textKosong(KodeDepartemen,"Poli/Unit"); }else if(Longitude.getText().trim().equals("")){ Valid.textKosong(Longitude,"Longitude"); }else if(Latitude.getText().trim().equals("")){ Valid.textKosong(Latitude,"Latitude"); }else if(Altitude.getText().trim().equals("")){ Valid.textKosong(Altitude,"Altitude"); }else{ if(tbJnsPerawatan.getSelectedRow()>-1){ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"id\": \""+tbJnsPerawatan.getValueAt(tbJnsPerawatan.getSelectedRow(),2).toString()+"\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \""+KodePoli.getText()+"\"" + "}" + "]," + "\"status\": \"active\"," + "\"name\": \""+NamaPoli.getText()+"\"," + "\"description\": \""+NamaPoli.getText()+"\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+Longitude.getText()+"," + "\"latitude\": "+Latitude.getText()+"," + "\"altitude\": "+Altitude.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasi.getText()+"\"" + "}" + "}"; System.out.println("URL : "+link+"/Location"); System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location/"+tbJnsPerawatan.getValueAt(tbJnsPerawatan.getSelectedRow(),2).toString(), HttpMethod.PUT, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Sequel.mengedittf("satu_sehat_mapping_lokasi_ralan","kd_poli=?","kd_poli=?,id_organisasi_satusehat=?,id_lokasi_satusehat=?,longitude=?,latitude=?,altittude=?",7,new String[]{ KodePoli.getText(),IDOrganisasi.getText(),response.asText(),Longitude.getText(),Latitude.getText(),Altitude.getText(),tbJnsPerawatan.getValueAt(tbJnsPerawatan.getSelectedRow(),0).toString() })==true){ tabMode.setValueAt(KodePoli.getText(),tbJnsPerawatan.getSelectedRow(),0); tabMode.setValueAt(NamaPoli.getText(),tbJnsPerawatan.getSelectedRow(),1); tabMode.setValueAt(response.asText(),tbJnsPerawatan.getSelectedRow(),2); tabMode.setValueAt(Longitude.getText(),tbJnsPerawatan.getSelectedRow(),3); tabMode.setValueAt(Latitude.getText(),tbJnsPerawatan.getSelectedRow(),4); tabMode.setValueAt(Altitude.getText(),tbJnsPerawatan.getSelectedRow(),5); tabMode.setValueAt(KodeDepartemen.getText(),tbJnsPerawatan.getSelectedRow(),6); tabMode.setValueAt(NamaDepartemen.getText(),tbJnsPerawatan.getSelectedRow(),7); tabMode.setValueAt(IDOrganisasi.getText(),tbJnsPerawatan.getSelectedRow(),8); emptTeks(); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping lokasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } } } }else if(TabRawat.getSelectedIndex()==1){ if(KodeDepartemenKamar.getText().trim().equals("")||NamaDepartemenKamar.getText().trim().equals("")){ Valid.textKosong(KodeDepartemenKamar,"Departemen/Organisasi"); }else if(KodeKamar.getText().trim().equals("")||NamaKamar.getText().trim().equals("")){ Valid.textKosong(KodeKamar,"Kamar/Ruang"); }else if(LongitudeKamar.getText().trim().equals("")){ Valid.textKosong(LongitudeKamar,"Longitude"); }else if(LatitudeKamar.getText().trim().equals("")){ Valid.textKosong(LatitudeKamar,"Latitude"); }else if(AltitudeKamar.getText().trim().equals("")){ Valid.textKosong(AltitudeKamar,"Altitude"); }else{ if(tbLokasiKamar.getSelectedRow()>-1){ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"id\": \""+tbLokasiKamar.getValueAt(tbLokasiKamar.getSelectedRow(),2).toString()+"\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \""+KodeKamar.getText()+"\"" + "}" + "]," + "\"status\": \"active\"," + "\"name\": \""+NamaKamar.getText()+"\"," + "\"description\": \""+NamaKamar.getText()+" Nomor "+KodeKamar.getText()+"\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+LongitudeKamar.getText()+"," + "\"latitude\": "+LatitudeKamar.getText()+"," + "\"altitude\": "+AltitudeKamar.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasiKamar.getText()+"\"" + "}" + "}"; System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location/"+tbLokasiKamar.getValueAt(tbLokasiKamar.getSelectedRow(),2).toString(), HttpMethod.PUT, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Sequel.mengedittf("satu_sehat_mapping_lokasi_ranap","kd_kamar=?","kd_kamar=?,id_organisasi_satusehat=?,id_lokasi_satusehat=?,longitude=?,latitude=?,altittude=?",7,new String[]{ KodeKamar.getText(),IDOrganisasiKamar.getText(),response.asText(),LongitudeKamar.getText(),LatitudeKamar.getText(),AltitudeKamar.getText(),tbLokasiKamar.getValueAt(tbLokasiKamar.getSelectedRow(),0).toString() })==true){ tabModeKamar.setValueAt(KodeKamar.getText(),tbLokasiKamar.getSelectedRow(),0); tabModeKamar.setValueAt(NamaKamar.getText(),tbLokasiKamar.getSelectedRow(),1); tabModeKamar.setValueAt(response.asText(),tbLokasiKamar.getSelectedRow(),2); tabModeKamar.setValueAt(LongitudeKamar.getText(),tbLokasiKamar.getSelectedRow(),3); tabModeKamar.setValueAt(LatitudeKamar.getText(),tbLokasiKamar.getSelectedRow(),4); tabModeKamar.setValueAt(AltitudeKamar.getText(),tbLokasiKamar.getSelectedRow(),5); tabModeKamar.setValueAt(KodeDepartemenKamar.getText(),tbLokasiKamar.getSelectedRow(),6); tabModeKamar.setValueAt(NamaDepartemenKamar.getText(),tbLokasiKamar.getSelectedRow(),7); tabModeKamar.setValueAt(IDOrganisasiKamar.getText(),tbLokasiKamar.getSelectedRow(),8); emptTeks(); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping lokasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } } } }else if(TabRawat.getSelectedIndex()==2){ if(KodeDepartemenRuangOK.getText().trim().equals("")||NamaDepartemenRuangOK.getText().trim().equals("")){ Valid.textKosong(KodeDepartemenRuangOK,"Departemen/Organisasi"); }else if(LongitudeRuangOK.getText().trim().equals("")){ Valid.textKosong(LongitudeRuangOK,"Longitude"); }else if(LatitudeRuangOK.getText().trim().equals("")){ Valid.textKosong(LatitudeRuangOK,"Latitude"); }else if(AltitudeRuangOK.getText().trim().equals("")){ Valid.textKosong(AltitudeRuangOK,"Altitude"); }else{ if(tbLokasiRuangOK.getSelectedRow()>-1){ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"id\": \""+tbLokasiRuangOK.getValueAt(tbLokasiRuangOK.getSelectedRow(),0).toString()+"\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \"R.OK.FAS\"" + "}" + "]," + "\"status\": \"active\"," + "\"name\": \"Ruang Operasi\"," + "\"description\": \"Ruang Operasi\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+LongitudeRuangOK.getText()+"," + "\"latitude\": "+LatitudeRuangOK.getText()+"," + "\"altitude\": "+AltitudeRuangOK.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasiRuangOK.getText()+"\"" + "}" + "}"; System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location/"+tbLokasiRuangOK.getValueAt(tbLokasiRuangOK.getSelectedRow(),0).toString(), HttpMethod.PUT, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Sequel.mengedittf("satu_sehat_mapping_lokasi_ruangok","id_lokasi_satusehat=?","id_organisasi_satusehat=?,id_lokasi_satusehat=?,longitude=?,latitude=?,altittude=?",6,new String[]{ IDOrganisasiRuangOK.getText(),response.asText(),LongitudeRuangOK.getText(),LatitudeRuangOK.getText(),AltitudeRuangOK.getText(),tbLokasiRuangOK.getValueAt(tbLokasiRuangOK.getSelectedRow(),0).toString() })==true){ tabModeRuangOK.setValueAt(response.asText(),tbLokasiRuangOK.getSelectedRow(),0); tabModeRuangOK.setValueAt(LongitudeRuangOK.getText(),tbLokasiRuangOK.getSelectedRow(),1); tabModeRuangOK.setValueAt(LatitudeRuangOK.getText(),tbLokasiRuangOK.getSelectedRow(),2); tabModeRuangOK.setValueAt(AltitudeRuangOK.getText(),tbLokasiRuangOK.getSelectedRow(),3); tabModeRuangOK.setValueAt(KodeDepartemenRuangOK.getText(),tbLokasiRuangOK.getSelectedRow(),4); tabModeRuangOK.setValueAt(NamaDepartemenRuangOK.getText(),tbLokasiRuangOK.getSelectedRow(),5); tabModeRuangOK.setValueAt(IDOrganisasiRuangOK.getText(),tbLokasiRuangOK.getSelectedRow(),6); emptTeks(); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping lokasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } } } }else if(TabRawat.getSelectedIndex()==3){ if(KodeDepartemenRuangLabPK.getText().trim().equals("")||NamaDepartemenRuangLabPK.getText().trim().equals("")){ Valid.textKosong(KodeDepartemenRuangLabPK,"Departemen/Organisasi"); }else if(LongitudeRuangLabPK.getText().trim().equals("")){ Valid.textKosong(LongitudeRuangLabPK,"Longitude"); }else if(LatitudeRuangLabPK.getText().trim().equals("")){ Valid.textKosong(LatitudeRuangLabPK,"Latitude"); }else if(AltitudeRuangLabPK.getText().trim().equals("")){ Valid.textKosong(AltitudeRuangLabPK,"Altitude"); }else{ if(tbLokasiRuangLabPK.getSelectedRow()>-1){ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"id\": \""+tbLokasiRuangLabPK.getValueAt(tbLokasiRuangLabPK.getSelectedRow(),0).toString()+"\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \"R.LABPK.FAS\"" + "}" + "]," + "\"status\": \"active\"," + "\"name\": \"Ruang Laboratorium Patologi Klinik\"," + "\"description\": \"Ruang Laboratorium Patologi Klinik\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+LongitudeRuangLabPK.getText()+"," + "\"latitude\": "+LatitudeRuangLabPK.getText()+"," + "\"altitude\": "+AltitudeRuangLabPK.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasiRuangLabPK.getText()+"\"" + "}" + "}"; System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location/"+tbLokasiRuangLabPK.getValueAt(tbLokasiRuangLabPK.getSelectedRow(),0).toString(), HttpMethod.PUT, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Sequel.mengedittf("satu_sehat_mapping_lokasi_ruanglab","id_lokasi_satusehat=?","id_organisasi_satusehat=?,id_lokasi_satusehat=?,longitude=?,latitude=?,altittude=?",6,new String[]{ IDOrganisasiRuangLabPK.getText(),response.asText(),LongitudeRuangLabPK.getText(),LatitudeRuangLabPK.getText(),AltitudeRuangLabPK.getText(),tbLokasiRuangLabPK.getValueAt(tbLokasiRuangLabPK.getSelectedRow(),0).toString() })==true){ tabModeRuangLabPK.setValueAt(response.asText(),tbLokasiRuangLabPK.getSelectedRow(),0); tabModeRuangLabPK.setValueAt(LongitudeRuangLabPK.getText(),tbLokasiRuangLabPK.getSelectedRow(),1); tabModeRuangLabPK.setValueAt(LatitudeRuangLabPK.getText(),tbLokasiRuangLabPK.getSelectedRow(),2); tabModeRuangLabPK.setValueAt(AltitudeRuangLabPK.getText(),tbLokasiRuangLabPK.getSelectedRow(),3); tabModeRuangLabPK.setValueAt(KodeDepartemenRuangLabPK.getText(),tbLokasiRuangLabPK.getSelectedRow(),4); tabModeRuangLabPK.setValueAt(NamaDepartemenRuangLabPK.getText(),tbLokasiRuangLabPK.getSelectedRow(),5); tabModeRuangLabPK.setValueAt(IDOrganisasiRuangLabPK.getText(),tbLokasiRuangLabPK.getSelectedRow(),6); emptTeks(); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping lokasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } } } }else if(TabRawat.getSelectedIndex()==4){ if(KodeDepartemenRuangLabPA.getText().trim().equals("")||NamaDepartemenRuangLabPA.getText().trim().equals("")){ Valid.textKosong(KodeDepartemenRuangLabPA,"Departemen/Organisasi"); }else if(LongitudeRuangLabPA.getText().trim().equals("")){ Valid.textKosong(LongitudeRuangLabPA,"Longitude"); }else if(LatitudeRuangLabPA.getText().trim().equals("")){ Valid.textKosong(LatitudeRuangLabPA,"Latitude"); }else if(AltitudeRuangLabPA.getText().trim().equals("")){ Valid.textKosong(AltitudeRuangLabPA,"Altitude"); }else{ if(tbLokasiRuangLabPA.getSelectedRow()>-1){ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"id\": \""+tbLokasiRuangLabPA.getValueAt(tbLokasiRuangLabPA.getSelectedRow(),0).toString()+"\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \"R.LABPA.FAS\"" + "}" + "]," + "\"status\": \"active\"," + "\"name\": \"Ruang Laboratorium Patologi Anatomi\"," + "\"description\": \"Ruang Laboratorium Patologi Anatomi\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+LongitudeRuangLabPA.getText()+"," + "\"latitude\": "+LatitudeRuangLabPA.getText()+"," + "\"altitude\": "+AltitudeRuangLabPA.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasiRuangLabPA.getText()+"\"" + "}" + "}"; System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location/"+tbLokasiRuangLabPA.getValueAt(tbLokasiRuangLabPA.getSelectedRow(),0).toString(), HttpMethod.PUT, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Sequel.mengedittf("satu_sehat_mapping_lokasi_ruanglabpa","id_lokasi_satusehat=?","id_organisasi_satusehat=?,id_lokasi_satusehat=?,longitude=?,latitude=?,altittude=?",6,new String[]{ IDOrganisasiRuangLabPA.getText(),response.asText(),LongitudeRuangLabPA.getText(),LatitudeRuangLabPA.getText(),AltitudeRuangLabPA.getText(),tbLokasiRuangLabPA.getValueAt(tbLokasiRuangLabPA.getSelectedRow(),0).toString() })==true){ tabModeRuangLabPA.setValueAt(response.asText(),tbLokasiRuangLabPA.getSelectedRow(),0); tabModeRuangLabPA.setValueAt(LongitudeRuangLabPA.getText(),tbLokasiRuangLabPA.getSelectedRow(),1); tabModeRuangLabPA.setValueAt(LatitudeRuangLabPA.getText(),tbLokasiRuangLabPA.getSelectedRow(),2); tabModeRuangLabPA.setValueAt(AltitudeRuangLabPA.getText(),tbLokasiRuangLabPA.getSelectedRow(),3); tabModeRuangLabPA.setValueAt(KodeDepartemenRuangLabPA.getText(),tbLokasiRuangLabPA.getSelectedRow(),4); tabModeRuangLabPA.setValueAt(NamaDepartemenRuangLabPA.getText(),tbLokasiRuangLabPA.getSelectedRow(),5); tabModeRuangLabPA.setValueAt(IDOrganisasiRuangLabPA.getText(),tbLokasiRuangLabPA.getSelectedRow(),6); emptTeks(); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping lokasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } } } }else if(TabRawat.getSelectedIndex()==5){ if(KodeDepartemenRuangLabMB.getText().trim().equals("")||NamaDepartemenRuangLabMB.getText().trim().equals("")){ Valid.textKosong(KodeDepartemenRuangLabMB,"Departemen/Organisasi"); }else if(LongitudeRuangLabMB.getText().trim().equals("")){ Valid.textKosong(LongitudeRuangLabMB,"Longitude"); }else if(LatitudeRuangLabMB.getText().trim().equals("")){ Valid.textKosong(LatitudeRuangLabMB,"Latitude"); }else if(AltitudeRuangLabMB.getText().trim().equals("")){ Valid.textKosong(AltitudeRuangLabMB,"Altitude"); }else{ if(tbLokasiRuangLabMB.getSelectedRow()>-1){ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"id\": \""+tbLokasiRuangLabMB.getValueAt(tbLokasiRuangLabMB.getSelectedRow(),0).toString()+"\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \"R.LABMB.FAS\"" + "}" + "]," + "\"status\": \"active\"," + "\"name\": \"Ruang Laboratorium Mikrobiologi & Bio Molekuler\"," + "\"description\": \"Ruang Laboratorium Mikrobiologi & Bio Molekuler\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+LongitudeRuangLabMB.getText()+"," + "\"latitude\": "+LatitudeRuangLabMB.getText()+"," + "\"altitude\": "+AltitudeRuangLabMB.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasiRuangLabMB.getText()+"\"" + "}" + "}"; System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location/"+tbLokasiRuangLabMB.getValueAt(tbLokasiRuangLabMB.getSelectedRow(),0).toString(), HttpMethod.PUT, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Sequel.mengedittf("satu_sehat_mapping_lokasi_ruanglabmb","id_lokasi_satusehat=?","id_organisasi_satusehat=?,id_lokasi_satusehat=?,longitude=?,latitude=?,altittude=?",6,new String[]{ IDOrganisasiRuangLabMB.getText(),response.asText(),LongitudeRuangLabMB.getText(),LatitudeRuangLabMB.getText(),AltitudeRuangLabMB.getText(),tbLokasiRuangLabMB.getValueAt(tbLokasiRuangLabMB.getSelectedRow(),0).toString() })==true){ tabModeRuangLabMB.setValueAt(response.asText(),tbLokasiRuangLabMB.getSelectedRow(),0); tabModeRuangLabMB.setValueAt(LongitudeRuangLabMB.getText(),tbLokasiRuangLabMB.getSelectedRow(),1); tabModeRuangLabMB.setValueAt(LatitudeRuangLabMB.getText(),tbLokasiRuangLabMB.getSelectedRow(),2); tabModeRuangLabMB.setValueAt(AltitudeRuangLabMB.getText(),tbLokasiRuangLabMB.getSelectedRow(),3); tabModeRuangLabMB.setValueAt(KodeDepartemenRuangLabMB.getText(),tbLokasiRuangLabMB.getSelectedRow(),4); tabModeRuangLabMB.setValueAt(NamaDepartemenRuangLabMB.getText(),tbLokasiRuangLabMB.getSelectedRow(),5); tabModeRuangLabMB.setValueAt(IDOrganisasiRuangLabMB.getText(),tbLokasiRuangLabMB.getSelectedRow(),6); emptTeks(); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping lokasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } } } }else if(TabRawat.getSelectedIndex()==6){ if(KodeDepartemenRuangRadiologi.getText().trim().equals("")||NamaDepartemenRuangRadiologi.getText().trim().equals("")){ Valid.textKosong(KodeDepartemenRuangRadiologi,"Departemen/Organisasi"); }else if(LongitudeRuangRadiologi.getText().trim().equals("")){ Valid.textKosong(LongitudeRuangRadiologi,"Longitude"); }else if(LatitudeRuangRadiologi.getText().trim().equals("")){ Valid.textKosong(LatitudeRuangRadiologi,"Latitude"); }else if(AltitudeRuangRadiologi.getText().trim().equals("")){ Valid.textKosong(AltitudeRuangRadiologi,"Altitude"); }else{ if(tbLokasiRuangRadiologi.getSelectedRow()>-1){ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"id\": \""+tbLokasiRuangRadiologi.getValueAt(tbLokasiRuangRadiologi.getSelectedRow(),0).toString()+"\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \"R.RAD.FAS\"" + "}" + "]," + "\"status\": \"active\"," + "\"name\": \"Ruang Radiologi\"," + "\"description\": \"Ruang Radiologi\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+LongitudeRuangRadiologi.getText()+"," + "\"latitude\": "+LatitudeRuangRadiologi.getText()+"," + "\"altitude\": "+AltitudeRuangRadiologi.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasiRuangRadiologi.getText()+"\"" + "}" + "}"; System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location/"+tbLokasiRuangRadiologi.getValueAt(tbLokasiRuangRadiologi.getSelectedRow(),0).toString(), HttpMethod.PUT, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Sequel.mengedittf("satu_sehat_mapping_lokasi_ruangrad","id_lokasi_satusehat=?","id_organisasi_satusehat=?,id_lokasi_satusehat=?,longitude=?,latitude=?,altittude=?",6,new String[]{ IDOrganisasiRuangRadiologi.getText(),response.asText(),LongitudeRuangRadiologi.getText(),LatitudeRuangRadiologi.getText(),AltitudeRuangRadiologi.getText(),tbLokasiRuangRadiologi.getValueAt(tbLokasiRuangRadiologi.getSelectedRow(),0).toString() })==true){ tabModeRuangRadiologi.setValueAt(response.asText(),tbLokasiRuangRadiologi.getSelectedRow(),0); tabModeRuangRadiologi.setValueAt(LongitudeRuangRadiologi.getText(),tbLokasiRuangRadiologi.getSelectedRow(),1); tabModeRuangRadiologi.setValueAt(LatitudeRuangRadiologi.getText(),tbLokasiRuangRadiologi.getSelectedRow(),2); tabModeRuangRadiologi.setValueAt(AltitudeRuangRadiologi.getText(),tbLokasiRuangRadiologi.getSelectedRow(),3); tabModeRuangRadiologi.setValueAt(KodeDepartemenRuangRadiologi.getText(),tbLokasiRuangRadiologi.getSelectedRow(),4); tabModeRuangRadiologi.setValueAt(NamaDepartemenRuangRadiologi.getText(),tbLokasiRuangRadiologi.getSelectedRow(),5); tabModeRuangRadiologi.setValueAt(IDOrganisasiRuangRadiologi.getText(),tbLokasiRuangRadiologi.getSelectedRow(),6); emptTeks(); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping lokasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } } } }else if(TabRawat.getSelectedIndex()==7){ if(KodeDepartemenFarmasi.getText().trim().equals("")||NamaDepartemenFarmasi.getText().trim().equals("")){ Valid.textKosong(KodeDepartemenFarmasi,"Departemen/Organisasi"); }else if(KodeFarmasi.getText().trim().equals("")||NamaFarmasi.getText().trim().equals("")){ Valid.textKosong(KodeFarmasi,"Farmasi/Depo"); }else if(LongitudeFarmasi.getText().trim().equals("")){ Valid.textKosong(LongitudeFarmasi,"Longitude"); }else if(LatitudeFarmasi.getText().trim().equals("")){ Valid.textKosong(LatitudeFarmasi,"Latitude"); }else if(AltitudeFarmasi.getText().trim().equals("")){ Valid.textKosong(AltitudeFarmasi,"Altitude"); }else{ if(tbLokasiFarmasi.getSelectedRow()>-1){ try{ headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Bearer "+api.TokenSatuSehat()); json = "{" + "\"resourceType\": \"Location\"," + "\"id\": \""+tbLokasiFarmasi.getValueAt(tbLokasiFarmasi.getSelectedRow(),2).toString()+"\"," + "\"identifier\": [" + "{" + "\"system\": \"http://sys-ids.kemkes.go.id/location/"+koneksiDB.IDSATUSEHAT()+"\"," + "\"value\": \""+KodeFarmasi.getText()+"\"" + "}" + "]," + "\"status\": \"active\"," + "\"name\": \""+NamaFarmasi.getText()+"\"," + "\"description\": \""+NamaFarmasi.getText()+"\"," + "\"mode\": \"instance\"," + "\"telecom\": [" + "{" + "\"system\": \"phone\"," + "\"value\": \""+akses.getkontakrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"email\"," + "\"value\": \""+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}," + "{" + "\"system\": \"url\"," + "\"value\": \"www."+akses.getemailrs()+"\"," + "\"use\": \"work\"" + "}" + "]," + "\"address\": {" + "\"use\": \"work\"," + "\"line\": [" + "\""+akses.getalamatrs()+"\"" + "]," + "\"city\": \""+akses.getkabupatenrs()+"\"," + "\"postalCode\": \""+koneksiDB.KODEPOSSATUSEHAT()+"\"," + "\"country\": \"ID\"," + "\"extension\": [" + "{" + "\"url\": \"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode\"," + "\"extension\": [" + "{" + "\"url\": \"province\"," + "\"valueCode\": \""+koneksiDB.PROPINSISATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"city\"," + "\"valueCode\": \""+koneksiDB.KABUPATENSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"district\"," + "\"valueCode\": \""+koneksiDB.KECAMATANSATUSEHAT()+"\"" + "}," + "{" + "\"url\": \"village\"," + "\"valueCode\": \""+koneksiDB.KELURAHANSATUSEHAT()+"\"" + "}" + "]" + "}" + "]" + "}," + "\"physicalType\": {" + "\"coding\": [" + "{" + "\"system\": \"http://terminology.hl7.org/CodeSystem/location-physical-type\"," + "\"code\": \"ro\"," + "\"display\": \"Room\"" + "}" + "]" + "}," + "\"position\": {" + "\"longitude\": "+LongitudeFarmasi.getText()+"," + "\"latitude\": "+LatitudeFarmasi.getText()+"," + "\"altitude\": "+AltitudeFarmasi.getText()+ "}," + "\"managingOrganization\": {" + "\"reference\": \"Organization/"+IDOrganisasiFarmasi.getText()+"\"" + "}" + "}"; System.out.println("URL : "+link+"/Location"); System.out.println("Request JSON : "+json); requestEntity = new HttpEntity(json,headers); json=api.getRest().exchange(link+"/Location/"+tbLokasiFarmasi.getValueAt(tbLokasiFarmasi.getSelectedRow(),2).toString(), HttpMethod.PUT, requestEntity, String.class).getBody(); System.out.println("Result JSON : "+json); root = mapper.readTree(json); response = root.path("id"); if(!response.asText().equals("")){ if(Sequel.mengedittf("satu_sehat_mapping_lokasi_depo_farmasi","kd_bangsal=?","kd_bangsal=?,id_organisasi_satusehat=?,id_lokasi_satusehat=?,longitude=?,latitude=?,altittude=?",7,new String[]{ KodeFarmasi.getText(),IDOrganisasiFarmasi.getText(),response.asText(),LongitudeFarmasi.getText(),LatitudeFarmasi.getText(),AltitudeFarmasi.getText(),tbLokasiFarmasi.getValueAt(tbLokasiFarmasi.getSelectedRow(),0).toString() })==true){ tabModeRuangFarmasi.setValueAt(KodeFarmasi.getText(),tbLokasiFarmasi.getSelectedRow(),0); tabModeRuangFarmasi.setValueAt(NamaFarmasi.getText(),tbLokasiFarmasi.getSelectedRow(),1); tabModeRuangFarmasi.setValueAt(response.asText(),tbLokasiFarmasi.getSelectedRow(),2); tabModeRuangFarmasi.setValueAt(LongitudeFarmasi.getText(),tbLokasiFarmasi.getSelectedRow(),3); tabModeRuangFarmasi.setValueAt(LatitudeFarmasi.getText(),tbLokasiFarmasi.getSelectedRow(),4); tabModeRuangFarmasi.setValueAt(AltitudeFarmasi.getText(),tbLokasiFarmasi.getSelectedRow(),5); tabModeRuangFarmasi.setValueAt(KodeDepartemenFarmasi.getText(),tbLokasiFarmasi.getSelectedRow(),6); tabModeRuangFarmasi.setValueAt(NamaDepartemenFarmasi.getText(),tbLokasiFarmasi.getSelectedRow(),7); tabModeRuangFarmasi.setValueAt(IDOrganisasiFarmasi.getText(),tbLokasiFarmasi.getSelectedRow(),8); emptTeks(); } }else{ JOptionPane.showMessageDialog(null,"Gagal melakukan mapping lokasi ke server Satu Sehat Kemenkes"); } }catch(Exception e){ System.out.println("Notifikasi Bridging : "+e); JOptionPane.showMessageDialog(null,"Error Respon Satu Sehat Kemenkes : "+e); } } } } }//GEN-LAST:event_BtnEditActionPerformed private void BtnEditKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_BtnEditKeyPressed if(evt.getKeyCode()==KeyEvent.VK_SPACE){ BtnEditActionPerformed(null); }else{ Valid.pindah(evt, BtnHapus, BtnPrint); } }//GEN-LAST:event_BtnEditKeyPressed private void BtnKeluarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnKeluarActionPerformed dispose(); }//GEN-LAST:event_BtnKeluarActionPerformed private void BtnKeluarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_BtnKeluarKeyPressed if(evt.getKeyCode()==KeyEvent.VK_SPACE){ dispose(); }else{Valid.pindah(evt,BtnEdit,TCari);} }//GEN-LAST:event_BtnKeluarKeyPressed private void BtnPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnPrintActionPerformed if(TabRawat.getSelectedIndex()==0){ this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); if(tabMode.getRowCount()==0){ JOptionPane.showMessageDialog(null,"Maaf, data sudah habis. Tidak ada data yang bisa anda print...!!!!"); BtnBatal.requestFocus(); }else if(tabMode.getRowCount()!=0){ Map<String, Object> param = new HashMap<>(); param.put("namars",akses.getnamars()); param.put("alamatrs",akses.getalamatrs()); param.put("kotars",akses.getkabupatenrs()); param.put("propinsirs",akses.getpropinsirs()); param.put("kontakrs",akses.getkontakrs()); param.put("emailrs",akses.getemailrs()); param.put("logo",Sequel.cariGambar("select setting.logo from setting")); param.put("parameter","%"+TCari.getText().trim()+"%"); Valid.MyReport("rptMapingLokasiSatuSehat.jasper","report","::[ Mapping Poli/Lokasi Satu Sehat Kemenkes ]::",param); } this.setCursor(Cursor.getDefaultCursor()); }else if(TabRawat.getSelectedIndex()==1){ this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); if(tabModeKamar.getRowCount()==0){ JOptionPane.showMessageDialog(null,"Maaf, data sudah habis. Tidak ada data yang bisa anda print...!!!!"); BtnBatal.requestFocus(); }else if(tabModeKamar.getRowCount()!=0){ Map<String, Object> param = new HashMap<>(); param.put("namars",akses.getnamars()); param.put("alamatrs",akses.getalamatrs()); param.put("kotars",akses.getkabupatenrs()); param.put("propinsirs",akses.getpropinsirs()); param.put("kontakrs",akses.getkontakrs()); param.put("emailrs",akses.getemailrs()); param.put("logo",Sequel.cariGambar("select setting.logo from setting")); param.put("parameter","%"+TCari.getText().trim()+"%"); Valid.MyReport("rptMapingLokasiSatuSehat2.jasper","report","::[ Mapping Kamar Inap/Ruang Inap Satu Sehat Kemenkes ]::",param); } this.setCursor(Cursor.getDefaultCursor()); }else if(TabRawat.getSelectedIndex()==2){ this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); if(tabModeRuangOK.getRowCount()==0){ JOptionPane.showMessageDialog(null,"Maaf, data sudah habis. Tidak ada data yang bisa anda print...!!!!"); BtnBatal.requestFocus(); }else if(tabModeRuangOK.getRowCount()!=0){ Map<String, Object> param = new HashMap<>(); param.put("namars",akses.getnamars()); param.put("alamatrs",akses.getalamatrs()); param.put("kotars",akses.getkabupatenrs()); param.put("propinsirs",akses.getpropinsirs()); param.put("kontakrs",akses.getkontakrs()); param.put("emailrs",akses.getemailrs()); param.put("logo",Sequel.cariGambar("select setting.logo from setting")); Valid.MyReport("rptMapingLokasiSatuSehat3.jasper","report","::[ Mapping Lokasi Ruang Operasi Satu Sehat Kemenkes ]::",param); } this.setCursor(Cursor.getDefaultCursor()); }else if(TabRawat.getSelectedIndex()==3){ this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); if(tabModeRuangLabPK.getRowCount()==0){ JOptionPane.showMessageDialog(null,"Maaf, data sudah habis. Tidak ada data yang bisa anda print...!!!!"); BtnBatal.requestFocus(); }else if(tabModeRuangLabPK.getRowCount()!=0){ Map<String, Object> param = new HashMap<>(); param.put("namars",akses.getnamars()); param.put("alamatrs",akses.getalamatrs()); param.put("kotars",akses.getkabupatenrs()); param.put("propinsirs",akses.getpropinsirs()); param.put("kontakrs",akses.getkontakrs()); param.put("emailrs",akses.getemailrs()); param.put("logo",Sequel.cariGambar("select setting.logo from setting")); Valid.MyReport("rptMapingLokasiSatuSehat4.jasper","report","::[ Mapping Lokasi Ruang Laboratorium Patologi Klinis Satu Sehat Kemenkes ]::",param); } this.setCursor(Cursor.getDefaultCursor()); }else if(TabRawat.getSelectedIndex()==4){ this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); if(tabModeRuangLabPA.getRowCount()==0){ JOptionPane.showMessageDialog(null,"Maaf, data sudah habis. Tidak ada data yang bisa anda print...!!!!"); BtnBatal.requestFocus(); }else if(tabModeRuangLabPA.getRowCount()!=0){ Map<String, Object> param = new HashMap<>(); param.put("namars",akses.getnamars()); param.put("alamatrs",akses.getalamatrs()); param.put("kotars",akses.getkabupatenrs()); param.put("propinsirs",akses.getpropinsirs()); param.put("kontakrs",akses.getkontakrs()); param.put("emailrs",akses.getemailrs()); param.put("logo",Sequel.cariGambar("select setting.logo from setting")); Valid.MyReport("rptMapingLokasiSatuSehat5.jasper","report","::[ Mapping Lokasi Ruang Laboratorium Patologi Anatomi Satu Sehat Kemenkes ]::",param); } this.setCursor(Cursor.getDefaultCursor()); }else if(TabRawat.getSelectedIndex()==5){ this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); if(tabModeRuangLabMB.getRowCount()==0){ JOptionPane.showMessageDialog(null,"Maaf, data sudah habis. Tidak ada data yang bisa anda print...!!!!"); BtnBatal.requestFocus(); }else if(tabModeRuangLabMB.getRowCount()!=0){ Map<String, Object> param = new HashMap<>(); param.put("namars",akses.getnamars()); param.put("alamatrs",akses.getalamatrs()); param.put("kotars",akses.getkabupatenrs()); param.put("propinsirs",akses.getpropinsirs()); param.put("kontakrs",akses.getkontakrs()); param.put("emailrs",akses.getemailrs()); param.put("logo",Sequel.cariGambar("select setting.logo from setting")); Valid.MyReport("rptMapingLokasiSatuSehat6.jasper","report","::[ Mapping Lokasi Ruang Laboratorium Mikrobiologi & Bio Molekuler Satu Sehat Kemenkes ]::",param); } this.setCursor(Cursor.getDefaultCursor()); }else if(TabRawat.getSelectedIndex()==6){ this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); if(tabModeRuangRadiologi.getRowCount()==0){ JOptionPane.showMessageDialog(null,"Maaf, data sudah habis. Tidak ada data yang bisa anda print...!!!!"); BtnBatal.requestFocus(); }else if(tabModeRuangRadiologi.getRowCount()!=0){ Map<String, Object> param = new HashMap<>(); param.put("namars",akses.getnamars()); param.put("alamatrs",akses.getalamatrs()); param.put("kotars",akses.getkabupatenrs()); param.put("propinsirs",akses.getpropinsirs()); param.put("kontakrs",akses.getkontakrs()); param.put("emailrs",akses.getemailrs()); param.put("logo",Sequel.cariGambar("select setting.logo from setting")); Valid.MyReport("rptMapingLokasiSatuSehat7.jasper","report","::[ Mapping Lokasi Ruang Radiologi Satu Sehat Kemenkes ]::",param); } this.setCursor(Cursor.getDefaultCursor()); }else if(TabRawat.getSelectedIndex()==7){ this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); if(tabModeRuangFarmasi.getRowCount()==0){ JOptionPane.showMessageDialog(null,"Maaf, data sudah habis. Tidak ada data yang bisa anda print...!!!!"); BtnBatal.requestFocus(); }else if(tabModeRuangFarmasi.getRowCount()!=0){ Map<String, Object> param = new HashMap<>(); param.put("namars",akses.getnamars()); param.put("alamatrs",akses.getalamatrs()); param.put("kotars",akses.getkabupatenrs()); param.put("propinsirs",akses.getpropinsirs()); param.put("kontakrs",akses.getkontakrs()); param.put("emailrs",akses.getemailrs()); param.put("logo",Sequel.cariGambar("select setting.logo from setting")); param.put("parameter","%"+TCari.getText().trim()+"%"); Valid.MyReport("rptMapingLokasiSatuSehat8.jasper","report","::[ Mapping Lokasi Depo/Farmasi Satu Sehat Kemenkes ]::",param); } this.setCursor(Cursor.getDefaultCursor()); } }//GEN-LAST:event_BtnPrintActionPerformed private void BtnPrintKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_BtnPrintKeyPressed if(evt.getKeyCode()==KeyEvent.VK_SPACE){ BtnPrintActionPerformed(null); }else{ Valid.pindah(evt, BtnEdit, BtnKeluar); } }//GEN-LAST:event_BtnPrintKeyPressed private void TCariKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_TCariKeyPressed if(evt.getKeyCode()==KeyEvent.VK_ENTER){ BtnCariActionPerformed(null); }else if(evt.getKeyCode()==KeyEvent.VK_PAGE_DOWN){ BtnCari.requestFocus(); }else if(evt.getKeyCode()==KeyEvent.VK_PAGE_UP){ BtnKeluar.requestFocus(); } }//GEN-LAST:event_TCariKeyPressed private void BtnCariActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnCariActionPerformed TabRawatMouseClicked(null); }//GEN-LAST:event_BtnCariActionPerformed private void BtnCariKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_BtnCariKeyPressed if(evt.getKeyCode()==KeyEvent.VK_SPACE){ BtnCariActionPerformed(null); }else{ Valid.pindah(evt, TCari, BtnAll); } }//GEN-LAST:event_BtnCariKeyPressed private void BtnAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnAllActionPerformed TCari.setText(""); TabRawatMouseClicked(null); }//GEN-LAST:event_BtnAllActionPerformed private void BtnAllKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_BtnAllKeyPressed if(evt.getKeyCode()==KeyEvent.VK_SPACE){ TCari.setText(""); tampil(); }else{ Valid.pindah(evt, BtnPrint, BtnKeluar); } }//GEN-LAST:event_BtnAllKeyPressed private void tbJnsPerawatanMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbJnsPerawatanMouseClicked if(tabMode.getRowCount()!=0){ try { getData(); } catch (java.lang.NullPointerException e) { } } }//GEN-LAST:event_tbJnsPerawatanMouseClicked private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened tampil(); emptTeks(); }//GEN-LAST:event_formWindowOpened private void tbJnsPerawatanKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbJnsPerawatanKeyReleased if(tabMode.getRowCount()!=0){ if((evt.getKeyCode()==KeyEvent.VK_ENTER)||(evt.getKeyCode()==KeyEvent.VK_UP)||(evt.getKeyCode()==KeyEvent.VK_DOWN)){ try { getData(); } catch (java.lang.NullPointerException e) { } } } }//GEN-LAST:event_tbJnsPerawatanKeyReleased private void btnPoliRSActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPoliRSActionPerformed poli.isCek(); poli.setSize(internalFrame1.getWidth()-20,internalFrame1.getHeight()-20); poli.setLocationRelativeTo(internalFrame1); poli.setVisible(true); }//GEN-LAST:event_btnPoliRSActionPerformed private void btnPoliRSKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnPoliRSKeyPressed Valid.pindah(evt, TCari,Longitude); }//GEN-LAST:event_btnPoliRSKeyPressed private void TabRawatMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TabRawatMouseClicked if(TabRawat.getSelectedIndex()==0){ tampil(); }else if(TabRawat.getSelectedIndex()==1){ tampilkamar(); }else if(TabRawat.getSelectedIndex()==2){ tampilruangok(); }else if(TabRawat.getSelectedIndex()==3){ tampilruanglabpk(); }else if(TabRawat.getSelectedIndex()==4){ tampilruanglabpa(); }else if(TabRawat.getSelectedIndex()==5){ tampilruanglabmb(); }else if(TabRawat.getSelectedIndex()==6){ tampilruangradiologi(); }else if(TabRawat.getSelectedIndex()==7){ tampilruangfarmasi(); } }//GEN-LAST:event_TabRawatMouseClicked private void btnDepartemenKamarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDepartemenKamarActionPerformed pilih=2; organisasi.setSize(internalFrame1.getWidth()-20,internalFrame1.getHeight()-20); organisasi.setLocationRelativeTo(internalFrame1); organisasi.setVisible(true); }//GEN-LAST:event_btnDepartemenKamarActionPerformed private void btnDepartemenKamarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnDepartemenKamarKeyPressed Valid.pindah(evt, AltitudeKamar, BtnSimpan); }//GEN-LAST:event_btnDepartemenKamarKeyPressed private void btnKamarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnKamarActionPerformed kamar.load(); kamar.isCek(); kamar.emptTeks(); kamar.tampil(); kamar.setSize(internalFrame1.getWidth()-20,internalFrame1.getHeight()-20); kamar.setLocationRelativeTo(internalFrame1); kamar.setVisible(true); }//GEN-LAST:event_btnKamarActionPerformed private void btnKamarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnKamarKeyPressed Valid.pindah(evt, TCari, LongitudeKamar); }//GEN-LAST:event_btnKamarKeyPressed private void tbLokasiKamarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbLokasiKamarMouseClicked if(tabModeKamar.getRowCount()!=0){ try { getDataKamar(); } catch (java.lang.NullPointerException e) { } } }//GEN-LAST:event_tbLokasiKamarMouseClicked private void tbLokasiKamarKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbLokasiKamarKeyReleased if(tabModeKamar.getRowCount()!=0){ if((evt.getKeyCode()==KeyEvent.VK_ENTER)||(evt.getKeyCode()==KeyEvent.VK_UP)||(evt.getKeyCode()==KeyEvent.VK_DOWN)){ try { getDataKamar(); } catch (java.lang.NullPointerException e) { } } } }//GEN-LAST:event_tbLokasiKamarKeyReleased private void LongitudeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_LongitudeKeyPressed Valid.pindah(evt, btnPoliRS,Latitude); }//GEN-LAST:event_LongitudeKeyPressed private void LatitudeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_LatitudeKeyPressed Valid.pindah(evt, Longitude,Altitude); }//GEN-LAST:event_LatitudeKeyPressed private void AltitudeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_AltitudeKeyPressed Valid.pindah(evt, Latitude,btnDepartemenRS); }//GEN-LAST:event_AltitudeKeyPressed private void LongitudeKamarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_LongitudeKamarKeyPressed Valid.pindah(evt, btnKamar, LatitudeKamar); }//GEN-LAST:event_LongitudeKamarKeyPressed private void LatitudeKamarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_LatitudeKamarKeyPressed Valid.pindah(evt, LongitudeKamar, AltitudeKamar); }//GEN-LAST:event_LatitudeKamarKeyPressed private void AltitudeKamarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_AltitudeKamarKeyPressed Valid.pindah(evt, LatitudeKamar, btnDepartemenKamar); }//GEN-LAST:event_AltitudeKamarKeyPressed private void btnDepartemenRuangOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDepartemenRuangOKActionPerformed pilih=3; organisasi.setSize(internalFrame1.getWidth()-20,internalFrame1.getHeight()-20); organisasi.setLocationRelativeTo(internalFrame1); organisasi.setVisible(true); }//GEN-LAST:event_btnDepartemenRuangOKActionPerformed private void btnDepartemenRuangOKKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnDepartemenRuangOKKeyPressed Valid.pindah(evt, AltitudeRuangOK, BtnSimpan); }//GEN-LAST:event_btnDepartemenRuangOKKeyPressed private void LongitudeRuangOKKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_LongitudeRuangOKKeyPressed Valid.pindah(evt, TCari, LatitudeRuangOK); }//GEN-LAST:event_LongitudeRuangOKKeyPressed private void LatitudeRuangOKKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_LatitudeRuangOKKeyPressed Valid.pindah(evt, LongitudeRuangOK, AltitudeRuangOK); }//GEN-LAST:event_LatitudeRuangOKKeyPressed private void AltitudeRuangOKKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_AltitudeRuangOKKeyPressed Valid.pindah(evt, LatitudeRuangOK, btnDepartemenRuangOK); }//GEN-LAST:event_AltitudeRuangOKKeyPressed private void tbLokasiRuangOKMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbLokasiRuangOKMouseClicked if(tabModeRuangOK.getRowCount()!=0){ try { getDataRuangOK(); } catch (java.lang.NullPointerException e) { } } }//GEN-LAST:event_tbLokasiRuangOKMouseClicked private void tbLokasiRuangOKKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbLokasiRuangOKKeyReleased if(tabModeRuangOK.getRowCount()!=0){ if((evt.getKeyCode()==KeyEvent.VK_ENTER)||(evt.getKeyCode()==KeyEvent.VK_UP)||(evt.getKeyCode()==KeyEvent.VK_DOWN)){ try { getDataRuangOK(); } catch (java.lang.NullPointerException e) { } } } }//GEN-LAST:event_tbLokasiRuangOKKeyReleased private void btnDepartemenRuangLabPKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDepartemenRuangLabPKActionPerformed pilih=4; organisasi.setSize(internalFrame1.getWidth()-20,internalFrame1.getHeight()-20); organisasi.setLocationRelativeTo(internalFrame1); organisasi.setVisible(true); }//GEN-LAST:event_btnDepartemenRuangLabPKActionPerformed private void btnDepartemenRuangLabPKKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnDepartemenRuangLabPKKeyPressed Valid.pindah(evt, AltitudeRuangLabPK, BtnSimpan); }//GEN-LAST:event_btnDepartemenRuangLabPKKeyPressed private void LongitudeRuangLabPKKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_LongitudeRuangLabPKKeyPressed Valid.pindah(evt, TCari, LatitudeRuangLabPK); }//GEN-LAST:event_LongitudeRuangLabPKKeyPressed private void LatitudeRuangLabPKKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_LatitudeRuangLabPKKeyPressed Valid.pindah(evt, LongitudeRuangLabPK, AltitudeRuangLabPK); }//GEN-LAST:event_LatitudeRuangLabPKKeyPressed private void AltitudeRuangLabPKKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_AltitudeRuangLabPKKeyPressed Valid.pindah(evt, LatitudeRuangLabPK, btnDepartemenRuangOK); }//GEN-LAST:event_AltitudeRuangLabPKKeyPressed private void tbLokasiRuangLabPKMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbLokasiRuangLabPKMouseClicked if(tabModeRuangLabPK.getRowCount()!=0){ try { getDataRuangLabPK(); } catch (java.lang.NullPointerException e) { } } }//GEN-LAST:event_tbLokasiRuangLabPKMouseClicked private void tbLokasiRuangLabPKKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbLokasiRuangLabPKKeyReleased if(tabModeRuangLabPK.getRowCount()!=0){ if((evt.getKeyCode()==KeyEvent.VK_ENTER)||(evt.getKeyCode()==KeyEvent.VK_UP)||(evt.getKeyCode()==KeyEvent.VK_DOWN)){ try { getDataRuangLabPK(); } catch (java.lang.NullPointerException e) { } } } }//GEN-LAST:event_tbLokasiRuangLabPKKeyReleased private void btnDepartemenRuangLabPAActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDepartemenRuangLabPAActionPerformed pilih=5; organisasi.setSize(internalFrame1.getWidth()-20,internalFrame1.getHeight()-20); organisasi.setLocationRelativeTo(internalFrame1); organisasi.setVisible(true); }//GEN-LAST:event_btnDepartemenRuangLabPAActionPerformed private void btnDepartemenRuangLabPAKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnDepartemenRuangLabPAKeyPressed Valid.pindah(evt, AltitudeRuangLabPA, BtnSimpan); }//GEN-LAST:event_btnDepartemenRuangLabPAKeyPressed private void LongitudeRuangLabPAKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_LongitudeRuangLabPAKeyPressed Valid.pindah(evt, TCari, LatitudeRuangLabPA); }//GEN-LAST:event_LongitudeRuangLabPAKeyPressed private void LatitudeRuangLabPAKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_LatitudeRuangLabPAKeyPressed Valid.pindah(evt,LongitudeRuangLabPA, AltitudeRuangLabPA); }//GEN-LAST:event_LatitudeRuangLabPAKeyPressed private void AltitudeRuangLabPAKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_AltitudeRuangLabPAKeyPressed Valid.pindah(evt, LatitudeRuangLabPA, btnDepartemenRuangLabPA); }//GEN-LAST:event_AltitudeRuangLabPAKeyPressed private void tbLokasiRuangLabPAMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbLokasiRuangLabPAMouseClicked if(tabModeRuangLabPA.getRowCount()!=0){ try { getDataRuangLabPA(); } catch (java.lang.NullPointerException e) { } } }//GEN-LAST:event_tbLokasiRuangLabPAMouseClicked private void tbLokasiRuangLabPAKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbLokasiRuangLabPAKeyReleased if(tabModeRuangLabPA.getRowCount()!=0){ if((evt.getKeyCode()==KeyEvent.VK_ENTER)||(evt.getKeyCode()==KeyEvent.VK_UP)||(evt.getKeyCode()==KeyEvent.VK_DOWN)){ try { getDataRuangLabPA(); } catch (java.lang.NullPointerException e) { } } } }//GEN-LAST:event_tbLokasiRuangLabPAKeyReleased private void btnDepartemenRuangLabMBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDepartemenRuangLabMBActionPerformed pilih=6; organisasi.setSize(internalFrame1.getWidth()-20,internalFrame1.getHeight()-20); organisasi.setLocationRelativeTo(internalFrame1); organisasi.setVisible(true); }//GEN-LAST:event_btnDepartemenRuangLabMBActionPerformed private void btnDepartemenRuangLabMBKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnDepartemenRuangLabMBKeyPressed Valid.pindah(evt, AltitudeRuangLabMB, BtnSimpan); }//GEN-LAST:event_btnDepartemenRuangLabMBKeyPressed private void LongitudeRuangLabMBKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_LongitudeRuangLabMBKeyPressed Valid.pindah(evt, TCari, LatitudeRuangLabMB); }//GEN-LAST:event_LongitudeRuangLabMBKeyPressed private void LatitudeRuangLabMBKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_LatitudeRuangLabMBKeyPressed Valid.pindah(evt, LongitudeRuangLabMB, AltitudeRuangLabMB); }//GEN-LAST:event_LatitudeRuangLabMBKeyPressed private void AltitudeRuangLabMBKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_AltitudeRuangLabMBKeyPressed Valid.pindah(evt, LatitudeRuangLabMB, btnDepartemenRuangLabMB); }//GEN-LAST:event_AltitudeRuangLabMBKeyPressed private void tbLokasiRuangLabMBMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbLokasiRuangLabMBMouseClicked if(tabModeRuangLabMB.getRowCount()!=0){ try { getDataRuangLabMB(); } catch (java.lang.NullPointerException e) { } } }//GEN-LAST:event_tbLokasiRuangLabMBMouseClicked private void tbLokasiRuangLabMBKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbLokasiRuangLabMBKeyReleased if(tabModeRuangLabMB.getRowCount()!=0){ if((evt.getKeyCode()==KeyEvent.VK_ENTER)||(evt.getKeyCode()==KeyEvent.VK_UP)||(evt.getKeyCode()==KeyEvent.VK_DOWN)){ try { getDataRuangLabMB(); } catch (java.lang.NullPointerException e) { } } } }//GEN-LAST:event_tbLokasiRuangLabMBKeyReleased private void btnDepartemenRuangRadiologiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDepartemenRuangRadiologiActionPerformed pilih=7; organisasi.setSize(internalFrame1.getWidth()-20,internalFrame1.getHeight()-20); organisasi.setLocationRelativeTo(internalFrame1); organisasi.setVisible(true); }//GEN-LAST:event_btnDepartemenRuangRadiologiActionPerformed private void btnDepartemenRuangRadiologiKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnDepartemenRuangRadiologiKeyPressed Valid.pindah(evt, AltitudeRuangRadiologi, BtnSimpan); }//GEN-LAST:event_btnDepartemenRuangRadiologiKeyPressed private void LongitudeRuangRadiologiKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_LongitudeRuangRadiologiKeyPressed Valid.pindah(evt, TCari, LatitudeRuangRadiologi); }//GEN-LAST:event_LongitudeRuangRadiologiKeyPressed private void LatitudeRuangRadiologiKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_LatitudeRuangRadiologiKeyPressed Valid.pindah(evt, LongitudeRuangRadiologi, AltitudeRuangRadiologi); }//GEN-LAST:event_LatitudeRuangRadiologiKeyPressed private void AltitudeRuangRadiologiKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_AltitudeRuangRadiologiKeyPressed Valid.pindah(evt, LatitudeRuangRadiologi, btnDepartemenRuangRadiologi); }//GEN-LAST:event_AltitudeRuangRadiologiKeyPressed private void tbLokasiRuangRadiologiMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbLokasiRuangRadiologiMouseClicked if(tabModeRuangRadiologi.getRowCount()!=0){ try { getDataRuangRadiologi(); } catch (java.lang.NullPointerException e) { } } }//GEN-LAST:event_tbLokasiRuangRadiologiMouseClicked private void tbLokasiRuangRadiologiKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbLokasiRuangRadiologiKeyReleased if(tabModeRuangRadiologi.getRowCount()!=0){ if((evt.getKeyCode()==KeyEvent.VK_ENTER)||(evt.getKeyCode()==KeyEvent.VK_UP)||(evt.getKeyCode()==KeyEvent.VK_DOWN)){ try { getDataRuangRadiologi(); } catch (java.lang.NullPointerException e) { } } } }//GEN-LAST:event_tbLokasiRuangRadiologiKeyReleased private void btnDepartemenFarmasiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDepartemenFarmasiActionPerformed pilih=8; organisasi.setSize(internalFrame1.getWidth()-20,internalFrame1.getHeight()-20); organisasi.setLocationRelativeTo(internalFrame1); organisasi.setVisible(true); }//GEN-LAST:event_btnDepartemenFarmasiActionPerformed private void btnDepartemenFarmasiKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnDepartemenFarmasiKeyPressed Valid.pindah(evt, AltitudeFarmasi,BtnSimpan); }//GEN-LAST:event_btnDepartemenFarmasiKeyPressed private void btnFarmasiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFarmasiActionPerformed kamar.bangsal.isCek(); kamar.bangsal.setSize(internalFrame1.getWidth()-20,internalFrame1.getHeight()-20); kamar.bangsal.setLocationRelativeTo(internalFrame1); kamar.bangsal.setVisible(true); }//GEN-LAST:event_btnFarmasiActionPerformed private void btnFarmasiKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnFarmasiKeyPressed Valid.pindah(evt, TCari,LongitudeFarmasi); }//GEN-LAST:event_btnFarmasiKeyPressed private void LongitudeFarmasiKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_LongitudeFarmasiKeyPressed Valid.pindah(evt, btnFarmasi,LatitudeFarmasi); }//GEN-LAST:event_LongitudeFarmasiKeyPressed private void LatitudeFarmasiKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_LatitudeFarmasiKeyPressed Valid.pindah(evt, LongitudeFarmasi,AltitudeFarmasi); }//GEN-LAST:event_LatitudeFarmasiKeyPressed private void AltitudeFarmasiKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_AltitudeFarmasiKeyPressed Valid.pindah(evt,LatitudeFarmasi,btnDepartemenFarmasi); }//GEN-LAST:event_AltitudeFarmasiKeyPressed private void tbLokasiFarmasiMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbLokasiFarmasiMouseClicked if(tabModeRuangFarmasi.getRowCount()!=0){ try { getDataRuangFarmasi(); } catch (java.lang.NullPointerException e) { } } }//GEN-LAST:event_tbLokasiFarmasiMouseClicked private void tbLokasiFarmasiKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbLokasiFarmasiKeyReleased if(tabModeRuangFarmasi.getRowCount()!=0){ if((evt.getKeyCode()==KeyEvent.VK_ENTER)||(evt.getKeyCode()==KeyEvent.VK_UP)||(evt.getKeyCode()==KeyEvent.VK_DOWN)){ try { getDataRuangFarmasi(); } catch (java.lang.NullPointerException e) { } } } }//GEN-LAST:event_tbLokasiFarmasiKeyReleased /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(() -> { SatuSehatMapingLokasi dialog = new SatuSehatMapingLokasi(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); }); } // Variables declaration - do not modify//GEN-BEGIN:variables private widget.TextBox Altitude; private widget.TextBox AltitudeFarmasi; private widget.TextBox AltitudeKamar; private widget.TextBox AltitudeRuangLabMB; private widget.TextBox AltitudeRuangLabPA; private widget.TextBox AltitudeRuangLabPK; private widget.TextBox AltitudeRuangOK; private widget.TextBox AltitudeRuangRadiologi; private widget.Button BtnAll; private widget.Button BtnBatal; private widget.Button BtnCari; private widget.Button BtnEdit; private widget.Button BtnHapus; private widget.Button BtnKeluar; private widget.Button BtnPrint; private widget.Button BtnSimpan; private widget.PanelBiasa FormInput; private widget.PanelBiasa FormInput1; private widget.PanelBiasa FormInput2; private widget.PanelBiasa FormInput3; private widget.PanelBiasa FormInput4; private widget.PanelBiasa FormInput5; private widget.PanelBiasa FormInput6; private widget.PanelBiasa FormInput7; private widget.TextBox IDOrganisasi; private widget.TextBox IDOrganisasiFarmasi; private widget.TextBox IDOrganisasiKamar; private widget.TextBox IDOrganisasiRuangLabMB; private widget.TextBox IDOrganisasiRuangLabPA; private widget.TextBox IDOrganisasiRuangLabPK; private widget.TextBox IDOrganisasiRuangOK; private widget.TextBox IDOrganisasiRuangRadiologi; private widget.TextBox KodeDepartemen; private widget.TextBox KodeDepartemenFarmasi; private widget.TextBox KodeDepartemenKamar; private widget.TextBox KodeDepartemenRuangLabMB; private widget.TextBox KodeDepartemenRuangLabPA; private widget.TextBox KodeDepartemenRuangLabPK; private widget.TextBox KodeDepartemenRuangOK; private widget.TextBox KodeDepartemenRuangRadiologi; private widget.TextBox KodeFarmasi; private widget.TextBox KodeKamar; private widget.TextBox KodePoli; private widget.Label LCount; private widget.TextBox Latitude; private widget.TextBox LatitudeFarmasi; private widget.TextBox LatitudeKamar; private widget.TextBox LatitudeRuangLabMB; private widget.TextBox LatitudeRuangLabPA; private widget.TextBox LatitudeRuangLabPK; private widget.TextBox LatitudeRuangOK; private widget.TextBox LatitudeRuangRadiologi; private widget.TextBox Longitude; private widget.TextBox LongitudeFarmasi; private widget.TextBox LongitudeKamar; private widget.TextBox LongitudeRuangLabMB; private widget.TextBox LongitudeRuangLabPA; private widget.TextBox LongitudeRuangLabPK; private widget.TextBox LongitudeRuangOK; private widget.TextBox LongitudeRuangRadiologi; private widget.TextBox NamaDepartemen; private widget.TextBox NamaDepartemenFarmasi; private widget.TextBox NamaDepartemenKamar; private widget.TextBox NamaDepartemenRuangLabMB; private widget.TextBox NamaDepartemenRuangLabPA; private widget.TextBox NamaDepartemenRuangLabPK; private widget.TextBox NamaDepartemenRuangOK; private widget.TextBox NamaDepartemenRuangRadiologi; private widget.TextBox NamaFarmasi; private widget.TextBox NamaKamar; private widget.TextBox NamaPoli; private widget.ScrollPane Scroll; private widget.ScrollPane Scroll1; private widget.ScrollPane Scroll2; private widget.ScrollPane Scroll3; private widget.ScrollPane Scroll4; private widget.ScrollPane Scroll5; private widget.ScrollPane Scroll6; private widget.ScrollPane Scroll7; private widget.TextBox TCari; private javax.swing.JTabbedPane TabRawat; private widget.Button btnDepartemenFarmasi; private widget.Button btnDepartemenKamar; private widget.Button btnDepartemenRS; private widget.Button btnDepartemenRuangLabMB; private widget.Button btnDepartemenRuangLabPA; private widget.Button btnDepartemenRuangLabPK; private widget.Button btnDepartemenRuangOK; private widget.Button btnDepartemenRuangRadiologi; private widget.Button btnFarmasi; private widget.Button btnKamar; private widget.Button btnPoliRS; private widget.InternalFrame internalFrame1; private widget.InternalFrame internalFrame2; private widget.InternalFrame internalFrame3; private widget.InternalFrame internalFrame4; private widget.InternalFrame internalFrame5; private widget.InternalFrame internalFrame6; private widget.InternalFrame internalFrame7; private widget.InternalFrame internalFrame8; private widget.InternalFrame internalFrame9; private widget.Label jLabel10; private widget.Label jLabel11; private widget.Label jLabel12; private widget.Label jLabel13; private widget.Label jLabel14; private widget.Label jLabel15; private widget.Label jLabel16; private widget.Label jLabel17; private widget.Label jLabel18; private widget.Label jLabel19; private widget.Label jLabel20; private widget.Label jLabel21; private widget.Label jLabel22; private widget.Label jLabel23; private widget.Label jLabel24; private widget.Label jLabel25; private widget.Label jLabel26; private widget.Label jLabel27; private widget.Label jLabel28; private widget.Label jLabel29; private widget.Label jLabel30; private widget.Label jLabel31; private widget.Label jLabel32; private widget.Label jLabel33; private widget.Label jLabel34; private widget.Label jLabel35; private widget.Label jLabel36; private widget.Label jLabel37; private widget.Label jLabel38; private widget.Label jLabel39; private widget.Label jLabel4; private widget.Label jLabel40; private widget.Label jLabel5; private widget.Label jLabel6; private widget.Label jLabel7; private widget.Label jLabel8; private widget.Label jLabel9; private javax.swing.JPanel jPanel3; private widget.panelisi panelGlass8; private widget.panelisi panelGlass9; private widget.Table tbJnsPerawatan; private widget.Table tbLokasiFarmasi; private widget.Table tbLokasiKamar; private widget.Table tbLokasiRuangLabMB; private widget.Table tbLokasiRuangLabPA; private widget.Table tbLokasiRuangLabPK; private widget.Table tbLokasiRuangOK; private widget.Table tbLokasiRuangRadiologi; // End of variables declaration//GEN-END:variables private void tampil() { Valid.tabelKosong(tabMode); try{ ps=koneksi.prepareStatement( "select satu_sehat_mapping_lokasi_ralan.kd_poli,poliklinik.nm_poli,satu_sehat_mapping_lokasi_ralan.id_lokasi_satusehat,"+ "satu_sehat_mapping_lokasi_ralan.longitude,satu_sehat_mapping_lokasi_ralan.latitude,satu_sehat_mapping_lokasi_ralan.altittude,"+ "satu_sehat_mapping_departemen.dep_id,departemen.nama,satu_sehat_mapping_lokasi_ralan.id_organisasi_satusehat "+ "from satu_sehat_mapping_lokasi_ralan inner join poliklinik on satu_sehat_mapping_lokasi_ralan.kd_poli=poliklinik.kd_poli "+ "inner join satu_sehat_mapping_departemen on satu_sehat_mapping_lokasi_ralan.id_organisasi_satusehat=satu_sehat_mapping_departemen.id_organisasi_satusehat "+ "inner join departemen on satu_sehat_mapping_departemen.dep_id=departemen.dep_id "+ (TCari.getText().equals("")?"":"where satu_sehat_mapping_departemen.dep_id like ? or departemen.nama like ? or "+ "poliklinik.nm_poli like ? or satu_sehat_mapping_lokasi_ralan.kd_poli like ?")+" order by departemen.nama"); try { if(!TCari.getText().equals("")){ ps.setString(1,"%"+TCari.getText()+"%"); ps.setString(2,"%"+TCari.getText()+"%"); ps.setString(3,"%"+TCari.getText()+"%"); ps.setString(4,"%"+TCari.getText()+"%"); } rs=ps.executeQuery(); while(rs.next()){ tabMode.addRow(new Object[]{ rs.getString("kd_poli"),rs.getString("nm_poli"),rs.getString("id_lokasi_satusehat"),rs.getString("longitude"),rs.getString("latitude"), rs.getString("altittude"),rs.getString("dep_id"),rs.getString("nama"),rs.getString("id_organisasi_satusehat") }); } } catch (Exception e) { System.out.println("Notif : "+e); } finally{ if(rs!=null){ rs.close(); } if(ps!=null){ ps.close(); } } }catch(Exception e){ System.out.println("Notifikasi : "+e); } LCount.setText(""+tabMode.getRowCount()); } public void emptTeks() { if(TabRawat.getSelectedIndex()==0){ KodePoli.setText(""); NamaPoli.setText(""); Longitude.setText(""); Altitude.setText(""); Latitude.setText(""); KodeDepartemen.setText(""); NamaDepartemen.setText(""); IDOrganisasi.setText(""); btnPoliRS.requestFocus(); }else if(TabRawat.getSelectedIndex()==1){ KodeKamar.setText(""); NamaKamar.setText(""); LongitudeKamar.setText(""); AltitudeKamar.setText(""); LatitudeKamar.setText(""); KodeDepartemenKamar.setText(""); NamaDepartemenKamar.setText(""); IDOrganisasiKamar.setText(""); btnKamar.requestFocus(); }else if(TabRawat.getSelectedIndex()==2){ LongitudeRuangOK.setText(""); AltitudeRuangOK.setText(""); LatitudeRuangOK.setText(""); KodeDepartemenRuangOK.setText(""); NamaDepartemenRuangOK.setText(""); LongitudeRuangOK.requestFocus(); IDOrganisasiRuangOK.setText(""); }else if(TabRawat.getSelectedIndex()==3){ LongitudeRuangLabPK.setText(""); AltitudeRuangLabPK.setText(""); LatitudeRuangLabPK.setText(""); KodeDepartemenRuangLabPK.setText(""); NamaDepartemenRuangLabPK.setText(""); LongitudeRuangLabPK.requestFocus(); IDOrganisasiRuangLabPK.setText(""); }else if(TabRawat.getSelectedIndex()==4){ LongitudeRuangLabPA.setText(""); AltitudeRuangLabPA.setText(""); LatitudeRuangLabPA.setText(""); KodeDepartemenRuangLabPA.setText(""); NamaDepartemenRuangLabPA.setText(""); LongitudeRuangLabPA.requestFocus(); IDOrganisasiRuangLabPA.setText(""); }else if(TabRawat.getSelectedIndex()==5){ LongitudeRuangLabMB.setText(""); AltitudeRuangLabMB.setText(""); LatitudeRuangLabMB.setText(""); KodeDepartemenRuangLabMB.setText(""); NamaDepartemenRuangLabMB.setText(""); LongitudeRuangLabMB.requestFocus(); IDOrganisasiRuangLabMB.setText(""); }else if(TabRawat.getSelectedIndex()==6){ LongitudeRuangRadiologi.setText(""); AltitudeRuangRadiologi.setText(""); LatitudeRuangRadiologi.setText(""); KodeDepartemenRuangRadiologi.setText(""); NamaDepartemenRuangRadiologi.setText(""); LongitudeRuangRadiologi.requestFocus(); IDOrganisasiRuangRadiologi.setText(""); }else if(TabRawat.getSelectedIndex()==7){ KodeFarmasi.setText(""); NamaFarmasi.setText(""); LongitudeFarmasi.setText(""); AltitudeFarmasi.setText(""); LatitudeFarmasi.setText(""); KodeDepartemenFarmasi.setText(""); NamaDepartemenFarmasi.setText(""); IDOrganisasiFarmasi.setText(""); btnFarmasi.requestFocus(); } } private void getData() { if(tbJnsPerawatan.getSelectedRow()!= -1){ KodePoli.setText(tbJnsPerawatan.getValueAt(tbJnsPerawatan.getSelectedRow(),0).toString()); NamaPoli.setText(tbJnsPerawatan.getValueAt(tbJnsPerawatan.getSelectedRow(),1).toString()); Longitude.setText(tbJnsPerawatan.getValueAt(tbJnsPerawatan.getSelectedRow(),3).toString()); Latitude.setText(tbJnsPerawatan.getValueAt(tbJnsPerawatan.getSelectedRow(),4).toString()); Altitude.setText(tbJnsPerawatan.getValueAt(tbJnsPerawatan.getSelectedRow(),5).toString()); KodeDepartemen.setText(tbJnsPerawatan.getValueAt(tbJnsPerawatan.getSelectedRow(),6).toString()); NamaDepartemen.setText(tbJnsPerawatan.getValueAt(tbJnsPerawatan.getSelectedRow(),7).toString()); IDOrganisasi.setText(tbJnsPerawatan.getValueAt(tbJnsPerawatan.getSelectedRow(),8).toString()); } } private void getDataKamar() { if(tbLokasiKamar.getSelectedRow()!= -1){ KodeKamar.setText(tbLokasiKamar.getValueAt(tbLokasiKamar.getSelectedRow(),0).toString()); NamaKamar.setText(tbLokasiKamar.getValueAt(tbLokasiKamar.getSelectedRow(),1).toString()); LongitudeKamar.setText(tbLokasiKamar.getValueAt(tbLokasiKamar.getSelectedRow(),3).toString()); LatitudeKamar.setText(tbLokasiKamar.getValueAt(tbLokasiKamar.getSelectedRow(),4).toString()); AltitudeKamar.setText(tbLokasiKamar.getValueAt(tbLokasiKamar.getSelectedRow(),5).toString()); KodeDepartemenKamar.setText(tbLokasiKamar.getValueAt(tbLokasiKamar.getSelectedRow(),6).toString()); NamaDepartemenKamar.setText(tbLokasiKamar.getValueAt(tbLokasiKamar.getSelectedRow(),7).toString()); IDOrganisasiKamar.setText(tbLokasiKamar.getValueAt(tbLokasiKamar.getSelectedRow(),8).toString()); } } public void isCek(){ BtnSimpan.setEnabled(akses.getsatu_sehat_mapping_lokasi()); BtnHapus.setEnabled(akses.getsatu_sehat_mapping_lokasi()); BtnEdit.setEnabled(akses.getsatu_sehat_mapping_lokasi()); BtnPrint.setEnabled(akses.getsatu_sehat_mapping_lokasi()); } private void tampilkamar() { Valid.tabelKosong(tabModeKamar); try{ ps=koneksi.prepareStatement( "select satu_sehat_mapping_lokasi_ranap.kd_kamar,bangsal.nm_bangsal,satu_sehat_mapping_lokasi_ranap.id_lokasi_satusehat,"+ "satu_sehat_mapping_lokasi_ranap.longitude,satu_sehat_mapping_lokasi_ranap.latitude,satu_sehat_mapping_lokasi_ranap.altittude,"+ "satu_sehat_mapping_departemen.dep_id,departemen.nama,satu_sehat_mapping_lokasi_ranap.id_organisasi_satusehat "+ "from satu_sehat_mapping_lokasi_ranap inner join kamar on satu_sehat_mapping_lokasi_ranap.kd_kamar=kamar.kd_kamar "+ "inner join bangsal on kamar.kd_bangsal=bangsal.kd_bangsal inner join satu_sehat_mapping_departemen "+ "on satu_sehat_mapping_lokasi_ranap.id_organisasi_satusehat=satu_sehat_mapping_departemen.id_organisasi_satusehat "+ "inner join departemen on satu_sehat_mapping_departemen.dep_id=departemen.dep_id "+ (TCari.getText().equals("")?"":"where satu_sehat_mapping_departemen.dep_id like ? or departemen.nama like ? or "+ "bangsal.nm_bangsal like ? or satu_sehat_mapping_lokasi_ranap.kd_kamar like ?")+" order by departemen.nama"); try { if(!TCari.getText().equals("")){ ps.setString(1,"%"+TCari.getText()+"%"); ps.setString(2,"%"+TCari.getText()+"%"); ps.setString(3,"%"+TCari.getText()+"%"); ps.setString(4,"%"+TCari.getText()+"%"); } rs=ps.executeQuery(); while(rs.next()){ tabModeKamar.addRow(new Object[]{ rs.getString("kd_kamar"),rs.getString("nm_bangsal"),rs.getString("id_lokasi_satusehat"),rs.getString("longitude"),rs.getString("latitude"), rs.getString("altittude"),rs.getString("dep_id"),rs.getString("nama"),rs.getString("id_organisasi_satusehat") }); } } catch (Exception e) { System.out.println("Notif : "+e); } finally{ if(rs!=null){ rs.close(); } if(ps!=null){ ps.close(); } } }catch(Exception e){ System.out.println("Notifikasi : "+e); } LCount.setText(""+tabModeKamar.getRowCount()); } private void tampilruangok() { Valid.tabelKosong(tabModeRuangOK); try{ ps=koneksi.prepareStatement( "select satu_sehat_mapping_lokasi_ruangok.id_lokasi_satusehat,satu_sehat_mapping_lokasi_ruangok.longitude,"+ "satu_sehat_mapping_lokasi_ruangok.latitude,satu_sehat_mapping_lokasi_ruangok.altittude,"+ "satu_sehat_mapping_departemen.dep_id,departemen.nama,satu_sehat_mapping_lokasi_ruangok.id_organisasi_satusehat "+ "from satu_sehat_mapping_lokasi_ruangok inner join satu_sehat_mapping_departemen "+ "on satu_sehat_mapping_lokasi_ruangok.id_organisasi_satusehat=satu_sehat_mapping_departemen.id_organisasi_satusehat "+ "inner join departemen on satu_sehat_mapping_departemen.dep_id=departemen.dep_id"); try { rs=ps.executeQuery(); while(rs.next()){ tabModeRuangOK.addRow(new Object[]{ rs.getString("id_lokasi_satusehat"),rs.getString("longitude"),rs.getString("latitude"), rs.getString("altittude"),rs.getString("dep_id"),rs.getString("nama"),rs.getString("id_organisasi_satusehat") }); } } catch (Exception e) { System.out.println("Notif : "+e); } finally{ if(rs!=null){ rs.close(); } if(ps!=null){ ps.close(); } } }catch(Exception e){ System.out.println("Notifikasi : "+e); } LCount.setText(""+tabModeRuangOK.getRowCount()); } private void tampilruanglabpk() { Valid.tabelKosong(tabModeRuangLabPK); try{ ps=koneksi.prepareStatement( "select satu_sehat_mapping_lokasi_ruanglab.id_lokasi_satusehat,satu_sehat_mapping_lokasi_ruanglab.longitude,"+ "satu_sehat_mapping_lokasi_ruanglab.latitude,satu_sehat_mapping_lokasi_ruanglab.altittude,"+ "satu_sehat_mapping_departemen.dep_id,departemen.nama,satu_sehat_mapping_lokasi_ruanglab.id_organisasi_satusehat "+ "from satu_sehat_mapping_lokasi_ruanglab inner join satu_sehat_mapping_departemen "+ "on satu_sehat_mapping_lokasi_ruanglab.id_organisasi_satusehat=satu_sehat_mapping_departemen.id_organisasi_satusehat "+ "inner join departemen on satu_sehat_mapping_departemen.dep_id=departemen.dep_id"); try { rs=ps.executeQuery(); while(rs.next()){ tabModeRuangLabPK.addRow(new Object[]{ rs.getString("id_lokasi_satusehat"),rs.getString("longitude"),rs.getString("latitude"), rs.getString("altittude"),rs.getString("dep_id"),rs.getString("nama"),rs.getString("id_organisasi_satusehat") }); } } catch (Exception e) { System.out.println("Notif : "+e); } finally{ if(rs!=null){ rs.close(); } if(ps!=null){ ps.close(); } } }catch(Exception e){ System.out.println("Notifikasi : "+e); } LCount.setText(""+tabModeRuangLabPK.getRowCount()); } private void tampilruanglabpa() { Valid.tabelKosong(tabModeRuangLabPA); try{ ps=koneksi.prepareStatement( "select satu_sehat_mapping_lokasi_ruanglabpa.id_lokasi_satusehat,satu_sehat_mapping_lokasi_ruanglabpa.longitude,"+ "satu_sehat_mapping_lokasi_ruanglabpa.latitude,satu_sehat_mapping_lokasi_ruanglabpa.altittude,"+ "satu_sehat_mapping_departemen.dep_id,departemen.nama,satu_sehat_mapping_lokasi_ruanglabpa.id_organisasi_satusehat "+ "from satu_sehat_mapping_lokasi_ruanglabpa inner join satu_sehat_mapping_departemen "+ "on satu_sehat_mapping_lokasi_ruanglabpa.id_organisasi_satusehat=satu_sehat_mapping_departemen.id_organisasi_satusehat "+ "inner join departemen on satu_sehat_mapping_departemen.dep_id=departemen.dep_id"); try { rs=ps.executeQuery(); while(rs.next()){ tabModeRuangLabPA.addRow(new Object[]{ rs.getString("id_lokasi_satusehat"),rs.getString("longitude"),rs.getString("latitude"), rs.getString("altittude"),rs.getString("dep_id"),rs.getString("nama"),rs.getString("id_organisasi_satusehat") }); } } catch (Exception e) { System.out.println("Notif : "+e); } finally{ if(rs!=null){ rs.close(); } if(ps!=null){ ps.close(); } } }catch(Exception e){ System.out.println("Notifikasi : "+e); } LCount.setText(""+tabModeRuangLabPA.getRowCount()); } private void tampilruanglabmb() { Valid.tabelKosong(tabModeRuangLabMB); try{ ps=koneksi.prepareStatement( "select satu_sehat_mapping_lokasi_ruanglabmb.id_lokasi_satusehat,satu_sehat_mapping_lokasi_ruanglabmb.longitude,"+ "satu_sehat_mapping_lokasi_ruanglabmb.latitude,satu_sehat_mapping_lokasi_ruanglabmb.altittude,"+ "satu_sehat_mapping_departemen.dep_id,departemen.nama,satu_sehat_mapping_lokasi_ruanglabmb.id_organisasi_satusehat "+ "from satu_sehat_mapping_lokasi_ruanglabmb inner join satu_sehat_mapping_departemen "+ "on satu_sehat_mapping_lokasi_ruanglabmb.id_organisasi_satusehat=satu_sehat_mapping_departemen.id_organisasi_satusehat "+ "inner join departemen on satu_sehat_mapping_departemen.dep_id=departemen.dep_id"); try { rs=ps.executeQuery(); while(rs.next()){ tabModeRuangLabMB.addRow(new Object[]{ rs.getString("id_lokasi_satusehat"),rs.getString("longitude"),rs.getString("latitude"), rs.getString("altittude"),rs.getString("dep_id"),rs.getString("nama"),rs.getString("id_organisasi_satusehat") }); } } catch (Exception e) { System.out.println("Notif : "+e); } finally{ if(rs!=null){ rs.close(); } if(ps!=null){ ps.close(); } } }catch(Exception e){ System.out.println("Notifikasi : "+e); } LCount.setText(""+tabModeRuangLabMB.getRowCount()); } private void tampilruangradiologi() { Valid.tabelKosong(tabModeRuangRadiologi); try{ ps=koneksi.prepareStatement( "select satu_sehat_mapping_lokasi_ruangrad.id_lokasi_satusehat,satu_sehat_mapping_lokasi_ruangrad.longitude,"+ "satu_sehat_mapping_lokasi_ruangrad.latitude,satu_sehat_mapping_lokasi_ruangrad.altittude,"+ "satu_sehat_mapping_departemen.dep_id,departemen.nama,satu_sehat_mapping_lokasi_ruangrad.id_organisasi_satusehat "+ "from satu_sehat_mapping_lokasi_ruangrad inner join satu_sehat_mapping_departemen "+ "on satu_sehat_mapping_lokasi_ruangrad.id_organisasi_satusehat=satu_sehat_mapping_departemen.id_organisasi_satusehat "+ "inner join departemen on satu_sehat_mapping_departemen.dep_id=departemen.dep_id"); try { rs=ps.executeQuery(); while(rs.next()){ tabModeRuangRadiologi.addRow(new Object[]{ rs.getString("id_lokasi_satusehat"),rs.getString("longitude"),rs.getString("latitude"), rs.getString("altittude"),rs.getString("dep_id"),rs.getString("nama"),rs.getString("id_organisasi_satusehat") }); } } catch (Exception e) { System.out.println("Notif : "+e); } finally{ if(rs!=null){ rs.close(); } if(ps!=null){ ps.close(); } } }catch(Exception e){ System.out.println("Notifikasi : "+e); } LCount.setText(""+tabModeRuangRadiologi.getRowCount()); } private void tampilruangfarmasi() { Valid.tabelKosong(tabModeRuangFarmasi); try{ ps=koneksi.prepareStatement( "select satu_sehat_mapping_lokasi_depo_farmasi.kd_bangsal,bangsal.nm_bangsal,satu_sehat_mapping_lokasi_depo_farmasi.id_lokasi_satusehat,"+ "satu_sehat_mapping_lokasi_depo_farmasi.longitude,satu_sehat_mapping_lokasi_depo_farmasi.latitude,satu_sehat_mapping_lokasi_depo_farmasi.altittude,"+ "satu_sehat_mapping_departemen.dep_id,departemen.nama,satu_sehat_mapping_lokasi_depo_farmasi.id_organisasi_satusehat "+ "from satu_sehat_mapping_lokasi_depo_farmasi inner join bangsal on satu_sehat_mapping_lokasi_depo_farmasi.kd_bangsal=bangsal.kd_bangsal "+ "inner join satu_sehat_mapping_departemen on satu_sehat_mapping_lokasi_depo_farmasi.id_organisasi_satusehat=satu_sehat_mapping_departemen.id_organisasi_satusehat "+ "inner join departemen on satu_sehat_mapping_departemen.dep_id=departemen.dep_id "+ (TCari.getText().equals("")?"":"where satu_sehat_mapping_departemen.dep_id like ? or departemen.nama like ? or "+ "bangsal.nm_bangsal like ? or satu_sehat_mapping_lokasi_depo_farmasi.kd_bangsal like ?")+" order by departemen.nama"); try { if(!TCari.getText().equals("")){ ps.setString(1,"%"+TCari.getText()+"%"); ps.setString(2,"%"+TCari.getText()+"%"); ps.setString(3,"%"+TCari.getText()+"%"); ps.setString(4,"%"+TCari.getText()+"%"); } rs=ps.executeQuery(); while(rs.next()){ tabModeRuangFarmasi.addRow(new Object[]{ rs.getString("kd_bangsal"),rs.getString("nm_bangsal"),rs.getString("id_lokasi_satusehat"),rs.getString("longitude"),rs.getString("latitude"), rs.getString("altittude"),rs.getString("dep_id"),rs.getString("nama"),rs.getString("id_organisasi_satusehat") }); } } catch (Exception e) { System.out.println("Notif : "+e); } finally{ if(rs!=null){ rs.close(); } if(ps!=null){ ps.close(); } } }catch(Exception e){ System.out.println("Notifikasi : "+e); } LCount.setText(""+tabModeRuangFarmasi.getRowCount()); } private void getDataRuangOK() { if(tbLokasiRuangOK.getSelectedRow()!= -1){ LongitudeRuangOK.setText(tbLokasiRuangOK.getValueAt(tbLokasiRuangOK.getSelectedRow(),1).toString()); LatitudeRuangOK.setText(tbLokasiRuangOK.getValueAt(tbLokasiRuangOK.getSelectedRow(),2).toString()); AltitudeRuangOK.setText(tbLokasiRuangOK.getValueAt(tbLokasiRuangOK.getSelectedRow(),3).toString()); KodeDepartemenRuangOK.setText(tbLokasiRuangOK.getValueAt(tbLokasiRuangOK.getSelectedRow(),4).toString()); NamaDepartemenRuangOK.setText(tbLokasiRuangOK.getValueAt(tbLokasiRuangOK.getSelectedRow(),5).toString()); IDOrganisasiRuangOK.setText(tbLokasiRuangOK.getValueAt(tbLokasiRuangOK.getSelectedRow(),6).toString()); } } private void getDataRuangLabPK() { if(tbLokasiRuangLabPK.getSelectedRow()!= -1){ LongitudeRuangLabPK.setText(tbLokasiRuangLabPK.getValueAt(tbLokasiRuangLabPK.getSelectedRow(),1).toString()); LatitudeRuangLabPK.setText(tbLokasiRuangLabPK.getValueAt(tbLokasiRuangLabPK.getSelectedRow(),2).toString()); AltitudeRuangLabPK.setText(tbLokasiRuangLabPK.getValueAt(tbLokasiRuangLabPK.getSelectedRow(),3).toString()); KodeDepartemenRuangLabPK.setText(tbLokasiRuangLabPK.getValueAt(tbLokasiRuangLabPK.getSelectedRow(),4).toString()); NamaDepartemenRuangLabPK.setText(tbLokasiRuangLabPK.getValueAt(tbLokasiRuangLabPK.getSelectedRow(),5).toString()); IDOrganisasiRuangLabPK.setText(tbLokasiRuangLabPK.getValueAt(tbLokasiRuangLabPK.getSelectedRow(),6).toString()); } } private void getDataRuangLabPA() { if(tbLokasiRuangLabPA.getSelectedRow()!= -1){ LongitudeRuangLabPA.setText(tbLokasiRuangLabPA.getValueAt(tbLokasiRuangLabPA.getSelectedRow(),1).toString()); LatitudeRuangLabPA.setText(tbLokasiRuangLabPA.getValueAt(tbLokasiRuangLabPA.getSelectedRow(),2).toString()); AltitudeRuangLabPA.setText(tbLokasiRuangLabPA.getValueAt(tbLokasiRuangLabPA.getSelectedRow(),3).toString()); KodeDepartemenRuangLabPA.setText(tbLokasiRuangLabPA.getValueAt(tbLokasiRuangLabPA.getSelectedRow(),4).toString()); NamaDepartemenRuangLabPA.setText(tbLokasiRuangLabPA.getValueAt(tbLokasiRuangLabPA.getSelectedRow(),5).toString()); IDOrganisasiRuangLabPA.setText(tbLokasiRuangLabPA.getValueAt(tbLokasiRuangLabPA.getSelectedRow(),6).toString()); } } private void getDataRuangLabMB() { if(tbLokasiRuangLabMB.getSelectedRow()!= -1){ LongitudeRuangLabMB.setText(tbLokasiRuangLabMB.getValueAt(tbLokasiRuangLabMB.getSelectedRow(),1).toString()); LatitudeRuangLabMB.setText(tbLokasiRuangLabMB.getValueAt(tbLokasiRuangLabMB.getSelectedRow(),2).toString()); AltitudeRuangLabMB.setText(tbLokasiRuangLabMB.getValueAt(tbLokasiRuangLabMB.getSelectedRow(),3).toString()); KodeDepartemenRuangLabMB.setText(tbLokasiRuangLabMB.getValueAt(tbLokasiRuangLabMB.getSelectedRow(),4).toString()); NamaDepartemenRuangLabMB.setText(tbLokasiRuangLabMB.getValueAt(tbLokasiRuangLabMB.getSelectedRow(),5).toString()); IDOrganisasiRuangLabMB.setText(tbLokasiRuangLabMB.getValueAt(tbLokasiRuangLabMB.getSelectedRow(),6).toString()); } } private void getDataRuangRadiologi() { if(tbLokasiRuangRadiologi.getSelectedRow()!= -1){ LongitudeRuangRadiologi.setText(tbLokasiRuangRadiologi.getValueAt(tbLokasiRuangRadiologi.getSelectedRow(),1).toString()); LatitudeRuangRadiologi.setText(tbLokasiRuangRadiologi.getValueAt(tbLokasiRuangRadiologi.getSelectedRow(),2).toString()); AltitudeRuangRadiologi.setText(tbLokasiRuangRadiologi.getValueAt(tbLokasiRuangRadiologi.getSelectedRow(),3).toString()); KodeDepartemenRuangRadiologi.setText(tbLokasiRuangRadiologi.getValueAt(tbLokasiRuangRadiologi.getSelectedRow(),4).toString()); NamaDepartemenRuangRadiologi.setText(tbLokasiRuangRadiologi.getValueAt(tbLokasiRuangRadiologi.getSelectedRow(),5).toString()); IDOrganisasiRuangRadiologi.setText(tbLokasiRuangRadiologi.getValueAt(tbLokasiRuangRadiologi.getSelectedRow(),6).toString()); } } private void getDataRuangFarmasi() { if(tbLokasiFarmasi.getSelectedRow()!= -1){ KodeFarmasi.setText(tbLokasiFarmasi.getValueAt(tbLokasiFarmasi.getSelectedRow(),0).toString()); NamaFarmasi.setText(tbLokasiFarmasi.getValueAt(tbLokasiFarmasi.getSelectedRow(),1).toString()); LongitudeFarmasi.setText(tbLokasiFarmasi.getValueAt(tbLokasiFarmasi.getSelectedRow(),3).toString()); LatitudeFarmasi.setText(tbLokasiFarmasi.getValueAt(tbLokasiFarmasi.getSelectedRow(),4).toString()); AltitudeFarmasi.setText(tbLokasiFarmasi.getValueAt(tbLokasiFarmasi.getSelectedRow(),5).toString()); KodeDepartemenFarmasi.setText(tbLokasiFarmasi.getValueAt(tbLokasiFarmasi.getSelectedRow(),6).toString()); NamaDepartemenFarmasi.setText(tbLokasiFarmasi.getValueAt(tbLokasiFarmasi.getSelectedRow(),7).toString()); IDOrganisasiFarmasi.setText(tbLokasiFarmasi.getValueAt(tbLokasiFarmasi.getSelectedRow(),8).toString()); } } }
mas-elkhanza/SIMRS-Khanza
src/bridging/SatuSehatMapingLokasi.java
213,365
/* * Copyright 2014 NAVER Corp. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.plugin.logback; import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig; import com.navercorp.pinpoint.common.util.CollectionUtils; import com.navercorp.pinpoint.common.util.StringUtils; import java.util.List; /** * @author Minwoo Jung * */ public class LogbackConfig { private static final String LOGBACK_LOGGING_TRANSACTION_INFO = "profiler.logback.logging.transactioninfo"; private static final String LOGBACK_LOGGING_PATTERN_REPLACE_ENABLE = "profiler.logback.logging.pattern.replace.enable"; private static final String LOGBACK_LOGGING_PATTERN_REPLACE_SEARCH = "profiler.logback.logging.pattern.replace.search"; private static final String LOGBACK_LOGGING_PATTERN_REPLACE_WITH = "profiler.logback.logging.pattern.replace.with"; private final boolean logbackLoggingTransactionInfo; private final boolean patternReplaceEnable; private final List<String> patternReplaceSearchList; private final String patternReplaceWith; public LogbackConfig(ProfilerConfig config) { this.logbackLoggingTransactionInfo = config.readBoolean(LOGBACK_LOGGING_TRANSACTION_INFO, false); this.patternReplaceSearchList = config.readList(LOGBACK_LOGGING_PATTERN_REPLACE_SEARCH); this.patternReplaceWith = config.readString(LOGBACK_LOGGING_PATTERN_REPLACE_WITH, ""); boolean configEnabled = config.readBoolean(LOGBACK_LOGGING_PATTERN_REPLACE_ENABLE, false); boolean configOk = !CollectionUtils.isEmpty(patternReplaceSearchList) && StringUtils.hasText(patternReplaceWith); this.patternReplaceEnable = configEnabled && configOk; } public boolean isLogbackLoggingTransactionInfo() { return logbackLoggingTransactionInfo; } public boolean isPatternReplaceEnable() { return patternReplaceEnable; } public List<String> getPatternReplaceSearchList() { return patternReplaceSearchList; } public String getPatternReplaceWith() { return patternReplaceWith; } @Override public String toString() { return "LogbackConfig{" + "logbackLoggingTransactionInfo=" + logbackLoggingTransactionInfo + ", patternReplaceEnable=" + patternReplaceEnable + ", patternReplaceSearchList=" + patternReplaceSearchList + ", patternReplaceWith='" + patternReplaceWith + '\'' + '}'; } }
pinpoint-apm/pinpoint
agent-module/plugins/logback/src/main/java/com/navercorp/pinpoint/plugin/logback/LogbackConfig.java
213,367
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ module java.base { exports java.io; exports java.lang.annotation; exports java.lang.invoke; exports java.lang.reflect; exports java.lang; exports java.math; exports java.nio.charset; exports java.security; exports java.sql; exports java.util; exports java.util.concurrent; exports java.util.concurrent.atomic; exports java.util.function; exports java.util.logging; exports java.util.stream; exports javax.annotation.processing; // TODO(goktug): Provide a public API for array stamping and stop exporting this. exports javaemul.internal; }
google/j2cl
jre/java/module-info.java
213,368
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package docking; import java.awt.*; import java.awt.datatransfer.*; import java.awt.dnd.DnDConstants; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.*; import java.util.List; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.tree.TreePath; import docking.widgets.label.GHtmlLabel; import docking.widgets.tree.*; import docking.widgets.tree.support.GTreeDragNDropHandler; import generic.theme.GIcon; import ghidra.util.*; import ghidra.util.exception.MultipleCauses; import ghidra.util.html.HTMLElement; import util.CollectionUtils; public class ErrLogExpandableDialog extends AbstractErrDialog { public static Icon IMG_REPORT = new GIcon("icon.dialog.error.expandable.report"); public static Icon IMG_EXCEPTION = new GIcon("icon.dialog.error.expandable.exception"); public static Icon IMG_FRAME_ELEMENT = new GIcon("icon.dialog.error.expandable.frame"); public static Icon IMG_STACK = new GIcon("icon.dialog.error.expandable.stack"); public static Icon IMG_CAUSE = new GIcon("icon.dialog.error.expandable.cause"); private static final String SEND = "Send Report..."; private static final String DETAIL = "Details >>>"; private static final String CLOSE = "<<< Details"; /** tracks 'details panel' open state across invocations */ private static boolean showingDetails = false; protected ReportRootNode root; protected GTree tree; private List<Throwable> errors = new ArrayList<>(); private String baseTitle; /** This spacer addresses the optical impression that the message panel changes size when showing details */ protected Component horizontalSpacer; protected JButton detailButton; protected JButton sendButton; protected JPopupMenu popup; protected ErrLogExpandableDialog(String title, String msg, Throwable throwable) { super(title); baseTitle = title; errors.add(throwable); popup = new JPopupMenu(); JMenuItem menuCopy = new JMenuItem("Copy"); menuCopy.setActionCommand((String) TransferHandler.getCopyAction().getValue(Action.NAME)); menuCopy.addActionListener(new TransferActionListener()); menuCopy.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_C, DockingUtils.CONTROL_KEY_MODIFIER_MASK)); popup.add(menuCopy); JPanel workPanel = new JPanel(new BorderLayout()); JPanel msgPanel = new JPanel(); msgPanel.setLayout(new BorderLayout(16, 16)); msgPanel.setBorder(new EmptyBorder(16, 16, 16, 16)); { JLabel msgText = new GHtmlLabel(getHTML(msg, CollectionUtils.asSet(throwable))) { @Override public Dimension getPreferredSize() { // rendering HTML the label can expand larger than the screen; keep it reasonable Dimension size = super.getPreferredSize(); size.width = 300; return size; } }; msgText.setIcon(UIManager.getIcon("OptionPane.errorIcon")); msgPanel.add(msgText, BorderLayout.CENTER); Box buttonBox = Box.createVerticalBox(); { sendButton = new JButton(SEND); sendButton.addActionListener(e -> sendCallback()); sendButton.setMaximumSize( new Dimension(Short.MAX_VALUE, sendButton.getPreferredSize().height)); if (ErrLogDialog.getErrorReporter() != null) { buttonBox.add(sendButton); buttonBox.add(Box.createVerticalStrut(16)); } detailButton = new JButton(showingDetails ? CLOSE : DETAIL); detailButton.addActionListener(e -> detailCallback()); detailButton.setMaximumSize( new Dimension(Short.MAX_VALUE, detailButton.getPreferredSize().height)); buttonBox.add(detailButton); } msgPanel.add(buttonBox, BorderLayout.EAST); horizontalSpacer = Box.createVerticalStrut(10); horizontalSpacer.setVisible(showingDetails); msgPanel.add(horizontalSpacer, BorderLayout.SOUTH); } workPanel.add(msgPanel, BorderLayout.NORTH); Box workBox = Box.createVerticalBox(); { root = new ReportRootNode(getTitle(), CollectionUtils.asSet(throwable)); tree = new GTree(root) { @Override public Dimension getPreferredSize() { Dimension dim = super.getPreferredSize(); dim.height = 400; dim.width = 800; // trial and error? return dim; } }; for (GTreeNode node : CollectionUtils.asIterable(root.iterator(true))) { if (node instanceof ReportExceptionNode) { tree.expandTree(node); } } tree.setSelectedNode(root.getChild(0)); tree.setVisible(showingDetails); ExcTreeTransferHandler handler = new ExcTreeTransferHandler(root); tree.setDragNDropHandler(handler); tree.setTransferHandler(handler); ActionMap map = tree.getActionMap(); map.put(TransferHandler.getCopyAction().getValue(Action.NAME), TransferHandler.getCopyAction()); tree.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { maybeShowPopup(e); } @Override public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } private void maybeShowPopup(MouseEvent e) { if (e.isPopupTrigger()) { popup.show(e.getComponent(), e.getX(), e.getY()); } } }); workBox.add(tree); } workPanel.add(workBox, BorderLayout.CENTER); repack(); addWorkPanel(workPanel); addDismissButton(); } private String getHTML(String msg, Collection<Throwable> report) { // // Usage question: The content herein will be escaped unless you call addHTMLContenet(). // Further, clients can provide messages that contain HTML. Is there a // use case where we want to show escaped HTML content? // // For now, I will assume no such use case exists, and allow HTML to go // through. // // If no such use case exists, then we should update HTMLElement to // not escape HTML. If it does exist, then we should put the onus on // the client. // HTMLElement html = new HTMLElement("html"); HTMLElement body = html.addElement("body"); if (msg != null) { if (msg.startsWith(HTMLUtilities.HTML)) { // already HTML from the user body.addHTMLContent(msg); } else { String withBRs = addBR(msg); body./*addElement("h3").*/addHTMLContent(withBRs); } } for (Throwable t : report) { String tMsg = getMessage(t); if (SystemUtilities.isEqual(msg, tMsg)) { // Don't put the same message on twice. Some clients call this dialog with // the message as simply Throwable.getMessage(). continue; } String htmlTMsg = addBR(tMsg); body.addElement("p").addHTMLContent(htmlTMsg); } return html.toString(); } private String addBR(String text) { String withBRs = HTMLUtilities.lineWrapWithHTMLLineBreaks(text, 0); return withBRs; } private String getMessage(Throwable t) { String message = t.getMessage(); if (message != null) { return message; } return t.getClass().getSimpleName(); } private void detailCallback() { showingDetails = !showingDetails; tree.setVisible(showingDetails); horizontalSpacer.setVisible(showingDetails); detailButton.setText(showingDetails ? CLOSE : DETAIL); repack(); } private void sendCallback() { String details = root.collectReportText(null, 0).trim(); String title = getTitle(); close(); ErrLogDialog.getErrorReporter().report(rootPanel, title, details); } @Override public Dimension getPreferredSize() { Dimension dim = super.getPreferredSize(); dim.width = 600; return dim; } @Override public void addException(String message, Throwable t) { int n = errors.size(); if (n > MAX_EXCEPTIONS) { return; } errors.add(t); root.addNode(new ReportExceptionNode(t)); updateTitle(); // signal the new error } @Override int getExceptionCount() { return root.getChildCount(); } @Override String getBaseTitle() { return baseTitle; } @Override public String getMessage() { return root.getReportText(); } static interface NodeWithText { public String getReportText(); public String collectReportText(Collection<? extends GTreeNode> included, int indent); public boolean doesIndent(); public static class Util { public static final String INDENTATION = " "; public static String collectReportText(GTreeNode cur, Collection<? extends GTreeNode> included, int indent) { StringBuilder b = new StringBuilder(); if (cur instanceof NodeWithText) { NodeWithText nwt = (NodeWithText) cur; String text = nwt.getReportText(); if (text != null) { b.append('\n'); for (int i = 0; i < indent; i++) { b.append(INDENTATION); } b.append(nwt.getReportText()); } if (nwt.doesIndent()) { indent += 1; } } boolean doAll = (included == null || !containsAny(included, cur.getChildren())); for (GTreeNode node : cur.getChildren()) { if (node instanceof NodeWithText && (doAll || included.contains(node))) { NodeWithText nwt = (NodeWithText) node; b.append(nwt.collectReportText(included, indent)); } } return b.toString(); } public static boolean containsAny(Collection<? extends GTreeNode> included, Collection<GTreeNode> allChildren) { Set<GTreeNode> res = new HashSet<>(); res.addAll(included); res.retainAll(allChildren); return !res.isEmpty(); } } } static class ReportRootNode extends GTreeNode implements NodeWithText { protected Collection<? extends Throwable> report; protected String title; protected boolean loaded = false; public ReportRootNode(String title, Collection<? extends Throwable> report) { this.title = title; this.report = report; for (Throwable exc : report) { addNode(new ReportExceptionNode(exc)); } } @Override public String getName() { return title; } @Override public Icon getIcon(boolean expanded) { return IMG_REPORT; } @Override public String getToolTip() { return "List of exceptions that occurred during relocation"; } @Override public boolean isLeaf() { return false; } @Override public String getReportText() { return "Error Report: " + title + "\n"; } @Override public String collectReportText(Collection<? extends GTreeNode> included, int indent) { return Util.collectReportText(this, included, indent); } @Override public boolean doesIndent() { return false; } } static class ReportExceptionNode extends GTreeLazyNode implements NodeWithText { protected Throwable exc; protected boolean loaded = false; public ReportExceptionNode(Throwable cause) { this.exc = cause; } @Override public String getName() { return getPrefix() + ": " + exc.toString(); } @Override protected List<GTreeNode> generateChildren() { List<GTreeNode> list = new ArrayList<>(); list.add(new ReportStackTraceNode(exc)); Throwable c = exc.getCause(); if (c != null) { if (c instanceof MultipleCauses) { for (Throwable t : ((MultipleCauses) c).getCauses()) { list.add(new ReportExceptionNode(t)); } } else { list.add(new ReportCauseNode(c)); } } return list; } @Override public Icon getIcon(boolean expanded) { return IMG_EXCEPTION; } @Override public String getToolTip() { return "An exception occurred"; } @Override public boolean isLeaf() { return false; } protected String getPrefix() { return "Exception"; } @Override public String getReportText() { return getName(); } @Override public String collectReportText(Collection<? extends GTreeNode> included, int indent) { return Util.collectReportText(this, included, indent); } @Override public boolean doesIndent() { return true; } } static class ReportStackTraceNode extends GTreeLazyNode implements NodeWithText { protected Throwable exc; protected boolean loaded = false; public ReportStackTraceNode(Throwable cause) { this.exc = cause; } @Override public Icon getIcon(boolean expanded) { return IMG_STACK; } @Override protected List<GTreeNode> generateChildren() { List<GTreeNode> list = new ArrayList<>(); for (StackTraceElement te : exc.getStackTrace()) { list.add(new ReportStackFrameNode(te)); } return list; } @Override public String getName() { return "Stack Trace"; } @Override public String getToolTip() { return "Stack Trace for " + exc.toString(); } @Override public boolean isLeaf() { return false; } @Override public String getReportText() { return null; } @Override public String collectReportText(Collection<? extends GTreeNode> included, int indent) { return Util.collectReportText(this, included, indent); } @Override public boolean doesIndent() { return false; } } static class ReportCauseNode extends ReportExceptionNode { public ReportCauseNode(Throwable cause) { super(cause); } @Override public Icon getIcon(boolean expanded) { return IMG_CAUSE; } @Override public String getToolTip() { return "The cause of the above exception"; } @Override public String getPrefix() { return "Caused by"; } } static class ReportStackFrameNode extends GTreeNode implements NodeWithText { private StackTraceElement te; public ReportStackFrameNode(StackTraceElement te) { this.te = te; } @Override public String getName() { return "at " + te.toString(); } @Override public Icon getIcon(boolean expanded) { return IMG_FRAME_ELEMENT; } @Override public String getToolTip() { return "Stack trace element"; } @Override public boolean isLeaf() { return true; } @Override public String getReportText() { return getName(); } @Override public String collectReportText(Collection<? extends GTreeNode> included, int indent) { return Util.collectReportText(this, included, indent); } @Override public boolean doesIndent() { return false; } } private static class ExcTreeTransferHandler extends TransferHandler implements GTreeDragNDropHandler { protected ReportRootNode root; public ExcTreeTransferHandler(ReportRootNode root) { this.root = root; } @Override public DataFlavor[] getSupportedDataFlavors(List<GTreeNode> transferNodes) { return new DataFlavor[] { DataFlavor.stringFlavor }; } @Override protected Transferable createTransferable(JComponent c) { ArrayList<GTreeNode> nodes = new ArrayList<>(); for (TreePath path : ((JTree) c).getSelectionPaths()) { nodes.add((GTreeNode) path.getLastPathComponent()); } try { return new StringSelection( (String) getTransferData(nodes, DataFlavor.stringFlavor)); } catch (UnsupportedFlavorException e) { Msg.debug(this, e.getMessage(), e); } return null; } @Override public Object getTransferData(List<GTreeNode> transferNodes, DataFlavor flavor) throws UnsupportedFlavorException { if (flavor != DataFlavor.stringFlavor) { throw new UnsupportedFlavorException(flavor); } if (transferNodes.isEmpty()) { return null; } if (transferNodes.size() == 1) { GTreeNode node = transferNodes.get(0); if (node instanceof NodeWithText) { return ((NodeWithText) node).collectReportText(transferNodes, 0).trim(); } return null; } return root.collectReportText(transferNodes, 0).trim(); } @Override public boolean isStartDragOk(List<GTreeNode> dragUserData, int dragAction) { for (GTreeNode node : dragUserData) { if (node instanceof NodeWithText) { return true; } } return false; } @Override public int getSupportedDragActions() { return DnDConstants.ACTION_COPY; } @Override public int getSourceActions(JComponent c) { return COPY; } @Override public boolean isDropSiteOk(GTreeNode destUserData, DataFlavor[] flavors, int dropAction) { return false; } @Override public void drop(GTreeNode destUserData, Transferable transferable, int dropAction) { throw new UnsupportedOperationException(); } } } class TransferActionListener implements ActionListener, PropertyChangeListener { private JComponent focusOwner = null; public TransferActionListener() { KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); manager.addPropertyChangeListener("permanentFocusOwner", this); } @Override public void propertyChange(PropertyChangeEvent e) { Object o = e.getNewValue(); if (o instanceof JComponent) { focusOwner = (JComponent) o; } else { focusOwner = null; } } @Override public void actionPerformed(ActionEvent e) { if (focusOwner == null) { return; } String action = e.getActionCommand(); Action a = focusOwner.getActionMap().get(action); if (a != null) { a.actionPerformed(new ActionEvent(focusOwner, ActionEvent.ACTION_PERFORMED, null)); } } }
NationalSecurityAgency/ghidra
Ghidra/Framework/Docking/src/main/java/docking/ErrLogExpandableDialog.java
213,369
/* * Copyright (C) 2020 Graylog, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. */ package org.graylog.security.certutil; import jakarta.inject.Inject; import jakarta.inject.Named; import jakarta.inject.Singleton; import org.glassfish.jersey.media.multipart.BodyPart; import org.glassfish.jersey.media.multipart.FormDataBodyPart; import org.graylog.security.certutil.ca.CAKeyPair; import org.graylog.security.certutil.ca.PemCaReader; import org.graylog.security.certutil.ca.exceptions.CACreationException; import org.graylog.security.certutil.ca.exceptions.KeyStoreStorageException; import org.graylog.security.certutil.keystore.storage.KeystoreFileStorage; import org.graylog.security.certutil.keystore.storage.KeystoreMongoStorage; import org.graylog.security.certutil.keystore.storage.location.KeystoreMongoLocation; import org.graylog2.Configuration; import org.graylog2.bootstrap.preflight.web.resources.model.CA; import org.graylog2.bootstrap.preflight.web.resources.model.CAType; import org.graylog2.cluster.certificates.CertificatesService; import org.graylog2.events.ClusterEventBus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.time.Duration; import java.util.List; import java.util.Optional; import static org.graylog.security.certutil.CertConstants.CA_KEY_ALIAS; import static org.graylog.security.certutil.CertConstants.PKCS12; @Singleton public class CaServiceImpl implements CaService { private static final Logger LOG = LoggerFactory.getLogger(CaServiceImpl.class); private final KeystoreMongoStorage mongoKeystore; private final KeystoreFileStorage fileKeystore; private final PemCaReader pemCaReader; private final CaConfiguration configuration; private final CertificatesService certificatesService; private final String passwordSecret; private final ClusterEventBus eventBus; @Inject public CaServiceImpl(KeystoreMongoStorage keystoreMongoStorage, KeystoreFileStorage keystoreFileStorage, final Configuration configuration, final PemCaReader pemCaReader, final CertificatesService certificatesService, final @Named("password_secret") String passwordSecret, ClusterEventBus eventBus) { this.mongoKeystore = keystoreMongoStorage; this.fileKeystore = keystoreFileStorage; this.pemCaReader = pemCaReader; this.configuration = configuration; this.certificatesService = certificatesService; this.passwordSecret = configuration.getCaPassword() != null ? configuration.getCaPassword() : passwordSecret; this.eventBus = eventBus; } @Override public CA get() throws KeyStoreStorageException { if (configuration.configuredCaExists()) { return new CA("local CA", CAType.LOCAL); } else { var keystore = mongoKeystore.readKeyStore(KeystoreMongoLocation.certificateAuthority(), passwordSecret.toCharArray()); return keystore.map(c -> new CA(KeystoreMongoLocation.CA_KEYSTORE_ID, CAType.GENERATED)).orElse(null); } } @Override public CA create(final String organization, final Integer daysValid, char[] password) throws CACreationException, KeyStoreStorageException, KeyStoreException { final Duration certificateValidity = Duration.ofDays(daysValid == null || daysValid == 0 ? DEFAULT_VALIDITY : daysValid); KeyStore keyStore = CAKeyPair.create(organization, passwordSecret.toCharArray(), certificateValidity).toKeyStore(); mongoKeystore.writeKeyStore(KeystoreMongoLocation.certificateAuthority(), keyStore, passwordSecret.toCharArray(), password); LOG.debug("Generated a new CA."); triggerCaChangedEvent(); return get(); } @Override public void upload(@Nullable String password, List<FormDataBodyPart> parts) throws CACreationException { final var passwordCharArray = password == null ? null : password.toCharArray(); // TODO: if the upload consists of more than one file, handle accordingly // or: decide that it's always only one file containing all certificates try { KeyStore keyStore = KeyStore.getInstance(PKCS12, "BC"); keyStore.load(null, null); for (BodyPart part : parts) { InputStream is = part.getEntityAs(InputStream.class); byte[] bytes = is.readAllBytes(); String pem = new String(bytes, StandardCharsets.UTF_8); // Test, if upload is PEM file, must contain at least a certificate if (pem.contains("-----BEGIN CERTIFICATE")) { var ca = pemCaReader.readCA(pem, password); keyStore.setKeyEntry(CA_KEY_ALIAS, ca.privateKey(), passwordCharArray, ca.certificates().toArray(new Certificate[0])); } else { ByteArrayInputStream bais = new ByteArrayInputStream(bytes); keyStore.load(bais, passwordCharArray); } } mongoKeystore.writeKeyStore(KeystoreMongoLocation.certificateAuthority(), keyStore, passwordCharArray, passwordSecret.toCharArray()); triggerCaChangedEvent(); } catch (IOException | KeyStoreStorageException | NoSuchAlgorithmException | CertificateException | KeyStoreException | NoSuchProviderException ex) { LOG.error("Could not write CA: " + ex.getMessage(), ex); throw new CACreationException("Could not write CA: " + ex.getMessage(), ex); } } @Override public void startOver() { certificatesService.removeCert(KeystoreMongoLocation.certificateAuthority()); } private void triggerCaChangedEvent() { eventBus.post(new CertificateAuthorityChangedEvent()); } @Override public Optional<KeyStore> loadKeyStore() throws KeyStoreStorageException { if (configuration.configuredCaExists()) { return fileKeystore.readKeyStore(configuration.getCaKeystoreFile(), configuration.getCaPassword().toCharArray()); } else { return mongoKeystore.readKeyStore(KeystoreMongoLocation.certificateAuthority(), passwordSecret.toCharArray()); } } }
Graylog2/graylog2-server
graylog2-server/src/main/java/org/graylog/security/certutil/CaServiceImpl.java
213,370
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.feature.vt.gui.duallisting; import ghidra.app.util.viewer.listingpanel.ListingCodeComparisonPanel; import ghidra.app.util.viewer.listingpanel.ListingPanel; import ghidra.feature.vt.api.main.*; import ghidra.feature.vt.api.markuptype.VTMarkupType; import ghidra.feature.vt.gui.plugin.VTController; import ghidra.feature.vt.gui.task.ApplyMarkupAtDestinationAddressTask; import ghidra.program.model.address.Address; import ghidra.program.util.ProgramLocation; import ghidra.util.Msg; import ghidra.util.SystemUtilities; import java.awt.Point; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.dnd.*; import java.util.ArrayList; import docking.dnd.*; public class VTDualListingDragNDropHandler implements Draggable, Droppable { private final int SOURCE = 0; // left side private final int DESTINATION = 1; // right side private ListingPanel[] listingPanels = new ListingPanel[2]; private VTController controller; ListingCodeComparisonPanel dualListingPanel; // Drag-N-Drop private DragSource dragSource; private DragGestureAdapter dragGestureAdapter; private DragSrcAdapter dragSourceAdapter; private int dragAction = DnDConstants.ACTION_MOVE; private DropTarget dropTarget; private DropTgtAdapter dropTargetAdapter; private DataFlavor[] acceptableFlavors; // data flavors that are valid. public VTDualListingDragNDropHandler(VTController controller, ListingCodeComparisonPanel dualListingPanel) { this.controller = controller; this.dualListingPanel = dualListingPanel; listingPanels[SOURCE] = dualListingPanel.getLeftPanel(); listingPanels[DESTINATION] = dualListingPanel.getRightPanel(); setUpDragDrop(); } private void setUpDragDrop() { setUpDrop(); // set up the component area as a drag site that provides mark-up items. dragSource = DragSource.getDefaultDragSource(); dragGestureAdapter = new DragGestureAdapter(this); dragSourceAdapter = new DragSrcAdapter(this); dragSource.createDefaultDragGestureRecognizer(listingPanels[SOURCE].getFieldPanel(), dragAction, dragGestureAdapter); } private void setUpDrop() { setAcceptableFlavors(); // set up the destination fieldPanel as a drop target that accepts mark-up items. dropTargetAdapter = new DropTgtAdapter(this, DnDConstants.ACTION_COPY_OR_MOVE, acceptableFlavors); dropTarget = new DropTarget(listingPanels[DESTINATION].getFieldPanel(), DnDConstants.ACTION_COPY_OR_MOVE, dropTargetAdapter, true); dropTarget.setActive(true); } private void setAcceptableFlavors() { acceptableFlavors = new DataFlavor[] { VTMarkupItemTransferable.localMarkupItemFlavor }; } @Override public int getDragAction() { return dragAction; } @Override public DragSourceListener getDragSourceListener() { return dragSourceAdapter; } @Override public boolean isStartDragOk(DragGestureEvent e) { if (!listingPanels[SOURCE].isStartDragOk()) { return false; } Point p = e.getDragOrigin(); ProgramLocation programLocation = listingPanels[SOURCE].getProgramLocation(p); VTMarkupItem markupItem = controller.getCurrentMarkupForLocation(programLocation, dualListingPanel.getLeftProgram()); if (markupItem == null) { return false; } if (markupItem.canApply()) { return true; } VTMarkupItemDestinationAddressEditStatus status = markupItem.getDestinationAddressEditStatus(); return status == VTMarkupItemDestinationAddressEditStatus.EDITABLE; } @Override public void dragCanceled(DragSourceDropEvent event) { // nothing to do } @Override public Transferable getTransferable(Point p) { if (!listingPanels[SOURCE].contains(p)) { return null; } ProgramLocation programLocation = listingPanels[SOURCE].getProgramLocation(p); VTMarkupItem markupItem = controller.getCurrentMarkupForLocation(programLocation, dualListingPanel.getLeftProgram()); if (markupItem == null) { return null; } return new VTMarkupItemTransferable(markupItem); } @Override public void dragUnderFeedback(boolean ok, DropTargetDragEvent e) { // nothing to do } @Override public void undoDragUnderFeedback() { // nothing to do } @Override public boolean isDropOk(DropTargetDragEvent e) { return true; } @Override public void add(Object obj, DropTargetDropEvent event, DataFlavor f) { VTMarkupItem markupItem = (VTMarkupItem) obj; VTMarkupType markupType = markupItem.getMarkupType(); Point p = event.getLocation(); ProgramLocation loc = listingPanels[DESTINATION].getProgramLocation(p); Address newDestinationAddress = markupType.getAddress(loc, dualListingPanel.getRightProgram()); if (newDestinationAddress == null) { Msg.showInfo(getClass(), dualListingPanel, "Invalid Drop Location", markupType.getDisplayName() + " was not dropped at a valid location."); return; } if ((markupItem.getStatus() == VTMarkupItemStatus.SAME) && (SystemUtilities.isEqual(markupItem.getDestinationAddress(), newDestinationAddress))) { // Dropped at expected address and already the same there. Msg.showInfo(getClass(), dualListingPanel, "Already The Same", markupType.getDisplayName() + " was dropped at its expected\ndestination where the value is already the same."); return; } ArrayList<VTMarkupItem> arrayList = new ArrayList<VTMarkupItem>(); arrayList.add(markupItem); // Use the following if you only want to set the address. // SetMarkupItemDestinationAddressTask task = // new SetMarkupItemDestinationAddressTask(controller.getSession(), arrayList, // newDestinationAddress); // Use the following if you want to set the address and apply the markup item using the default action. ApplyMarkupAtDestinationAddressTask task = new ApplyMarkupAtDestinationAddressTask(controller.getSession(), arrayList, newDestinationAddress, controller.getOptions()); controller.runVTTask(task); } @Override public void move() { // nothing to do } }
NationalSecurityAgency/ghidra
Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/gui/duallisting/VTDualListingDragNDropHandler.java
213,371
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.monitor.query; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.policy.HttpLogOptions; import com.azure.core.http.rest.Response; import com.azure.core.util.BinaryData; import com.azure.core.util.Context; import com.azure.core.util.HttpClientOptions; import com.azure.identity.DefaultAzureCredential; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.monitor.query.models.AggregationType; import com.azure.monitor.query.models.LogsBatchQuery; import com.azure.monitor.query.models.LogsBatchQueryResult; import com.azure.monitor.query.models.LogsBatchQueryResultCollection; import com.azure.monitor.query.models.LogsQueryOptions; import com.azure.monitor.query.models.LogsQueryResult; import com.azure.monitor.query.models.LogsQueryResultStatus; import com.azure.monitor.query.models.LogsTableRow; import com.azure.monitor.query.models.MetricResult; import com.azure.monitor.query.models.MetricValue; import com.azure.monitor.query.models.MetricsQueryResourcesResult; import com.azure.monitor.query.models.MetricsQueryOptions; import com.azure.monitor.query.models.MetricsQueryResult; import com.azure.monitor.query.models.QueryTimeInterval; import com.azure.monitor.query.models.TimeSeriesElement; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.time.Duration; import java.util.Arrays; import java.util.List; /** * Code samples for the README.md */ public class ReadmeSamples { /** * Sample for creating sync and async clients for querying logs. */ public void createLogsClients() { // BEGIN: readme-sample-createLogsQueryClient LogsQueryClient logsQueryClient = new LogsQueryClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); // END: readme-sample-createLogsQueryClient // BEGIN: readme-sample-createLogsQueryAsyncClient LogsQueryAsyncClient logsQueryAsyncClient = new LogsQueryClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .buildAsyncClient(); // END: readme-sample-createLogsQueryAsyncClient } /** * Sample for creating sync and async clients for querying metrics. */ public void createMetricsQueryClients() { // BEGIN: readme-sample-createMetricsQueryClient MetricsQueryClient metricsQueryClient = new MetricsQueryClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); // END: readme-sample-createMetricsQueryClient // BEGIN: readme-sample-createMetricsQueryAsyncClient MetricsQueryAsyncClient metricsQueryAsyncClient = new MetricsQueryClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .buildAsyncClient(); // END: readme-sample-createMetricsQueryAsyncClient } public void createMetricsClients() { // BEGIN: readme-sample-createMetricsClient MetricsClient metricsClient = new MetricsClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .endpoint("{endpoint}") .buildClient(); // END: readme-sample-createMetricsClient // BEGIN: readme-sample-createMetricsAsyncClient MetricsAsyncClient metricsAsyncClient = new MetricsClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .endpoint("{endpoint}") .buildAsyncClient(); // END: readme-sample-createMetricsAsyncClient } /** * Sample to query logs using a single Kusto query. */ public void queryLogs() { // BEGIN: readme-sample-logsquery LogsQueryClient logsQueryClient = new LogsQueryClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); LogsQueryResult queryResults = logsQueryClient.queryWorkspace("{workspace-id}", "{kusto-query}", new QueryTimeInterval(Duration.ofDays(2))); for (LogsTableRow row : queryResults.getTable().getRows()) { System.out.println(row.getColumnValue("OperationName") + " " + row.getColumnValue("ResourceGroup")); } // END: readme-sample-logsquery } /** * Sample to query logs from a resource using a single Kusto query. */ public void queryLogsByResourceId() { // BEGIN: readme-sample-logsquerybyresourceid LogsQueryClient logsQueryClient = new LogsQueryClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); LogsQueryResult queryResults = logsQueryClient.queryResource("{resource-id}", "{kusto-query}", new QueryTimeInterval(Duration.ofDays(2))); for (LogsTableRow row : queryResults.getTable().getRows()) { System.out.println(row.getColumnValue("OperationName") + " " + row.getColumnValue("ResourceGroup")); } // END: readme-sample-logsquerybyresourceid } /** * A custom model type to map logs query result to an object. */ // BEGIN: readme-sample-custommodel public class CustomLogModel { private String resourceGroup; private String operationName; public String getResourceGroup() { return resourceGroup; } public String getOperationName() { return operationName; } } // END: readme-sample-custommodel /** * Sample to query logs and convert the response to a strongly-typed list of objects. */ public void queryLogsAsModel() { // BEGIN: readme-sample-logsquerycustommodel LogsQueryClient logsQueryClient = new LogsQueryClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); List<CustomLogModel> customLogModels = logsQueryClient.queryWorkspace("{workspace-id}", "{kusto-query}", new QueryTimeInterval(Duration.ofDays(2)), CustomLogModel.class); for (CustomLogModel customLogModel : customLogModels) { System.out.println(customLogModel.getOperationName() + " " + customLogModel.getResourceGroup()); } // END: readme-sample-logsquerycustommodel } /** * Sample to execute a batch of logs queries. */ public void queryBatch() { // BEGIN: readme-sample-batchlogsquery LogsQueryClient logsQueryClient = new LogsQueryClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); LogsBatchQuery logsBatchQuery = new LogsBatchQuery(); String query1 = logsBatchQuery.addWorkspaceQuery("{workspace-id}", "{query-1}", new QueryTimeInterval(Duration.ofDays(2))); String query2 = logsBatchQuery.addWorkspaceQuery("{workspace-id}", "{query-2}", new QueryTimeInterval(Duration.ofDays(30))); String query3 = logsBatchQuery.addWorkspaceQuery("{workspace-id}", "{query-3}", new QueryTimeInterval(Duration.ofDays(10))); LogsBatchQueryResultCollection batchResults = logsQueryClient .queryBatchWithResponse(logsBatchQuery, Context.NONE).getValue(); LogsBatchQueryResult query1Result = batchResults.getResult(query1); for (LogsTableRow row : query1Result.getTable().getRows()) { System.out.println(row.getColumnValue("OperationName") + " " + row.getColumnValue("ResourceGroup")); } List<CustomLogModel> customLogModels = batchResults.getResult(query2, CustomLogModel.class); for (CustomLogModel customLogModel : customLogModels) { System.out.println(customLogModel.getOperationName() + " " + customLogModel.getResourceGroup()); } LogsBatchQueryResult query3Result = batchResults.getResult(query3); if (query3Result.getQueryResultStatus() == LogsQueryResultStatus.FAILURE) { System.out.println(query3Result.getError().getMessage()); } // END: readme-sample-batchlogsquery } /** * Sample to demonstrate executing an advanced Kusto query for logs that requires a long time to complete and * requires extending server timeout. */ public void getLogsWithServerTimeout() { // BEGIN: readme-sample-logsquerytimeout LogsQueryClient logsQueryClient = new LogsQueryClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); // set request options: server timeout LogsQueryOptions options = new LogsQueryOptions() .setServerTimeout(Duration.ofMinutes(10)); Response<LogsQueryResult> response = logsQueryClient.queryWorkspaceWithResponse("{workspace-id}", "{kusto-query}", new QueryTimeInterval(Duration.ofDays(2)), options, Context.NONE); // END: readme-sample-logsquerytimeout } /** * Sample to demonstrate querying multiple workspaces. */ public void getLogsQueryFromMultipleWorkspaces() { // BEGIN: readme-sample-logsquerymultipleworkspaces LogsQueryClient logsQueryClient = new LogsQueryClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); Response<LogsQueryResult> response = logsQueryClient.queryWorkspaceWithResponse("{workspace-id}", "{kusto-query}", new QueryTimeInterval(Duration.ofDays(2)), new LogsQueryOptions() .setAdditionalWorkspaces(Arrays.asList("{additional-workspace-identifiers}")), Context.NONE); LogsQueryResult result = response.getValue(); // END: readme-sample-logsquerymultipleworkspaces } /** * Sample to demonstrate querying Azure Monitor for metrics. */ public void getMetrics() { // BEGIN: readme-sample-metricsquery MetricsQueryClient metricsQueryClient = new MetricsQueryClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); MetricsQueryResult metricsQueryResult = metricsQueryClient.queryResource("{resource-uri}", Arrays.asList("SuccessfulCalls", "TotalCalls")); for (MetricResult metric : metricsQueryResult.getMetrics()) { System.out.println("Metric name " + metric.getMetricName()); for (TimeSeriesElement timeSeriesElement : metric.getTimeSeries()) { System.out.println("Dimensions " + timeSeriesElement.getMetadata()); for (MetricValue metricValue : timeSeriesElement.getValues()) { System.out.println(metricValue.getTimeStamp() + " " + metricValue.getTotal()); } } } // END: readme-sample-metricsquery } /** * Sample to demonstrate querying Azure Monitor for metrics with advanced options. */ public void getMetricsWithOptions() { // BEGIN: readme-sample-metricsqueryaggregation MetricsQueryClient metricsQueryClient = new MetricsQueryClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); Response<MetricsQueryResult> metricsResponse = metricsQueryClient .queryResourceWithResponse("{resource-id}", Arrays.asList("SuccessfulCalls", "TotalCalls"), new MetricsQueryOptions() .setGranularity(Duration.ofHours(1)) .setAggregations(Arrays.asList(AggregationType.AVERAGE, AggregationType.COUNT)), Context.NONE); MetricsQueryResult metricsQueryResult = metricsResponse.getValue(); for (MetricResult metric : metricsQueryResult.getMetrics()) { System.out.println("Metric name " + metric.getMetricName()); for (TimeSeriesElement timeSeriesElement : metric.getTimeSeries()) { System.out.println("Dimensions " + timeSeriesElement.getMetadata()); for (MetricValue metricValue : timeSeriesElement.getValues()) { System.out.println(metricValue.getTimeStamp() + " " + metricValue.getTotal()); } } } // END: readme-sample-metricsqueryaggregation } /** * Enable HTTP request and response logging. */ public void tsgEnableHttpLogging() { DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); // BEGIN: readme-sample-enablehttplogging LogsQueryClient logsQueryClient = new LogsQueryClientBuilder() .credential(credential) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .buildClient(); // or MetricsQueryClient metricsQueryClient = new MetricsQueryClientBuilder() .credential(credential) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .buildClient(); // END: readme-sample-enablehttplogging } /** * Sample to show how to set response timeout for http client. */ public void tsgHttpResponseTimeout() { DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); // BEGIN: readme-sample-responsetimeout LogsQueryClient client = new LogsQueryClientBuilder() .credential(credential) .clientOptions(new HttpClientOptions().setResponseTimeout(Duration.ofSeconds(120))) .buildClient(); // END: readme-sample-responsetimeout } /** * Sample to show how to set server timeout. */ public void tsgSetServerTimeout() { DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); // BEGIN: readme-sample-servertimeout LogsQueryClient client = new LogsQueryClientBuilder() .credential(credential) .buildClient(); client.queryWorkspaceWithResponse("{workspaceId}", "{kusto-query-string}", QueryTimeInterval.LAST_DAY, new LogsQueryOptions().setServerTimeout(Duration.ofMinutes(10)), Context.NONE); // END: readme-sample-servertimeout } /** * Sample to show how to allow partial errors for logs queries. */ public void tsgAllowPartialErrors() { DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); LogsQueryClient client = new LogsQueryClientBuilder() .credential(credential) .buildClient(); // BEGIN: readme-sample-allowpartialerrors client.queryWorkspaceWithResponse("{workspaceId}", "{kusto-query-string}", QueryTimeInterval.LAST_DAY, new LogsQueryOptions().setAllowPartialErrors(true), Context.NONE); // END: readme-sample-allowpartialerrors } /** * Sample to show how to configure response timeout for OkHttp client. */ public void tsgOkHttpResponseTimeout() { DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); // BEGIN: readme-sample-okhttpresponsetimeout LogsQueryClient client = new LogsQueryClientBuilder() .credential(credential) .clientOptions(new HttpClientOptions().setResponseTimeout(Duration.ofSeconds(120))) .buildClient(); // END: readme-sample-okhttpresponsetimeout } /** * Sample to show how to request for query execution statistics and consume the response. * * @throws IOException if parsing the statistics JSON fails. */ public void includeStatistics() throws IOException { DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); // BEGIN: readme-sample-includestatistics LogsQueryClient client = new LogsQueryClientBuilder() .credential(credential) .buildClient(); LogsQueryOptions options = new LogsQueryOptions() .setIncludeStatistics(true); Response<LogsQueryResult> response = client.queryWorkspaceWithResponse("{workspace-id}", "AzureActivity | top 10 by TimeGenerated", QueryTimeInterval.LAST_1_HOUR, options, Context.NONE); LogsQueryResult result = response.getValue(); BinaryData statistics = result.getStatistics(); ObjectMapper objectMapper = new ObjectMapper(); JsonNode statisticsJson = objectMapper.readTree(statistics.toBytes()); JsonNode queryStatistics = statisticsJson.get("query"); System.out.println("Query execution time = " + queryStatistics.get("executionTime").asDouble()); // END: readme-sample-includestatistics } /** * Sample to show how to request for visualization data and consume the response. * * @throws IOException if parsing the visualization JSON fails. */ public void includeVisualization() throws IOException { DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); // BEGIN: readme-sample-includevisualization LogsQueryClient client = new LogsQueryClientBuilder() .credential(credential) .buildClient(); String visualizationQuery = "StormEvents" + "| summarize event_count = count() by State" + "| where event_count > 10" + "| project State, event_count" + "| render columnchart"; LogsQueryOptions options = new LogsQueryOptions() .setIncludeVisualization(true); Response<LogsQueryResult> response = client.queryWorkspaceWithResponse("{workspace-id}", visualizationQuery, QueryTimeInterval.LAST_7_DAYS, options, Context.NONE); LogsQueryResult result = response.getValue(); BinaryData visualization = result.getVisualization(); ObjectMapper objectMapper = new ObjectMapper(); JsonNode visualizationJson = objectMapper.readTree(visualization.toBytes()); System.out.println("Visualization graph type = " + visualizationJson.get("visualization").asText()); // END: readme-sample-includevisualization } /** * Sample to show how to create a log query client using a sovereign cloud endpoint. */ public void createLogsClientWithSovereignCloud() { // BEGIN: readme-sample-createLogsQueryClientWithSovereignCloud LogsQueryClient logsQueryClient = new LogsQueryClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .endpoint("https://api.loganalytics.azure.cn/v1") .buildClient(); // END: readme-sample-createLogsQueryClientWithSovereignCloud } /** * Sample to show how to create a metrics query client using a sovereign cloud endpoint. */ public void createMetricsClientWithSovereignCloud() { // BEGIN: readme-sample-createMetricsQueryClientWithSovereignCloud MetricsQueryClient metricsQueryClient = new MetricsQueryClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .endpoint("https://management.chinacloudapi.cn") .buildClient(); // END: readme-sample-createMetricsQueryClientWithSovereignCloud } /** * Sample to demonstrate querying Azure Monitor for metrics. */ public void getMetricsForMultipleResources() { // BEGIN: readme-sample-metricsquerymultipleresources MetricsClient metricsClient = new MetricsClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .endpoint("{endpoint}") .buildClient(); MetricsQueryResourcesResult metricsQueryResourcesResult = metricsClient.queryResources( Arrays.asList("{resourceId1}", "{resourceId2}"), Arrays.asList("{metric1}", "{metric2}"), "{metricNamespace}"); for (MetricsQueryResult metricsQueryResult : metricsQueryResourcesResult.getMetricsQueryResults()) { // Each MetricsQueryResult corresponds to one of the resourceIds in the batch request. List<MetricResult> metrics = metricsQueryResult.getMetrics(); metrics.forEach(metric -> { System.out.println(metric.getMetricName()); System.out.println(metric.getId()); System.out.println(metric.getResourceType()); System.out.println(metric.getUnit()); System.out.println(metric.getTimeSeries().size()); System.out.println(metric.getTimeSeries().get(0).getValues().size()); metric.getTimeSeries() .stream() .flatMap(ts -> ts.getValues().stream()) .forEach(mv -> System.out.println(mv.getTimeStamp().toString() + "; Count = " + mv.getCount() + "; Average = " + mv.getAverage())); }); } // END: readme-sample-metricsquerymultipleresources } }
Azure/azure-sdk-for-java
sdk/monitor/azure-monitor-query/src/samples/java/com/azure/monitor/query/ReadmeSamples.java
213,372
/* ### * IP: GHIDRA * REVIEWED: YES * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.app.plugin.core.symboltree; import ghidra.app.plugin.core.symboltree.nodes.*; import ghidra.app.util.SelectionTransferData; import ghidra.app.util.SelectionTransferable; import ghidra.program.model.address.AddressSetView; import ghidra.program.model.listing.*; import ghidra.program.model.symbol.Namespace; import ghidra.program.model.symbol.Symbol; import ghidra.util.Msg; import java.awt.datatransfer.*; import java.awt.dnd.DnDConstants; import java.io.IOException; import java.util.*; import docking.widgets.tree.GTreeNode; import docking.widgets.tree.support.GTreeDragNDropHandler; public class SymbolGTreeDragNDropHandler implements GTreeDragNDropHandler { private final SymbolTreePlugin plugin; SymbolGTreeDragNDropHandler(SymbolTreePlugin plugin) { this.plugin = plugin; } @Override public void drop(GTreeNode destinationNode, Transferable transferable, int dropAction) { if (dropAction != DnDConstants.ACTION_MOVE) { return; } if (!(destinationNode instanceof SymbolTreeNode)) { return; } SymbolTreeNode destinationSymbolNode = (SymbolTreeNode) destinationNode; Namespace namespace = destinationSymbolNode.getNamespace(); if (namespace == null) { return; } if (transferable.isDataFlavorSupported(SelectionTransferable.localProgramSelectionFlavor)) { try { Object transferData = transferable.getTransferData(SelectionTransferable.localProgramSelectionFlavor); SelectionTransferData selectionData = (SelectionTransferData) transferData; dropProgramSelection(namespace, selectionData); return; } catch (UnsupportedFlavorException e) { Msg.showError(this, plugin.getTool().getToolFrame(), "Unsupported Data Flavor", "Unable to handle dropping of given data flavor: " + e.getMessage()); } catch (IOException e) { Msg.showError(this, plugin.getTool().getToolFrame(), "Unexpected Exception", "Unable to handle dropping of given data", e); } } try { Object transferData = transferable.getTransferData(SymbolTreeDataFlavor.DATA_FLAVOR); if (transferData instanceof List<?>) { dropNodeList(namespace, transferData); return; } } catch (UnsupportedFlavorException e) { Msg.showError(this, plugin.getTool().getToolFrame(), "Unsupported Data Flavor", "Unable to handle dropping of given data flavor: " + e.getMessage()); } catch (IOException e) { Msg.showError(this, plugin.getTool().getToolFrame(), "Unexpected Exception", "Unable to handle dropping of given data", e); } } private void dropProgramSelection(Namespace namespace, SelectionTransferData selectionData) { List<Symbol> symbolsToMove = new ArrayList<Symbol>(); Program program = plugin.getProgram(); FunctionManager functionManager = program.getFunctionManager(); AddressSetView addressSet = selectionData.getAddressSet(); FunctionIterator iterator = functionManager.getFunctions(addressSet, true); for (Function function : iterator) { symbolsToMove.add(function.getSymbol()); } SymbolTreeProvider provider = plugin.getProvider(); if (provider.reparentSymbols(namespace, symbolsToMove) != symbolsToMove.size()) { plugin.getTool().setStatusInfo("Failed to move one more specified symbols"); } } private void dropNodeList(Namespace namespace, Object transferData) { @SuppressWarnings("unchecked") List<GTreeNode> nodeList = (List<GTreeNode>) transferData; List<Symbol> symbolsToMoveList = new ArrayList<Symbol>(); for (GTreeNode node : nodeList) { // we only allow dragging of SymbolNodes SymbolNode symbolNode = (SymbolNode) node; Symbol symbol = symbolNode.getSymbol(); symbolsToMoveList.add(symbol); } SymbolTreeProvider provider = plugin.getProvider(); if (provider.reparentSymbols(namespace, symbolsToMoveList) != symbolsToMoveList.size()) { plugin.getTool().setStatusInfo("Failed to move one more specified symbols"); } } @Override public int getSupportedDragActions() { return DnDConstants.ACTION_MOVE; } @Override public boolean isDropSiteOk(GTreeNode destinationUserNode, DataFlavor[] flavors, int dropAction) { if (dropAction != DnDConstants.ACTION_MOVE) { return false; } Program program = plugin.getProgram(); if (program == null || program.isClosed()) { return false; } if (!(destinationUserNode instanceof SymbolTreeNode)) { return false; } SymbolTreeNode node = (SymbolTreeNode) destinationUserNode; return node.supportsDataFlavors(flavors); } @Override public boolean isStartDragOk(List<GTreeNode> dragUserData, int dragAction) { if (dragAction != DnDConstants.ACTION_MOVE) { return false; } for (GTreeNode node : dragUserData) { SymbolTreeNode symbolNode = (SymbolTreeNode) node; DataFlavor dataFlavor = symbolNode.getNodeDataFlavor(); if (dataFlavor == null) { return false; } } return dragUserData.size() != 0; } @Override public DataFlavor[] getSupportedDataFlavors(List<GTreeNode> transferNodes) { Set<DataFlavor> flavorSet = new HashSet<DataFlavor>(); for (GTreeNode node : transferNodes) { SymbolTreeNode symbolNode = (SymbolTreeNode) node; DataFlavor flavor = symbolNode.getNodeDataFlavor(); if (flavor != null) { flavorSet.add(flavor); } } return flavorSet.toArray(new DataFlavor[flavorSet.size()]); } @Override public Object getTransferData(List<GTreeNode> transferNodes, DataFlavor flavor) throws UnsupportedFlavorException { return transferNodes; } }
NationalSecurityAgency/ghidra
Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/symboltree/SymbolGTreeDragNDropHandler.java
213,375
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.framework.main.datatree; import java.awt.datatransfer.*; import java.awt.dnd.DnDConstants; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; import docking.dnd.GenericDataFlavor; import docking.tool.ToolConstants; import docking.widgets.tree.GTreeNode; import docking.widgets.tree.support.GTreeDragNDropHandler; import ghidra.framework.main.FrontEndTool; import ghidra.util.Msg; import ghidra.util.exception.AssertException; public class DataTreeDragNDropHandler implements GTreeDragNDropHandler { private static Map<DataFlavor, DataTreeFlavorHandler> activeProjectDropFlavorHandlerMap = new HashMap<>(); public static DataFlavor localDomainFileTreeFlavor = createLocalTreeNodeFlavor(); public static DataFlavor localDomainFileFlavor = createLocalTreeFlavor(); public static DataFlavor[] allSupportedFlavors = { localDomainFileTreeFlavor, localDomainFileFlavor, DataFlavor.stringFlavor }; // create a data flavor that is an List of GTreeNodes private static DataFlavor createLocalTreeNodeFlavor() { try { return new GenericDataFlavor( DataFlavor.javaJVMLocalObjectMimeType + "; class=java.util.List", "Local list of Drag/Drop Project Domain Tree objects"); } catch (Exception e) { Msg.showError(DataTreeDragNDropHandler.class, null, null, null, e); } return null; } private static DataFlavor createLocalTreeFlavor() { try { return new GenericDataFlavor( DataFlavor.javaJVMLocalObjectMimeType + "; class=java.util.List", "Local list of Drag/Drop Project Domain objects"); } catch (Exception e) { Msg.showError(DataTreeDragNDropHandler.class, null, null, null, e); } return null; } private boolean isActiveProject; private final FrontEndTool tool; private final DataTree tree; DataTreeDragNDropHandler(FrontEndTool tool, DataTree tree, boolean isActiveProject) { this.tool = tool; this.tree = tree; this.isActiveProject = isActiveProject; } @Override public void drop(GTreeNode destination, Transferable transferable, int dropAction) { DataFlavor[] transferDataFlavors = transferable.getTransferDataFlavors(); for (DataFlavor dataFlavor : transferDataFlavors) { DataTreeFlavorHandler flavorHandler = getFlavorHandler(dataFlavor); if (flavorHandler != null && handleDrop(destination, transferable, dropAction, dataFlavor, flavorHandler)) { return; } } } private boolean handleDrop(GTreeNode destination, Transferable transferable, int dropAction, DataFlavor dataFlavor, DataTreeFlavorHandler flavorHandler) { try { Object transferData = transferable.getTransferData(dataFlavor); return flavorHandler.handle(tool, tree, destination, transferData, dropAction); } catch (UnsupportedFlavorException e) { throw new AssertException("Got unsupported flavor from using a supported flavor"); } catch (IOException e) { Msg.showError(this, null, "IO Error", "Error during drop", e); } return false; } private DataTreeFlavorHandler getFlavorHandler(DataFlavor flavor) { return activeProjectDropFlavorHandlerMap.get(flavor); } @Override public int getSupportedDragActions() { return DnDConstants.ACTION_COPY_OR_MOVE; } @Override public boolean isDropSiteOk(GTreeNode destUserData, DataFlavor[] flavors, int dropAction) { if (!isActiveProject) { return false; } if (ToolConstants.NO_ACTIVE_PROJECT.equals(destUserData.getName())) { return false; } return true; } @Override public boolean isStartDragOk(List<GTreeNode> dragUserData, int dragAction) { for (GTreeNode gTreeNode : dragUserData) { if (gTreeNode.getParent() != null) { return true; } } return false; } @Override public DataFlavor[] getSupportedDataFlavors(List<GTreeNode> transferNodes) { return allSupportedFlavors; } @Override public Object getTransferData(List<GTreeNode> transferNodes, DataFlavor flavor) throws UnsupportedFlavorException { if (flavor == localDomainFileTreeFlavor) { // this removes files that are already in the list because they are children of // folders that are in the list return removeDuplicates(transferNodes); } else if (flavor == localDomainFileFlavor) { // filter for file nodes and convert each node to its corresponding domainFile return transferNodes.stream() .filter(DomainFileNode.class::isInstance) .map(node -> ((DomainFileNode) node).getDomainFile()) .collect(Collectors.toList()); } else if (flavor.equals(DataFlavor.stringFlavor)) { // allow users to copy the names of nodes return transferNodes.stream() .map(node -> node.getName()) .collect(Collectors.joining("\n")); } throw new AssertException("Called with a flavor that we didn't say we supported"); } private List<GTreeNode> removeDuplicates(List<GTreeNode> allNodes) { List<GTreeNode> folderNodes = getDomainFolderNodes(allNodes); // if a file has a parent in the list, then it is not needed as a separate entry return allNodes.stream() .filter(node -> !isChildOfFolders(folderNodes, node)) .collect(Collectors.toList()); } private List<GTreeNode> getDomainFolderNodes(List<GTreeNode> nodeList) { List<GTreeNode> folderList = new ArrayList<>(); for (GTreeNode node : nodeList) { if (node instanceof DomainFolderNode) { folderList.add(node); } } return folderList; } private boolean isChildOfFolders(List<GTreeNode> folderNodes, GTreeNode fileNode) { GTreeNode node = fileNode.getParent(); while (node != null) { if (folderNodes.contains(node)) { return true; } node = node.getParent(); } return false; } public static void addActiveDataFlavorHandler(DataFlavor flavor, DataTreeFlavorHandler handler) { activeProjectDropFlavorHandlerMap.put(flavor, handler); } public static DataTreeFlavorHandler removeActiveDataFlavorHandler(DataFlavor flavor) { return activeProjectDropFlavorHandlerMap.remove(flavor); } public void setProjectActive(boolean b) { isActiveProject = b; } }
NationalSecurityAgency/ghidra
Ghidra/Framework/Project/src/main/java/ghidra/framework/main/datatree/DataTreeDragNDropHandler.java
213,376
package util; /************************************************************ * Copyright 2004-2005,2007-2008 Masahiko SAWAI All Rights Reserved. * Copaido de http://stackoverflow.com/questions/2120228/java-swing-font-chooser em 12/04/2014 ************************************************************/ import controlador.Editor; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Frame; import java.awt.GraphicsEnvironment; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.InputMap; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.border.Border; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import javax.swing.text.Position; /** * The <code>JFontChooser</code> class is a swing component * for font selection. * This class has <code>JFileChooser</code> like APIs. * The following code pops up a font chooser dialog. * <pre> * JFontChooser fontChooser = new JFontChooser(); * int result = fontChooser.showDialog(parent); * if (result == JFontChooser.OK_OPTION) * { * Font font = fontChooser.getSelectedFont(); * System.out.println("Selected Font : " + font); * } * <pre> **/ public class JFontChooser extends JComponent { private static final long serialVersionUID = -862298636965016712L; // class variables /** * Return value from <code>showDialog()</code>. * @see #showDialog **/ public static final int OK_OPTION = 0; /** * Return value from <code>showDialog()</code>. * @see #showDialog **/ public static final int CANCEL_OPTION = 1; /** * Return value from <code>showDialog()</code>. * @see #showDialog **/ public static final int ERROR_OPTION = -1; private static final Font DEFAULT_SELECTED_FONT = new Font("Serif", Font.PLAIN, 12); private static final Font DEFAULT_FONT = new Font("Dialog", Font.PLAIN, 10); private static final int[] FONT_STYLE_CODES = { Font.PLAIN, Font.BOLD, Font.ITALIC, Font.BOLD | Font.ITALIC }; private static final String[] DEFAULT_FONT_SIZE_STRINGS = { "8", "9", "10", "11", "12", "14", "16", "18", "20", "22", "24", "26", "28", "36", "48", "72", }; // instance variables protected int dialogResultValue = ERROR_OPTION; private String[] fontStyleNames = null; private String[] fontFamilyNames = null; private String[] fontSizeStrings = null; private JTextField fontFamilyTextField = null; private JTextField fontStyleTextField = null; private JTextField fontSizeTextField = null; private JList fontNameList = null; private JList fontStyleList = null; private JList fontSizeList = null; private JPanel fontNamePanel = null; private JPanel fontStylePanel = null; private JPanel fontSizePanel = null; private JPanel samplePanel = null; private JPanel lastPanel = null; private JTextField sampleText = null; private JTextField lastText = null; /** * Constructs a <code>JFontChooser</code> object. **/ public JFontChooser() { this(DEFAULT_FONT_SIZE_STRINGS); } /** * Constructs a <code>JFontChooser</code> object using the given font size array. * @param fontSizeStrings the array of font size string. **/ public JFontChooser(String[] fontSizeStrings) { if (fontSizeStrings == null) { fontSizeStrings = DEFAULT_FONT_SIZE_STRINGS; } this.fontSizeStrings = fontSizeStrings; JPanel selectPanel = new JPanel(); selectPanel.setLayout(new BoxLayout(selectPanel, BoxLayout.X_AXIS)); selectPanel.add(getFontFamilyPanel()); selectPanel.add(getFontStylePanel()); selectPanel.add(getFontSizePanel()); JPanel contentsPanel = new JPanel(); GridLayout gl = new GridLayout(2, 1); contentsPanel.setLayout(gl); contentsPanel.add(selectPanel, BorderLayout.NORTH); JPanel pan = new JPanel(); pan.setLayout(gl); pan.add(getSamplePanel(), BorderLayout.CENTER); pan.add(getLastPanel(), BorderLayout.SOUTH); contentsPanel.add(pan, BorderLayout.CENTER); this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); this.add(contentsPanel); this.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); this.setSelectedFont(DEFAULT_SELECTED_FONT); } public JTextField getFontFamilyTextField() { if (fontFamilyTextField == null) { fontFamilyTextField = new JTextField(); fontFamilyTextField.addFocusListener( new TextFieldFocusHandlerForTextSelection(fontFamilyTextField)); fontFamilyTextField.addKeyListener( new TextFieldKeyHandlerForListSelectionUpDown(getFontFamilyList())); fontFamilyTextField.getDocument().addDocumentListener( new ListSearchTextFieldDocumentHandler(getFontFamilyList())); fontFamilyTextField.setFont(DEFAULT_FONT); } return fontFamilyTextField; } public JTextField getFontStyleTextField() { if (fontStyleTextField == null) { fontStyleTextField = new JTextField(); fontStyleTextField.addFocusListener( new TextFieldFocusHandlerForTextSelection(fontStyleTextField)); fontStyleTextField.addKeyListener( new TextFieldKeyHandlerForListSelectionUpDown(getFontStyleList())); fontStyleTextField.getDocument().addDocumentListener( new ListSearchTextFieldDocumentHandler(getFontStyleList())); fontStyleTextField.setFont(DEFAULT_FONT); } return fontStyleTextField; } public JTextField getFontSizeTextField() { if (fontSizeTextField == null) { fontSizeTextField = new JTextField(); fontSizeTextField.addFocusListener( new TextFieldFocusHandlerForTextSelection(fontSizeTextField)); fontSizeTextField.addKeyListener( new TextFieldKeyHandlerForListSelectionUpDown(getFontSizeList())); fontSizeTextField.getDocument().addDocumentListener( new ListSearchTextFieldDocumentHandler(getFontSizeList())); fontSizeTextField.setFont(DEFAULT_FONT); } return fontSizeTextField; } public JList getFontFamilyList() { if (fontNameList == null) { fontNameList = new JList(getFontFamilies()); fontNameList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); fontNameList.addListSelectionListener( new ListSelectionHandler(getFontFamilyTextField())); fontNameList.setSelectedIndex(0); fontNameList.setFont(DEFAULT_FONT); fontNameList.setFocusable(false); } return fontNameList; } public JList getFontStyleList() { if (fontStyleList == null) { fontStyleList = new JList(getFontStyleNames()); fontStyleList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); fontStyleList.addListSelectionListener( new ListSelectionHandler(getFontStyleTextField())); fontStyleList.setSelectedIndex(0); fontStyleList.setFont(DEFAULT_FONT); fontStyleList.setFocusable(false); } return fontStyleList; } public JList getFontSizeList() { if (fontSizeList == null) { fontSizeList = new JList(this.fontSizeStrings); fontSizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); fontSizeList.addListSelectionListener( new ListSelectionHandler(getFontSizeTextField())); fontSizeList.setSelectedIndex(0); fontSizeList.setFont(DEFAULT_FONT); fontSizeList.setFocusable(false); } return fontSizeList; } /** * Get the family name of the selected font. * @return the font family of the selected font. * * @see #setSelectedFontFamily **/ public String getSelectedFontFamily() { String fontName = (String) getFontFamilyList().getSelectedValue(); return fontName; } /** * Get the style of the selected font. * @return the style of the selected font. * <code>Font.PLAIN</code>, <code>Font.BOLD</code>, * <code>Font.ITALIC</code>, <code>Font.BOLD|Font.ITALIC</code> * * @see java.awt.Font#PLAIN * @see java.awt.Font#BOLD * @see java.awt.Font#ITALIC * @see #setSelectedFontStyle **/ public int getSelectedFontStyle() { int index = getFontStyleList().getSelectedIndex(); return FONT_STYLE_CODES[index]; } /** * Get the size of the selected font. * @return the size of the selected font * * @see #setSelectedFontSize **/ public int getSelectedFontSize() { int fontSize = 1; String fontSizeString = getFontSizeTextField().getText(); while (true) { try { fontSize = Integer.parseInt(fontSizeString); break; } catch (NumberFormatException e) { fontSizeString = (String) getFontSizeList().getSelectedValue(); getFontSizeTextField().setText(fontSizeString); } } return fontSize; } /** * Get the selected font. * @return the selected font * * @see #setSelectedFont * @see java.awt.Font **/ public Font getSelectedFont() { Font font = new Font(getSelectedFontFamily(), getSelectedFontStyle(), getSelectedFontSize()); return font; } /** * Set the family name of the selected font. * @param name the family name of the selected font. * * @see getSelectedFontFamily **/ public void setSelectedFontFamily(String name) { String[] names = getFontFamilies(); for (int i = 0; i < names.length; i++) { if (names[i].toLowerCase().equals(name.toLowerCase())) { getFontFamilyList().setSelectedIndex(i); break; } } updateSampleFont(); } /** * Set the style of the selected font. * @param style the size of the selected font. * <code>Font.PLAIN</code>, <code>Font.BOLD</code>, * <code>Font.ITALIC</code>, or * <code>Font.BOLD|Font.ITALIC</code>. * * @see java.awt.Font#PLAIN * @see java.awt.Font#BOLD * @see java.awt.Font#ITALIC * @see #getSelectedFontStyle **/ public void setSelectedFontStyle(int style) { for (int i = 0; i < FONT_STYLE_CODES.length; i++) { if (FONT_STYLE_CODES[i] == style) { getFontStyleList().setSelectedIndex(i); break; } } updateSampleFont(); } /** * Set the size of the selected font. * @param size the size of the selected font * * @see #getSelectedFontSize **/ public void setSelectedFontSize(int size) { String sizeString = String.valueOf(size); for (int i = 0; i < this.fontSizeStrings.length; i++) { if (this.fontSizeStrings[i].equals(sizeString)) { getFontSizeList().setSelectedIndex(i); break; } } getFontSizeTextField().setText(sizeString); updateSampleFont(); } /** * Set the selected font. * @param font the selected font * * @see #getSelectedFont * @see java.awt.Font **/ public void setSelectedFont(Font font) { setSelectedFontFamily(font.getFamily()); setSelectedFontStyle(font.getStyle()); setSelectedFontSize(font.getSize()); } public String getVersionString() { return ("Version"); } /** * Show font selection dialog. * @param parent Dialog's Parent component. * @return OK_OPTION, CANCEL_OPTION or ERROR_OPTION * * @see #OK_OPTION * @see #CANCEL_OPTION * @see #ERROR_OPTION **/ public int showDialog(Component parent) { dialogResultValue = ERROR_OPTION; JDialog dialog = createDialog(parent); dialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dialogResultValue = CANCEL_OPTION; } }); dialog.setVisible(true); dialog.dispose(); dialog = null; return dialogResultValue; } protected class ListSelectionHandler implements ListSelectionListener { private JTextComponent textComponent; ListSelectionHandler(JTextComponent textComponent) { this.textComponent = textComponent; } public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting() == false) { JList list = (JList) e.getSource(); String selectedValue = (String) list.getSelectedValue(); String oldValue = textComponent.getText(); textComponent.setText(selectedValue); if (!oldValue.equalsIgnoreCase(selectedValue)) { textComponent.selectAll(); textComponent.requestFocus(); } updateSampleFont(); } } } protected class TextFieldFocusHandlerForTextSelection extends FocusAdapter { private JTextComponent textComponent; public TextFieldFocusHandlerForTextSelection(JTextComponent textComponent) { this.textComponent = textComponent; } public void focusGained(FocusEvent e) { textComponent.selectAll(); } public void focusLost(FocusEvent e) { textComponent.select(0, 0); updateSampleFont(); } } protected class TextFieldKeyHandlerForListSelectionUpDown extends KeyAdapter { private JList targetList; public TextFieldKeyHandlerForListSelectionUpDown(JList list) { this.targetList = list; } public void keyPressed(KeyEvent e) { int i = targetList.getSelectedIndex(); switch (e.getKeyCode()) { case KeyEvent.VK_UP: i = targetList.getSelectedIndex() - 1; if (i < 0) { i = 0; } targetList.setSelectedIndex(i); break; case KeyEvent.VK_DOWN: int listSize = targetList.getModel().getSize(); i = targetList.getSelectedIndex() + 1; if (i >= listSize) { i = listSize - 1; } targetList.setSelectedIndex(i); break; default: break; } } } protected class ListSearchTextFieldDocumentHandler implements DocumentListener { JList targetList; public ListSearchTextFieldDocumentHandler(JList targetList) { this.targetList = targetList; } public void insertUpdate(DocumentEvent e) { update(e); } public void removeUpdate(DocumentEvent e) { update(e); } public void changedUpdate(DocumentEvent e) { update(e); } private void update(DocumentEvent event) { String newValue = ""; try { Document doc = event.getDocument(); newValue = doc.getText(0, doc.getLength()); } catch (BadLocationException e) { e.printStackTrace(); } if (newValue.length() > 0) { int index = targetList.getNextMatch(newValue, 0, Position.Bias.Forward); if (index < 0) { index = 0; } targetList.ensureIndexIsVisible(index); String matchedName = targetList.getModel().getElementAt(index).toString(); if (newValue.equalsIgnoreCase(matchedName)) { if (index != targetList.getSelectedIndex()) { SwingUtilities.invokeLater(new ListSelector(index)); } } } } public class ListSelector implements Runnable { private int index; public ListSelector(int index) { this.index = index; } public void run() { targetList.setSelectedIndex(this.index); } } } protected class DialogOKAction extends AbstractAction { protected static final String ACTION_NAME = "OK"; private JDialog dialog; protected DialogOKAction(JDialog dialog) { this.dialog = dialog; putValue(Action.DEFAULT, ACTION_NAME); putValue(Action.ACTION_COMMAND_KEY, ACTION_NAME); putValue(Action.NAME, (ACTION_NAME)); } public void actionPerformed(ActionEvent e) { dialogResultValue = OK_OPTION; dialog.setVisible(false); } } protected class DialogCancelAction extends AbstractAction { protected static final String ACTION_NAME = "Cancel"; private JDialog dialog; protected DialogCancelAction(JDialog dialog) { this.dialog = dialog; putValue(Action.DEFAULT, ACTION_NAME); putValue(Action.ACTION_COMMAND_KEY, ACTION_NAME); putValue(Action.NAME, (ACTION_NAME)); } public void actionPerformed(ActionEvent e) { dialogResultValue = CANCEL_OPTION; dialog.setVisible(false); } } protected JDialog createDialog(Component parent) { Frame frame = parent instanceof Frame ? (Frame) parent : (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent); JDialog dialog = new JDialog(frame, Editor.fromConfiguracao.getValor("Inspector.obj.font.selfonte"), true); Action okAction = new DialogOKAction(dialog); Action cancelAction = new DialogCancelAction(dialog); JButton okButton = new JButton(okAction); okButton.setFont(DEFAULT_FONT); JButton cancelButton = new JButton(cancelAction); cancelButton.setFont(DEFAULT_FONT); JPanel buttonsPanel = new JPanel(); buttonsPanel.setLayout(new GridLayout(2, 1)); buttonsPanel.add(okButton); buttonsPanel.add(cancelButton); buttonsPanel.setBorder(BorderFactory.createEmptyBorder(25, 0, 10, 10)); ActionMap actionMap = buttonsPanel.getActionMap(); actionMap.put(cancelAction.getValue(Action.DEFAULT), cancelAction); actionMap.put(okAction.getValue(Action.DEFAULT), okAction); InputMap inputMap = buttonsPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(KeyStroke.getKeyStroke("ESCAPE"), cancelAction.getValue(Action.DEFAULT)); inputMap.put(KeyStroke.getKeyStroke("ENTER"), okAction.getValue(Action.DEFAULT)); JPanel dialogEastPanel = new JPanel(); dialogEastPanel.setLayout(new BorderLayout()); dialogEastPanel.add(buttonsPanel, BorderLayout.NORTH); dialog.getContentPane().add(this, BorderLayout.CENTER); dialog.getContentPane().add(dialogEastPanel, BorderLayout.EAST); dialog.pack(); dialog.setLocationRelativeTo(frame); return dialog; } protected void updateSampleFont() { Font font = getSelectedFont(); getSampleTextField().setFont(font); } /** * Coloca a Font atual como a última fonte utilizada. */ public void makeLastRegistred() { Font font = getSelectedFont(); getLastTextField().setFont(font); } protected JPanel getFontFamilyPanel() { if (fontNamePanel == null) { fontNamePanel = new JPanel(); fontNamePanel.setLayout(new BorderLayout()); fontNamePanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); fontNamePanel.setPreferredSize(new Dimension(180, 100)); JScrollPane scrollPane = new JScrollPane(getFontFamilyList()); scrollPane.getVerticalScrollBar().setFocusable(false); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); JPanel p = new JPanel(); p.setLayout(new BorderLayout()); p.add(getFontFamilyTextField(), BorderLayout.NORTH); p.add(scrollPane, BorderLayout.CENTER); JLabel label = new JLabel(Editor.fromConfiguracao.getValor("Inspector.obj.font.nfonte")); label.setHorizontalAlignment(JLabel.LEFT); label.setHorizontalTextPosition(JLabel.LEFT); label.setLabelFor(getFontFamilyTextField()); char F = Editor.fromConfiguracao.getValor("Inspector.obj.font.nfonte_mnemonic").charAt(0); label.setDisplayedMnemonic(F); fontNamePanel.add(label, BorderLayout.NORTH); fontNamePanel.add(p, BorderLayout.CENTER); } return fontNamePanel; } protected JPanel getFontStylePanel() { if (fontStylePanel == null) { fontStylePanel = new JPanel(); fontStylePanel.setLayout(new BorderLayout()); fontStylePanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); fontStylePanel.setPreferredSize(new Dimension(140, 100)); JScrollPane scrollPane = new JScrollPane(getFontStyleList()); scrollPane.getVerticalScrollBar().setFocusable(false); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); JPanel p = new JPanel(); p.setLayout(new BorderLayout()); p.add(getFontStyleTextField(), BorderLayout.NORTH); p.add(scrollPane, BorderLayout.CENTER); JLabel label = new JLabel(Editor.fromConfiguracao.getValor("Inspector.obj.font.efonte")); label.setHorizontalAlignment(JLabel.LEFT); label.setHorizontalTextPosition(JLabel.LEFT); label.setLabelFor(getFontStyleTextField()); char E = Editor.fromConfiguracao.getValor("Inspector.obj.font.efonte_mnemonic").charAt(0); label.setDisplayedMnemonic(E); fontStylePanel.add(label, BorderLayout.NORTH); fontStylePanel.add(p, BorderLayout.CENTER); } return fontStylePanel; } protected JPanel getFontSizePanel() { if (fontSizePanel == null) { fontSizePanel = new JPanel(); fontSizePanel.setLayout(new BorderLayout()); fontSizePanel.setPreferredSize(new Dimension(70, 100)); fontSizePanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); JScrollPane scrollPane = new JScrollPane(getFontSizeList()); scrollPane.getVerticalScrollBar().setFocusable(false); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); JPanel p = new JPanel(); p.setLayout(new BorderLayout()); p.add(getFontSizeTextField(), BorderLayout.NORTH); p.add(scrollPane, BorderLayout.CENTER); JLabel label = new JLabel(Editor.fromConfiguracao.getValor("Inspector.obj.font.tfonte")); label.setHorizontalAlignment(JLabel.LEFT); label.setHorizontalTextPosition(JLabel.LEFT); label.setLabelFor(getFontSizeTextField()); char T = Editor.fromConfiguracao.getValor("Inspector.obj.font.tfonte_mnemonic").charAt(0); label.setDisplayedMnemonic(T); fontSizePanel.add(label, BorderLayout.NORTH); fontSizePanel.add(p, BorderLayout.CENTER); } return fontSizePanel; } protected JPanel getSamplePanel() { if (samplePanel == null) { Border titledBorder = BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), (Editor.fromConfiguracao.getValor("Inspector.obj.font.exemplo"))); Border empty = BorderFactory.createEmptyBorder(5, 10, 10, 10); Border border = BorderFactory.createCompoundBorder(titledBorder, empty); samplePanel = new JPanel(); samplePanel.setLayout(new BorderLayout()); samplePanel.setBorder(border); samplePanel.add(getSampleTextField(), BorderLayout.CENTER); } return samplePanel; } protected JPanel getLastPanel() { if (lastPanel == null) { Border titledBorder = BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), (Editor.fromConfiguracao.getValor("Inspector.obj.font.anterior"))); Border empty = BorderFactory.createEmptyBorder(5, 10, 10, 10); Border border = BorderFactory.createCompoundBorder(titledBorder, empty); lastPanel = new JPanel(); lastPanel.setLayout(new BorderLayout()); lastPanel.setBorder(border); lastPanel.add(getLastTextField(), BorderLayout.CENTER); JButton btn = new JButton(Editor.fromConfiguracao.getValor("Inspector.obj.font.restaurar")); btn.addActionListener((ActionEvent ae) -> { JFontChooser.this.setSelectedFont(getLastTextField().getFont()); }); lastPanel.add(btn, BorderLayout.EAST); } return lastPanel; } protected JTextField getSampleTextField() { if (sampleText == null) { Border lowered = BorderFactory.createLoweredBevelBorder(); sampleText = new JTextField(("AaBbYyZz")); sampleText.setBorder(lowered); sampleText.setPreferredSize(new Dimension(100, 40)); } return sampleText; } protected JTextField getLastTextField() { if (lastText == null) { Border lowered = BorderFactory.createLoweredBevelBorder(); lastText = new JTextField(("AaBbYyZz")); lastText.setBorder(lowered); lastText.setPreferredSize(new Dimension(80, 40)); } return lastText; } protected String[] getFontFamilies() { if (fontFamilyNames == null) { GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); fontFamilyNames = env.getAvailableFontFamilyNames(); } return fontFamilyNames; } protected String[] getFontStyleNames() { if (fontStyleNames == null) { int i = 0; fontStyleNames = new String[4]; fontStyleNames[i++] = util.Utilidades.decodeFontStyle(0); // ("Plain"); fontStyleNames[i++] = util.Utilidades.decodeFontStyle(1); // ("Bold"); fontStyleNames[i++] = util.Utilidades.decodeFontStyle(2); // ("Italic"); fontStyleNames[i++] = util.Utilidades.decodeFontStyle(3); // ("BoldItalic"); } return fontStyleNames; } }
chcandido/brModelo
src/util/JFontChooser.java
213,377
package org.knowm.xchange.lgo.dto.key; import java.time.Instant; public final class LgoKey { private final String id; private final Instant issuedAt; private final Instant disabledAt; private String value; public LgoKey(String id, Instant issuedAt, Instant disabledAt) { this.id = id; this.issuedAt = issuedAt; this.disabledAt = disabledAt; } public String getId() { return id; } public Instant getEnabledAt() { return issuedAt; } public Instant getDisabledAt() { return disabledAt; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
knowm/XChange
xchange-lgo/src/main/java/org/knowm/xchange/lgo/dto/key/LgoKey.java
213,378
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.internal.cache; import org.apache.geode.util.internal.GeodeGlossary; /** * No instances of this class. Just some static method having to do with inline keys. * */ public class InlineKeyHelper { public static final boolean INLINE_REGION_KEYS = !Boolean.getBoolean(GeodeGlossary.GEMFIRE_PREFIX + "DISABLE_INLINE_REGION_KEYS"); /** * The maximum number of longs any of region entry subclasses use to store the string key inline. */ public static final int MAX_LONGS_USED_FOR_STRING_KEY = 2; /** * Given the number of longs used to encode the inline string return the maximum number of * characters that can be encoded into that many longs. */ public static int getMaxInlineStringKey(int longCount, boolean byteEncoded) { return (longCount * (byteEncoded ? 8 : 4)) - 1; } /** * Return null if the given string can not be encoded inline. Return true if the given string can * be encoded inline as bytes. Return false if the given string can be encoded inline as chars. */ public static Boolean canStringBeInlineEncoded(String skey) { if (skey.length() > getMaxInlineStringKey(MAX_LONGS_USED_FOR_STRING_KEY, true)) { return null; } if (isByteEncodingOk(skey)) { return Boolean.TRUE; } else { if (skey.length() > getMaxInlineStringKey(MAX_LONGS_USED_FOR_STRING_KEY, false)) { return null; } else { return Boolean.FALSE; } } } private static boolean isByteEncodingOk(String skey) { for (int i = 0; i < skey.length(); i++) { if (skey.charAt(i) > 0x7f) { return false; } } return true; } }
apache/geode
geode-core/src/main/java/org/apache/geode/internal/cache/InlineKeyHelper.java
213,379
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.app.plugin.core.datamgr.tree; import java.awt.datatransfer.*; import java.awt.dnd.DnDConstants; import java.io.IOException; import java.util.ArrayList; import java.util.List; import docking.dnd.GenericDataFlavor; import docking.widgets.tree.GTree; import docking.widgets.tree.GTreeNode; import docking.widgets.tree.support.GTreeDragNDropHandler; import generic.jar.ResourceFile; import ghidra.app.plugin.core.datamgr.DataTypeManagerPlugin; import ghidra.app.plugin.core.datamgr.archive.FileArchive; import ghidra.app.plugin.core.datamgr.util.DataTypeTreeCopyMoveTask; import ghidra.app.plugin.core.datamgr.util.DataTypeTreeCopyMoveTask.ActionType; import ghidra.program.model.data.*; import ghidra.util.Msg; import ghidra.util.task.Task; public class DataTypeDragNDropHandler implements GTreeDragNDropHandler { private static DataFlavor localDataTypeTreeFlavor = createLocalTreeNodeFlavor(); public static DataFlavor[] allSupportedFlavors = { DataTypeTransferable.localDataTypeFlavor, localDataTypeTreeFlavor }; public static DataFlavor[] builtinFlavors = { DataTypeTransferable.localBuiltinDataTypeFlavor, localDataTypeTreeFlavor }; public static DataFlavor[] restrictedFlavors = { localDataTypeTreeFlavor }; private final GTree tree; private final DataTypeManagerPlugin plugin; // create a data flavor that is an List of GTreeNodes private static DataFlavor createLocalTreeNodeFlavor() { try { return new GenericDataFlavor( DataFlavor.javaJVMLocalObjectMimeType + "; class=java.util.List", "Local list of Drag/Drop DataType Tree objects"); } catch (Exception e) { Msg.showError(DataTypeDragNDropHandler.class, null, null, null, e); } return null; } public DataTypeDragNDropHandler(DataTypeManagerPlugin plugin, GTree tree) { this.plugin = plugin; this.tree = tree; } @Override @SuppressWarnings("unchecked") // old API call public void drop(GTreeNode destinationNode, Transferable transferable, int dropAction) { try { List<GTreeNode> list = (List<GTreeNode>) transferable.getTransferData(localDataTypeTreeFlavor); if (list.contains(destinationNode)) { // don't allow drop on dragged nodes. return; } CategoryNode updatedDestinationNode = getDropTargetNode(destinationNode); ActionType actionType = dropAction == DnDConstants.ACTION_COPY ? ActionType.COPY : ActionType.MOVE; Task task = new DataTypeTreeCopyMoveTask(updatedDestinationNode, list, actionType, (DataTypeArchiveGTree) tree, plugin.getConflictHandler()); plugin.getTool().execute(task, 250); } catch (UnsupportedFlavorException e) { Msg.error(this, "Unable to perform drop operation", e); } catch (IOException e) { Msg.error(this, "Unable to perform drop operation", e); } } private CategoryNode getDropTargetNode(GTreeNode node) { // clients can drop/paste onto a category or archive if (node instanceof CategoryNode) { return (CategoryNode) node; } return (CategoryNode) node.getParent(); } @Override public DataFlavor[] getSupportedDataFlavors(List<GTreeNode> draggedNodes) { // single, datatype node supports both datatype dragging *and* local tree dragging if (draggedNodes.size() == 1) { GTreeNode node = draggedNodes.get(0); if (node instanceof DataTypeNode) { DataType dataType = ((DataTypeNode) node).getDataType(); if (dataType instanceof BuiltInDataType || dataType instanceof MissingBuiltInDataType) { return builtinFlavors; } return allSupportedFlavors; } // we don't support dragging archives in their entirety if (node instanceof ArchiveNode) { return new DataFlavor[] {}; } } // multiple nodes or non-datatype nodes restrict dragging to local tree dragging return restrictedFlavors; } @Override public int getSupportedDragActions() { return DnDConstants.ACTION_COPY_OR_MOVE; } @Override public Object getTransferData(List<GTreeNode> dragUserData, DataFlavor flavor) { if (flavor.equals(DataTypeTransferable.localDataTypeFlavor) || flavor.equals(DataTypeTransferable.localBuiltinDataTypeFlavor)) { // we know from getSupportedDataFlavors() that this is a single DataTypeNode DataTypeNode dataTypeNode = (DataTypeNode) dragUserData.get(0); return dataTypeNode.getDataType(); } else if (flavor.equals(localDataTypeTreeFlavor)) { return dragUserData; } else if (flavor.equals(DataFlavor.javaFileListFlavor)) { List<?> nodeList = dragUserData; ArrayList<ResourceFile> fileList = new ArrayList<ResourceFile>(); for (Object node : nodeList) { ArchiveNode archiveNode = (ArchiveNode) node; FileArchive archive = (FileArchive) archiveNode.getArchive(); ResourceFile file = archive.getFile(); fileList.add(file); } return fileList; } return null; } @Override public boolean isDropSiteOk(GTreeNode destinationNode, DataFlavor[] flavors, int dropAction) { if (!isValidDataTypeDestination(destinationNode, flavors, dropAction)) { return false; } GTreeNode updatedDestinationNode = getDropTargetNode(destinationNode); if (isDroppingBuiltin(flavors)) { if (!isValidBuiltinDropSite(updatedDestinationNode)) { return false; } } return true; } /** * Verifies the given destination node can accept the given drop/copy/paste action and content * flavors. * @param destinationNode the node accepting the action * @param flavors the supported flavors of the action * @param dropAction the actual action see {@link DnDConstants} * @return true if valid */ public boolean isValidDataTypeDestination(GTreeNode destinationNode, DataFlavor[] flavors, int dropAction) { // can't drop/paste on the root node if (destinationNode == null || destinationNode.getParent() == null) { return false; } // can only drop/paste nodes from other dataType trees if (!containsFlavor(flavors, localDataTypeTreeFlavor)) { return false; } // destination node must belong to either a modifiable archive or a program archive. // i.e. it must be writable. ArchiveNode archiveNode = ((DataTypeTreeNode) destinationNode).getArchiveNode(); if (archiveNode == null || !archiveNode.isModifiable()) { return false; } return true; } private boolean isDroppingBuiltin(DataFlavor[] flavors) { for (DataFlavor flavor : flavors) { if (flavor.equals(DataTypeTransferable.localBuiltinDataTypeFlavor)) { return true; } } return false; } private boolean isValidBuiltinDropSite(GTreeNode destinationNode) { if (!(destinationNode instanceof CategoryNode)) { return true; } CategoryNode categoryNode = (CategoryNode) destinationNode; return (categoryNode instanceof ArchiveNode); } private boolean containsFlavor(DataFlavor[] flavors, DataFlavor flavor) { for (DataFlavor f : flavors) { if (f.equals(flavor)) { return true; } } return false; } @Override public boolean isStartDragOk(List<GTreeNode> dragUserData, int dragAction) { return true; } }
NationalSecurityAgency/ghidra
Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/tree/DataTypeDragNDropHandler.java