diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/powercrystals/powerconverters/power/buildcraft/TileEntityBuildCraftProducer.java b/src/powercrystals/powerconverters/power/buildcraft/TileEntityBuildCraftProducer.java index c6b1924..1472d6c 100644 --- a/src/powercrystals/powerconverters/power/buildcraft/TileEntityBuildCraftProducer.java +++ b/src/powercrystals/powerconverters/power/buildcraft/TileEntityBuildCraftProducer.java @@ -1,68 +1,68 @@ package powercrystals.powerconverters.power.buildcraft; import java.util.Map.Entry; import net.minecraftforge.common.ForgeDirection; import buildcraft.api.power.IPowerProvider; import buildcraft.api.power.IPowerReceptor; import powercrystals.core.power.PowerProviderAdvanced; import powercrystals.powerconverters.PowerConverterCore; import powercrystals.powerconverters.power.TileEntityEnergyProducer; public class TileEntityBuildCraftProducer extends TileEntityEnergyProducer<IPowerReceptor> implements IPowerReceptor { private IPowerProvider _powerProvider; public TileEntityBuildCraftProducer() { super(PowerConverterCore.powerSystemBuildCraft, 0, IPowerReceptor.class); _powerProvider = new PowerProviderAdvanced(); _powerProvider.configure(0, 0, 0, 0, 0); } @Override public int produceEnergy(int energy) { int mj = energy / PowerConverterCore.powerSystemBuildCraft.getInternalEnergyPerOutput(); for(Entry<ForgeDirection, IPowerReceptor> output : getTiles().entrySet()) { IPowerProvider pp = output.getValue().getPowerProvider(); if(pp != null && pp.preConditions(output.getValue()) && pp.getMinEnergyReceived() <= mj) { - int energyUsed = Math.min(Math.min(pp.getMaxEnergyReceived(), mj), pp.getMaxEnergyStored() - (int)Math.floor(pp.getEnergyStored())); - pp.receiveEnergy(energyUsed, output.getKey()); + int mjUsed = Math.min(Math.min(pp.getMaxEnergyReceived(), mj), pp.getMaxEnergyStored() - (int)Math.floor(pp.getEnergyStored())); + pp.receiveEnergy(mjUsed, output.getKey()); - energy -= energyUsed * PowerConverterCore.powerSystemBuildCraft.getInternalEnergyPerOutput(); - if(energy <= 0) + mj -= mjUsed; + if(mj <= 0) { return 0; } } } - return energy; + return mj * PowerConverterCore.powerSystemBuildCraft.getInternalEnergyPerOutput(); } @Override public void setPowerProvider(IPowerProvider provider) { _powerProvider = provider; } @Override public IPowerProvider getPowerProvider() { return _powerProvider; } @Override public void doWork() { } @Override public int powerRequest(ForgeDirection from) { return 0; } }
false
true
public int produceEnergy(int energy) { int mj = energy / PowerConverterCore.powerSystemBuildCraft.getInternalEnergyPerOutput(); for(Entry<ForgeDirection, IPowerReceptor> output : getTiles().entrySet()) { IPowerProvider pp = output.getValue().getPowerProvider(); if(pp != null && pp.preConditions(output.getValue()) && pp.getMinEnergyReceived() <= mj) { int energyUsed = Math.min(Math.min(pp.getMaxEnergyReceived(), mj), pp.getMaxEnergyStored() - (int)Math.floor(pp.getEnergyStored())); pp.receiveEnergy(energyUsed, output.getKey()); energy -= energyUsed * PowerConverterCore.powerSystemBuildCraft.getInternalEnergyPerOutput(); if(energy <= 0) { return 0; } } } return energy; }
public int produceEnergy(int energy) { int mj = energy / PowerConverterCore.powerSystemBuildCraft.getInternalEnergyPerOutput(); for(Entry<ForgeDirection, IPowerReceptor> output : getTiles().entrySet()) { IPowerProvider pp = output.getValue().getPowerProvider(); if(pp != null && pp.preConditions(output.getValue()) && pp.getMinEnergyReceived() <= mj) { int mjUsed = Math.min(Math.min(pp.getMaxEnergyReceived(), mj), pp.getMaxEnergyStored() - (int)Math.floor(pp.getEnergyStored())); pp.receiveEnergy(mjUsed, output.getKey()); mj -= mjUsed; if(mj <= 0) { return 0; } } } return mj * PowerConverterCore.powerSystemBuildCraft.getInternalEnergyPerOutput(); }
diff --git a/Evoting/src/com/rau/evoting/beans/Vote.java b/Evoting/src/com/rau/evoting/beans/Vote.java index 5e932d0..beb3dcf 100644 --- a/Evoting/src/com/rau/evoting/beans/Vote.java +++ b/Evoting/src/com/rau/evoting/beans/Vote.java @@ -1,321 +1,321 @@ package com.rau.evoting.beans; import java.math.BigInteger; import java.util.ArrayList; import javax.faces.context.FacesContext; import javax.faces.event.AjaxBehaviorEvent; import javax.mail.MessagingException; import org.primefaces.model.StreamedContent; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.rau.evoting.ElGamal.BigIntegerTypeAdapter; import com.rau.evoting.ElGamal.ChaumPedersen; import com.rau.evoting.ElGamal.ChaumPedersenProof; import com.rau.evoting.ElGamal.CryptoUtil; import com.rau.evoting.ElGamal.ElGamalHelper; import com.rau.evoting.data.ElectionDP; import com.rau.evoting.data.ElectionVoteDP; import com.rau.evoting.data.ElectonAnswerDP; import com.rau.evoting.data.UserDP; import com.rau.evoting.models.Answer; import com.rau.evoting.models.Election; import com.rau.evoting.models.User; import com.rau.evoting.utils.BarcodeHelper; import com.rau.evoting.utils.MailService; import com.rau.evoting.utils.Pair; import com.rau.evoting.utils.StringHelper; import com.rau.evoting.utils.Util; public class Vote { private ArrayList<Answer> answers; private ArrayList<Integer> a1; private ArrayList<Integer> a2; private boolean showEncode; private boolean showShuffle; private String encoded1; private String encoded2; private StreamedContent barcode1; private StreamedContent barcode2; private StreamedContent barcodeReceipt; private int selectedDecodedList; private boolean showDecode; private boolean showDecoded1; private boolean showDecoded2; private int selectedVote; private int elId; private int userId; private String decoded1; private String decoded2; private String hash1; private String hash2; private int receiptId; private Election election; private String publicKey; private BigInteger r1; private BigInteger r2; private String chaumPedersen; public Vote() { userId = (int) FacesContext.getCurrentInstance().getExternalContext() .getSessionMap().get("userId"); } public String fromElection() { elId = Integer.valueOf(FacesContext.getCurrentInstance() .getExternalContext().getRequestParameterMap().get("elId")); answers = ElectonAnswerDP.getElectionAnswers(elId); showEncode = false; showShuffle = true; selectedDecodedList = 1; showDecode = false; showDecoded1 = false; showDecoded2 = false; selectedVote = 1; barcode1 = null; barcode2 = null; barcodeReceipt = null; encoded1 = null; encoded2 = null; a1 = new ArrayList<Integer>(); a2 = new ArrayList<Integer>(); for (Answer ans : answers) { a1.add(ans.getId()); a2.add(ans.getId()); } election = ElectionDP.getElection(elId); publicKey = election.getPublicKey(); return "Vote?faces-redirect=true"; } public void shuffle(AjaxBehaviorEvent event) { Util.shuffle(a1); Util.shuffle(a2); showEncode = true; } public void encode(AjaxBehaviorEvent event) { showShuffle = false; decoded1 = StringHelper.converInttListToString(a1); ElGamalHelper e1 = new ElGamalHelper(publicKey); encoded1 = e1.encode(decoded1); System.out.println("enc + dec: " + encoded1 + " " + decoded1); barcode1 = BarcodeHelper.getBarcodeFromString(encoded1); decoded2 = StringHelper.converInttListToString(a2); r1 = e1.getR(); ElGamalHelper e2 = new ElGamalHelper(publicKey); encoded2 = e2.encode(decoded2); System.out.println("enc + dec2: " + encoded2 + " " + decoded2); barcode2 = BarcodeHelper.getBarcodeFromString(encoded2); r2 = e2.getR(); showEncode = false; showDecode = true; } public void decode(AjaxBehaviorEvent event) { showDecode = false; hash1 = StringHelper.getSHA256hash(encoded1); hash2 = StringHelper.getSHA256hash(encoded2); if (selectedDecodedList == 1) { showDecoded1 = true; // make decode logic } else { showDecoded2 = true; // make decode logic } } public String vote() { // vote ChaumPedersenProof chaum = new ChaumPedersenProof(); ChaumPedersen cp = chaum.generate(new BigInteger(publicKey), - (selectedDecodedList == 1 ? r2 : r1)); - cp.setMessage(selectedDecodedList == 1 ? decoded2 : decoded1); + (selectedDecodedList == 1 ? r1 : r2)); + cp.setMessage(selectedDecodedList == 1 ? decoded1 : decoded2); Pair<BigInteger, BigInteger> enc = CryptoUtil - .getEncodedA_B(selectedDecodedList == 1 ? encoded2 : encoded1); + .getEncodedA_B(selectedDecodedList == 1 ? encoded1 : encoded2); cp.setA(enc.getFirst()); cp.setB(enc.getSecond()); Gson gson = new GsonBuilder().registerTypeAdapter(BigInteger.class, new BigIntegerTypeAdapter()).create(); chaumPedersen = gson.toJson(cp); receiptId = ElectionVoteDP.setElectionVote(elId, userId, selectedDecodedList, (selectedDecodedList == 1 ? decoded1 : decoded2), encoded1, encoded2, selectedVote, chaumPedersen); barcodeReceipt = BarcodeHelper.getBarcodeFromString(chaumPedersen); if (receiptId == -1) { return "Home?faces-redirect=true"; } String message = " Reciept Id: " + receiptId + "\n " + " hash1: " + hash1 + "\n " + " hash2: " + hash2 + "\n " + " selected audit ballot: " + selectedDecodedList + " - " + (selectedDecodedList == 1 ? decoded1 : decoded2) + "\n " + " your choice: " + selectedVote; String subject = "Receipt for " + election.getName() + " election"; User user = UserDP.getUser(userId); try { MailService.sendMessage(user.getEmail(), subject, message); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "AfterVote?faces-redirect=true"; } public ArrayList<Answer> getAnswers() { return answers; } public void setAnswers(ArrayList<Answer> answers) { this.answers = answers; } public ArrayList<Integer> getA1() { return a1; } public void setA1(ArrayList<Integer> a1) { this.a1 = a1; } public ArrayList<Integer> getA2() { return a2; } public void setA2(ArrayList<Integer> a2) { this.a2 = a2; } public boolean isShowEncode() { return showEncode; } public void setShowEncode(boolean showEncode) { this.showEncode = showEncode; } public boolean isShowShuffle() { return showShuffle; } public void setShowShuffle(boolean showShuffle) { this.showShuffle = showShuffle; } public StreamedContent getBarcode1() { return barcode1; } public void setBarcode1(StreamedContent encoded1) { this.barcode1 = encoded1; } public StreamedContent getBarcode2() { return barcode2; } public void setBarcode2(StreamedContent encoded2) { this.barcode2 = encoded2; } public StreamedContent getBarcodeReceipt() { return barcodeReceipt; } public void setBarcodeReceipt(StreamedContent barcodeReceipt) { this.barcodeReceipt = barcodeReceipt; } public int getSelectedDecodedList() { return selectedDecodedList; } public void setSelectedDecodedList(int selectedDecodedList) { this.selectedDecodedList = selectedDecodedList; } public boolean isShowDecode() { return showDecode; } public void setShowDecode(boolean showDecode) { this.showDecode = showDecode; } public boolean isShowDecoded1() { return showDecoded1; } public void setShowDecoded1(boolean showDecoded1) { this.showDecoded1 = showDecoded1; } public boolean isShowDecoded2() { return showDecoded2; } public void setShowDecoded2(boolean showDecoded2) { this.showDecoded2 = showDecoded2; } public int getSelectedVote() { return selectedVote; } public void setSelectedVote(int selectedVote) { this.selectedVote = selectedVote; } public String getHash1() { return hash1; } public void setHash1(String hash1) { this.hash1 = hash1; } public String getHash2() { return hash2; } public void setHash2(String hash2) { this.hash2 = hash2; } public String getDecoded1() { return decoded1; } public void setDecoded1(String decoded1) { this.decoded1 = decoded1; } public String getDecoded2() { return decoded2; } public void setDecoded2(String decoded2) { this.decoded2 = decoded2; } public int getReceiptId() { return receiptId; } public void setReceiptId(int receiptId) { this.receiptId = receiptId; } }
false
true
public String vote() { // vote ChaumPedersenProof chaum = new ChaumPedersenProof(); ChaumPedersen cp = chaum.generate(new BigInteger(publicKey), (selectedDecodedList == 1 ? r2 : r1)); cp.setMessage(selectedDecodedList == 1 ? decoded2 : decoded1); Pair<BigInteger, BigInteger> enc = CryptoUtil .getEncodedA_B(selectedDecodedList == 1 ? encoded2 : encoded1); cp.setA(enc.getFirst()); cp.setB(enc.getSecond()); Gson gson = new GsonBuilder().registerTypeAdapter(BigInteger.class, new BigIntegerTypeAdapter()).create(); chaumPedersen = gson.toJson(cp); receiptId = ElectionVoteDP.setElectionVote(elId, userId, selectedDecodedList, (selectedDecodedList == 1 ? decoded1 : decoded2), encoded1, encoded2, selectedVote, chaumPedersen); barcodeReceipt = BarcodeHelper.getBarcodeFromString(chaumPedersen); if (receiptId == -1) { return "Home?faces-redirect=true"; } String message = " Reciept Id: " + receiptId + "\n " + " hash1: " + hash1 + "\n " + " hash2: " + hash2 + "\n " + " selected audit ballot: " + selectedDecodedList + " - " + (selectedDecodedList == 1 ? decoded1 : decoded2) + "\n " + " your choice: " + selectedVote; String subject = "Receipt for " + election.getName() + " election"; User user = UserDP.getUser(userId); try { MailService.sendMessage(user.getEmail(), subject, message); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "AfterVote?faces-redirect=true"; }
public String vote() { // vote ChaumPedersenProof chaum = new ChaumPedersenProof(); ChaumPedersen cp = chaum.generate(new BigInteger(publicKey), (selectedDecodedList == 1 ? r1 : r2)); cp.setMessage(selectedDecodedList == 1 ? decoded1 : decoded2); Pair<BigInteger, BigInteger> enc = CryptoUtil .getEncodedA_B(selectedDecodedList == 1 ? encoded1 : encoded2); cp.setA(enc.getFirst()); cp.setB(enc.getSecond()); Gson gson = new GsonBuilder().registerTypeAdapter(BigInteger.class, new BigIntegerTypeAdapter()).create(); chaumPedersen = gson.toJson(cp); receiptId = ElectionVoteDP.setElectionVote(elId, userId, selectedDecodedList, (selectedDecodedList == 1 ? decoded1 : decoded2), encoded1, encoded2, selectedVote, chaumPedersen); barcodeReceipt = BarcodeHelper.getBarcodeFromString(chaumPedersen); if (receiptId == -1) { return "Home?faces-redirect=true"; } String message = " Reciept Id: " + receiptId + "\n " + " hash1: " + hash1 + "\n " + " hash2: " + hash2 + "\n " + " selected audit ballot: " + selectedDecodedList + " - " + (selectedDecodedList == 1 ? decoded1 : decoded2) + "\n " + " your choice: " + selectedVote; String subject = "Receipt for " + election.getName() + " election"; User user = UserDP.getUser(userId); try { MailService.sendMessage(user.getEmail(), subject, message); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "AfterVote?faces-redirect=true"; }
diff --git a/src/ramirez57/CLIShop/Main.java b/src/ramirez57/CLIShop/Main.java index d01aaf9..a6da0f6 100644 --- a/src/ramirez57/CLIShop/Main.java +++ b/src/ramirez57/CLIShop/Main.java @@ -1,288 +1,302 @@ package ramirez57.CLIShop; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.logging.Logger; import net.milkbowl.vault.economy.Economy; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.Listener; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; public class Main extends JavaPlugin implements Listener { Server mc; PluginManager pluginmgr; Logger log; Economy economy; Player player; String string; File salesFile; FileConfiguration sales; File configFile; FileConfiguration config; Material material; ItemStack itemstack; List<String> stringlist; public void onEnable() { mc = this.getServer(); log = this.getLogger(); pluginmgr = this.getServer().getPluginManager(); if(!setupEcon()) { log.info("Problem depending vault. Disabling..."); pluginmgr.disablePlugin(this); return; } salesFile = new File(this.getDataFolder(), "SALES"); sales = YamlConfiguration.loadConfiguration(salesFile); configFile = new File(this.getDataFolder(), "config.yml"); config = this.getConfig(); config.options().copyDefaults(true); savesales(); saveconfig(); } public void onDisable() { } public void reload() { config = YamlConfiguration.loadConfiguration(configFile); sales = YamlConfiguration.loadConfiguration(salesFile); return; } public void savesales() { try { sales.save(salesFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return; } public void saveconfig() { try { config.save(configFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return; } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){ if(cmd.getName().equalsIgnoreCase("cs")){ if(isplayer(sender)) { player = (Player)sender; if(args.length > 0) { if(args[0].equalsIgnoreCase("help")) { sender.sendMessage(ChatColor.GOLD + "/cs help" + ChatColor.GRAY + " - Display help information"); sender.sendMessage(ChatColor.GOLD + "/cs sell " + ChatColor.GRAY + "- Sell amount of item for cost per one"); sender.sendMessage(ChatColor.GOLD + "/cs sell hand " + ChatColor.GRAY + "- Sell amount of what is in your hand for cost per one"); sender.sendMessage(ChatColor.GOLD + "/cs buy " + ChatColor.GRAY + "- Buy the amount of item from player"); sender.sendMessage(ChatColor.GOLD + "/cs list <page> <item> " + ChatColor.GRAY + "- Show the CLIShop market"); sender.sendMessage(ChatColor.LIGHT_PURPLE + "Type a command for further help on syntax."); return true; } if(args[0].equalsIgnoreCase("sell")) { if(args.length > 3) { try {Integer.parseInt(args[2]);} catch(NumberFormatException e) {player.sendMessage("/cs sell [item] [amount] [cost_per_one]");return true;} try {Double.parseDouble(args[3]);} catch(NumberFormatException e) {player.sendMessage("/cs sell [item] [amount] [cost_per_one]");return true;} if(Double.parseDouble(args[3]) > config.getDouble("price_limit")) { player.sendMessage(ChatColor.RED + "You may not set a price that high."); player.sendMessage(ChatColor.RED + "Price limit is " + String.valueOf(config.getDouble("price_limit"))); return true; } if(Double.parseDouble(args[3]) < 0) { player.sendMessage(ChatColor.RED + "You must set a price 0 or higher."); return true; } if(!args[1].equalsIgnoreCase("hand")) { if(Material.matchMaterial(args[1]) == null) { sender.sendMessage("What is " + args[1] + "?"); return true; } } else { args[1] = player.getItemInHand().getType().toString(); } material = Material.matchMaterial(args[1]); if(Integer.parseInt(args[2]) <= 0 || material == Material.AIR) { player.sendMessage(ChatColor.RED + "Stop trying to sell nothing."); return true; } if(!player.getInventory().contains(material, Integer.parseInt(args[2]))) { sender.sendMessage("You do not have at least " + args[2] + " of " + args[1]); return true; } else { int eax,ebx; eax = Integer.parseInt(args[2]); while(eax > 0) { ebx = player.getInventory().first(material); itemstack = player.getInventory().getItem(ebx); if(itemstack.getDurability() > 0 && !config.getBoolean("sell_damaged_items")) { player.sendMessage(ChatColor.RED + "You cannot sell damaged items."); return true; } if(itemstack.getAmount() <= eax) { eax -= itemstack.getAmount(); itemstack.setAmount(0); player.getInventory().setItem(ebx, itemstack); } else { itemstack.setAmount(itemstack.getAmount()-eax); player.getInventory().setItem(ebx, itemstack); eax = 0; } } string = material.toString() +"."+player.getName().toUpperCase() + "."; sales.set(string + "amount", sales.getInt(string + "amount", 0) + Integer.parseInt(args[2])); sales.set(string + "durability", itemstack.getDurability()); sales.set(string + "cost", Double.parseDouble(args[3])); stringlist = sales.getStringList(material.toString() + ".sellers");if(!stringlist.contains(player.getName().toUpperCase())) stringlist.add(player.getName().toUpperCase()); sales.set(material.toString() + ".sellers", stringlist); savesales(); player.sendMessage(ChatColor.GREEN + "Put item (" + args[1] + " x " + args[2] + ") on the market for " + args[3] + " " + economy.currencyNamePlural() + " per one."); mc.broadcastMessage(ChatColor.BLUE + player.getName() + ChatColor.GREEN +" is now selling " + ChatColor.YELLOW + args[2] + " " + Material.matchMaterial(args[1]).toString() + ChatColor.GREEN + " for " + ChatColor.RED + args[3] + " " + economy.currencyNamePlural() + " per one."); return true; } } else { player.sendMessage("/cs sell [item] [amount] [cost_per_one]"); return true; } } if(args[0].equalsIgnoreCase("buy")) { if(args.length > 3) { try{Integer.parseInt(args[3]);} catch(NumberFormatException e) {player.sendMessage("/cs buy [player] [item] [amount]");return true;} material = Material.matchMaterial(args[2]); if(material == null) { player.sendMessage("What is " + args[2] + "?"); return true; } String szsale = material.toString() + "." + args[1].toUpperCase() + "."; int eax = Integer.parseInt(args[3]); if(sales.getInt(szsale + "amount",0) > 0) { if(sales.getInt(szsale + "amount",0) >= eax) { double cost = sales.getDouble(szsale + "cost") * Integer.parseInt(args[3]); String name = player.getName(); if(economy.getBalance(name) >= cost) { economy.withdrawPlayer(name, cost); economy.depositPlayer(args[1], cost); if(mc.getPlayer(args[1]).isOnline()) { mc.getPlayer(args[1]).sendMessage(ChatColor.GREEN + name + " has bought " + args[3] + " of your " + args[2] + "(" + cost + " " + economy.currencyNamePlural() + ")"); } } else if(name.equalsIgnoreCase(args[1])) { player.sendMessage(ChatColor.GREEN + "Taking item off the market..."); } else { player.sendMessage(ChatColor.RED + "You do not have enough " + economy.currencyNamePlural()); player.sendMessage(ChatColor.RED + String.valueOf(cost) + " " + economy.currencyNamePlural() + " is required."); return true; } itemstack = new ItemStack(material,Integer.parseInt(args[3]),Short.parseShort(sales.getString(szsale + "durability","0"))); Iterator<ItemStack> i_stacks = player.getInventory().addItem(itemstack).values().iterator(); while(i_stacks.hasNext()) { player.getWorld().dropItem(player.getLocation(), i_stacks.next()); //drop any items that couldn't fit player.sendMessage(ChatColor.YELLOW + "Some items could not fit. They were dropped at your location."); } if(sales.getInt(szsale + "amount",0)-Integer.parseInt(args[3]) <= 0) { sales.set(szsale + "amount", null); sales.set(szsale + "durability", null); //sold out sales.set(szsale + "cost", null); sales.set(material.toString() + "." + args[1].toUpperCase(), null); stringlist = sales.getStringList(material.toString() + ".sellers");stringlist.remove(args[1].toUpperCase()); sales.set(material.toString() + ".sellers", stringlist); } else { sales.set(szsale + "amount", sales.getInt(szsale + "amount",0)-Integer.parseInt(args[3])); } savesales(); player.sendMessage(ChatColor.GREEN + "Received item."); return true; } else { player.sendMessage(ChatColor.RED + "Player " + args[1] + " is not selling that many " + args[2]); player.sendMessage(ChatColor.RED + args[1] + " is selling " + String.valueOf(sales.getInt(string + "amount",0)) + " " + args[2]); return true; } } else { player.sendMessage(ChatColor.RED + "Player " + args[1] + " is not selling any " + args[2]); return true; } } else { player.sendMessage("/cs buy [player] [item] [amount]"); return true; } } if(args[0].equalsIgnoreCase("list")) { int page = 1; String filter; if(args.length >= 2) { try{page=Integer.valueOf(args[1]);} catch(NumberFormatException e) {player.sendMessage(ChatColor.RED + "That page number is invalid.");return true;} } if(args.length >= 3) filter = Material.matchMaterial(args[2]).toString(); else filter = "NONE"; int lineend = 11 * page; int linestart = lineend-10; int lines = 1; player.sendMessage(ChatColor.RED + "|-----Page " + String.valueOf(page) + "-----|"); - for(Material mat : Material.values()) { - if(mat.toString().equals(filter) || filter.equals("NONE")) { - List<String> sellers = sales.getStringList(mat.toString() + "." + "sellers"); - for(Object seller : sellers.toArray()) { - if(lines >= linestart && lines <= lineend) { - player.sendMessage(ChatColor.BLUE + mc.getPlayer(String.valueOf(seller)).getName() + ChatColor.RED + " is selling " + ChatColor.YELLOW + String.valueOf(sales.getInt(mat.toString() + "." + seller + ".amount")) + " " + mat.toString() + ChatColor.RED + " for " + ChatColor.GREEN + String.valueOf(sales.getDouble(mat.toString() + "." + seller + "." + "cost")) + " " + economy.currencyNamePlural() + " per one."); - } - lines++; + if(config.getBoolean("shorthand")) { //The check is done first so it can process faster later. + for(Material mat : Material.values()) { + if(mat.toString().equals(filter) || filter.equals("NONE")) { + List<String> sellers = sales.getStringList(mat.toString() + "." + "sellers"); + for(Object seller : sellers.toArray()) { + if(lines >= linestart && lines <= lineend) { + player.sendMessage(ChatColor.BLUE + mc.getPlayer(String.valueOf(seller)).getName() + ChatColor.RED + ": " + ChatColor.YELLOW + String.valueOf(sales.getInt(mat.toString() + "." + seller + ".amount")) + " " + mat.toString() + ChatColor.RED + " for " + ChatColor.GREEN + String.valueOf(sales.getDouble(mat.toString() + "." + seller + ".cost")) + " " + economy.currencyNamePlural() + " each."); + } + lines++; + } } - } + } + } else { + for(Material mat : Material.values()) { + if(mat.toString().equals(filter) || filter.equals("NONE")) { + List<String> sellers = sales.getStringList(mat.toString() + "." + "sellers"); + for(Object seller : sellers.toArray()) { + if(lines >= linestart && lines <= lineend) { + player.sendMessage(ChatColor.BLUE + mc.getPlayer(String.valueOf(seller)).getName() + ChatColor.RED + " is selling " + ChatColor.YELLOW + String.valueOf(sales.getInt(mat.toString() + "." + seller + ".amount")) + " " + mat.toString() + ChatColor.RED + " for " + ChatColor.GREEN + String.valueOf(sales.getDouble(mat.toString() + "." + seller + ".cost")) + " " + economy.currencyNamePlural() + " per one."); + } + lines++; + } + } + } } player.sendMessage(ChatColor.RED + "Type " + ChatColor.YELLOW + "/cs list " + String.valueOf(page+1) + ChatColor.RED + " to see the next page"); return true; } } else { return false; } } else { sender.sendMessage("Only players can use this command."); return true; } } if(cmd.getName().equalsIgnoreCase("csadmin")) { if(args.length > 0) { if(args[0].equalsIgnoreCase("reload")) { reload(); sender.sendMessage(ChatColor.GREEN + "Configuration reloaded."); return true; } } } return false; } public boolean isplayer(CommandSender _sender) { return _sender instanceof Player; } public boolean setupEcon() { RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); if (economyProvider != null) { economy = economyProvider.getProvider(); } return (economy != null); } public boolean sell(String playername, ItemStack item, double cost) { return true; } }
false
true
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){ if(cmd.getName().equalsIgnoreCase("cs")){ if(isplayer(sender)) { player = (Player)sender; if(args.length > 0) { if(args[0].equalsIgnoreCase("help")) { sender.sendMessage(ChatColor.GOLD + "/cs help" + ChatColor.GRAY + " - Display help information"); sender.sendMessage(ChatColor.GOLD + "/cs sell " + ChatColor.GRAY + "- Sell amount of item for cost per one"); sender.sendMessage(ChatColor.GOLD + "/cs sell hand " + ChatColor.GRAY + "- Sell amount of what is in your hand for cost per one"); sender.sendMessage(ChatColor.GOLD + "/cs buy " + ChatColor.GRAY + "- Buy the amount of item from player"); sender.sendMessage(ChatColor.GOLD + "/cs list <page> <item> " + ChatColor.GRAY + "- Show the CLIShop market"); sender.sendMessage(ChatColor.LIGHT_PURPLE + "Type a command for further help on syntax."); return true; } if(args[0].equalsIgnoreCase("sell")) { if(args.length > 3) { try {Integer.parseInt(args[2]);} catch(NumberFormatException e) {player.sendMessage("/cs sell [item] [amount] [cost_per_one]");return true;} try {Double.parseDouble(args[3]);} catch(NumberFormatException e) {player.sendMessage("/cs sell [item] [amount] [cost_per_one]");return true;} if(Double.parseDouble(args[3]) > config.getDouble("price_limit")) { player.sendMessage(ChatColor.RED + "You may not set a price that high."); player.sendMessage(ChatColor.RED + "Price limit is " + String.valueOf(config.getDouble("price_limit"))); return true; } if(Double.parseDouble(args[3]) < 0) { player.sendMessage(ChatColor.RED + "You must set a price 0 or higher."); return true; } if(!args[1].equalsIgnoreCase("hand")) { if(Material.matchMaterial(args[1]) == null) { sender.sendMessage("What is " + args[1] + "?"); return true; } } else { args[1] = player.getItemInHand().getType().toString(); } material = Material.matchMaterial(args[1]); if(Integer.parseInt(args[2]) <= 0 || material == Material.AIR) { player.sendMessage(ChatColor.RED + "Stop trying to sell nothing."); return true; } if(!player.getInventory().contains(material, Integer.parseInt(args[2]))) { sender.sendMessage("You do not have at least " + args[2] + " of " + args[1]); return true; } else { int eax,ebx; eax = Integer.parseInt(args[2]); while(eax > 0) { ebx = player.getInventory().first(material); itemstack = player.getInventory().getItem(ebx); if(itemstack.getDurability() > 0 && !config.getBoolean("sell_damaged_items")) { player.sendMessage(ChatColor.RED + "You cannot sell damaged items."); return true; } if(itemstack.getAmount() <= eax) { eax -= itemstack.getAmount(); itemstack.setAmount(0); player.getInventory().setItem(ebx, itemstack); } else { itemstack.setAmount(itemstack.getAmount()-eax); player.getInventory().setItem(ebx, itemstack); eax = 0; } } string = material.toString() +"."+player.getName().toUpperCase() + "."; sales.set(string + "amount", sales.getInt(string + "amount", 0) + Integer.parseInt(args[2])); sales.set(string + "durability", itemstack.getDurability()); sales.set(string + "cost", Double.parseDouble(args[3])); stringlist = sales.getStringList(material.toString() + ".sellers");if(!stringlist.contains(player.getName().toUpperCase())) stringlist.add(player.getName().toUpperCase()); sales.set(material.toString() + ".sellers", stringlist); savesales(); player.sendMessage(ChatColor.GREEN + "Put item (" + args[1] + " x " + args[2] + ") on the market for " + args[3] + " " + economy.currencyNamePlural() + " per one."); mc.broadcastMessage(ChatColor.BLUE + player.getName() + ChatColor.GREEN +" is now selling " + ChatColor.YELLOW + args[2] + " " + Material.matchMaterial(args[1]).toString() + ChatColor.GREEN + " for " + ChatColor.RED + args[3] + " " + economy.currencyNamePlural() + " per one."); return true; } } else { player.sendMessage("/cs sell [item] [amount] [cost_per_one]"); return true; } } if(args[0].equalsIgnoreCase("buy")) { if(args.length > 3) { try{Integer.parseInt(args[3]);} catch(NumberFormatException e) {player.sendMessage("/cs buy [player] [item] [amount]");return true;} material = Material.matchMaterial(args[2]); if(material == null) { player.sendMessage("What is " + args[2] + "?"); return true; } String szsale = material.toString() + "." + args[1].toUpperCase() + "."; int eax = Integer.parseInt(args[3]); if(sales.getInt(szsale + "amount",0) > 0) { if(sales.getInt(szsale + "amount",0) >= eax) { double cost = sales.getDouble(szsale + "cost") * Integer.parseInt(args[3]); String name = player.getName(); if(economy.getBalance(name) >= cost) { economy.withdrawPlayer(name, cost); economy.depositPlayer(args[1], cost); if(mc.getPlayer(args[1]).isOnline()) { mc.getPlayer(args[1]).sendMessage(ChatColor.GREEN + name + " has bought " + args[3] + " of your " + args[2] + "(" + cost + " " + economy.currencyNamePlural() + ")"); } } else if(name.equalsIgnoreCase(args[1])) { player.sendMessage(ChatColor.GREEN + "Taking item off the market..."); } else { player.sendMessage(ChatColor.RED + "You do not have enough " + economy.currencyNamePlural()); player.sendMessage(ChatColor.RED + String.valueOf(cost) + " " + economy.currencyNamePlural() + " is required."); return true; } itemstack = new ItemStack(material,Integer.parseInt(args[3]),Short.parseShort(sales.getString(szsale + "durability","0"))); Iterator<ItemStack> i_stacks = player.getInventory().addItem(itemstack).values().iterator(); while(i_stacks.hasNext()) { player.getWorld().dropItem(player.getLocation(), i_stacks.next()); //drop any items that couldn't fit player.sendMessage(ChatColor.YELLOW + "Some items could not fit. They were dropped at your location."); } if(sales.getInt(szsale + "amount",0)-Integer.parseInt(args[3]) <= 0) { sales.set(szsale + "amount", null); sales.set(szsale + "durability", null); //sold out sales.set(szsale + "cost", null); sales.set(material.toString() + "." + args[1].toUpperCase(), null); stringlist = sales.getStringList(material.toString() + ".sellers");stringlist.remove(args[1].toUpperCase()); sales.set(material.toString() + ".sellers", stringlist); } else { sales.set(szsale + "amount", sales.getInt(szsale + "amount",0)-Integer.parseInt(args[3])); } savesales(); player.sendMessage(ChatColor.GREEN + "Received item."); return true; } else { player.sendMessage(ChatColor.RED + "Player " + args[1] + " is not selling that many " + args[2]); player.sendMessage(ChatColor.RED + args[1] + " is selling " + String.valueOf(sales.getInt(string + "amount",0)) + " " + args[2]); return true; } } else { player.sendMessage(ChatColor.RED + "Player " + args[1] + " is not selling any " + args[2]); return true; } } else { player.sendMessage("/cs buy [player] [item] [amount]"); return true; } } if(args[0].equalsIgnoreCase("list")) { int page = 1; String filter; if(args.length >= 2) { try{page=Integer.valueOf(args[1]);} catch(NumberFormatException e) {player.sendMessage(ChatColor.RED + "That page number is invalid.");return true;} } if(args.length >= 3) filter = Material.matchMaterial(args[2]).toString(); else filter = "NONE"; int lineend = 11 * page; int linestart = lineend-10; int lines = 1; player.sendMessage(ChatColor.RED + "|-----Page " + String.valueOf(page) + "-----|"); for(Material mat : Material.values()) { if(mat.toString().equals(filter) || filter.equals("NONE")) { List<String> sellers = sales.getStringList(mat.toString() + "." + "sellers"); for(Object seller : sellers.toArray()) { if(lines >= linestart && lines <= lineend) { player.sendMessage(ChatColor.BLUE + mc.getPlayer(String.valueOf(seller)).getName() + ChatColor.RED + " is selling " + ChatColor.YELLOW + String.valueOf(sales.getInt(mat.toString() + "." + seller + ".amount")) + " " + mat.toString() + ChatColor.RED + " for " + ChatColor.GREEN + String.valueOf(sales.getDouble(mat.toString() + "." + seller + "." + "cost")) + " " + economy.currencyNamePlural() + " per one."); } lines++; } } } player.sendMessage(ChatColor.RED + "Type " + ChatColor.YELLOW + "/cs list " + String.valueOf(page+1) + ChatColor.RED + " to see the next page"); return true; } } else { return false; } } else { sender.sendMessage("Only players can use this command."); return true; } } if(cmd.getName().equalsIgnoreCase("csadmin")) { if(args.length > 0) { if(args[0].equalsIgnoreCase("reload")) { reload(); sender.sendMessage(ChatColor.GREEN + "Configuration reloaded."); return true; } } } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){ if(cmd.getName().equalsIgnoreCase("cs")){ if(isplayer(sender)) { player = (Player)sender; if(args.length > 0) { if(args[0].equalsIgnoreCase("help")) { sender.sendMessage(ChatColor.GOLD + "/cs help" + ChatColor.GRAY + " - Display help information"); sender.sendMessage(ChatColor.GOLD + "/cs sell " + ChatColor.GRAY + "- Sell amount of item for cost per one"); sender.sendMessage(ChatColor.GOLD + "/cs sell hand " + ChatColor.GRAY + "- Sell amount of what is in your hand for cost per one"); sender.sendMessage(ChatColor.GOLD + "/cs buy " + ChatColor.GRAY + "- Buy the amount of item from player"); sender.sendMessage(ChatColor.GOLD + "/cs list <page> <item> " + ChatColor.GRAY + "- Show the CLIShop market"); sender.sendMessage(ChatColor.LIGHT_PURPLE + "Type a command for further help on syntax."); return true; } if(args[0].equalsIgnoreCase("sell")) { if(args.length > 3) { try {Integer.parseInt(args[2]);} catch(NumberFormatException e) {player.sendMessage("/cs sell [item] [amount] [cost_per_one]");return true;} try {Double.parseDouble(args[3]);} catch(NumberFormatException e) {player.sendMessage("/cs sell [item] [amount] [cost_per_one]");return true;} if(Double.parseDouble(args[3]) > config.getDouble("price_limit")) { player.sendMessage(ChatColor.RED + "You may not set a price that high."); player.sendMessage(ChatColor.RED + "Price limit is " + String.valueOf(config.getDouble("price_limit"))); return true; } if(Double.parseDouble(args[3]) < 0) { player.sendMessage(ChatColor.RED + "You must set a price 0 or higher."); return true; } if(!args[1].equalsIgnoreCase("hand")) { if(Material.matchMaterial(args[1]) == null) { sender.sendMessage("What is " + args[1] + "?"); return true; } } else { args[1] = player.getItemInHand().getType().toString(); } material = Material.matchMaterial(args[1]); if(Integer.parseInt(args[2]) <= 0 || material == Material.AIR) { player.sendMessage(ChatColor.RED + "Stop trying to sell nothing."); return true; } if(!player.getInventory().contains(material, Integer.parseInt(args[2]))) { sender.sendMessage("You do not have at least " + args[2] + " of " + args[1]); return true; } else { int eax,ebx; eax = Integer.parseInt(args[2]); while(eax > 0) { ebx = player.getInventory().first(material); itemstack = player.getInventory().getItem(ebx); if(itemstack.getDurability() > 0 && !config.getBoolean("sell_damaged_items")) { player.sendMessage(ChatColor.RED + "You cannot sell damaged items."); return true; } if(itemstack.getAmount() <= eax) { eax -= itemstack.getAmount(); itemstack.setAmount(0); player.getInventory().setItem(ebx, itemstack); } else { itemstack.setAmount(itemstack.getAmount()-eax); player.getInventory().setItem(ebx, itemstack); eax = 0; } } string = material.toString() +"."+player.getName().toUpperCase() + "."; sales.set(string + "amount", sales.getInt(string + "amount", 0) + Integer.parseInt(args[2])); sales.set(string + "durability", itemstack.getDurability()); sales.set(string + "cost", Double.parseDouble(args[3])); stringlist = sales.getStringList(material.toString() + ".sellers");if(!stringlist.contains(player.getName().toUpperCase())) stringlist.add(player.getName().toUpperCase()); sales.set(material.toString() + ".sellers", stringlist); savesales(); player.sendMessage(ChatColor.GREEN + "Put item (" + args[1] + " x " + args[2] + ") on the market for " + args[3] + " " + economy.currencyNamePlural() + " per one."); mc.broadcastMessage(ChatColor.BLUE + player.getName() + ChatColor.GREEN +" is now selling " + ChatColor.YELLOW + args[2] + " " + Material.matchMaterial(args[1]).toString() + ChatColor.GREEN + " for " + ChatColor.RED + args[3] + " " + economy.currencyNamePlural() + " per one."); return true; } } else { player.sendMessage("/cs sell [item] [amount] [cost_per_one]"); return true; } } if(args[0].equalsIgnoreCase("buy")) { if(args.length > 3) { try{Integer.parseInt(args[3]);} catch(NumberFormatException e) {player.sendMessage("/cs buy [player] [item] [amount]");return true;} material = Material.matchMaterial(args[2]); if(material == null) { player.sendMessage("What is " + args[2] + "?"); return true; } String szsale = material.toString() + "." + args[1].toUpperCase() + "."; int eax = Integer.parseInt(args[3]); if(sales.getInt(szsale + "amount",0) > 0) { if(sales.getInt(szsale + "amount",0) >= eax) { double cost = sales.getDouble(szsale + "cost") * Integer.parseInt(args[3]); String name = player.getName(); if(economy.getBalance(name) >= cost) { economy.withdrawPlayer(name, cost); economy.depositPlayer(args[1], cost); if(mc.getPlayer(args[1]).isOnline()) { mc.getPlayer(args[1]).sendMessage(ChatColor.GREEN + name + " has bought " + args[3] + " of your " + args[2] + "(" + cost + " " + economy.currencyNamePlural() + ")"); } } else if(name.equalsIgnoreCase(args[1])) { player.sendMessage(ChatColor.GREEN + "Taking item off the market..."); } else { player.sendMessage(ChatColor.RED + "You do not have enough " + economy.currencyNamePlural()); player.sendMessage(ChatColor.RED + String.valueOf(cost) + " " + economy.currencyNamePlural() + " is required."); return true; } itemstack = new ItemStack(material,Integer.parseInt(args[3]),Short.parseShort(sales.getString(szsale + "durability","0"))); Iterator<ItemStack> i_stacks = player.getInventory().addItem(itemstack).values().iterator(); while(i_stacks.hasNext()) { player.getWorld().dropItem(player.getLocation(), i_stacks.next()); //drop any items that couldn't fit player.sendMessage(ChatColor.YELLOW + "Some items could not fit. They were dropped at your location."); } if(sales.getInt(szsale + "amount",0)-Integer.parseInt(args[3]) <= 0) { sales.set(szsale + "amount", null); sales.set(szsale + "durability", null); //sold out sales.set(szsale + "cost", null); sales.set(material.toString() + "." + args[1].toUpperCase(), null); stringlist = sales.getStringList(material.toString() + ".sellers");stringlist.remove(args[1].toUpperCase()); sales.set(material.toString() + ".sellers", stringlist); } else { sales.set(szsale + "amount", sales.getInt(szsale + "amount",0)-Integer.parseInt(args[3])); } savesales(); player.sendMessage(ChatColor.GREEN + "Received item."); return true; } else { player.sendMessage(ChatColor.RED + "Player " + args[1] + " is not selling that many " + args[2]); player.sendMessage(ChatColor.RED + args[1] + " is selling " + String.valueOf(sales.getInt(string + "amount",0)) + " " + args[2]); return true; } } else { player.sendMessage(ChatColor.RED + "Player " + args[1] + " is not selling any " + args[2]); return true; } } else { player.sendMessage("/cs buy [player] [item] [amount]"); return true; } } if(args[0].equalsIgnoreCase("list")) { int page = 1; String filter; if(args.length >= 2) { try{page=Integer.valueOf(args[1]);} catch(NumberFormatException e) {player.sendMessage(ChatColor.RED + "That page number is invalid.");return true;} } if(args.length >= 3) filter = Material.matchMaterial(args[2]).toString(); else filter = "NONE"; int lineend = 11 * page; int linestart = lineend-10; int lines = 1; player.sendMessage(ChatColor.RED + "|-----Page " + String.valueOf(page) + "-----|"); if(config.getBoolean("shorthand")) { //The check is done first so it can process faster later. for(Material mat : Material.values()) { if(mat.toString().equals(filter) || filter.equals("NONE")) { List<String> sellers = sales.getStringList(mat.toString() + "." + "sellers"); for(Object seller : sellers.toArray()) { if(lines >= linestart && lines <= lineend) { player.sendMessage(ChatColor.BLUE + mc.getPlayer(String.valueOf(seller)).getName() + ChatColor.RED + ": " + ChatColor.YELLOW + String.valueOf(sales.getInt(mat.toString() + "." + seller + ".amount")) + " " + mat.toString() + ChatColor.RED + " for " + ChatColor.GREEN + String.valueOf(sales.getDouble(mat.toString() + "." + seller + ".cost")) + " " + economy.currencyNamePlural() + " each."); } lines++; } } } } else { for(Material mat : Material.values()) { if(mat.toString().equals(filter) || filter.equals("NONE")) { List<String> sellers = sales.getStringList(mat.toString() + "." + "sellers"); for(Object seller : sellers.toArray()) { if(lines >= linestart && lines <= lineend) { player.sendMessage(ChatColor.BLUE + mc.getPlayer(String.valueOf(seller)).getName() + ChatColor.RED + " is selling " + ChatColor.YELLOW + String.valueOf(sales.getInt(mat.toString() + "." + seller + ".amount")) + " " + mat.toString() + ChatColor.RED + " for " + ChatColor.GREEN + String.valueOf(sales.getDouble(mat.toString() + "." + seller + ".cost")) + " " + economy.currencyNamePlural() + " per one."); } lines++; } } } } player.sendMessage(ChatColor.RED + "Type " + ChatColor.YELLOW + "/cs list " + String.valueOf(page+1) + ChatColor.RED + " to see the next page"); return true; } } else { return false; } } else { sender.sendMessage("Only players can use this command."); return true; } } if(cmd.getName().equalsIgnoreCase("csadmin")) { if(args.length > 0) { if(args[0].equalsIgnoreCase("reload")) { reload(); sender.sendMessage(ChatColor.GREEN + "Configuration reloaded."); return true; } } } return false; }
diff --git a/dowsers-entity/src/main/java/com/intelligentsia/dowsers/entity/store/MetaEntityStoreSupport.java b/dowsers-entity/src/main/java/com/intelligentsia/dowsers/entity/store/MetaEntityStoreSupport.java index 8ae20a9..cf585ff 100755 --- a/dowsers-entity/src/main/java/com/intelligentsia/dowsers/entity/store/MetaEntityStoreSupport.java +++ b/dowsers-entity/src/main/java/com/intelligentsia/dowsers/entity/store/MetaEntityStoreSupport.java @@ -1,81 +1,86 @@ /** * 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 com.intelligentsia.dowsers.entity.store; import java.util.Collection; import com.google.common.base.Preconditions; import com.google.common.collect.Sets; import com.intelligentsia.dowsers.entity.meta.MetaEntity; import com.intelligentsia.dowsers.entity.reference.Reference; /** * MetaEntityStoreSupport. * * @author <a href="mailto:[email protected]" >Jerome Guibert</a> * */ public class MetaEntityStoreSupport implements MetaEntityStore { /** * Underlying {@link EntityStore}. */ private final EntityStore entityStore; /** * Build a new instance of MetaEntityStoreSupport.java. * * @param entityStore * @throws NullPointerException * if entityStore is null */ public MetaEntityStoreSupport(final EntityStore entityStore) throws NullPointerException { super(); this.entityStore = Preconditions.checkNotNull(entityStore); } @Override public Collection<MetaEntity> find(final Reference reference) throws NullPointerException { final Collection<MetaEntity> result = Sets.newLinkedHashSet(); + // we are looking for MetaEntity with attribute 'name' equals to + // EntityClassName in reference parameter. + Reference target = new Reference(MetaEntity.class, "name", Preconditions.checkNotNull(reference).getEntityClassName()); try { - result.add(entityStore.find(MetaEntity.class, Preconditions.checkNotNull(reference))); + for (Reference ref : entityStore.find(target)) { + result.add(entityStore.find(MetaEntity.class, ref)); + } } catch (final EntityNotFoundException entityNotFoundException) { // oups } return result; } @Override public void store(final MetaEntity entity) throws NullPointerException, ConcurrencyException, IllegalArgumentException { entityStore.store(entity); } @Override public void remove(final MetaEntity entity) throws NullPointerException, IllegalArgumentException { entityStore.remove(entity); } @Override public void remove(final Reference reference) throws NullPointerException, IllegalArgumentException { Preconditions.checkArgument(MetaEntity.class.getSimpleName().equals(Preconditions.checkNotNull(reference).getEntityClassName())); entityStore.remove(reference); } }
false
true
public Collection<MetaEntity> find(final Reference reference) throws NullPointerException { final Collection<MetaEntity> result = Sets.newLinkedHashSet(); try { result.add(entityStore.find(MetaEntity.class, Preconditions.checkNotNull(reference))); } catch (final EntityNotFoundException entityNotFoundException) { // oups } return result; }
public Collection<MetaEntity> find(final Reference reference) throws NullPointerException { final Collection<MetaEntity> result = Sets.newLinkedHashSet(); // we are looking for MetaEntity with attribute 'name' equals to // EntityClassName in reference parameter. Reference target = new Reference(MetaEntity.class, "name", Preconditions.checkNotNull(reference).getEntityClassName()); try { for (Reference ref : entityStore.find(target)) { result.add(entityStore.find(MetaEntity.class, ref)); } } catch (final EntityNotFoundException entityNotFoundException) { // oups } return result; }
diff --git a/src/main/java/net/paguo/trafshow/backend/snmp/summary/commands/impl/SearchTrafficDataCommandImpl.java b/src/main/java/net/paguo/trafshow/backend/snmp/summary/commands/impl/SearchTrafficDataCommandImpl.java index aaf9143..867335a 100644 --- a/src/main/java/net/paguo/trafshow/backend/snmp/summary/commands/impl/SearchTrafficDataCommandImpl.java +++ b/src/main/java/net/paguo/trafshow/backend/snmp/summary/commands/impl/SearchTrafficDataCommandImpl.java @@ -1,66 +1,66 @@ package net.paguo.trafshow.backend.snmp.summary.commands.impl; import net.paguo.trafshow.backend.snmp.summary.database.DBProxy; import net.paguo.trafshow.backend.snmp.summary.database.DBProxyFactory; import net.paguo.trafshow.backend.snmp.summary.model.RouterSummaryTraffic; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * @author Reyentenko */ public class SearchTrafficDataCommandImpl { private static final Log log = LogFactory.getLog(SearchTrafficDataCommandImpl.class); private Connection connection; public SearchTrafficDataCommandImpl() { } public final Long findRecordId(RouterSummaryTraffic record) { if (connection == null) { openConnection(); } Long result = null; try { PreparedStatement pst = connection.prepareStatement("select a_id from aggreg where cisco = ? and" + - " iface = ? and date = ?"); + " iface = ? and dat = ?"); pst.setString(1, record.getRouter()); pst.setString(2, record.getIface()); pst.setDate(3, new java.sql.Date(record.getDate().getTime())); ResultSet rs = pst.executeQuery(); if (rs.next()) { result = rs.getLong(1); } rs.close(); pst.close(); } catch (SQLException e) { log.error(e); } return result; } private void openConnection() { DBProxy proxy = DBProxyFactory.getDBProxy(); try { connection = proxy.getConnection(); } catch (SQLException e) { log.error(e); } } public void closeConnection() { if (connection != null) { try { connection.close(); } catch (SQLException e) { log.error(e); } } } }
true
true
public final Long findRecordId(RouterSummaryTraffic record) { if (connection == null) { openConnection(); } Long result = null; try { PreparedStatement pst = connection.prepareStatement("select a_id from aggreg where cisco = ? and" + " iface = ? and date = ?"); pst.setString(1, record.getRouter()); pst.setString(2, record.getIface()); pst.setDate(3, new java.sql.Date(record.getDate().getTime())); ResultSet rs = pst.executeQuery(); if (rs.next()) { result = rs.getLong(1); } rs.close(); pst.close(); } catch (SQLException e) { log.error(e); } return result; }
public final Long findRecordId(RouterSummaryTraffic record) { if (connection == null) { openConnection(); } Long result = null; try { PreparedStatement pst = connection.prepareStatement("select a_id from aggreg where cisco = ? and" + " iface = ? and dat = ?"); pst.setString(1, record.getRouter()); pst.setString(2, record.getIface()); pst.setDate(3, new java.sql.Date(record.getDate().getTime())); ResultSet rs = pst.executeQuery(); if (rs.next()) { result = rs.getLong(1); } rs.close(); pst.close(); } catch (SQLException e) { log.error(e); } return result; }
diff --git a/integration/mule1/src/test/java/org/mule/galaxy/mule1/RegistryConfigLookupTest.java b/integration/mule1/src/test/java/org/mule/galaxy/mule1/RegistryConfigLookupTest.java index b96edc69..05092f6d 100755 --- a/integration/mule1/src/test/java/org/mule/galaxy/mule1/RegistryConfigLookupTest.java +++ b/integration/mule1/src/test/java/org/mule/galaxy/mule1/RegistryConfigLookupTest.java @@ -1,65 +1,65 @@ package org.mule.galaxy.mule1; import java.io.InputStream; import java.util.List; import org.apache.abdera.i18n.text.UrlEncoding; import org.apache.abdera.model.Document; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.protocol.client.AbderaClient; import org.apache.abdera.protocol.client.ClientResponse; import org.apache.abdera.protocol.client.RequestOptions; import org.apache.axiom.om.util.Base64; import org.mule.galaxy.test.AbstractAtomTest; import org.mule.galaxy.util.IOUtils; public class RegistryConfigLookupTest extends AbstractAtomTest { public void testMuleLookup() throws Exception { AbderaClient client = new AbderaClient(abdera); String url = "http://localhost:9002/api/registry"; // // POST a Mule configuration // RequestOptions opts = new RequestOptions(); // opts.setContentType("application/xml; charset=utf-8"); // opts.setSlug("hello-config.xml"); // opts.setHeader("X-Artifact-Version", "0.1"); // opts.setHeader("X-Workspace", "Default Workspace"); // opts.setAuthorization("Basic " + Base64.encode("admin:admin".getBytes())); // ClientResponse res = client.post(url, getClass().getResourceAsStream("/mule/hello-config.xml"), opts); // assertEquals(201, res.getStatus()); // // TODO: this query language will improve in the future, so don't read too much into it yet - String search = UrlEncoding.encode("select artifact where mule2.service = 'GreeterUMO'"); + String search = UrlEncoding.encode("select artifact where mule.descriptor = 'GreeterUMO'"); url = url + "?q=" + search; // GET a Feed with Mule Configurations which match the criteria RequestOptions defaultOpts = client.getDefaultRequestOptions(); defaultOpts.setAuthorization("Basic " + Base64.encode("admin:admin".getBytes())); ClientResponse res = client.get(url, defaultOpts); assertEquals(200, res.getStatus()); Document<Feed> feedDoc = res.getDocument(); // prettyPrint(feedDoc); List<Entry> entries = feedDoc.getRoot().getEntries(); assertEquals(1, entries.size()); Entry entry = entries.get(0); // GET the actual mule configuration String muleConfigUrlLink = entry.getContentSrc().toString(); System.out.println(muleConfigUrlLink); res = client.get(muleConfigUrlLink, defaultOpts); assertEquals(200, res.getStatus()); // Use this as your handle to the mule configuration InputStream is = res.getInputStream(); IOUtils.copy(is, System.out); } protected String getWebappDirectory() { return "../../web/src/main/webapp"; } }
true
true
public void testMuleLookup() throws Exception { AbderaClient client = new AbderaClient(abdera); String url = "http://localhost:9002/api/registry"; // // POST a Mule configuration // RequestOptions opts = new RequestOptions(); // opts.setContentType("application/xml; charset=utf-8"); // opts.setSlug("hello-config.xml"); // opts.setHeader("X-Artifact-Version", "0.1"); // opts.setHeader("X-Workspace", "Default Workspace"); // opts.setAuthorization("Basic " + Base64.encode("admin:admin".getBytes())); // ClientResponse res = client.post(url, getClass().getResourceAsStream("/mule/hello-config.xml"), opts); // assertEquals(201, res.getStatus()); // // TODO: this query language will improve in the future, so don't read too much into it yet String search = UrlEncoding.encode("select artifact where mule2.service = 'GreeterUMO'"); url = url + "?q=" + search; // GET a Feed with Mule Configurations which match the criteria RequestOptions defaultOpts = client.getDefaultRequestOptions(); defaultOpts.setAuthorization("Basic " + Base64.encode("admin:admin".getBytes())); ClientResponse res = client.get(url, defaultOpts); assertEquals(200, res.getStatus()); Document<Feed> feedDoc = res.getDocument(); // prettyPrint(feedDoc); List<Entry> entries = feedDoc.getRoot().getEntries(); assertEquals(1, entries.size()); Entry entry = entries.get(0); // GET the actual mule configuration String muleConfigUrlLink = entry.getContentSrc().toString(); System.out.println(muleConfigUrlLink); res = client.get(muleConfigUrlLink, defaultOpts); assertEquals(200, res.getStatus()); // Use this as your handle to the mule configuration InputStream is = res.getInputStream(); IOUtils.copy(is, System.out); }
public void testMuleLookup() throws Exception { AbderaClient client = new AbderaClient(abdera); String url = "http://localhost:9002/api/registry"; // // POST a Mule configuration // RequestOptions opts = new RequestOptions(); // opts.setContentType("application/xml; charset=utf-8"); // opts.setSlug("hello-config.xml"); // opts.setHeader("X-Artifact-Version", "0.1"); // opts.setHeader("X-Workspace", "Default Workspace"); // opts.setAuthorization("Basic " + Base64.encode("admin:admin".getBytes())); // ClientResponse res = client.post(url, getClass().getResourceAsStream("/mule/hello-config.xml"), opts); // assertEquals(201, res.getStatus()); // // TODO: this query language will improve in the future, so don't read too much into it yet String search = UrlEncoding.encode("select artifact where mule.descriptor = 'GreeterUMO'"); url = url + "?q=" + search; // GET a Feed with Mule Configurations which match the criteria RequestOptions defaultOpts = client.getDefaultRequestOptions(); defaultOpts.setAuthorization("Basic " + Base64.encode("admin:admin".getBytes())); ClientResponse res = client.get(url, defaultOpts); assertEquals(200, res.getStatus()); Document<Feed> feedDoc = res.getDocument(); // prettyPrint(feedDoc); List<Entry> entries = feedDoc.getRoot().getEntries(); assertEquals(1, entries.size()); Entry entry = entries.get(0); // GET the actual mule configuration String muleConfigUrlLink = entry.getContentSrc().toString(); System.out.println(muleConfigUrlLink); res = client.get(muleConfigUrlLink, defaultOpts); assertEquals(200, res.getStatus()); // Use this as your handle to the mule configuration InputStream is = res.getInputStream(); IOUtils.copy(is, System.out); }
diff --git a/source/com/mucommander/shell/Shell.java b/source/com/mucommander/shell/Shell.java index 1a9e9d41..89a95e9c 100644 --- a/source/com/mucommander/shell/Shell.java +++ b/source/com/mucommander/shell/Shell.java @@ -1,139 +1,139 @@ package com.mucommander.shell; import com.mucommander.Debug; import com.mucommander.PlatformManager; import com.mucommander.conf.*; import com.mucommander.file.AbstractFile; import com.mucommander.file.impl.local.LocalFile; import com.mucommander.process.AbstractProcess; import com.mucommander.process.ProcessListener; import com.mucommander.process.ProcessRunner; import com.mucommander.command.CommandParser; import java.io.IOException; /** * @author Maxence Bernard, Nicolas Rinaudo */ public class Shell implements ConfigurationListener { // - Class variables ----------------------------------------------------- // ----------------------------------------------------------------------- /** Tokens that compose the shell command. */ private static String[] tokens; /** Tokens that compose remote shell commands. */ private static String[] remoteTokens; /** Instance of configuration listener. */ private static Shell confListener; // - Initialisation ------------------------------------------------------ // ----------------------------------------------------------------------- /** * Initialises the shell. */ static { ConfigurationManager.addConfigurationListener(confListener = new Shell()); // This could in theory also be written without the confListener reference. // It turns out, however, that proGuard is a bit too keen when removing fields // he thinks are not used. This code is written that way to make sure // confListener is not taken out, and the ConfigurationListener instance removed // instantly as there is only a WeakReference on it. // The things we have to do... confListener.setShellCommand(); remoteTokens = new String[1]; } /** * Prevents instances of Shell from being created. */ private Shell() {} // - Shell interaction --------------------------------------------------- // ----------------------------------------------------------------------- /** * Executes the specified command in the specified folder. * <p> * The <code>currentFolder</code> folder parameter will only be used if it's neither a * remote directory nor an archive. Otherwise, the command will run from the user's * home directory. * </p> * @param command command to run. * @param currentFolder where to run the command from. * @return the resulting process. * @exception IOException thrown if any error occurs while trying to run the command. */ public static AbstractProcess execute(String command, AbstractFile currentFolder) throws IOException {return execute(command, currentFolder, null);} /** * Executes the specified command in the specified folder. * <p> * The <code>currentFolder</code> folder parameter will only be used if it's neither a * remote directory nor an archive. Otherwise, the command will run from the user's * home directory. * </p> * <p> * Information about the resulting process will be sent to the specified <code>listener</code>. * </p> * @param command command to run. * @param currentFolder where to run the command from. * @param listener where to send information about the resulting process. * @return the resulting process. * @exception IOException thrown if any error occurs while trying to run the command. */ public static synchronized AbstractProcess execute(String command, AbstractFile currentFolder, ProcessListener listener) throws IOException { String[] commandTokens; if(Debug.ON) Debug.trace("Executing " + command); // Adds the command to history. ShellHistoryManager.add(command); // Builds the shell command. // Local files use the configuration defined shell. Remote files // will execute the command as-is. - if(currentFolder instanceof LocalFile) { + if(currentFolder instanceof LocalFile || !currentFolder.canRunProcess()) { tokens[tokens.length - 1] = command; commandTokens = tokens; } else { remoteTokens[0] = command; commandTokens = remoteTokens; } // Starts the process. return ProcessRunner.execute(commandTokens, currentFolder, listener); } // - Configuration management -------------------------------------------- // ----------------------------------------------------------------------- /** * Extracts the shell command from configuration. */ private static synchronized void setShellCommand() { String command; // Shell command. // Retrieves the configuration defined shell command. if(ConfigurationManager.getVariableBoolean(ConfigurationVariables.USE_CUSTOM_SHELL, ConfigurationVariables.DEFAULT_USE_CUSTOM_SHELL)) command = ConfigurationManager.getVariable(ConfigurationVariables.CUSTOM_SHELL, PlatformManager.getDefaultShellCommand()); else command = PlatformManager.getDefaultShellCommand(); // Splits the command into tokens, leaving room for the argument. tokens = CommandParser.getTokensWithParams(command, 1); } /** * Reacts to configuration changes. */ public boolean configurationChanged(ConfigurationEvent event) { if(event.getVariable().startsWith(ConfigurationVariables.SHELL_SECTION)) setShellCommand(); return true; } }
true
true
public static synchronized AbstractProcess execute(String command, AbstractFile currentFolder, ProcessListener listener) throws IOException { String[] commandTokens; if(Debug.ON) Debug.trace("Executing " + command); // Adds the command to history. ShellHistoryManager.add(command); // Builds the shell command. // Local files use the configuration defined shell. Remote files // will execute the command as-is. if(currentFolder instanceof LocalFile) { tokens[tokens.length - 1] = command; commandTokens = tokens; } else { remoteTokens[0] = command; commandTokens = remoteTokens; } // Starts the process. return ProcessRunner.execute(commandTokens, currentFolder, listener); }
public static synchronized AbstractProcess execute(String command, AbstractFile currentFolder, ProcessListener listener) throws IOException { String[] commandTokens; if(Debug.ON) Debug.trace("Executing " + command); // Adds the command to history. ShellHistoryManager.add(command); // Builds the shell command. // Local files use the configuration defined shell. Remote files // will execute the command as-is. if(currentFolder instanceof LocalFile || !currentFolder.canRunProcess()) { tokens[tokens.length - 1] = command; commandTokens = tokens; } else { remoteTokens[0] = command; commandTokens = remoteTokens; } // Starts the process. return ProcessRunner.execute(commandTokens, currentFolder, listener); }
diff --git a/maven-release-manager/src/main/java/org/apache/maven/shared/release/util/ReleaseUtil.java b/maven-release-manager/src/main/java/org/apache/maven/shared/release/util/ReleaseUtil.java index c102d03..1eb6be8 100644 --- a/maven-release-manager/src/main/java/org/apache/maven/shared/release/util/ReleaseUtil.java +++ b/maven-release-manager/src/main/java/org/apache/maven/shared/release/util/ReleaseUtil.java @@ -1,286 +1,287 @@ package org.apache.maven.shared.release.util; /* * 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. */ import java.io.File; import java.io.IOException; import java.io.Reader; import java.util.Iterator; import java.util.List; import java.util.Locale; import org.apache.commons.lang.StringUtils; import org.apache.maven.project.MavenProject; import org.apache.maven.shared.release.ReleaseExecutionException; import org.apache.maven.shared.release.config.ReleaseDescriptor; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.ReaderFactory; /** * @author <a href="mailto:[email protected]">Emmanuel Venisse</a> * @version $Id$ */ public class ReleaseUtil { public static final String RELEASE_POMv4 = "release-pom.xml"; public static final String POMv4 = "pom.xml"; private static final String FS = File.separator; /** * The line separator to use. */ public static final String LS = System.getProperty( "line.separator" ); private ReleaseUtil() { // noop } public static MavenProject getRootProject( List<MavenProject> reactorProjects ) { MavenProject project = (MavenProject) reactorProjects.get( 0 ); for ( Iterator<MavenProject> i = reactorProjects.iterator(); i.hasNext(); ) { MavenProject currentProject = i.next(); if ( currentProject.isExecutionRoot() ) { project = currentProject; break; } } return project; } public static File getStandardPom( MavenProject project ) { if ( project == null ) { return null; } File pom = project.getFile(); if ( pom == null ) { return null; } File releasePom = getReleasePom( project ); if ( pom.equals( releasePom ) ) { pom = new File( pom.getParent(), POMv4 ); } return pom; } public static File getReleasePom( MavenProject project ) { if ( project == null ) { return null; } File pom = project.getFile(); if ( pom == null ) { return null; } return new File( pom.getParent(), RELEASE_POMv4 ); } /** * Gets the string contents of the specified XML file. Note: In contrast to an XML processor, the line separators in * the returned string will be normalized to use the platform's native line separator. This is basically to save * another normalization step when writing the string contents back to an XML file. * * @param file The path to the XML file to read in, must not be <code>null</code>. * @return The string contents of the XML file. * @throws IOException If the file could not be opened/read. */ public static String readXmlFile( File file ) throws IOException { return readXmlFile( file, LS ); } public static String readXmlFile( File file, String ls ) throws IOException { Reader reader = null; try { reader = ReaderFactory.newXmlReader( file ); return normalizeLineEndings( IOUtil.toString( reader ), ls ); } finally { IOUtil.close( reader ); } } /** * Normalizes the line separators in the specified string. * * @param text The string to normalize, may be <code>null</code>. * @param separator The line separator to use for normalization, typically "\n" or "\r\n", must not be * <code>null</code>. * @return The input string with normalized line separators or <code>null</code> if the string was <code>null</code> * . */ public static String normalizeLineEndings( String text, String separator ) { String norm = text; if ( text != null ) { norm = text.replaceAll( "(\r\n)|(\n)|(\r)", separator ); } return norm; } public static ReleaseDescriptor createBasedirAlignedReleaseDescriptor( ReleaseDescriptor releaseDescriptor, List<MavenProject> reactorProjects ) throws ReleaseExecutionException { String basedir; try { basedir = getCommonBasedir( reactorProjects ); } catch ( IOException e ) { throw new ReleaseExecutionException( "Exception occurred while calculating common basedir: " + e.getMessage(), e ); } int parentLevels = getBaseWorkingDirectoryParentCount( basedir, FileUtils.normalize( releaseDescriptor.getWorkingDirectory() ) ); String url = releaseDescriptor.getScmSourceUrl(); url = realignScmUrl( parentLevels, url ); ReleaseDescriptor descriptor = new ReleaseDescriptor(); descriptor.setWorkingDirectory( basedir ); descriptor.setScmSourceUrl( url ); return descriptor; } public static String getCommonBasedir( List<MavenProject> reactorProjects ) throws IOException { return getCommonBasedir( reactorProjects, FS ); } public static String getCommonBasedir( List<MavenProject> reactorProjects, String separator ) throws IOException { String[] baseDirs = new String[reactorProjects.size()]; int idx = 0; for ( Iterator<MavenProject> i = reactorProjects.iterator(); i.hasNext(); ) { MavenProject p = i.next(); String dir = p.getBasedir().getCanonicalPath(); // always end with separator so that we know what is a path and what is a partial directory name in the // next call if ( !dir.endsWith( separator ) ) { dir = dir + separator; } baseDirs[idx++] = dir; } String basedir = StringUtils.getCommonPrefix( baseDirs ); - if ( !basedir.endsWith( separator ) ) + int separatorPos = basedir.lastIndexOf( separator ); + if ( !basedir.endsWith( separator ) && separatorPos >= 0 ) { - basedir = basedir.substring( 0, basedir.lastIndexOf( separator ) ); + basedir = basedir.substring( 0, separatorPos ); } if ( basedir.endsWith( separator ) && basedir.length() > 1 ) { basedir = basedir.substring( 0, basedir.length() - 1 ); } return basedir; } public static int getBaseWorkingDirectoryParentCount( String basedir, String workingDirectory ) { int num = 0; // we can safely assume case-insensitivity as we are just backtracking, not comparing. This helps with issues // on Windows with C: vs c: workingDirectory = workingDirectory.toLowerCase( Locale.ENGLISH ); basedir = basedir.toLowerCase( Locale.ENGLISH ); File workingDirectoryFile = new File( workingDirectory ); File basedirFile = new File( basedir ); if ( !workingDirectoryFile.equals( basedirFile ) && workingDirectory.startsWith( basedir ) ) { do { workingDirectoryFile = workingDirectoryFile.getParentFile(); num++; } while ( !workingDirectoryFile.equals( basedirFile ) ); } return num; } public static String realignScmUrl( int parentLevels, String url ) { if ( !StringUtils.isEmpty( url ) ) { int index = url.length(); String suffix = ""; if ( url.endsWith( "/" ) ) { index--; suffix = "/"; } for ( int i = 0; i < parentLevels && index > 0; i++ ) { index = url.lastIndexOf( '/', index - 1 ); } if ( index > 0 ) { url = url.substring( 0, index ) + suffix; } } return url; } public static boolean isSymlink( File file ) throws IOException { return !file.getAbsolutePath().equals( file.getCanonicalPath() ); } }
false
true
public static String getCommonBasedir( List<MavenProject> reactorProjects, String separator ) throws IOException { String[] baseDirs = new String[reactorProjects.size()]; int idx = 0; for ( Iterator<MavenProject> i = reactorProjects.iterator(); i.hasNext(); ) { MavenProject p = i.next(); String dir = p.getBasedir().getCanonicalPath(); // always end with separator so that we know what is a path and what is a partial directory name in the // next call if ( !dir.endsWith( separator ) ) { dir = dir + separator; } baseDirs[idx++] = dir; } String basedir = StringUtils.getCommonPrefix( baseDirs ); if ( !basedir.endsWith( separator ) ) { basedir = basedir.substring( 0, basedir.lastIndexOf( separator ) ); } if ( basedir.endsWith( separator ) && basedir.length() > 1 ) { basedir = basedir.substring( 0, basedir.length() - 1 ); } return basedir; }
public static String getCommonBasedir( List<MavenProject> reactorProjects, String separator ) throws IOException { String[] baseDirs = new String[reactorProjects.size()]; int idx = 0; for ( Iterator<MavenProject> i = reactorProjects.iterator(); i.hasNext(); ) { MavenProject p = i.next(); String dir = p.getBasedir().getCanonicalPath(); // always end with separator so that we know what is a path and what is a partial directory name in the // next call if ( !dir.endsWith( separator ) ) { dir = dir + separator; } baseDirs[idx++] = dir; } String basedir = StringUtils.getCommonPrefix( baseDirs ); int separatorPos = basedir.lastIndexOf( separator ); if ( !basedir.endsWith( separator ) && separatorPos >= 0 ) { basedir = basedir.substring( 0, separatorPos ); } if ( basedir.endsWith( separator ) && basedir.length() > 1 ) { basedir = basedir.substring( 0, basedir.length() - 1 ); } return basedir; }
diff --git a/src/main/java/org/agmip/ui/quadui/ApplyDomeTask.java b/src/main/java/org/agmip/ui/quadui/ApplyDomeTask.java index 7c0f6ce..5df43fb 100644 --- a/src/main/java/org/agmip/ui/quadui/ApplyDomeTask.java +++ b/src/main/java/org/agmip/ui/quadui/ApplyDomeTask.java @@ -1,166 +1,167 @@ package org.agmip.ui.quadui; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.File; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import org.agmip.core.types.TranslatorInput; import org.agmip.dome.DomeUtil; import org.agmip.dome.Engine; import org.agmip.translators.csv.DomeInput; import org.agmip.util.MapUtil; import org.apache.pivot.util.concurrent.Task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ApplyDomeTask extends Task<HashMap> { private static Logger log = LoggerFactory.getLogger(ApplyDomeTask.class); private HashMap<String, HashMap<String, Object>> domes = new HashMap<String, HashMap<String, Object>>(); private HashMap source; private String mode; public ApplyDomeTask(String fieldFile, String strategyFile, String mode, HashMap m) { this.source = m; this.mode = mode; // Setup the domes here. if (mode.equals("strategy")) { loadDomeFile(strategyFile); } loadDomeFile(fieldFile); } private void loadDomeFile(String fileName) { String fileNameTest = fileName.toUpperCase(); log.debug("Loading DOME file: {}", fileName); if (fileNameTest.endsWith(".ZIP")) { log.debug("Entering Zip file handling"); ZipFile z = null; try { z = new ZipFile(fileName); Enumeration entries = z.entries(); while (entries.hasMoreElements()) { // Do we handle nested zips? Not yet. ZipEntry entry = (ZipEntry) entries.nextElement(); File zipFileName = new File(entry.getName()); if (zipFileName.getName().toLowerCase().endsWith(".csv") && ! zipFileName.getName().startsWith(".")) { log.debug("Processing file: {}", zipFileName.getName()); DomeInput translator = new DomeInput(); translator.readCSV(z.getInputStream(entry)); HashMap<String, Object> dome = translator.getDome(); log.debug("dome info: {}", dome.toString()); String domeName = DomeUtil.generateDomeName(dome); if (! domeName.equals("----")) { domes.put(domeName, new HashMap<String, Object>(dome)); } } } z.close(); } catch (Exception ex) { log.error("Error processing DOME file: {}", ex.getMessage()); HashMap<String, Object> d = new HashMap<String, Object>(); d.put("errors", ex.getMessage()); } } else if (fileNameTest.endsWith(".CSV")) { log.debug("Entering single file DOME handling"); try { DomeInput translator = new DomeInput(); HashMap<String, Object> dome = (HashMap<String, Object>) translator.readFile(fileName); String domeName = DomeUtil.generateDomeName(dome); log.debug("Dome name: {}", domeName); log.debug("Dome layout: {}", dome.toString()); domes.put(domeName, dome); } catch (Exception ex) { log.error("Error processing DOME file: {}", ex.getMessage()); HashMap<String, Object> d = new HashMap<String, Object>(); d.put("errors", ex.getMessage()); } } } @Override public HashMap<String, Object> execute() { // First extract all the domes and put them in a HashMap by DOME_NAME // The read the DOME_NAME field of the CSV file // Split the DOME_NAME, and then apply sequentially to the HashMap. // PLEASE NOTE: This can be a massive undertaking if the source map // is really large. Need to find optimization points. HashMap<String, Object> output = new HashMap<String, Object>(); //HashMap<String, ArrayList<HashMap<String, String>>> dome; // Load the dome if (domes.isEmpty()) { log.error("No DOME to apply."); HashMap<String, Object> d = new HashMap<String, Object>(); //d.put("domeinfo", new HashMap<String, String>()); d.put("domeoutput", source); return d; } // Flatten the data and apply the dome. Engine domeEngine; ArrayList<HashMap<String, Object>> flattenedData = MapUtil.flatPack(source); if (mode.equals("strategy")) { log.debug("Domes: {}", domes.toString()); log.debug("Entering Strategy mode!"); Engine generatorEngine; ArrayList<HashMap<String, Object>> strategyResults = new ArrayList<HashMap<String, Object>>(); for (HashMap<String, Object> entry : flattenedData) { String strategyName = MapUtil.getValueOr(entry, "seasonal_strategy", ""); log.debug("Looking for ss: {}", strategyName); if (! strategyName.equals("")) { if (domes.containsKey(strategyName)) { log.debug("Found strategyName"); generatorEngine = new Engine(domes.get(strategyName), true); generatorEngine.apply(entry); ArrayList<HashMap<String, Object>> newEntries = generatorEngine.runGenerators(entry); log.debug("New Entries to add: {}", newEntries.size()); strategyResults.addAll(newEntries); } else { log.error("Cannot find strategy: {}", strategyName); } } } log.debug("=== FINISHED GENERATION ==="); log.debug("Generated count: {}", strategyResults.size()); ArrayList<HashMap<String, Object>> exp = MapUtil.getRawPackageContents(source, "experiments"); exp.clear(); exp.addAll(strategyResults); flattenedData = MapUtil.flatPack(source); } for (HashMap<String, Object> entry : flattenedData) { String domeName = MapUtil.getValueOr(entry, "field_overlay", ""); if (! domeName.equals("")) { String tmp[] = domeName.split("[|]"); int tmpLength = tmp.length; for (int i=0; i < tmpLength; i++) { - log.debug("Looping for dome_name: {}", tmp[i]); - if (domes.containsKey(tmp[i])) { - domeEngine = new Engine(domes.get(tmp[i])); + String tmpDomeId = tmp[i].toUpperCase(); + log.debug("Looping for dome_name: {}", tmpDomeId); + if (domes.containsKey(tmpDomeId)) { + domeEngine = new Engine(domes.get(tmpDomeId)); domeEngine.apply(entry); } } } } output.put("domeoutput", MapUtil.bundle(flattenedData)); return output; } }
true
true
public HashMap<String, Object> execute() { // First extract all the domes and put them in a HashMap by DOME_NAME // The read the DOME_NAME field of the CSV file // Split the DOME_NAME, and then apply sequentially to the HashMap. // PLEASE NOTE: This can be a massive undertaking if the source map // is really large. Need to find optimization points. HashMap<String, Object> output = new HashMap<String, Object>(); //HashMap<String, ArrayList<HashMap<String, String>>> dome; // Load the dome if (domes.isEmpty()) { log.error("No DOME to apply."); HashMap<String, Object> d = new HashMap<String, Object>(); //d.put("domeinfo", new HashMap<String, String>()); d.put("domeoutput", source); return d; } // Flatten the data and apply the dome. Engine domeEngine; ArrayList<HashMap<String, Object>> flattenedData = MapUtil.flatPack(source); if (mode.equals("strategy")) { log.debug("Domes: {}", domes.toString()); log.debug("Entering Strategy mode!"); Engine generatorEngine; ArrayList<HashMap<String, Object>> strategyResults = new ArrayList<HashMap<String, Object>>(); for (HashMap<String, Object> entry : flattenedData) { String strategyName = MapUtil.getValueOr(entry, "seasonal_strategy", ""); log.debug("Looking for ss: {}", strategyName); if (! strategyName.equals("")) { if (domes.containsKey(strategyName)) { log.debug("Found strategyName"); generatorEngine = new Engine(domes.get(strategyName), true); generatorEngine.apply(entry); ArrayList<HashMap<String, Object>> newEntries = generatorEngine.runGenerators(entry); log.debug("New Entries to add: {}", newEntries.size()); strategyResults.addAll(newEntries); } else { log.error("Cannot find strategy: {}", strategyName); } } } log.debug("=== FINISHED GENERATION ==="); log.debug("Generated count: {}", strategyResults.size()); ArrayList<HashMap<String, Object>> exp = MapUtil.getRawPackageContents(source, "experiments"); exp.clear(); exp.addAll(strategyResults); flattenedData = MapUtil.flatPack(source); } for (HashMap<String, Object> entry : flattenedData) { String domeName = MapUtil.getValueOr(entry, "field_overlay", ""); if (! domeName.equals("")) { String tmp[] = domeName.split("[|]"); int tmpLength = tmp.length; for (int i=0; i < tmpLength; i++) { log.debug("Looping for dome_name: {}", tmp[i]); if (domes.containsKey(tmp[i])) { domeEngine = new Engine(domes.get(tmp[i])); domeEngine.apply(entry); } } } } output.put("domeoutput", MapUtil.bundle(flattenedData)); return output; }
public HashMap<String, Object> execute() { // First extract all the domes and put them in a HashMap by DOME_NAME // The read the DOME_NAME field of the CSV file // Split the DOME_NAME, and then apply sequentially to the HashMap. // PLEASE NOTE: This can be a massive undertaking if the source map // is really large. Need to find optimization points. HashMap<String, Object> output = new HashMap<String, Object>(); //HashMap<String, ArrayList<HashMap<String, String>>> dome; // Load the dome if (domes.isEmpty()) { log.error("No DOME to apply."); HashMap<String, Object> d = new HashMap<String, Object>(); //d.put("domeinfo", new HashMap<String, String>()); d.put("domeoutput", source); return d; } // Flatten the data and apply the dome. Engine domeEngine; ArrayList<HashMap<String, Object>> flattenedData = MapUtil.flatPack(source); if (mode.equals("strategy")) { log.debug("Domes: {}", domes.toString()); log.debug("Entering Strategy mode!"); Engine generatorEngine; ArrayList<HashMap<String, Object>> strategyResults = new ArrayList<HashMap<String, Object>>(); for (HashMap<String, Object> entry : flattenedData) { String strategyName = MapUtil.getValueOr(entry, "seasonal_strategy", ""); log.debug("Looking for ss: {}", strategyName); if (! strategyName.equals("")) { if (domes.containsKey(strategyName)) { log.debug("Found strategyName"); generatorEngine = new Engine(domes.get(strategyName), true); generatorEngine.apply(entry); ArrayList<HashMap<String, Object>> newEntries = generatorEngine.runGenerators(entry); log.debug("New Entries to add: {}", newEntries.size()); strategyResults.addAll(newEntries); } else { log.error("Cannot find strategy: {}", strategyName); } } } log.debug("=== FINISHED GENERATION ==="); log.debug("Generated count: {}", strategyResults.size()); ArrayList<HashMap<String, Object>> exp = MapUtil.getRawPackageContents(source, "experiments"); exp.clear(); exp.addAll(strategyResults); flattenedData = MapUtil.flatPack(source); } for (HashMap<String, Object> entry : flattenedData) { String domeName = MapUtil.getValueOr(entry, "field_overlay", ""); if (! domeName.equals("")) { String tmp[] = domeName.split("[|]"); int tmpLength = tmp.length; for (int i=0; i < tmpLength; i++) { String tmpDomeId = tmp[i].toUpperCase(); log.debug("Looping for dome_name: {}", tmpDomeId); if (domes.containsKey(tmpDomeId)) { domeEngine = new Engine(domes.get(tmpDomeId)); domeEngine.apply(entry); } } } } output.put("domeoutput", MapUtil.bundle(flattenedData)); return output; }
diff --git a/src/com/hydrasmp/godPowers/SlayCommand.java b/src/com/hydrasmp/godPowers/SlayCommand.java index 0577889..782cf41 100755 --- a/src/com/hydrasmp/godPowers/SlayCommand.java +++ b/src/com/hydrasmp/godPowers/SlayCommand.java @@ -1,133 +1,133 @@ package com.hydrasmp.godPowers; //import org.bukkit.World; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class SlayCommand implements CommandExecutor { private Player player, targetPlayer; private final godPowers plugin; public SlayCommand(godPowers instance) { plugin = instance; } public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { World world = sender instanceof Player ? ((Player) sender).getWorld() : plugin.getServer().getWorlds().get(0); String[] split = args; if(sender instanceof Player) { player = (Player) sender; if(player.hasPermission("godpowers.slay")) { if(split.length == 1) { targetPlayer = plugin.getServer().getPlayer(split[0]); if(targetPlayer==null) { player.sendMessage(ChatColor.RED + "The user "+split[0]+" does not exist or is not currently logged in."); } else if(plugin.godmodeEnabled.contains(targetPlayer.getName())) { player.sendMessage(ChatColor.RED + "Fool! You cannot kill a god!"); } else { targetPlayer.setHealth(0); plugin.dropDeadItems(targetPlayer); - player.sendMessage("ChatColor.BLUE + You have slain " + targetPlayer.getName() + "."); + player.sendMessage(ChatColor.BLUE + "You have slain " + targetPlayer.getName() + "."); targetPlayer.sendMessage(ChatColor.BLUE + "By the will of " + player.getName() + ", you have died."); } return true; } else if(split.length == 2) { targetPlayer = plugin.getServer().getPlayer(split[0]); if(targetPlayer==null) { player.sendMessage(ChatColor.RED + "The user "+split[0]+" does not exist or is not currently logged in."); return true; } else if(plugin.godmodeEnabled.contains(targetPlayer.getName())) { player.sendMessage(ChatColor.DARK_RED+"Fool! You cannot kill a god!"); return true; } if(split[1].equalsIgnoreCase("a") || split[1].equalsIgnoreCase("arrows")) { int x = -4; Location arrows = new Location(world, targetPlayer.getLocation().getX()+x, targetPlayer.getLocation().getY()+1, targetPlayer.getLocation().getZ()+x); while(arrows.getBlock().getTypeId() != 0) { arrows = new Location(world, targetPlayer.getLocation().getX()+x, targetPlayer.getLocation().getY()+1, targetPlayer.getLocation().getZ()+x); if(arrows.getBlock().getTypeId() == 0) break; else if(x > 4) break; } player.sendMessage(ChatColor.BLUE + "You slay " + targetPlayer.getName() + " with a volley of arrows!"); plugin.arrowKill.add(targetPlayer.getName()); } else if(split[1].equalsIgnoreCase("f") || split[1].equalsIgnoreCase("fire")) { player.sendMessage(ChatColor.BLUE + "You ignite " + targetPlayer.getName() + " for your amusement."); targetPlayer.setFireTicks(500); targetPlayer.sendMessage(ChatColor.BLUE + "The gods have lit you on fire for their amusement."); plugin.burn.add(targetPlayer.getName()); } else if(split[1].equalsIgnoreCase("d") || split[1].equalsIgnoreCase("drop")) { player.sendMessage(ChatColor.BLUE + "You drop " + targetPlayer.getName() + " from the heavens and watch them plummet to their doom."); targetPlayer.teleport(new Location(world, targetPlayer.getLocation().getX(), 1000, targetPlayer.getLocation().getZ())); targetPlayer.sendMessage(ChatColor.BLUE + "The gods drop you from the heavens."); } else if(split[1].equalsIgnoreCase("l") || split[1].equalsIgnoreCase("lightning")) { player.sendMessage(ChatColor.BLUE + "You strike " + targetPlayer.getName() + " with a bolt of lightning!"); player.getWorld().strikeLightning(targetPlayer.getLocation()); } else if(split[1].equalsIgnoreCase("c") || split[1].equalsIgnoreCase("curse")) { player.sendMessage(ChatColor.BLUE + "You cast a curse upon " + targetPlayer.getName() + "'s head!"); targetPlayer.sendMessage(ChatColor.DARK_PURPLE + "The gods have cast a deadly curse upon you!"); int id = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { public void run() { targetPlayer.damage(4); targetPlayer.sendMessage(ChatColor.DARK_PURPLE + "You feel your life ebbing away as the curse takes hold."); } }, 30L,30L); plugin.curse.put(targetPlayer.getName(), Integer.valueOf(id)); } else if(split[1].equalsIgnoreCase("v") || split[1].equalsIgnoreCase("void")) { player.sendMessage(ChatColor.BLUE + "You toss " + targetPlayer.getName() + " into the void!"); targetPlayer.sendMessage(ChatColor.DARK_GRAY + "The gods have cast you into the void."); Location voidLoc = targetPlayer.getLocation(); voidLoc.setY(0); targetPlayer.teleport(voidLoc); } return true; } else { player.sendMessage(ChatColor.RED + "Incorrect syntax, use '/slay [playerName]'"); return true; } } else { player.sendMessage(ChatColor.DARK_RED + "The gods prevent you from using this command."); return true; } } return false; } }
true
true
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { World world = sender instanceof Player ? ((Player) sender).getWorld() : plugin.getServer().getWorlds().get(0); String[] split = args; if(sender instanceof Player) { player = (Player) sender; if(player.hasPermission("godpowers.slay")) { if(split.length == 1) { targetPlayer = plugin.getServer().getPlayer(split[0]); if(targetPlayer==null) { player.sendMessage(ChatColor.RED + "The user "+split[0]+" does not exist or is not currently logged in."); } else if(plugin.godmodeEnabled.contains(targetPlayer.getName())) { player.sendMessage(ChatColor.RED + "Fool! You cannot kill a god!"); } else { targetPlayer.setHealth(0); plugin.dropDeadItems(targetPlayer); player.sendMessage("ChatColor.BLUE + You have slain " + targetPlayer.getName() + "."); targetPlayer.sendMessage(ChatColor.BLUE + "By the will of " + player.getName() + ", you have died."); } return true; } else if(split.length == 2) { targetPlayer = plugin.getServer().getPlayer(split[0]); if(targetPlayer==null) { player.sendMessage(ChatColor.RED + "The user "+split[0]+" does not exist or is not currently logged in."); return true; } else if(plugin.godmodeEnabled.contains(targetPlayer.getName())) { player.sendMessage(ChatColor.DARK_RED+"Fool! You cannot kill a god!"); return true; } if(split[1].equalsIgnoreCase("a") || split[1].equalsIgnoreCase("arrows")) { int x = -4; Location arrows = new Location(world, targetPlayer.getLocation().getX()+x, targetPlayer.getLocation().getY()+1, targetPlayer.getLocation().getZ()+x); while(arrows.getBlock().getTypeId() != 0) { arrows = new Location(world, targetPlayer.getLocation().getX()+x, targetPlayer.getLocation().getY()+1, targetPlayer.getLocation().getZ()+x); if(arrows.getBlock().getTypeId() == 0) break; else if(x > 4) break; } player.sendMessage(ChatColor.BLUE + "You slay " + targetPlayer.getName() + " with a volley of arrows!"); plugin.arrowKill.add(targetPlayer.getName()); } else if(split[1].equalsIgnoreCase("f") || split[1].equalsIgnoreCase("fire")) { player.sendMessage(ChatColor.BLUE + "You ignite " + targetPlayer.getName() + " for your amusement."); targetPlayer.setFireTicks(500); targetPlayer.sendMessage(ChatColor.BLUE + "The gods have lit you on fire for their amusement."); plugin.burn.add(targetPlayer.getName()); } else if(split[1].equalsIgnoreCase("d") || split[1].equalsIgnoreCase("drop")) { player.sendMessage(ChatColor.BLUE + "You drop " + targetPlayer.getName() + " from the heavens and watch them plummet to their doom."); targetPlayer.teleport(new Location(world, targetPlayer.getLocation().getX(), 1000, targetPlayer.getLocation().getZ())); targetPlayer.sendMessage(ChatColor.BLUE + "The gods drop you from the heavens."); } else if(split[1].equalsIgnoreCase("l") || split[1].equalsIgnoreCase("lightning")) { player.sendMessage(ChatColor.BLUE + "You strike " + targetPlayer.getName() + " with a bolt of lightning!"); player.getWorld().strikeLightning(targetPlayer.getLocation()); } else if(split[1].equalsIgnoreCase("c") || split[1].equalsIgnoreCase("curse")) { player.sendMessage(ChatColor.BLUE + "You cast a curse upon " + targetPlayer.getName() + "'s head!"); targetPlayer.sendMessage(ChatColor.DARK_PURPLE + "The gods have cast a deadly curse upon you!"); int id = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { public void run() { targetPlayer.damage(4); targetPlayer.sendMessage(ChatColor.DARK_PURPLE + "You feel your life ebbing away as the curse takes hold."); } }, 30L,30L); plugin.curse.put(targetPlayer.getName(), Integer.valueOf(id)); } else if(split[1].equalsIgnoreCase("v") || split[1].equalsIgnoreCase("void")) { player.sendMessage(ChatColor.BLUE + "You toss " + targetPlayer.getName() + " into the void!"); targetPlayer.sendMessage(ChatColor.DARK_GRAY + "The gods have cast you into the void."); Location voidLoc = targetPlayer.getLocation(); voidLoc.setY(0); targetPlayer.teleport(voidLoc); } return true; } else { player.sendMessage(ChatColor.RED + "Incorrect syntax, use '/slay [playerName]'"); return true; } } else { player.sendMessage(ChatColor.DARK_RED + "The gods prevent you from using this command."); return true; } } return false; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { World world = sender instanceof Player ? ((Player) sender).getWorld() : plugin.getServer().getWorlds().get(0); String[] split = args; if(sender instanceof Player) { player = (Player) sender; if(player.hasPermission("godpowers.slay")) { if(split.length == 1) { targetPlayer = plugin.getServer().getPlayer(split[0]); if(targetPlayer==null) { player.sendMessage(ChatColor.RED + "The user "+split[0]+" does not exist or is not currently logged in."); } else if(plugin.godmodeEnabled.contains(targetPlayer.getName())) { player.sendMessage(ChatColor.RED + "Fool! You cannot kill a god!"); } else { targetPlayer.setHealth(0); plugin.dropDeadItems(targetPlayer); player.sendMessage(ChatColor.BLUE + "You have slain " + targetPlayer.getName() + "."); targetPlayer.sendMessage(ChatColor.BLUE + "By the will of " + player.getName() + ", you have died."); } return true; } else if(split.length == 2) { targetPlayer = plugin.getServer().getPlayer(split[0]); if(targetPlayer==null) { player.sendMessage(ChatColor.RED + "The user "+split[0]+" does not exist or is not currently logged in."); return true; } else if(plugin.godmodeEnabled.contains(targetPlayer.getName())) { player.sendMessage(ChatColor.DARK_RED+"Fool! You cannot kill a god!"); return true; } if(split[1].equalsIgnoreCase("a") || split[1].equalsIgnoreCase("arrows")) { int x = -4; Location arrows = new Location(world, targetPlayer.getLocation().getX()+x, targetPlayer.getLocation().getY()+1, targetPlayer.getLocation().getZ()+x); while(arrows.getBlock().getTypeId() != 0) { arrows = new Location(world, targetPlayer.getLocation().getX()+x, targetPlayer.getLocation().getY()+1, targetPlayer.getLocation().getZ()+x); if(arrows.getBlock().getTypeId() == 0) break; else if(x > 4) break; } player.sendMessage(ChatColor.BLUE + "You slay " + targetPlayer.getName() + " with a volley of arrows!"); plugin.arrowKill.add(targetPlayer.getName()); } else if(split[1].equalsIgnoreCase("f") || split[1].equalsIgnoreCase("fire")) { player.sendMessage(ChatColor.BLUE + "You ignite " + targetPlayer.getName() + " for your amusement."); targetPlayer.setFireTicks(500); targetPlayer.sendMessage(ChatColor.BLUE + "The gods have lit you on fire for their amusement."); plugin.burn.add(targetPlayer.getName()); } else if(split[1].equalsIgnoreCase("d") || split[1].equalsIgnoreCase("drop")) { player.sendMessage(ChatColor.BLUE + "You drop " + targetPlayer.getName() + " from the heavens and watch them plummet to their doom."); targetPlayer.teleport(new Location(world, targetPlayer.getLocation().getX(), 1000, targetPlayer.getLocation().getZ())); targetPlayer.sendMessage(ChatColor.BLUE + "The gods drop you from the heavens."); } else if(split[1].equalsIgnoreCase("l") || split[1].equalsIgnoreCase("lightning")) { player.sendMessage(ChatColor.BLUE + "You strike " + targetPlayer.getName() + " with a bolt of lightning!"); player.getWorld().strikeLightning(targetPlayer.getLocation()); } else if(split[1].equalsIgnoreCase("c") || split[1].equalsIgnoreCase("curse")) { player.sendMessage(ChatColor.BLUE + "You cast a curse upon " + targetPlayer.getName() + "'s head!"); targetPlayer.sendMessage(ChatColor.DARK_PURPLE + "The gods have cast a deadly curse upon you!"); int id = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { public void run() { targetPlayer.damage(4); targetPlayer.sendMessage(ChatColor.DARK_PURPLE + "You feel your life ebbing away as the curse takes hold."); } }, 30L,30L); plugin.curse.put(targetPlayer.getName(), Integer.valueOf(id)); } else if(split[1].equalsIgnoreCase("v") || split[1].equalsIgnoreCase("void")) { player.sendMessage(ChatColor.BLUE + "You toss " + targetPlayer.getName() + " into the void!"); targetPlayer.sendMessage(ChatColor.DARK_GRAY + "The gods have cast you into the void."); Location voidLoc = targetPlayer.getLocation(); voidLoc.setY(0); targetPlayer.teleport(voidLoc); } return true; } else { player.sendMessage(ChatColor.RED + "Incorrect syntax, use '/slay [playerName]'"); return true; } } else { player.sendMessage(ChatColor.DARK_RED + "The gods prevent you from using this command."); return true; } } return false; }
diff --git a/src/test/java/io/cloudsoft/socialapps/drupal/DrupalTest.java b/src/test/java/io/cloudsoft/socialapps/drupal/DrupalTest.java index 2a4ce42..9b2b36d 100644 --- a/src/test/java/io/cloudsoft/socialapps/drupal/DrupalTest.java +++ b/src/test/java/io/cloudsoft/socialapps/drupal/DrupalTest.java @@ -1,63 +1,63 @@ package io.cloudsoft.socialapps.drupal; import brooklyn.entity.basic.Entities; import brooklyn.entity.database.mysql.MySqlNode; import brooklyn.event.basic.DependentConfiguration; import brooklyn.location.basic.SshMachineLocation; import brooklyn.test.HttpTestUtils; import brooklyn.test.entity.TestApplication; import brooklyn.util.MutableMap; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.Arrays; import java.util.Map; public class DrupalTest { private SshMachineLocation location; private final static String SCRIPT = "create database drupal; " + "GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES ON drupal.* TO 'drupal'@'localhost' IDENTIFIED BY 'password'; " + "GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES ON drupal.* TO 'drupal'@'127.0.0.1' IDENTIFIED BY 'password'; " + "GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES ON drupal.* TO 'drupal'@'%' IDENTIFIED BY 'password';" + "FLUSH PRIVILEGES;"; private TestApplication app; @BeforeMethod(alwaysRun = true) public void setUp() { Map map = MutableMap.of("user", "root", "address", "someip", "password", "somepassword"); location = new SshMachineLocation(map); app = new TestApplication(); } @AfterMethod(alwaysRun = true) public void tearDown() { if (app != null) Entities.destroy(app); } @Test(groups = "Live") public void test() { Map mysqlConf = MutableMap.of("creationScriptContents", SCRIPT); MySqlNode mySqlNode = new MySqlNode(mysqlConf, app); - brooklyn.entity.webapp.drupal.Drupal drupal = new brooklyn.entity.webapp.drupal.Drupal(app); - drupal.setConfig(brooklyn.entity.webapp.drupal.Drupal.DATABASE_HOST, "127.0.0.1"); - drupal.setConfig(brooklyn.entity.webapp.drupal.Drupal.DATABASE_SCHEMA, "drupal"); - drupal.setConfig(brooklyn.entity.webapp.drupal.Drupal.DATABASE_USER, "drupal"); - drupal.setConfig(brooklyn.entity.webapp.drupal.Drupal.DATABASE_PORT, DependentConfiguration.attributeWhenReady(mySqlNode, MySqlNode.MYSQL_PORT)); - drupal.setConfig(brooklyn.entity.webapp.drupal.Drupal.DATABASE_PASSWORD, "password"); - drupal.setConfig(brooklyn.entity.webapp.drupal.Drupal.ADMIN_EMAIL, "[email protected]"); - drupal.setConfig(brooklyn.entity.webapp.drupal.Drupal.DATABASE_UP, DependentConfiguration.attributeWhenReady(mySqlNode, MySqlNode.SERVICE_UP)); + Drupal drupal = new Drupal(app); + drupal.setConfig(Drupal.DATABASE_HOST, "127.0.0.1"); + drupal.setConfig(Drupal.DATABASE_SCHEMA, "drupal"); + drupal.setConfig(Drupal.DATABASE_USER, "drupal"); + drupal.setConfig(Drupal.DATABASE_PORT, DependentConfiguration.attributeWhenReady(mySqlNode, MySqlNode.MYSQL_PORT)); + drupal.setConfig(Drupal.DATABASE_PASSWORD, "password"); + drupal.setConfig(Drupal.ADMIN_EMAIL, "[email protected]"); + drupal.setConfig(Drupal.DATABASE_UP, DependentConfiguration.attributeWhenReady(mySqlNode, MySqlNode.SERVICE_UP)); Entities.startManagement(app); app.start(Arrays.asList(location)); - HttpTestUtils.assertContentEventuallyContainsText("http://" + drupal.getAttribute(brooklyn.entity.webapp.drupal.Drupal.HOSTNAME) + "/index.php", "Welcome"); + HttpTestUtils.assertContentEventuallyContainsText("http://" + drupal.getAttribute(Drupal.HOSTNAME) + "/index.php", "Welcome"); } }
false
true
public void test() { Map mysqlConf = MutableMap.of("creationScriptContents", SCRIPT); MySqlNode mySqlNode = new MySqlNode(mysqlConf, app); brooklyn.entity.webapp.drupal.Drupal drupal = new brooklyn.entity.webapp.drupal.Drupal(app); drupal.setConfig(brooklyn.entity.webapp.drupal.Drupal.DATABASE_HOST, "127.0.0.1"); drupal.setConfig(brooklyn.entity.webapp.drupal.Drupal.DATABASE_SCHEMA, "drupal"); drupal.setConfig(brooklyn.entity.webapp.drupal.Drupal.DATABASE_USER, "drupal"); drupal.setConfig(brooklyn.entity.webapp.drupal.Drupal.DATABASE_PORT, DependentConfiguration.attributeWhenReady(mySqlNode, MySqlNode.MYSQL_PORT)); drupal.setConfig(brooklyn.entity.webapp.drupal.Drupal.DATABASE_PASSWORD, "password"); drupal.setConfig(brooklyn.entity.webapp.drupal.Drupal.ADMIN_EMAIL, "[email protected]"); drupal.setConfig(brooklyn.entity.webapp.drupal.Drupal.DATABASE_UP, DependentConfiguration.attributeWhenReady(mySqlNode, MySqlNode.SERVICE_UP)); Entities.startManagement(app); app.start(Arrays.asList(location)); HttpTestUtils.assertContentEventuallyContainsText("http://" + drupal.getAttribute(brooklyn.entity.webapp.drupal.Drupal.HOSTNAME) + "/index.php", "Welcome"); }
public void test() { Map mysqlConf = MutableMap.of("creationScriptContents", SCRIPT); MySqlNode mySqlNode = new MySqlNode(mysqlConf, app); Drupal drupal = new Drupal(app); drupal.setConfig(Drupal.DATABASE_HOST, "127.0.0.1"); drupal.setConfig(Drupal.DATABASE_SCHEMA, "drupal"); drupal.setConfig(Drupal.DATABASE_USER, "drupal"); drupal.setConfig(Drupal.DATABASE_PORT, DependentConfiguration.attributeWhenReady(mySqlNode, MySqlNode.MYSQL_PORT)); drupal.setConfig(Drupal.DATABASE_PASSWORD, "password"); drupal.setConfig(Drupal.ADMIN_EMAIL, "[email protected]"); drupal.setConfig(Drupal.DATABASE_UP, DependentConfiguration.attributeWhenReady(mySqlNode, MySqlNode.SERVICE_UP)); Entities.startManagement(app); app.start(Arrays.asList(location)); HttpTestUtils.assertContentEventuallyContainsText("http://" + drupal.getAttribute(Drupal.HOSTNAME) + "/index.php", "Welcome"); }
diff --git a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/cocoon/ThemeMatcher.java b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/cocoon/ThemeMatcher.java index 6b8fcf313..2789a7573 100644 --- a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/cocoon/ThemeMatcher.java +++ b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/cocoon/ThemeMatcher.java @@ -1,152 +1,152 @@ /** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.cocoon; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import org.apache.avalon.framework.logger.AbstractLogEnabled; import org.apache.avalon.framework.parameters.Parameters; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; import org.apache.cocoon.matching.Matcher; import org.apache.cocoon.sitemap.PatternException; import org.dspace.app.xmlui.configuration.XMLUIConfiguration; import org.dspace.app.xmlui.configuration.Theme; import org.dspace.app.xmlui.utils.HandleUtil; import org.dspace.content.DSpaceObject; import org.dspace.core.ConfigurationManager; /** * This class determines the correct Theme to apply to the URL. This is * determined by the Theme rules defined in the xmlui.xml configuration file. * Each rule is evaluated in order and the first rule to match is the selected * Theme. * * Once the Theme has been selected the following sitemap parameters are * provided: {themeName} is a unique name for the Theme, and {theme} is the * theme's path. * * @author Scott Phillips */ public class ThemeMatcher extends AbstractLogEnabled implements Matcher { /** * @param src * name of sitemap parameter to find (ignored) * @param objectModel * environment passed through via cocoon * @param parameters * parameters passed to this matcher in the sitemap * @return null or map containing value of sitemap parameter 'src' */ public Map match(String src, Map objectModel, Parameters parameters) throws PatternException { try { Request request = ObjectModelHelper.getRequest(objectModel); String uri = request.getSitemapURI(); DSpaceObject dso = HandleUtil.obtainHandle(objectModel); // Allow the user to override the theme configuration if (ConfigurationManager.getBooleanProperty("xmlui.theme.allowoverrides",false)) { String themePathOverride = request.getParameter("themepath"); if (themePathOverride != null && themePathOverride.length() > 0) { // Allowing the user to specify the theme path is a security risk because it // allows the user to direct which sitemap is executed next. An attacker could // use this in combination with another attack execute code on the server. // Ultimately this option should not be turned on in a production system and // only used in development. However lets do some simple sanity checks to // protect us a little even when under development. // Allow: allow all letters and numbers plus periods (but not consecutive), // dashes, underscores, and forward slashes - if (!themePathOverride.matches("^[a-zA-V0-9][a-zA-Z0-9/_\\-]*/?$")) { + if (!themePathOverride.matches("^[a-zA-Z0-9][a-zA-Z0-9/_\\-]*/?$")) { throw new IllegalArgumentException("The user specified theme path, \""+themePathOverride+"\", may be " + "an exploit attempt. To use this feature please limit your theme paths to only letters " + "(a-Z), numbers(0-9), dashes(-), underscores (_), and trailing forward slashes (/)."); } // The user is selecting to override a theme, ignore any set // rules to apply and use the one specified. String themeNameOverride = request.getParameter("themename"); String themeIdOverride = request.getParameter("themeid"); if (themeNameOverride == null || themeNameOverride.length() == 0) { themeNameOverride = "User specified theme"; } getLogger().debug("User as specified to override theme selection with theme "+ "(name=\""+themeNameOverride+"\", path=\""+themePathOverride+"\", id=\""+themeIdOverride+"\")"); Map<String, String> result = new HashMap<String, String>(); result.put("themeName", themeNameOverride); result.put("theme", themePathOverride); result.put("themeID", themeIdOverride); return result; } } List<Theme> rules = XMLUIConfiguration.getThemeRules(); getLogger().debug("Checking if URL=" + uri + " matches any theme rules."); for (Theme rule : rules) { getLogger().debug("rule=" + rule.getName()); if (!(rule.hasRegex() || rule.hasHandle())) { // Skip any rule with out a pattern or handle continue; } getLogger().debug("checking for patterns"); if (rule.hasRegex()) { // If the rule has a pattern insure that the URL matches it. Pattern pattern = rule.getPattern(); if (!pattern.matcher(uri).find()) { continue; } } getLogger().debug("checking for handles"); if (rule.hasHandle() && !HandleUtil.inheritsFrom(dso, rule.getHandle())) { continue; } getLogger().debug("rule selected!!"); Map<String, String> result = new HashMap<String, String>(); result.put("themeName", rule.getName()); result.put("theme", rule.getPath()); result.put("themeID", rule.getId()); request.getSession().setAttribute("themeName", rule.getName()); request.getSession().setAttribute("theme", rule.getPath()); request.getSession().setAttribute("themeID", rule.getId()); return result; } } catch (SQLException sqle) { throw new PatternException(sqle); } // No themes matched. return null; } }
true
true
public Map match(String src, Map objectModel, Parameters parameters) throws PatternException { try { Request request = ObjectModelHelper.getRequest(objectModel); String uri = request.getSitemapURI(); DSpaceObject dso = HandleUtil.obtainHandle(objectModel); // Allow the user to override the theme configuration if (ConfigurationManager.getBooleanProperty("xmlui.theme.allowoverrides",false)) { String themePathOverride = request.getParameter("themepath"); if (themePathOverride != null && themePathOverride.length() > 0) { // Allowing the user to specify the theme path is a security risk because it // allows the user to direct which sitemap is executed next. An attacker could // use this in combination with another attack execute code on the server. // Ultimately this option should not be turned on in a production system and // only used in development. However lets do some simple sanity checks to // protect us a little even when under development. // Allow: allow all letters and numbers plus periods (but not consecutive), // dashes, underscores, and forward slashes if (!themePathOverride.matches("^[a-zA-V0-9][a-zA-Z0-9/_\\-]*/?$")) { throw new IllegalArgumentException("The user specified theme path, \""+themePathOverride+"\", may be " + "an exploit attempt. To use this feature please limit your theme paths to only letters " + "(a-Z), numbers(0-9), dashes(-), underscores (_), and trailing forward slashes (/)."); } // The user is selecting to override a theme, ignore any set // rules to apply and use the one specified. String themeNameOverride = request.getParameter("themename"); String themeIdOverride = request.getParameter("themeid"); if (themeNameOverride == null || themeNameOverride.length() == 0) { themeNameOverride = "User specified theme"; } getLogger().debug("User as specified to override theme selection with theme "+ "(name=\""+themeNameOverride+"\", path=\""+themePathOverride+"\", id=\""+themeIdOverride+"\")"); Map<String, String> result = new HashMap<String, String>(); result.put("themeName", themeNameOverride); result.put("theme", themePathOverride); result.put("themeID", themeIdOverride); return result; } } List<Theme> rules = XMLUIConfiguration.getThemeRules(); getLogger().debug("Checking if URL=" + uri + " matches any theme rules."); for (Theme rule : rules) { getLogger().debug("rule=" + rule.getName()); if (!(rule.hasRegex() || rule.hasHandle())) { // Skip any rule with out a pattern or handle continue; } getLogger().debug("checking for patterns"); if (rule.hasRegex()) { // If the rule has a pattern insure that the URL matches it. Pattern pattern = rule.getPattern(); if (!pattern.matcher(uri).find()) { continue; } } getLogger().debug("checking for handles"); if (rule.hasHandle() && !HandleUtil.inheritsFrom(dso, rule.getHandle())) { continue; } getLogger().debug("rule selected!!"); Map<String, String> result = new HashMap<String, String>(); result.put("themeName", rule.getName()); result.put("theme", rule.getPath()); result.put("themeID", rule.getId()); request.getSession().setAttribute("themeName", rule.getName()); request.getSession().setAttribute("theme", rule.getPath()); request.getSession().setAttribute("themeID", rule.getId()); return result; } } catch (SQLException sqle) { throw new PatternException(sqle); } // No themes matched. return null; }
public Map match(String src, Map objectModel, Parameters parameters) throws PatternException { try { Request request = ObjectModelHelper.getRequest(objectModel); String uri = request.getSitemapURI(); DSpaceObject dso = HandleUtil.obtainHandle(objectModel); // Allow the user to override the theme configuration if (ConfigurationManager.getBooleanProperty("xmlui.theme.allowoverrides",false)) { String themePathOverride = request.getParameter("themepath"); if (themePathOverride != null && themePathOverride.length() > 0) { // Allowing the user to specify the theme path is a security risk because it // allows the user to direct which sitemap is executed next. An attacker could // use this in combination with another attack execute code on the server. // Ultimately this option should not be turned on in a production system and // only used in development. However lets do some simple sanity checks to // protect us a little even when under development. // Allow: allow all letters and numbers plus periods (but not consecutive), // dashes, underscores, and forward slashes if (!themePathOverride.matches("^[a-zA-Z0-9][a-zA-Z0-9/_\\-]*/?$")) { throw new IllegalArgumentException("The user specified theme path, \""+themePathOverride+"\", may be " + "an exploit attempt. To use this feature please limit your theme paths to only letters " + "(a-Z), numbers(0-9), dashes(-), underscores (_), and trailing forward slashes (/)."); } // The user is selecting to override a theme, ignore any set // rules to apply and use the one specified. String themeNameOverride = request.getParameter("themename"); String themeIdOverride = request.getParameter("themeid"); if (themeNameOverride == null || themeNameOverride.length() == 0) { themeNameOverride = "User specified theme"; } getLogger().debug("User as specified to override theme selection with theme "+ "(name=\""+themeNameOverride+"\", path=\""+themePathOverride+"\", id=\""+themeIdOverride+"\")"); Map<String, String> result = new HashMap<String, String>(); result.put("themeName", themeNameOverride); result.put("theme", themePathOverride); result.put("themeID", themeIdOverride); return result; } } List<Theme> rules = XMLUIConfiguration.getThemeRules(); getLogger().debug("Checking if URL=" + uri + " matches any theme rules."); for (Theme rule : rules) { getLogger().debug("rule=" + rule.getName()); if (!(rule.hasRegex() || rule.hasHandle())) { // Skip any rule with out a pattern or handle continue; } getLogger().debug("checking for patterns"); if (rule.hasRegex()) { // If the rule has a pattern insure that the URL matches it. Pattern pattern = rule.getPattern(); if (!pattern.matcher(uri).find()) { continue; } } getLogger().debug("checking for handles"); if (rule.hasHandle() && !HandleUtil.inheritsFrom(dso, rule.getHandle())) { continue; } getLogger().debug("rule selected!!"); Map<String, String> result = new HashMap<String, String>(); result.put("themeName", rule.getName()); result.put("theme", rule.getPath()); result.put("themeID", rule.getId()); request.getSession().setAttribute("themeName", rule.getName()); request.getSession().setAttribute("theme", rule.getPath()); request.getSession().setAttribute("themeID", rule.getId()); return result; } } catch (SQLException sqle) { throw new PatternException(sqle); } // No themes matched. return null; }
diff --git a/butterknife/src/main/java/butterknife/Views.java b/butterknife/src/main/java/butterknife/Views.java index fafa12a..8453b45 100644 --- a/butterknife/src/main/java/butterknife/Views.java +++ b/butterknife/src/main/java/butterknife/Views.java @@ -1,252 +1,253 @@ package butterknife; import android.app.Activity; import android.view.View; import java.io.IOException; import java.io.Writer; import java.lang.reflect.Method; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.tools.JavaFileObject; import static javax.lang.model.element.ElementKind.CLASS; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PROTECTED; import static javax.lang.model.element.Modifier.STATIC; import static javax.tools.Diagnostic.Kind.ERROR; public class Views { private Views() { // No instances. } private static final Map<Class<?>, Method> INJECTORS = new LinkedHashMap<Class<?>, Method>(); /** * Inject fields annotated with {@link InjectView} in the specified {@link Activity}. * * @param target Target activity for field injection. * @throws UnableToInjectException if injection could not be performed. */ public static void inject(Activity target) { inject(target, Activity.class, target); } /** * Inject fields annotated with {@link InjectView} in the specified {@code source} using {@code * target} as the view root. * * @param target Target class for field injection. * @param source View tree root on which IDs will be looked up. * @throws UnableToInjectException if injection could not be performed. */ public static void inject(Object target, View source) { inject(target, View.class, source); } private static void inject(Object target, Class<?> sourceType, Object source) { try { Class<?> targetClass = target.getClass(); Method inject = INJECTORS.get(targetClass); if (inject == null) { Class<?> injector = Class.forName(targetClass.getName() + AnnotationProcessor.SUFFIX); inject = injector.getMethod("inject", targetClass, sourceType); INJECTORS.put(targetClass, inject); } inject.invoke(null, target, source); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new UnableToInjectException("Unable to inject views for " + target, e); } } /** Simpler version of {@link View#findViewById(int)} which infers the target type. */ @SuppressWarnings({ "unchecked", "UnusedDeclaration" }) // Checked by runtime cast, helper method. public static <T extends View> T findById(View view, int id) { return (T) view.findViewById(id); } /** Simpler version of {@link Activity#findViewById(int)} which infers the target type. */ @SuppressWarnings({ "unchecked", "UnusedDeclaration" }) // Checked by runtime cast, helper method. public static <T extends View> T findById(Activity activity, int id) { return (T) activity.findViewById(id); } public static class UnableToInjectException extends RuntimeException { UnableToInjectException(String message, Throwable cause) { super(message, cause); } } @SupportedAnnotationTypes("butterknife.InjectView") public static class AnnotationProcessor extends AbstractProcessor { static final String SUFFIX = "$$ViewInjector"; @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } private void error(String message, Object... args) { processingEnv.getMessager().printMessage(ERROR, String.format(message, args)); } @Override public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) { TypeMirror viewType = processingEnv.getElementUtils().getTypeElement(TYPE_VIEW).asType(); Map<TypeElement, Set<InjectionPoint>> injectionsByClass = new LinkedHashMap<TypeElement, Set<InjectionPoint>>(); Set<TypeMirror> injectionTargets = new HashSet<TypeMirror>(); for (Element element : env.getElementsAnnotatedWith(InjectView.class)) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type extends from View. if (!processingEnv.getTypeUtils().isSubtype(element.asType(), viewType)) { error("@InjectView fields must extend from View (%s.%s).", enclosingElement.getQualifiedName(), element); continue; } // Verify field properties. Set<Modifier> modifiers = element.getModifiers(); if (modifiers.contains(PRIVATE) || modifiers.contains(PROTECTED) || modifiers.contains( STATIC)) { error("@InjectView fields must not be private, protected, or static (%s.%s).", enclosingElement.getQualifiedName(), element); continue; } // Verify containing type. if (enclosingElement.getKind() != CLASS) { error("@InjectView field annotations may only be specified in classes (%s).", element); continue; } // Get and optionally create a set of all injection points for a type. Set<InjectionPoint> injections = injectionsByClass.get(enclosingElement); if (injections == null) { injections = new HashSet<InjectionPoint>(); injectionsByClass.put(enclosingElement, injections); } // Assemble information on the injection point. String variableName = element.getSimpleName().toString(); String type = element.asType().toString(); int value = element.getAnnotation(InjectView.class).value(); injections.add(new InjectionPoint(variableName, type, value)); // Add to the valid injection targets set. injectionTargets.add(enclosingElement.asType()); } for (Map.Entry<TypeElement, Set<InjectionPoint>> injection : injectionsByClass.entrySet()) { TypeElement type = injection.getKey(); Set<InjectionPoint> injectionPoints = injection.getValue(); String targetType = type.getQualifiedName().toString(); String sourceType = resolveSourceType(type); - String packageName = processingEnv.getElementUtils().getPackageOf(type).toString(); + String packageName = + processingEnv.getElementUtils().getPackageOf(type).getQualifiedName().toString(); String className = type.getQualifiedName().toString().substring(packageName.length() + 1).replace('.', '$') + SUFFIX; String parentClass = resolveParentType(type, injectionTargets); StringBuilder injections = new StringBuilder(); if (parentClass != null) { injections.append(" ") .append(parentClass) .append(SUFFIX) .append(".inject(activity);\n\n"); } for (InjectionPoint injectionPoint : injectionPoints) { injections.append(injectionPoint).append("\n"); } // Write the view injector class. try { JavaFileObject jfo = processingEnv.getFiler().createSourceFile(packageName + "." + className, type); Writer writer = jfo.openWriter(); writer.write(String.format(INJECTOR, packageName, className, targetType, sourceType, injections.toString())); writer.flush(); writer.close(); } catch (IOException e) { error(e.getMessage()); } } return true; } /** Returns {@link #TYPE_ACTIVITY} or {@link #TYPE_VIEW} as the injection target type. */ private String resolveSourceType(TypeElement typeElement) { TypeMirror type; while (true) { type = typeElement.getSuperclass(); if (type.getKind() == TypeKind.NONE) { return TYPE_VIEW; } if (type.toString().equals(TYPE_ACTIVITY)) { return TYPE_ACTIVITY; } typeElement = (TypeElement) ((DeclaredType) type).asElement(); } } /** Finds the parent injector type in the supplied set, if any. */ private String resolveParentType(TypeElement typeElement, Set<TypeMirror> parents) { TypeMirror type; while (true) { type = typeElement.getSuperclass(); if (type.getKind() == TypeKind.NONE) { return null; } if (parents.contains(type)) { return type.toString(); } typeElement = (TypeElement) ((DeclaredType) type).asElement(); } } private static class InjectionPoint { private final String variableName; private final String type; private final int value; InjectionPoint(String variableName, String type, int value) { this.variableName = variableName; this.type = type; this.value = value; } @Override public String toString() { return String.format(INJECTION, variableName, type, value); } } private static final String TYPE_ACTIVITY = "android.app.Activity"; private static final String TYPE_VIEW = "android.view.View"; private static final String INJECTION = " target.%s = (%s) source.findViewById(%s);"; private static final String INJECTOR = "" + "// Generated code from Butter Knife. Do not modify!\n" + "package %s;\n\n" + "public class %s {\n" + " public static void inject(%s target, %s source) {\n" + "%s" + " }\n" + "}\n"; } }
true
true
@Override public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) { TypeMirror viewType = processingEnv.getElementUtils().getTypeElement(TYPE_VIEW).asType(); Map<TypeElement, Set<InjectionPoint>> injectionsByClass = new LinkedHashMap<TypeElement, Set<InjectionPoint>>(); Set<TypeMirror> injectionTargets = new HashSet<TypeMirror>(); for (Element element : env.getElementsAnnotatedWith(InjectView.class)) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type extends from View. if (!processingEnv.getTypeUtils().isSubtype(element.asType(), viewType)) { error("@InjectView fields must extend from View (%s.%s).", enclosingElement.getQualifiedName(), element); continue; } // Verify field properties. Set<Modifier> modifiers = element.getModifiers(); if (modifiers.contains(PRIVATE) || modifiers.contains(PROTECTED) || modifiers.contains( STATIC)) { error("@InjectView fields must not be private, protected, or static (%s.%s).", enclosingElement.getQualifiedName(), element); continue; } // Verify containing type. if (enclosingElement.getKind() != CLASS) { error("@InjectView field annotations may only be specified in classes (%s).", element); continue; } // Get and optionally create a set of all injection points for a type. Set<InjectionPoint> injections = injectionsByClass.get(enclosingElement); if (injections == null) { injections = new HashSet<InjectionPoint>(); injectionsByClass.put(enclosingElement, injections); } // Assemble information on the injection point. String variableName = element.getSimpleName().toString(); String type = element.asType().toString(); int value = element.getAnnotation(InjectView.class).value(); injections.add(new InjectionPoint(variableName, type, value)); // Add to the valid injection targets set. injectionTargets.add(enclosingElement.asType()); } for (Map.Entry<TypeElement, Set<InjectionPoint>> injection : injectionsByClass.entrySet()) { TypeElement type = injection.getKey(); Set<InjectionPoint> injectionPoints = injection.getValue(); String targetType = type.getQualifiedName().toString(); String sourceType = resolveSourceType(type); String packageName = processingEnv.getElementUtils().getPackageOf(type).toString(); String className = type.getQualifiedName().toString().substring(packageName.length() + 1).replace('.', '$') + SUFFIX; String parentClass = resolveParentType(type, injectionTargets); StringBuilder injections = new StringBuilder(); if (parentClass != null) { injections.append(" ") .append(parentClass) .append(SUFFIX) .append(".inject(activity);\n\n"); } for (InjectionPoint injectionPoint : injectionPoints) { injections.append(injectionPoint).append("\n"); } // Write the view injector class. try { JavaFileObject jfo = processingEnv.getFiler().createSourceFile(packageName + "." + className, type); Writer writer = jfo.openWriter(); writer.write(String.format(INJECTOR, packageName, className, targetType, sourceType, injections.toString())); writer.flush(); writer.close(); } catch (IOException e) { error(e.getMessage()); } } return true; }
@Override public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) { TypeMirror viewType = processingEnv.getElementUtils().getTypeElement(TYPE_VIEW).asType(); Map<TypeElement, Set<InjectionPoint>> injectionsByClass = new LinkedHashMap<TypeElement, Set<InjectionPoint>>(); Set<TypeMirror> injectionTargets = new HashSet<TypeMirror>(); for (Element element : env.getElementsAnnotatedWith(InjectView.class)) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type extends from View. if (!processingEnv.getTypeUtils().isSubtype(element.asType(), viewType)) { error("@InjectView fields must extend from View (%s.%s).", enclosingElement.getQualifiedName(), element); continue; } // Verify field properties. Set<Modifier> modifiers = element.getModifiers(); if (modifiers.contains(PRIVATE) || modifiers.contains(PROTECTED) || modifiers.contains( STATIC)) { error("@InjectView fields must not be private, protected, or static (%s.%s).", enclosingElement.getQualifiedName(), element); continue; } // Verify containing type. if (enclosingElement.getKind() != CLASS) { error("@InjectView field annotations may only be specified in classes (%s).", element); continue; } // Get and optionally create a set of all injection points for a type. Set<InjectionPoint> injections = injectionsByClass.get(enclosingElement); if (injections == null) { injections = new HashSet<InjectionPoint>(); injectionsByClass.put(enclosingElement, injections); } // Assemble information on the injection point. String variableName = element.getSimpleName().toString(); String type = element.asType().toString(); int value = element.getAnnotation(InjectView.class).value(); injections.add(new InjectionPoint(variableName, type, value)); // Add to the valid injection targets set. injectionTargets.add(enclosingElement.asType()); } for (Map.Entry<TypeElement, Set<InjectionPoint>> injection : injectionsByClass.entrySet()) { TypeElement type = injection.getKey(); Set<InjectionPoint> injectionPoints = injection.getValue(); String targetType = type.getQualifiedName().toString(); String sourceType = resolveSourceType(type); String packageName = processingEnv.getElementUtils().getPackageOf(type).getQualifiedName().toString(); String className = type.getQualifiedName().toString().substring(packageName.length() + 1).replace('.', '$') + SUFFIX; String parentClass = resolveParentType(type, injectionTargets); StringBuilder injections = new StringBuilder(); if (parentClass != null) { injections.append(" ") .append(parentClass) .append(SUFFIX) .append(".inject(activity);\n\n"); } for (InjectionPoint injectionPoint : injectionPoints) { injections.append(injectionPoint).append("\n"); } // Write the view injector class. try { JavaFileObject jfo = processingEnv.getFiler().createSourceFile(packageName + "." + className, type); Writer writer = jfo.openWriter(); writer.write(String.format(INJECTOR, packageName, className, targetType, sourceType, injections.toString())); writer.flush(); writer.close(); } catch (IOException e) { error(e.getMessage()); } } return true; }
diff --git a/plugins/core/com.vectorsf.jvoice.core.validation/src/com/vectorsf/jvoice/core/validation/operations/CallStateValidator.java b/plugins/core/com.vectorsf.jvoice.core.validation/src/com/vectorsf/jvoice/core/validation/operations/CallStateValidator.java index b642c463..17ba9186 100644 --- a/plugins/core/com.vectorsf.jvoice.core.validation/src/com/vectorsf/jvoice/core/validation/operations/CallStateValidator.java +++ b/plugins/core/com.vectorsf.jvoice.core.validation/src/com/vectorsf/jvoice/core/validation/operations/CallStateValidator.java @@ -1,73 +1,67 @@ package com.vectorsf.jvoice.core.validation.operations; import java.io.File; import com.vectorsf.jvoice.model.operations.CallState; import com.vectorsf.jvoice.model.operations.ComponentBean; import com.vectorsf.jvoice.model.operations.Flow; public class CallStateValidator { private final String PATH = "src/main/java"; private IOperationsValidator operationsValidator; public CallStateValidator(IOperationsValidator operationsValidator) { this.operationsValidator = operationsValidator; } public boolean validate_CallState_methodInstanceBeanExecutionState(CallState state) { Flow flow = (Flow) state.eContainer(); boolean existbean = false; for (ComponentBean bean : flow.getBeans()) { if (bean == state.getBean()) { existbean = true; } } if (!existbean) { operationsValidator.error(state, "Instance Bean " + state.getBean() + " not found"); } return true; } public boolean validate_CallState_exitsBeanInExecute(CallState state) { Flow flow = (Flow) state.eContainer(); File rawFile = ValidatorUtils.getFile(state); - System.out.println("****************** 1 rawFile " + rawFile); File projectFile = ValidatorUtils.findProjectFile(rawFile); - System.out.println("****************** 2 projectFile " + projectFile); String classbean; if (state.getBean() != null) { classbean = state.getBean().getFqdn(); - System.out.println("****************** 3 classbean " + classbean); File folder = new File(projectFile, PATH); - System.out.println("****************** 4 folder " + folder); File filepack = new File(folder, classbean.replace(".", "/").concat(".java")); - System.out.println("****************** 5 filepack " + filepack); - System.out.println("****************** 6 filepack.exists() " + filepack.exists()); if (!filepack.exists()) { operationsValidator.error(state, "No exits bean in execute state \"" + state.getName() + "\" in flow \"" + flow.getName() + "\""); } } return true; } public boolean validate_CallState_noEmptyParams(CallState state) { for (String param : state.getParameters()) { if (param.trim().isEmpty()) { operationsValidator.error(state, "Parameters in Call State must not be empty."); // Se utiliza un "break" para que solo aparezca un mensaje por // estado, ya que no se puede poner el nombre del parametro vacio // y por tanto, no se puede poner un mensaje por parametro. break; } } return true; } }
false
true
public boolean validate_CallState_exitsBeanInExecute(CallState state) { Flow flow = (Flow) state.eContainer(); File rawFile = ValidatorUtils.getFile(state); System.out.println("****************** 1 rawFile " + rawFile); File projectFile = ValidatorUtils.findProjectFile(rawFile); System.out.println("****************** 2 projectFile " + projectFile); String classbean; if (state.getBean() != null) { classbean = state.getBean().getFqdn(); System.out.println("****************** 3 classbean " + classbean); File folder = new File(projectFile, PATH); System.out.println("****************** 4 folder " + folder); File filepack = new File(folder, classbean.replace(".", "/").concat(".java")); System.out.println("****************** 5 filepack " + filepack); System.out.println("****************** 6 filepack.exists() " + filepack.exists()); if (!filepack.exists()) { operationsValidator.error(state, "No exits bean in execute state \"" + state.getName() + "\" in flow \"" + flow.getName() + "\""); } } return true; }
public boolean validate_CallState_exitsBeanInExecute(CallState state) { Flow flow = (Flow) state.eContainer(); File rawFile = ValidatorUtils.getFile(state); File projectFile = ValidatorUtils.findProjectFile(rawFile); String classbean; if (state.getBean() != null) { classbean = state.getBean().getFqdn(); File folder = new File(projectFile, PATH); File filepack = new File(folder, classbean.replace(".", "/").concat(".java")); if (!filepack.exists()) { operationsValidator.error(state, "No exits bean in execute state \"" + state.getName() + "\" in flow \"" + flow.getName() + "\""); } } return true; }
diff --git a/modules/cpr/src/main/java/org/atmosphere/cpr/AtmosphereRequest.java b/modules/cpr/src/main/java/org/atmosphere/cpr/AtmosphereRequest.java index dba95622c..510a7efb1 100644 --- a/modules/cpr/src/main/java/org/atmosphere/cpr/AtmosphereRequest.java +++ b/modules/cpr/src/main/java/org/atmosphere/cpr/AtmosphereRequest.java @@ -1,414 +1,414 @@ /* * Copyright 2011 Jeanfrancois Arcand * * 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 org.atmosphere.cpr; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE; /** * A Builder for constructing {@link HttpServletRequest} */ public class AtmosphereRequest extends HttpServletRequestWrapper { private final ByteInputStream bis; private final BufferedReader br; private final String pathInfo; private final Map<String, String> headers; private final Map<String, String[]> queryStrings; private final String methodType; private final String contentType; private final HttpServletRequest request; private final String servletPath; private final String requestURI; private final String requestURL; private final Map<String, Object> localAttributes; private AtmosphereRequest(Builder b) { super(b.request); pathInfo = b.pathInfo == null ? b.request.getPathInfo() : b.pathInfo; request = b.request; - headers = b.headers == null ? Collections.<String, String>emptyMap() : b.headers; + headers = b.headers == null ? new HashMap<String, String[]>() : b.headers; queryStrings = b.queryStrings == null ? new HashMap<String, String[]>() : b.queryStrings; servletPath = b.servletPath; requestURI = b.requestURI; requestURL = b.requestURL; localAttributes = b.localAttributes; if (b.dataBytes != null) { bis = new ByteInputStream(b.dataBytes, b.offset, b.length); try { br = new BufferedReader(new StringReader(new String(b.dataBytes, b.offset, b.length, b.encoding))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } else if (b.data != null) { bis = new ByteInputStream(b.data.getBytes(), 0, b.data.getBytes().length); br = new BufferedReader(new StringReader(b.data)); } else { bis = null; br = null; } methodType = b.methodType == null ? (request != null ? request.getMethod() : "GET") : b.methodType; contentType = b.contentType == null ? (request != null ? request.getContentType() : "text/plain") : b.contentType; } /** * {@inheritDoc} */ @Override public String getPathInfo() { return pathInfo; } /** * {@inheritDoc} */ @Override public String getMethod() { return methodType; } /** * {@inheritDoc} */ @Override public String getContentType() { return contentType; } /** * {@inheritDoc} */ @Override public String getServletPath() { return servletPath != null ? servletPath : super.getServletPath(); } /** * {@inheritDoc} */ @Override public String getRequestURI() { return requestURI != null ? requestURI : (request != null ? super.getRequestURI() : null); } /** * {@inheritDoc} */ @Override public StringBuffer getRequestURL() { return requestURL != null ? new StringBuffer(requestURL) : (request != null ? request.getRequestURL() : null); } /** * {@inheritDoc} */ @Override public Enumeration getHeaders(String name) { ArrayList list = Collections.list(super.getHeaders(name)); if (name.equalsIgnoreCase("content-type")) { list.add(contentType); } if (headers.get(name) != null) { list.add(headers.get(name)); } if (request != null) { if (list.size() == 0 && name.startsWith(X_ATMOSPHERE)) { if (request.getAttribute(name) != null) { list.add(request.getAttribute(name)); } } } return Collections.enumeration(list); } /** * {@inheritDoc} */ @Override public Enumeration<String> getHeaderNames() { ArrayList list = Collections.list(super.getHeaderNames()); list.add("content-type"); if (request != null) { Enumeration e = request.getAttributeNames(); while (e.hasMoreElements()) { String name = e.nextElement().toString(); if (name.startsWith(X_ATMOSPHERE)) { list.add(name); } } } list.addAll(headers.keySet()); return Collections.enumeration(list); } @Override public String getHeader(String s) { if (s.equalsIgnoreCase("Connection")) { return "keep-alive"; } else if ("content-type".equalsIgnoreCase(s)) { return contentType; } else { String name = super.getHeader(s); if (name == null) { if (headers.get(s) != null) { return headers.get(s); } if (s.startsWith(X_ATMOSPHERE) && request != null) { return (String) request.getAttribute(s); } } return name; } } /** * {@inheritDoc} */ @Override public String getParameter(String s) { String name = super.getParameter(s); if (name == null) { if (queryStrings.get(s) != null) { return queryStrings.get(s)[0]; } } return name; } /** * {@inheritDoc} */ @Override public Map<String, String[]> getParameterMap() { Map<String, String[]> m = (request != null ? request.getParameterMap() : Collections.<String, String[]>emptyMap()); for (Map.Entry<String, String[]> e : m.entrySet()) { String[] s = queryStrings.get(e.getKey()); if (s != null) { String[] s1 = new String[s.length + e.getValue().length]; System.arraycopy(s, 0, s1, 0, s.length); System.arraycopy(s1, s.length + 1, e.getValue(), 0, e.getValue().length); queryStrings.put(e.getKey(), s1); } else { queryStrings.put(e.getKey(), e.getValue()); } } return Collections.unmodifiableMap(queryStrings); } /** * {@inheritDoc} */ @Override public String[] getParameterValues(String s) { String[] list = super.getParameterValues(s) == null ? new String[0] : super.getParameterValues(s); if (queryStrings.get(s) != null) { String[] newList = queryStrings.get(s); String[] s1 = new String[list.length + newList.length]; System.arraycopy(list, 0, s1, 0, list.length); System.arraycopy(s1, list.length + 1, newList, 0, newList.length); } return list; } /** * {@inheritDoc} */ @Override public ServletInputStream getInputStream() throws IOException { return bis == null ? (request != null ? request.getInputStream() : null) : bis; } /** * {@inheritDoc} */ @Override public BufferedReader getReader() throws IOException { return br == null ? (request != null ? request.getReader() : null) : br; } private final static class ByteInputStream extends ServletInputStream { private final ByteArrayInputStream bis; public ByteInputStream(byte[] data, int offset, int length) { this.bis = new ByteArrayInputStream(data, offset, length); } @Override public int read() throws IOException { return bis.read(); } } /** * {@inheritDoc} */ @Override public void setAttribute(String s, Object o) { localAttributes.put(s, o); } /** * {@inheritDoc} */ @Override public Object getAttribute(String s) { return localAttributes.get(s) != null ? localAttributes.get(s) : (request != null ? request.getAttribute(s) : null); } /** * {@inheritDoc} */ @Override public void removeAttribute(String name) { if (localAttributes.remove(name) == null && request != null) { request.removeAttribute(name); } } /** * {@inheritDoc} */ @Override public Enumeration<String> getAttributeNames() { Map<String, Object> m = new HashMap<String, Object>(); m.putAll(localAttributes); Enumeration<String> e = (request != null ? request.getAttributeNames() : null); if (e != null) { String s; while (e.hasMoreElements()) { s = e.nextElement(); m.put(s, request.getAttribute(s)); } } return Collections.enumeration(m.keySet()); } public final static class Builder { private HttpServletRequest request; private String pathInfo; private byte[] dataBytes; private int offset; private int length; private String encoding = "UTF-8"; private String methodType; private String contentType; private String data; private Map<String, String> headers; private Map<String, String[]> queryStrings; private String servletPath; private String requestURI; private String requestURL; private Map<String, Object> localAttributes = new HashMap<String, Object>(); public Builder() { } public Builder headers(Map<String, String> headers) { this.headers = headers; return this; } public Builder attributes(Map<String, Object> attributes) { localAttributes = attributes; return this; } public Builder request(HttpServletRequest request) { this.request = request; return this; } public Builder servletPath(String servletPath) { this.servletPath = servletPath; return this; } public Builder requestURI(String requestURI) { this.requestURI = requestURI; return this; } public Builder requestURL(String requestURL) { this.requestURL = requestURL; return this; } public Builder pathInfo(String pathInfo) { this.pathInfo = pathInfo; return this; } public Builder body(byte[] dataBytes, int offset, int length) { this.dataBytes = dataBytes; this.offset = offset; this.length = length; return this; } public Builder encoding(String encoding) { this.encoding = encoding; return this; } public Builder method(String methodType) { this.methodType = methodType; return this; } public Builder contentType(String contentType) { this.contentType = contentType; return this; } public Builder body(String data) { this.data = data; return this; } public AtmosphereRequest build() { return new AtmosphereRequest(this); } public Builder queryStrings(Map<String, String[]> queryStrings) { this.queryStrings = queryStrings; return this; } } }
true
true
private AtmosphereRequest(Builder b) { super(b.request); pathInfo = b.pathInfo == null ? b.request.getPathInfo() : b.pathInfo; request = b.request; headers = b.headers == null ? Collections.<String, String>emptyMap() : b.headers; queryStrings = b.queryStrings == null ? new HashMap<String, String[]>() : b.queryStrings; servletPath = b.servletPath; requestURI = b.requestURI; requestURL = b.requestURL; localAttributes = b.localAttributes; if (b.dataBytes != null) { bis = new ByteInputStream(b.dataBytes, b.offset, b.length); try { br = new BufferedReader(new StringReader(new String(b.dataBytes, b.offset, b.length, b.encoding))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } else if (b.data != null) { bis = new ByteInputStream(b.data.getBytes(), 0, b.data.getBytes().length); br = new BufferedReader(new StringReader(b.data)); } else { bis = null; br = null; } methodType = b.methodType == null ? (request != null ? request.getMethod() : "GET") : b.methodType; contentType = b.contentType == null ? (request != null ? request.getContentType() : "text/plain") : b.contentType; }
private AtmosphereRequest(Builder b) { super(b.request); pathInfo = b.pathInfo == null ? b.request.getPathInfo() : b.pathInfo; request = b.request; headers = b.headers == null ? new HashMap<String, String[]>() : b.headers; queryStrings = b.queryStrings == null ? new HashMap<String, String[]>() : b.queryStrings; servletPath = b.servletPath; requestURI = b.requestURI; requestURL = b.requestURL; localAttributes = b.localAttributes; if (b.dataBytes != null) { bis = new ByteInputStream(b.dataBytes, b.offset, b.length); try { br = new BufferedReader(new StringReader(new String(b.dataBytes, b.offset, b.length, b.encoding))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } else if (b.data != null) { bis = new ByteInputStream(b.data.getBytes(), 0, b.data.getBytes().length); br = new BufferedReader(new StringReader(b.data)); } else { bis = null; br = null; } methodType = b.methodType == null ? (request != null ? request.getMethod() : "GET") : b.methodType; contentType = b.contentType == null ? (request != null ? request.getContentType() : "text/plain") : b.contentType; }
diff --git a/src/de/christianzunker/mobilecitygate/controller/PoiController.java b/src/de/christianzunker/mobilecitygate/controller/PoiController.java index 67f7718..c2c8c7c 100644 --- a/src/de/christianzunker/mobilecitygate/controller/PoiController.java +++ b/src/de/christianzunker/mobilecitygate/controller/PoiController.java @@ -1,377 +1,379 @@ package de.christianzunker.mobilecitygate.controller; import java.net.SocketTimeoutException; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Vector; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.MediaType; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.WebResource; import de.christianzunker.mobilecitygate.beans.Client; import de.christianzunker.mobilecitygate.beans.Config; import de.christianzunker.mobilecitygate.beans.Poi; import de.christianzunker.mobilecitygate.beans.PoiCategory; import de.christianzunker.mobilecitygate.beans.Profile; import de.christianzunker.mobilecitygate.beans.Route; import de.christianzunker.mobilecitygate.dao.ClientDao; import de.christianzunker.mobilecitygate.dao.MessageDao; import de.christianzunker.mobilecitygate.dao.PoiCategoryDao; import de.christianzunker.mobilecitygate.dao.PoiDao; import de.christianzunker.mobilecitygate.dao.ProfileDao; import de.christianzunker.mobilecitygate.dao.RouteDao; import de.christianzunker.mobilecitygate.utils.GoogleServices; @Controller public class PoiController { // NO_UCD private static final Logger logger = Logger.getLogger(PoiController.class); @Autowired private GoogleServices google; @Autowired private PoiCategoryDao poiCatDao; @Autowired private Config config; @Autowired private ProfileDao profileDao; @Autowired private PoiDao poiDao; @Autowired private RouteDao routeDao; @Autowired private ClientDao clientDao; @Autowired private MessageDao messageDao; @Cacheable("pois") @RequestMapping(value = "/{client}/{locale}/pois") public String getPois(@PathVariable("client") String client, @PathVariable("locale") String locale, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { logger.debug("entering method getPois"); Calendar cal = Calendar.getInstance(); long starttime = cal.getTimeInMillis(); long curtime = 0L; logger.trace("starttime: " + starttime); //TODO do a more precise check on locale with table languages? if (!locale.matches("[a-z]{2}") || !client.matches("[0-9a-zA-Z_-]*") || client.length() > 45) { logger.error("Fehlerhafte Parameter!"); throw new Exception("Fehlerhafte Parameter!"); } Client clientObj = clientDao.getClientByUrl(client); HashMap<String, String> hashMessagesPoiOverview = messageDao.getMessagesByPageClientIdLocale("poi-overview", clientObj.getId(), locale); HashMap<String, String> hashMessagesMap = messageDao.getMessagesByPageClientIdLocale("map", clientObj.getId(), locale); curtime = cal.getTimeInMillis(); logger.trace("PERF: after get messages took ms: " + (curtime - starttime)); //get shortened URL for easier Twitter usage - String longUrl = "http://" + request.getServerName() + request.getContextPath() + "/" + clientObj.getUrl() + "/" + locale + "/"; + //String longUrl = "http://" + request.getServerName() + request.getContextPath() + "/" + clientObj.getUrl() + "/" + locale + "/"; + // TODO: get correct server name programatically (currently it is localhost) + String longUrl = "http://m.mobiles-stadttor.de" + request.getContextPath() + "/" + clientObj.getUrl() + "/" + locale + "/"; clientObj.setShortUrl(google.getShortUrl(longUrl)); curtime = cal.getTimeInMillis(); logger.trace("PERF: after get short url took ms: " + (curtime - starttime)); List<PoiCategory> cats = poiCatDao.getActiveCategoriesByClientLocale(clientObj.getId(), locale); List<Profile> profiles = profileDao.getActiveProfilesByClientLocale(clientObj.getId(), locale); //List<Poi> pois = poiDao.getPoisNotInRoute(); List<Poi> pois = poiDao.getPoisNotInRouteByClientLocale(clientObj.getId(), locale); List<Route> routes = routeDao.getRouteListByClientLocale(clientObj.getId(), locale); curtime = cal.getTimeInMillis(); logger.trace("PERF: after get categories, profiles, routes and pois took ms: " + (curtime - starttime)); for (Route route : routes) { route.setPois(poiDao.getPoisByRouteLocale(route.getId(), locale)); if (logger.isDebugEnabled()) { logger.debug("#route pois: " + route.getPois().size()); } } curtime = cal.getTimeInMillis(); logger.trace("PERF: after set pois for route took ms: " + (curtime - starttime)); for (Profile profile : profiles) { List<Integer> ids = poiDao.getPoiIdsByProfileByClientLocale(profile.getId(), clientObj.getId(), locale); String stringIds = ""; for (Integer id : ids) { stringIds += id.toString() + ","; } //remove last , if (stringIds.length() > 0) { stringIds = stringIds.substring(0, stringIds.length() - 1); } profile.setNonUsablePoiIds(stringIds); } curtime = cal.getTimeInMillis(); logger.trace("PERF: after associate pois to profiles took ms: " + (curtime - starttime)); for (PoiCategory cat : cats) { List<Integer> ids = poiDao.getPoiIdsByCategoryLocale(cat.getId(), locale); String stringIds = ""; for (Integer id : ids) { stringIds += id.toString() + ","; } //remove last , if (stringIds.length() > 0) { stringIds = stringIds.substring(0, stringIds.length() - 1); } cat.setPois(stringIds); } curtime = cal.getTimeInMillis(); logger.trace("PERF: after associate pois to categories took ms: " + (curtime - starttime)); model.addAttribute("tilesServers", config.getTilesServers()); model.addAttribute("profiles", profiles); model.addAttribute("poiCategories", cats); model.addAttribute("pois", pois); model.addAttribute("config", config); model.addAttribute("routes", routes); model.addAttribute("locale", locale); model.addAttribute("client", clientObj); model.addAttribute("messagesPoiOverview", hashMessagesPoiOverview); model.addAttribute("messagesMap", hashMessagesMap); curtime = cal.getTimeInMillis(); logger.trace("PERF: after setting the model took ms: " + (curtime - starttime)); logger.debug("leaving method getPois"); return "poi-map"; } /* @Cacheable("urls") public String getGoogleShortUrl(String longUrl) { String shortUrl = longUrl; String googleUrl = "https://www.googleapis.com/urlshortener/v1/url?" + config.getGoogleApiKey(); try { com.sun.jersey.api.client.Client jsonClient = com.sun.jersey.api.client.Client.create(); int timeout = config.getGoogleTimeout(); if (!(timeout > 0)) { // config not set, connect with a default timeout of 200ms timeout = 200; } logger.trace("Google timeout: " + timeout + "ms"); jsonClient.setConnectTimeout(timeout); WebResource webResource = jsonClient.resource(googleUrl); String jsonRequest = "{ \"longUrl\": \"" + longUrl + "\" }"; logger.debug("jsonRequest: " + jsonRequest); String jsonResponse = webResource.accept( MediaType.APPLICATION_JSON_TYPE). type(MediaType.APPLICATION_JSON_TYPE). post(String.class, jsonRequest); logger.debug("jsonResponse: " + jsonResponse); JsonParser jsonParser = new JsonParser(); JsonObject jsonObj = (JsonObject)jsonParser.parse(jsonResponse); if ( jsonObj != null && jsonObj.has("id")) { shortUrl = jsonObj.get("id").toString(); shortUrl = shortUrl.replace("\"", ""); } } catch (ClientHandlerException ex) { Exception rootCause = (Exception) ex.getCause(); if (rootCause.getClass().equals(SocketTimeoutException.class)) { logger.error("Got connection timeout!"); } logger.error("Couldn't connect to Google URL Shortener!", ex); } return shortUrl; } */ @Cacheable("pois") @RequestMapping(value = "/poi/{poiId}", headers="Accept=*/*", method=RequestMethod.GET) public @ResponseBody Poi getPoiById(@PathVariable("poiId") int poiId) { logger.debug("entering method getPoiById"); Poi poi = poiDao.getPoiById(poiId); try { Route route = routeDao.getRouteByPoiId(poiId); poi.setRoute(route.getName()); poi.setRouteId(route.getId()); } catch (EmptyResultDataAccessException ex) { logger.info("no route assigned for poi " + poi.getName() + "(id: " + poi.getId() + ")"); poi.setRoute("no route assigned"); } PoiCategory cat = poiCatDao.getCategoryByPoi(poiId); List<Profile> profiles = profileDao.getProfilesByPoi(poiId); poi.setIcon(cat.getIcon()); poi.setPoiCategory(cat.getName()); poi.setPoiCategoryId(cat.getId()); List<String> profileNames = new Vector<String>(); List<Integer> profileIds = new Vector<Integer>(); for (Profile profile : profiles) { logger.trace("profileName: " + profile.getName()); profileNames.add(profile.getName()); logger.trace("profileId: " + profile.getId()); profileIds.add(new Integer(profile.getId())); } poi.setPoiProfileIds(profileIds); logger.trace("#profileNames: " + poi.getPoiProfileIds().size()); poi.setPoiProfiles(profileNames); logger.trace("#profileNames: " + poi.getPoiProfiles().size()); logger.debug("leaving method getPoiById"); return poi; } @CacheEvict(value = "pois", allEntries=true) @RequestMapping(value = "/poi/{poiId}", headers="Accept=application/json", method=RequestMethod.POST) public @ResponseBody int setPoiById(@PathVariable("poiId") int poiId, @RequestBody Poi poi) { logger.debug("entering method setPoiById"); int rc = 0; if (poiId > 0) { rc = poiDao.updatePoiById(poiId, poi); if (poi.getRouteId() > 0) { // TODO: What if new assignment? rc = poiDao.updatePoiRouteById(poiId, poi.getRouteId()); } else { rc = poiDao.deletePoiRouteById(poiId); } logger.debug("poi.getPoiProfileIds().size(): " + poi.getPoiProfileIds().size()); if (poi.getPoiProfileIds().size() > 0) { rc = poiDao.updatePoiProfilesById(poiId, poi); } else { rc = poiDao.deletePoiProfilesById(poiId); } if (poi.getPoiCategoryId() > 0) { // TODO: What if new assignment? rc = poiDao.updatePoiCategoryById(poiId, poi.getPoiCategoryId()); } else { rc = poiDao.deletePoiCategoryById(poiId); } } else { // TODO: good design? split it in multiple methods? rc = poiDao.createPoi(poi); poiId = rc; rc = poiDao.createPoiRoute(poiId, poi); } logger.debug("leaving method setPoiById"); return rc; } @CacheEvict(value = "pois", allEntries=true) @RequestMapping(value = "/poi/{poiId}", method=RequestMethod.DELETE) public @ResponseBody int deletePoiById(@PathVariable("poiId") int poiId) { logger.debug("entering method deletePoiById"); int rc = poiDao.deletePoiById(poiId); logger.debug("leaving method deletePoiById"); return rc; } @RequestMapping(value = "/pois/{routeId}", headers="Accept=*/*", method=RequestMethod.GET) // TODO is it allowed to throw exceptions in this method or is there a different way because of REST + JSON? public @ResponseBody List<Poi> getPoisByRouteId(@PathVariable("routeId") int routeId) throws Exception { logger.debug("entering method getPois"); List<Poi> pois = poiDao.getPoisByRoute(routeId); logger.debug("leaving method getPois"); return pois; } @RequestMapping(value = "/pois/{clientid}/{locale}", headers="Accept=*/*", method=RequestMethod.GET) // TODO is it allowed to throw exceptions in this method or is there a different way because of REST + JSON? public @ResponseBody List<Poi> getUnassignedPois(@PathVariable("clientid") int clientId, @PathVariable("locale") String locale) throws Exception { logger.debug("entering method getUnassignedPois"); if (!locale.matches("[a-z]{2}")) { logger.error("Fehlerhafte Parameter!"); throw new Exception("Fehlerhafte Parameter!"); } List<Poi> pois = poiDao.getPoisNotInRouteByClientLocale(clientId, locale); logger.debug("leaving method getUnassignedPois"); return pois; } @RequestMapping(value = "/pois", method=RequestMethod.POST) // TODO is it allowed to throw exceptions in this method or is there a different way because of REST + JSON? public @ResponseBody List<Poi> getPois(@ModelAttribute Integer[] poiIds) throws Exception { logger.debug("entering method getPois"); logger.debug("poiIds.toString(): " + poiIds.toString()); List<Poi> pois = poiDao.getPoisByIds(poiIds.toString()); logger.debug("leaving method getPois"); return pois; } @CacheEvict(value = "pois", allEntries=true) @RequestMapping(value = "/poi/publish", method=RequestMethod.POST) // TODO is it allowed to throw exceptions in this method or is there a different way because of REST + JSON? public @ResponseBody int publishAllPois() throws Exception { logger.debug("entering method publishAllPois"); // TODO: Publish routes by client and locale depending on the logged in user and his rights int rc = poiDao.publishAllPois(); logger.debug("leaving method publishAllPois"); return rc; } @CacheEvict(value = "pois", allEntries=true) @RequestMapping(value = "/poi/publish/{poiId}", method=RequestMethod.POST) public @ResponseBody int publishPoiById(@PathVariable("poiId") int poiId) { logger.debug("entering method publishPoiById"); int rc = poiDao.publishPoiById(poiId); logger.debug("leaving method publishPoiById"); return rc; } @ExceptionHandler(Exception.class) public String handleException(Exception ex, HttpServletRequest request) { logger.error("Error in " + this.getClass(), ex); return "general-error"; } }
true
true
public String getPois(@PathVariable("client") String client, @PathVariable("locale") String locale, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { logger.debug("entering method getPois"); Calendar cal = Calendar.getInstance(); long starttime = cal.getTimeInMillis(); long curtime = 0L; logger.trace("starttime: " + starttime); //TODO do a more precise check on locale with table languages? if (!locale.matches("[a-z]{2}") || !client.matches("[0-9a-zA-Z_-]*") || client.length() > 45) { logger.error("Fehlerhafte Parameter!"); throw new Exception("Fehlerhafte Parameter!"); } Client clientObj = clientDao.getClientByUrl(client); HashMap<String, String> hashMessagesPoiOverview = messageDao.getMessagesByPageClientIdLocale("poi-overview", clientObj.getId(), locale); HashMap<String, String> hashMessagesMap = messageDao.getMessagesByPageClientIdLocale("map", clientObj.getId(), locale); curtime = cal.getTimeInMillis(); logger.trace("PERF: after get messages took ms: " + (curtime - starttime)); //get shortened URL for easier Twitter usage String longUrl = "http://" + request.getServerName() + request.getContextPath() + "/" + clientObj.getUrl() + "/" + locale + "/"; clientObj.setShortUrl(google.getShortUrl(longUrl)); curtime = cal.getTimeInMillis(); logger.trace("PERF: after get short url took ms: " + (curtime - starttime)); List<PoiCategory> cats = poiCatDao.getActiveCategoriesByClientLocale(clientObj.getId(), locale); List<Profile> profiles = profileDao.getActiveProfilesByClientLocale(clientObj.getId(), locale); //List<Poi> pois = poiDao.getPoisNotInRoute(); List<Poi> pois = poiDao.getPoisNotInRouteByClientLocale(clientObj.getId(), locale); List<Route> routes = routeDao.getRouteListByClientLocale(clientObj.getId(), locale); curtime = cal.getTimeInMillis(); logger.trace("PERF: after get categories, profiles, routes and pois took ms: " + (curtime - starttime)); for (Route route : routes) { route.setPois(poiDao.getPoisByRouteLocale(route.getId(), locale)); if (logger.isDebugEnabled()) { logger.debug("#route pois: " + route.getPois().size()); } } curtime = cal.getTimeInMillis(); logger.trace("PERF: after set pois for route took ms: " + (curtime - starttime)); for (Profile profile : profiles) { List<Integer> ids = poiDao.getPoiIdsByProfileByClientLocale(profile.getId(), clientObj.getId(), locale); String stringIds = ""; for (Integer id : ids) { stringIds += id.toString() + ","; } //remove last , if (stringIds.length() > 0) { stringIds = stringIds.substring(0, stringIds.length() - 1); } profile.setNonUsablePoiIds(stringIds); } curtime = cal.getTimeInMillis(); logger.trace("PERF: after associate pois to profiles took ms: " + (curtime - starttime)); for (PoiCategory cat : cats) { List<Integer> ids = poiDao.getPoiIdsByCategoryLocale(cat.getId(), locale); String stringIds = ""; for (Integer id : ids) { stringIds += id.toString() + ","; } //remove last , if (stringIds.length() > 0) { stringIds = stringIds.substring(0, stringIds.length() - 1); } cat.setPois(stringIds); } curtime = cal.getTimeInMillis(); logger.trace("PERF: after associate pois to categories took ms: " + (curtime - starttime)); model.addAttribute("tilesServers", config.getTilesServers()); model.addAttribute("profiles", profiles); model.addAttribute("poiCategories", cats); model.addAttribute("pois", pois); model.addAttribute("config", config); model.addAttribute("routes", routes); model.addAttribute("locale", locale); model.addAttribute("client", clientObj); model.addAttribute("messagesPoiOverview", hashMessagesPoiOverview); model.addAttribute("messagesMap", hashMessagesMap); curtime = cal.getTimeInMillis(); logger.trace("PERF: after setting the model took ms: " + (curtime - starttime)); logger.debug("leaving method getPois"); return "poi-map"; }
public String getPois(@PathVariable("client") String client, @PathVariable("locale") String locale, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { logger.debug("entering method getPois"); Calendar cal = Calendar.getInstance(); long starttime = cal.getTimeInMillis(); long curtime = 0L; logger.trace("starttime: " + starttime); //TODO do a more precise check on locale with table languages? if (!locale.matches("[a-z]{2}") || !client.matches("[0-9a-zA-Z_-]*") || client.length() > 45) { logger.error("Fehlerhafte Parameter!"); throw new Exception("Fehlerhafte Parameter!"); } Client clientObj = clientDao.getClientByUrl(client); HashMap<String, String> hashMessagesPoiOverview = messageDao.getMessagesByPageClientIdLocale("poi-overview", clientObj.getId(), locale); HashMap<String, String> hashMessagesMap = messageDao.getMessagesByPageClientIdLocale("map", clientObj.getId(), locale); curtime = cal.getTimeInMillis(); logger.trace("PERF: after get messages took ms: " + (curtime - starttime)); //get shortened URL for easier Twitter usage //String longUrl = "http://" + request.getServerName() + request.getContextPath() + "/" + clientObj.getUrl() + "/" + locale + "/"; // TODO: get correct server name programatically (currently it is localhost) String longUrl = "http://m.mobiles-stadttor.de" + request.getContextPath() + "/" + clientObj.getUrl() + "/" + locale + "/"; clientObj.setShortUrl(google.getShortUrl(longUrl)); curtime = cal.getTimeInMillis(); logger.trace("PERF: after get short url took ms: " + (curtime - starttime)); List<PoiCategory> cats = poiCatDao.getActiveCategoriesByClientLocale(clientObj.getId(), locale); List<Profile> profiles = profileDao.getActiveProfilesByClientLocale(clientObj.getId(), locale); //List<Poi> pois = poiDao.getPoisNotInRoute(); List<Poi> pois = poiDao.getPoisNotInRouteByClientLocale(clientObj.getId(), locale); List<Route> routes = routeDao.getRouteListByClientLocale(clientObj.getId(), locale); curtime = cal.getTimeInMillis(); logger.trace("PERF: after get categories, profiles, routes and pois took ms: " + (curtime - starttime)); for (Route route : routes) { route.setPois(poiDao.getPoisByRouteLocale(route.getId(), locale)); if (logger.isDebugEnabled()) { logger.debug("#route pois: " + route.getPois().size()); } } curtime = cal.getTimeInMillis(); logger.trace("PERF: after set pois for route took ms: " + (curtime - starttime)); for (Profile profile : profiles) { List<Integer> ids = poiDao.getPoiIdsByProfileByClientLocale(profile.getId(), clientObj.getId(), locale); String stringIds = ""; for (Integer id : ids) { stringIds += id.toString() + ","; } //remove last , if (stringIds.length() > 0) { stringIds = stringIds.substring(0, stringIds.length() - 1); } profile.setNonUsablePoiIds(stringIds); } curtime = cal.getTimeInMillis(); logger.trace("PERF: after associate pois to profiles took ms: " + (curtime - starttime)); for (PoiCategory cat : cats) { List<Integer> ids = poiDao.getPoiIdsByCategoryLocale(cat.getId(), locale); String stringIds = ""; for (Integer id : ids) { stringIds += id.toString() + ","; } //remove last , if (stringIds.length() > 0) { stringIds = stringIds.substring(0, stringIds.length() - 1); } cat.setPois(stringIds); } curtime = cal.getTimeInMillis(); logger.trace("PERF: after associate pois to categories took ms: " + (curtime - starttime)); model.addAttribute("tilesServers", config.getTilesServers()); model.addAttribute("profiles", profiles); model.addAttribute("poiCategories", cats); model.addAttribute("pois", pois); model.addAttribute("config", config); model.addAttribute("routes", routes); model.addAttribute("locale", locale); model.addAttribute("client", clientObj); model.addAttribute("messagesPoiOverview", hashMessagesPoiOverview); model.addAttribute("messagesMap", hashMessagesMap); curtime = cal.getTimeInMillis(); logger.trace("PERF: after setting the model took ms: " + (curtime - starttime)); logger.debug("leaving method getPois"); return "poi-map"; }
diff --git a/src/ch/sbs/plugin/preptools/PrepToolLoader.java b/src/ch/sbs/plugin/preptools/PrepToolLoader.java index 17e3618..81d06eb 100644 --- a/src/ch/sbs/plugin/preptools/PrepToolLoader.java +++ b/src/ch/sbs/plugin/preptools/PrepToolLoader.java @@ -1,75 +1,75 @@ package ch.sbs.plugin.preptools; import java.util.ArrayList; import java.util.List; public class PrepToolLoader { // Ordnungszahlen public static final String ORDINAL_REGEX = "\\b\\d+\\."; // Römische Zahlen // case sensitive public static final String ROMAN_REGEX = "\\b[IVXCMLD]+\\b\\.?"; // Zahl mit Masseinheit // ignore case public static final String MEASURE_REGEX = "(?i:\\d*['.,]*\\d+\\s*[A-Z]{1,2}\\b)"; // Grossbuchstaben(folgen) des Typs A, A-Z, MM, USA, A4 // case sensitive public static final String ABBREV_CAPITAL_REGEX = "(\\b[A-ZÄÖÜ]+)(\\d*\\b)"; public static final String ABBREV_CAPITAL_REPLACE = "<abbr>$1</abbr>$2"; // Abkürzungen des Typs x.y. oder x. y. // ignore case public static final String ABBREV_PERIOD_REGEX = "\\b(?i:[A-ZÄÖÜ]{1,4}\\.\\s*[A-ZÄÖÜ]{1,4}\\.)"; // Akronyme des Typs GmbH, GSoA, etc. // case sensitive public static final String ABBREV_ACRONYM_REGEX = "\\b\\w*[a-z]+[A-Z]+\\w*\\b"; // http://redmine.sbszh.ch/issues/show/1203 public static final String PAGEBREAK_REGEX = "</p\\s*>\\s*(<pagenum\\s+id\\s*=\\s*\"page-\\d+\" page\\s*=\\s*\"normal\"\\s*>\\s*\\d+\\s*</pagenum\\s*>)\\s*<p\\s*>"; public static final String PAGEBREAK_REPLACE = " $1 "; // http://redmine.sbszh.ch/issues/show/1201 public static final String PLACEHOLDER = "_____"; public static final String ACCENT_REGEX = "(?iu:(\\b\\w*[àâçéèêëìîïòôœùû]\\w*\\b))"; public static final String ACCENT_REPLACE = "<span brl:accents=\"" + PLACEHOLDER + "\">$1</span>"; // TODO: preptools should load themselves. // PrepToolLoader shouldn't know or care about specific tools. public static List<PrepTool> loadPrepTools( final PrepToolsPluginExtension thePrepToolsPluginExtension) { final List<PrepTool> prepTools = new ArrayList<PrepTool>(); int i = 0; prepTools.add(new VFormPrepTool(thePrepToolsPluginExtension, i++, 'o')); prepTools .add(new ParensPrepTool(thePrepToolsPluginExtension, i++, 's')); prepTools.add(new RegexPrepTool(thePrepToolsPluginExtension, i++, 'd', "Ordinal", ORDINAL_REGEX, "brl:num role=\"ordinal\"")); prepTools.add(new RegexPrepTool(thePrepToolsPluginExtension, i++, 'r', "Roman", ROMAN_REGEX, "brl:num role=\"roman\"")); prepTools.add(new RegexPrepTool(thePrepToolsPluginExtension, i++, 'u', "Measure", MEASURE_REGEX, "brl:num role=\"measure\"")); prepTools.add(new RegexPrepTool(thePrepToolsPluginExtension, i++, 'v', "AbbrevPeriod", ABBREV_PERIOD_REGEX, "abbr")); prepTools.add(new FullRegexPrepTool(thePrepToolsPluginExtension, i++, 't', "AbbrevCapital", ABBREV_CAPITAL_REGEX, "abbr", ABBREV_CAPITAL_REPLACE)); prepTools.add(new RegexPrepTool(thePrepToolsPluginExtension, i++, 'y', "Acronym", ABBREV_ACRONYM_REGEX, "abbr")); prepTools.add(new FullRegexPrepTool(thePrepToolsPluginExtension, i++, 'k', "Pagebreak", PAGEBREAK_REGEX, null, PAGEBREAK_REPLACE)); prepTools.add(new AccentPrepTool(thePrepToolsPluginExtension, i++, 'a', - "Accent", ACCENT_REGEX, "span", ACCENT_REPLACE)); + "Accent", ACCENT_REGEX, "span.*?", ACCENT_REPLACE)); return prepTools; } }
true
true
public static List<PrepTool> loadPrepTools( final PrepToolsPluginExtension thePrepToolsPluginExtension) { final List<PrepTool> prepTools = new ArrayList<PrepTool>(); int i = 0; prepTools.add(new VFormPrepTool(thePrepToolsPluginExtension, i++, 'o')); prepTools .add(new ParensPrepTool(thePrepToolsPluginExtension, i++, 's')); prepTools.add(new RegexPrepTool(thePrepToolsPluginExtension, i++, 'd', "Ordinal", ORDINAL_REGEX, "brl:num role=\"ordinal\"")); prepTools.add(new RegexPrepTool(thePrepToolsPluginExtension, i++, 'r', "Roman", ROMAN_REGEX, "brl:num role=\"roman\"")); prepTools.add(new RegexPrepTool(thePrepToolsPluginExtension, i++, 'u', "Measure", MEASURE_REGEX, "brl:num role=\"measure\"")); prepTools.add(new RegexPrepTool(thePrepToolsPluginExtension, i++, 'v', "AbbrevPeriod", ABBREV_PERIOD_REGEX, "abbr")); prepTools.add(new FullRegexPrepTool(thePrepToolsPluginExtension, i++, 't', "AbbrevCapital", ABBREV_CAPITAL_REGEX, "abbr", ABBREV_CAPITAL_REPLACE)); prepTools.add(new RegexPrepTool(thePrepToolsPluginExtension, i++, 'y', "Acronym", ABBREV_ACRONYM_REGEX, "abbr")); prepTools.add(new FullRegexPrepTool(thePrepToolsPluginExtension, i++, 'k', "Pagebreak", PAGEBREAK_REGEX, null, PAGEBREAK_REPLACE)); prepTools.add(new AccentPrepTool(thePrepToolsPluginExtension, i++, 'a', "Accent", ACCENT_REGEX, "span", ACCENT_REPLACE)); return prepTools; }
public static List<PrepTool> loadPrepTools( final PrepToolsPluginExtension thePrepToolsPluginExtension) { final List<PrepTool> prepTools = new ArrayList<PrepTool>(); int i = 0; prepTools.add(new VFormPrepTool(thePrepToolsPluginExtension, i++, 'o')); prepTools .add(new ParensPrepTool(thePrepToolsPluginExtension, i++, 's')); prepTools.add(new RegexPrepTool(thePrepToolsPluginExtension, i++, 'd', "Ordinal", ORDINAL_REGEX, "brl:num role=\"ordinal\"")); prepTools.add(new RegexPrepTool(thePrepToolsPluginExtension, i++, 'r', "Roman", ROMAN_REGEX, "brl:num role=\"roman\"")); prepTools.add(new RegexPrepTool(thePrepToolsPluginExtension, i++, 'u', "Measure", MEASURE_REGEX, "brl:num role=\"measure\"")); prepTools.add(new RegexPrepTool(thePrepToolsPluginExtension, i++, 'v', "AbbrevPeriod", ABBREV_PERIOD_REGEX, "abbr")); prepTools.add(new FullRegexPrepTool(thePrepToolsPluginExtension, i++, 't', "AbbrevCapital", ABBREV_CAPITAL_REGEX, "abbr", ABBREV_CAPITAL_REPLACE)); prepTools.add(new RegexPrepTool(thePrepToolsPluginExtension, i++, 'y', "Acronym", ABBREV_ACRONYM_REGEX, "abbr")); prepTools.add(new FullRegexPrepTool(thePrepToolsPluginExtension, i++, 'k', "Pagebreak", PAGEBREAK_REGEX, null, PAGEBREAK_REPLACE)); prepTools.add(new AccentPrepTool(thePrepToolsPluginExtension, i++, 'a', "Accent", ACCENT_REGEX, "span.*?", ACCENT_REPLACE)); return prepTools; }
diff --git a/components/bio-formats/src/loci/formats/in/FV1000Reader.java b/components/bio-formats/src/loci/formats/in/FV1000Reader.java index 6a042c127..a5d3987ce 100644 --- a/components/bio-formats/src/loci/formats/in/FV1000Reader.java +++ b/components/bio-formats/src/loci/formats/in/FV1000Reader.java @@ -1,1535 +1,1535 @@ // // FV1000Reader.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.in; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.util.Arrays; import java.util.HashMap; import java.util.Hashtable; import java.util.Vector; import loci.common.ByteArrayHandle; import loci.common.DataTools; import loci.common.DateTools; import loci.common.IniList; import loci.common.IniParser; import loci.common.IniTable; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.common.services.DependencyException; import loci.common.services.ServiceFactory; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.MetadataTools; import loci.formats.meta.MetadataStore; import loci.formats.services.POIService; import loci.formats.tiff.IFD; import loci.formats.tiff.IFDList; import loci.formats.tiff.TiffParser; import ome.xml.model.primitives.NonNegativeInteger; import ome.xml.model.primitives.PositiveInteger; /** * FV1000Reader is the file format reader for Fluoview FV 1000 OIB and * Fluoview FV 1000 OIF files. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://dev.loci.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/FV1000Reader.java">Trac</a>, * <a href="http://dev.loci.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/FV1000Reader.java">SVN</a></dd></dl> * * @author Melissa Linkert melissa at glencoesoftware.com */ public class FV1000Reader extends FormatReader { // -- Constants -- public static final String FV1000_MAGIC_STRING_1 = "FileInformation"; public static final String FV1000_MAGIC_STRING_2 = "Acquisition Parameters"; public static final String[] OIB_SUFFIX = {"oib"}; public static final String[] OIF_SUFFIX = {"oif"}; public static final String[] FV1000_SUFFIXES = {"oib", "oif"}; public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; private static final int NUM_DIMENSIONS = 9; /** ROI types. */ private static final int POINT = 2; private static final int LINE = 3; private static final int POLYLINE = 4; private static final int RECTANGLE = 5; private static final int CIRCLE = 6; private static final int ELLIPSE = 7; private static final int POLYGON = 8; private static final int FREE_SHAPE = 9; private static final int FREE_LINE = 10; private static final int GRID = 11; private static final int ARROW = 12; private static final int COLOR_BAR = 13; private static final int SCALE = 15; private static final String ROTATION = "rotate(%d %f %f)"; // -- Fields -- private IniParser parser = new IniParser(); /** Names of every TIFF file to open. */ private Vector<String> tiffs; /** Name of thumbnail file. */ private String thumbId; /** Helper reader for thumbnail. */ private BMPReader thumbReader; /** Used file list. */ private Vector<String> usedFiles; /** Flag indicating this is an OIB dataset. */ private boolean isOIB; /** File mappings for OIB file. */ private Hashtable<String, String> oibMapping; private String[] code, size; private Double[] pixelSize; private int imageDepth; private Vector<String> previewNames; private String pixelSizeX, pixelSizeY; private int validBits; private Vector<String> illuminations; private Vector<Integer> wavelengths; private String pinholeSize; private String magnification, lensNA, objectiveName, workingDistance; private String creationDate; private Vector<ChannelData> channels; private Vector<String> lutNames = new Vector<String>(); private Hashtable<Integer, String> filenames = new Hashtable<Integer, String>(); private Hashtable<Integer, String> roiFilenames = new Hashtable<Integer, String>(); private POIService poi; private short[][][] lut; private int lastChannel; private double pixelSizeZ = 1, pixelSizeT = 1; private String ptyStart = null, ptyEnd = null, ptyPattern = null, line = null; // -- Constructor -- /** Constructs a new FV1000 reader. */ public FV1000Reader() { super("Olympus FV1000", new String[] {"oib", "oif", "pty", "lut"}); domains = new String[] {FormatTools.LM_DOMAIN}; hasCompanionFiles = true; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isSingleFile(String) */ public boolean isSingleFile(String id) throws FormatException, IOException { return checkSuffix(id, OIB_SUFFIX); } /* @see loci.formats.IFormatReader#isThisType(String, boolean) */ public boolean isThisType(String name, boolean open) { if (checkSuffix(name, FV1000_SUFFIXES)) return true; if (!open) return false; // not allowed to touch the file system try { Location oif = new Location(findOIFFile(name)); return oif.exists() && !oif.isDirectory() && checkSuffix(oif.getAbsolutePath(), "oif"); } catch (IndexOutOfBoundsException e) { } catch (NullPointerException e) { } catch (FormatException e) { } return false; } /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { final int blockLen = 1024; if (!FormatTools.validStream(stream, blockLen, false)) return false; String s = DataTools.stripString(stream.readString(blockLen)); return s.indexOf(FV1000_MAGIC_STRING_1) >= 0 || s.indexOf(FV1000_MAGIC_STRING_2) >= 0; } /* @see loci.formats.IFormatReader#fileGroupOption(String) */ public int fileGroupOption(String id) throws FormatException, IOException { String name = id.toLowerCase(); if (checkSuffix(name, FV1000_SUFFIXES)) { return FormatTools.CANNOT_GROUP; } return FormatTools.MUST_GROUP; } /* @see loci.formats.IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() { FormatTools.assertId(currentId, true, 1); return lut == null || !isIndexed() ? null : lut[lastChannel]; } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); int file = no; int image = 0; String filename = null; if (series == 0) { file = no / (getImageCount() / tiffs.size()); image = no % (getImageCount() / tiffs.size()); if (file < tiffs.size()) filename = tiffs.get(file); } else { file = no / (getImageCount() / previewNames.size()); image = no % (getImageCount() / previewNames.size()); if (file < previewNames.size()) { filename = previewNames.get(file); } } int[] coords = getZCTCoords(image); lastChannel = coords[1]; if (filename == null) return buf; RandomAccessInputStream plane = null; try { plane = getFile(filename); } catch (IOException e) { } if (plane == null) return buf; TiffParser tp = new TiffParser(plane); IFDList ifds = tp.getIFDs(); if (image >= ifds.size()) return buf; IFD ifd = ifds.get(image); if (getSizeY() != ifd.getImageLength()) { tp.getSamples(ifd, buf, x, getIndex(coords[0], 0, coords[2]), w, 1); } else tp.getSamples(ifd, buf, x, y, w, h); plane.close(); plane = null; tp = null; return buf; } /* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */ public String[] getSeriesUsedFiles(boolean noPixels) { FormatTools.assertId(currentId, true, 1); if (isOIB) { return noPixels ? null : new String[] {currentId}; } Vector<String> files = new Vector<String>(); if (usedFiles != null) { for (String file : usedFiles) { String f = file.toLowerCase(); if (!f.endsWith(".tif") && !f.endsWith(".tiff") && !f.endsWith(".bmp")) { files.add(file); } } } if (!noPixels) { if (getSeries() == 0 && tiffs != null) { files.addAll(tiffs); } else if (getSeries() == 1 && previewNames != null) { files.addAll(previewNames); } } return files.toArray(new String[0]); } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (thumbReader != null) thumbReader.close(fileOnly); if (!fileOnly) { tiffs = usedFiles = null; filenames = new Hashtable<Integer, String>(); roiFilenames = new Hashtable<Integer, String>(); thumbReader = null; thumbId = null; isOIB = false; previewNames = null; if (poi != null) poi.close(); poi = null; lastChannel = 0; wavelengths = null; illuminations = null; oibMapping = null; code = size = null; pixelSize = null; imageDepth = 0; pixelSizeX = pixelSizeY = null; validBits = 0; pinholeSize = null; magnification = lensNA = objectiveName = workingDistance = null; creationDate = null; lut = null; channels = null; } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); parser.setCommentDelimiter(null); isOIB = checkSuffix(id, OIB_SUFFIX); if (isOIB) { try { ServiceFactory factory = new ServiceFactory(); poi = factory.getInstance(POIService.class); } catch (DependencyException de) { throw new FormatException("POI library not found", de); } poi.initialize(Location.getMappedId(id)); } // mappedOIF is used to distinguish between datasets that are being read // directly (e.g. using ImageJ or showinf), and datasets that are being // imported through omebf. In the latter case, the necessary directory // structure is not preserved (only relative file names are stored in // OMEIS), so we will need to use slightly different logic to build the // list of associated files. boolean mappedOIF = !isOIB && !new File(id).getAbsoluteFile().exists(); wavelengths = new Vector<Integer>(); illuminations = new Vector<String>(); channels = new Vector<ChannelData>(); String oifName = null; if (isOIB) { oifName = mapOIBFiles(); } else { // make sure we have the OIF file, not a TIFF if (!checkSuffix(id, OIF_SUFFIX)) { currentId = findOIFFile(id); initFile(currentId); } oifName = currentId; } String oifPath = new Location(oifName).getAbsoluteFile().getAbsolutePath(); String path = (isOIB || !oifPath.endsWith(oifName) || mappedOIF) ? "" : oifPath.substring(0, oifPath.lastIndexOf(File.separator) + 1); try { RandomAccessInputStream s = getFile(oifName); s.close(); } catch (IOException e) { oifName = oifName.replaceAll(".oif", ".OIF"); } // parse key/value pairs from the OIF file code = new String[NUM_DIMENSIONS]; size = new String[NUM_DIMENSIONS]; pixelSize = new Double[NUM_DIMENSIONS]; previewNames = new Vector<String>(); boolean laserEnabled = true; IniList f = getIniFile(oifName); IniTable saveInfo = f.getTable("ProfileSaveInfo"); String[] saveKeys = saveInfo.keySet().toArray(new String[saveInfo.size()]); for (String key : saveKeys) { String value = saveInfo.get(key).toString(); value = sanitizeValue(value).trim(); if (key.startsWith("IniFileName") && key.indexOf("Thumb") == -1 && !isPreviewName(value)) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1).trim(); } filenames.put(new Integer(key.substring(11)), value); } else if (key.startsWith("RoiFileName") && key.indexOf("Thumb") == -1 && !isPreviewName(value)) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1).trim(); } try { roiFilenames.put(new Integer(key.substring(11)), value); } catch (NumberFormatException e) { } } else if (key.equals("PtyFileNameS")) ptyStart = value; else if (key.equals("PtyFileNameE")) ptyEnd = value; else if (key.equals("PtyFileNameT2")) ptyPattern = value; else if (key.indexOf("Thumb") != -1) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1); } if (thumbId == null) thumbId = value.trim(); } else if (key.startsWith("LutFileName")) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1); } lutNames.add(path + value); } else if (isPreviewName(value)) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1); } previewNames.add(path + value.trim()); } } if (filenames.size() == 0) addPtyFiles(); for (int i=0; i<NUM_DIMENSIONS; i++) { IniTable commonParams = f.getTable("Axis " + i + " Parameters Common"); code[i] = commonParams.get("AxisCode"); size[i] = commonParams.get("MaxSize"); double end = Double.parseDouble(commonParams.get("EndPosition")); double start = Double.parseDouble(commonParams.get("StartPosition")); pixelSize[i] = end - start; } IniTable referenceParams = f.getTable("Reference Image Parameter"); imageDepth = Integer.parseInt(referenceParams.get("ImageDepth")); pixelSizeX = referenceParams.get("WidthConvertValue"); pixelSizeY = referenceParams.get("HeightConvertValue"); String ripValidBitCounts = referenceParams.get("ValidBitCounts"); if (ripValidBitCounts != null) { validBits = Integer.parseInt(ripValidBitCounts); } int index = 0; IniTable laser = f.getTable("Laser " + index + " Parameters"); while (laser != null) { laserEnabled = laser.get("Laser Enable").equals("1"); if (laserEnabled) { wavelengths.add(new Integer(laser.get("LaserWavelength"))); } creationDate = laser.get("ImageCaputreDate"); if (creationDate == null) { creationDate = laser.get("ImageCaptureDate"); } index++; laser = f.getTable("Laser " + index + " Parameters"); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { index = 1; IniTable guiChannel = f.getTable("GUI Channel " + index + " Parameters"); while (guiChannel != null) { ChannelData channel = new ChannelData(); String gain = guiChannel.get("AnalogPMTGain"); if (gain != null) channel.gain = new Double(gain); String voltage = guiChannel.get("AnalogPMTVoltage"); if (voltage != null) channel.voltage = new Double(voltage); channel.barrierFilter = guiChannel.get("BF Name"); channel.active = Integer.parseInt(guiChannel.get("CH Activate")) != 0; channel.name = guiChannel.get("CH Name"); channel.dyeName = guiChannel.get("DyeName"); channel.emissionFilter = guiChannel.get("EmissionDM Name"); channel.emWave = new Integer(guiChannel.get("EmissionWavelength")); channel.excitationFilter = guiChannel.get("ExcitationDM Name"); channel.exWave = new Integer(guiChannel.get("ExcitationWavelength")); channels.add(channel); index++; guiChannel = f.getTable("GUI Channel " + index + " Parameters"); } index = 1; IniTable channel = f.getTable("Channel " + index + " Parameters"); while (channel != null) { String illumination = channel.get("LightType"); if (illumination != null) illumination = illumination.toLowerCase(); if (illumination == null) { // Ignored } else if (illumination.indexOf("fluorescence") != -1) { illumination = "Epifluorescence"; } else if (illumination.indexOf("transmitted") != -1) { illumination = "Transmitted"; } else illumination = null; illuminations.add(illumination); index++; channel = f.getTable("Channel " + index + " Parameters"); } HashMap<String, String> iniMap = f.flattenIntoHashMap(); metadata.putAll(iniMap); } LOGGER.info("Initializing helper readers"); // populate core metadata for preview series if (previewNames.size() > 0) { Vector<String> v = new Vector<String>(); for (int i=0; i<previewNames.size(); i++) { String ss = previewNames.get(i); ss = replaceExtension(ss, "pty", "tif"); if (ss.endsWith(".tif")) v.add(ss); } previewNames = v; if (previewNames.size() > 0) { core = new CoreMetadata[2]; core[0] = new CoreMetadata(); core[1] = new CoreMetadata(); IFDList ifds = null; for (String previewName : previewNames) { RandomAccessInputStream preview = getFile(previewName); TiffParser tp = new TiffParser(preview); ifds = tp.getIFDs(); preview.close(); tp = null; core[1].imageCount += ifds.size(); } core[1].sizeX = (int) ifds.get(0).getImageWidth(); core[1].sizeY = (int) ifds.get(0).getImageLength(); core[1].sizeZ = 1; core[1].sizeT = 1; core[1].sizeC = core[1].imageCount; core[1].rgb = false; int bits = ifds.get(0).getBitsPerSample()[0]; while ((bits % 8) != 0) bits++; bits /= 8; core[1].pixelType = FormatTools.pixelTypeFromBytes(bits, false, false); core[1].dimensionOrder = "XYCZT"; core[1].indexed = false; } } core[0].imageCount = filenames.size(); tiffs = new Vector<String>(getImageCount()); thumbReader = new BMPReader(); thumbId = replaceExtension(thumbId, "pty", "bmp"); thumbId = sanitizeFile(thumbId, path); LOGGER.info("Reading additional metadata"); // open each INI file (.pty extension) and build list of TIFF files String tiffPath = null; core[0].dimensionOrder = "XY"; Hashtable<String, String> values = new Hashtable<String, String>(); Vector<String> baseKeys = new Vector<String>(); for (int i=0, ii=0; ii<getImageCount(); i++, ii++) { String file = filenames.get(new Integer(i)); while (file == null) file = filenames.get(new Integer(++i)); file = sanitizeFile(file, path); if (file.indexOf(File.separator) != -1) { tiffPath = file.substring(0, file.lastIndexOf(File.separator)); } else tiffPath = file; Location ptyFile = new Location(file); if (!isOIB && !ptyFile.exists()) { LOGGER.warn("Could not find .pty file ({}); guessing at the " + "corresponding TIFF file.", file); String tiff = replaceExtension(file, ".pty", ".tif"); tiffs.add(ii, tiff); continue; } IniList pty = getIniFile(file); IniTable fileInfo = pty.getTable("File Info"); file = sanitizeValue(fileInfo.get("DataName")); if (!isPreviewName(file)) { while (file.indexOf("GST") != -1) { file = removeGST(file); } if (!mappedOIF) { if (isOIB) { file = tiffPath + File.separator + file; } else file = new Location(tiffPath, file).getAbsolutePath(); } tiffs.add(ii, file); } for (int dim=0; dim<NUM_DIMENSIONS; dim++) { IniTable axis = pty.getTable("Axis " + dim + " Parameters"); if (axis == null) break; boolean addAxis = Integer.parseInt(axis.get("Number")) > 1; if (dim == 2) { if (addAxis && getDimensionOrder().indexOf("C") == -1) { core[0].dimensionOrder += "C"; } } else if (dim == 3) { if (addAxis && getDimensionOrder().indexOf("Z") == -1) { core[0].dimensionOrder += "Z"; } } else if (dim == 4) { if (addAxis && getDimensionOrder().indexOf("T") == -1) { core[0].dimensionOrder += "T"; } } } core[0].bitsPerPixel = validBits; IniTable acquisition = pty.getTable("Acquisition Parameters Common"); if (acquisition != null) { magnification = acquisition.get("Magnification"); lensNA = acquisition.get("ObjectiveLens NAValue"); objectiveName = acquisition.get("ObjectiveLens Name"); workingDistance = acquisition.get("ObjectiveLens WDValue"); pinholeSize = acquisition.get("PinholeDiameter"); String validBitCounts = acquisition.get("ValidBitCounts"); if (validBitCounts != null) { core[0].bitsPerPixel = Integer.parseInt(validBitCounts); } } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { for (IniTable table : pty) { String[] keys = table.keySet().toArray(new String[table.size()]); for (String key : keys) { values.put("Image " + ii + " : " + key, table.get(key)); if (!baseKeys.contains(key)) baseKeys.add(key); } } } } for (String key : baseKeys) { if (key.equals("DataName") || key.indexOf("FileName") >= 0) break; boolean equal = true; String first = values.get("Image 0 : " + key); for (int i=1; i<getImageCount(); i++) { if (!first.equals(values.get("Image " + i + " : " + key))) { equal = false; break; } } if (equal) { addGlobalMeta(key, first); } else { for (int i=0; i<getImageCount(); i++) { String k = "Image " + i + " : " + key; addGlobalMeta(k, values.get(k)); } } } if (tiffs.size() != getImageCount()) { core[0].imageCount = tiffs.size(); } usedFiles = new Vector<String>(); if (tiffPath != null) { usedFiles.add(isOIB ? id : oifName); if (!isOIB) { Location dir = new Location(tiffPath); if (!dir.exists()) { throw new FormatException( "Required directory " + tiffPath + " was not found."); } String[] list = mappedOIF ? Location.getIdMap().keySet().toArray(new String[0]) : dir.list(true); for (int i=0; i<list.length; i++) { if (mappedOIF) usedFiles.add(list[i]); else { String p = new Location(tiffPath, list[i]).getAbsolutePath(); String check = p.toLowerCase(); if (!check.endsWith(".tif") && !check.endsWith(".pty") && !check.endsWith(".roi") && !check.endsWith(".lut") && !check.endsWith(".bmp")) { continue; } usedFiles.add(p); } } } } LOGGER.info("Populating metadata"); // calculate axis sizes int realChannels = 0; for (int i=0; i<NUM_DIMENSIONS; i++) { int ss = Integer.parseInt(size[i]); if (pixelSize[i] == null) pixelSize[i] = 1.0; if (code[i].equals("X")) core[0].sizeX = ss; else if (code[i].equals("Y") && ss > 1) core[0].sizeY = ss; else if (code[i].equals("Z")) { if (getSizeY() == 0) { core[0].sizeY = ss; } else { core[0].sizeZ = ss; // Z size stored in nm pixelSizeZ = Math.abs((pixelSize[i].doubleValue() / (getSizeZ() - 1)) / 1000); } } else if (code[i].equals("T")) { if (getSizeY() == 0) { core[0].sizeY = ss; } else { core[0].sizeT = ss; pixelSizeT = Math.abs((pixelSize[i].doubleValue() / (getSizeT() - 1)) / 1000); } } else if (ss > 0) { if (getSizeC() == 0) core[0].sizeC = ss; else core[0].sizeC *= ss; if (code[i].equals("C")) realChannels = ss; } } if (getSizeZ() == 0) core[0].sizeZ = 1; if (getSizeC() == 0) core[0].sizeC = 1; if (getSizeT() == 0) core[0].sizeT = 1; if (getImageCount() == getSizeC() && getSizeY() == 1) { core[0].imageCount *= getSizeZ() * getSizeT(); } else if (getImageCount() == getSizeC()) { core[0].sizeZ = 1; core[0].sizeT = 1; } if (getSizeZ() * getSizeT() * getSizeC() != getImageCount()) { int diff = (getSizeZ() * getSizeC() * getSizeT()) - getImageCount(); if (diff == previewNames.size() || diff < 0) { diff /= getSizeC(); if (getSizeT() > 1 && getSizeZ() == 1) core[0].sizeT -= diff; else if (getSizeZ() > 1 && getSizeT() == 1) core[0].sizeZ -= diff; } else core[0].imageCount += diff; } if (getSizeC() > 1 && getSizeZ() == 1 && getSizeT() == 1) { if (getDimensionOrder().indexOf("C") == -1) core[0].dimensionOrder += "C"; } if (getDimensionOrder().indexOf("Z") == -1) core[0].dimensionOrder += "Z"; if (getDimensionOrder().indexOf("C") == -1) core[0].dimensionOrder += "C"; if (getDimensionOrder().indexOf("T") == -1) core[0].dimensionOrder += "T"; core[0].pixelType = FormatTools.pixelTypeFromBytes(imageDepth, false, false); // set up thumbnail file mapping try { RandomAccessInputStream thumb = getFile(thumbId); byte[] b = new byte[(int) thumb.length()]; thumb.read(b); thumb.close(); Location.mapFile("thumbnail.bmp", new ByteArrayHandle(b)); thumbReader.setId("thumbnail.bmp"); for (int i=0; i<getSeriesCount(); i++) { core[i].thumbSizeX = thumbReader.getSizeX(); core[i].thumbSizeY = thumbReader.getSizeY(); } Location.mapFile("thumbnail.bmp", null); } catch (IOException e) { LOGGER.debug("Could not read thumbnail", e); } catch (FormatException e) { LOGGER.debug("Could not read thumbnail", e); } // initialize lookup table lut = new short[getSizeC()][3][65536]; byte[] buffer = new byte[65536 * 4]; int count = (int) Math.min(getSizeC(), lutNames.size()); for (int c=0; c<count; c++) { Exception exc = null; try { RandomAccessInputStream stream = getFile(lutNames.get(c)); stream.seek(stream.length() - 65536 * 4); stream.read(buffer); stream.close(); for (int q=0; q<buffer.length; q+=4) { - lut[c][0][q / 4] = buffer[q + 1]; - lut[c][1][q / 4] = buffer[q + 2]; - lut[c][2][q / 4] = buffer[q + 3]; + lut[c][0][q / 4] = buffer[q + 2]; + lut[c][1][q / 4] = buffer[q + 1]; + lut[c][2][q / 4] = buffer[q]; } } catch (IOException e) { exc = e; } catch (FormatException e) { exc = e; } if (exc != null) { LOGGER.debug("Could not read LUT", exc); lut = null; break; } } for (int i=0; i<getSeriesCount(); i++) { core[i].rgb = false; core[i].littleEndian = true; core[i].interleaved = false; core[i].metadataComplete = true; - core[i].indexed = false; + core[i].indexed = lut != null; core[i].falseColor = false; } // populate MetadataStore MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); if (creationDate != null) { creationDate = creationDate.replaceAll("'", ""); creationDate = DateTools.formatDate(creationDate, DATE_FORMAT); } for (int i=0; i<getSeriesCount(); i++) { // populate Image data store.setImageName("Series " + (i + 1), i); if (creationDate != null) store.setImageAcquiredDate(creationDate, i); else MetadataTools.setDefaultCreationDate(store, id, i); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { populateMetadataStore(store, path); } } private void populateMetadataStore(MetadataStore store, String path) throws FormatException, IOException { String instrumentID = MetadataTools.createLSID("Instrument", 0); store.setInstrumentID(instrumentID, 0); for (int i=0; i<getSeriesCount(); i++) { // link Instrument and Image store.setImageInstrumentRef(instrumentID, i); // populate Dimensions data if (pixelSizeX != null) { store.setPixelsPhysicalSizeX(new Double(pixelSizeX), i); } if (pixelSizeY != null) { store.setPixelsPhysicalSizeY(new Double(pixelSizeY), i); } if (pixelSizeZ == Double.NEGATIVE_INFINITY || pixelSizeZ == Double.POSITIVE_INFINITY || getSizeZ() == 1) { pixelSizeZ = 0d; } if (pixelSizeT == Double.NEGATIVE_INFINITY || pixelSizeT == Double.POSITIVE_INFINITY || getSizeT() == 1) { pixelSizeT = 0d; } store.setPixelsPhysicalSizeZ(pixelSizeZ, i); store.setPixelsTimeIncrement(pixelSizeT, i); // populate LogicalChannel data for (int c=0; c<core[i].sizeC; c++) { if (c < illuminations.size()) { store.setChannelIlluminationType( getIlluminationType(illuminations.get(c)), i, c); } } } int channelIndex = 0; for (ChannelData channel : channels) { if (!channel.active) continue; if (channelIndex >= getEffectiveSizeC()) break; // populate Detector data String detectorID = MetadataTools.createLSID("Detector", 0, channelIndex); store.setDetectorID(detectorID, 0, channelIndex); store.setDetectorSettingsID(detectorID, 0, channelIndex); store.setDetectorGain(channel.gain, 0, channelIndex); store.setDetectorVoltage(channel.voltage, 0, channelIndex); store.setDetectorType(getDetectorType("PMT"), 0, channelIndex); // populate LogicalChannel data store.setChannelName(channel.name, 0, channelIndex); String lightSourceID = MetadataTools.createLSID("LightSource", 0, channelIndex); store.setChannelLightSourceSettingsID(lightSourceID, 0, channelIndex); if (channel.emWave.intValue() > 0) { store.setChannelEmissionWavelength( new PositiveInteger(channel.emWave), 0, channelIndex); } if (channel.exWave.intValue() > 0) { store.setChannelExcitationWavelength( new PositiveInteger(channel.exWave), 0, channelIndex); store.setChannelLightSourceSettingsWavelength( new PositiveInteger(channel.exWave), 0, channelIndex); } // populate Filter data if (channel.barrierFilter != null) { String filterID = MetadataTools.createLSID("Filter", 0, channelIndex); store.setFilterID(filterID, 0, channelIndex); store.setFilterModel(channel.barrierFilter, 0, channelIndex); if (channel.barrierFilter.indexOf("-") != -1) { String[] emValues = channel.barrierFilter.split("-"); for (int i=0; i<emValues.length; i++) { emValues[i] = emValues[i].replaceAll("\\D", ""); } try { store.setTransmittanceRangeCutIn( PositiveInteger.valueOf(emValues[0]), 0, channelIndex); store.setTransmittanceRangeCutOut( PositiveInteger.valueOf(emValues[1]), 0, channelIndex); } catch (NumberFormatException e) { } } store.setLightPathEmissionFilterRef(filterID, 0, channelIndex, 0); } // populate FilterSet data int emIndex = channelIndex * 2; int exIndex = channelIndex * 2 + 1; String emFilter = MetadataTools.createLSID("Dichroic", 0, emIndex); String exFilter = MetadataTools.createLSID("Dichroic", 0, exIndex); // populate Dichroic data store.setDichroicID(emFilter, 0, emIndex); store.setDichroicModel(channel.emissionFilter, 0, emIndex); store.setDichroicID(exFilter, 0, exIndex); store.setDichroicModel(channel.excitationFilter, 0, exIndex); store.setLightPathDichroicRef(exFilter, 0, channelIndex); // populate Laser data store.setLaserID(lightSourceID, 0, channelIndex); store.setLaserLaserMedium(getLaserMedium(channel.dyeName), 0, channelIndex); if (channelIndex < wavelengths.size()) { store.setLaserWavelength( new PositiveInteger(wavelengths.get(channelIndex)), 0, channelIndex); } store.setLaserType(getLaserType("Other"), 0, channelIndex); channelIndex++; } // populate Objective data if (lensNA != null) store.setObjectiveLensNA(new Double(lensNA), 0, 0); store.setObjectiveModel(objectiveName, 0, 0); if (magnification != null) { int mag = (int) Float.parseFloat(magnification); store.setObjectiveNominalMagnification(new PositiveInteger(mag), 0, 0); } if (workingDistance != null) { store.setObjectiveWorkingDistance(new Double(workingDistance), 0, 0); } store.setObjectiveCorrection(getCorrection("Other"), 0, 0); store.setObjectiveImmersion(getImmersion("Other"), 0, 0); // link Objective to Image using ObjectiveSettings String objectiveID = MetadataTools.createLSID("Objective", 0, 0); store.setObjectiveID(objectiveID, 0, 0); store.setImageObjectiveSettingsID(objectiveID, 0); if (getMetadataOptions().getMetadataLevel() != MetadataLevel.NO_OVERLAYS) { int nextROI = -1; // populate ROI data - there is one ROI file per plane for (int i=0; i<roiFilenames.size(); i++) { if (i >= getImageCount()) break; String filename = roiFilenames.get(new Integer(i)); filename = sanitizeFile(filename, path); nextROI = parseROIFile(filename, store, nextROI, i); } } } private int parseROIFile(String filename, MetadataStore store, int nextROI, int plane) throws FormatException, IOException { int[] coordinates = getZCTCoords(plane); IniList roiFile = null; try { roiFile = getIniFile(filename); } catch (FormatException e) { LOGGER.debug("Could not parse ROI file {}", filename, e); return nextROI; } catch (IOException e) { LOGGER.debug("Could not parse ROI file {}", filename, e); return nextROI; } boolean validROI = false; int shape = -1; int shapeType = -1; String[] xc = null, yc = null; int divide = 0; int fontSize = 0, lineWidth = 0, angle = 0; String fontName = null, name = null; for (IniTable table : roiFile) { String tableName = table.get(IniTable.HEADER_KEY); if (tableName.equals("ROIBase FileInformation")) { try { String roiName = table.get("Name").replaceAll("\"", ""); validROI = Integer.parseInt(roiName) > 1; } catch (NumberFormatException e) { validROI = false; } if (!validROI) continue; } else if (tableName.equals("ROIBase Body")) { shapeType = Integer.parseInt(table.get("SHAPE")); divide = Integer.parseInt(table.get("DIVIDE")); String[] fontAttributes = table.get("FONT").split(","); fontName = fontAttributes[0]; fontSize = Integer.parseInt(fontAttributes[1]); lineWidth = Integer.parseInt(table.get("LINEWIDTH")); name = table.get("NAME"); angle = Integer.parseInt(table.get("ANGLE")); xc = table.get("X").split(","); yc = table.get("Y").split(","); int x = Integer.parseInt(xc[0]); int width = xc.length > 1 ? Integer.parseInt(xc[1]) - x : 0; int y = Integer.parseInt(yc[0]); int height = yc.length > 1 ? Integer.parseInt(yc[1]) - y : 0; if (width + x <= getSizeX() && height + y <= getSizeY()) { shape++; Integer zIndex = new Integer(coordinates[0]); Integer tIndex = new Integer(coordinates[2]); if (shape == 0) { nextROI++; String roiID = MetadataTools.createLSID("ROI", nextROI); store.setROIID(roiID, nextROI); store.setImageROIRef(roiID, 0, nextROI); } String shapeID = MetadataTools.createLSID("Shape", nextROI, shape); if (shapeType == POINT) { store.setPointID(shapeID, nextROI, shape); store.setPointTheZ(new NonNegativeInteger(zIndex), nextROI, shape); store.setPointTheT(new NonNegativeInteger(tIndex), nextROI, shape); store.setPointFontSize( new NonNegativeInteger(fontSize), nextROI, shape); store.setPointStrokeWidth(new Double(lineWidth), nextROI, shape); store.setPointX(new Double(xc[0]), nextROI, shape); store.setPointY(new Double(yc[0]), nextROI, shape); } else if (shapeType == GRID || shapeType == RECTANGLE) { if (shapeType == RECTANGLE) divide = 1; width /= divide; height /= divide; for (int row=0; row<divide; row++) { for (int col=0; col<divide; col++) { double realX = x + col * width; double realY = y + row * height; shapeID = MetadataTools.createLSID("Shape", nextROI, shape); store.setRectangleID(shapeID, nextROI, shape); store.setRectangleX(realX, nextROI, shape); store.setRectangleY(realY, nextROI, shape); store.setRectangleWidth(new Double(width), nextROI, shape); store.setRectangleHeight(new Double(height), nextROI, shape); store.setRectangleTheZ( new NonNegativeInteger(zIndex), nextROI, shape); store.setRectangleTheT( new NonNegativeInteger(tIndex), nextROI, shape); store.setRectangleFontSize( new NonNegativeInteger(fontSize), nextROI, shape); store.setRectangleStrokeWidth( new Double(lineWidth), nextROI, shape); double centerX = realX + (width / 2); double centerY = realY + (height / 2); store.setRectangleTransform(String.format(ROTATION, angle, centerX, centerY), nextROI, shape); if (row < divide - 1 || col < divide - 1) shape++; } } } else if (shapeType == LINE) { store.setLineID(shapeID, nextROI, shape); store.setLineX1(new Double(x), nextROI, shape); store.setLineY1(new Double(y), nextROI, shape); store.setLineX2(new Double(x + width), nextROI, shape); store.setLineY2(new Double(y + height), nextROI, shape); store.setLineTheZ(new NonNegativeInteger(zIndex), nextROI, shape); store.setLineTheT(new NonNegativeInteger(tIndex), nextROI, shape); store.setLineFontSize( new NonNegativeInteger(fontSize), nextROI, shape); store.setLineStrokeWidth(new Double(lineWidth), nextROI, shape); int centerX = x + (width / 2); int centerY = y + (height / 2); store.setLineTransform(String.format(ROTATION, angle, (float) centerX, (float) centerY), nextROI, shape); } else if (shapeType == CIRCLE || shapeType == ELLIPSE) { double rx = width / 2; double ry = shapeType == CIRCLE ? rx : height / 2; store.setEllipseID(shapeID, nextROI, shape); store.setEllipseX(x + rx, nextROI, shape); store.setEllipseY(y + ry, nextROI, shape); store.setEllipseRadiusX(rx, nextROI, shape); store.setEllipseRadiusY(ry, nextROI, shape); store.setEllipseTheZ( new NonNegativeInteger(zIndex), nextROI, shape); store.setEllipseTheT( new NonNegativeInteger(tIndex), nextROI, shape); store.setEllipseFontSize( new NonNegativeInteger(fontSize), nextROI, shape); store.setEllipseStrokeWidth(new Double(lineWidth), nextROI, shape); store.setEllipseTransform(String.format(ROTATION, angle, x + rx, y + ry), nextROI, shape); } else if (shapeType == POLYGON || shapeType == FREE_SHAPE || shapeType == POLYLINE || shapeType == FREE_LINE) { StringBuffer points = new StringBuffer(); for (int point=0; point<xc.length; point++) { points.append(xc[point]); points.append(","); points.append(yc[point]); if (point < xc.length - 1) points.append(" "); } store.setPolylineID(shapeID, nextROI, shape); store.setPolylinePoints(points.toString(), nextROI, shape); store.setPolylineTransform("rotate(" + angle + ")", nextROI, shape); store.setPolylineClosed( shapeType == POLYGON || shapeType == FREE_SHAPE, nextROI, shape); store.setPolylineTheZ( new NonNegativeInteger(zIndex), nextROI, shape); store.setPolylineTheT( new NonNegativeInteger(tIndex), nextROI, shape); store.setPolylineFontSize( new NonNegativeInteger(fontSize), nextROI, shape); store.setPolylineStrokeWidth(new Double(lineWidth), nextROI, shape); } else { if (shape == 0) nextROI--; shape--; } } } } return nextROI; } private void addPtyFiles() throws FormatException { if (ptyStart != null && ptyEnd != null && ptyPattern != null) { // FV1000 version 2 gives the first .pty file, the last .pty and // the file name pattern. Version 1 lists each .pty file individually. // pattern is typically 's_C%03dT%03d.pty' // build list of block indexes String[] prefixes = ptyPattern.split("%03d"); // get first and last numbers for each block int[] first = scanFormat(ptyPattern, ptyStart); int[] last = scanFormat(ptyPattern, ptyEnd); int[] lengths = new int[prefixes.length - 1]; int totalFiles = 1; for (int i=0; i<first.length; i++) { lengths[i] = last[i] - first[i] + 1; totalFiles *= lengths[i]; } // add each .pty file for (int file=0; file<totalFiles; file++) { int[] pos = FormatTools.rasterToPosition(lengths, file); StringBuffer pty = new StringBuffer(); for (int block=0; block<prefixes.length; block++) { pty.append(prefixes[block]); if (block < pos.length) { String num = String.valueOf(pos[block] + 1); for (int q=0; q<3 - num.length(); q++) { pty.append("0"); } pty.append(num); } } filenames.put(new Integer(file), pty.toString()); } } } // -- Helper methods -- private String findOIFFile(String baseFile) throws FormatException { Location current = new Location(baseFile).getAbsoluteFile(); String parent = current.getParent(); Location tmp = new Location(parent).getParentFile(); parent = tmp.getAbsolutePath(); baseFile = current.getName(); if (baseFile == null || baseFile.indexOf("_") == -1) return null; baseFile = baseFile.substring(0, baseFile.lastIndexOf("_")); if (checkSuffix(current.getName(), new String[] {"roi", "lut"})) { if (!new Location(tmp, baseFile + ".oif").exists() && !new Location(tmp, baseFile + ".OIF").exists() && baseFile.indexOf("_") >= 0) { // some metadata files have an extra underscore baseFile = baseFile.substring(0, baseFile.lastIndexOf("_")); } } baseFile += ".oif"; tmp = new Location(tmp, baseFile); String oifFile = tmp.getAbsolutePath(); if (!tmp.exists()) { oifFile = oifFile.substring(0, oifFile.lastIndexOf(".")) + ".OIF"; tmp = new Location(oifFile); if (!tmp.exists()) { baseFile = current.getParent(); baseFile = baseFile.substring(0, baseFile.lastIndexOf(".")); baseFile = baseFile.substring(0, baseFile.lastIndexOf(".")); tmp = new Location(baseFile + ".oif"); oifFile = tmp.getAbsolutePath(); if (!tmp.exists()) { tmp = new Location(tmp.getParent(), tmp.getName().toUpperCase()); oifFile = tmp.getAbsolutePath(); if (!tmp.exists()) { // check in parent directory if (parent.endsWith(File.separator)) { parent = parent.substring(0, parent.length() - 1); } String dir = parent.substring(parent.lastIndexOf(File.separator)); dir = dir.substring(0, dir.lastIndexOf(".")); tmp = new Location(parent); oifFile = new Location(tmp, dir).getAbsolutePath(); if (!new Location(oifFile).exists()) { throw new FormatException("OIF file not found"); } } } } } return oifFile; } private String mapOIBFiles() throws FormatException, IOException { String oifName = null; String infoFile = null; Vector<String> list = poi.getDocumentList(); for (String name : list) { if (name.endsWith("OibInfo.txt")) { infoFile = name; break; } } if (infoFile == null) { throw new FormatException("OibInfo.txt not found in " + currentId); } RandomAccessInputStream ras = poi.getDocumentStream(infoFile); oibMapping = new Hashtable<String, String>(); // set up file name mappings String s = DataTools.stripString(ras.readString((int) ras.length())); ras.close(); String[] lines = s.split("\n"); // sort the lines to ensure that the // directory key is before the file names Arrays.sort(lines); String directoryKey = null, directoryValue = null, key = null, value = null; for (String line : lines) { line = line.trim(); if (line.indexOf("=") != -1) { key = line.substring(0, line.indexOf("=")); value = line.substring(line.indexOf("=") + 1); if (directoryKey != null && directoryValue != null) { value = value.replaceAll(directoryKey, directoryValue); } value = removeGST(value); if (key.startsWith("Stream")) { value = sanitizeFile(value, ""); if (checkSuffix(value, OIF_SUFFIX)) oifName = value; if (directoryKey != null && value.startsWith(directoryValue)) { oibMapping.put(value, "Root Entry" + File.separator + directoryKey + File.separator + key); } else { oibMapping.put(value, "Root Entry" + File.separator + key); } } else if (key.startsWith("Storage")) { directoryKey = key; directoryValue = value; } } } s = null; return oifName; } private String sanitizeValue(String value) { String f = value.replaceAll("\"", ""); f = f.replace('\\', File.separatorChar); f = f.replace('/', File.separatorChar); while (f.indexOf("GST") != -1) { f = removeGST(f); } return f; } private String sanitizeFile(String file, String path) { String f = sanitizeValue(file); if (path.equals("")) return f; return path + File.separator + f; } private String removeGST(String s) { if (s.indexOf("GST") != -1) { String first = s.substring(0, s.indexOf("GST")); int ndx = s.indexOf(File.separator) < s.indexOf("GST") ? s.length() : s.indexOf(File.separator); String last = s.substring(s.lastIndexOf("=", ndx) + 1); return first + last; } return s; } private RandomAccessInputStream getFile(String name) throws FormatException, IOException { if (isOIB) { name = name.replace('\\', File.separatorChar); name = name.replace('/', File.separatorChar); String realName = oibMapping.get(name); if (realName == null) { throw new FormatException("File " + name + " not found."); } return poi.getDocumentStream(realName); } else return new RandomAccessInputStream(name); } private boolean isPreviewName(String name) { // "-R" in the file name indicates that this is a preview image int index = name.indexOf("-R"); return index == name.length() - 9; } private String replaceExtension(String name, String oldExt, String newExt) { if (!name.endsWith("." + oldExt)) { return name; } return name.substring(0, name.length() - oldExt.length()) + newExt; } /* Return the numbers in the given string matching %..d style patterns */ private static int[] scanFormat(String pattern, String string) throws FormatException { Vector<Integer> percentOffsets = new Vector<Integer>(); int offset = -1; for (;;) { offset = pattern.indexOf('%', offset + 1); if (offset < 0 || offset + 1 >= pattern.length()) { break; } if (pattern.charAt(offset + 1) == '%') { continue; } percentOffsets.add(new Integer(offset)); } int[] result = new int[percentOffsets.size()]; int patternOffset = 0; offset = 0; for (int i=0; i<result.length; i++) { int percent = percentOffsets.get(i).intValue(); if (!string.regionMatches(offset, pattern, patternOffset, percent - patternOffset)) { throw new FormatException("String '" + string + "' does not match format '" + pattern + "'"); } offset += percent - patternOffset; patternOffset = percent; int endOffset = offset; while (endOffset < string.length() && Character.isDigit(string.charAt(endOffset))) { endOffset++; } result[i] = Integer.parseInt(string.substring(offset, endOffset)); offset = endOffset; while (++patternOffset < pattern.length() && pattern.charAt(patternOffset - 1) != 'd') { ; /* do nothing */ } } int remaining = pattern.length() - patternOffset; if (string.length() - offset != remaining || !string.regionMatches(offset, pattern, patternOffset, remaining)) { throw new FormatException("String '" + string + "' does not match format '" + pattern + "'"); } return result; } private IniList getIniFile(String filename) throws FormatException, IOException { RandomAccessInputStream stream = getFile(filename); String data = stream.readString((int) stream.length()); if (!data.startsWith("[")) { data = data.substring(data.indexOf("["), data.length()); } data = DataTools.stripString(data); BufferedReader reader = new BufferedReader(new StringReader(data)); stream.close(); IniList list = parser.parseINI(reader); // most of the values will be wrapped in double quotes for (IniTable table : list) { LOGGER.debug(""); LOGGER.debug("[" + table.get(IniTable.HEADER_KEY) + "]"); String[] keys = table.keySet().toArray(new String[table.size()]); for (String key : keys) { String value = sanitizeValue(table.get(key)); LOGGER.debug(key + " = " + value); table.put(key, value); } } reader.close(); return list; } // -- Helper classes -- class ChannelData { public boolean active; public Double gain; public Double voltage; public String name; public String emissionFilter; public String excitationFilter; public Integer emWave; public Integer exWave; public String dyeName; public String barrierFilter; } }
false
true
protected void initFile(String id) throws FormatException, IOException { super.initFile(id); parser.setCommentDelimiter(null); isOIB = checkSuffix(id, OIB_SUFFIX); if (isOIB) { try { ServiceFactory factory = new ServiceFactory(); poi = factory.getInstance(POIService.class); } catch (DependencyException de) { throw new FormatException("POI library not found", de); } poi.initialize(Location.getMappedId(id)); } // mappedOIF is used to distinguish between datasets that are being read // directly (e.g. using ImageJ or showinf), and datasets that are being // imported through omebf. In the latter case, the necessary directory // structure is not preserved (only relative file names are stored in // OMEIS), so we will need to use slightly different logic to build the // list of associated files. boolean mappedOIF = !isOIB && !new File(id).getAbsoluteFile().exists(); wavelengths = new Vector<Integer>(); illuminations = new Vector<String>(); channels = new Vector<ChannelData>(); String oifName = null; if (isOIB) { oifName = mapOIBFiles(); } else { // make sure we have the OIF file, not a TIFF if (!checkSuffix(id, OIF_SUFFIX)) { currentId = findOIFFile(id); initFile(currentId); } oifName = currentId; } String oifPath = new Location(oifName).getAbsoluteFile().getAbsolutePath(); String path = (isOIB || !oifPath.endsWith(oifName) || mappedOIF) ? "" : oifPath.substring(0, oifPath.lastIndexOf(File.separator) + 1); try { RandomAccessInputStream s = getFile(oifName); s.close(); } catch (IOException e) { oifName = oifName.replaceAll(".oif", ".OIF"); } // parse key/value pairs from the OIF file code = new String[NUM_DIMENSIONS]; size = new String[NUM_DIMENSIONS]; pixelSize = new Double[NUM_DIMENSIONS]; previewNames = new Vector<String>(); boolean laserEnabled = true; IniList f = getIniFile(oifName); IniTable saveInfo = f.getTable("ProfileSaveInfo"); String[] saveKeys = saveInfo.keySet().toArray(new String[saveInfo.size()]); for (String key : saveKeys) { String value = saveInfo.get(key).toString(); value = sanitizeValue(value).trim(); if (key.startsWith("IniFileName") && key.indexOf("Thumb") == -1 && !isPreviewName(value)) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1).trim(); } filenames.put(new Integer(key.substring(11)), value); } else if (key.startsWith("RoiFileName") && key.indexOf("Thumb") == -1 && !isPreviewName(value)) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1).trim(); } try { roiFilenames.put(new Integer(key.substring(11)), value); } catch (NumberFormatException e) { } } else if (key.equals("PtyFileNameS")) ptyStart = value; else if (key.equals("PtyFileNameE")) ptyEnd = value; else if (key.equals("PtyFileNameT2")) ptyPattern = value; else if (key.indexOf("Thumb") != -1) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1); } if (thumbId == null) thumbId = value.trim(); } else if (key.startsWith("LutFileName")) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1); } lutNames.add(path + value); } else if (isPreviewName(value)) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1); } previewNames.add(path + value.trim()); } } if (filenames.size() == 0) addPtyFiles(); for (int i=0; i<NUM_DIMENSIONS; i++) { IniTable commonParams = f.getTable("Axis " + i + " Parameters Common"); code[i] = commonParams.get("AxisCode"); size[i] = commonParams.get("MaxSize"); double end = Double.parseDouble(commonParams.get("EndPosition")); double start = Double.parseDouble(commonParams.get("StartPosition")); pixelSize[i] = end - start; } IniTable referenceParams = f.getTable("Reference Image Parameter"); imageDepth = Integer.parseInt(referenceParams.get("ImageDepth")); pixelSizeX = referenceParams.get("WidthConvertValue"); pixelSizeY = referenceParams.get("HeightConvertValue"); String ripValidBitCounts = referenceParams.get("ValidBitCounts"); if (ripValidBitCounts != null) { validBits = Integer.parseInt(ripValidBitCounts); } int index = 0; IniTable laser = f.getTable("Laser " + index + " Parameters"); while (laser != null) { laserEnabled = laser.get("Laser Enable").equals("1"); if (laserEnabled) { wavelengths.add(new Integer(laser.get("LaserWavelength"))); } creationDate = laser.get("ImageCaputreDate"); if (creationDate == null) { creationDate = laser.get("ImageCaptureDate"); } index++; laser = f.getTable("Laser " + index + " Parameters"); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { index = 1; IniTable guiChannel = f.getTable("GUI Channel " + index + " Parameters"); while (guiChannel != null) { ChannelData channel = new ChannelData(); String gain = guiChannel.get("AnalogPMTGain"); if (gain != null) channel.gain = new Double(gain); String voltage = guiChannel.get("AnalogPMTVoltage"); if (voltage != null) channel.voltage = new Double(voltage); channel.barrierFilter = guiChannel.get("BF Name"); channel.active = Integer.parseInt(guiChannel.get("CH Activate")) != 0; channel.name = guiChannel.get("CH Name"); channel.dyeName = guiChannel.get("DyeName"); channel.emissionFilter = guiChannel.get("EmissionDM Name"); channel.emWave = new Integer(guiChannel.get("EmissionWavelength")); channel.excitationFilter = guiChannel.get("ExcitationDM Name"); channel.exWave = new Integer(guiChannel.get("ExcitationWavelength")); channels.add(channel); index++; guiChannel = f.getTable("GUI Channel " + index + " Parameters"); } index = 1; IniTable channel = f.getTable("Channel " + index + " Parameters"); while (channel != null) { String illumination = channel.get("LightType"); if (illumination != null) illumination = illumination.toLowerCase(); if (illumination == null) { // Ignored } else if (illumination.indexOf("fluorescence") != -1) { illumination = "Epifluorescence"; } else if (illumination.indexOf("transmitted") != -1) { illumination = "Transmitted"; } else illumination = null; illuminations.add(illumination); index++; channel = f.getTable("Channel " + index + " Parameters"); } HashMap<String, String> iniMap = f.flattenIntoHashMap(); metadata.putAll(iniMap); } LOGGER.info("Initializing helper readers"); // populate core metadata for preview series if (previewNames.size() > 0) { Vector<String> v = new Vector<String>(); for (int i=0; i<previewNames.size(); i++) { String ss = previewNames.get(i); ss = replaceExtension(ss, "pty", "tif"); if (ss.endsWith(".tif")) v.add(ss); } previewNames = v; if (previewNames.size() > 0) { core = new CoreMetadata[2]; core[0] = new CoreMetadata(); core[1] = new CoreMetadata(); IFDList ifds = null; for (String previewName : previewNames) { RandomAccessInputStream preview = getFile(previewName); TiffParser tp = new TiffParser(preview); ifds = tp.getIFDs(); preview.close(); tp = null; core[1].imageCount += ifds.size(); } core[1].sizeX = (int) ifds.get(0).getImageWidth(); core[1].sizeY = (int) ifds.get(0).getImageLength(); core[1].sizeZ = 1; core[1].sizeT = 1; core[1].sizeC = core[1].imageCount; core[1].rgb = false; int bits = ifds.get(0).getBitsPerSample()[0]; while ((bits % 8) != 0) bits++; bits /= 8; core[1].pixelType = FormatTools.pixelTypeFromBytes(bits, false, false); core[1].dimensionOrder = "XYCZT"; core[1].indexed = false; } } core[0].imageCount = filenames.size(); tiffs = new Vector<String>(getImageCount()); thumbReader = new BMPReader(); thumbId = replaceExtension(thumbId, "pty", "bmp"); thumbId = sanitizeFile(thumbId, path); LOGGER.info("Reading additional metadata"); // open each INI file (.pty extension) and build list of TIFF files String tiffPath = null; core[0].dimensionOrder = "XY"; Hashtable<String, String> values = new Hashtable<String, String>(); Vector<String> baseKeys = new Vector<String>(); for (int i=0, ii=0; ii<getImageCount(); i++, ii++) { String file = filenames.get(new Integer(i)); while (file == null) file = filenames.get(new Integer(++i)); file = sanitizeFile(file, path); if (file.indexOf(File.separator) != -1) { tiffPath = file.substring(0, file.lastIndexOf(File.separator)); } else tiffPath = file; Location ptyFile = new Location(file); if (!isOIB && !ptyFile.exists()) { LOGGER.warn("Could not find .pty file ({}); guessing at the " + "corresponding TIFF file.", file); String tiff = replaceExtension(file, ".pty", ".tif"); tiffs.add(ii, tiff); continue; } IniList pty = getIniFile(file); IniTable fileInfo = pty.getTable("File Info"); file = sanitizeValue(fileInfo.get("DataName")); if (!isPreviewName(file)) { while (file.indexOf("GST") != -1) { file = removeGST(file); } if (!mappedOIF) { if (isOIB) { file = tiffPath + File.separator + file; } else file = new Location(tiffPath, file).getAbsolutePath(); } tiffs.add(ii, file); } for (int dim=0; dim<NUM_DIMENSIONS; dim++) { IniTable axis = pty.getTable("Axis " + dim + " Parameters"); if (axis == null) break; boolean addAxis = Integer.parseInt(axis.get("Number")) > 1; if (dim == 2) { if (addAxis && getDimensionOrder().indexOf("C") == -1) { core[0].dimensionOrder += "C"; } } else if (dim == 3) { if (addAxis && getDimensionOrder().indexOf("Z") == -1) { core[0].dimensionOrder += "Z"; } } else if (dim == 4) { if (addAxis && getDimensionOrder().indexOf("T") == -1) { core[0].dimensionOrder += "T"; } } } core[0].bitsPerPixel = validBits; IniTable acquisition = pty.getTable("Acquisition Parameters Common"); if (acquisition != null) { magnification = acquisition.get("Magnification"); lensNA = acquisition.get("ObjectiveLens NAValue"); objectiveName = acquisition.get("ObjectiveLens Name"); workingDistance = acquisition.get("ObjectiveLens WDValue"); pinholeSize = acquisition.get("PinholeDiameter"); String validBitCounts = acquisition.get("ValidBitCounts"); if (validBitCounts != null) { core[0].bitsPerPixel = Integer.parseInt(validBitCounts); } } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { for (IniTable table : pty) { String[] keys = table.keySet().toArray(new String[table.size()]); for (String key : keys) { values.put("Image " + ii + " : " + key, table.get(key)); if (!baseKeys.contains(key)) baseKeys.add(key); } } } } for (String key : baseKeys) { if (key.equals("DataName") || key.indexOf("FileName") >= 0) break; boolean equal = true; String first = values.get("Image 0 : " + key); for (int i=1; i<getImageCount(); i++) { if (!first.equals(values.get("Image " + i + " : " + key))) { equal = false; break; } } if (equal) { addGlobalMeta(key, first); } else { for (int i=0; i<getImageCount(); i++) { String k = "Image " + i + " : " + key; addGlobalMeta(k, values.get(k)); } } } if (tiffs.size() != getImageCount()) { core[0].imageCount = tiffs.size(); } usedFiles = new Vector<String>(); if (tiffPath != null) { usedFiles.add(isOIB ? id : oifName); if (!isOIB) { Location dir = new Location(tiffPath); if (!dir.exists()) { throw new FormatException( "Required directory " + tiffPath + " was not found."); } String[] list = mappedOIF ? Location.getIdMap().keySet().toArray(new String[0]) : dir.list(true); for (int i=0; i<list.length; i++) { if (mappedOIF) usedFiles.add(list[i]); else { String p = new Location(tiffPath, list[i]).getAbsolutePath(); String check = p.toLowerCase(); if (!check.endsWith(".tif") && !check.endsWith(".pty") && !check.endsWith(".roi") && !check.endsWith(".lut") && !check.endsWith(".bmp")) { continue; } usedFiles.add(p); } } } } LOGGER.info("Populating metadata"); // calculate axis sizes int realChannels = 0; for (int i=0; i<NUM_DIMENSIONS; i++) { int ss = Integer.parseInt(size[i]); if (pixelSize[i] == null) pixelSize[i] = 1.0; if (code[i].equals("X")) core[0].sizeX = ss; else if (code[i].equals("Y") && ss > 1) core[0].sizeY = ss; else if (code[i].equals("Z")) { if (getSizeY() == 0) { core[0].sizeY = ss; } else { core[0].sizeZ = ss; // Z size stored in nm pixelSizeZ = Math.abs((pixelSize[i].doubleValue() / (getSizeZ() - 1)) / 1000); } } else if (code[i].equals("T")) { if (getSizeY() == 0) { core[0].sizeY = ss; } else { core[0].sizeT = ss; pixelSizeT = Math.abs((pixelSize[i].doubleValue() / (getSizeT() - 1)) / 1000); } } else if (ss > 0) { if (getSizeC() == 0) core[0].sizeC = ss; else core[0].sizeC *= ss; if (code[i].equals("C")) realChannels = ss; } } if (getSizeZ() == 0) core[0].sizeZ = 1; if (getSizeC() == 0) core[0].sizeC = 1; if (getSizeT() == 0) core[0].sizeT = 1; if (getImageCount() == getSizeC() && getSizeY() == 1) { core[0].imageCount *= getSizeZ() * getSizeT(); } else if (getImageCount() == getSizeC()) { core[0].sizeZ = 1; core[0].sizeT = 1; } if (getSizeZ() * getSizeT() * getSizeC() != getImageCount()) { int diff = (getSizeZ() * getSizeC() * getSizeT()) - getImageCount(); if (diff == previewNames.size() || diff < 0) { diff /= getSizeC(); if (getSizeT() > 1 && getSizeZ() == 1) core[0].sizeT -= diff; else if (getSizeZ() > 1 && getSizeT() == 1) core[0].sizeZ -= diff; } else core[0].imageCount += diff; } if (getSizeC() > 1 && getSizeZ() == 1 && getSizeT() == 1) { if (getDimensionOrder().indexOf("C") == -1) core[0].dimensionOrder += "C"; } if (getDimensionOrder().indexOf("Z") == -1) core[0].dimensionOrder += "Z"; if (getDimensionOrder().indexOf("C") == -1) core[0].dimensionOrder += "C"; if (getDimensionOrder().indexOf("T") == -1) core[0].dimensionOrder += "T"; core[0].pixelType = FormatTools.pixelTypeFromBytes(imageDepth, false, false); // set up thumbnail file mapping try { RandomAccessInputStream thumb = getFile(thumbId); byte[] b = new byte[(int) thumb.length()]; thumb.read(b); thumb.close(); Location.mapFile("thumbnail.bmp", new ByteArrayHandle(b)); thumbReader.setId("thumbnail.bmp"); for (int i=0; i<getSeriesCount(); i++) { core[i].thumbSizeX = thumbReader.getSizeX(); core[i].thumbSizeY = thumbReader.getSizeY(); } Location.mapFile("thumbnail.bmp", null); } catch (IOException e) { LOGGER.debug("Could not read thumbnail", e); } catch (FormatException e) { LOGGER.debug("Could not read thumbnail", e); } // initialize lookup table lut = new short[getSizeC()][3][65536]; byte[] buffer = new byte[65536 * 4]; int count = (int) Math.min(getSizeC(), lutNames.size()); for (int c=0; c<count; c++) { Exception exc = null; try { RandomAccessInputStream stream = getFile(lutNames.get(c)); stream.seek(stream.length() - 65536 * 4); stream.read(buffer); stream.close(); for (int q=0; q<buffer.length; q+=4) { lut[c][0][q / 4] = buffer[q + 1]; lut[c][1][q / 4] = buffer[q + 2]; lut[c][2][q / 4] = buffer[q + 3]; } } catch (IOException e) { exc = e; } catch (FormatException e) { exc = e; } if (exc != null) { LOGGER.debug("Could not read LUT", exc); lut = null; break; } } for (int i=0; i<getSeriesCount(); i++) { core[i].rgb = false; core[i].littleEndian = true; core[i].interleaved = false; core[i].metadataComplete = true; core[i].indexed = false; core[i].falseColor = false; } // populate MetadataStore MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); if (creationDate != null) { creationDate = creationDate.replaceAll("'", ""); creationDate = DateTools.formatDate(creationDate, DATE_FORMAT); } for (int i=0; i<getSeriesCount(); i++) { // populate Image data store.setImageName("Series " + (i + 1), i); if (creationDate != null) store.setImageAcquiredDate(creationDate, i); else MetadataTools.setDefaultCreationDate(store, id, i); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { populateMetadataStore(store, path); } }
protected void initFile(String id) throws FormatException, IOException { super.initFile(id); parser.setCommentDelimiter(null); isOIB = checkSuffix(id, OIB_SUFFIX); if (isOIB) { try { ServiceFactory factory = new ServiceFactory(); poi = factory.getInstance(POIService.class); } catch (DependencyException de) { throw new FormatException("POI library not found", de); } poi.initialize(Location.getMappedId(id)); } // mappedOIF is used to distinguish between datasets that are being read // directly (e.g. using ImageJ or showinf), and datasets that are being // imported through omebf. In the latter case, the necessary directory // structure is not preserved (only relative file names are stored in // OMEIS), so we will need to use slightly different logic to build the // list of associated files. boolean mappedOIF = !isOIB && !new File(id).getAbsoluteFile().exists(); wavelengths = new Vector<Integer>(); illuminations = new Vector<String>(); channels = new Vector<ChannelData>(); String oifName = null; if (isOIB) { oifName = mapOIBFiles(); } else { // make sure we have the OIF file, not a TIFF if (!checkSuffix(id, OIF_SUFFIX)) { currentId = findOIFFile(id); initFile(currentId); } oifName = currentId; } String oifPath = new Location(oifName).getAbsoluteFile().getAbsolutePath(); String path = (isOIB || !oifPath.endsWith(oifName) || mappedOIF) ? "" : oifPath.substring(0, oifPath.lastIndexOf(File.separator) + 1); try { RandomAccessInputStream s = getFile(oifName); s.close(); } catch (IOException e) { oifName = oifName.replaceAll(".oif", ".OIF"); } // parse key/value pairs from the OIF file code = new String[NUM_DIMENSIONS]; size = new String[NUM_DIMENSIONS]; pixelSize = new Double[NUM_DIMENSIONS]; previewNames = new Vector<String>(); boolean laserEnabled = true; IniList f = getIniFile(oifName); IniTable saveInfo = f.getTable("ProfileSaveInfo"); String[] saveKeys = saveInfo.keySet().toArray(new String[saveInfo.size()]); for (String key : saveKeys) { String value = saveInfo.get(key).toString(); value = sanitizeValue(value).trim(); if (key.startsWith("IniFileName") && key.indexOf("Thumb") == -1 && !isPreviewName(value)) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1).trim(); } filenames.put(new Integer(key.substring(11)), value); } else if (key.startsWith("RoiFileName") && key.indexOf("Thumb") == -1 && !isPreviewName(value)) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1).trim(); } try { roiFilenames.put(new Integer(key.substring(11)), value); } catch (NumberFormatException e) { } } else if (key.equals("PtyFileNameS")) ptyStart = value; else if (key.equals("PtyFileNameE")) ptyEnd = value; else if (key.equals("PtyFileNameT2")) ptyPattern = value; else if (key.indexOf("Thumb") != -1) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1); } if (thumbId == null) thumbId = value.trim(); } else if (key.startsWith("LutFileName")) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1); } lutNames.add(path + value); } else if (isPreviewName(value)) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1); } previewNames.add(path + value.trim()); } } if (filenames.size() == 0) addPtyFiles(); for (int i=0; i<NUM_DIMENSIONS; i++) { IniTable commonParams = f.getTable("Axis " + i + " Parameters Common"); code[i] = commonParams.get("AxisCode"); size[i] = commonParams.get("MaxSize"); double end = Double.parseDouble(commonParams.get("EndPosition")); double start = Double.parseDouble(commonParams.get("StartPosition")); pixelSize[i] = end - start; } IniTable referenceParams = f.getTable("Reference Image Parameter"); imageDepth = Integer.parseInt(referenceParams.get("ImageDepth")); pixelSizeX = referenceParams.get("WidthConvertValue"); pixelSizeY = referenceParams.get("HeightConvertValue"); String ripValidBitCounts = referenceParams.get("ValidBitCounts"); if (ripValidBitCounts != null) { validBits = Integer.parseInt(ripValidBitCounts); } int index = 0; IniTable laser = f.getTable("Laser " + index + " Parameters"); while (laser != null) { laserEnabled = laser.get("Laser Enable").equals("1"); if (laserEnabled) { wavelengths.add(new Integer(laser.get("LaserWavelength"))); } creationDate = laser.get("ImageCaputreDate"); if (creationDate == null) { creationDate = laser.get("ImageCaptureDate"); } index++; laser = f.getTable("Laser " + index + " Parameters"); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { index = 1; IniTable guiChannel = f.getTable("GUI Channel " + index + " Parameters"); while (guiChannel != null) { ChannelData channel = new ChannelData(); String gain = guiChannel.get("AnalogPMTGain"); if (gain != null) channel.gain = new Double(gain); String voltage = guiChannel.get("AnalogPMTVoltage"); if (voltage != null) channel.voltage = new Double(voltage); channel.barrierFilter = guiChannel.get("BF Name"); channel.active = Integer.parseInt(guiChannel.get("CH Activate")) != 0; channel.name = guiChannel.get("CH Name"); channel.dyeName = guiChannel.get("DyeName"); channel.emissionFilter = guiChannel.get("EmissionDM Name"); channel.emWave = new Integer(guiChannel.get("EmissionWavelength")); channel.excitationFilter = guiChannel.get("ExcitationDM Name"); channel.exWave = new Integer(guiChannel.get("ExcitationWavelength")); channels.add(channel); index++; guiChannel = f.getTable("GUI Channel " + index + " Parameters"); } index = 1; IniTable channel = f.getTable("Channel " + index + " Parameters"); while (channel != null) { String illumination = channel.get("LightType"); if (illumination != null) illumination = illumination.toLowerCase(); if (illumination == null) { // Ignored } else if (illumination.indexOf("fluorescence") != -1) { illumination = "Epifluorescence"; } else if (illumination.indexOf("transmitted") != -1) { illumination = "Transmitted"; } else illumination = null; illuminations.add(illumination); index++; channel = f.getTable("Channel " + index + " Parameters"); } HashMap<String, String> iniMap = f.flattenIntoHashMap(); metadata.putAll(iniMap); } LOGGER.info("Initializing helper readers"); // populate core metadata for preview series if (previewNames.size() > 0) { Vector<String> v = new Vector<String>(); for (int i=0; i<previewNames.size(); i++) { String ss = previewNames.get(i); ss = replaceExtension(ss, "pty", "tif"); if (ss.endsWith(".tif")) v.add(ss); } previewNames = v; if (previewNames.size() > 0) { core = new CoreMetadata[2]; core[0] = new CoreMetadata(); core[1] = new CoreMetadata(); IFDList ifds = null; for (String previewName : previewNames) { RandomAccessInputStream preview = getFile(previewName); TiffParser tp = new TiffParser(preview); ifds = tp.getIFDs(); preview.close(); tp = null; core[1].imageCount += ifds.size(); } core[1].sizeX = (int) ifds.get(0).getImageWidth(); core[1].sizeY = (int) ifds.get(0).getImageLength(); core[1].sizeZ = 1; core[1].sizeT = 1; core[1].sizeC = core[1].imageCount; core[1].rgb = false; int bits = ifds.get(0).getBitsPerSample()[0]; while ((bits % 8) != 0) bits++; bits /= 8; core[1].pixelType = FormatTools.pixelTypeFromBytes(bits, false, false); core[1].dimensionOrder = "XYCZT"; core[1].indexed = false; } } core[0].imageCount = filenames.size(); tiffs = new Vector<String>(getImageCount()); thumbReader = new BMPReader(); thumbId = replaceExtension(thumbId, "pty", "bmp"); thumbId = sanitizeFile(thumbId, path); LOGGER.info("Reading additional metadata"); // open each INI file (.pty extension) and build list of TIFF files String tiffPath = null; core[0].dimensionOrder = "XY"; Hashtable<String, String> values = new Hashtable<String, String>(); Vector<String> baseKeys = new Vector<String>(); for (int i=0, ii=0; ii<getImageCount(); i++, ii++) { String file = filenames.get(new Integer(i)); while (file == null) file = filenames.get(new Integer(++i)); file = sanitizeFile(file, path); if (file.indexOf(File.separator) != -1) { tiffPath = file.substring(0, file.lastIndexOf(File.separator)); } else tiffPath = file; Location ptyFile = new Location(file); if (!isOIB && !ptyFile.exists()) { LOGGER.warn("Could not find .pty file ({}); guessing at the " + "corresponding TIFF file.", file); String tiff = replaceExtension(file, ".pty", ".tif"); tiffs.add(ii, tiff); continue; } IniList pty = getIniFile(file); IniTable fileInfo = pty.getTable("File Info"); file = sanitizeValue(fileInfo.get("DataName")); if (!isPreviewName(file)) { while (file.indexOf("GST") != -1) { file = removeGST(file); } if (!mappedOIF) { if (isOIB) { file = tiffPath + File.separator + file; } else file = new Location(tiffPath, file).getAbsolutePath(); } tiffs.add(ii, file); } for (int dim=0; dim<NUM_DIMENSIONS; dim++) { IniTable axis = pty.getTable("Axis " + dim + " Parameters"); if (axis == null) break; boolean addAxis = Integer.parseInt(axis.get("Number")) > 1; if (dim == 2) { if (addAxis && getDimensionOrder().indexOf("C") == -1) { core[0].dimensionOrder += "C"; } } else if (dim == 3) { if (addAxis && getDimensionOrder().indexOf("Z") == -1) { core[0].dimensionOrder += "Z"; } } else if (dim == 4) { if (addAxis && getDimensionOrder().indexOf("T") == -1) { core[0].dimensionOrder += "T"; } } } core[0].bitsPerPixel = validBits; IniTable acquisition = pty.getTable("Acquisition Parameters Common"); if (acquisition != null) { magnification = acquisition.get("Magnification"); lensNA = acquisition.get("ObjectiveLens NAValue"); objectiveName = acquisition.get("ObjectiveLens Name"); workingDistance = acquisition.get("ObjectiveLens WDValue"); pinholeSize = acquisition.get("PinholeDiameter"); String validBitCounts = acquisition.get("ValidBitCounts"); if (validBitCounts != null) { core[0].bitsPerPixel = Integer.parseInt(validBitCounts); } } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { for (IniTable table : pty) { String[] keys = table.keySet().toArray(new String[table.size()]); for (String key : keys) { values.put("Image " + ii + " : " + key, table.get(key)); if (!baseKeys.contains(key)) baseKeys.add(key); } } } } for (String key : baseKeys) { if (key.equals("DataName") || key.indexOf("FileName") >= 0) break; boolean equal = true; String first = values.get("Image 0 : " + key); for (int i=1; i<getImageCount(); i++) { if (!first.equals(values.get("Image " + i + " : " + key))) { equal = false; break; } } if (equal) { addGlobalMeta(key, first); } else { for (int i=0; i<getImageCount(); i++) { String k = "Image " + i + " : " + key; addGlobalMeta(k, values.get(k)); } } } if (tiffs.size() != getImageCount()) { core[0].imageCount = tiffs.size(); } usedFiles = new Vector<String>(); if (tiffPath != null) { usedFiles.add(isOIB ? id : oifName); if (!isOIB) { Location dir = new Location(tiffPath); if (!dir.exists()) { throw new FormatException( "Required directory " + tiffPath + " was not found."); } String[] list = mappedOIF ? Location.getIdMap().keySet().toArray(new String[0]) : dir.list(true); for (int i=0; i<list.length; i++) { if (mappedOIF) usedFiles.add(list[i]); else { String p = new Location(tiffPath, list[i]).getAbsolutePath(); String check = p.toLowerCase(); if (!check.endsWith(".tif") && !check.endsWith(".pty") && !check.endsWith(".roi") && !check.endsWith(".lut") && !check.endsWith(".bmp")) { continue; } usedFiles.add(p); } } } } LOGGER.info("Populating metadata"); // calculate axis sizes int realChannels = 0; for (int i=0; i<NUM_DIMENSIONS; i++) { int ss = Integer.parseInt(size[i]); if (pixelSize[i] == null) pixelSize[i] = 1.0; if (code[i].equals("X")) core[0].sizeX = ss; else if (code[i].equals("Y") && ss > 1) core[0].sizeY = ss; else if (code[i].equals("Z")) { if (getSizeY() == 0) { core[0].sizeY = ss; } else { core[0].sizeZ = ss; // Z size stored in nm pixelSizeZ = Math.abs((pixelSize[i].doubleValue() / (getSizeZ() - 1)) / 1000); } } else if (code[i].equals("T")) { if (getSizeY() == 0) { core[0].sizeY = ss; } else { core[0].sizeT = ss; pixelSizeT = Math.abs((pixelSize[i].doubleValue() / (getSizeT() - 1)) / 1000); } } else if (ss > 0) { if (getSizeC() == 0) core[0].sizeC = ss; else core[0].sizeC *= ss; if (code[i].equals("C")) realChannels = ss; } } if (getSizeZ() == 0) core[0].sizeZ = 1; if (getSizeC() == 0) core[0].sizeC = 1; if (getSizeT() == 0) core[0].sizeT = 1; if (getImageCount() == getSizeC() && getSizeY() == 1) { core[0].imageCount *= getSizeZ() * getSizeT(); } else if (getImageCount() == getSizeC()) { core[0].sizeZ = 1; core[0].sizeT = 1; } if (getSizeZ() * getSizeT() * getSizeC() != getImageCount()) { int diff = (getSizeZ() * getSizeC() * getSizeT()) - getImageCount(); if (diff == previewNames.size() || diff < 0) { diff /= getSizeC(); if (getSizeT() > 1 && getSizeZ() == 1) core[0].sizeT -= diff; else if (getSizeZ() > 1 && getSizeT() == 1) core[0].sizeZ -= diff; } else core[0].imageCount += diff; } if (getSizeC() > 1 && getSizeZ() == 1 && getSizeT() == 1) { if (getDimensionOrder().indexOf("C") == -1) core[0].dimensionOrder += "C"; } if (getDimensionOrder().indexOf("Z") == -1) core[0].dimensionOrder += "Z"; if (getDimensionOrder().indexOf("C") == -1) core[0].dimensionOrder += "C"; if (getDimensionOrder().indexOf("T") == -1) core[0].dimensionOrder += "T"; core[0].pixelType = FormatTools.pixelTypeFromBytes(imageDepth, false, false); // set up thumbnail file mapping try { RandomAccessInputStream thumb = getFile(thumbId); byte[] b = new byte[(int) thumb.length()]; thumb.read(b); thumb.close(); Location.mapFile("thumbnail.bmp", new ByteArrayHandle(b)); thumbReader.setId("thumbnail.bmp"); for (int i=0; i<getSeriesCount(); i++) { core[i].thumbSizeX = thumbReader.getSizeX(); core[i].thumbSizeY = thumbReader.getSizeY(); } Location.mapFile("thumbnail.bmp", null); } catch (IOException e) { LOGGER.debug("Could not read thumbnail", e); } catch (FormatException e) { LOGGER.debug("Could not read thumbnail", e); } // initialize lookup table lut = new short[getSizeC()][3][65536]; byte[] buffer = new byte[65536 * 4]; int count = (int) Math.min(getSizeC(), lutNames.size()); for (int c=0; c<count; c++) { Exception exc = null; try { RandomAccessInputStream stream = getFile(lutNames.get(c)); stream.seek(stream.length() - 65536 * 4); stream.read(buffer); stream.close(); for (int q=0; q<buffer.length; q+=4) { lut[c][0][q / 4] = buffer[q + 2]; lut[c][1][q / 4] = buffer[q + 1]; lut[c][2][q / 4] = buffer[q]; } } catch (IOException e) { exc = e; } catch (FormatException e) { exc = e; } if (exc != null) { LOGGER.debug("Could not read LUT", exc); lut = null; break; } } for (int i=0; i<getSeriesCount(); i++) { core[i].rgb = false; core[i].littleEndian = true; core[i].interleaved = false; core[i].metadataComplete = true; core[i].indexed = lut != null; core[i].falseColor = false; } // populate MetadataStore MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); if (creationDate != null) { creationDate = creationDate.replaceAll("'", ""); creationDate = DateTools.formatDate(creationDate, DATE_FORMAT); } for (int i=0; i<getSeriesCount(); i++) { // populate Image data store.setImageName("Series " + (i + 1), i); if (creationDate != null) store.setImageAcquiredDate(creationDate, i); else MetadataTools.setDefaultCreationDate(store, id, i); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { populateMetadataStore(store, path); } }
diff --git a/java/src/com/android/inputmethod/latin/LatinIME.java b/java/src/com/android/inputmethod/latin/LatinIME.java index 8b130aec..e52c4a10 100644 --- a/java/src/com/android/inputmethod/latin/LatinIME.java +++ b/java/src/com/android/inputmethod/latin/LatinIME.java @@ -1,2085 +1,2088 @@ /* * Copyright (C) 2008 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 com.android.inputmethod.latin; import com.android.inputmethod.compat.CompatUtils; import com.android.inputmethod.compat.EditorInfoCompatUtils; import com.android.inputmethod.compat.InputConnectionCompatUtils; import com.android.inputmethod.compat.InputMethodManagerCompatWrapper; import com.android.inputmethod.compat.InputMethodServiceCompatWrapper; import com.android.inputmethod.compat.InputTypeCompatUtils; import com.android.inputmethod.deprecated.LanguageSwitcherProxy; import com.android.inputmethod.deprecated.VoiceProxy; import com.android.inputmethod.keyboard.Keyboard; import com.android.inputmethod.keyboard.KeyboardActionListener; import com.android.inputmethod.keyboard.KeyboardSwitcher; import com.android.inputmethod.keyboard.KeyboardView; import com.android.inputmethod.keyboard.LatinKeyboard; import com.android.inputmethod.keyboard.LatinKeyboardView; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.inputmethodservice.InputMethodService; import android.media.AudioManager; import android.net.ConnectivityManager; import android.os.Debug; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.SystemClock; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.text.InputType; import android.text.TextUtils; import android.util.DisplayMetrics; import android.util.Log; import android.util.PrintWriterPrinter; import android.util.Printer; import android.view.HapticFeedbackConstants; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.CompletionInfo; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.ExtractedText; import android.view.inputmethod.InputConnection; import android.widget.LinearLayout; import java.io.FileDescriptor; import java.io.PrintWriter; import java.util.Locale; /** * Input method implementation for Qwerty'ish keyboard. */ public class LatinIME extends InputMethodServiceCompatWrapper implements KeyboardActionListener { private static final String TAG = LatinIME.class.getSimpleName(); private static final boolean PERF_DEBUG = false; private static final boolean TRACE = false; private static boolean DEBUG = LatinImeLogger.sDBG; /** * The private IME option used to indicate that no microphone should be * shown for a given text field. For instance, this is specified by the * search dialog when the dialog is already showing a voice search button. * * @deprecated Use {@link LatinIME#IME_OPTION_NO_MICROPHONE} with package name prefixed. */ @SuppressWarnings("dep-ann") public static final String IME_OPTION_NO_MICROPHONE_COMPAT = "nm"; /** * The private IME option used to indicate that no microphone should be * shown for a given text field. For instance, this is specified by the * search dialog when the dialog is already showing a voice search button. */ public static final String IME_OPTION_NO_MICROPHONE = "noMicrophoneKey"; /** * The private IME option used to indicate that no settings key should be * shown for a given text field. */ public static final String IME_OPTION_NO_SETTINGS_KEY = "noSettingsKey"; private static final int EXTENDED_TOUCHABLE_REGION_HEIGHT = 100; // How many continuous deletes at which to start deleting at a higher speed. private static final int DELETE_ACCELERATE_AT = 20; // Key events coming any faster than this are long-presses. private static final int QUICK_PRESS = 200; /** * The name of the scheme used by the Package Manager to warn of a new package installation, * replacement or removal. */ private static final String SCHEME_PACKAGE = "package"; private int mSuggestionVisibility; private static final int SUGGESTION_VISIBILILTY_SHOW_VALUE = R.string.prefs_suggestion_visibility_show_value; private static final int SUGGESTION_VISIBILILTY_SHOW_ONLY_PORTRAIT_VALUE = R.string.prefs_suggestion_visibility_show_only_portrait_value; private static final int SUGGESTION_VISIBILILTY_HIDE_VALUE = R.string.prefs_suggestion_visibility_hide_value; private static final int[] SUGGESTION_VISIBILITY_VALUE_ARRAY = new int[] { SUGGESTION_VISIBILILTY_SHOW_VALUE, SUGGESTION_VISIBILILTY_SHOW_ONLY_PORTRAIT_VALUE, SUGGESTION_VISIBILILTY_HIDE_VALUE }; private Settings.Values mSettingsValues; private View mCandidateViewContainer; private int mCandidateStripHeight; private CandidateView mCandidateView; private Suggest mSuggest; private CompletionInfo[] mApplicationSpecifiedCompletions; private AlertDialog mOptionsDialog; private InputMethodManagerCompatWrapper mImm; private Resources mResources; private SharedPreferences mPrefs; private String mInputMethodId; private KeyboardSwitcher mKeyboardSwitcher; private SubtypeSwitcher mSubtypeSwitcher; private VoiceProxy mVoiceProxy; private Recorrection mRecorrection; private UserDictionary mUserDictionary; private UserBigramDictionary mUserBigramDictionary; private ContactsDictionary mContactsDictionary; private AutoDictionary mAutoDictionary; // TODO: Create an inner class to group options and pseudo-options to improve readability. // These variables are initialized according to the {@link EditorInfo#inputType}. private boolean mShouldInsertMagicSpace; private boolean mInputTypeNoAutoCorrect; private boolean mIsSettingsSuggestionStripOn; private boolean mApplicationSpecifiedCompletionOn; private final StringBuilder mComposing = new StringBuilder(); private WordComposer mWord = new WordComposer(); private CharSequence mBestWord; private boolean mHasUncommittedTypedChars; private boolean mHasDictionary; // Magic space: a space that should disappear on space/apostrophe insertion, move after the // punctuation on punctuation insertion, and become a real space on alpha char insertion. private boolean mJustAddedMagicSpace; // This indicates whether the last char is a magic space. private int mCorrectionMode; private int mCommittedLength; private int mOrientation; // Keep track of the last selection range to decide if we need to show word alternatives private int mLastSelectionStart; private int mLastSelectionEnd; // Indicates whether the suggestion strip is to be on in landscape private boolean mJustAccepted; private int mDeleteCount; private long mLastKeyTime; private AudioManager mAudioManager; // Align sound effect volume on music volume private static final float FX_VOLUME = -1.0f; private boolean mSilentModeOn; // System-wide current configuration // TODO: Move this flag to VoiceProxy private boolean mConfigurationChanging; // Object for reacting to adding/removing a dictionary pack. private BroadcastReceiver mDictionaryPackInstallReceiver = new DictionaryPackInstallBroadcastReceiver(this); // Keeps track of most recently inserted text (multi-character key) for reverting private CharSequence mEnteredText; public final UIHandler mHandler = new UIHandler(); public class UIHandler extends Handler { private static final int MSG_UPDATE_SUGGESTIONS = 0; private static final int MSG_UPDATE_OLD_SUGGESTIONS = 1; private static final int MSG_UPDATE_SHIFT_STATE = 2; private static final int MSG_VOICE_RESULTS = 3; private static final int MSG_FADEOUT_LANGUAGE_ON_SPACEBAR = 4; private static final int MSG_DISMISS_LANGUAGE_ON_SPACEBAR = 5; private static final int MSG_SPACE_TYPED = 6; private static final int MSG_SET_BIGRAM_PREDICTIONS = 7; @Override public void handleMessage(Message msg) { final KeyboardSwitcher switcher = mKeyboardSwitcher; final LatinKeyboardView inputView = switcher.getInputView(); switch (msg.what) { case MSG_UPDATE_SUGGESTIONS: updateSuggestions(); break; case MSG_UPDATE_OLD_SUGGESTIONS: mRecorrection.setRecorrectionSuggestions(mVoiceProxy, mCandidateView, mSuggest, mKeyboardSwitcher, mWord, mHasUncommittedTypedChars, mLastSelectionStart, mLastSelectionEnd, mSettingsValues.mWordSeparators); break; case MSG_UPDATE_SHIFT_STATE: switcher.updateShiftState(); break; case MSG_SET_BIGRAM_PREDICTIONS: updateBigramPredictions(); break; case MSG_VOICE_RESULTS: mVoiceProxy.handleVoiceResults(preferCapitalization() || (switcher.isAlphabetMode() && switcher.isShiftedOrShiftLocked())); break; case MSG_FADEOUT_LANGUAGE_ON_SPACEBAR: if (inputView != null) { inputView.setSpacebarTextFadeFactor( (1.0f + mSettingsValues.mFinalFadeoutFactorOfLanguageOnSpacebar) / 2, (LatinKeyboard)msg.obj); } sendMessageDelayed(obtainMessage(MSG_DISMISS_LANGUAGE_ON_SPACEBAR, msg.obj), mSettingsValues.mDurationOfFadeoutLanguageOnSpacebar); break; case MSG_DISMISS_LANGUAGE_ON_SPACEBAR: if (inputView != null) { inputView.setSpacebarTextFadeFactor( mSettingsValues.mFinalFadeoutFactorOfLanguageOnSpacebar, (LatinKeyboard)msg.obj); } break; } } public void postUpdateSuggestions() { removeMessages(MSG_UPDATE_SUGGESTIONS); sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTIONS), mSettingsValues.mDelayUpdateSuggestions); } public void cancelUpdateSuggestions() { removeMessages(MSG_UPDATE_SUGGESTIONS); } public boolean hasPendingUpdateSuggestions() { return hasMessages(MSG_UPDATE_SUGGESTIONS); } public void postUpdateOldSuggestions() { removeMessages(MSG_UPDATE_OLD_SUGGESTIONS); sendMessageDelayed(obtainMessage(MSG_UPDATE_OLD_SUGGESTIONS), mSettingsValues.mDelayUpdateOldSuggestions); } public void cancelUpdateOldSuggestions() { removeMessages(MSG_UPDATE_OLD_SUGGESTIONS); } public void postUpdateShiftKeyState() { removeMessages(MSG_UPDATE_SHIFT_STATE); sendMessageDelayed(obtainMessage(MSG_UPDATE_SHIFT_STATE), mSettingsValues.mDelayUpdateShiftState); } public void cancelUpdateShiftState() { removeMessages(MSG_UPDATE_SHIFT_STATE); } public void postUpdateBigramPredictions() { removeMessages(MSG_SET_BIGRAM_PREDICTIONS); sendMessageDelayed(obtainMessage(MSG_SET_BIGRAM_PREDICTIONS), mSettingsValues.mDelayUpdateSuggestions); } public void cancelUpdateBigramPredictions() { removeMessages(MSG_SET_BIGRAM_PREDICTIONS); } public void updateVoiceResults() { sendMessage(obtainMessage(MSG_VOICE_RESULTS)); } public void startDisplayLanguageOnSpacebar(boolean localeChanged) { removeMessages(MSG_FADEOUT_LANGUAGE_ON_SPACEBAR); removeMessages(MSG_DISMISS_LANGUAGE_ON_SPACEBAR); final LatinKeyboardView inputView = mKeyboardSwitcher.getInputView(); if (inputView != null) { final LatinKeyboard keyboard = mKeyboardSwitcher.getLatinKeyboard(); // The language is always displayed when the delay is negative. final boolean needsToDisplayLanguage = localeChanged || mSettingsValues.mDelayBeforeFadeoutLanguageOnSpacebar < 0; // The language is never displayed when the delay is zero. if (mSettingsValues.mDelayBeforeFadeoutLanguageOnSpacebar != 0) { inputView.setSpacebarTextFadeFactor(needsToDisplayLanguage ? 1.0f : mSettingsValues.mFinalFadeoutFactorOfLanguageOnSpacebar, keyboard); } // The fadeout animation will start when the delay is positive. if (localeChanged && mSettingsValues.mDelayBeforeFadeoutLanguageOnSpacebar > 0) { sendMessageDelayed(obtainMessage(MSG_FADEOUT_LANGUAGE_ON_SPACEBAR, keyboard), mSettingsValues.mDelayBeforeFadeoutLanguageOnSpacebar); } } } public void startDoubleSpacesTimer() { removeMessages(MSG_SPACE_TYPED); sendMessageDelayed(obtainMessage(MSG_SPACE_TYPED), mSettingsValues.mDoubleSpacesTurnIntoPeriodTimeout); } public void cancelDoubleSpacesTimer() { removeMessages(MSG_SPACE_TYPED); } public boolean isAcceptingDoubleSpaces() { return hasMessages(MSG_SPACE_TYPED); } } @Override public void onCreate() { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); mPrefs = prefs; LatinImeLogger.init(this, prefs); LanguageSwitcherProxy.init(this, prefs); SubtypeSwitcher.init(this, prefs); KeyboardSwitcher.init(this, prefs); Recorrection.init(this, prefs); super.onCreate(); mImm = InputMethodManagerCompatWrapper.getInstance(this); mInputMethodId = Utils.getInputMethodId(mImm, getPackageName()); mSubtypeSwitcher = SubtypeSwitcher.getInstance(); mKeyboardSwitcher = KeyboardSwitcher.getInstance(); mRecorrection = Recorrection.getInstance(); loadSettings(); final Resources res = getResources(); mResources = res; Utils.GCUtils.getInstance().reset(); boolean tryGC = true; for (int i = 0; i < Utils.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) { try { initSuggest(); tryGC = false; } catch (OutOfMemoryError e) { tryGC = Utils.GCUtils.getInstance().tryGCOrWait("InitSuggest", e); } } mOrientation = res.getConfiguration().orientation; // Register to receive ringer mode change and network state change. // Also receive installation and removal of a dictionary pack. final IntentFilter filter = new IntentFilter(); filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(mReceiver, filter); mVoiceProxy = VoiceProxy.init(this, prefs, mHandler); final IntentFilter packageFilter = new IntentFilter(); packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED); packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); packageFilter.addDataScheme(SCHEME_PACKAGE); registerReceiver(mDictionaryPackInstallReceiver, packageFilter); final IntentFilter newDictFilter = new IntentFilter(); newDictFilter.addAction( DictionaryPackInstallBroadcastReceiver.NEW_DICTIONARY_INTENT_ACTION); registerReceiver(mDictionaryPackInstallReceiver, newDictFilter); } // Has to be package-visible for unit tests /* package */ void loadSettings() { if (null == mPrefs) mPrefs = PreferenceManager.getDefaultSharedPreferences(this); if (null == mSubtypeSwitcher) mSubtypeSwitcher = SubtypeSwitcher.getInstance(); mSettingsValues = new Settings.Values(mPrefs, this, mSubtypeSwitcher.getInputLocaleStr()); } private void initSuggest() { final String localeStr = mSubtypeSwitcher.getInputLocaleStr(); final Locale keyboardLocale = new Locale(localeStr); final Resources res = mResources; final Locale savedLocale = Utils.setSystemLocale(res, keyboardLocale); if (mSuggest != null) { mSuggest.close(); } int mainDicResId = Utils.getMainDictionaryResourceId(res); mSuggest = new Suggest(this, mainDicResId, keyboardLocale); if (mSettingsValues.mAutoCorrectEnabled) { mSuggest.setAutoCorrectionThreshold(mSettingsValues.mAutoCorrectionThreshold); } updateAutoTextEnabled(); mUserDictionary = new UserDictionary(this, localeStr); mSuggest.setUserDictionary(mUserDictionary); mContactsDictionary = new ContactsDictionary(this, Suggest.DIC_CONTACTS); mSuggest.setContactsDictionary(mContactsDictionary); mAutoDictionary = new AutoDictionary(this, this, localeStr, Suggest.DIC_AUTO); mSuggest.setAutoDictionary(mAutoDictionary); mUserBigramDictionary = new UserBigramDictionary(this, this, localeStr, Suggest.DIC_USER); mSuggest.setUserBigramDictionary(mUserBigramDictionary); updateCorrectionMode(); Utils.setSystemLocale(res, savedLocale); } /* package private */ void resetSuggestMainDict() { final String localeStr = mSubtypeSwitcher.getInputLocaleStr(); final Locale keyboardLocale = new Locale(localeStr); int mainDicResId = Utils.getMainDictionaryResourceId(mResources); mSuggest.resetMainDict(this, mainDicResId, keyboardLocale); } @Override public void onDestroy() { if (mSuggest != null) { mSuggest.close(); mSuggest = null; } unregisterReceiver(mReceiver); unregisterReceiver(mDictionaryPackInstallReceiver); mVoiceProxy.destroy(); LatinImeLogger.commit(); LatinImeLogger.onDestroy(); super.onDestroy(); } @Override public void onConfigurationChanged(Configuration conf) { mSubtypeSwitcher.onConfigurationChanged(conf); // If orientation changed while predicting, commit the change if (conf.orientation != mOrientation) { InputConnection ic = getCurrentInputConnection(); commitTyped(ic); if (ic != null) ic.finishComposingText(); // For voice input mOrientation = conf.orientation; if (isShowingOptionDialog()) mOptionsDialog.dismiss(); } mConfigurationChanging = true; super.onConfigurationChanged(conf); mVoiceProxy.onConfigurationChanged(conf); mConfigurationChanging = false; // This will work only when the subtype is not supported. LanguageSwitcherProxy.onConfigurationChanged(conf); } @Override public View onCreateInputView() { return mKeyboardSwitcher.onCreateInputView(); } @Override public View onCreateCandidatesView() { LayoutInflater inflater = getLayoutInflater(); LinearLayout container = (LinearLayout)inflater.inflate(R.layout.candidates, null); mCandidateViewContainer = container; mCandidateStripHeight = (int)mResources.getDimension(R.dimen.candidate_strip_height); mCandidateView = (CandidateView) container.findViewById(R.id.candidates); mCandidateView.setService(this); setCandidatesViewShown(true); return container; } @Override public void onStartInputView(EditorInfo attribute, boolean restarting) { final KeyboardSwitcher switcher = mKeyboardSwitcher; LatinKeyboardView inputView = switcher.getInputView(); if (DEBUG) { Log.d(TAG, "onStartInputView: " + inputView); } // In landscape mode, this method gets called without the input view being created. if (inputView == null) { return; } mSubtypeSwitcher.updateParametersOnStartInputView(); TextEntryState.reset(); // Most such things we decide below in initializeInputAttributesAndGetMode, but we need to // know now whether this is a password text field, because we need to know now whether we // want to enable the voice button. final VoiceProxy voiceIme = mVoiceProxy; voiceIme.resetVoiceStates(InputTypeCompatUtils.isPasswordInputType(attribute.inputType) || InputTypeCompatUtils.isVisiblePasswordInputType(attribute.inputType)); initializeInputAttributes(attribute); inputView.closing(); mEnteredText = null; mComposing.setLength(0); mHasUncommittedTypedChars = false; mDeleteCount = 0; mJustAddedMagicSpace = false; loadSettings(); updateCorrectionMode(); updateAutoTextEnabled(); updateSuggestionVisibility(mPrefs, mResources); if (mSuggest != null && mSettingsValues.mAutoCorrectEnabled) { mSuggest.setAutoCorrectionThreshold(mSettingsValues.mAutoCorrectionThreshold); } mVoiceProxy.loadSettings(attribute, mPrefs); // This will work only when the subtype is not supported. LanguageSwitcherProxy.loadSettings(); if (mSubtypeSwitcher.isKeyboardMode()) { switcher.loadKeyboard(attribute, mSubtypeSwitcher.isShortcutImeEnabled() && voiceIme.isVoiceButtonEnabled(), voiceIme.isVoiceButtonOnPrimary()); switcher.updateShiftState(); } setCandidatesViewShownInternal(isCandidateStripVisible(), false /* needsInputViewShown */ ); // Delay updating suggestions because keyboard input view may not be shown at this point. mHandler.postUpdateSuggestions(); updateCorrectionMode(); inputView.setKeyPreviewEnabled(mSettingsValues.mPopupOn); inputView.setProximityCorrectionEnabled(true); // If we just entered a text field, maybe it has some old text that requires correction mRecorrection.checkRecorrectionOnStart(); inputView.setForeground(true); voiceIme.onStartInputView(inputView.getWindowToken()); if (TRACE) Debug.startMethodTracing("/data/trace/latinime"); } private void initializeInputAttributes(EditorInfo attribute) { if (attribute == null) return; final int inputType = attribute.inputType; final int variation = inputType & InputType.TYPE_MASK_VARIATION; mShouldInsertMagicSpace = false; mInputTypeNoAutoCorrect = false; mIsSettingsSuggestionStripOn = false; mApplicationSpecifiedCompletionOn = false; mApplicationSpecifiedCompletions = null; if ((inputType & InputType.TYPE_MASK_CLASS) == InputType.TYPE_CLASS_TEXT) { mIsSettingsSuggestionStripOn = true; // Make sure that passwords are not displayed in candidate view if (InputTypeCompatUtils.isPasswordInputType(inputType) || InputTypeCompatUtils.isVisiblePasswordInputType(inputType)) { mIsSettingsSuggestionStripOn = false; } if (InputTypeCompatUtils.isEmailVariation(variation) || variation == InputType.TYPE_TEXT_VARIATION_PERSON_NAME) { mShouldInsertMagicSpace = false; } else { mShouldInsertMagicSpace = true; } if (InputTypeCompatUtils.isEmailVariation(variation)) { mIsSettingsSuggestionStripOn = false; } else if (variation == InputType.TYPE_TEXT_VARIATION_URI) { mIsSettingsSuggestionStripOn = false; } else if (variation == InputType.TYPE_TEXT_VARIATION_FILTER) { mIsSettingsSuggestionStripOn = false; } else if (variation == InputType.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT) { // If it's a browser edit field and auto correct is not ON explicitly, then // disable auto correction, but keep suggestions on. if ((inputType & InputType.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0) { mInputTypeNoAutoCorrect = true; } } // If NO_SUGGESTIONS is set, don't do prediction. if ((inputType & InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS) != 0) { mIsSettingsSuggestionStripOn = false; mInputTypeNoAutoCorrect = true; } // If it's not multiline and the autoCorrect flag is not set, then don't correct if ((inputType & InputType.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0 && (inputType & InputType.TYPE_TEXT_FLAG_MULTI_LINE) == 0) { mInputTypeNoAutoCorrect = true; } if ((inputType & InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE) != 0) { mIsSettingsSuggestionStripOn = false; mApplicationSpecifiedCompletionOn = isFullscreenMode(); } } } @Override public void onFinishInput() { super.onFinishInput(); LatinImeLogger.commit(); mKeyboardSwitcher.onAutoCorrectionStateChanged(false); mVoiceProxy.flushVoiceInputLogs(mConfigurationChanging); KeyboardView inputView = mKeyboardSwitcher.getInputView(); if (inputView != null) inputView.closing(); if (mAutoDictionary != null) mAutoDictionary.flushPendingWrites(); if (mUserBigramDictionary != null) mUserBigramDictionary.flushPendingWrites(); } @Override public void onFinishInputView(boolean finishingInput) { super.onFinishInputView(finishingInput); KeyboardView inputView = mKeyboardSwitcher.getInputView(); if (inputView != null) inputView.setForeground(false); // Remove pending messages related to update suggestions mHandler.cancelUpdateSuggestions(); mHandler.cancelUpdateOldSuggestions(); } @Override public void onUpdateExtractedText(int token, ExtractedText text) { super.onUpdateExtractedText(token, text); mVoiceProxy.showPunctuationHintIfNecessary(); } @Override public void onUpdateSelection(int oldSelStart, int oldSelEnd, int newSelStart, int newSelEnd, int candidatesStart, int candidatesEnd) { super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, candidatesStart, candidatesEnd); if (DEBUG) { Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart + ", ose=" + oldSelEnd + ", lss=" + mLastSelectionStart + ", lse=" + mLastSelectionEnd + ", nss=" + newSelStart + ", nse=" + newSelEnd + ", cs=" + candidatesStart + ", ce=" + candidatesEnd); } mVoiceProxy.setCursorAndSelection(newSelEnd, newSelStart); // If the current selection in the text view changes, we should // clear whatever candidate text we have. final boolean selectionChanged = (newSelStart != candidatesEnd || newSelEnd != candidatesEnd) && mLastSelectionStart != newSelStart; final boolean candidatesCleared = candidatesStart == -1 && candidatesEnd == -1; if (((mComposing.length() > 0 && mHasUncommittedTypedChars) || mVoiceProxy.isVoiceInputHighlighted()) && (selectionChanged || candidatesCleared)) { if (candidatesCleared) { // If the composing span has been cleared, save the typed word in the history for // recorrection before we reset the candidate strip. Then, we'll be able to show // suggestions for recorrection right away. mRecorrection.saveWordInHistory(mWord, mComposing); } mComposing.setLength(0); mHasUncommittedTypedChars = false; if (isCursorTouchingWord()) { mHandler.cancelUpdateBigramPredictions(); mHandler.postUpdateSuggestions(); } else { setPunctuationSuggestions(); } TextEntryState.reset(); InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.finishComposingText(); } mVoiceProxy.setVoiceInputHighlighted(false); } else if (!mHasUncommittedTypedChars && !mJustAccepted) { if (TextEntryState.isAcceptedDefault() || TextEntryState.isSpaceAfterPicked()) { if (TextEntryState.isAcceptedDefault()) TextEntryState.reset(); mJustAddedMagicSpace = false; // The user moved the cursor. } } mJustAccepted = false; mHandler.postUpdateShiftKeyState(); // Make a note of the cursor position mLastSelectionStart = newSelStart; mLastSelectionEnd = newSelEnd; mRecorrection.updateRecorrectionSelection(mKeyboardSwitcher, mCandidateView, candidatesStart, candidatesEnd, newSelStart, newSelEnd, oldSelStart, mLastSelectionStart, mLastSelectionEnd, mHasUncommittedTypedChars); } public void setLastSelection(int start, int end) { mLastSelectionStart = start; mLastSelectionEnd = end; } /** * This is called when the user has clicked on the extracted text view, * when running in fullscreen mode. The default implementation hides * the candidates view when this happens, but only if the extracted text * editor has a vertical scroll bar because its text doesn't fit. * Here we override the behavior due to the possibility that a re-correction could * cause the candidate strip to disappear and re-appear. */ @Override public void onExtractedTextClicked() { if (mRecorrection.isRecorrectionEnabled() && isSuggestionsRequested()) return; super.onExtractedTextClicked(); } /** * This is called when the user has performed a cursor movement in the * extracted text view, when it is running in fullscreen mode. The default * implementation hides the candidates view when a vertical movement * happens, but only if the extracted text editor has a vertical scroll bar * because its text doesn't fit. * Here we override the behavior due to the possibility that a re-correction could * cause the candidate strip to disappear and re-appear. */ @Override public void onExtractedCursorMovement(int dx, int dy) { if (mRecorrection.isRecorrectionEnabled() && isSuggestionsRequested()) return; super.onExtractedCursorMovement(dx, dy); } @Override public void hideWindow() { LatinImeLogger.commit(); mKeyboardSwitcher.onAutoCorrectionStateChanged(false); if (TRACE) Debug.stopMethodTracing(); if (mOptionsDialog != null && mOptionsDialog.isShowing()) { mOptionsDialog.dismiss(); mOptionsDialog = null; } mVoiceProxy.hideVoiceWindow(mConfigurationChanging); mRecorrection.clearWordsInHistory(); super.hideWindow(); } @Override public void onDisplayCompletions(CompletionInfo[] applicationSpecifiedCompletions) { if (DEBUG) { Log.i(TAG, "Received completions:"); if (applicationSpecifiedCompletions != null) { for (int i = 0; i < applicationSpecifiedCompletions.length; i++) { Log.i(TAG, " #" + i + ": " + applicationSpecifiedCompletions[i]); } } } if (mApplicationSpecifiedCompletionOn) { mApplicationSpecifiedCompletions = applicationSpecifiedCompletions; if (applicationSpecifiedCompletions == null) { clearSuggestions(); return; } SuggestedWords.Builder builder = new SuggestedWords.Builder() .setApplicationSpecifiedCompletions(applicationSpecifiedCompletions) .setTypedWordValid(true) .setHasMinimalSuggestion(true); // When in fullscreen mode, show completions generated by the application setSuggestions(builder.build()); mBestWord = null; setCandidatesViewShown(true); } } private void setCandidatesViewShownInternal(boolean shown, boolean needsInputViewShown) { // TODO: Modify this if we support candidates with hard keyboard if (onEvaluateInputViewShown()) { final boolean shouldShowCandidates = shown && (needsInputViewShown ? mKeyboardSwitcher.isInputViewShown() : true); if (isExtractViewShown()) { // No need to have extra space to show the key preview. mCandidateViewContainer.setMinimumHeight(0); super.setCandidatesViewShown(shown); } else { // We must control the visibility of the suggestion strip in order to avoid clipped // key previews, even when we don't show the suggestion strip. mCandidateViewContainer.setVisibility( shouldShowCandidates ? View.VISIBLE : View.INVISIBLE); super.setCandidatesViewShown(true); } } } @Override public void setCandidatesViewShown(boolean shown) { setCandidatesViewShownInternal(shown, true /* needsInputViewShown */ ); } @Override public void onComputeInsets(InputMethodService.Insets outInsets) { super.onComputeInsets(outInsets); final KeyboardView inputView = mKeyboardSwitcher.getInputView(); if (inputView == null) return; final int containerHeight = mCandidateViewContainer.getHeight(); int touchY = containerHeight; // Need to set touchable region only if input view is being shown if (mKeyboardSwitcher.isInputViewShown()) { if (mCandidateViewContainer.getVisibility() == View.VISIBLE) { touchY -= mCandidateStripHeight; } final int touchWidth = inputView.getWidth(); final int touchHeight = inputView.getHeight() + containerHeight // Extend touchable region below the keyboard. + EXTENDED_TOUCHABLE_REGION_HEIGHT; if (DEBUG) { Log.d(TAG, "Touchable region: y=" + touchY + " width=" + touchWidth + " height=" + touchHeight); } setTouchableRegionCompat(outInsets, 0, touchY, touchWidth, touchHeight); } outInsets.contentTopInsets = touchY; outInsets.visibleTopInsets = touchY; } @Override public boolean onEvaluateFullscreenMode() { final Resources res = mResources; DisplayMetrics dm = res.getDisplayMetrics(); float displayHeight = dm.heightPixels; // If the display is more than X inches high, don't go to fullscreen mode float dimen = res.getDimension(R.dimen.max_height_for_fullscreen); if (displayHeight > dimen) { return false; } else { return super.onEvaluateFullscreenMode(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (event.getRepeatCount() == 0 && mKeyboardSwitcher.getInputView() != null) { if (mKeyboardSwitcher.getInputView().handleBack()) { return true; } } break; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DPAD_LEFT: case KeyEvent.KEYCODE_DPAD_RIGHT: // Enable shift key and DPAD to do selections if (mKeyboardSwitcher.isInputViewShown() && mKeyboardSwitcher.isShiftedOrShiftLocked()) { KeyEvent newEvent = new KeyEvent(event.getDownTime(), event.getEventTime(), event.getAction(), event.getKeyCode(), event.getRepeatCount(), event.getDeviceId(), event.getScanCode(), KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_ON); InputConnection ic = getCurrentInputConnection(); if (ic != null) ic.sendKeyEvent(newEvent); return true; } break; } return super.onKeyUp(keyCode, event); } public void commitTyped(InputConnection inputConnection) { if (mHasUncommittedTypedChars) { mHasUncommittedTypedChars = false; if (mComposing.length() > 0) { if (inputConnection != null) { inputConnection.commitText(mComposing, 1); } mCommittedLength = mComposing.length(); TextEntryState.acceptedTyped(mComposing); addToAutoAndUserBigramDictionaries(mComposing, AutoDictionary.FREQUENCY_FOR_TYPED); } updateSuggestions(); } } public boolean getCurrentAutoCapsState() { InputConnection ic = getCurrentInputConnection(); EditorInfo ei = getCurrentInputEditorInfo(); if (mSettingsValues.mAutoCap && ic != null && ei != null && ei.inputType != InputType.TYPE_NULL) { return ic.getCursorCapsMode(ei.inputType) != 0; } return false; } private void swapSwapperAndSpace() { final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; CharSequence lastTwo = ic.getTextBeforeCursor(2, 0); // It is guaranteed lastTwo.charAt(1) is a swapper - else this method is not called. if (lastTwo != null && lastTwo.length() == 2 && lastTwo.charAt(0) == Keyboard.CODE_SPACE) { ic.beginBatchEdit(); ic.deleteSurroundingText(2, 0); ic.commitText(lastTwo.charAt(1) + " ", 1); ic.endBatchEdit(); mKeyboardSwitcher.updateShiftState(); } } private void maybeDoubleSpace() { if (mCorrectionMode == Suggest.CORRECTION_NONE) return; final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; CharSequence lastThree = ic.getTextBeforeCursor(3, 0); if (lastThree != null && lastThree.length() == 3 && Character.isLetterOrDigit(lastThree.charAt(0)) && lastThree.charAt(1) == Keyboard.CODE_SPACE && lastThree.charAt(2) == Keyboard.CODE_SPACE && mHandler.isAcceptingDoubleSpaces()) { mHandler.cancelDoubleSpacesTimer(); ic.beginBatchEdit(); ic.deleteSurroundingText(2, 0); ic.commitText(". ", 1); ic.endBatchEdit(); mKeyboardSwitcher.updateShiftState(); } else { mHandler.startDoubleSpacesTimer(); } } private void maybeRemovePreviousPeriod(CharSequence text) { final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; // When the text's first character is '.', remove the previous period // if there is one. CharSequence lastOne = ic.getTextBeforeCursor(1, 0); if (lastOne != null && lastOne.length() == 1 && lastOne.charAt(0) == Keyboard.CODE_PERIOD && text.charAt(0) == Keyboard.CODE_PERIOD) { ic.deleteSurroundingText(1, 0); } } private void removeTrailingSpace() { final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; CharSequence lastOne = ic.getTextBeforeCursor(1, 0); if (lastOne != null && lastOne.length() == 1 && lastOne.charAt(0) == Keyboard.CODE_SPACE) { ic.deleteSurroundingText(1, 0); } } public boolean addWordToDictionary(String word) { mUserDictionary.addWord(word, 128); // Suggestion strip should be updated after the operation of adding word to the // user dictionary mHandler.postUpdateSuggestions(); return true; } private boolean isAlphabet(int code) { if (Character.isLetter(code)) { return true; } else { return false; } } private void onSettingsKeyPressed() { if (!isShowingOptionDialog()) { if (!mSettingsValues.mEnableShowSubtypeSettings) { showSubtypeSelectorAndSettings(); } else if (Utils.hasMultipleEnabledIMEsOrSubtypes(mImm)) { showOptionsMenu(); } else { launchSettings(); } } } private void onSettingsKeyLongPressed() { if (!isShowingOptionDialog()) { if (Utils.hasMultipleEnabledIMEsOrSubtypes(mImm)) { mImm.showInputMethodPicker(); } else { launchSettings(); } } } private boolean isShowingOptionDialog() { return mOptionsDialog != null && mOptionsDialog.isShowing(); } // Implementation of {@link KeyboardActionListener}. @Override public void onCodeInput(int primaryCode, int[] keyCodes, int x, int y) { long when = SystemClock.uptimeMillis(); if (primaryCode != Keyboard.CODE_DELETE || when > mLastKeyTime + QUICK_PRESS) { mDeleteCount = 0; } mLastKeyTime = when; KeyboardSwitcher switcher = mKeyboardSwitcher; final boolean distinctMultiTouch = switcher.hasDistinctMultitouch(); switch (primaryCode) { case Keyboard.CODE_DELETE: handleBackspace(); mDeleteCount++; LatinImeLogger.logOnDelete(); break; case Keyboard.CODE_SHIFT: // Shift key is handled in onPress() when device has distinct multi-touch panel. if (!distinctMultiTouch) switcher.toggleShift(); break; case Keyboard.CODE_SWITCH_ALPHA_SYMBOL: // Symbol key is handled in onPress() when device has distinct multi-touch panel. if (!distinctMultiTouch) switcher.changeKeyboardMode(); break; case Keyboard.CODE_CANCEL: if (!isShowingOptionDialog()) { handleClose(); } break; case Keyboard.CODE_SETTINGS: onSettingsKeyPressed(); break; case Keyboard.CODE_SETTINGS_LONGPRESS: onSettingsKeyLongPressed(); break; case LatinKeyboard.CODE_NEXT_LANGUAGE: toggleLanguage(true); break; case LatinKeyboard.CODE_PREV_LANGUAGE: toggleLanguage(false); break; case Keyboard.CODE_CAPSLOCK: switcher.toggleCapsLock(); break; case Keyboard.CODE_SHORTCUT: mSubtypeSwitcher.switchToShortcutIME(); break; case Keyboard.CODE_TAB: handleTab(); break; default: if (mSettingsValues.isWordSeparator(primaryCode)) { handleSeparator(primaryCode, x, y); } else { handleCharacter(primaryCode, keyCodes, x, y); } } switcher.onKey(primaryCode); // Reset after any single keystroke mEnteredText = null; } @Override public void onTextInput(CharSequence text) { mVoiceProxy.commitVoiceInput(); InputConnection ic = getCurrentInputConnection(); if (ic == null) return; mRecorrection.abortRecorrection(false); ic.beginBatchEdit(); commitTyped(ic); maybeRemovePreviousPeriod(text); ic.commitText(text, 1); ic.endBatchEdit(); mKeyboardSwitcher.updateShiftState(); mKeyboardSwitcher.onKey(Keyboard.CODE_DUMMY); mJustAddedMagicSpace = false; mEnteredText = text; } @Override public void onCancelInput() { // User released a finger outside any key mKeyboardSwitcher.onCancelInput(); } private void handleBackspace() { if (mVoiceProxy.logAndRevertVoiceInput()) return; final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; ic.beginBatchEdit(); mVoiceProxy.handleBackspace(); boolean deleteChar = false; if (mHasUncommittedTypedChars) { final int length = mComposing.length(); if (length > 0) { mComposing.delete(length - 1, length); mWord.deleteLast(); ic.setComposingText(mComposing, 1); if (mComposing.length() == 0) { mHasUncommittedTypedChars = false; } if (1 == length) { // 1 == length means we are about to erase the last character of the word, // so we can show bigrams. mHandler.postUpdateBigramPredictions(); } else { // length > 1, so we still have letters to deduce a suggestion from. mHandler.postUpdateSuggestions(); } } else { ic.deleteSurroundingText(1, 0); } } else { deleteChar = true; } mHandler.postUpdateShiftKeyState(); TextEntryState.backspace(); if (TextEntryState.isUndoCommit()) { revertLastWord(deleteChar); ic.endBatchEdit(); return; } if (mEnteredText != null && sameAsTextBeforeCursor(ic, mEnteredText)) { ic.deleteSurroundingText(mEnteredText.length(), 0); } else if (deleteChar) { if (mCandidateView != null && mCandidateView.dismissAddToDictionaryHint()) { // Go back to the suggestion mode if the user canceled the // "Touch again to save". // NOTE: In gerenal, we don't revert the word when backspacing // from a manual suggestion pick. We deliberately chose a // different behavior only in the case of picking the first // suggestion (typed word). It's intentional to have made this // inconsistent with backspacing after selecting other suggestions. revertLastWord(deleteChar); } else { sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL); if (mDeleteCount > DELETE_ACCELERATE_AT) { sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL); } } } ic.endBatchEdit(); } private void handleTab() { final int imeOptions = getCurrentInputEditorInfo().imeOptions; if (!EditorInfoCompatUtils.hasFlagNavigateNext(imeOptions) && !EditorInfoCompatUtils.hasFlagNavigatePrevious(imeOptions)) { sendDownUpKeyEvents(KeyEvent.KEYCODE_TAB); return; } final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; // True if keyboard is in either chording shift or manual temporary upper case mode. final boolean isManualTemporaryUpperCase = mKeyboardSwitcher.isManualTemporaryUpperCase(); if (EditorInfoCompatUtils.hasFlagNavigateNext(imeOptions) && !isManualTemporaryUpperCase) { EditorInfoCompatUtils.performEditorActionNext(ic); ic.performEditorAction(EditorInfo.IME_ACTION_NEXT); } else if (EditorInfoCompatUtils.hasFlagNavigatePrevious(imeOptions) && isManualTemporaryUpperCase) { EditorInfoCompatUtils.performEditorActionPrevious(ic); } } private void handleCharacter(int primaryCode, int[] keyCodes, int x, int y) { mVoiceProxy.handleCharacter(); if (mJustAddedMagicSpace && mSettingsValues.isMagicSpaceStripper(primaryCode)) { removeTrailingSpace(); } if (mLastSelectionStart == mLastSelectionEnd) { mRecorrection.abortRecorrection(false); } int code = primaryCode; if (isAlphabet(code) && isSuggestionsRequested() && !isCursorTouchingWord()) { if (!mHasUncommittedTypedChars) { mHasUncommittedTypedChars = true; mComposing.setLength(0); mRecorrection.saveWordInHistory(mWord, mBestWord); mWord.reset(); clearSuggestions(); } } KeyboardSwitcher switcher = mKeyboardSwitcher; if (switcher.isShiftedOrShiftLocked()) { if (keyCodes == null || keyCodes[0] < Character.MIN_CODE_POINT || keyCodes[0] > Character.MAX_CODE_POINT) { return; } code = keyCodes[0]; if (switcher.isAlphabetMode() && Character.isLowerCase(code)) { int upperCaseCode = Character.toUpperCase(code); if (upperCaseCode != code) { code = upperCaseCode; } else { // Some keys, such as [eszett], have upper case as multi-characters. String upperCase = new String(new int[] {code}, 0, 1).toUpperCase(); onTextInput(upperCase); return; } } } if (mHasUncommittedTypedChars) { if (mComposing.length() == 0 && switcher.isAlphabetMode() && switcher.isShiftedOrShiftLocked()) { mWord.setFirstCharCapitalized(true); } mComposing.append((char) code); mWord.add(code, keyCodes, x, y); InputConnection ic = getCurrentInputConnection(); if (ic != null) { // If it's the first letter, make note of auto-caps state if (mWord.size() == 1) { mWord.setAutoCapitalized(getCurrentAutoCapsState()); } ic.setComposingText(mComposing, 1); } mHandler.postUpdateSuggestions(); } else { sendKeyChar((char)code); } if (mJustAddedMagicSpace && mSettingsValues.isMagicSpaceSwapper(primaryCode)) { swapSwapperAndSpace(); } else { mJustAddedMagicSpace = false; } switcher.updateShiftState(); if (LatinIME.PERF_DEBUG) measureCps(); TextEntryState.typedCharacter((char) code, mSettingsValues.isWordSeparator(code), x, y); } private void handleSeparator(int primaryCode, int x, int y) { mVoiceProxy.handleSeparator(); // Should dismiss the "Touch again to save" message when handling separator if (mCandidateView != null && mCandidateView.dismissAddToDictionaryHint()) { mHandler.cancelUpdateBigramPredictions(); mHandler.postUpdateSuggestions(); } boolean pickedDefault = false; // Handle separator final InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.beginBatchEdit(); mRecorrection.abortRecorrection(false); } if (mHasUncommittedTypedChars) { // In certain languages where single quote is a separator, it's better // not to auto correct, but accept the typed word. For instance, // in Italian dov' should not be expanded to dove' because the elision // requires the last vowel to be removed. final boolean shouldAutoCorrect = (mSettingsValues.mAutoCorrectEnabled || mSettingsValues.mQuickFixes) && !mInputTypeNoAutoCorrect && mHasDictionary; if (shouldAutoCorrect && primaryCode != Keyboard.CODE_SINGLE_QUOTE) { pickedDefault = pickDefaultSuggestion(primaryCode); } else { commitTyped(ic); } } if (mJustAddedMagicSpace) { if (mSettingsValues.isMagicSpaceSwapper(primaryCode)) { sendKeyChar((char)primaryCode); swapSwapperAndSpace(); } else { if (mSettingsValues.isMagicSpaceStripper(primaryCode)) removeTrailingSpace(); sendKeyChar((char)primaryCode); mJustAddedMagicSpace = false; } } else { sendKeyChar((char)primaryCode); } if (isSuggestionsRequested() && primaryCode == Keyboard.CODE_SPACE) { maybeDoubleSpace(); } TextEntryState.typedCharacter((char) primaryCode, true, x, y); if (pickedDefault) { CharSequence typedWord = mWord.getTypedWord(); TextEntryState.backToAcceptedDefault(typedWord); if (!TextUtils.isEmpty(typedWord) && !typedWord.equals(mBestWord)) { InputConnectionCompatUtils.commitCorrection( ic, mLastSelectionEnd - typedWord.length(), typedWord, mBestWord); if (mCandidateView != null) mCandidateView.onAutoCorrectionInverted(mBestWord); } } if (Keyboard.CODE_SPACE == primaryCode) { if (!isCursorTouchingWord()) { mHandler.cancelUpdateSuggestions(); mHandler.cancelUpdateOldSuggestions(); mHandler.postUpdateBigramPredictions(); } } else { // Set punctuation right away. onUpdateSelection will fire but tests whether it is // already displayed or not, so it's okay. setPunctuationSuggestions(); } mKeyboardSwitcher.updateShiftState(); if (ic != null) { ic.endBatchEdit(); } } private void handleClose() { commitTyped(getCurrentInputConnection()); mVoiceProxy.handleClose(); requestHideSelf(0); LatinKeyboardView inputView = mKeyboardSwitcher.getInputView(); if (inputView != null) inputView.closing(); } public boolean isSuggestionsRequested() { return mIsSettingsSuggestionStripOn && (mCorrectionMode > 0 || isShowingSuggestionsStrip()); } public boolean isShowingPunctuationList() { return mSettingsValues.mSuggestPuncList == mCandidateView.getSuggestions(); } public boolean isShowingSuggestionsStrip() { return (mSuggestionVisibility == SUGGESTION_VISIBILILTY_SHOW_VALUE) || (mSuggestionVisibility == SUGGESTION_VISIBILILTY_SHOW_ONLY_PORTRAIT_VALUE && mOrientation == Configuration.ORIENTATION_PORTRAIT); } public boolean isCandidateStripVisible() { if (mCandidateView == null) return false; if (mCandidateView.isShowingAddToDictionaryHint() || TextEntryState.isRecorrecting()) return true; if (!isShowingSuggestionsStrip()) return false; if (mApplicationSpecifiedCompletionOn) return true; return isSuggestionsRequested(); } public void switchToKeyboardView() { if (DEBUG) { Log.d(TAG, "Switch to keyboard view."); } View v = mKeyboardSwitcher.getInputView(); if (v != null) { // Confirms that the keyboard view doesn't have parent view. ViewParent p = v.getParent(); if (p != null && p instanceof ViewGroup) { ((ViewGroup) p).removeView(v); } setInputView(v); } setCandidatesViewShown(isCandidateStripVisible()); updateInputViewShown(); mHandler.postUpdateSuggestions(); } public void clearSuggestions() { setSuggestions(SuggestedWords.EMPTY); } public void setSuggestions(SuggestedWords words) { if (mVoiceProxy.getAndResetIsShowingHint()) { setCandidatesView(mCandidateViewContainer); } if (mCandidateView != null) { mCandidateView.setSuggestions(words); if (mCandidateView.isConfigCandidateHighlightFontColorEnabled()) { mKeyboardSwitcher.onAutoCorrectionStateChanged( words.hasWordAboveAutoCorrectionScoreThreshold()); } } } public void updateSuggestions() { // Check if we have a suggestion engine attached. if ((mSuggest == null || !isSuggestionsRequested()) && !mVoiceProxy.isVoiceInputHighlighted()) { return; } if (!mHasUncommittedTypedChars) { setPunctuationSuggestions(); return; } showSuggestions(mWord); } private void showSuggestions(WordComposer word) { // TODO: May need a better way of retrieving previous word CharSequence prevWord = EditingUtils.getPreviousWord(getCurrentInputConnection(), mSettingsValues.mWordSeparators); SuggestedWords.Builder builder = mSuggest.getSuggestedWordBuilder( mKeyboardSwitcher.getInputView(), word, prevWord); boolean correctionAvailable = !mInputTypeNoAutoCorrect && mSuggest.hasAutoCorrection(); final CharSequence typedWord = word.getTypedWord(); // Here, we want to promote a whitelisted word if exists. final boolean typedWordValid = AutoCorrection.isValidWordForAutoCorrection( mSuggest.getUnigramDictionaries(), typedWord, preferCapitalization()); if (mCorrectionMode == Suggest.CORRECTION_FULL || mCorrectionMode == Suggest.CORRECTION_FULL_BIGRAM) { correctionAvailable |= typedWordValid; } // Don't auto-correct words with multiple capital letter correctionAvailable &= !word.isMostlyCaps(); correctionAvailable &= !TextEntryState.isRecorrecting(); // Basically, we update the suggestion strip only when suggestion count > 1. However, // there is an exception: We update the suggestion strip whenever typed word's length // is 1 or typed word is found in dictionary, regardless of suggestion count. Actually, // in most cases, suggestion count is 1 when typed word's length is 1, but we do always // need to clear the previous state when the user starts typing a word (i.e. typed word's // length == 1). if (builder.size() > 1 || typedWord.length() == 1 || typedWordValid || mCandidateView.isShowingAddToDictionaryHint()) { builder.setTypedWordValid(typedWordValid).setHasMinimalSuggestion(correctionAvailable); } else { final SuggestedWords previousSuggestions = mCandidateView.getSuggestions(); if (previousSuggestions == mSettingsValues.mSuggestPuncList) return; builder.addTypedWordAndPreviousSuggestions(typedWord, previousSuggestions); } showSuggestions(builder.build(), typedWord); } public void showSuggestions(SuggestedWords suggestedWords, CharSequence typedWord) { setSuggestions(suggestedWords); if (suggestedWords.size() > 0) { if (Utils.shouldBlockedBySafetyNetForAutoCorrection(suggestedWords, mSuggest)) { mBestWord = typedWord; } else if (suggestedWords.hasAutoCorrectionWord()) { mBestWord = suggestedWords.getWord(1); } else { mBestWord = typedWord; } } else { mBestWord = null; } setCandidatesViewShown(isCandidateStripVisible()); } private boolean pickDefaultSuggestion(int separatorCode) { // Complete any pending candidate query first if (mHandler.hasPendingUpdateSuggestions()) { mHandler.cancelUpdateSuggestions(); updateSuggestions(); } if (mBestWord != null && mBestWord.length() > 0) { TextEntryState.acceptedDefault(mWord.getTypedWord(), mBestWord, separatorCode); mJustAccepted = true; pickSuggestion(mBestWord); // Add the word to the auto dictionary if it's not a known word addToAutoAndUserBigramDictionaries(mBestWord, AutoDictionary.FREQUENCY_FOR_TYPED); return true; } return false; } public void pickSuggestionManually(int index, CharSequence suggestion) { SuggestedWords suggestions = mCandidateView.getSuggestions(); mVoiceProxy.flushAndLogAllTextModificationCounters(index, suggestion, mSettingsValues.mWordSeparators); final boolean recorrecting = TextEntryState.isRecorrecting(); InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.beginBatchEdit(); } if (mApplicationSpecifiedCompletionOn && mApplicationSpecifiedCompletions != null && index >= 0 && index < mApplicationSpecifiedCompletions.length) { CompletionInfo ci = mApplicationSpecifiedCompletions[index]; if (ic != null) { ic.commitCompletion(ci); } mCommittedLength = suggestion.length(); if (mCandidateView != null) { mCandidateView.clear(); } mKeyboardSwitcher.updateShiftState(); if (ic != null) { ic.endBatchEdit(); } return; } // If this is a punctuation, apply it through the normal key press if (suggestion.length() == 1 && (mSettingsValues.isWordSeparator(suggestion.charAt(0)) || mSettingsValues.isSuggestedPunctuation(suggestion.charAt(0)))) { // Word separators are suggested before the user inputs something. // So, LatinImeLogger logs "" as a user's input. LatinImeLogger.logOnManualSuggestion( "", suggestion.toString(), index, suggestions.mWords); // Find out whether the previous character is a space. If it is, as a special case // for punctuation entered through the suggestion strip, it should be considered // a magic space even if it was a normal space. This is meant to help in case the user // pressed space on purpose of displaying the suggestion strip punctuation. final char primaryCode = suggestion.charAt(0); final int toLeft = (ic == null) ? 0 : ic.getTextBeforeCursor(1, 0).charAt(0); final boolean oldMagicSpace = mJustAddedMagicSpace; if (Keyboard.CODE_SPACE == toLeft) mJustAddedMagicSpace = true; onCodeInput(primaryCode, new int[] { primaryCode }, KeyboardActionListener.NOT_A_TOUCH_COORDINATE, KeyboardActionListener.NOT_A_TOUCH_COORDINATE); mJustAddedMagicSpace = oldMagicSpace; if (ic != null) { ic.endBatchEdit(); } return; } if (!mHasUncommittedTypedChars) { // If we are not composing a word, then it was a suggestion inferred from // context - no user input. We should reset the word composer. mWord.reset(); } mJustAccepted = true; pickSuggestion(suggestion); // Add the word to the auto dictionary if it's not a known word if (index == 0) { addToAutoAndUserBigramDictionaries(suggestion, AutoDictionary.FREQUENCY_FOR_PICKED); } else { addToOnlyBigramDictionary(suggestion, 1); } LatinImeLogger.logOnManualSuggestion(mComposing.toString(), suggestion.toString(), index, suggestions.mWords); TextEntryState.acceptedSuggestion(mComposing.toString(), suggestion); // Follow it with a space if (mShouldInsertMagicSpace && !recorrecting) { sendMagicSpace(); } // We should show the hint if the user pressed the first entry AND either: // - There is no dictionary (we know that because we tried to load it => null != mSuggest // AND mHasDictionary is false) // - There is a dictionary and the word is not in it // Please note that if mSuggest is null, it means that everything is off: suggestion // and correction, so we shouldn't try to show the hint // We used to look at mCorrectionMode here, but showing the hint should have nothing // to do with the autocorrection setting. final boolean showingAddToDictionaryHint = index == 0 && mSuggest != null // If there is no dictionary the hint should be shown. && (!mHasDictionary // If "suggestion" is not in the dictionary, the hint should be shown. || !AutoCorrection.isValidWord( mSuggest.getUnigramDictionaries(), suggestion, true)); if (!recorrecting) { // Fool the state watcher so that a subsequent backspace will not do a revert, unless // we just did a correction, in which case we need to stay in // TextEntryState.State.PICKED_SUGGESTION state. TextEntryState.typedCharacter((char) Keyboard.CODE_SPACE, true, WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE); - // From there on onUpdateSelection() will fire so suggestions will be updated + // On Honeycomb+, onUpdateSelection() will fire, but in Gingerbread- in WebTextView + // only it does not, for some reason. Force update suggestions so that it works + // in Gingerbread- in WebTextView too. + mHandler.postUpdateSuggestions(); } else if (!showingAddToDictionaryHint) { // If we're not showing the "Touch again to save", then show corrections again. // In case the cursor position doesn't change, make sure we show the suggestions again. clearSuggestions(); mHandler.postUpdateOldSuggestions(); } if (showingAddToDictionaryHint) { mCandidateView.showAddToDictionaryHint(suggestion); } if (ic != null) { ic.endBatchEdit(); } } /** * Commits the chosen word to the text field and saves it for later * retrieval. * @param suggestion the suggestion picked by the user to be committed to * the text field */ private void pickSuggestion(CharSequence suggestion) { KeyboardSwitcher switcher = mKeyboardSwitcher; if (!switcher.isKeyboardAvailable()) return; InputConnection ic = getCurrentInputConnection(); if (ic != null) { mVoiceProxy.rememberReplacedWord(suggestion, mSettingsValues.mWordSeparators); ic.commitText(suggestion, 1); } mRecorrection.saveWordInHistory(mWord, suggestion); mHasUncommittedTypedChars = false; mCommittedLength = suggestion.length(); } private static final WordComposer sEmptyWordComposer = new WordComposer(); private void updateBigramPredictions() { if (mSuggest == null || !isSuggestionsRequested()) return; if (!mSettingsValues.mBigramPredictionEnabled) { setPunctuationSuggestions(); return; } final CharSequence prevWord = EditingUtils.getThisWord(getCurrentInputConnection(), mSettingsValues.mWordSeparators); SuggestedWords.Builder builder = mSuggest.getSuggestedWordBuilder( mKeyboardSwitcher.getInputView(), sEmptyWordComposer, prevWord); if (builder.size() > 0) { // Explicitly supply an empty typed word (the no-second-arg version of // showSuggestions will retrieve the word near the cursor, we don't want that here) showSuggestions(builder.build(), ""); } else { if (!isShowingPunctuationList()) setPunctuationSuggestions(); } } public void setPunctuationSuggestions() { setSuggestions(mSettingsValues.mSuggestPuncList); setCandidatesViewShown(isCandidateStripVisible()); } private void addToAutoAndUserBigramDictionaries(CharSequence suggestion, int frequencyDelta) { checkAddToDictionary(suggestion, frequencyDelta, false); } private void addToOnlyBigramDictionary(CharSequence suggestion, int frequencyDelta) { checkAddToDictionary(suggestion, frequencyDelta, true); } /** * Adds to the UserBigramDictionary and/or AutoDictionary * @param selectedANotTypedWord true if it should be added to bigram dictionary if possible */ private void checkAddToDictionary(CharSequence suggestion, int frequencyDelta, boolean selectedANotTypedWord) { if (suggestion == null || suggestion.length() < 1) return; // Only auto-add to dictionary if auto-correct is ON. Otherwise we'll be // adding words in situations where the user or application really didn't // want corrections enabled or learned. if (!(mCorrectionMode == Suggest.CORRECTION_FULL || mCorrectionMode == Suggest.CORRECTION_FULL_BIGRAM)) { return; } final boolean selectedATypedWordAndItsInAutoDic = !selectedANotTypedWord && mAutoDictionary.isValidWord(suggestion); final boolean isValidWord = AutoCorrection.isValidWord( mSuggest.getUnigramDictionaries(), suggestion, true); final boolean needsToAddToAutoDictionary = selectedATypedWordAndItsInAutoDic || !isValidWord; if (needsToAddToAutoDictionary) { mAutoDictionary.addWord(suggestion.toString(), frequencyDelta); } if (mUserBigramDictionary != null) { // We don't want to register as bigrams words separated by a separator. // For example "I will, and you too" : we don't want the pair ("will" "and") to be // a bigram. CharSequence prevWord = EditingUtils.getPreviousWord(getCurrentInputConnection(), mSettingsValues.mWordSeparators); if (!TextUtils.isEmpty(prevWord)) { mUserBigramDictionary.addBigrams(prevWord.toString(), suggestion.toString()); } } } public boolean isCursorTouchingWord() { InputConnection ic = getCurrentInputConnection(); if (ic == null) return false; CharSequence toLeft = ic.getTextBeforeCursor(1, 0); CharSequence toRight = ic.getTextAfterCursor(1, 0); if (!TextUtils.isEmpty(toLeft) && !mSettingsValues.isWordSeparator(toLeft.charAt(0)) && !mSettingsValues.isSuggestedPunctuation(toLeft.charAt(0))) { return true; } if (!TextUtils.isEmpty(toRight) && !mSettingsValues.isWordSeparator(toRight.charAt(0)) && !mSettingsValues.isSuggestedPunctuation(toRight.charAt(0))) { return true; } return false; } private boolean sameAsTextBeforeCursor(InputConnection ic, CharSequence text) { CharSequence beforeText = ic.getTextBeforeCursor(text.length(), 0); return TextUtils.equals(text, beforeText); } public void revertLastWord(boolean deleteChar) { final int length = mComposing.length(); if (!mHasUncommittedTypedChars && length > 0) { final InputConnection ic = getCurrentInputConnection(); final CharSequence punctuation = ic.getTextBeforeCursor(1, 0); if (deleteChar) ic.deleteSurroundingText(1, 0); int toDelete = mCommittedLength; final CharSequence toTheLeft = ic.getTextBeforeCursor(mCommittedLength, 0); if (!TextUtils.isEmpty(toTheLeft) && mSettingsValues.isWordSeparator(toTheLeft.charAt(0))) { toDelete--; } ic.deleteSurroundingText(toDelete, 0); // Re-insert punctuation only when the deleted character was word separator and the // composing text wasn't equal to the auto-corrected text. if (deleteChar && !TextUtils.isEmpty(punctuation) && mSettingsValues.isWordSeparator(punctuation.charAt(0)) && !TextUtils.equals(mComposing, toTheLeft)) { ic.commitText(mComposing, 1); TextEntryState.acceptedTyped(mComposing); ic.commitText(punctuation, 1); TextEntryState.typedCharacter(punctuation.charAt(0), true, WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE); // Clear composing text mComposing.setLength(0); } else { mHasUncommittedTypedChars = true; ic.setComposingText(mComposing, 1); TextEntryState.backspace(); } mHandler.cancelUpdateBigramPredictions(); mHandler.postUpdateSuggestions(); } else { sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL); } } public boolean isWordSeparator(int code) { return mSettingsValues.isWordSeparator(code); } private void sendMagicSpace() { sendKeyChar((char)Keyboard.CODE_SPACE); mJustAddedMagicSpace = true; mKeyboardSwitcher.updateShiftState(); } public boolean preferCapitalization() { return mWord.isFirstCharCapitalized(); } // Notify that language or mode have been changed and toggleLanguage will update KeyboardID // according to new language or mode. public void onRefreshKeyboard() { // Reload keyboard because the current language has been changed. mKeyboardSwitcher.loadKeyboard(getCurrentInputEditorInfo(), mSubtypeSwitcher.isShortcutImeEnabled() && mVoiceProxy.isVoiceButtonEnabled(), mVoiceProxy.isVoiceButtonOnPrimary()); initSuggest(); loadSettings(); mKeyboardSwitcher.updateShiftState(); } // "reset" and "next" are used only for USE_SPACEBAR_LANGUAGE_SWITCHER. private void toggleLanguage(boolean next) { if (mSubtypeSwitcher.useSpacebarLanguageSwitcher()) { mSubtypeSwitcher.toggleLanguage(next); } // The following is necessary because on API levels < 10, we don't get notified when // subtype changes. onRefreshKeyboard(); } @Override public void onSwipeDown() { if (mSettingsValues.mSwipeDownDismissKeyboardEnabled) handleClose(); } @Override public void onPress(int primaryCode, boolean withSliding) { if (mKeyboardSwitcher.isVibrateAndSoundFeedbackRequired()) { vibrate(); playKeyClick(primaryCode); } KeyboardSwitcher switcher = mKeyboardSwitcher; final boolean distinctMultiTouch = switcher.hasDistinctMultitouch(); if (distinctMultiTouch && primaryCode == Keyboard.CODE_SHIFT) { switcher.onPressShift(withSliding); } else if (distinctMultiTouch && primaryCode == Keyboard.CODE_SWITCH_ALPHA_SYMBOL) { switcher.onPressSymbol(); } else { switcher.onOtherKeyPressed(); } } @Override public void onRelease(int primaryCode, boolean withSliding) { KeyboardSwitcher switcher = mKeyboardSwitcher; // Reset any drag flags in the keyboard final boolean distinctMultiTouch = switcher.hasDistinctMultitouch(); if (distinctMultiTouch && primaryCode == Keyboard.CODE_SHIFT) { switcher.onReleaseShift(withSliding); } else if (distinctMultiTouch && primaryCode == Keyboard.CODE_SWITCH_ALPHA_SYMBOL) { switcher.onReleaseSymbol(); } } // receive ringer mode change and network state change. private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) { updateRingerMode(); } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { mSubtypeSwitcher.onNetworkStateChanged(intent); } } }; // update flags for silent mode private void updateRingerMode() { if (mAudioManager == null) { mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); } if (mAudioManager != null) { mSilentModeOn = (mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL); } } private void playKeyClick(int primaryCode) { // if mAudioManager is null, we don't have the ringer state yet // mAudioManager will be set by updateRingerMode if (mAudioManager == null) { if (mKeyboardSwitcher.getInputView() != null) { updateRingerMode(); } } if (isSoundOn()) { // FIXME: Volume and enable should come from UI settings // FIXME: These should be triggered after auto-repeat logic int sound = AudioManager.FX_KEYPRESS_STANDARD; switch (primaryCode) { case Keyboard.CODE_DELETE: sound = AudioManager.FX_KEYPRESS_DELETE; break; case Keyboard.CODE_ENTER: sound = AudioManager.FX_KEYPRESS_RETURN; break; case Keyboard.CODE_SPACE: sound = AudioManager.FX_KEYPRESS_SPACEBAR; break; } mAudioManager.playSoundEffect(sound, FX_VOLUME); } } public void vibrate() { if (!mSettingsValues.mVibrateOn) { return; } LatinKeyboardView inputView = mKeyboardSwitcher.getInputView(); if (inputView != null) { inputView.performHapticFeedback( HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING); } } public void promoteToUserDictionary(String word, int frequency) { if (mUserDictionary.isValidWord(word)) return; mUserDictionary.addWord(word, frequency); } public WordComposer getCurrentWord() { return mWord; } public boolean getPopupOn() { return mSettingsValues.mPopupOn; } boolean isSoundOn() { return mSettingsValues.mSoundOn && !mSilentModeOn; } private void updateCorrectionMode() { // TODO: cleanup messy flags mHasDictionary = mSuggest != null ? mSuggest.hasMainDictionary() : false; final boolean shouldAutoCorrect = (mSettingsValues.mAutoCorrectEnabled || mSettingsValues.mQuickFixes) && !mInputTypeNoAutoCorrect && mHasDictionary; mCorrectionMode = (shouldAutoCorrect && mSettingsValues.mAutoCorrectEnabled) ? Suggest.CORRECTION_FULL : (shouldAutoCorrect ? Suggest.CORRECTION_BASIC : Suggest.CORRECTION_NONE); mCorrectionMode = (mSettingsValues.mBigramSuggestionEnabled && shouldAutoCorrect && mSettingsValues.mAutoCorrectEnabled) ? Suggest.CORRECTION_FULL_BIGRAM : mCorrectionMode; if (mSuggest != null) { mSuggest.setCorrectionMode(mCorrectionMode); } } private void updateAutoTextEnabled() { if (mSuggest == null) return; mSuggest.setQuickFixesEnabled(mSettingsValues.mQuickFixes && SubtypeSwitcher.getInstance().isSystemLanguageSameAsInputLanguage()); } private void updateSuggestionVisibility(final SharedPreferences prefs, final Resources res) { final String suggestionVisiblityStr = prefs.getString( Settings.PREF_SHOW_SUGGESTIONS_SETTING, res.getString(R.string.prefs_suggestion_visibility_default_value)); for (int visibility : SUGGESTION_VISIBILITY_VALUE_ARRAY) { if (suggestionVisiblityStr.equals(res.getString(visibility))) { mSuggestionVisibility = visibility; break; } } } protected void launchSettings() { launchSettings(Settings.class); } public void launchDebugSettings() { launchSettings(DebugSettings.class); } protected void launchSettings(Class<? extends PreferenceActivity> settingsClass) { handleClose(); Intent intent = new Intent(); intent.setClass(LatinIME.this, settingsClass); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } private void showSubtypeSelectorAndSettings() { final CharSequence title = getString(R.string.english_ime_input_options); final CharSequence[] items = new CharSequence[] { // TODO: Should use new string "Select active input modes". getString(R.string.language_selection_title), getString(R.string.english_ime_settings), }; final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int position) { di.dismiss(); switch (position) { case 0: Intent intent = CompatUtils.getInputLanguageSelectionIntent( mInputMethodId, Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); break; case 1: launchSettings(); break; } } }; showOptionsMenuInternal(title, items, listener); } private void showOptionsMenu() { final CharSequence title = getString(R.string.english_ime_input_options); final CharSequence[] items = new CharSequence[] { getString(R.string.selectInputMethod), getString(R.string.english_ime_settings), }; final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int position) { di.dismiss(); switch (position) { case 0: mImm.showInputMethodPicker(); break; case 1: launchSettings(); break; } } }; showOptionsMenuInternal(title, items, listener); } private void showOptionsMenuInternal(CharSequence title, CharSequence[] items, DialogInterface.OnClickListener listener) { final IBinder windowToken = mKeyboardSwitcher.getInputView().getWindowToken(); if (windowToken == null) return; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true); builder.setIcon(R.drawable.ic_dialog_keyboard); builder.setNegativeButton(android.R.string.cancel, null); builder.setItems(items, listener); builder.setTitle(title); mOptionsDialog = builder.create(); mOptionsDialog.setCanceledOnTouchOutside(true); Window window = mOptionsDialog.getWindow(); WindowManager.LayoutParams lp = window.getAttributes(); lp.token = windowToken; lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; window.setAttributes(lp); window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); mOptionsDialog.show(); } @Override protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) { super.dump(fd, fout, args); final Printer p = new PrintWriterPrinter(fout); p.println("LatinIME state :"); p.println(" Keyboard mode = " + mKeyboardSwitcher.getKeyboardMode()); p.println(" mComposing=" + mComposing.toString()); p.println(" mIsSuggestionsRequested=" + mIsSettingsSuggestionStripOn); p.println(" mCorrectionMode=" + mCorrectionMode); p.println(" mHasUncommittedTypedChars=" + mHasUncommittedTypedChars); p.println(" mAutoCorrectEnabled=" + mSettingsValues.mAutoCorrectEnabled); p.println(" mShouldInsertMagicSpace=" + mShouldInsertMagicSpace); p.println(" mApplicationSpecifiedCompletionOn=" + mApplicationSpecifiedCompletionOn); p.println(" TextEntryState.state=" + TextEntryState.getState()); p.println(" mSoundOn=" + mSettingsValues.mSoundOn); p.println(" mVibrateOn=" + mSettingsValues.mVibrateOn); p.println(" mPopupOn=" + mSettingsValues.mPopupOn); } // Characters per second measurement private long mLastCpsTime; private static final int CPS_BUFFER_SIZE = 16; private long[] mCpsIntervals = new long[CPS_BUFFER_SIZE]; private int mCpsIndex; private void measureCps() { long now = System.currentTimeMillis(); if (mLastCpsTime == 0) mLastCpsTime = now - 100; // Initial mCpsIntervals[mCpsIndex] = now - mLastCpsTime; mLastCpsTime = now; mCpsIndex = (mCpsIndex + 1) % CPS_BUFFER_SIZE; long total = 0; for (int i = 0; i < CPS_BUFFER_SIZE; i++) total += mCpsIntervals[i]; System.out.println("CPS = " + ((CPS_BUFFER_SIZE * 1000f) / total)); } }
true
true
public void pickSuggestionManually(int index, CharSequence suggestion) { SuggestedWords suggestions = mCandidateView.getSuggestions(); mVoiceProxy.flushAndLogAllTextModificationCounters(index, suggestion, mSettingsValues.mWordSeparators); final boolean recorrecting = TextEntryState.isRecorrecting(); InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.beginBatchEdit(); } if (mApplicationSpecifiedCompletionOn && mApplicationSpecifiedCompletions != null && index >= 0 && index < mApplicationSpecifiedCompletions.length) { CompletionInfo ci = mApplicationSpecifiedCompletions[index]; if (ic != null) { ic.commitCompletion(ci); } mCommittedLength = suggestion.length(); if (mCandidateView != null) { mCandidateView.clear(); } mKeyboardSwitcher.updateShiftState(); if (ic != null) { ic.endBatchEdit(); } return; } // If this is a punctuation, apply it through the normal key press if (suggestion.length() == 1 && (mSettingsValues.isWordSeparator(suggestion.charAt(0)) || mSettingsValues.isSuggestedPunctuation(suggestion.charAt(0)))) { // Word separators are suggested before the user inputs something. // So, LatinImeLogger logs "" as a user's input. LatinImeLogger.logOnManualSuggestion( "", suggestion.toString(), index, suggestions.mWords); // Find out whether the previous character is a space. If it is, as a special case // for punctuation entered through the suggestion strip, it should be considered // a magic space even if it was a normal space. This is meant to help in case the user // pressed space on purpose of displaying the suggestion strip punctuation. final char primaryCode = suggestion.charAt(0); final int toLeft = (ic == null) ? 0 : ic.getTextBeforeCursor(1, 0).charAt(0); final boolean oldMagicSpace = mJustAddedMagicSpace; if (Keyboard.CODE_SPACE == toLeft) mJustAddedMagicSpace = true; onCodeInput(primaryCode, new int[] { primaryCode }, KeyboardActionListener.NOT_A_TOUCH_COORDINATE, KeyboardActionListener.NOT_A_TOUCH_COORDINATE); mJustAddedMagicSpace = oldMagicSpace; if (ic != null) { ic.endBatchEdit(); } return; } if (!mHasUncommittedTypedChars) { // If we are not composing a word, then it was a suggestion inferred from // context - no user input. We should reset the word composer. mWord.reset(); } mJustAccepted = true; pickSuggestion(suggestion); // Add the word to the auto dictionary if it's not a known word if (index == 0) { addToAutoAndUserBigramDictionaries(suggestion, AutoDictionary.FREQUENCY_FOR_PICKED); } else { addToOnlyBigramDictionary(suggestion, 1); } LatinImeLogger.logOnManualSuggestion(mComposing.toString(), suggestion.toString(), index, suggestions.mWords); TextEntryState.acceptedSuggestion(mComposing.toString(), suggestion); // Follow it with a space if (mShouldInsertMagicSpace && !recorrecting) { sendMagicSpace(); } // We should show the hint if the user pressed the first entry AND either: // - There is no dictionary (we know that because we tried to load it => null != mSuggest // AND mHasDictionary is false) // - There is a dictionary and the word is not in it // Please note that if mSuggest is null, it means that everything is off: suggestion // and correction, so we shouldn't try to show the hint // We used to look at mCorrectionMode here, but showing the hint should have nothing // to do with the autocorrection setting. final boolean showingAddToDictionaryHint = index == 0 && mSuggest != null // If there is no dictionary the hint should be shown. && (!mHasDictionary // If "suggestion" is not in the dictionary, the hint should be shown. || !AutoCorrection.isValidWord( mSuggest.getUnigramDictionaries(), suggestion, true)); if (!recorrecting) { // Fool the state watcher so that a subsequent backspace will not do a revert, unless // we just did a correction, in which case we need to stay in // TextEntryState.State.PICKED_SUGGESTION state. TextEntryState.typedCharacter((char) Keyboard.CODE_SPACE, true, WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE); // From there on onUpdateSelection() will fire so suggestions will be updated } else if (!showingAddToDictionaryHint) { // If we're not showing the "Touch again to save", then show corrections again. // In case the cursor position doesn't change, make sure we show the suggestions again. clearSuggestions(); mHandler.postUpdateOldSuggestions(); } if (showingAddToDictionaryHint) { mCandidateView.showAddToDictionaryHint(suggestion); } if (ic != null) { ic.endBatchEdit(); } }
public void pickSuggestionManually(int index, CharSequence suggestion) { SuggestedWords suggestions = mCandidateView.getSuggestions(); mVoiceProxy.flushAndLogAllTextModificationCounters(index, suggestion, mSettingsValues.mWordSeparators); final boolean recorrecting = TextEntryState.isRecorrecting(); InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.beginBatchEdit(); } if (mApplicationSpecifiedCompletionOn && mApplicationSpecifiedCompletions != null && index >= 0 && index < mApplicationSpecifiedCompletions.length) { CompletionInfo ci = mApplicationSpecifiedCompletions[index]; if (ic != null) { ic.commitCompletion(ci); } mCommittedLength = suggestion.length(); if (mCandidateView != null) { mCandidateView.clear(); } mKeyboardSwitcher.updateShiftState(); if (ic != null) { ic.endBatchEdit(); } return; } // If this is a punctuation, apply it through the normal key press if (suggestion.length() == 1 && (mSettingsValues.isWordSeparator(suggestion.charAt(0)) || mSettingsValues.isSuggestedPunctuation(suggestion.charAt(0)))) { // Word separators are suggested before the user inputs something. // So, LatinImeLogger logs "" as a user's input. LatinImeLogger.logOnManualSuggestion( "", suggestion.toString(), index, suggestions.mWords); // Find out whether the previous character is a space. If it is, as a special case // for punctuation entered through the suggestion strip, it should be considered // a magic space even if it was a normal space. This is meant to help in case the user // pressed space on purpose of displaying the suggestion strip punctuation. final char primaryCode = suggestion.charAt(0); final int toLeft = (ic == null) ? 0 : ic.getTextBeforeCursor(1, 0).charAt(0); final boolean oldMagicSpace = mJustAddedMagicSpace; if (Keyboard.CODE_SPACE == toLeft) mJustAddedMagicSpace = true; onCodeInput(primaryCode, new int[] { primaryCode }, KeyboardActionListener.NOT_A_TOUCH_COORDINATE, KeyboardActionListener.NOT_A_TOUCH_COORDINATE); mJustAddedMagicSpace = oldMagicSpace; if (ic != null) { ic.endBatchEdit(); } return; } if (!mHasUncommittedTypedChars) { // If we are not composing a word, then it was a suggestion inferred from // context - no user input. We should reset the word composer. mWord.reset(); } mJustAccepted = true; pickSuggestion(suggestion); // Add the word to the auto dictionary if it's not a known word if (index == 0) { addToAutoAndUserBigramDictionaries(suggestion, AutoDictionary.FREQUENCY_FOR_PICKED); } else { addToOnlyBigramDictionary(suggestion, 1); } LatinImeLogger.logOnManualSuggestion(mComposing.toString(), suggestion.toString(), index, suggestions.mWords); TextEntryState.acceptedSuggestion(mComposing.toString(), suggestion); // Follow it with a space if (mShouldInsertMagicSpace && !recorrecting) { sendMagicSpace(); } // We should show the hint if the user pressed the first entry AND either: // - There is no dictionary (we know that because we tried to load it => null != mSuggest // AND mHasDictionary is false) // - There is a dictionary and the word is not in it // Please note that if mSuggest is null, it means that everything is off: suggestion // and correction, so we shouldn't try to show the hint // We used to look at mCorrectionMode here, but showing the hint should have nothing // to do with the autocorrection setting. final boolean showingAddToDictionaryHint = index == 0 && mSuggest != null // If there is no dictionary the hint should be shown. && (!mHasDictionary // If "suggestion" is not in the dictionary, the hint should be shown. || !AutoCorrection.isValidWord( mSuggest.getUnigramDictionaries(), suggestion, true)); if (!recorrecting) { // Fool the state watcher so that a subsequent backspace will not do a revert, unless // we just did a correction, in which case we need to stay in // TextEntryState.State.PICKED_SUGGESTION state. TextEntryState.typedCharacter((char) Keyboard.CODE_SPACE, true, WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE); // On Honeycomb+, onUpdateSelection() will fire, but in Gingerbread- in WebTextView // only it does not, for some reason. Force update suggestions so that it works // in Gingerbread- in WebTextView too. mHandler.postUpdateSuggestions(); } else if (!showingAddToDictionaryHint) { // If we're not showing the "Touch again to save", then show corrections again. // In case the cursor position doesn't change, make sure we show the suggestions again. clearSuggestions(); mHandler.postUpdateOldSuggestions(); } if (showingAddToDictionaryHint) { mCandidateView.showAddToDictionaryHint(suggestion); } if (ic != null) { ic.endBatchEdit(); } }
diff --git a/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/interfaces/IOptionsGenerator.java b/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/interfaces/IOptionsGenerator.java index ecd141af1..d70be9357 100644 --- a/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/interfaces/IOptionsGenerator.java +++ b/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/interfaces/IOptionsGenerator.java @@ -1,94 +1,94 @@ /******************************************************************************* * Copyright (c) 2006-2011 * Software Technology Group, Dresden University of Technology * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Software Technology Group - TU Dresden, Germany * - initial API and implementation ******************************************************************************/ package org.emftext.sdk.codegen.resource.generators.interfaces; import org.emftext.sdk.codegen.composites.JavaComposite; import org.emftext.sdk.codegen.parameters.ArtifactParameter; import org.emftext.sdk.codegen.resource.GenerationContext; import org.emftext.sdk.codegen.resource.generators.JavaBaseGenerator; public class IOptionsGenerator extends JavaBaseGenerator<ArtifactParameter<GenerationContext>> { public static final String DISABLE_CREATING_MARKERS_FOR_PROBLEMS = "DISABLE_CREATING_MARKERS_FOR_PROBLEMS"; public static final String DISABLE_LOCATION_MAP = "DISABLE_LOCATION_MAP"; public static final String DISABLE_LAYOUT_INFORMATION_RECORDING = "DISABLE_LAYOUT_INFORMATION_RECORDING"; @Override public void generateJavaContents(JavaComposite sc) { sc.add("package " + getResourcePackageName() + ";"); sc.addLineBreak(); sc.addJavadoc( "A list of constants that contains the keys for some options that " + "are built into EMFText. Generated resource plug-ins do automatically " + - "recognize this options and use them if they are configured properly." + "recognize these options and use them if they are configured properly." ); sc.add("public interface " + getResourceClassName() + " {"); sc.addLineBreak(); sc.addJavadoc("The key for the option to provide a stream pre-processor."); sc.add("public String INPUT_STREAM_PREPROCESSOR_PROVIDER = new " + metaInformationClassName + "().getInputStreamPreprocessorProviderOptionKey();"); sc.addLineBreak(); sc.addJavadoc("The key for the option to provide a resource post-processor."); sc.add("public String RESOURCE_POSTPROCESSOR_PROVIDER = new " + metaInformationClassName + "().getResourcePostProcessorProviderOptionKey();"); sc.addLineBreak(); sc.addJavadoc( "The key for the option to specify an expected content type in text resources and text parsers. " + "A content type is an EClass that specifies the root object of a text resource. If this option " + "is set, the parser does not use the start symbols defined in the .cs specification, but use the " + "given EClass as start symbol instead. Note that the value for this option must be an EClass object " + "and not the name of the EClass." ); sc.add("public final String RESOURCE_CONTENT_TYPE = \"RESOURCE_CONTENT_TYPE\";"); sc.addLineBreak(); sc.addJavadoc( "The key for the option to disable marker creation for resource problems. " + "If this option is set to <code>true</code> when loading resources, " + "reported problems will not be added as Eclipse workspace markers. " + "This option is used by the MarkerResolutionGenerator class, which will end up " + "in an infinite loop if marker are created when loading resources as this creation " + "triggers the loading of the same resource and so on." ); sc.add("public final String " + DISABLE_CREATING_MARKERS_FOR_PROBLEMS + " = \"" + DISABLE_CREATING_MARKERS_FOR_PROBLEMS + "\";"); sc.addLineBreak(); sc.addJavadoc( "The key for the option to disable the location map that " + "maps EObjects to the position of their textual representations. " + "If this option is set to <code>true</code>, the " + "memory footprint of large models is reduced. Disabling the " + "location map, however, disables functionality that relies on it " + "(e.g. navigation in the text editor)." ); sc.add("public final String " + DISABLE_LOCATION_MAP + " = \"" + DISABLE_LOCATION_MAP + "\";"); sc.addLineBreak(); sc.addJavadoc( "The key for the option to disable the recording of layout information. " + "If this option is set to <code>true</code>, the " + "memory footprint of large models is reduced. When " + "layout information recording is disabled, a new layout is " + "computed during printing and the original layout is not preserved." ); sc.add("public final String " + DISABLE_LAYOUT_INFORMATION_RECORDING + " = \"" + DISABLE_LAYOUT_INFORMATION_RECORDING + "\";"); sc.addLineBreak(); sc.add("}"); } }
true
true
public void generateJavaContents(JavaComposite sc) { sc.add("package " + getResourcePackageName() + ";"); sc.addLineBreak(); sc.addJavadoc( "A list of constants that contains the keys for some options that " + "are built into EMFText. Generated resource plug-ins do automatically " + "recognize this options and use them if they are configured properly." ); sc.add("public interface " + getResourceClassName() + " {"); sc.addLineBreak(); sc.addJavadoc("The key for the option to provide a stream pre-processor."); sc.add("public String INPUT_STREAM_PREPROCESSOR_PROVIDER = new " + metaInformationClassName + "().getInputStreamPreprocessorProviderOptionKey();"); sc.addLineBreak(); sc.addJavadoc("The key for the option to provide a resource post-processor."); sc.add("public String RESOURCE_POSTPROCESSOR_PROVIDER = new " + metaInformationClassName + "().getResourcePostProcessorProviderOptionKey();"); sc.addLineBreak(); sc.addJavadoc( "The key for the option to specify an expected content type in text resources and text parsers. " + "A content type is an EClass that specifies the root object of a text resource. If this option " + "is set, the parser does not use the start symbols defined in the .cs specification, but use the " + "given EClass as start symbol instead. Note that the value for this option must be an EClass object " + "and not the name of the EClass." ); sc.add("public final String RESOURCE_CONTENT_TYPE = \"RESOURCE_CONTENT_TYPE\";"); sc.addLineBreak(); sc.addJavadoc( "The key for the option to disable marker creation for resource problems. " + "If this option is set to <code>true</code> when loading resources, " + "reported problems will not be added as Eclipse workspace markers. " + "This option is used by the MarkerResolutionGenerator class, which will end up " + "in an infinite loop if marker are created when loading resources as this creation " + "triggers the loading of the same resource and so on." ); sc.add("public final String " + DISABLE_CREATING_MARKERS_FOR_PROBLEMS + " = \"" + DISABLE_CREATING_MARKERS_FOR_PROBLEMS + "\";"); sc.addLineBreak(); sc.addJavadoc( "The key for the option to disable the location map that " + "maps EObjects to the position of their textual representations. " + "If this option is set to <code>true</code>, the " + "memory footprint of large models is reduced. Disabling the " + "location map, however, disables functionality that relies on it " + "(e.g. navigation in the text editor)." ); sc.add("public final String " + DISABLE_LOCATION_MAP + " = \"" + DISABLE_LOCATION_MAP + "\";"); sc.addLineBreak(); sc.addJavadoc( "The key for the option to disable the recording of layout information. " + "If this option is set to <code>true</code>, the " + "memory footprint of large models is reduced. When " + "layout information recording is disabled, a new layout is " + "computed during printing and the original layout is not preserved." ); sc.add("public final String " + DISABLE_LAYOUT_INFORMATION_RECORDING + " = \"" + DISABLE_LAYOUT_INFORMATION_RECORDING + "\";"); sc.addLineBreak(); sc.add("}"); }
public void generateJavaContents(JavaComposite sc) { sc.add("package " + getResourcePackageName() + ";"); sc.addLineBreak(); sc.addJavadoc( "A list of constants that contains the keys for some options that " + "are built into EMFText. Generated resource plug-ins do automatically " + "recognize these options and use them if they are configured properly." ); sc.add("public interface " + getResourceClassName() + " {"); sc.addLineBreak(); sc.addJavadoc("The key for the option to provide a stream pre-processor."); sc.add("public String INPUT_STREAM_PREPROCESSOR_PROVIDER = new " + metaInformationClassName + "().getInputStreamPreprocessorProviderOptionKey();"); sc.addLineBreak(); sc.addJavadoc("The key for the option to provide a resource post-processor."); sc.add("public String RESOURCE_POSTPROCESSOR_PROVIDER = new " + metaInformationClassName + "().getResourcePostProcessorProviderOptionKey();"); sc.addLineBreak(); sc.addJavadoc( "The key for the option to specify an expected content type in text resources and text parsers. " + "A content type is an EClass that specifies the root object of a text resource. If this option " + "is set, the parser does not use the start symbols defined in the .cs specification, but use the " + "given EClass as start symbol instead. Note that the value for this option must be an EClass object " + "and not the name of the EClass." ); sc.add("public final String RESOURCE_CONTENT_TYPE = \"RESOURCE_CONTENT_TYPE\";"); sc.addLineBreak(); sc.addJavadoc( "The key for the option to disable marker creation for resource problems. " + "If this option is set to <code>true</code> when loading resources, " + "reported problems will not be added as Eclipse workspace markers. " + "This option is used by the MarkerResolutionGenerator class, which will end up " + "in an infinite loop if marker are created when loading resources as this creation " + "triggers the loading of the same resource and so on." ); sc.add("public final String " + DISABLE_CREATING_MARKERS_FOR_PROBLEMS + " = \"" + DISABLE_CREATING_MARKERS_FOR_PROBLEMS + "\";"); sc.addLineBreak(); sc.addJavadoc( "The key for the option to disable the location map that " + "maps EObjects to the position of their textual representations. " + "If this option is set to <code>true</code>, the " + "memory footprint of large models is reduced. Disabling the " + "location map, however, disables functionality that relies on it " + "(e.g. navigation in the text editor)." ); sc.add("public final String " + DISABLE_LOCATION_MAP + " = \"" + DISABLE_LOCATION_MAP + "\";"); sc.addLineBreak(); sc.addJavadoc( "The key for the option to disable the recording of layout information. " + "If this option is set to <code>true</code>, the " + "memory footprint of large models is reduced. When " + "layout information recording is disabled, a new layout is " + "computed during printing and the original layout is not preserved." ); sc.add("public final String " + DISABLE_LAYOUT_INFORMATION_RECORDING + " = \"" + DISABLE_LAYOUT_INFORMATION_RECORDING + "\";"); sc.addLineBreak(); sc.add("}"); }
diff --git a/freeplane/src/org/freeplane/view/swing/map/attribute/AttributePopupMenu.java b/freeplane/src/org/freeplane/view/swing/map/attribute/AttributePopupMenu.java index 55ecc5d73..348f02124 100644 --- a/freeplane/src/org/freeplane/view/swing/map/attribute/AttributePopupMenu.java +++ b/freeplane/src/org/freeplane/view/swing/map/attribute/AttributePopupMenu.java @@ -1,271 +1,273 @@ /* * Freeplane - mind map editor * Copyright (C) 2008 Dimitry Polivaev * * This file author is Dimitry Polivaev * * 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, see <http://www.gnu.org/licenses/>. */ package org.freeplane.view.swing.map.attribute; import java.awt.Component; import java.awt.EventQueue; import java.awt.KeyboardFocusManager; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.SwingUtilities; import javax.swing.table.JTableHeader; import org.freeplane.core.resources.ResourceBundles; import org.freeplane.features.common.attribute.AttributeTableLayoutModel; import org.freeplane.features.common.attribute.IAttributeTableModel; /** * @author Dimitry Polivaev */ class AttributePopupMenu extends JPopupMenu implements MouseListener { /** * */ private static final long serialVersionUID = 1L; private JMenuItem delete = null; private JMenuItem down = null; private JMenuItem insert = null; private boolean oldTable; private JMenuItem optimalWidth = null; private int row; private AttributeTable table; private JMenuItem up = null; @Override protected void firePopupMenuWillBecomeInvisible() { if (row != -1) { table.removeRowSelectionInterval(row, row); } oldTable = true; EventQueue.invokeLater(new Runnable() { public void run() { if (!oldTable) { return; } final KeyboardFocusManager focusManager = java.awt.KeyboardFocusManager .getCurrentKeyboardFocusManager(); final Component focusOwner = SwingUtilities.getAncestorOfClass(AttributeTable.class, focusManager .getFocusOwner()); if (table != focusOwner && focusOwner instanceof JComponent) { table.requestFocus(true); ((JComponent) focusOwner).requestFocus(); } table = null; } }); } @Override protected void firePopupMenuWillBecomeVisible() { super.firePopupMenuWillBecomeVisible(); if (row != -1) { table.addRowSelectionInterval(row, row); } } /** * @return Returns the delete. */ private JMenuItem getDelete() { if (delete == null) { delete = new JMenuItem(ResourceBundles.getText("attributes_popup_delete")); delete.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { table.removeRow(row); } }); } return delete; } /** * @return Returns the down. */ private JMenuItem getDown() { if (down == null) { down = new JMenuItem(ResourceBundles.getText("attributes_popup_down")); down.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { table.moveRowDown(row); } }); } return down; } /** * @return Returns the insert. */ private JMenuItem getInsert() { if (insert == null) { insert = new JMenuItem(ResourceBundles.getText("attributes_popup_new")); insert.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { table.insertRow(row + 1); } }); } return insert; } /** * @return Returns the optimalWidth. */ private JMenuItem getOptimalWidth() { if (optimalWidth == null) { optimalWidth = new JMenuItem(ResourceBundles.getText("attributes_popup_optimal_width")); optimalWidth.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { table.setOptimalColumnWidths(); } }); } return optimalWidth; } public AttributeTable getTable() { return table; } /** * @return Returns the up. */ private JMenuItem getUp() { if (up == null) { up = new JMenuItem(ResourceBundles.getText("attributes_popup_up")); up.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { table.moveRowUp(row); } }); } return up; } /** * */ private void make() { final String attributeViewType = table.getAttributeView().getViewType(); final IAttributeTableModel model = table.getAttributeTableModel(); final int rowCount = model.getRowCount(); if (attributeViewType.equals(AttributeTableLayoutModel.SHOW_ALL)) { if (rowCount != 0) { add(getOptimalWidth()); } add(getInsert()); if (row != -1) { add(getDelete()); if (row != 0) { add(getUp()); } if (row != rowCount - 1) { add(getDown()); } } } else { if (rowCount != 0) { add(getOptimalWidth()); } } } private void maybeShowPopup(final MouseEvent e) { if (e.isPopupTrigger()) { selectTable(e.getComponent(), e.getPoint()); if(table.isEditing()){ return; } table.requestFocus(); make(); show(e.getComponent(), e.getX(), e.getY()); } } /* * (non-Javadoc) * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent) */ public void mouseClicked(final MouseEvent e) { } /* * (non-Javadoc) * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent) */ public void mouseEntered(final MouseEvent e) { } /* * (non-Javadoc) * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent) */ public void mouseExited(final MouseEvent e) { } public void mousePressed(final MouseEvent e) { maybeShowPopup(e); } public void mouseReleased(final MouseEvent e) { maybeShowPopup(e); } private void selectTable(final Component component, final Point point) throws AssertionError { final int componentCount = getComponentCount(); for (int i = componentCount; i > 0;) { remove(--i); } if (component instanceof AttributeTable) { table = (AttributeTable) component; if(table.isEditing()){ return; } oldTable = false; row = table.rowAtPoint(point); - if (table.getValueAt(row, 0).equals("")) { - row--; + if(row >= 0){ + if (table.getValueAt(row, 0).equals("")) { + row--; + } } if(row >= 0){ table.changeSelection(row, table.columnAtPoint(point), false, false); } return; } if (component instanceof JTableHeader) { final JTableHeader header = (JTableHeader) component; table = (AttributeTable) header.getTable(); if(table.isEditing()){ return; } oldTable = false; row = -1; return; } throw new AssertionError(); } }
true
true
private void selectTable(final Component component, final Point point) throws AssertionError { final int componentCount = getComponentCount(); for (int i = componentCount; i > 0;) { remove(--i); } if (component instanceof AttributeTable) { table = (AttributeTable) component; if(table.isEditing()){ return; } oldTable = false; row = table.rowAtPoint(point); if (table.getValueAt(row, 0).equals("")) { row--; } if(row >= 0){ table.changeSelection(row, table.columnAtPoint(point), false, false); } return; } if (component instanceof JTableHeader) { final JTableHeader header = (JTableHeader) component; table = (AttributeTable) header.getTable(); if(table.isEditing()){ return; } oldTable = false; row = -1; return; } throw new AssertionError(); }
private void selectTable(final Component component, final Point point) throws AssertionError { final int componentCount = getComponentCount(); for (int i = componentCount; i > 0;) { remove(--i); } if (component instanceof AttributeTable) { table = (AttributeTable) component; if(table.isEditing()){ return; } oldTable = false; row = table.rowAtPoint(point); if(row >= 0){ if (table.getValueAt(row, 0).equals("")) { row--; } } if(row >= 0){ table.changeSelection(row, table.columnAtPoint(point), false, false); } return; } if (component instanceof JTableHeader) { final JTableHeader header = (JTableHeader) component; table = (AttributeTable) header.getTable(); if(table.isEditing()){ return; } oldTable = false; row = -1; return; } throw new AssertionError(); }
diff --git a/src/main/java/net/floodlightcontroller/devicemanager/web/DeviceSerializer.java b/src/main/java/net/floodlightcontroller/devicemanager/web/DeviceSerializer.java index 4e4e07db..e946d7b8 100644 --- a/src/main/java/net/floodlightcontroller/devicemanager/web/DeviceSerializer.java +++ b/src/main/java/net/floodlightcontroller/devicemanager/web/DeviceSerializer.java @@ -1,72 +1,75 @@ /** * Copyright 2012 Big Switch Networks, Inc. * Originally created by David Erickson, Stanford University * * 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 net.floodlightcontroller.devicemanager.web; import java.io.IOException; import net.floodlightcontroller.devicemanager.SwitchPort; import net.floodlightcontroller.devicemanager.internal.Device; import net.floodlightcontroller.packet.IPv4; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.JsonSerializer; import org.codehaus.jackson.map.SerializerProvider; import org.openflow.util.HexString; /** * Serialize a device object */ public class DeviceSerializer extends JsonSerializer<Device> { @Override public void serialize(Device device, JsonGenerator jGen, SerializerProvider serializer) throws IOException, JsonProcessingException { jGen.writeStartObject(); jGen.writeStringField("entityClass", device.getEntityClass().getName()); jGen.writeArrayFieldStart("mac"); jGen.writeString(HexString.toHexString(device.getMACAddress(), 6)); jGen.writeEndArray(); jGen.writeArrayFieldStart("ipv4"); for (Integer ip : device.getIPv4Addresses()) jGen.writeString(IPv4.fromIPv4Address(ip)); jGen.writeEndArray(); jGen.writeArrayFieldStart("vlan"); for (Short vlan : device.getVlanId()) if (vlan >= 0) jGen.writeNumber(vlan); jGen.writeEndArray(); jGen.writeArrayFieldStart("attachmentPoint"); for (SwitchPort ap : device.getAttachmentPoints(true)) { serializer.defaultSerializeValue(ap, jGen); } jGen.writeEndArray(); jGen.writeNumberField("lastSeen", device.getLastSeen().getTime()); - jGen.writeStringField("dhcpClientName", device.getDHCPClientName()); + String dhcpClientName = device.getDHCPClientName(); + if (dhcpClientName != null) { + jGen.writeStringField("dhcpClientName", dhcpClientName); + } jGen.writeEndObject(); } }
true
true
public void serialize(Device device, JsonGenerator jGen, SerializerProvider serializer) throws IOException, JsonProcessingException { jGen.writeStartObject(); jGen.writeStringField("entityClass", device.getEntityClass().getName()); jGen.writeArrayFieldStart("mac"); jGen.writeString(HexString.toHexString(device.getMACAddress(), 6)); jGen.writeEndArray(); jGen.writeArrayFieldStart("ipv4"); for (Integer ip : device.getIPv4Addresses()) jGen.writeString(IPv4.fromIPv4Address(ip)); jGen.writeEndArray(); jGen.writeArrayFieldStart("vlan"); for (Short vlan : device.getVlanId()) if (vlan >= 0) jGen.writeNumber(vlan); jGen.writeEndArray(); jGen.writeArrayFieldStart("attachmentPoint"); for (SwitchPort ap : device.getAttachmentPoints(true)) { serializer.defaultSerializeValue(ap, jGen); } jGen.writeEndArray(); jGen.writeNumberField("lastSeen", device.getLastSeen().getTime()); jGen.writeStringField("dhcpClientName", device.getDHCPClientName()); jGen.writeEndObject(); }
public void serialize(Device device, JsonGenerator jGen, SerializerProvider serializer) throws IOException, JsonProcessingException { jGen.writeStartObject(); jGen.writeStringField("entityClass", device.getEntityClass().getName()); jGen.writeArrayFieldStart("mac"); jGen.writeString(HexString.toHexString(device.getMACAddress(), 6)); jGen.writeEndArray(); jGen.writeArrayFieldStart("ipv4"); for (Integer ip : device.getIPv4Addresses()) jGen.writeString(IPv4.fromIPv4Address(ip)); jGen.writeEndArray(); jGen.writeArrayFieldStart("vlan"); for (Short vlan : device.getVlanId()) if (vlan >= 0) jGen.writeNumber(vlan); jGen.writeEndArray(); jGen.writeArrayFieldStart("attachmentPoint"); for (SwitchPort ap : device.getAttachmentPoints(true)) { serializer.defaultSerializeValue(ap, jGen); } jGen.writeEndArray(); jGen.writeNumberField("lastSeen", device.getLastSeen().getTime()); String dhcpClientName = device.getDHCPClientName(); if (dhcpClientName != null) { jGen.writeStringField("dhcpClientName", dhcpClientName); } jGen.writeEndObject(); }
diff --git a/RutubeAPI/src/ru/rutube/RutubeAPI/RutubeApp.java b/RutubeAPI/src/ru/rutube/RutubeAPI/RutubeApp.java index f68c84f..a9f020b 100644 --- a/RutubeAPI/src/ru/rutube/RutubeAPI/RutubeApp.java +++ b/RutubeAPI/src/ru/rutube/RutubeAPI/RutubeApp.java @@ -1,178 +1,180 @@ package ru.rutube.RutubeAPI; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import com.android.volley.RequestQueue; import com.android.volley.toolbox.ImageLoader; import java.text.SimpleDateFormat; import java.util.Date; import ru.rutube.RutubeAPI.tools.MemDiskBitmapCache; /** * Created by tumbler on 22.06.13. */ public class RutubeApp extends Application { private static ImageLoader.ImageCache sBitmapCache; protected static final SimpleDateFormat reprDateFormat = new SimpleDateFormat("d MMMM y"); private static RutubeApp instance; private RequestQueue requestQueue; private volatile boolean mLoadingFeed; public RutubeApp() { instance = this; mLoadingFeed = false; } public static RutubeApp getInstance() { if (instance == null) instance = new RutubeApp(); return instance; } public static Context getContext() { if (instance != null) { return instance.getApplicationContext(); } return null; } public RequestQueue getRequestQueue() { return requestQueue; } public void setRequestQueue(RequestQueue requestQueue) { this.requestQueue = requestQueue; } public boolean isOnline() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); return networkInfo != null; } @Override public void onCreate() { super.onCreate(); } /** * вызывается при действиях, * - повороты экрана * - открытие/закрытие клавиатуры * - изменение настроек приложения и тд * @param newConfig */ @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } /** * вызывается при очистке памяти (кэша, ресурсов объектов в памяти и тд) */ @Override public void onLowMemory() { super.onLowMemory(); } /** * вызывается при преждевременном завершении работы приложения * (именно приложения, а не коммандой "ядра") */ @Override public void onTerminate() { super.onTerminate(); } public static ImageLoader.ImageCache getBitmapCache() { if (sBitmapCache != null) return sBitmapCache; Context context = instance.getApplicationContext(); assert context != null; sBitmapCache = new MemDiskBitmapCache(getContext().getExternalCacheDir()); return sBitmapCache; } public static String getUrl(int stringId) { Uri baseUri = Uri.parse(getContext().getString(R.string.base_uri)); Uri resultUri = baseUri.buildUpon() .appendEncodedPath(getContext().getString(stringId)) .build(); assert resultUri != null; return resultUri.toString(); } public static Uri getFeedUri(int stringId, int param) { Uri baseUri = Uri.parse(getContext().getString(R.string.base_uri)); String path = getContext().getString(stringId).replace("api/", ""); return baseUri.buildUpon() .appendEncodedPath(String.format(path, param)) .build(); } public void openFeed(Uri feedUri, Context context) { if (feedUri == null) throw new IllegalArgumentException("Can't open feeed"); Intent intent = new Intent("ru.rutube.feed.open"); intent.setData(feedUri); context.startActivity(intent); } public static String getUrl(String path) { assert getContext() != null; Uri baseUri = Uri.parse(getContext().getString(R.string.base_uri)); Uri resultUri = baseUri.buildUpon() .appendEncodedPath(path) .build(); assert resultUri != null; return resultUri.toString(); } public static boolean isLoadingFeed() { return instance.mLoadingFeed; } public static void startLoading() { instance.mLoadingFeed = true; } public static void stopLoading() { instance.mLoadingFeed = false; } public String getCreatedText(Date created) { + if (created == null) + return null; Date now = new Date(); long seconds = (now.getTime() - created.getTime()) / 1000; if (seconds < 3600) return getResources().getString(R.string.now); if (seconds < 24 * 3600) return getResources().getString(R.string.today); if (seconds < 2 * 24 * 3600) return getResources().getString(R.string.yesterday); if (seconds < 5 * 24 * 3600) return String.format(getResources().getString(R.string.days_ago_24, seconds / (24 * 3600))); if (seconds < 7 * 24 * 3600) return String.format(getResources().getString(R.string.days_ago_59, seconds / (24 * 3600))); if (seconds < 14 * 24 * 3600) return String.format(getResources().getString(R.string.week_ago, seconds / (7 * 24 * 3600))); if (seconds < 31 * 24 * 3600) return String.format(getResources().getString(R.string.weeks_ago, seconds / (7 * 24 * 3600))); return reprDateFormat.format(created); } }
true
true
public String getCreatedText(Date created) { Date now = new Date(); long seconds = (now.getTime() - created.getTime()) / 1000; if (seconds < 3600) return getResources().getString(R.string.now); if (seconds < 24 * 3600) return getResources().getString(R.string.today); if (seconds < 2 * 24 * 3600) return getResources().getString(R.string.yesterday); if (seconds < 5 * 24 * 3600) return String.format(getResources().getString(R.string.days_ago_24, seconds / (24 * 3600))); if (seconds < 7 * 24 * 3600) return String.format(getResources().getString(R.string.days_ago_59, seconds / (24 * 3600))); if (seconds < 14 * 24 * 3600) return String.format(getResources().getString(R.string.week_ago, seconds / (7 * 24 * 3600))); if (seconds < 31 * 24 * 3600) return String.format(getResources().getString(R.string.weeks_ago, seconds / (7 * 24 * 3600))); return reprDateFormat.format(created); }
public String getCreatedText(Date created) { if (created == null) return null; Date now = new Date(); long seconds = (now.getTime() - created.getTime()) / 1000; if (seconds < 3600) return getResources().getString(R.string.now); if (seconds < 24 * 3600) return getResources().getString(R.string.today); if (seconds < 2 * 24 * 3600) return getResources().getString(R.string.yesterday); if (seconds < 5 * 24 * 3600) return String.format(getResources().getString(R.string.days_ago_24, seconds / (24 * 3600))); if (seconds < 7 * 24 * 3600) return String.format(getResources().getString(R.string.days_ago_59, seconds / (24 * 3600))); if (seconds < 14 * 24 * 3600) return String.format(getResources().getString(R.string.week_ago, seconds / (7 * 24 * 3600))); if (seconds < 31 * 24 * 3600) return String.format(getResources().getString(R.string.weeks_ago, seconds / (7 * 24 * 3600))); return reprDateFormat.format(created); }
diff --git a/impl/src/main/java/org/jboss/weld/bootstrap/events/SimpleAnnotationDiscovery.java b/impl/src/main/java/org/jboss/weld/bootstrap/events/SimpleAnnotationDiscovery.java index 717e6d842..bfb3c6ca6 100644 --- a/impl/src/main/java/org/jboss/weld/bootstrap/events/SimpleAnnotationDiscovery.java +++ b/impl/src/main/java/org/jboss/weld/bootstrap/events/SimpleAnnotationDiscovery.java @@ -1,99 +1,99 @@ /* * JBoss, Home of Professional Open Source * Copyright 2012, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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 org.jboss.weld.bootstrap.events; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collection; import org.jboss.weld.resources.ReflectionCache; public class SimpleAnnotationDiscovery implements AnnotationDiscovery { private final ReflectionCache cache; public SimpleAnnotationDiscovery(ReflectionCache cache) { this.cache = cache; } @Override public boolean containsAnnotations(Class<?> javaClass, Collection<Class<? extends Annotation>> requiredAnnotations) { for (Class<?> clazz = javaClass; clazz != null && clazz != Object.class; clazz = clazz.getSuperclass()) { // class level annotations - if (containsAnnotations(cache.getAnnotations(javaClass), requiredAnnotations)) { + if (containsAnnotations(cache.getAnnotations(clazz), requiredAnnotations)) { return true; } // fields - for (Field field : javaClass.getDeclaredFields()) { + for (Field field : clazz.getDeclaredFields()) { if (containsAnnotations(cache.getAnnotations(field), requiredAnnotations)) { return true; } } // constructors - for (Constructor<?> constructor : javaClass.getConstructors()) { + for (Constructor<?> constructor : clazz.getConstructors()) { if (containsAnnotations(cache.getAnnotations(constructor), requiredAnnotations)) { return true; } for (Annotation[] parameterAnnotations : constructor.getParameterAnnotations()) { if (containsAnnotations(parameterAnnotations, requiredAnnotations)) { return true; } } } // methods - for (Method method : javaClass.getMethods()) { + for (Method method : clazz.getDeclaredMethods()) { if (containsAnnotations(cache.getAnnotations(method), requiredAnnotations)) { return true; } for (Annotation[] parameterAnnotations : method.getParameterAnnotations()) { if (containsAnnotations(parameterAnnotations, requiredAnnotations)) { return true; } } } } return false; } private boolean containsAnnotations(Annotation[] annotations, Collection<Class<? extends Annotation>> requiredAnnotations) { return containsAnnotations(annotations, requiredAnnotations, true); } private boolean containsAnnotations(Annotation[] annotations, Collection<Class<? extends Annotation>> requiredAnnotations, boolean checkMetaAnnotations) { for (Class<? extends Annotation> requiredAnnotation : requiredAnnotations) { for (Annotation annotation : annotations) { Class<? extends Annotation> annotationType = annotation.annotationType(); if (requiredAnnotation.equals(annotationType)) { return true; } if (checkMetaAnnotations && containsAnnotations(cache.getAnnotations(annotationType), requiredAnnotations, false)) { return true; } } } return false; } @Override public void cleanup() { } }
false
true
public boolean containsAnnotations(Class<?> javaClass, Collection<Class<? extends Annotation>> requiredAnnotations) { for (Class<?> clazz = javaClass; clazz != null && clazz != Object.class; clazz = clazz.getSuperclass()) { // class level annotations if (containsAnnotations(cache.getAnnotations(javaClass), requiredAnnotations)) { return true; } // fields for (Field field : javaClass.getDeclaredFields()) { if (containsAnnotations(cache.getAnnotations(field), requiredAnnotations)) { return true; } } // constructors for (Constructor<?> constructor : javaClass.getConstructors()) { if (containsAnnotations(cache.getAnnotations(constructor), requiredAnnotations)) { return true; } for (Annotation[] parameterAnnotations : constructor.getParameterAnnotations()) { if (containsAnnotations(parameterAnnotations, requiredAnnotations)) { return true; } } } // methods for (Method method : javaClass.getMethods()) { if (containsAnnotations(cache.getAnnotations(method), requiredAnnotations)) { return true; } for (Annotation[] parameterAnnotations : method.getParameterAnnotations()) { if (containsAnnotations(parameterAnnotations, requiredAnnotations)) { return true; } } } } return false; }
public boolean containsAnnotations(Class<?> javaClass, Collection<Class<? extends Annotation>> requiredAnnotations) { for (Class<?> clazz = javaClass; clazz != null && clazz != Object.class; clazz = clazz.getSuperclass()) { // class level annotations if (containsAnnotations(cache.getAnnotations(clazz), requiredAnnotations)) { return true; } // fields for (Field field : clazz.getDeclaredFields()) { if (containsAnnotations(cache.getAnnotations(field), requiredAnnotations)) { return true; } } // constructors for (Constructor<?> constructor : clazz.getConstructors()) { if (containsAnnotations(cache.getAnnotations(constructor), requiredAnnotations)) { return true; } for (Annotation[] parameterAnnotations : constructor.getParameterAnnotations()) { if (containsAnnotations(parameterAnnotations, requiredAnnotations)) { return true; } } } // methods for (Method method : clazz.getDeclaredMethods()) { if (containsAnnotations(cache.getAnnotations(method), requiredAnnotations)) { return true; } for (Annotation[] parameterAnnotations : method.getParameterAnnotations()) { if (containsAnnotations(parameterAnnotations, requiredAnnotations)) { return true; } } } } return false; }
diff --git a/bukkit/src/test/java/com/mvplugin/mockbukkit/MockWorld.java b/bukkit/src/test/java/com/mvplugin/mockbukkit/MockWorld.java index cac749e..8fb3e6e 100644 --- a/bukkit/src/test/java/com/mvplugin/mockbukkit/MockWorld.java +++ b/bukkit/src/test/java/com/mvplugin/mockbukkit/MockWorld.java @@ -1,757 +1,761 @@ package com.mvplugin.mockbukkit; import com.mvplugin.core.FileLocations; import org.bukkit.BlockChangeDelegate; import org.bukkit.Chunk; import org.bukkit.ChunkSnapshot; import org.bukkit.Difficulty; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.TreeType; import org.bukkit.World; import org.bukkit.WorldCreator; import org.bukkit.WorldType; import org.bukkit.block.Biome; import org.bukkit.block.Block; import org.bukkit.entity.Arrow; import org.bukkit.entity.CreatureType; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.FallingBlock; import org.bukkit.entity.Item; import org.bukkit.entity.LightningStrike; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.ChunkGenerator; import org.bukkit.inventory.ItemStack; import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.Plugin; import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import pluginbase.bukkit.config.BukkitConfiguration; import pluginbase.bukkit.config.YamlConfiguration; import pluginbase.config.SerializationRegistrar; import pluginbase.config.annotation.SerializeWith; import pluginbase.config.serializers.Serializer; import java.io.File; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; public class MockWorld implements World { static { SerializationRegistrar.registerClass(MockWorld.class); SerializationRegistrar.registerClass(Location.class); SerializationRegistrar.registerClass(UUID.class); } String name; @SerializeWith(UUIDSerializer.class) UUID uuid; WorldType type = WorldType.NORMAL; Environment environment; long seed = 0L; transient long time = 0L; boolean pvp = true; boolean keepSpawnInMemory = true; Difficulty difficulty = Difficulty.EASY; @SerializeWith(LocationSerializer.class) Location spawn = new Location(this, 0, 0, 0, 0, 0); transient File folder; transient File datFile; private MockWorld() { } public MockWorld(WorldCreator creator) { this.name = creator.name(); this.environment = creator.environment(); + this.type = creator.type(); + this.seed = creator.seed(); + this.uuid = UUID.nameUUIDFromBytes(name.getBytes()); folder = new File(FileLocations.WORLDS_DIRECTORY, name); datFile = new File(folder, "level.dat"); if (!datFile.exists()) { - this.type = creator.type(); - this.seed = creator.seed(); - uuid = UUID.nameUUIDFromBytes(name.getBytes()); save(); } else { try { YamlConfiguration config = BukkitConfiguration.loadYamlConfig(datFile); MockWorld world = (MockWorld) config.get(name); - this.type = world.type; - this.seed = world.seed; - this.uuid = world.uuid; - this.environment = world.environment; - this.spawn = world.spawn; - this.difficulty = world.difficulty; - this.pvp = world.pvp; - this.keepSpawnInMemory = world.keepSpawnInMemory; + if (world != null) { + this.type = world.type; + this.seed = world.seed; + this.uuid = world.uuid; + this.environment = world.environment; + this.spawn = world.spawn; + this.difficulty = world.difficulty; + this.pvp = world.pvp; + this.keepSpawnInMemory = world.keepSpawnInMemory; + } else { + save(); + } } catch (Exception e) { e.printStackTrace(); } } } private void load() { } @Override public Block getBlockAt(int i, int i2, int i3) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public Block getBlockAt(Location location) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public int getBlockTypeIdAt(int i, int i2, int i3) { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public int getBlockTypeIdAt(Location location) { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public int getHighestBlockYAt(int i, int i2) { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public int getHighestBlockYAt(Location location) { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public Block getHighestBlockAt(int i, int i2) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public Block getHighestBlockAt(Location location) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public Chunk getChunkAt(int i, int i2) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public Chunk getChunkAt(Location location) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public Chunk getChunkAt(Block block) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isChunkLoaded(Chunk chunk) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public Chunk[] getLoadedChunks() { return new Chunk[0]; //To change body of implemented methods use File | Settings | File Templates. } @Override public void loadChunk(Chunk chunk) { //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isChunkLoaded(int i, int i2) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isChunkInUse(int i, int i2) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public void loadChunk(int i, int i2) { //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean loadChunk(int i, int i2, boolean b) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean unloadChunk(Chunk chunk) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean unloadChunk(int i, int i2) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean unloadChunk(int i, int i2, boolean b) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean unloadChunk(int i, int i2, boolean b, boolean b2) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean unloadChunkRequest(int i, int i2) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean unloadChunkRequest(int i, int i2, boolean b) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean regenerateChunk(int i, int i2) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean refreshChunk(int i, int i2) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public Item dropItem(Location location, ItemStack itemStack) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public Item dropItemNaturally(Location location, ItemStack itemStack) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public Arrow spawnArrow(Location location, Vector vector, float v, float v2) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean generateTree(Location location, TreeType treeType) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean generateTree(Location location, TreeType treeType, BlockChangeDelegate blockChangeDelegate) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public Entity spawnEntity(Location location, EntityType entityType) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public LivingEntity spawnCreature(Location location, EntityType entityType) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public LivingEntity spawnCreature(Location location, CreatureType creatureType) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public LightningStrike strikeLightning(Location location) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public LightningStrike strikeLightningEffect(Location location) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public List<Entity> getEntities() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public List<LivingEntity> getLivingEntities() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public <T extends Entity> Collection<T> getEntitiesByClass(Class<T>... classes) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public <T extends Entity> Collection<T> getEntitiesByClass(Class<T> tClass) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public Collection<Entity> getEntitiesByClasses(Class<?>... classes) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public List<Player> getPlayers() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getName() { return name; } @Override public UUID getUID() { return uuid; } @Override public Location getSpawnLocation() { return spawn; } @Override public boolean setSpawnLocation(int x, int y, int z) { spawn = new Location(this, x, y, z); return true; } @Override public long getTime() { return time; } @Override public void setTime(long l) { this.time = l; } @Override public long getFullTime() { return time; } @Override public void setFullTime(long l) { time = l; } @Override public boolean hasStorm() { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public void setStorm(boolean b) { //To change body of implemented methods use File | Settings | File Templates. } @Override public int getWeatherDuration() { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public void setWeatherDuration(int i) { //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isThundering() { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public void setThundering(boolean b) { //To change body of implemented methods use File | Settings | File Templates. } @Override public int getThunderDuration() { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public void setThunderDuration(int i) { //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean createExplosion(double v, double v2, double v3, float v4) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean createExplosion(double v, double v2, double v3, float v4, boolean b) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean createExplosion(double v, double v2, double v3, float v4, boolean b, boolean b2) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean createExplosion(Location location, float v) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean createExplosion(Location location, float v, boolean b) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public Environment getEnvironment() { return environment; } @Override public long getSeed() { return seed; } @Override public boolean getPVP() { return pvp; } @Override public void setPVP(boolean b) { this.pvp = b; } @Override public ChunkGenerator getGenerator() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public void save() { try { if (!datFile.exists()) { folder.mkdirs(); datFile.createNewFile(); } YamlConfiguration config = new YamlConfiguration(); config.set(name, this); config.save(datFile); } catch (Exception e) { e.printStackTrace(); } } @Override public List<BlockPopulator> getPopulators() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public <T extends Entity> T spawn(Location location, Class<T> tClass) throws IllegalArgumentException { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public FallingBlock spawnFallingBlock(Location location, Material material, byte b) throws IllegalArgumentException { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public FallingBlock spawnFallingBlock(Location location, int i, byte b) throws IllegalArgumentException { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public void playEffect(Location location, Effect effect, int i) { //To change body of implemented methods use File | Settings | File Templates. } @Override public void playEffect(Location location, Effect effect, int i, int i2) { //To change body of implemented methods use File | Settings | File Templates. } @Override public <T> void playEffect(Location location, Effect effect, T t) { //To change body of implemented methods use File | Settings | File Templates. } @Override public <T> void playEffect(Location location, Effect effect, T t, int i) { //To change body of implemented methods use File | Settings | File Templates. } @Override public ChunkSnapshot getEmptyChunkSnapshot(int i, int i2, boolean b, boolean b2) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public void setSpawnFlags(boolean b, boolean b2) { //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean getAllowAnimals() { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean getAllowMonsters() { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public Biome getBiome(int i, int i2) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public void setBiome(int i, int i2, Biome biome) { //To change body of implemented methods use File | Settings | File Templates. } @Override public double getTemperature(int i, int i2) { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public double getHumidity(int i, int i2) { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public int getMaxHeight() { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public int getSeaLevel() { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean getKeepSpawnInMemory() { return keepSpawnInMemory; } @Override public void setKeepSpawnInMemory(boolean b) { keepSpawnInMemory = b; } @Override public boolean isAutoSave() { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public void setAutoSave(boolean b) { //To change body of implemented methods use File | Settings | File Templates. } @Override public void setDifficulty(Difficulty difficulty) { this.difficulty = difficulty; } @Override public Difficulty getDifficulty() { return difficulty; } @Override public File getWorldFolder() { return folder; } @Override public WorldType getWorldType() { return type; } @Override public boolean canGenerateStructures() { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public long getTicksPerAnimalSpawns() { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public void setTicksPerAnimalSpawns(int i) { //To change body of implemented methods use File | Settings | File Templates. } @Override public long getTicksPerMonsterSpawns() { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public void setTicksPerMonsterSpawns(int i) { //To change body of implemented methods use File | Settings | File Templates. } @Override public int getMonsterSpawnLimit() { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public void setMonsterSpawnLimit(int i) { //To change body of implemented methods use File | Settings | File Templates. } @Override public int getAnimalSpawnLimit() { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public void setAnimalSpawnLimit(int i) { //To change body of implemented methods use File | Settings | File Templates. } @Override public int getWaterAnimalSpawnLimit() { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public void setWaterAnimalSpawnLimit(int i) { //To change body of implemented methods use File | Settings | File Templates. } @Override public int getAmbientSpawnLimit() { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public void setAmbientSpawnLimit(int i) { //To change body of implemented methods use File | Settings | File Templates. } @Override public void playSound(Location location, Sound sound, float v, float v2) { //To change body of implemented methods use File | Settings | File Templates. } @Override public String[] getGameRules() { return new String[0]; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getGameRuleValue(String s) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean setGameRuleValue(String s, String s2) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isGameRule(String s) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public void setMetadata(String s, MetadataValue metadataValue) { //To change body of implemented methods use File | Settings | File Templates. } @Override public List<MetadataValue> getMetadata(String s) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean hasMetadata(String s) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public void removeMetadata(String s, Plugin plugin) { //To change body of implemented methods use File | Settings | File Templates. } @Override public void sendPluginMessage(Plugin plugin, String s, byte[] bytes) { //To change body of implemented methods use File | Settings | File Templates. } @Override public Set<String> getListeningPluginChannels() { return null; //To change body of implemented methods use File | Settings | File Templates. } private static class UUIDSerializer implements Serializer<UUID> { @Nullable @Override public Object serialize(@Nullable UUID uuid) { return uuid != null ? uuid.toString() : null; } @Nullable @Override public UUID deserialize(@Nullable Object o, @NotNull Class<UUID> uuidClass) throws IllegalArgumentException { return o != null ? UUID.fromString(o.toString()) : null; } } private static class LocationSerializer implements Serializer<Location> { @Nullable @Override public Object serialize(@Nullable Location l) { if (l == null) { return null; } Map<String, Object> map = new HashMap<String, Object>(3); map.put("x", l.getX()); map.put("y", l.getY()); map.put("z", l.getZ()); return map; } @Nullable @Override public Location deserialize(@Nullable Object serialized, @NotNull Class<Location> wantedType) throws IllegalArgumentException { if (serialized == null || !(serialized instanceof Map)) { return null; } Map map = (Map) serialized; double x = 0, y = 0, z = 0; try { x = Double.valueOf(map.get("x").toString()); y = Double.valueOf(map.get("y").toString()); z = Double.valueOf(map.get("z").toString()); } catch (Exception ignore) { } return new Location(null, x, y, z); } } }
false
true
public MockWorld(WorldCreator creator) { this.name = creator.name(); this.environment = creator.environment(); folder = new File(FileLocations.WORLDS_DIRECTORY, name); datFile = new File(folder, "level.dat"); if (!datFile.exists()) { this.type = creator.type(); this.seed = creator.seed(); uuid = UUID.nameUUIDFromBytes(name.getBytes()); save(); } else { try { YamlConfiguration config = BukkitConfiguration.loadYamlConfig(datFile); MockWorld world = (MockWorld) config.get(name); this.type = world.type; this.seed = world.seed; this.uuid = world.uuid; this.environment = world.environment; this.spawn = world.spawn; this.difficulty = world.difficulty; this.pvp = world.pvp; this.keepSpawnInMemory = world.keepSpawnInMemory; } catch (Exception e) { e.printStackTrace(); } } }
public MockWorld(WorldCreator creator) { this.name = creator.name(); this.environment = creator.environment(); this.type = creator.type(); this.seed = creator.seed(); this.uuid = UUID.nameUUIDFromBytes(name.getBytes()); folder = new File(FileLocations.WORLDS_DIRECTORY, name); datFile = new File(folder, "level.dat"); if (!datFile.exists()) { save(); } else { try { YamlConfiguration config = BukkitConfiguration.loadYamlConfig(datFile); MockWorld world = (MockWorld) config.get(name); if (world != null) { this.type = world.type; this.seed = world.seed; this.uuid = world.uuid; this.environment = world.environment; this.spawn = world.spawn; this.difficulty = world.difficulty; this.pvp = world.pvp; this.keepSpawnInMemory = world.keepSpawnInMemory; } else { save(); } } catch (Exception e) { e.printStackTrace(); } } }
diff --git a/modules/rampart-samples/basic/sample09/src/org/apache/rampart/samples/sample09/PWCBHandler.java b/modules/rampart-samples/basic/sample09/src/org/apache/rampart/samples/sample09/PWCBHandler.java index 92adde4e2..b1911f767 100644 --- a/modules/rampart-samples/basic/sample09/src/org/apache/rampart/samples/sample09/PWCBHandler.java +++ b/modules/rampart-samples/basic/sample09/src/org/apache/rampart/samples/sample09/PWCBHandler.java @@ -1,50 +1,50 @@ /* * Copyright 2004,2005 The Apache Software Foundation. * * 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 org.apache.rampart.samples.sample09; import org.apache.ws.security.WSPasswordCallback; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.UnsupportedCallbackException; import java.io.IOException; public class PWCBHandler implements CallbackHandler { private static final byte[] key = { (byte) 0x31, (byte) 0xfd, (byte) 0xcb, (byte) 0xda, (byte) 0xfb, (byte) 0xcd, (byte) 0x6b, (byte) 0xa8, (byte) 0xe6, (byte) 0x19, (byte) 0xa7, (byte) 0xbf, (byte) 0x51, (byte) 0xf7, (byte) 0xc7, (byte) 0x3e }; public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { WSPasswordCallback pwcb = (WSPasswordCallback) callbacks[i]; - if (pwcb.getUsage() == WSPasswordCallback.KEY_NAME) { + if (pwcb.getUsage() == WSPasswordCallback.SECRET_KEY) { pwcb.setKey(key); } } } }
true
true
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { WSPasswordCallback pwcb = (WSPasswordCallback) callbacks[i]; if (pwcb.getUsage() == WSPasswordCallback.KEY_NAME) { pwcb.setKey(key); } } }
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { WSPasswordCallback pwcb = (WSPasswordCallback) callbacks[i]; if (pwcb.getUsage() == WSPasswordCallback.SECRET_KEY) { pwcb.setKey(key); } } }
diff --git a/wicket-rest-api/src/main/java/org/innobuilt/wicket/rest/JsonWebServicePage.java b/wicket-rest-api/src/main/java/org/innobuilt/wicket/rest/JsonWebServicePage.java index 5c5ef98..1713a38 100644 --- a/wicket-rest-api/src/main/java/org/innobuilt/wicket/rest/JsonWebServicePage.java +++ b/wicket-rest-api/src/main/java/org/innobuilt/wicket/rest/JsonWebServicePage.java @@ -1,87 +1,88 @@ package org.innobuilt.wicket.rest; import java.io.*; import org.apache.wicket.PageParameters; import org.apache.wicket.markup.MarkupStream; import org.apache.wicket.model.Model; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public abstract class JsonWebServicePage extends AbstractWebServicePage { private transient GsonBuilder builder; private Class clazz; public Class getClazz() { return clazz; } public void setClazz(Class clazz) { this.clazz = clazz; } public JsonWebServicePage(PageParameters params) { super(params); builder = new GsonBuilder(); } /** * Call this constructor from subclass if you plan to receive json in PUT or POST. * * @param params * @param clazz - The class type you want returned by getModelObject(). */ public JsonWebServicePage(PageParameters params, Class clazz) { this(params); //TODO override doPut and doPost if clazz is not set, throw an exception this.clazz = clazz; } protected final void onRender(MarkupStream markupStream) { if (!isAuthorized()) { return; } + getResponse().setContentType( "application/json; charset=UTF-8" ); Writer pw = null; try { pw = new OutputStreamWriter(getResponse().getOutputStream(), "UTF-8"); pw.write(getJson()); } catch ( UnsupportedEncodingException e ) { // nope - UTF-8 always included } catch (IOException e) { // probably just closing } finally { if (pw != null) { try { pw.close(); } catch ( IOException e ) { // ignore } } } } private String getJson() { Gson gson = builder.create(); return gson.toJson(getDefaultModelObject()); } @Override public final String getMarkupType() { return "text/json"; } public GsonBuilder getBuilder() { return builder; } @Override protected void setModelFromBody(String body) { Gson gson = builder.create(); setDefaultModel(new Model((Serializable)gson.fromJson(body, clazz))); } }
true
true
protected final void onRender(MarkupStream markupStream) { if (!isAuthorized()) { return; } Writer pw = null; try { pw = new OutputStreamWriter(getResponse().getOutputStream(), "UTF-8"); pw.write(getJson()); } catch ( UnsupportedEncodingException e ) { // nope - UTF-8 always included } catch (IOException e) { // probably just closing } finally { if (pw != null) { try { pw.close(); } catch ( IOException e ) { // ignore } } } }
protected final void onRender(MarkupStream markupStream) { if (!isAuthorized()) { return; } getResponse().setContentType( "application/json; charset=UTF-8" ); Writer pw = null; try { pw = new OutputStreamWriter(getResponse().getOutputStream(), "UTF-8"); pw.write(getJson()); } catch ( UnsupportedEncodingException e ) { // nope - UTF-8 always included } catch (IOException e) { // probably just closing } finally { if (pw != null) { try { pw.close(); } catch ( IOException e ) { // ignore } } } }
diff --git a/src/com/macleod2486/magicbuilder/Gatherer.java b/src/com/macleod2486/magicbuilder/Gatherer.java index 5f39226..f84ce51 100644 --- a/src/com/macleod2486/magicbuilder/Gatherer.java +++ b/src/com/macleod2486/magicbuilder/Gatherer.java @@ -1,495 +1,495 @@ /* Magic Builder * A simple java program that grabs the latest prices and displays them per set. Copyright (C) 2013 Manuel Gonzales Jr. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see [http://www.gnu.org/licenses/]. */ package com.macleod2486.magicbuilder; import java.io.File; import java.io.FileOutputStream; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; //Apache Imports import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Row; //JSoup imports import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class Gatherer { private String Sets[]=new String[300]; private String Names[]=new String[300]; //Urls of each of the different formats from the Wizards website private String structuredFormat[]={"https://www.wizards.com/magic/magazine/article.aspx?x=judge/resources/sfrstandard", "https://www.wizards.com/Magic/TCG/Resources.aspx?x=judge/resources/sfrextended", "https://www.wizards.com/Magic/TCG/Resources.aspx?x=judge/resources/sfrmodern"}; //Url of all the formats private String allFormat="http://store.tcgplayer.com/magic?partner=WWWTCG"; private int pointer=0; int year=0; int selection = 4; //Connects to the TCG website to then gather the prices public void tcg() { try { //Keeps track of the rows within the sheet as data is being written int rowNum; //Creates a excel file for the information to be stored HSSFWorkbook standard = new HSSFWorkbook(); HSSFSheet setname; Row newRow; //Various values to screen the data String clean; double highprice = 0; double mediumPrice = 0; double lowPrice = 0; String temp; //Variables to take in information Document page; Element table; Elements row; Elements item; //Variables for extra information about the set double averageHighPrice = 0; double averageMediumPrice = 0; double averageLowPrice = 0; DecimalFormat format = new DecimalFormat("#.00"); /* * Grabs the modified set values to then be used for the website url format * Not the most effecient for loop but will be modified as time goes on. */ for(int limit=0; limit<pointer; limit++) { rowNum=0; System.out.println("\nSet name: "+Names[limit]+"\n"); //Creates a new sheet per set after it filters out bad characters if(Names[limit].contains(":")) { Names[limit]=Names[limit].replaceAll(":", "\\W"); } else if(Names[limit].contains("/")) { Names[limit]=Names[limit].replaceAll("/", "\\W"); } setname=standard.createSheet(Names[limit]); //Sets up the initial row in the sheet newRow = setname.createRow(0); newRow.createCell(0).setCellValue("Card Name"); newRow.createCell(1).setCellValue("High Price"); newRow.createCell(2).setCellValue("Medium Price"); newRow.createCell(3).setCellValue("Low Price"); /*Each modified string value is then put in the following url to then parse the information from it. */ page = Jsoup.connect("http://magic.tcgplayer.com/db/price_guide.asp?setname="+Sets[limit]).get(); table = page.select("table").get(2); row=table.select("tr"); //Grabs each card that was selected for(Element tableRow: row) { //Gets the first row item=tableRow.select("td"); clean=item.get(0).text(); //Filters out land cards if(!clean.contains("Forest")&&!clean.contains("Mountain")&&!clean.contains("Swamp")&&!clean.contains("Island")&&!clean.contains("Plains")&&!clean.isEmpty()) { - if(item.get(5).text().length()>2&&item.get(6).text().length()>2&&item.get(6).text().length()>2) + if(item.get(5).text().length()>2&&item.get(6).text().length()>2&&item.get(7).text().length()>2) { //Creates new row in the sheet newRow = setname.createRow(rowNum+1); //Gets the name of the card clean=clean.substring(1); newRow.createCell(0).setCellValue(clean); //This gets the high price temp=item.get(5).text(); highprice=removeCommas(temp.substring(1,temp.length()-2)); newRow.createCell(1).setCellValue(highprice); averageHighPrice += highprice; //This gets the medium price temp=item.get(6).text(); mediumPrice=removeCommas(temp.substring(1,temp.length()-2)); newRow.createCell(2).setCellValue(mediumPrice); averageMediumPrice +=mediumPrice; //This gets the low price temp = item.get(7).text(); lowPrice = removeCommas(temp.substring(1,temp.length()-2)); newRow.createCell(3).setCellValue(lowPrice); averageLowPrice += lowPrice; System.out.println(clean+" H:$"+highprice+" M:$"+mediumPrice+" L:$"+lowPrice); rowNum++; } } } if(Double.isNaN(averageHighPrice)&&Double.isNaN(averageMediumPrice)&&Double.isNaN(averageLowPrice)) { //Finds the averages averageHighPrice /= rowNum; averageMediumPrice /= rowNum; averageLowPrice /= rowNum; //Formats them averageHighPrice = Double.parseDouble(format.format(averageHighPrice)); averageMediumPrice = Double.parseDouble(format.format(averageMediumPrice)); averageLowPrice = Double.parseDouble(format.format(averageLowPrice)); //Inserts the values into the table newRow = setname.getRow(0); newRow.createCell(4).setCellValue("Average High Price"); newRow.createCell(5).setCellValue("Average Medium Price"); newRow.createCell(6).setCellValue("Average Low Price"); newRow = setname.getRow(1); newRow.createCell(4).setCellValue(averageHighPrice); newRow.createCell(5).setCellValue(averageMediumPrice); newRow.createCell(6).setCellValue(averageLowPrice); System.out.println("Average Prices "+averageHighPrice+" "+averageMediumPrice+" "+averageLowPrice); } //Zeroes them out averageHighPrice = averageMediumPrice = averageLowPrice = 0; //Sets the sheet to auto size columns setname.autoSizeColumn(0); setname.autoSizeColumn(1); setname.autoSizeColumn(2); setname.autoSizeColumn(3); setname.autoSizeColumn(4); setname.autoSizeColumn(5); setname.autoSizeColumn(6); } //Creates the date to be added in the output file name. DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy"); Date date = new Date(); if(this.selection == 0) { File standardFile = new File("Standard-"+dateFormat.format(date)+"-.xls"); FileOutputStream standardOutput = new FileOutputStream(standardFile); standard.write(standardOutput); standardOutput.close(); } else if(this.selection == 1) { File standardFile = new File("Extended-"+dateFormat.format(date)+"-.xls"); FileOutputStream standardOutput = new FileOutputStream(standardFile); standard.write(standardOutput); standardOutput.close(); } else if(this.selection == 2) { File standardFile = new File("Modern-"+dateFormat.format(date)+"-.xls"); FileOutputStream standardOutput = new FileOutputStream(standardFile); standard.write(standardOutput); standardOutput.close(); } else { File standardFile = new File("All-"+dateFormat.format(date)+"-.xls"); FileOutputStream standardOutput = new FileOutputStream(standardFile); standard.write(standardOutput); standardOutput.close(); } } catch(Exception e) { e.printStackTrace(); if(e.toString().contains("Status=400")) { System.out.println("That webpage does not exist!"); } else if(e.toString().contains("SocketTimeout")) { System.out.println("Your connection timed out"); } } } //Similer to the other method but selects every set from a different location public boolean gatherAll() { String clean; char check; try { //Grabs the webpage then selects the list of sets Document page = Jsoup.connect(allFormat).get(); Elements article = page.select("div#advancedSearchSets"); Elements table = article.select("table"); Elements tableBody = table.select("tbody"); Elements tableRow = tableBody.select("tr"); Elements list; this.pointer = 0; //Loops through each item within the list of available sets for(Element item: tableRow) { //Selects all the links within the table rows list = item.select("a[href]"); for(Element itemName: list) { Names[pointer]=itemName.text(); //Replaces all blank characters with the %20 characters clean = itemName.text().replaceAll(" ", "%20"); //Further processes the items within found on the site for(int length=0; length<clean.length(); length++) { check=clean.charAt(length); if(check=='(') { clean = clean.substring(0,length-3); } } //Since there is a in-consistancy within the database these are necessary if(clean.contains("Starter")&&clean.contains("1999")) { Sets[pointer]="Starter%201999"; } else if(clean.contains("Starter")&&clean.contains("2000")) { Sets[pointer]="Starter%202000"; } else if(clean.contains("Magic")&&clean.contains("2010")) { Sets[pointer]="Magic%202010"; } else if(clean.contains("Planechase")&&clean.contains("2012")) { Sets[pointer]="Planechase%202012"; } else if(clean.contains("PDS")&&clean.contains("Fire")) { Sets[pointer]="Premium%20Deck%20Series:%20Fire%20and%20Lightning"; } else if(clean.contains("PDS")&&clean.contains("Slivers")) { Sets[pointer]="Premium%20Deck%20Series:%20Slivers"; } else if(clean.contains("PDS")&&clean.contains("Graveborn")) { Sets[pointer]="Premium%20Deck%20Series:%20Graveborn"; } else if(clean.contains("vs")&&clean.contains("Knights")&&clean.contains("Dragons")) { Sets[pointer]="Duel%20Decks:%20Knights%20vs%20Dragons"; } else if(clean.contains("vs.")) { Sets[pointer]="Duel%20Decks:%20"+clean; } else if(clean.contains("Sixth")&&clean.contains("Edition")) { Sets[pointer]="Classic%20Sixth%20Edition"; } else if(clean.contains("Seventh")&&clean.contains("Edition")) { Sets[pointer]="7th%20Edition"; } else if(clean.contains("Eighth")&&clean.contains("Edition")) { Sets[pointer]="8th%20Edition"; } else if(clean.contains("Ninth")&&clean.contains("Edition")) { Sets[pointer]="9th%20Edition"; } else if(clean.contains("Tenth")&&clean.contains("Edition")) { Sets[pointer]="10th%20Edition"; } //Checks to see if the set is a core set or not else if(clean.matches(".*\\d\\d\\d\\d.*")) { Sets[pointer]=coreSet(clean); } else { Sets[pointer]=clean; } this.pointer++; } } return true; } catch(Exception e) { System.out.println("Error! "+e); return false; } } public boolean gather(int selection) { String clean; char check; this.selection = selection; try { //Grabs the webpage then selects the list of sets Document page = Jsoup.connect(structuredFormat[selection]).get(); Elements article = page.select("div.article-content"); Element table = article.select("ul").get(0); Elements list = table.select("li"); pointer = 0; //Loops through each item within the list of available standard sets for(Element item: list) { Names[pointer]=item.text(); clean = item.text().replaceAll(" ", "%20"); //Further processes the items within found on the site for(int length=0; length<clean.length(); length++) { check=clean.charAt(length); if(check=='(') { clean = clean.substring(0,length-3); } } //Since there is a in-consistancy within the database these two are necessary if(clean.contains("Magic")&&clean.contains("2010")) { Sets[pointer]="Magic%202010"; } else if(clean.contains("Ravnica")&&clean.contains("City")) { Sets[pointer]="Ravnica"; } else if(clean.contains("Sixth")&&clean.contains("Edition")) { Sets[pointer]="Classic%20Sixth%20Edition"; } else if(clean.contains("Seventh")&&clean.contains("Edition")) { Sets[pointer]="7th%20Edition"; } else if(clean.contains("Eighth")&&clean.contains("Edition")) { Sets[pointer]="8th%20Edition"; } else if(clean.contains("Ninth")&&clean.contains("Edition")) { Sets[pointer]="9th%20Edition"; } else if(clean.contains("Tenth")&&clean.contains("Edition")) { Sets[pointer]="10th%20Edition"; } //Checks to see if the set is a core set or not else if(clean.matches(".*\\d\\d\\d\\d.*")) { Sets[pointer]=coreSet(clean); } else { Sets[pointer]=clean; } this.pointer++; } return true; } catch(Exception e) { System.out.println("Error! "+e); e.printStackTrace(); return false; } } //If a core set is detected then the name is edited to fit the TCG format private String coreSet(String input) { String output=input+"%20(M"+input.substring(input.length()-2)+")"; return output; } private Double removeCommas(String input) { double output=0; boolean found = false; for(int start =0; start<input.length(); start++) { if(input.charAt(start)==',') { output=Double.parseDouble(input.substring(0,start)+input.substring(start+1)); found=true; break; } } if(found) return output; else return(Double.parseDouble(input)); } }
true
true
public void tcg() { try { //Keeps track of the rows within the sheet as data is being written int rowNum; //Creates a excel file for the information to be stored HSSFWorkbook standard = new HSSFWorkbook(); HSSFSheet setname; Row newRow; //Various values to screen the data String clean; double highprice = 0; double mediumPrice = 0; double lowPrice = 0; String temp; //Variables to take in information Document page; Element table; Elements row; Elements item; //Variables for extra information about the set double averageHighPrice = 0; double averageMediumPrice = 0; double averageLowPrice = 0; DecimalFormat format = new DecimalFormat("#.00"); /* * Grabs the modified set values to then be used for the website url format * Not the most effecient for loop but will be modified as time goes on. */ for(int limit=0; limit<pointer; limit++) { rowNum=0; System.out.println("\nSet name: "+Names[limit]+"\n"); //Creates a new sheet per set after it filters out bad characters if(Names[limit].contains(":")) { Names[limit]=Names[limit].replaceAll(":", "\\W"); } else if(Names[limit].contains("/")) { Names[limit]=Names[limit].replaceAll("/", "\\W"); } setname=standard.createSheet(Names[limit]); //Sets up the initial row in the sheet newRow = setname.createRow(0); newRow.createCell(0).setCellValue("Card Name"); newRow.createCell(1).setCellValue("High Price"); newRow.createCell(2).setCellValue("Medium Price"); newRow.createCell(3).setCellValue("Low Price"); /*Each modified string value is then put in the following url to then parse the information from it. */ page = Jsoup.connect("http://magic.tcgplayer.com/db/price_guide.asp?setname="+Sets[limit]).get(); table = page.select("table").get(2); row=table.select("tr"); //Grabs each card that was selected for(Element tableRow: row) { //Gets the first row item=tableRow.select("td"); clean=item.get(0).text(); //Filters out land cards if(!clean.contains("Forest")&&!clean.contains("Mountain")&&!clean.contains("Swamp")&&!clean.contains("Island")&&!clean.contains("Plains")&&!clean.isEmpty()) { if(item.get(5).text().length()>2&&item.get(6).text().length()>2&&item.get(6).text().length()>2) { //Creates new row in the sheet newRow = setname.createRow(rowNum+1); //Gets the name of the card clean=clean.substring(1); newRow.createCell(0).setCellValue(clean); //This gets the high price temp=item.get(5).text(); highprice=removeCommas(temp.substring(1,temp.length()-2)); newRow.createCell(1).setCellValue(highprice); averageHighPrice += highprice; //This gets the medium price temp=item.get(6).text(); mediumPrice=removeCommas(temp.substring(1,temp.length()-2)); newRow.createCell(2).setCellValue(mediumPrice); averageMediumPrice +=mediumPrice; //This gets the low price temp = item.get(7).text(); lowPrice = removeCommas(temp.substring(1,temp.length()-2)); newRow.createCell(3).setCellValue(lowPrice); averageLowPrice += lowPrice; System.out.println(clean+" H:$"+highprice+" M:$"+mediumPrice+" L:$"+lowPrice); rowNum++; } } } if(Double.isNaN(averageHighPrice)&&Double.isNaN(averageMediumPrice)&&Double.isNaN(averageLowPrice)) { //Finds the averages averageHighPrice /= rowNum; averageMediumPrice /= rowNum; averageLowPrice /= rowNum; //Formats them averageHighPrice = Double.parseDouble(format.format(averageHighPrice)); averageMediumPrice = Double.parseDouble(format.format(averageMediumPrice)); averageLowPrice = Double.parseDouble(format.format(averageLowPrice)); //Inserts the values into the table newRow = setname.getRow(0); newRow.createCell(4).setCellValue("Average High Price"); newRow.createCell(5).setCellValue("Average Medium Price"); newRow.createCell(6).setCellValue("Average Low Price"); newRow = setname.getRow(1); newRow.createCell(4).setCellValue(averageHighPrice); newRow.createCell(5).setCellValue(averageMediumPrice); newRow.createCell(6).setCellValue(averageLowPrice); System.out.println("Average Prices "+averageHighPrice+" "+averageMediumPrice+" "+averageLowPrice); } //Zeroes them out averageHighPrice = averageMediumPrice = averageLowPrice = 0; //Sets the sheet to auto size columns setname.autoSizeColumn(0); setname.autoSizeColumn(1); setname.autoSizeColumn(2); setname.autoSizeColumn(3); setname.autoSizeColumn(4); setname.autoSizeColumn(5); setname.autoSizeColumn(6); } //Creates the date to be added in the output file name. DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy"); Date date = new Date(); if(this.selection == 0) { File standardFile = new File("Standard-"+dateFormat.format(date)+"-.xls"); FileOutputStream standardOutput = new FileOutputStream(standardFile); standard.write(standardOutput); standardOutput.close(); } else if(this.selection == 1) { File standardFile = new File("Extended-"+dateFormat.format(date)+"-.xls"); FileOutputStream standardOutput = new FileOutputStream(standardFile); standard.write(standardOutput); standardOutput.close(); } else if(this.selection == 2) { File standardFile = new File("Modern-"+dateFormat.format(date)+"-.xls"); FileOutputStream standardOutput = new FileOutputStream(standardFile); standard.write(standardOutput); standardOutput.close(); } else { File standardFile = new File("All-"+dateFormat.format(date)+"-.xls"); FileOutputStream standardOutput = new FileOutputStream(standardFile); standard.write(standardOutput); standardOutput.close(); } } catch(Exception e) { e.printStackTrace(); if(e.toString().contains("Status=400")) { System.out.println("That webpage does not exist!"); } else if(e.toString().contains("SocketTimeout")) { System.out.println("Your connection timed out"); } } }
public void tcg() { try { //Keeps track of the rows within the sheet as data is being written int rowNum; //Creates a excel file for the information to be stored HSSFWorkbook standard = new HSSFWorkbook(); HSSFSheet setname; Row newRow; //Various values to screen the data String clean; double highprice = 0; double mediumPrice = 0; double lowPrice = 0; String temp; //Variables to take in information Document page; Element table; Elements row; Elements item; //Variables for extra information about the set double averageHighPrice = 0; double averageMediumPrice = 0; double averageLowPrice = 0; DecimalFormat format = new DecimalFormat("#.00"); /* * Grabs the modified set values to then be used for the website url format * Not the most effecient for loop but will be modified as time goes on. */ for(int limit=0; limit<pointer; limit++) { rowNum=0; System.out.println("\nSet name: "+Names[limit]+"\n"); //Creates a new sheet per set after it filters out bad characters if(Names[limit].contains(":")) { Names[limit]=Names[limit].replaceAll(":", "\\W"); } else if(Names[limit].contains("/")) { Names[limit]=Names[limit].replaceAll("/", "\\W"); } setname=standard.createSheet(Names[limit]); //Sets up the initial row in the sheet newRow = setname.createRow(0); newRow.createCell(0).setCellValue("Card Name"); newRow.createCell(1).setCellValue("High Price"); newRow.createCell(2).setCellValue("Medium Price"); newRow.createCell(3).setCellValue("Low Price"); /*Each modified string value is then put in the following url to then parse the information from it. */ page = Jsoup.connect("http://magic.tcgplayer.com/db/price_guide.asp?setname="+Sets[limit]).get(); table = page.select("table").get(2); row=table.select("tr"); //Grabs each card that was selected for(Element tableRow: row) { //Gets the first row item=tableRow.select("td"); clean=item.get(0).text(); //Filters out land cards if(!clean.contains("Forest")&&!clean.contains("Mountain")&&!clean.contains("Swamp")&&!clean.contains("Island")&&!clean.contains("Plains")&&!clean.isEmpty()) { if(item.get(5).text().length()>2&&item.get(6).text().length()>2&&item.get(7).text().length()>2) { //Creates new row in the sheet newRow = setname.createRow(rowNum+1); //Gets the name of the card clean=clean.substring(1); newRow.createCell(0).setCellValue(clean); //This gets the high price temp=item.get(5).text(); highprice=removeCommas(temp.substring(1,temp.length()-2)); newRow.createCell(1).setCellValue(highprice); averageHighPrice += highprice; //This gets the medium price temp=item.get(6).text(); mediumPrice=removeCommas(temp.substring(1,temp.length()-2)); newRow.createCell(2).setCellValue(mediumPrice); averageMediumPrice +=mediumPrice; //This gets the low price temp = item.get(7).text(); lowPrice = removeCommas(temp.substring(1,temp.length()-2)); newRow.createCell(3).setCellValue(lowPrice); averageLowPrice += lowPrice; System.out.println(clean+" H:$"+highprice+" M:$"+mediumPrice+" L:$"+lowPrice); rowNum++; } } } if(Double.isNaN(averageHighPrice)&&Double.isNaN(averageMediumPrice)&&Double.isNaN(averageLowPrice)) { //Finds the averages averageHighPrice /= rowNum; averageMediumPrice /= rowNum; averageLowPrice /= rowNum; //Formats them averageHighPrice = Double.parseDouble(format.format(averageHighPrice)); averageMediumPrice = Double.parseDouble(format.format(averageMediumPrice)); averageLowPrice = Double.parseDouble(format.format(averageLowPrice)); //Inserts the values into the table newRow = setname.getRow(0); newRow.createCell(4).setCellValue("Average High Price"); newRow.createCell(5).setCellValue("Average Medium Price"); newRow.createCell(6).setCellValue("Average Low Price"); newRow = setname.getRow(1); newRow.createCell(4).setCellValue(averageHighPrice); newRow.createCell(5).setCellValue(averageMediumPrice); newRow.createCell(6).setCellValue(averageLowPrice); System.out.println("Average Prices "+averageHighPrice+" "+averageMediumPrice+" "+averageLowPrice); } //Zeroes them out averageHighPrice = averageMediumPrice = averageLowPrice = 0; //Sets the sheet to auto size columns setname.autoSizeColumn(0); setname.autoSizeColumn(1); setname.autoSizeColumn(2); setname.autoSizeColumn(3); setname.autoSizeColumn(4); setname.autoSizeColumn(5); setname.autoSizeColumn(6); } //Creates the date to be added in the output file name. DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy"); Date date = new Date(); if(this.selection == 0) { File standardFile = new File("Standard-"+dateFormat.format(date)+"-.xls"); FileOutputStream standardOutput = new FileOutputStream(standardFile); standard.write(standardOutput); standardOutput.close(); } else if(this.selection == 1) { File standardFile = new File("Extended-"+dateFormat.format(date)+"-.xls"); FileOutputStream standardOutput = new FileOutputStream(standardFile); standard.write(standardOutput); standardOutput.close(); } else if(this.selection == 2) { File standardFile = new File("Modern-"+dateFormat.format(date)+"-.xls"); FileOutputStream standardOutput = new FileOutputStream(standardFile); standard.write(standardOutput); standardOutput.close(); } else { File standardFile = new File("All-"+dateFormat.format(date)+"-.xls"); FileOutputStream standardOutput = new FileOutputStream(standardFile); standard.write(standardOutput); standardOutput.close(); } } catch(Exception e) { e.printStackTrace(); if(e.toString().contains("Status=400")) { System.out.println("That webpage does not exist!"); } else if(e.toString().contains("SocketTimeout")) { System.out.println("Your connection timed out"); } } }
diff --git a/mifos/src/org/mifos/framework/security/util/ActivityMapper.java b/mifos/src/org/mifos/framework/security/util/ActivityMapper.java index 036f2a03b..da8d11c29 100644 --- a/mifos/src/org/mifos/framework/security/util/ActivityMapper.java +++ b/mifos/src/org/mifos/framework/security/util/ActivityMapper.java @@ -1,1339 +1,1339 @@ /** * */ package org.mifos.framework.security.util; import java.util.HashMap; import java.util.Map; import org.mifos.application.accounts.util.helpers.AccountStates; import org.mifos.application.customer.group.util.helpers.GroupConstants; import org.mifos.application.customer.util.helpers.CustomerConstants; import org.mifos.framework.security.authorization.AuthorizationManager; import org.mifos.framework.security.util.resources.SecurityConstants; public class ActivityMapper { private final short SAVING_CANCHANGESTATETO_PARTIALAPPLICATION = 140; private final short SAVING_CANCHANGESTATETO_PENDINGAPPROVAL = 180; private final short SAVING_CANCHANGESTATETO_CANCEL = 181; private final short SAVING_CANCHANGESTATETO_APPROVED = 182; private final short SAVING_CANCHANGESTATETO_INACTIVE = 183; private final short SAVING_CANCHANGESTATETO_INACTIVE_BLACKLISTED = 184; private final short SAVING_BLACKLISTED_FLAG = 6; private final short SAVING_CANSAVEFORLATER = 137; private final short SAVING_CANSUBMITFORAPPROVAL = 185; private final short LOANACC_CANCHANGETO_PARTIALAPPLICATION = 103; private final short LOANACC_CANCHANGETO_PENDINGAPPROVAL = 108; private final short LOANACC_CANCHANGETO_APPROVED = 104; private final short LOANACC_CANCHANGETO_DBTOLOANOFFICER = 106; private final short LOANACC_CANCHANGETO_ACTIVEINGOODSTANDING = 107; private final short LOANACC_CANCHANGETO_OBLIGATIONSMET = 111; private final short LOANACC_CANCHANGETO_WRITTENOFF = 109; private final short LOANACC_CANCHANGETO_RESCHEDULED = 110; private final short LOANACC_CANCHANGETO_BADSTANDING = 112; private final short LOANACC_CANCHANGETO_CANCEL = 105; private final short LOANACC_CANSAVEFORLATER = 101; private final short LOANACC_CANSUBMITFORAPPROVAL = 102; // client state change mappings private final short CLIENT_CANCHANGETO_PARTIALAPPLICATION = 37; private final short CLIENT_CANCHANGETO_APPROVED = 38; private final short CLIENT_CANCHANGETO_CANCELLED = 39; private final short CLIENT_CANCHANGETO_ONHOLD = 40; private final short CLIENT_CANCHANGETO_CLOSED = 41; private final short CLIENT_CANCHANGETO_PENDINGAPPROVAL = 42; private final short CLIENT_BLACKLISTED_FLAG = 3; private final short CLIENT_CLOSED_BLACKLISTED_FLAG = 8; private final short CLIENT_CANCHANGETO_CANCEL_BLACKLISTED = 55; private final short CLIENT_CREATEPARTIAL = 35; private final short CLIENT_CREATEPENDING = 36; // group sate change mappings private final short GROUP_CANCHANGETO_PARTIALAPPLICATION = 59; private final short GROUP_CANCHANGETO_APPROVED = 60; private final short GROUP_CANCHANGETO_CANCELLED = 61; private final short GROUP_CANCHANGETO_ONHOLD = 62; private final short GROUP_CANCHANGETO_CLOSED = 63; private final short GROUP_CANCHANGETO_PENDINGAPPROVAL = 64; private final short GROUP_CANCEL_BLACKLISTED_FLAG = 13; private final short GROUP_CLOSED_BLACKLISTED_FLAG = 18; private final short GROUP_CANCHANGETO_CANCEL_BLACKLISTED = 77; private final short GROUP_CREATEPARTIAL = 57; private final short GROUP_CREATEPENDING = 58; private ActivityMapper() { activityMap.put("/AdminAction-load", SecurityConstants.VIEW); // customer serach action activityMap.put("/CustomerSearchAction-load", SecurityConstants.VIEW); activityMap.put("/CustomerSearchAction-search", SecurityConstants.SEARCH); activityMap.put("/CustomerSearchAction-preview", SecurityConstants.SEARCH); activityMap.put("/CustomerSearchAction-get", SecurityConstants.SEARCH); activityMap.put("/CustomerSearchAction-getHomePage", SecurityConstants.VIEW); activityMap.put("/CustomerSearchAction-getOfficeHomePage", SecurityConstants.VIEW); activityMap.put("/CustomerSearchAction-loadAllBranches", SecurityConstants.VIEW); activityMap.put("/mifoslogout-logout", SecurityConstants.VIEW); // Change password related activityMap.put("/mifoslogin-update", SecurityConstants.VIEW); // Office related mapping activityMap.put("/OfficeAction-loadall", SecurityConstants.VIEW); activityMap.put("/OfficeAction-load", SecurityConstants.OFFICE_CREATE_OFFICE); activityMap.put("/OfficeAction-loadParent", SecurityConstants.VIEW); activityMap.put("/OfficeAction-preview", SecurityConstants.VIEW); activityMap.put("/OfficeAction-create", SecurityConstants.OFFICE_CREATE_OFFICE); activityMap.put("/OfficeAction-get", SecurityConstants.VIEW); activityMap.put("/OfficeAction-manage", SecurityConstants.OFFICE_EDIT_OFFICE); activityMap.put("/OfficeAction-previous", SecurityConstants.VIEW); activityMap.put("/OfficeAction-update", SecurityConstants.OFFICE_EDIT_OFFICE); activityMap .put("/OfficeHierarchyAction-cancel", SecurityConstants.VIEW); activityMap.put("/OfficeHierarchyAction-load", SecurityConstants.VIEW); activityMap.put("/OfficeHierarchyAction-update", SecurityConstants.OFFICE_EDIT_OFFICE); activityMap.put("/offhierarchyaction-cancel", SecurityConstants.VIEW); activityMap.put("/offhierarchyaction-load", SecurityConstants.VIEW); activityMap.put("/offhierarchyaction-update",SecurityConstants.OFFICE_EDIT_OFFICE); //m2 office action activityMap.put("/offAction-load", SecurityConstants.OFFICE_CREATE_OFFICE); activityMap.put("/offAction-loadParent", SecurityConstants.VIEW); activityMap.put("/offAction-preview", SecurityConstants.VIEW); activityMap.put("/offAction-previous", SecurityConstants.VIEW); activityMap.put("/offAction-create", SecurityConstants.OFFICE_CREATE_OFFICE); activityMap.put("/offAction-get", SecurityConstants.VIEW); activityMap.put("/offAction-edit", SecurityConstants.OFFICE_EDIT_OFFICE); activityMap.put("/offAction-editpreview", SecurityConstants.OFFICE_EDIT_OFFICE); activityMap.put("/offAction-editprevious", SecurityConstants.OFFICE_EDIT_OFFICE); activityMap.put("/offAction-update", SecurityConstants.OFFICE_EDIT_OFFICE); activityMap.put("/offAction-getAllOffices", SecurityConstants.VIEW); // roles and permission related mappings activityMap.put("/manageRolesAndPermission-manage", SecurityConstants.VIEW); activityMap .put("/manageRolesAndPermission-get", SecurityConstants.VIEW); activityMap.put("/manageRolesAndPermission-load", SecurityConstants.ROLES_CREATE_ROLES); activityMap.put("/manageRolesAndPermission-create", SecurityConstants.ROLES_CREATE_ROLES); activityMap.put("/manageRolesAndPermission-update", SecurityConstants.ROLES_EDIT_ROLES); activityMap.put("/manageRolesAndPermission-cancel", SecurityConstants.VIEW); activityMap.put("/manageRolesAndPermission-preview", SecurityConstants.ROLES_DELETE_ROLES); activityMap.put("/manageRolesAndPermission-delete", SecurityConstants.ROLES_DELETE_ROLES); // Group ralated mappings // activities related to create group activityMap.put("/GroupAction-chooseOffice", SecurityConstants.VIEW); activityMap.put("/GroupAction-hierarchyCheck", SecurityConstants.VIEW); activityMap.put("/GroupAction-load", SecurityConstants.VIEW); activityMap.put("/GroupAction-loadMeeting", SecurityConstants.MEETING_CREATE_GROUP_MEETING); activityMap.put("/GroupAction-setDefaultFormedByPersonnel", SecurityConstants.VIEW); activityMap.put("/GroupAction-previous", SecurityConstants.VIEW); activityMap.put("/GroupAction-preview", SecurityConstants.VIEW); activityMap.put("/GroupAction-create", SecurityConstants.VIEW); activityMap.put("/GroupAction-search", SecurityConstants.VIEW); // activities related to retrieve group for Group Module activityMap.put("/GroupAction-getDetails", SecurityConstants.VIEW); activityMap.put("/GroupAction-get", SecurityConstants.VIEW); // activities related to update group status for Group Module activityMap.put("/GroupAction-loadStatus", SecurityConstants.VIEW); activityMap.put("/GroupAction-updateStatus", SecurityConstants.VIEW); // activities related to update group for Group Module activityMap.put("/GroupAction-manage", SecurityConstants.GROUP_EDIT_GROUP); activityMap.put("/GroupAction-update", SecurityConstants.GROUP_EDIT_GROUP); // activities related to change center membership for Group Module activityMap.put("/GroupAction-loadParentTransfer", SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); activityMap.put("/GroupAction-confirmParentTransfer", SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); activityMap.put("/GroupAction-updateParent", SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); // activities related to change center membership for Group Module activityMap.put("/GroupAction-loadParentTransfer", SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); activityMap.put("/GroupAction-confirmParentTransfer", SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); activityMap.put("/GroupAction-updateParent", SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); // activities related to transfer the group for Group Module activityMap.put("/GroupAction-loadTransfer", SecurityConstants.GROUP_TRANSFER_THE_GROUP); activityMap.put("/GroupAction-confirmBranchTransfer", SecurityConstants.GROUP_TRANSFER_THE_GROUP); activityMap.put("/GroupAction-updateBranch", SecurityConstants.GROUP_TRANSFER_THE_GROUP); // apply charges activityMap.put("/closedaccsearchaction-search", SecurityConstants.GROUP_APPLY_CHARGES_TO_GROUP_ACCOUNT); activityMap.put("/GroupAction-loadSearch", SecurityConstants.VIEW); // Customer Notes related mapping // activityMap.put("/CustomerNoteAction-load",SecurityConstants.CUSTOMER_ADD_NOTES_TO_CENTER_GROUP_CLIENT); activityMap.put("/CustomerNoteAction-preview", SecurityConstants.VIEW); activityMap.put("/CustomerNoteAction-previous", SecurityConstants.VIEW); activityMap.put("/CustomerNoteAction-create", SecurityConstants.VIEW); activityMap.put("/CustomerNoteAction-get", SecurityConstants.VIEW); activityMap.put("/CustomerNoteAction-search", SecurityConstants.VIEW); // mapping for group activityMap.put("/CustomerNoteAction-load-Group", SecurityConstants.GROUP_ADD_NOTE_TO_GROUP); activityMap.put("/CustomerNoteAction-load-Client", SecurityConstants.CLIENT_ADD_NOTE_TO_CLIENT); activityMap.put("/CustomerNoteAction-load-Center", SecurityConstants.CENTER_ADD_NOTE_TO_CENTER); // Customer Historical Data related mapping activityMap.put("/CustomerHistoricalDataAction-load-Group", SecurityConstants.GROUP_ADD_EDIT_HISTORICAL_DATA); activityMap.put("/CustomerHistoricalDataAction-load-Client", SecurityConstants.CIENT_ADD_EDIT_HISTORICAL_DATA); activityMap.put("/CustomerHistoricalDataAction-get", SecurityConstants.VIEW); activityMap.put("/CustomerHistoricalDataAction-preview", SecurityConstants.VIEW); activityMap.put("/CustomerHistoricalDataAction-previous", SecurityConstants.VIEW); activityMap.put("/CustomerHistoricalDataAction-update", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-load-Group", SecurityConstants.GROUP_ADD_EDIT_HISTORICAL_DATA); activityMap.put("/custHistoricalDataAction-load-Client", SecurityConstants.CIENT_ADD_EDIT_HISTORICAL_DATA); activityMap.put("/custHistoricalDataAction-get", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-preview", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-previous", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-update", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-loadHistoricalData-Group", SecurityConstants.GROUP_ADD_EDIT_HISTORICAL_DATA); activityMap.put("/custHistoricalDataAction-loadHistoricalData-Client", SecurityConstants.CIENT_ADD_EDIT_HISTORICAL_DATA); activityMap.put("/custHistoricalDataAction-getHistoricalData", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-previewHistoricalData", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-previousHistoricalData", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-updateHistoricalData", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-cancelHistoricalData", SecurityConstants.VIEW); // personnel related mappings activityMap.put("/PersonnelAction-chooseOffice", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); activityMap.put("/PersonnelAction-load", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); activityMap.put("/PersonnelAction-preview", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-previous", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-create", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); activityMap.put("/PersonnelAction-get", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-manage", SecurityConstants.PERSONNEL_EDIT_PERSONNEL); activityMap.put("/PersonnelAction-update", SecurityConstants.PERSONNEL_EDIT_PERSONNEL); activityMap.put("/PersonnelAction-loadSearch", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-search", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-loadUnLockUser", SecurityConstants.PERSONNEL_UNLOCK_PERSONNEL); activityMap.put("/PersonnelAction-unLockUserAccount", SecurityConstants.PERSONNEL_UNLOCK_PERSONNEL); //m2 personnel related mappings activityMap.put("/PersonAction-get",SecurityConstants.VIEW); activityMap.put("/PersonAction-chooseOffice", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); activityMap.put("/PersonAction-load", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); activityMap.put("/PersonAction-manage", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); activityMap.put("/PersonAction-previewManage", SecurityConstants.VIEW); activityMap.put("/PersonAction-previousManage", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); activityMap.put("/PersonAction-update", SecurityConstants.PERSONNEL_EDIT_PERSONNEL); activityMap.put("/PersonnelAction-prevPersonalInfo", SecurityConstants.VIEW); activityMap.put("/PersonAction-preview", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); activityMap.put("/PersonAction-previous", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); activityMap.put("/PersonAction-create", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); // for your settings link activityMap.put("/PersonnelAction-getDetails", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-editPersonalInfo", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); activityMap.put("/PersonnelAction-previewPersonalInfo", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-prevPersonalInfo", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-updateSettings", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); activityMap.put("/PersonnelAction-loadChangePassword", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); activityMap.put("/PersonnelNotesAction-load", SecurityConstants.PERSONNEL_EDIT_PERSONNEL); activityMap .put("/PersonnelNotesAction-preview", SecurityConstants.VIEW); activityMap.put("/PersonnelNotesAction-previous", SecurityConstants.VIEW); activityMap.put("/PersonnelNotesAction-create", SecurityConstants.PERSONNEL_EDIT_PERSONNEL); activityMap.put("/PersonnelNotesAction-search", SecurityConstants.VIEW); activityMap.put("/PersonnelNotesAction-get", SecurityConstants.VIEW); //M2 personnel notes activityMap.put("/personnelNoteAction-load",SecurityConstants.PERSONNEL_EDIT_PERSONNEL); activityMap.put("/personnelNoteAction-preview", SecurityConstants.VIEW); activityMap.put("/personnelNoteAction-previous",SecurityConstants.VIEW); activityMap.put("/personnelNoteAction-create",SecurityConstants.VIEW); activityMap.put("/personnelNoteAction-search", SecurityConstants.VIEW); // center ralated mappings activityMap.put("/centerAction-chooseOffice", SecurityConstants.CENTER_CREATE_NEW_CENTER); activityMap.put("/centerAction-load", SecurityConstants.CENTER_CREATE_NEW_CENTER); activityMap.put("/centerAction-loadMeeting-CenterCreate", SecurityConstants.MEETING_CREATE_CENTER_MEETING); activityMap.put("/centerAction-loadMeeting-Center", SecurityConstants.MEETING_UPDATE_CENTER_MEETING); activityMap.put("/centerAction-getDetails", SecurityConstants.VIEW); activityMap.put("/centerAction-get", SecurityConstants.VIEW); activityMap.put("/centerAction-loadStatus", SecurityConstants.CENTER_EDIT_STATUS); activityMap.put("/centerAction-updateStatus", SecurityConstants.CENTER_EDIT_STATUS); activityMap .put( "/centerAction-manage", SecurityConstants.CENTER_MODIFY_CENTER_INFORMATION_AND_CHANGE_CENTER_STATUS); activityMap.put("/centerAction-previous", SecurityConstants.VIEW); activityMap.put("/centerAction-preview", SecurityConstants.VIEW); activityMap.put("/centerAction-create", SecurityConstants.CENTER_CREATE_NEW_CENTER); activityMap .put( "/centerAction-update", SecurityConstants.CENTER_MODIFY_CENTER_INFORMATION_AND_CHANGE_CENTER_STATUS); activityMap.put("/centerAction-loadSearch", SecurityConstants.VIEW); activityMap.put("/centerAction-search", SecurityConstants.VIEW); //For M2 Center ------------------------ activityMap.put("/centerCustAction-chooseOffice", SecurityConstants.CENTER_CREATE_NEW_CENTER); activityMap.put("/centerCustAction-load", SecurityConstants.CENTER_CREATE_NEW_CENTER); activityMap.put("/centerCustAction-loadMeeting-CenterCreate", SecurityConstants.MEETING_CREATE_CENTER_MEETING); activityMap.put("/centerCustAction-previous", SecurityConstants.VIEW); activityMap.put("/centerCustAction-preview", SecurityConstants.VIEW); activityMap.put("/centerCustAction-create", SecurityConstants.CENTER_CREATE_NEW_CENTER); activityMap.put( "/centerCustAction-manage", SecurityConstants.CENTER_MODIFY_CENTER_INFORMATION_AND_CHANGE_CENTER_STATUS); activityMap.put("/centerCustAction-editPrevious", SecurityConstants.VIEW); activityMap.put("/centerCustAction-editPreview", SecurityConstants.VIEW); activityMap.put( "/centerCustAction-update", SecurityConstants.CENTER_MODIFY_CENTER_INFORMATION_AND_CHANGE_CENTER_STATUS); activityMap.put("/centerCustAction-get", SecurityConstants.VIEW); // For M2 Center ends // colsed account searchaction in center details page activityMap .put("/closedaccsearchaction-search", SecurityConstants.VIEW); // CustomerSearch // activityMap.put("/CustomerSearchAction-validate",SecurityConstants.VIEW); // client creation action activityMap .put("/clientCreationAction-preLoad", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-load", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-chooseOffice", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-setDefaultFormedByPersonnel", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-next", SecurityConstants.VIEW); activityMap .put("/clientCreationAction-preview", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-prevPersonalInfo", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-prevMFIInfo", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-create", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-get", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-getDetails", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-loadStatus", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-loadTransfer", SecurityConstants.CIENT_CHANGE_GROUP_MEMBERSHIP); activityMap.put("/clientCreationAction-loadBranchTransfer", SecurityConstants.CIENT_TRANSFER_THE_CLIENT); activityMap.put("/clientCreationAction-editMFIInfo", SecurityConstants.CIENT_EDIT_MFI_INFORMATION); activityMap.put("/clientCreationAction-editPersonalInfo", SecurityConstants.CLIENT_UPDATE_PERSONNEL_INFO); activityMap.put("/clientCreationAction-update", SecurityConstants.CLIENT_UPDATE_PERSONNEL_INFO); activityMap.put("/clientCreationAction-updateMfi", SecurityConstants.CIENT_EDIT_MFI_INFORMATION); activityMap.put("/clientCreationAction-loadMeeting-ClientCreate", SecurityConstants.MEETING_CREATE_CLIENT_MEETING); activityMap.put("/clientCreationAction-loadMeeting-Client", SecurityConstants.MEETING_UPDATE_CLIENT_MEETING); activityMap.put("/clientCreationAction-previous", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-retrievePictureOnPreview", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-retrievePicture", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-showPicture", SecurityConstants.VIEW); activityMap .put( "/clientCreationAction-loadHistoricalData", SecurityConstants.CUSTOMER_ADD_HISTORICAL_DATA_TO_CENTER_GROUP_CLIENT); activityMap.put("/clientStatusAction-load", SecurityConstants.VIEW); activityMap.put("/clientStatusAction-preview", SecurityConstants.VIEW); activityMap.put("/clientStatusAction-previous", SecurityConstants.VIEW); activityMap.put("/clientStatusAction-update", SecurityConstants.VIEW); activityMap.put("/clientTransferAction-loadParents",SecurityConstants.CIENT_CHANGE_GROUP_MEMBERSHIP); activityMap.put("/clientTransferAction-loadBranches",SecurityConstants.CIENT_TRANSFER_THE_CLIENT); activityMap.put("/clientTransferAction-previewBranchTransfer",SecurityConstants.VIEW); activityMap.put("/clientTransferAction-previewParentTransfer",SecurityConstants.VIEW); activityMap.put("/clientTransferAction-updateParent", SecurityConstants.CIENT_CHANGE_GROUP_MEMBERSHIP); activityMap.put("/clientTransferAction-transferToBranch",SecurityConstants.CIENT_TRANSFER_THE_CLIENT); activityMap.put("/groupTransferAction-loadParents",SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); activityMap.put("/groupTransferAction-loadBranches",SecurityConstants.GROUP_TRANSFER_THE_GROUP); activityMap.put("/groupTransferAction-previewBranchTransfer",SecurityConstants.VIEW); activityMap.put("/groupTransferAction-previewParentTransfer",SecurityConstants.VIEW); activityMap.put("/groupTransferAction-transferToCenter", SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); activityMap.put("/groupTransferAction-transferToBranch",SecurityConstants.GROUP_TRANSFER_THE_GROUP); // meeting action activityMap.put("/MeetingAction-load", SecurityConstants.VIEW); activityMap.put("/MeetingAction-loadMeeting-Group", SecurityConstants.MEETING_UPDATE_GROUP_MEETING); activityMap.put("/MeetingAction-loadMeeting-Client", SecurityConstants.MEETING_UPDATE_CLIENT_MEETING); activityMap.put("/MeetingAction-create", SecurityConstants.VIEW); activityMap.put("/MeetingAction-get-Group", SecurityConstants.MEETING_UPDATE_GROUP_MEETING); activityMap.put("/MeetingAction-get-Client", SecurityConstants.MEETING_UPDATE_CLIENT_MEETING); activityMap.put("/MeetingAction-get-Center", SecurityConstants.MEETING_UPDATE_CENTER_MEETING); activityMap.put("/MeetingAction-update", SecurityConstants.VIEW); activityMap.put("/MeetingAction-preview", SecurityConstants.VIEW); activityMap.put("/MeetingAction-previous", SecurityConstants.VIEW); // product categories mapping activityMap.put("/productCategoryAction-load", SecurityConstants.DEFINE_NEW_PRODUCT_CATEGORIES); activityMap.put("/productCategoryAction-createPreview", SecurityConstants.VIEW); activityMap.put("/productCategoryAction-create", SecurityConstants.DEFINE_NEW_PRODUCT_CATEGORIES); activityMap.put("/productCategoryAction-get", SecurityConstants.VIEW); activityMap.put("/productCategoryAction-managePreview", SecurityConstants.VIEW); activityMap.put("/productCategoryAction-manage", SecurityConstants.EDIT_PRODUCT_CATEGORIES); activityMap.put("/productCategoryAction-update", SecurityConstants.EDIT_PRODUCT_CATEGORIES); activityMap.put("/productCategoryAction-getAllCategories", SecurityConstants.VIEW); activityMap.put("/productCategoryAction-createPrevious", SecurityConstants.VIEW); activityMap.put("/productCategoryAction-managePrevious", SecurityConstants.VIEW); // saving product mappeings activityMap.put("/savingsprdaction-search", SecurityConstants.VIEW); activityMap.put("/savingsprdaction-load", SecurityConstants.DEFINE_NEW_SAVING_PRODUCT_INSTANCE); activityMap.put("/savingsprdaction-preview", SecurityConstants.VIEW); activityMap.put("/savingsprdaction-previous", SecurityConstants.VIEW); activityMap.put("/savingsprdaction-create", SecurityConstants.DEFINE_NEW_SAVING_PRODUCT_INSTANCE); activityMap.put("/savingsprdaction-get", SecurityConstants.VIEW); activityMap.put("/savingsprdaction-manage", SecurityConstants.EDIT_SAVING_PRODUCT); activityMap.put("/savingsprdaction-update", SecurityConstants.EDIT_SAVING_PRODUCT); activityMap.put("/savingsproductaction-search", SecurityConstants.VIEW); activityMap.put("/savingsproductaction-load", SecurityConstants.DEFINE_NEW_SAVING_PRODUCT_INSTANCE); activityMap.put("/savingsproductaction-preview", SecurityConstants.VIEW); activityMap.put("/savingsproductaction-previous", SecurityConstants.VIEW); activityMap.put("/savingsproductaction-create", SecurityConstants.DEFINE_NEW_SAVING_PRODUCT_INSTANCE); activityMap.put("/savingsproductaction-get", SecurityConstants.VIEW); activityMap.put("/savingsproductaction-cancelCreate", SecurityConstants.VIEW); activityMap.put("/savingsproductaction-manage", SecurityConstants.EDIT_SAVING_PRODUCT); activityMap.put("/savingsproductaction-update", SecurityConstants.EDIT_SAVING_PRODUCT); // view lateness mappings activityMap.put("/prdconfigurationaction-search", SecurityConstants.VIEW); activityMap.put("/prdconfigurationaction-update", SecurityConstants.EDIT_PRODUCT_CATEGORIES); // loan product categories activityMap.put("/loanprdaction-load", SecurityConstants.DEFINE_NEW_LOAN_PRODUCT_INSTANCE); activityMap.put("/loanprdaction-preview", SecurityConstants.VIEW); activityMap.put("/loanprdaction-previous", SecurityConstants.VIEW); activityMap.put("/loanprdaction-create", SecurityConstants.DEFINE_NEW_LOAN_PRODUCT_INSTANCE); activityMap.put("/loanprdaction-search", SecurityConstants.VIEW); activityMap.put("/loanprdaction-get", SecurityConstants.VIEW); activityMap.put("/loanprdaction-manage", SecurityConstants.EDIT_LOAN_PRODUCT); activityMap.put("/loanprdaction-update", SecurityConstants.EDIT_LOAN_PRODUCT); // Fee mapping activityMap.put("/feesAction-search", SecurityConstants.VIEW); activityMap.put("/feesAction-load", SecurityConstants.FEES_CREATE_FEES); activityMap.put("/feesAction-preview", SecurityConstants.VIEW); activityMap.put("/feesAction-create", SecurityConstants.FEES_CREATE_FEES); activityMap.put("/feesAction-get", SecurityConstants.VIEW); activityMap.put("/feesAction-manage", SecurityConstants.FEES_EDIT_FEES); activityMap.put("/feesAction-update", SecurityConstants.FEES_EDIT_FEES); activityMap.put("/feesAction-previous", SecurityConstants.VIEW); activityMap.put("/feeaction-search", SecurityConstants.VIEW); activityMap.put("/feeaction-load", SecurityConstants.FEES_CREATE_FEES); activityMap.put("/feeaction-preview", SecurityConstants.VIEW); activityMap.put("/feeaction-editPreview", SecurityConstants.VIEW); activityMap .put("/feeaction-create", SecurityConstants.FEES_CREATE_FEES); activityMap.put("/feeaction-get", SecurityConstants.VIEW); activityMap.put("/feeaction-manage", SecurityConstants.FEES_EDIT_FEES); activityMap.put("/feeaction-update", SecurityConstants.FEES_EDIT_FEES); activityMap.put("/feeaction-previous", SecurityConstants.VIEW); activityMap.put("/feeaction-editPrevious", SecurityConstants.VIEW); activityMap.put("/feeaction-viewAll", SecurityConstants.VIEW); activityMap.put("/feeaction-cancelCreate", SecurityConstants.VIEW); activityMap.put("/feeaction-cancelEdit", SecurityConstants.VIEW); // checklist mapping activityMap.put("/checkListAction-loadall", SecurityConstants.VIEW); activityMap.put("/checkListAction-load", SecurityConstants.CHECKLIST_CREATE_CHECKLIST); activityMap.put("/checkListAction-create", SecurityConstants.CHECKLIST_CREATE_CHECKLIST); activityMap.put("/checkListAction-preview", SecurityConstants.VIEW); activityMap.put("/checkListAction-previous", SecurityConstants.VIEW); activityMap.put("/checkListAction-previous", SecurityConstants.CHECKLIST_CREATE_CHECKLIST); activityMap.put("/checkListAction-loadParent", SecurityConstants.VIEW); activityMap.put("/checkListAction-get", SecurityConstants.VIEW); activityMap.put("/checkListAction-manage", SecurityConstants.CHECKLIST_EDIT_CHECKLIST); activityMap.put("/checkListAction-update", SecurityConstants.CHECKLIST_EDIT_CHECKLIST); // mapping for search before loan activityMap.put("/AccountsSearchAction-load", SecurityConstants.VIEW); activityMap.put("/AccountsSearchAction-search", SecurityConstants.VIEW); // mapping for loan activityMap.put("/loanAction-getPrdOfferings", SecurityConstants.VIEW); activityMap.put("/loanAction-load", SecurityConstants.VIEW); activityMap.put("/loanAction-next", SecurityConstants.VIEW); activityMap.put("/loanAction-preview", SecurityConstants.VIEW); activityMap.put("/loanAction-previous", SecurityConstants.VIEW); activityMap.put("/loanAction-get", SecurityConstants.VIEW); activityMap.put("/loanAction-manage", SecurityConstants.LOAN_UPDATE_LOAN); activityMap.put("/loanAction-update", SecurityConstants.LOAN_UPDATE_LOAN); activityMap.put("/loanAction-getLoanChangeLog", SecurityConstants.VIEW); activityMap.put("/loanAction-search", SecurityConstants.VIEW); activityMap.put("/loanAction-create", SecurityConstants.VIEW); // mapping for loanActivity activityMap.put("/loanAccountAction-getAllActivity", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-get",SecurityConstants.VIEW); activityMap.put("/loanAccountAction-getLoanRepaymentSchedule",SecurityConstants.VIEW); activityMap.put("/loanAccountAction-viewStatusHistory", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-manage", SecurityConstants.LOAN_UPDATE_LOAN); activityMap.put("/loanAccountAction-managePreview",SecurityConstants.VIEW); activityMap.put("/loanAccountAction-managePrevious",SecurityConstants.VIEW); activityMap.put("/loanAccountAction-cancel",SecurityConstants.VIEW); activityMap.put("/loanAccountAction-update", SecurityConstants.LOAN_UPDATE_LOAN); activityMap.put("/loanAccountAction-getPrdOfferings", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-load", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-schedulePreview", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-preview", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-previous", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-create", SecurityConstants.VIEW); // mapping for account status::TO BE REMOVED activityMap.put("/LoanStatusAction-load", SecurityConstants.VIEW); activityMap.put("/LoanStatusAction-preview", SecurityConstants.VIEW); activityMap.put("/LoanStatusAction-previous", SecurityConstants.VIEW); activityMap.put("/LoanStatusAction-update", SecurityConstants.VIEW); activityMap.put("/LoanStatusAction-search", SecurityConstants.VIEW); activityMap.put("/LoanStatusAction-writeOff", SecurityConstants.VIEW); // mapping for account status activityMap.put("/editStatusAction-load", SecurityConstants.VIEW); activityMap.put("/editStatusAction-preview", SecurityConstants.VIEW); activityMap.put("/editStatusAction-previous", SecurityConstants.VIEW); activityMap.put("/editStatusAction-update", SecurityConstants.VIEW); //mapping for custAction activityMap.put("/custAction-getClosedAccounts", SecurityConstants.VIEW); activityMap.put("/custAction-getBackToDetailsPage", SecurityConstants.VIEW); // mapping for account notes activityMap.put("/AccountNotesAction-load", SecurityConstants.LOAN_CAN_ADD_NOTES_TO_LOAN); activityMap.put("/AccountNotesAction-preview", SecurityConstants.VIEW); activityMap.put("/AccountNotesAction-previous", SecurityConstants.VIEW); activityMap.put("/AccountNotesAction-get", SecurityConstants.VIEW); activityMap.put("/AccountNotesAction-search", SecurityConstants.VIEW); activityMap.put("/AccountNotesAction-create", SecurityConstants.LOAN_CAN_ADD_NOTES_TO_LOAN); // mapping for apply payment activityMap.put("/accountTrxn-load", SecurityConstants.APPLY_PAYMENT_TO_CLIENT_GROUP_CENTERS_LOANS); activityMap.put("/accountTrxn-create", SecurityConstants.APPLY_PAYMENT_TO_CLIENT_GROUP_CENTERS_LOANS); activityMap.put("/accountTrxn-preview", SecurityConstants.VIEW); activityMap.put("/accountTrxn-getInstallmentHistory", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-getInstallmentDetails", SecurityConstants.VIEW); activityMap.put("/accountTrxn-previous", SecurityConstants.VIEW); // apply charges activityMap.put("/AccountsApplyChargesAction-load", SecurityConstants.APPLY_CHARGES_TO_CLIENT_GROUP_CENTERS_LOANS); activityMap.put("/AccountsApplyChargesAction-create", SecurityConstants.APPLY_CHARGES_TO_CLIENT_GROUP_CENTERS_LOANS); // fund mapping activityMap.put("/fundAction-load", SecurityConstants.FUNDS_CREATE_FUNDS); activityMap.put("/fundAction-create", SecurityConstants.FUNDS_CREATE_FUNDS); activityMap.put("/fundAction-preview", SecurityConstants.VIEW); activityMap.put("/fundAction-getAllFunds", SecurityConstants.VIEW); activityMap.put("/fundAction-get", SecurityConstants.VIEW); activityMap.put("/fundAction-update", SecurityConstants.FUNDS_EDIT_FUNDS); activityMap.put("/fundAction-previous", SecurityConstants.FUNDS_CREATE_FUNDS); activityMap.put("/fundAction-manage", SecurityConstants.FUNDS_EDIT_FUNDS); // mapping for bulk entry activityMap.put("/bulkentryaction-load", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-preview", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-previous", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-get", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-getLastMeetingDateForCustomer", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-create", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-loadLoanOfficers", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-loadCustomerList", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-validate", SecurityConstants.VIEW); // removing fees activityMap.put("/accountAppAction-removeFees", SecurityConstants.LOAN_REMOVE_FEE_TYPE_ATTACHED_TO_ACCOUNT); activityMap.put("/accountAppAction-getTrxnHistory", SecurityConstants.VIEW); // mapping for savings account activityMap.put("/savingsAction-getPrdOfferings", SecurityConstants.VIEW); activityMap.put("/savingsAction-load", SecurityConstants.VIEW); activityMap.put("/savingsAction-reLoad", SecurityConstants.VIEW); activityMap.put("/savingsAction-preview", SecurityConstants.VIEW); activityMap.put("/savingsAction-previous", SecurityConstants.VIEW); activityMap.put("/savingsAction-create", SecurityConstants.VIEW); activityMap.put("/savingsAction-get", SecurityConstants.VIEW); activityMap.put("/savingsAction-getStatusHistory", SecurityConstants.VIEW); activityMap.put("/savingsAction-edit", SecurityConstants.SAVINGS_UPDATE_SAVINGS); activityMap.put("/savingsAction-editPreview", SecurityConstants.SAVINGS_UPDATE_SAVINGS); activityMap.put("/savingsAction-editPrevious", SecurityConstants.SAVINGS_UPDATE_SAVINGS); activityMap.put("/savingsAction-update", SecurityConstants.SAVINGS_UPDATE_SAVINGS); activityMap.put("/savingsAction-getRecentActivity", SecurityConstants.VIEW); activityMap.put("/savingsAction-getTransactionHistory", SecurityConstants.VIEW); activityMap.put("/savingsAction-getDepositDueDetails", SecurityConstants.VIEW); activityMap.put("/savingsAction-waiveAmountDue", SecurityConstants.SAVINGS_CANWAIVE_DUEAMOUNT); activityMap.put("/savingsAction-waiveAmountOverDue", SecurityConstants.SAVINGS_CANWAIVE_OVERDUEAMOUNT); // close savings account activityMap.put("/savingsClosureAction-load", SecurityConstants.SAVINGS_CLOSE_SAVINGS_ACCOUNT); activityMap.put("/savingsClosureAction-preview", SecurityConstants.SAVINGS_CLOSE_SAVINGS_ACCOUNT); activityMap.put("/savingsClosureAction-previous", SecurityConstants.SAVINGS_CLOSE_SAVINGS_ACCOUNT); activityMap.put("/savingsClosureAction-close", SecurityConstants.SAVINGS_CLOSE_SAVINGS_ACCOUNT); // savings accountadjustment activityMap.put("/savingsApplyAdjustmentAction-load", SecurityConstants.SAVINGS_APPLY_ADJUSTMENT); activityMap.put("/savingsApplyAdjustmentAction-preview", SecurityConstants.SAVINGS_APPLY_ADJUSTMENT); activityMap.put("/savingsApplyAdjustmentAction-previous", SecurityConstants.SAVINGS_APPLY_ADJUSTMENT); activityMap.put("/savingsApplyAdjustmentAction-adjustLastUserAction", SecurityConstants.SAVINGS_APPLY_ADJUSTMENT); // entries for apply adjustment. activityMap.put("/applyAdjustment-loadAdjustment", SecurityConstants.LOAN_MAKE_ADJUSTMENT_ENTRY_TO_ACCOUNT); activityMap.put("/applyAdjustment-previewAdjustment", SecurityConstants.LOAN_MAKE_ADJUSTMENT_ENTRY_TO_ACCOUNT); activityMap.put("/applyAdjustment-applyAdjustment", SecurityConstants.LOAN_MAKE_ADJUSTMENT_ENTRY_TO_ACCOUNT); activityMap.put("/applyAdjustment-cancelAdjustment", SecurityConstants.LOAN_MAKE_ADJUSTMENT_ENTRY_TO_ACCOUNT); // mapping for repaying loan account activityMap.put("/repayLoanAction-loadRepayment", SecurityConstants.LOAN_CAN_REPAY_LOAN); activityMap.put("/repayLoanAction-preview", SecurityConstants.LOAN_CAN_REPAY_LOAN); activityMap.put("/repayLoanAction-previous", SecurityConstants.LOAN_CAN_REPAY_LOAN); activityMap.put("/repayLoanAction-makeRepayment", SecurityConstants.LOAN_CAN_REPAY_LOAN); // mapping for reports activityMap.put("/reportsAction-load", SecurityConstants.VIEW); activityMap.put("/reportsAction-report_designer", SecurityConstants.CLIENTSDETAILVIEW); activityMap.put("/reportsAction-product_history", SecurityConstants.CLIENTSPRODUCTHISTORY); activityMap.put("/reportsAction-branch_performance", SecurityConstants.BRANCHPERFORMANCE); activityMap.put("/reportsAction-area_performance", SecurityConstants.AREAPERFORMANCE); activityMap.put("/reportsAction-collection_sheet", SecurityConstants.COLLECTIONSHEET); activityMap.put("/reportsAction-loan_distribution", SecurityConstants.LOANDISTRIBUTION); activityMap.put("/reportsAction-branch_disbursement", SecurityConstants.BRANCHDISBURSEMENT); activityMap.put("/reportsAction-staffwise_report", SecurityConstants.STAFFWISEREPORT); activityMap.put("/reportsAction-branchwise_report", SecurityConstants.BRANCHWISEREPORT); activityMap.put("/reportsAction-analysis", SecurityConstants.ANALYSIS); activityMap.put("/reportsAction-kendra_meeting", SecurityConstants.KENDRA_MEETING); activityMap.put("/reportsAction-administerreports_path", SecurityConstants.ADMINISTER_REPORTS); // entries for apply adjustment for customer. activityMap .put( "/custApplyAdjustment-loadAdjustment-Client", SecurityConstants.CIENT_MAKE_ADJUSTMENT_ENTRIES_TO_CLIENT_ACCOUNT); activityMap.put("/custApplyAdjustment-previewAdjustment-Client", SecurityConstants.VIEW); activityMap.put("/custApplyAdjustment-applyAdjustment-Client", SecurityConstants.VIEW); activityMap.put("/custApplyAdjustment-cancelAdjustment-Client", SecurityConstants.VIEW); activityMap .put( "/custApplyAdjustment-loadAdjustment-Group", SecurityConstants.GROUP_MAKE_ADJUSTMENT_ENTRIES_TO_GROUP_ACCOUNT); activityMap.put("/custApplyAdjustment-previewAdjustment-Group", SecurityConstants.VIEW); activityMap.put("/custApplyAdjustment-applyAdjustment-Group", SecurityConstants.VIEW); activityMap.put("/custApplyAdjustment-cancelAdjustment-Group", SecurityConstants.VIEW); activityMap .put( "/custApplyAdjustment-loadAdjustment-Center", SecurityConstants.CENTER_MAKE_ADJUSTMENT_ENTRIES_TO_CENTER_ACCOUNT); activityMap.put("/custApplyAdjustment-previewAdjustment-Center", SecurityConstants.VIEW); activityMap.put("/custApplyAdjustment-applyAdjustment-Center", SecurityConstants.VIEW); activityMap.put("/custApplyAdjustment-cancelAdjustment-Center", SecurityConstants.VIEW); activityMap.put("/customerAction-forwardWaiveChargeDue", SecurityConstants.VIEW); activityMap.put("/customerAction-forwardWaiveChargeOverDue", SecurityConstants.VIEW); activityMap.put("/customerAction-waiveChargeDue-Client", SecurityConstants.CIENT_WAIVE_FEE_INSTALLMENT); activityMap.put("/customerAction-waiveChargeOverDue-Client", SecurityConstants.CIENT_WAIVE_FEE_INSTALLMENT); activityMap.put("/customerAction-waiveChargeDue-Group", SecurityConstants.GROUP_WAIVE_FEE_INSTALLMENT); activityMap.put("/customerAction-waiveChargeOverDue-Group", SecurityConstants.GROUP_WAIVE_FEE_INSTALLMENT); activityMap.put("/customerAction-waiveChargeDue-Center", SecurityConstants.CENTER_WAIVE_FEE_INSTALLMENT); activityMap.put("/customerAction-waiveChargeOverDue-Center", SecurityConstants.CENTER_WAIVE_FEE_INSTALLMENT); activityMap.put("/customerAction-getAllActivity", SecurityConstants.VIEW); activityMap.put("/customerAction-getAllClosedAccounts", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-waiveChargeDue", SecurityConstants.LOAN_WAIVE_FEE_INSTALLMENT); activityMap.put("/loanAccountAction-waiveChargeDue", SecurityConstants.LOAN_WAIVE_PANELTY); activityMap.put("/loanAccountAction-forwardWaiveCharge", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-waiveChargeOverDue", SecurityConstants.LOAN_WAIVE_FEE_INSTALLMENT); activityMap.put("/loanAccountAction-waiveChargeOverDue", SecurityConstants.LOAN_WAIVE_PANELTY); // mapping for accountPayment activityMap.put("/applyPaymentAction-load-Loan", SecurityConstants.LOAN_MAKE_PAYMENT_TO_ACCOUNT); activityMap.put("/applyPaymentAction-load-Center", SecurityConstants.CENTER_MAKE_PAYMENTS_TO_CENTER_ACCOUNT); activityMap.put("/applyPaymentAction-load-Group", SecurityConstants.GROUP_MAKE_PAYMENT_TO_GROUP_ACCOUNT); activityMap.put("/applyPaymentAction-load-Client", SecurityConstants.CIENT_MAKE_PAYMENT_TO_CLIENT_ACCOUNT); activityMap.put("/applyPaymentAction-preview", SecurityConstants.VIEW); activityMap.put("/applyPaymentAction-previous",SecurityConstants.VIEW); activityMap.put("/applyPaymentAction-applyPayment",SecurityConstants.VIEW); //mapping fro loan disbursal activityMap.put("/loanDisbursmentAction-load", SecurityConstants.LOAN_CAN_DISBURSE_LOAN); activityMap.put("/loanDisbursmentAction-preview", SecurityConstants.VIEW); activityMap.put("/loanDisbursmentAction-previous",SecurityConstants.VIEW); activityMap.put("/loanDisbursmentAction-update",SecurityConstants.VIEW); //mapping for savings deposit/withdrawal activityMap.put("/savingsDepositWithdrawalAction-load", SecurityConstants.SAVINGS_CAN_MAKE_DEPOSIT_WITHDRAWAL); activityMap.put("/savingsDepositWithdrawalAction-reLoad", SecurityConstants.SAVINGS_CAN_MAKE_DEPOSIT_WITHDRAWAL); activityMap.put("/savingsDepositWithdrawalAction-preview", SecurityConstants.VIEW); activityMap.put("/savingsDepositWithdrawalAction-previous",SecurityConstants.VIEW); activityMap.put("/savingsDepositWithdrawalAction-makePayment",SecurityConstants.VIEW); // mapping for notes activityMap.put("/notesAction-load-Savings", SecurityConstants.SAVINGS_CAN_ADD_NOTES_TO_SAVINGS); activityMap.put("/notesAction-load-Loan", SecurityConstants.LOAN_CAN_ADD_NOTES_TO_LOAN); activityMap.put("/notesAction-preview", SecurityConstants.VIEW); activityMap.put("/notesAction-previous", SecurityConstants.VIEW); activityMap.put("/notesAction-get", SecurityConstants.VIEW); activityMap.put("/notesAction-search", SecurityConstants.VIEW); activityMap.put("/notesAction-create-Savings", SecurityConstants.SAVINGS_CAN_ADD_NOTES_TO_SAVINGS); //mapping for editing customer status activityMap.put("/editCustomerStatusAction-load-Center", SecurityConstants.CENTER_EDIT_STATUS); activityMap.put("/editCustomerStatusAction-preview", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-previous", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-update", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-load-Client", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-loadStatus-Group", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-previewStatus", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-previousStatus", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-updateStatus", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-cancelStatus", SecurityConstants.VIEW); activityMap.put("/notesAction-create-Loan", SecurityConstants.LOAN_CAN_ADD_NOTES_TO_LOAN); // apply charges activityMap.put("/applyChargeAction-load", SecurityConstants.VIEW); activityMap.put("/applyChargeAction-update", SecurityConstants.APPLY_CHARGES_TO_CLIENT_GROUP_CENTERS_LOANS); //mapping for adding customer notes activityMap.put("/customerNotesAction-load-Center", SecurityConstants.CENTER_ADD_NOTE_TO_CENTER); activityMap.put("/customerNotesAction-preview", SecurityConstants.VIEW); activityMap.put("/customerNotesAction-previous", SecurityConstants.VIEW); activityMap.put("/customerNotesAction-create", SecurityConstants.VIEW); activityMap.put("/customerNotesAction-search", SecurityConstants.VIEW); - activityMap.put("/customerNotesAction-load-Group", SecurityConstants.VIEW); - activityMap.put("/customerNotesAction-load-Client", SecurityConstants.VIEW); + activityMap.put("/customerNotesAction-load-Group", SecurityConstants.GROUP_ADD_NOTE_TO_GROUP); + activityMap.put("/customerNotesAction-load-Client", SecurityConstants.CLIENT_ADD_NOTE_TO_CLIENT); // client creation action- migration activityMap.put("/clientCustAction-load", SecurityConstants.VIEW); activityMap.put("/clientCustAction-chooseOffice", SecurityConstants.VIEW); activityMap.put("/clientCustAction-next", SecurityConstants.VIEW); activityMap .put("/clientCustAction-preview", SecurityConstants.VIEW); activityMap.put("/clientCustAction-previewPersonalInfo", SecurityConstants.VIEW); activityMap.put("/clientCustAction-retrievePictureOnPreview", SecurityConstants.VIEW); activityMap.put("/clientCustAction-prevPersonalInfo", SecurityConstants.VIEW); activityMap.put("/clientCustAction-prevMFIInfo", SecurityConstants.VIEW); activityMap.put("/clientCustAction-prevMeeting", SecurityConstants.VIEW); activityMap.put("/clientCustAction-create", SecurityConstants.VIEW); activityMap.put("/clientCustAction-loadMeeting-ClientCreate", SecurityConstants.MEETING_CREATE_CLIENT_MEETING); activityMap.put("/clientCustAction-get", SecurityConstants.VIEW); activityMap.put("/clientCustAction-editPersonalInfo", SecurityConstants.CLIENT_UPDATE_PERSONNEL_INFO); activityMap.put("/clientCustAction-previewEditPersonalInfo", SecurityConstants.VIEW); activityMap.put("/clientCustAction-prevEditPersonalInfo", SecurityConstants.VIEW); activityMap.put("/clientCustAction-updatePersonalInfo", SecurityConstants.CLIENT_UPDATE_PERSONNEL_INFO); activityMap.put("/clientCustAction-editMfiInfo", SecurityConstants.CIENT_EDIT_MFI_INFORMATION); activityMap.put("/clientCustAction-previewEditMfiInfo", SecurityConstants.VIEW); activityMap.put("/clientCustAction-prevEditMfiInfo", SecurityConstants.VIEW); activityMap.put("/clientCustAction-updateMfiInfo", SecurityConstants.CIENT_EDIT_MFI_INFORMATION); activityMap.put("/clientCustAction-loadMeeting-Client", SecurityConstants.MEETING_UPDATE_CLIENT_MEETING); activityMap.put("/clientCustAction-retrievePicture", SecurityConstants.VIEW); activityMap.put("/clientCustAction-showPicture", SecurityConstants.VIEW); activityMap.put("/ChangeAccountStatus-load", SecurityConstants.VIEW); activityMap.put("/ChangeAccountStatus-searchResults", SecurityConstants.VIEW); activityMap.put("/ChangeAccountStatus-update", SecurityConstants.VIEW); activityMap.put("/ChangeAccountStatus-getLoanOfficers", SecurityConstants.VIEW); // Group related mappings for M2 activityMap.put("/groupCustAction-hierarchyCheck", SecurityConstants.VIEW); activityMap.put("/groupCustAction-chooseOffice",SecurityConstants.VIEW); activityMap.put("/groupCustAction-load", SecurityConstants.VIEW); activityMap.put("/groupCustAction-loadMeeting-GroupCreate",SecurityConstants.MEETING_CREATE_GROUP_MEETING); activityMap.put("/groupCustAction-preview", SecurityConstants.VIEW); activityMap.put("/groupCustAction-previous", SecurityConstants.VIEW); activityMap.put("/groupCustAction-create", SecurityConstants.VIEW); activityMap.put("/groupCustAction-getDetails", SecurityConstants.VIEW); activityMap.put("/groupCustAction-get", SecurityConstants.VIEW); activityMap.put("/groupCustAction-manage",SecurityConstants.GROUP_EDIT_GROUP); activityMap.put("/groupCustAction-previewManage",SecurityConstants.VIEW); activityMap.put("/groupCustAction-previousManage",SecurityConstants.VIEW); activityMap.put("/groupCustAction-update",SecurityConstants.GROUP_EDIT_GROUP); // for your settings new action class activityMap.put("/yourSettings-get", SecurityConstants.VIEW); activityMap.put("/yourSettings-manage", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); activityMap.put("/yourSettings-preview", SecurityConstants.VIEW); activityMap.put("/yourSettings-previous", SecurityConstants.VIEW); activityMap.put("/yourSettings-update", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); activityMap.put("/yourSettings-loadChangePassword", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); //for CustomerAccountAction activityMap.put("/customerAccountAction-load", SecurityConstants.VIEW); } private static ActivityMapper instance = new ActivityMapper(); public static ActivityMapper getInstance() { return instance; } private Map<String, Short> activityMap = new HashMap<String, Short>(); public Short getActivityId(String key) { return activityMap.get(key); } public short getActivityIdForNewStateId(short newState, short cancelFlag) { short activityId = -1; switch (newState) { case AccountStates.SAVINGS_ACC_APPROVED: activityId = SAVING_CANCHANGESTATETO_APPROVED; break; case AccountStates.SAVINGS_ACC_CANCEL: switch (cancelFlag) { case SAVING_BLACKLISTED_FLAG: activityId = SAVING_CANCHANGESTATETO_INACTIVE_BLACKLISTED; break; default: activityId = SAVING_CANCHANGESTATETO_CANCEL; break; } break; case AccountStates.SAVINGS_ACC_INACTIVE: activityId = SAVING_CANCHANGESTATETO_INACTIVE; break; case AccountStates.SAVINGS_ACC_PARTIALAPPLICATION: activityId = SAVING_CANCHANGESTATETO_PARTIALAPPLICATION; break; case AccountStates.SAVINGS_ACC_PENDINGAPPROVAL: activityId = SAVING_CANCHANGESTATETO_PENDINGAPPROVAL; break; // loan mappings case AccountStates.LOANACC_ACTIVEINGOODSTANDING: activityId = LOANACC_CANCHANGETO_ACTIVEINGOODSTANDING; break; case AccountStates.LOANACC_APPROVED: activityId = LOANACC_CANCHANGETO_APPROVED; break; case AccountStates.LOANACC_BADSTANDING: activityId = LOANACC_CANCHANGETO_BADSTANDING; break; case AccountStates.LOANACC_CANCEL: activityId = LOANACC_CANCHANGETO_CANCEL; break; case AccountStates.LOANACC_DBTOLOANOFFICER: activityId = LOANACC_CANCHANGETO_DBTOLOANOFFICER; break; case AccountStates.LOANACC_OBLIGATIONSMET: activityId = LOANACC_CANCHANGETO_OBLIGATIONSMET; break; case AccountStates.LOANACC_PARTIALAPPLICATION: activityId = LOANACC_CANCHANGETO_PARTIALAPPLICATION; break; case AccountStates.LOANACC_PENDINGAPPROVAL: activityId = LOANACC_CANCHANGETO_PENDINGAPPROVAL; break; case AccountStates.LOANACC_RESCHEDULED: activityId = LOANACC_CANCHANGETO_RESCHEDULED; break; case AccountStates.LOANACC_WRITTENOFF: activityId = LOANACC_CANCHANGETO_WRITTENOFF; break; default: break; } return activityId; } public short getActivityIdForState(short state) { short activityId = -1; switch (state) { case AccountStates.SAVINGS_ACC_PARTIALAPPLICATION: activityId = SAVING_CANSAVEFORLATER; break; case AccountStates.SAVINGS_ACC_PENDINGAPPROVAL: case AccountStates.SAVINGS_ACC_APPROVED: activityId = SAVING_CANSUBMITFORAPPROVAL; break; case AccountStates.LOANACC_PARTIALAPPLICATION: activityId = LOANACC_CANSAVEFORLATER; break; case AccountStates.LOANACC_PENDINGAPPROVAL: case AccountStates.LOANACC_APPROVED: activityId = LOANACC_CANSUBMITFORAPPROVAL; break; default: break; } return activityId; } public short getActivityIdForNewCustomerStateId(short newState, short cancelFlag) { short activityId = -1; switch (newState) { case CustomerConstants.CLIENT_APPROVED: activityId = CLIENT_CANCHANGETO_APPROVED; break; case CustomerConstants.CLIENT_CANCELLED: switch (cancelFlag) { case CLIENT_BLACKLISTED_FLAG: activityId = CLIENT_CANCHANGETO_CANCEL_BLACKLISTED; break; default: activityId = CLIENT_CANCHANGETO_CANCELLED; break; } break; case CustomerConstants.CLIENT_CLOSED: switch (cancelFlag) { case CLIENT_CLOSED_BLACKLISTED_FLAG: activityId = CLIENT_CANCHANGETO_CANCEL_BLACKLISTED; break; default: activityId = CLIENT_CANCHANGETO_CLOSED; break; } break; case CustomerConstants.CLIENT_ONHOLD: activityId = CLIENT_CANCHANGETO_ONHOLD; break; case CustomerConstants.CLIENT_PARTIAL: activityId = CLIENT_CANCHANGETO_PARTIALAPPLICATION; break; case CustomerConstants.CLIENT_PENDING: activityId = CLIENT_CANCHANGETO_PENDINGAPPROVAL; break; // group mappings case GroupConstants.PARTIAL_APPLICATION: activityId = GROUP_CANCHANGETO_PARTIALAPPLICATION; break; case GroupConstants.CANCELLED: switch (cancelFlag) { case GROUP_CANCEL_BLACKLISTED_FLAG: activityId = GROUP_CANCHANGETO_CANCEL_BLACKLISTED; break; default: activityId = GROUP_CANCHANGETO_CANCELLED; break; } break; case GroupConstants.CLOSED: switch (cancelFlag) { case GROUP_CLOSED_BLACKLISTED_FLAG: activityId = GROUP_CANCHANGETO_CANCEL_BLACKLISTED; break; default: activityId = GROUP_CANCHANGETO_CLOSED; break; } break; case GroupConstants.HOLD: activityId = GROUP_CANCHANGETO_ONHOLD; break; case GroupConstants.PENDING_APPROVAL: activityId = GROUP_CANCHANGETO_PENDINGAPPROVAL; break; case GroupConstants.ACTIVE: activityId = GROUP_CANCHANGETO_APPROVED; break; default: break; } return activityId; } public short getActivityIdForCustomerState(short state) { short activityId = -1; switch (state) { case CustomerConstants.CLIENT_PARTIAL: activityId = CLIENT_CREATEPARTIAL; break; case CustomerConstants.CLIENT_PENDING: case CustomerConstants.CLIENT_APPROVED: activityId = CLIENT_CREATEPENDING; break; case GroupConstants.PARTIAL_APPLICATION: activityId = GROUP_CREATEPARTIAL; break; case GroupConstants.PENDING_APPROVAL: case GroupConstants.ACTIVE: activityId = GROUP_CREATEPENDING; break; default: break; } return activityId; } public Map<String, Short> getActivityMap() { return activityMap; } public void setActivityMap(Map<String, Short> activityMap) { this.activityMap = activityMap; } public boolean isStateChangePermittedForAccount(short newSate, short stateFlag, UserContext userContext, Short recordOfficeId, Short recordLoanOfficerId) { return AuthorizationManager.getInstance().isActivityAllowed( userContext, new ActivityContext(getActivityIdForNewStateId(newSate, stateFlag), recordOfficeId, recordLoanOfficerId)); } public boolean isStateChangePermittedForCustomer(short newSate, short stateFlag, UserContext userContext, Short recordOfficeId, Short recordLoanOfficerId) { return AuthorizationManager.getInstance().isActivityAllowed( userContext, new ActivityContext(getActivityIdForNewCustomerStateId(newSate, stateFlag), recordOfficeId, recordLoanOfficerId)); } public boolean isSavePermittedForAccount(short newSate, UserContext userContext, Short recordOfficeId, Short recordLoanOfficerId) { return AuthorizationManager.getInstance().isActivityAllowed( userContext, new ActivityContext(getActivityIdForState(newSate), recordOfficeId, recordLoanOfficerId)); } public boolean isSavePermittedForCustomer(short newSate, UserContext userContext, Short recordOfficeId, Short recordLoanOfficerId) { return AuthorizationManager.getInstance().isActivityAllowed( userContext, new ActivityContext(getActivityIdForCustomerState(newSate), recordOfficeId, recordLoanOfficerId)); } }
true
true
private ActivityMapper() { activityMap.put("/AdminAction-load", SecurityConstants.VIEW); // customer serach action activityMap.put("/CustomerSearchAction-load", SecurityConstants.VIEW); activityMap.put("/CustomerSearchAction-search", SecurityConstants.SEARCH); activityMap.put("/CustomerSearchAction-preview", SecurityConstants.SEARCH); activityMap.put("/CustomerSearchAction-get", SecurityConstants.SEARCH); activityMap.put("/CustomerSearchAction-getHomePage", SecurityConstants.VIEW); activityMap.put("/CustomerSearchAction-getOfficeHomePage", SecurityConstants.VIEW); activityMap.put("/CustomerSearchAction-loadAllBranches", SecurityConstants.VIEW); activityMap.put("/mifoslogout-logout", SecurityConstants.VIEW); // Change password related activityMap.put("/mifoslogin-update", SecurityConstants.VIEW); // Office related mapping activityMap.put("/OfficeAction-loadall", SecurityConstants.VIEW); activityMap.put("/OfficeAction-load", SecurityConstants.OFFICE_CREATE_OFFICE); activityMap.put("/OfficeAction-loadParent", SecurityConstants.VIEW); activityMap.put("/OfficeAction-preview", SecurityConstants.VIEW); activityMap.put("/OfficeAction-create", SecurityConstants.OFFICE_CREATE_OFFICE); activityMap.put("/OfficeAction-get", SecurityConstants.VIEW); activityMap.put("/OfficeAction-manage", SecurityConstants.OFFICE_EDIT_OFFICE); activityMap.put("/OfficeAction-previous", SecurityConstants.VIEW); activityMap.put("/OfficeAction-update", SecurityConstants.OFFICE_EDIT_OFFICE); activityMap .put("/OfficeHierarchyAction-cancel", SecurityConstants.VIEW); activityMap.put("/OfficeHierarchyAction-load", SecurityConstants.VIEW); activityMap.put("/OfficeHierarchyAction-update", SecurityConstants.OFFICE_EDIT_OFFICE); activityMap.put("/offhierarchyaction-cancel", SecurityConstants.VIEW); activityMap.put("/offhierarchyaction-load", SecurityConstants.VIEW); activityMap.put("/offhierarchyaction-update",SecurityConstants.OFFICE_EDIT_OFFICE); //m2 office action activityMap.put("/offAction-load", SecurityConstants.OFFICE_CREATE_OFFICE); activityMap.put("/offAction-loadParent", SecurityConstants.VIEW); activityMap.put("/offAction-preview", SecurityConstants.VIEW); activityMap.put("/offAction-previous", SecurityConstants.VIEW); activityMap.put("/offAction-create", SecurityConstants.OFFICE_CREATE_OFFICE); activityMap.put("/offAction-get", SecurityConstants.VIEW); activityMap.put("/offAction-edit", SecurityConstants.OFFICE_EDIT_OFFICE); activityMap.put("/offAction-editpreview", SecurityConstants.OFFICE_EDIT_OFFICE); activityMap.put("/offAction-editprevious", SecurityConstants.OFFICE_EDIT_OFFICE); activityMap.put("/offAction-update", SecurityConstants.OFFICE_EDIT_OFFICE); activityMap.put("/offAction-getAllOffices", SecurityConstants.VIEW); // roles and permission related mappings activityMap.put("/manageRolesAndPermission-manage", SecurityConstants.VIEW); activityMap .put("/manageRolesAndPermission-get", SecurityConstants.VIEW); activityMap.put("/manageRolesAndPermission-load", SecurityConstants.ROLES_CREATE_ROLES); activityMap.put("/manageRolesAndPermission-create", SecurityConstants.ROLES_CREATE_ROLES); activityMap.put("/manageRolesAndPermission-update", SecurityConstants.ROLES_EDIT_ROLES); activityMap.put("/manageRolesAndPermission-cancel", SecurityConstants.VIEW); activityMap.put("/manageRolesAndPermission-preview", SecurityConstants.ROLES_DELETE_ROLES); activityMap.put("/manageRolesAndPermission-delete", SecurityConstants.ROLES_DELETE_ROLES); // Group ralated mappings // activities related to create group activityMap.put("/GroupAction-chooseOffice", SecurityConstants.VIEW); activityMap.put("/GroupAction-hierarchyCheck", SecurityConstants.VIEW); activityMap.put("/GroupAction-load", SecurityConstants.VIEW); activityMap.put("/GroupAction-loadMeeting", SecurityConstants.MEETING_CREATE_GROUP_MEETING); activityMap.put("/GroupAction-setDefaultFormedByPersonnel", SecurityConstants.VIEW); activityMap.put("/GroupAction-previous", SecurityConstants.VIEW); activityMap.put("/GroupAction-preview", SecurityConstants.VIEW); activityMap.put("/GroupAction-create", SecurityConstants.VIEW); activityMap.put("/GroupAction-search", SecurityConstants.VIEW); // activities related to retrieve group for Group Module activityMap.put("/GroupAction-getDetails", SecurityConstants.VIEW); activityMap.put("/GroupAction-get", SecurityConstants.VIEW); // activities related to update group status for Group Module activityMap.put("/GroupAction-loadStatus", SecurityConstants.VIEW); activityMap.put("/GroupAction-updateStatus", SecurityConstants.VIEW); // activities related to update group for Group Module activityMap.put("/GroupAction-manage", SecurityConstants.GROUP_EDIT_GROUP); activityMap.put("/GroupAction-update", SecurityConstants.GROUP_EDIT_GROUP); // activities related to change center membership for Group Module activityMap.put("/GroupAction-loadParentTransfer", SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); activityMap.put("/GroupAction-confirmParentTransfer", SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); activityMap.put("/GroupAction-updateParent", SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); // activities related to change center membership for Group Module activityMap.put("/GroupAction-loadParentTransfer", SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); activityMap.put("/GroupAction-confirmParentTransfer", SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); activityMap.put("/GroupAction-updateParent", SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); // activities related to transfer the group for Group Module activityMap.put("/GroupAction-loadTransfer", SecurityConstants.GROUP_TRANSFER_THE_GROUP); activityMap.put("/GroupAction-confirmBranchTransfer", SecurityConstants.GROUP_TRANSFER_THE_GROUP); activityMap.put("/GroupAction-updateBranch", SecurityConstants.GROUP_TRANSFER_THE_GROUP); // apply charges activityMap.put("/closedaccsearchaction-search", SecurityConstants.GROUP_APPLY_CHARGES_TO_GROUP_ACCOUNT); activityMap.put("/GroupAction-loadSearch", SecurityConstants.VIEW); // Customer Notes related mapping // activityMap.put("/CustomerNoteAction-load",SecurityConstants.CUSTOMER_ADD_NOTES_TO_CENTER_GROUP_CLIENT); activityMap.put("/CustomerNoteAction-preview", SecurityConstants.VIEW); activityMap.put("/CustomerNoteAction-previous", SecurityConstants.VIEW); activityMap.put("/CustomerNoteAction-create", SecurityConstants.VIEW); activityMap.put("/CustomerNoteAction-get", SecurityConstants.VIEW); activityMap.put("/CustomerNoteAction-search", SecurityConstants.VIEW); // mapping for group activityMap.put("/CustomerNoteAction-load-Group", SecurityConstants.GROUP_ADD_NOTE_TO_GROUP); activityMap.put("/CustomerNoteAction-load-Client", SecurityConstants.CLIENT_ADD_NOTE_TO_CLIENT); activityMap.put("/CustomerNoteAction-load-Center", SecurityConstants.CENTER_ADD_NOTE_TO_CENTER); // Customer Historical Data related mapping activityMap.put("/CustomerHistoricalDataAction-load-Group", SecurityConstants.GROUP_ADD_EDIT_HISTORICAL_DATA); activityMap.put("/CustomerHistoricalDataAction-load-Client", SecurityConstants.CIENT_ADD_EDIT_HISTORICAL_DATA); activityMap.put("/CustomerHistoricalDataAction-get", SecurityConstants.VIEW); activityMap.put("/CustomerHistoricalDataAction-preview", SecurityConstants.VIEW); activityMap.put("/CustomerHistoricalDataAction-previous", SecurityConstants.VIEW); activityMap.put("/CustomerHistoricalDataAction-update", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-load-Group", SecurityConstants.GROUP_ADD_EDIT_HISTORICAL_DATA); activityMap.put("/custHistoricalDataAction-load-Client", SecurityConstants.CIENT_ADD_EDIT_HISTORICAL_DATA); activityMap.put("/custHistoricalDataAction-get", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-preview", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-previous", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-update", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-loadHistoricalData-Group", SecurityConstants.GROUP_ADD_EDIT_HISTORICAL_DATA); activityMap.put("/custHistoricalDataAction-loadHistoricalData-Client", SecurityConstants.CIENT_ADD_EDIT_HISTORICAL_DATA); activityMap.put("/custHistoricalDataAction-getHistoricalData", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-previewHistoricalData", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-previousHistoricalData", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-updateHistoricalData", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-cancelHistoricalData", SecurityConstants.VIEW); // personnel related mappings activityMap.put("/PersonnelAction-chooseOffice", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); activityMap.put("/PersonnelAction-load", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); activityMap.put("/PersonnelAction-preview", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-previous", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-create", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); activityMap.put("/PersonnelAction-get", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-manage", SecurityConstants.PERSONNEL_EDIT_PERSONNEL); activityMap.put("/PersonnelAction-update", SecurityConstants.PERSONNEL_EDIT_PERSONNEL); activityMap.put("/PersonnelAction-loadSearch", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-search", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-loadUnLockUser", SecurityConstants.PERSONNEL_UNLOCK_PERSONNEL); activityMap.put("/PersonnelAction-unLockUserAccount", SecurityConstants.PERSONNEL_UNLOCK_PERSONNEL); //m2 personnel related mappings activityMap.put("/PersonAction-get",SecurityConstants.VIEW); activityMap.put("/PersonAction-chooseOffice", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); activityMap.put("/PersonAction-load", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); activityMap.put("/PersonAction-manage", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); activityMap.put("/PersonAction-previewManage", SecurityConstants.VIEW); activityMap.put("/PersonAction-previousManage", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); activityMap.put("/PersonAction-update", SecurityConstants.PERSONNEL_EDIT_PERSONNEL); activityMap.put("/PersonnelAction-prevPersonalInfo", SecurityConstants.VIEW); activityMap.put("/PersonAction-preview", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); activityMap.put("/PersonAction-previous", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); activityMap.put("/PersonAction-create", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); // for your settings link activityMap.put("/PersonnelAction-getDetails", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-editPersonalInfo", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); activityMap.put("/PersonnelAction-previewPersonalInfo", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-prevPersonalInfo", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-updateSettings", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); activityMap.put("/PersonnelAction-loadChangePassword", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); activityMap.put("/PersonnelNotesAction-load", SecurityConstants.PERSONNEL_EDIT_PERSONNEL); activityMap .put("/PersonnelNotesAction-preview", SecurityConstants.VIEW); activityMap.put("/PersonnelNotesAction-previous", SecurityConstants.VIEW); activityMap.put("/PersonnelNotesAction-create", SecurityConstants.PERSONNEL_EDIT_PERSONNEL); activityMap.put("/PersonnelNotesAction-search", SecurityConstants.VIEW); activityMap.put("/PersonnelNotesAction-get", SecurityConstants.VIEW); //M2 personnel notes activityMap.put("/personnelNoteAction-load",SecurityConstants.PERSONNEL_EDIT_PERSONNEL); activityMap.put("/personnelNoteAction-preview", SecurityConstants.VIEW); activityMap.put("/personnelNoteAction-previous",SecurityConstants.VIEW); activityMap.put("/personnelNoteAction-create",SecurityConstants.VIEW); activityMap.put("/personnelNoteAction-search", SecurityConstants.VIEW); // center ralated mappings activityMap.put("/centerAction-chooseOffice", SecurityConstants.CENTER_CREATE_NEW_CENTER); activityMap.put("/centerAction-load", SecurityConstants.CENTER_CREATE_NEW_CENTER); activityMap.put("/centerAction-loadMeeting-CenterCreate", SecurityConstants.MEETING_CREATE_CENTER_MEETING); activityMap.put("/centerAction-loadMeeting-Center", SecurityConstants.MEETING_UPDATE_CENTER_MEETING); activityMap.put("/centerAction-getDetails", SecurityConstants.VIEW); activityMap.put("/centerAction-get", SecurityConstants.VIEW); activityMap.put("/centerAction-loadStatus", SecurityConstants.CENTER_EDIT_STATUS); activityMap.put("/centerAction-updateStatus", SecurityConstants.CENTER_EDIT_STATUS); activityMap .put( "/centerAction-manage", SecurityConstants.CENTER_MODIFY_CENTER_INFORMATION_AND_CHANGE_CENTER_STATUS); activityMap.put("/centerAction-previous", SecurityConstants.VIEW); activityMap.put("/centerAction-preview", SecurityConstants.VIEW); activityMap.put("/centerAction-create", SecurityConstants.CENTER_CREATE_NEW_CENTER); activityMap .put( "/centerAction-update", SecurityConstants.CENTER_MODIFY_CENTER_INFORMATION_AND_CHANGE_CENTER_STATUS); activityMap.put("/centerAction-loadSearch", SecurityConstants.VIEW); activityMap.put("/centerAction-search", SecurityConstants.VIEW); //For M2 Center ------------------------ activityMap.put("/centerCustAction-chooseOffice", SecurityConstants.CENTER_CREATE_NEW_CENTER); activityMap.put("/centerCustAction-load", SecurityConstants.CENTER_CREATE_NEW_CENTER); activityMap.put("/centerCustAction-loadMeeting-CenterCreate", SecurityConstants.MEETING_CREATE_CENTER_MEETING); activityMap.put("/centerCustAction-previous", SecurityConstants.VIEW); activityMap.put("/centerCustAction-preview", SecurityConstants.VIEW); activityMap.put("/centerCustAction-create", SecurityConstants.CENTER_CREATE_NEW_CENTER); activityMap.put( "/centerCustAction-manage", SecurityConstants.CENTER_MODIFY_CENTER_INFORMATION_AND_CHANGE_CENTER_STATUS); activityMap.put("/centerCustAction-editPrevious", SecurityConstants.VIEW); activityMap.put("/centerCustAction-editPreview", SecurityConstants.VIEW); activityMap.put( "/centerCustAction-update", SecurityConstants.CENTER_MODIFY_CENTER_INFORMATION_AND_CHANGE_CENTER_STATUS); activityMap.put("/centerCustAction-get", SecurityConstants.VIEW); // For M2 Center ends // colsed account searchaction in center details page activityMap .put("/closedaccsearchaction-search", SecurityConstants.VIEW); // CustomerSearch // activityMap.put("/CustomerSearchAction-validate",SecurityConstants.VIEW); // client creation action activityMap .put("/clientCreationAction-preLoad", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-load", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-chooseOffice", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-setDefaultFormedByPersonnel", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-next", SecurityConstants.VIEW); activityMap .put("/clientCreationAction-preview", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-prevPersonalInfo", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-prevMFIInfo", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-create", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-get", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-getDetails", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-loadStatus", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-loadTransfer", SecurityConstants.CIENT_CHANGE_GROUP_MEMBERSHIP); activityMap.put("/clientCreationAction-loadBranchTransfer", SecurityConstants.CIENT_TRANSFER_THE_CLIENT); activityMap.put("/clientCreationAction-editMFIInfo", SecurityConstants.CIENT_EDIT_MFI_INFORMATION); activityMap.put("/clientCreationAction-editPersonalInfo", SecurityConstants.CLIENT_UPDATE_PERSONNEL_INFO); activityMap.put("/clientCreationAction-update", SecurityConstants.CLIENT_UPDATE_PERSONNEL_INFO); activityMap.put("/clientCreationAction-updateMfi", SecurityConstants.CIENT_EDIT_MFI_INFORMATION); activityMap.put("/clientCreationAction-loadMeeting-ClientCreate", SecurityConstants.MEETING_CREATE_CLIENT_MEETING); activityMap.put("/clientCreationAction-loadMeeting-Client", SecurityConstants.MEETING_UPDATE_CLIENT_MEETING); activityMap.put("/clientCreationAction-previous", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-retrievePictureOnPreview", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-retrievePicture", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-showPicture", SecurityConstants.VIEW); activityMap .put( "/clientCreationAction-loadHistoricalData", SecurityConstants.CUSTOMER_ADD_HISTORICAL_DATA_TO_CENTER_GROUP_CLIENT); activityMap.put("/clientStatusAction-load", SecurityConstants.VIEW); activityMap.put("/clientStatusAction-preview", SecurityConstants.VIEW); activityMap.put("/clientStatusAction-previous", SecurityConstants.VIEW); activityMap.put("/clientStatusAction-update", SecurityConstants.VIEW); activityMap.put("/clientTransferAction-loadParents",SecurityConstants.CIENT_CHANGE_GROUP_MEMBERSHIP); activityMap.put("/clientTransferAction-loadBranches",SecurityConstants.CIENT_TRANSFER_THE_CLIENT); activityMap.put("/clientTransferAction-previewBranchTransfer",SecurityConstants.VIEW); activityMap.put("/clientTransferAction-previewParentTransfer",SecurityConstants.VIEW); activityMap.put("/clientTransferAction-updateParent", SecurityConstants.CIENT_CHANGE_GROUP_MEMBERSHIP); activityMap.put("/clientTransferAction-transferToBranch",SecurityConstants.CIENT_TRANSFER_THE_CLIENT); activityMap.put("/groupTransferAction-loadParents",SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); activityMap.put("/groupTransferAction-loadBranches",SecurityConstants.GROUP_TRANSFER_THE_GROUP); activityMap.put("/groupTransferAction-previewBranchTransfer",SecurityConstants.VIEW); activityMap.put("/groupTransferAction-previewParentTransfer",SecurityConstants.VIEW); activityMap.put("/groupTransferAction-transferToCenter", SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); activityMap.put("/groupTransferAction-transferToBranch",SecurityConstants.GROUP_TRANSFER_THE_GROUP); // meeting action activityMap.put("/MeetingAction-load", SecurityConstants.VIEW); activityMap.put("/MeetingAction-loadMeeting-Group", SecurityConstants.MEETING_UPDATE_GROUP_MEETING); activityMap.put("/MeetingAction-loadMeeting-Client", SecurityConstants.MEETING_UPDATE_CLIENT_MEETING); activityMap.put("/MeetingAction-create", SecurityConstants.VIEW); activityMap.put("/MeetingAction-get-Group", SecurityConstants.MEETING_UPDATE_GROUP_MEETING); activityMap.put("/MeetingAction-get-Client", SecurityConstants.MEETING_UPDATE_CLIENT_MEETING); activityMap.put("/MeetingAction-get-Center", SecurityConstants.MEETING_UPDATE_CENTER_MEETING); activityMap.put("/MeetingAction-update", SecurityConstants.VIEW); activityMap.put("/MeetingAction-preview", SecurityConstants.VIEW); activityMap.put("/MeetingAction-previous", SecurityConstants.VIEW); // product categories mapping activityMap.put("/productCategoryAction-load", SecurityConstants.DEFINE_NEW_PRODUCT_CATEGORIES); activityMap.put("/productCategoryAction-createPreview", SecurityConstants.VIEW); activityMap.put("/productCategoryAction-create", SecurityConstants.DEFINE_NEW_PRODUCT_CATEGORIES); activityMap.put("/productCategoryAction-get", SecurityConstants.VIEW); activityMap.put("/productCategoryAction-managePreview", SecurityConstants.VIEW); activityMap.put("/productCategoryAction-manage", SecurityConstants.EDIT_PRODUCT_CATEGORIES); activityMap.put("/productCategoryAction-update", SecurityConstants.EDIT_PRODUCT_CATEGORIES); activityMap.put("/productCategoryAction-getAllCategories", SecurityConstants.VIEW); activityMap.put("/productCategoryAction-createPrevious", SecurityConstants.VIEW); activityMap.put("/productCategoryAction-managePrevious", SecurityConstants.VIEW); // saving product mappeings activityMap.put("/savingsprdaction-search", SecurityConstants.VIEW); activityMap.put("/savingsprdaction-load", SecurityConstants.DEFINE_NEW_SAVING_PRODUCT_INSTANCE); activityMap.put("/savingsprdaction-preview", SecurityConstants.VIEW); activityMap.put("/savingsprdaction-previous", SecurityConstants.VIEW); activityMap.put("/savingsprdaction-create", SecurityConstants.DEFINE_NEW_SAVING_PRODUCT_INSTANCE); activityMap.put("/savingsprdaction-get", SecurityConstants.VIEW); activityMap.put("/savingsprdaction-manage", SecurityConstants.EDIT_SAVING_PRODUCT); activityMap.put("/savingsprdaction-update", SecurityConstants.EDIT_SAVING_PRODUCT); activityMap.put("/savingsproductaction-search", SecurityConstants.VIEW); activityMap.put("/savingsproductaction-load", SecurityConstants.DEFINE_NEW_SAVING_PRODUCT_INSTANCE); activityMap.put("/savingsproductaction-preview", SecurityConstants.VIEW); activityMap.put("/savingsproductaction-previous", SecurityConstants.VIEW); activityMap.put("/savingsproductaction-create", SecurityConstants.DEFINE_NEW_SAVING_PRODUCT_INSTANCE); activityMap.put("/savingsproductaction-get", SecurityConstants.VIEW); activityMap.put("/savingsproductaction-cancelCreate", SecurityConstants.VIEW); activityMap.put("/savingsproductaction-manage", SecurityConstants.EDIT_SAVING_PRODUCT); activityMap.put("/savingsproductaction-update", SecurityConstants.EDIT_SAVING_PRODUCT); // view lateness mappings activityMap.put("/prdconfigurationaction-search", SecurityConstants.VIEW); activityMap.put("/prdconfigurationaction-update", SecurityConstants.EDIT_PRODUCT_CATEGORIES); // loan product categories activityMap.put("/loanprdaction-load", SecurityConstants.DEFINE_NEW_LOAN_PRODUCT_INSTANCE); activityMap.put("/loanprdaction-preview", SecurityConstants.VIEW); activityMap.put("/loanprdaction-previous", SecurityConstants.VIEW); activityMap.put("/loanprdaction-create", SecurityConstants.DEFINE_NEW_LOAN_PRODUCT_INSTANCE); activityMap.put("/loanprdaction-search", SecurityConstants.VIEW); activityMap.put("/loanprdaction-get", SecurityConstants.VIEW); activityMap.put("/loanprdaction-manage", SecurityConstants.EDIT_LOAN_PRODUCT); activityMap.put("/loanprdaction-update", SecurityConstants.EDIT_LOAN_PRODUCT); // Fee mapping activityMap.put("/feesAction-search", SecurityConstants.VIEW); activityMap.put("/feesAction-load", SecurityConstants.FEES_CREATE_FEES); activityMap.put("/feesAction-preview", SecurityConstants.VIEW); activityMap.put("/feesAction-create", SecurityConstants.FEES_CREATE_FEES); activityMap.put("/feesAction-get", SecurityConstants.VIEW); activityMap.put("/feesAction-manage", SecurityConstants.FEES_EDIT_FEES); activityMap.put("/feesAction-update", SecurityConstants.FEES_EDIT_FEES); activityMap.put("/feesAction-previous", SecurityConstants.VIEW); activityMap.put("/feeaction-search", SecurityConstants.VIEW); activityMap.put("/feeaction-load", SecurityConstants.FEES_CREATE_FEES); activityMap.put("/feeaction-preview", SecurityConstants.VIEW); activityMap.put("/feeaction-editPreview", SecurityConstants.VIEW); activityMap .put("/feeaction-create", SecurityConstants.FEES_CREATE_FEES); activityMap.put("/feeaction-get", SecurityConstants.VIEW); activityMap.put("/feeaction-manage", SecurityConstants.FEES_EDIT_FEES); activityMap.put("/feeaction-update", SecurityConstants.FEES_EDIT_FEES); activityMap.put("/feeaction-previous", SecurityConstants.VIEW); activityMap.put("/feeaction-editPrevious", SecurityConstants.VIEW); activityMap.put("/feeaction-viewAll", SecurityConstants.VIEW); activityMap.put("/feeaction-cancelCreate", SecurityConstants.VIEW); activityMap.put("/feeaction-cancelEdit", SecurityConstants.VIEW); // checklist mapping activityMap.put("/checkListAction-loadall", SecurityConstants.VIEW); activityMap.put("/checkListAction-load", SecurityConstants.CHECKLIST_CREATE_CHECKLIST); activityMap.put("/checkListAction-create", SecurityConstants.CHECKLIST_CREATE_CHECKLIST); activityMap.put("/checkListAction-preview", SecurityConstants.VIEW); activityMap.put("/checkListAction-previous", SecurityConstants.VIEW); activityMap.put("/checkListAction-previous", SecurityConstants.CHECKLIST_CREATE_CHECKLIST); activityMap.put("/checkListAction-loadParent", SecurityConstants.VIEW); activityMap.put("/checkListAction-get", SecurityConstants.VIEW); activityMap.put("/checkListAction-manage", SecurityConstants.CHECKLIST_EDIT_CHECKLIST); activityMap.put("/checkListAction-update", SecurityConstants.CHECKLIST_EDIT_CHECKLIST); // mapping for search before loan activityMap.put("/AccountsSearchAction-load", SecurityConstants.VIEW); activityMap.put("/AccountsSearchAction-search", SecurityConstants.VIEW); // mapping for loan activityMap.put("/loanAction-getPrdOfferings", SecurityConstants.VIEW); activityMap.put("/loanAction-load", SecurityConstants.VIEW); activityMap.put("/loanAction-next", SecurityConstants.VIEW); activityMap.put("/loanAction-preview", SecurityConstants.VIEW); activityMap.put("/loanAction-previous", SecurityConstants.VIEW); activityMap.put("/loanAction-get", SecurityConstants.VIEW); activityMap.put("/loanAction-manage", SecurityConstants.LOAN_UPDATE_LOAN); activityMap.put("/loanAction-update", SecurityConstants.LOAN_UPDATE_LOAN); activityMap.put("/loanAction-getLoanChangeLog", SecurityConstants.VIEW); activityMap.put("/loanAction-search", SecurityConstants.VIEW); activityMap.put("/loanAction-create", SecurityConstants.VIEW); // mapping for loanActivity activityMap.put("/loanAccountAction-getAllActivity", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-get",SecurityConstants.VIEW); activityMap.put("/loanAccountAction-getLoanRepaymentSchedule",SecurityConstants.VIEW); activityMap.put("/loanAccountAction-viewStatusHistory", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-manage", SecurityConstants.LOAN_UPDATE_LOAN); activityMap.put("/loanAccountAction-managePreview",SecurityConstants.VIEW); activityMap.put("/loanAccountAction-managePrevious",SecurityConstants.VIEW); activityMap.put("/loanAccountAction-cancel",SecurityConstants.VIEW); activityMap.put("/loanAccountAction-update", SecurityConstants.LOAN_UPDATE_LOAN); activityMap.put("/loanAccountAction-getPrdOfferings", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-load", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-schedulePreview", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-preview", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-previous", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-create", SecurityConstants.VIEW); // mapping for account status::TO BE REMOVED activityMap.put("/LoanStatusAction-load", SecurityConstants.VIEW); activityMap.put("/LoanStatusAction-preview", SecurityConstants.VIEW); activityMap.put("/LoanStatusAction-previous", SecurityConstants.VIEW); activityMap.put("/LoanStatusAction-update", SecurityConstants.VIEW); activityMap.put("/LoanStatusAction-search", SecurityConstants.VIEW); activityMap.put("/LoanStatusAction-writeOff", SecurityConstants.VIEW); // mapping for account status activityMap.put("/editStatusAction-load", SecurityConstants.VIEW); activityMap.put("/editStatusAction-preview", SecurityConstants.VIEW); activityMap.put("/editStatusAction-previous", SecurityConstants.VIEW); activityMap.put("/editStatusAction-update", SecurityConstants.VIEW); //mapping for custAction activityMap.put("/custAction-getClosedAccounts", SecurityConstants.VIEW); activityMap.put("/custAction-getBackToDetailsPage", SecurityConstants.VIEW); // mapping for account notes activityMap.put("/AccountNotesAction-load", SecurityConstants.LOAN_CAN_ADD_NOTES_TO_LOAN); activityMap.put("/AccountNotesAction-preview", SecurityConstants.VIEW); activityMap.put("/AccountNotesAction-previous", SecurityConstants.VIEW); activityMap.put("/AccountNotesAction-get", SecurityConstants.VIEW); activityMap.put("/AccountNotesAction-search", SecurityConstants.VIEW); activityMap.put("/AccountNotesAction-create", SecurityConstants.LOAN_CAN_ADD_NOTES_TO_LOAN); // mapping for apply payment activityMap.put("/accountTrxn-load", SecurityConstants.APPLY_PAYMENT_TO_CLIENT_GROUP_CENTERS_LOANS); activityMap.put("/accountTrxn-create", SecurityConstants.APPLY_PAYMENT_TO_CLIENT_GROUP_CENTERS_LOANS); activityMap.put("/accountTrxn-preview", SecurityConstants.VIEW); activityMap.put("/accountTrxn-getInstallmentHistory", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-getInstallmentDetails", SecurityConstants.VIEW); activityMap.put("/accountTrxn-previous", SecurityConstants.VIEW); // apply charges activityMap.put("/AccountsApplyChargesAction-load", SecurityConstants.APPLY_CHARGES_TO_CLIENT_GROUP_CENTERS_LOANS); activityMap.put("/AccountsApplyChargesAction-create", SecurityConstants.APPLY_CHARGES_TO_CLIENT_GROUP_CENTERS_LOANS); // fund mapping activityMap.put("/fundAction-load", SecurityConstants.FUNDS_CREATE_FUNDS); activityMap.put("/fundAction-create", SecurityConstants.FUNDS_CREATE_FUNDS); activityMap.put("/fundAction-preview", SecurityConstants.VIEW); activityMap.put("/fundAction-getAllFunds", SecurityConstants.VIEW); activityMap.put("/fundAction-get", SecurityConstants.VIEW); activityMap.put("/fundAction-update", SecurityConstants.FUNDS_EDIT_FUNDS); activityMap.put("/fundAction-previous", SecurityConstants.FUNDS_CREATE_FUNDS); activityMap.put("/fundAction-manage", SecurityConstants.FUNDS_EDIT_FUNDS); // mapping for bulk entry activityMap.put("/bulkentryaction-load", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-preview", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-previous", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-get", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-getLastMeetingDateForCustomer", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-create", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-loadLoanOfficers", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-loadCustomerList", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-validate", SecurityConstants.VIEW); // removing fees activityMap.put("/accountAppAction-removeFees", SecurityConstants.LOAN_REMOVE_FEE_TYPE_ATTACHED_TO_ACCOUNT); activityMap.put("/accountAppAction-getTrxnHistory", SecurityConstants.VIEW); // mapping for savings account activityMap.put("/savingsAction-getPrdOfferings", SecurityConstants.VIEW); activityMap.put("/savingsAction-load", SecurityConstants.VIEW); activityMap.put("/savingsAction-reLoad", SecurityConstants.VIEW); activityMap.put("/savingsAction-preview", SecurityConstants.VIEW); activityMap.put("/savingsAction-previous", SecurityConstants.VIEW); activityMap.put("/savingsAction-create", SecurityConstants.VIEW); activityMap.put("/savingsAction-get", SecurityConstants.VIEW); activityMap.put("/savingsAction-getStatusHistory", SecurityConstants.VIEW); activityMap.put("/savingsAction-edit", SecurityConstants.SAVINGS_UPDATE_SAVINGS); activityMap.put("/savingsAction-editPreview", SecurityConstants.SAVINGS_UPDATE_SAVINGS); activityMap.put("/savingsAction-editPrevious", SecurityConstants.SAVINGS_UPDATE_SAVINGS); activityMap.put("/savingsAction-update", SecurityConstants.SAVINGS_UPDATE_SAVINGS); activityMap.put("/savingsAction-getRecentActivity", SecurityConstants.VIEW); activityMap.put("/savingsAction-getTransactionHistory", SecurityConstants.VIEW); activityMap.put("/savingsAction-getDepositDueDetails", SecurityConstants.VIEW); activityMap.put("/savingsAction-waiveAmountDue", SecurityConstants.SAVINGS_CANWAIVE_DUEAMOUNT); activityMap.put("/savingsAction-waiveAmountOverDue", SecurityConstants.SAVINGS_CANWAIVE_OVERDUEAMOUNT); // close savings account activityMap.put("/savingsClosureAction-load", SecurityConstants.SAVINGS_CLOSE_SAVINGS_ACCOUNT); activityMap.put("/savingsClosureAction-preview", SecurityConstants.SAVINGS_CLOSE_SAVINGS_ACCOUNT); activityMap.put("/savingsClosureAction-previous", SecurityConstants.SAVINGS_CLOSE_SAVINGS_ACCOUNT); activityMap.put("/savingsClosureAction-close", SecurityConstants.SAVINGS_CLOSE_SAVINGS_ACCOUNT); // savings accountadjustment activityMap.put("/savingsApplyAdjustmentAction-load", SecurityConstants.SAVINGS_APPLY_ADJUSTMENT); activityMap.put("/savingsApplyAdjustmentAction-preview", SecurityConstants.SAVINGS_APPLY_ADJUSTMENT); activityMap.put("/savingsApplyAdjustmentAction-previous", SecurityConstants.SAVINGS_APPLY_ADJUSTMENT); activityMap.put("/savingsApplyAdjustmentAction-adjustLastUserAction", SecurityConstants.SAVINGS_APPLY_ADJUSTMENT); // entries for apply adjustment. activityMap.put("/applyAdjustment-loadAdjustment", SecurityConstants.LOAN_MAKE_ADJUSTMENT_ENTRY_TO_ACCOUNT); activityMap.put("/applyAdjustment-previewAdjustment", SecurityConstants.LOAN_MAKE_ADJUSTMENT_ENTRY_TO_ACCOUNT); activityMap.put("/applyAdjustment-applyAdjustment", SecurityConstants.LOAN_MAKE_ADJUSTMENT_ENTRY_TO_ACCOUNT); activityMap.put("/applyAdjustment-cancelAdjustment", SecurityConstants.LOAN_MAKE_ADJUSTMENT_ENTRY_TO_ACCOUNT); // mapping for repaying loan account activityMap.put("/repayLoanAction-loadRepayment", SecurityConstants.LOAN_CAN_REPAY_LOAN); activityMap.put("/repayLoanAction-preview", SecurityConstants.LOAN_CAN_REPAY_LOAN); activityMap.put("/repayLoanAction-previous", SecurityConstants.LOAN_CAN_REPAY_LOAN); activityMap.put("/repayLoanAction-makeRepayment", SecurityConstants.LOAN_CAN_REPAY_LOAN); // mapping for reports activityMap.put("/reportsAction-load", SecurityConstants.VIEW); activityMap.put("/reportsAction-report_designer", SecurityConstants.CLIENTSDETAILVIEW); activityMap.put("/reportsAction-product_history", SecurityConstants.CLIENTSPRODUCTHISTORY); activityMap.put("/reportsAction-branch_performance", SecurityConstants.BRANCHPERFORMANCE); activityMap.put("/reportsAction-area_performance", SecurityConstants.AREAPERFORMANCE); activityMap.put("/reportsAction-collection_sheet", SecurityConstants.COLLECTIONSHEET); activityMap.put("/reportsAction-loan_distribution", SecurityConstants.LOANDISTRIBUTION); activityMap.put("/reportsAction-branch_disbursement", SecurityConstants.BRANCHDISBURSEMENT); activityMap.put("/reportsAction-staffwise_report", SecurityConstants.STAFFWISEREPORT); activityMap.put("/reportsAction-branchwise_report", SecurityConstants.BRANCHWISEREPORT); activityMap.put("/reportsAction-analysis", SecurityConstants.ANALYSIS); activityMap.put("/reportsAction-kendra_meeting", SecurityConstants.KENDRA_MEETING); activityMap.put("/reportsAction-administerreports_path", SecurityConstants.ADMINISTER_REPORTS); // entries for apply adjustment for customer. activityMap .put( "/custApplyAdjustment-loadAdjustment-Client", SecurityConstants.CIENT_MAKE_ADJUSTMENT_ENTRIES_TO_CLIENT_ACCOUNT); activityMap.put("/custApplyAdjustment-previewAdjustment-Client", SecurityConstants.VIEW); activityMap.put("/custApplyAdjustment-applyAdjustment-Client", SecurityConstants.VIEW); activityMap.put("/custApplyAdjustment-cancelAdjustment-Client", SecurityConstants.VIEW); activityMap .put( "/custApplyAdjustment-loadAdjustment-Group", SecurityConstants.GROUP_MAKE_ADJUSTMENT_ENTRIES_TO_GROUP_ACCOUNT); activityMap.put("/custApplyAdjustment-previewAdjustment-Group", SecurityConstants.VIEW); activityMap.put("/custApplyAdjustment-applyAdjustment-Group", SecurityConstants.VIEW); activityMap.put("/custApplyAdjustment-cancelAdjustment-Group", SecurityConstants.VIEW); activityMap .put( "/custApplyAdjustment-loadAdjustment-Center", SecurityConstants.CENTER_MAKE_ADJUSTMENT_ENTRIES_TO_CENTER_ACCOUNT); activityMap.put("/custApplyAdjustment-previewAdjustment-Center", SecurityConstants.VIEW); activityMap.put("/custApplyAdjustment-applyAdjustment-Center", SecurityConstants.VIEW); activityMap.put("/custApplyAdjustment-cancelAdjustment-Center", SecurityConstants.VIEW); activityMap.put("/customerAction-forwardWaiveChargeDue", SecurityConstants.VIEW); activityMap.put("/customerAction-forwardWaiveChargeOverDue", SecurityConstants.VIEW); activityMap.put("/customerAction-waiveChargeDue-Client", SecurityConstants.CIENT_WAIVE_FEE_INSTALLMENT); activityMap.put("/customerAction-waiveChargeOverDue-Client", SecurityConstants.CIENT_WAIVE_FEE_INSTALLMENT); activityMap.put("/customerAction-waiveChargeDue-Group", SecurityConstants.GROUP_WAIVE_FEE_INSTALLMENT); activityMap.put("/customerAction-waiveChargeOverDue-Group", SecurityConstants.GROUP_WAIVE_FEE_INSTALLMENT); activityMap.put("/customerAction-waiveChargeDue-Center", SecurityConstants.CENTER_WAIVE_FEE_INSTALLMENT); activityMap.put("/customerAction-waiveChargeOverDue-Center", SecurityConstants.CENTER_WAIVE_FEE_INSTALLMENT); activityMap.put("/customerAction-getAllActivity", SecurityConstants.VIEW); activityMap.put("/customerAction-getAllClosedAccounts", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-waiveChargeDue", SecurityConstants.LOAN_WAIVE_FEE_INSTALLMENT); activityMap.put("/loanAccountAction-waiveChargeDue", SecurityConstants.LOAN_WAIVE_PANELTY); activityMap.put("/loanAccountAction-forwardWaiveCharge", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-waiveChargeOverDue", SecurityConstants.LOAN_WAIVE_FEE_INSTALLMENT); activityMap.put("/loanAccountAction-waiveChargeOverDue", SecurityConstants.LOAN_WAIVE_PANELTY); // mapping for accountPayment activityMap.put("/applyPaymentAction-load-Loan", SecurityConstants.LOAN_MAKE_PAYMENT_TO_ACCOUNT); activityMap.put("/applyPaymentAction-load-Center", SecurityConstants.CENTER_MAKE_PAYMENTS_TO_CENTER_ACCOUNT); activityMap.put("/applyPaymentAction-load-Group", SecurityConstants.GROUP_MAKE_PAYMENT_TO_GROUP_ACCOUNT); activityMap.put("/applyPaymentAction-load-Client", SecurityConstants.CIENT_MAKE_PAYMENT_TO_CLIENT_ACCOUNT); activityMap.put("/applyPaymentAction-preview", SecurityConstants.VIEW); activityMap.put("/applyPaymentAction-previous",SecurityConstants.VIEW); activityMap.put("/applyPaymentAction-applyPayment",SecurityConstants.VIEW); //mapping fro loan disbursal activityMap.put("/loanDisbursmentAction-load", SecurityConstants.LOAN_CAN_DISBURSE_LOAN); activityMap.put("/loanDisbursmentAction-preview", SecurityConstants.VIEW); activityMap.put("/loanDisbursmentAction-previous",SecurityConstants.VIEW); activityMap.put("/loanDisbursmentAction-update",SecurityConstants.VIEW); //mapping for savings deposit/withdrawal activityMap.put("/savingsDepositWithdrawalAction-load", SecurityConstants.SAVINGS_CAN_MAKE_DEPOSIT_WITHDRAWAL); activityMap.put("/savingsDepositWithdrawalAction-reLoad", SecurityConstants.SAVINGS_CAN_MAKE_DEPOSIT_WITHDRAWAL); activityMap.put("/savingsDepositWithdrawalAction-preview", SecurityConstants.VIEW); activityMap.put("/savingsDepositWithdrawalAction-previous",SecurityConstants.VIEW); activityMap.put("/savingsDepositWithdrawalAction-makePayment",SecurityConstants.VIEW); // mapping for notes activityMap.put("/notesAction-load-Savings", SecurityConstants.SAVINGS_CAN_ADD_NOTES_TO_SAVINGS); activityMap.put("/notesAction-load-Loan", SecurityConstants.LOAN_CAN_ADD_NOTES_TO_LOAN); activityMap.put("/notesAction-preview", SecurityConstants.VIEW); activityMap.put("/notesAction-previous", SecurityConstants.VIEW); activityMap.put("/notesAction-get", SecurityConstants.VIEW); activityMap.put("/notesAction-search", SecurityConstants.VIEW); activityMap.put("/notesAction-create-Savings", SecurityConstants.SAVINGS_CAN_ADD_NOTES_TO_SAVINGS); //mapping for editing customer status activityMap.put("/editCustomerStatusAction-load-Center", SecurityConstants.CENTER_EDIT_STATUS); activityMap.put("/editCustomerStatusAction-preview", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-previous", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-update", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-load-Client", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-loadStatus-Group", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-previewStatus", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-previousStatus", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-updateStatus", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-cancelStatus", SecurityConstants.VIEW); activityMap.put("/notesAction-create-Loan", SecurityConstants.LOAN_CAN_ADD_NOTES_TO_LOAN); // apply charges activityMap.put("/applyChargeAction-load", SecurityConstants.VIEW); activityMap.put("/applyChargeAction-update", SecurityConstants.APPLY_CHARGES_TO_CLIENT_GROUP_CENTERS_LOANS); //mapping for adding customer notes activityMap.put("/customerNotesAction-load-Center", SecurityConstants.CENTER_ADD_NOTE_TO_CENTER); activityMap.put("/customerNotesAction-preview", SecurityConstants.VIEW); activityMap.put("/customerNotesAction-previous", SecurityConstants.VIEW); activityMap.put("/customerNotesAction-create", SecurityConstants.VIEW); activityMap.put("/customerNotesAction-search", SecurityConstants.VIEW); activityMap.put("/customerNotesAction-load-Group", SecurityConstants.VIEW); activityMap.put("/customerNotesAction-load-Client", SecurityConstants.VIEW); // client creation action- migration activityMap.put("/clientCustAction-load", SecurityConstants.VIEW); activityMap.put("/clientCustAction-chooseOffice", SecurityConstants.VIEW); activityMap.put("/clientCustAction-next", SecurityConstants.VIEW); activityMap .put("/clientCustAction-preview", SecurityConstants.VIEW); activityMap.put("/clientCustAction-previewPersonalInfo", SecurityConstants.VIEW); activityMap.put("/clientCustAction-retrievePictureOnPreview", SecurityConstants.VIEW); activityMap.put("/clientCustAction-prevPersonalInfo", SecurityConstants.VIEW); activityMap.put("/clientCustAction-prevMFIInfo", SecurityConstants.VIEW); activityMap.put("/clientCustAction-prevMeeting", SecurityConstants.VIEW); activityMap.put("/clientCustAction-create", SecurityConstants.VIEW); activityMap.put("/clientCustAction-loadMeeting-ClientCreate", SecurityConstants.MEETING_CREATE_CLIENT_MEETING); activityMap.put("/clientCustAction-get", SecurityConstants.VIEW); activityMap.put("/clientCustAction-editPersonalInfo", SecurityConstants.CLIENT_UPDATE_PERSONNEL_INFO); activityMap.put("/clientCustAction-previewEditPersonalInfo", SecurityConstants.VIEW); activityMap.put("/clientCustAction-prevEditPersonalInfo", SecurityConstants.VIEW); activityMap.put("/clientCustAction-updatePersonalInfo", SecurityConstants.CLIENT_UPDATE_PERSONNEL_INFO); activityMap.put("/clientCustAction-editMfiInfo", SecurityConstants.CIENT_EDIT_MFI_INFORMATION); activityMap.put("/clientCustAction-previewEditMfiInfo", SecurityConstants.VIEW); activityMap.put("/clientCustAction-prevEditMfiInfo", SecurityConstants.VIEW); activityMap.put("/clientCustAction-updateMfiInfo", SecurityConstants.CIENT_EDIT_MFI_INFORMATION); activityMap.put("/clientCustAction-loadMeeting-Client", SecurityConstants.MEETING_UPDATE_CLIENT_MEETING); activityMap.put("/clientCustAction-retrievePicture", SecurityConstants.VIEW); activityMap.put("/clientCustAction-showPicture", SecurityConstants.VIEW); activityMap.put("/ChangeAccountStatus-load", SecurityConstants.VIEW); activityMap.put("/ChangeAccountStatus-searchResults", SecurityConstants.VIEW); activityMap.put("/ChangeAccountStatus-update", SecurityConstants.VIEW); activityMap.put("/ChangeAccountStatus-getLoanOfficers", SecurityConstants.VIEW); // Group related mappings for M2 activityMap.put("/groupCustAction-hierarchyCheck", SecurityConstants.VIEW); activityMap.put("/groupCustAction-chooseOffice",SecurityConstants.VIEW); activityMap.put("/groupCustAction-load", SecurityConstants.VIEW); activityMap.put("/groupCustAction-loadMeeting-GroupCreate",SecurityConstants.MEETING_CREATE_GROUP_MEETING); activityMap.put("/groupCustAction-preview", SecurityConstants.VIEW); activityMap.put("/groupCustAction-previous", SecurityConstants.VIEW); activityMap.put("/groupCustAction-create", SecurityConstants.VIEW); activityMap.put("/groupCustAction-getDetails", SecurityConstants.VIEW); activityMap.put("/groupCustAction-get", SecurityConstants.VIEW); activityMap.put("/groupCustAction-manage",SecurityConstants.GROUP_EDIT_GROUP); activityMap.put("/groupCustAction-previewManage",SecurityConstants.VIEW); activityMap.put("/groupCustAction-previousManage",SecurityConstants.VIEW); activityMap.put("/groupCustAction-update",SecurityConstants.GROUP_EDIT_GROUP); // for your settings new action class activityMap.put("/yourSettings-get", SecurityConstants.VIEW); activityMap.put("/yourSettings-manage", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); activityMap.put("/yourSettings-preview", SecurityConstants.VIEW); activityMap.put("/yourSettings-previous", SecurityConstants.VIEW); activityMap.put("/yourSettings-update", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); activityMap.put("/yourSettings-loadChangePassword", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); //for CustomerAccountAction activityMap.put("/customerAccountAction-load", SecurityConstants.VIEW); }
private ActivityMapper() { activityMap.put("/AdminAction-load", SecurityConstants.VIEW); // customer serach action activityMap.put("/CustomerSearchAction-load", SecurityConstants.VIEW); activityMap.put("/CustomerSearchAction-search", SecurityConstants.SEARCH); activityMap.put("/CustomerSearchAction-preview", SecurityConstants.SEARCH); activityMap.put("/CustomerSearchAction-get", SecurityConstants.SEARCH); activityMap.put("/CustomerSearchAction-getHomePage", SecurityConstants.VIEW); activityMap.put("/CustomerSearchAction-getOfficeHomePage", SecurityConstants.VIEW); activityMap.put("/CustomerSearchAction-loadAllBranches", SecurityConstants.VIEW); activityMap.put("/mifoslogout-logout", SecurityConstants.VIEW); // Change password related activityMap.put("/mifoslogin-update", SecurityConstants.VIEW); // Office related mapping activityMap.put("/OfficeAction-loadall", SecurityConstants.VIEW); activityMap.put("/OfficeAction-load", SecurityConstants.OFFICE_CREATE_OFFICE); activityMap.put("/OfficeAction-loadParent", SecurityConstants.VIEW); activityMap.put("/OfficeAction-preview", SecurityConstants.VIEW); activityMap.put("/OfficeAction-create", SecurityConstants.OFFICE_CREATE_OFFICE); activityMap.put("/OfficeAction-get", SecurityConstants.VIEW); activityMap.put("/OfficeAction-manage", SecurityConstants.OFFICE_EDIT_OFFICE); activityMap.put("/OfficeAction-previous", SecurityConstants.VIEW); activityMap.put("/OfficeAction-update", SecurityConstants.OFFICE_EDIT_OFFICE); activityMap .put("/OfficeHierarchyAction-cancel", SecurityConstants.VIEW); activityMap.put("/OfficeHierarchyAction-load", SecurityConstants.VIEW); activityMap.put("/OfficeHierarchyAction-update", SecurityConstants.OFFICE_EDIT_OFFICE); activityMap.put("/offhierarchyaction-cancel", SecurityConstants.VIEW); activityMap.put("/offhierarchyaction-load", SecurityConstants.VIEW); activityMap.put("/offhierarchyaction-update",SecurityConstants.OFFICE_EDIT_OFFICE); //m2 office action activityMap.put("/offAction-load", SecurityConstants.OFFICE_CREATE_OFFICE); activityMap.put("/offAction-loadParent", SecurityConstants.VIEW); activityMap.put("/offAction-preview", SecurityConstants.VIEW); activityMap.put("/offAction-previous", SecurityConstants.VIEW); activityMap.put("/offAction-create", SecurityConstants.OFFICE_CREATE_OFFICE); activityMap.put("/offAction-get", SecurityConstants.VIEW); activityMap.put("/offAction-edit", SecurityConstants.OFFICE_EDIT_OFFICE); activityMap.put("/offAction-editpreview", SecurityConstants.OFFICE_EDIT_OFFICE); activityMap.put("/offAction-editprevious", SecurityConstants.OFFICE_EDIT_OFFICE); activityMap.put("/offAction-update", SecurityConstants.OFFICE_EDIT_OFFICE); activityMap.put("/offAction-getAllOffices", SecurityConstants.VIEW); // roles and permission related mappings activityMap.put("/manageRolesAndPermission-manage", SecurityConstants.VIEW); activityMap .put("/manageRolesAndPermission-get", SecurityConstants.VIEW); activityMap.put("/manageRolesAndPermission-load", SecurityConstants.ROLES_CREATE_ROLES); activityMap.put("/manageRolesAndPermission-create", SecurityConstants.ROLES_CREATE_ROLES); activityMap.put("/manageRolesAndPermission-update", SecurityConstants.ROLES_EDIT_ROLES); activityMap.put("/manageRolesAndPermission-cancel", SecurityConstants.VIEW); activityMap.put("/manageRolesAndPermission-preview", SecurityConstants.ROLES_DELETE_ROLES); activityMap.put("/manageRolesAndPermission-delete", SecurityConstants.ROLES_DELETE_ROLES); // Group ralated mappings // activities related to create group activityMap.put("/GroupAction-chooseOffice", SecurityConstants.VIEW); activityMap.put("/GroupAction-hierarchyCheck", SecurityConstants.VIEW); activityMap.put("/GroupAction-load", SecurityConstants.VIEW); activityMap.put("/GroupAction-loadMeeting", SecurityConstants.MEETING_CREATE_GROUP_MEETING); activityMap.put("/GroupAction-setDefaultFormedByPersonnel", SecurityConstants.VIEW); activityMap.put("/GroupAction-previous", SecurityConstants.VIEW); activityMap.put("/GroupAction-preview", SecurityConstants.VIEW); activityMap.put("/GroupAction-create", SecurityConstants.VIEW); activityMap.put("/GroupAction-search", SecurityConstants.VIEW); // activities related to retrieve group for Group Module activityMap.put("/GroupAction-getDetails", SecurityConstants.VIEW); activityMap.put("/GroupAction-get", SecurityConstants.VIEW); // activities related to update group status for Group Module activityMap.put("/GroupAction-loadStatus", SecurityConstants.VIEW); activityMap.put("/GroupAction-updateStatus", SecurityConstants.VIEW); // activities related to update group for Group Module activityMap.put("/GroupAction-manage", SecurityConstants.GROUP_EDIT_GROUP); activityMap.put("/GroupAction-update", SecurityConstants.GROUP_EDIT_GROUP); // activities related to change center membership for Group Module activityMap.put("/GroupAction-loadParentTransfer", SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); activityMap.put("/GroupAction-confirmParentTransfer", SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); activityMap.put("/GroupAction-updateParent", SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); // activities related to change center membership for Group Module activityMap.put("/GroupAction-loadParentTransfer", SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); activityMap.put("/GroupAction-confirmParentTransfer", SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); activityMap.put("/GroupAction-updateParent", SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); // activities related to transfer the group for Group Module activityMap.put("/GroupAction-loadTransfer", SecurityConstants.GROUP_TRANSFER_THE_GROUP); activityMap.put("/GroupAction-confirmBranchTransfer", SecurityConstants.GROUP_TRANSFER_THE_GROUP); activityMap.put("/GroupAction-updateBranch", SecurityConstants.GROUP_TRANSFER_THE_GROUP); // apply charges activityMap.put("/closedaccsearchaction-search", SecurityConstants.GROUP_APPLY_CHARGES_TO_GROUP_ACCOUNT); activityMap.put("/GroupAction-loadSearch", SecurityConstants.VIEW); // Customer Notes related mapping // activityMap.put("/CustomerNoteAction-load",SecurityConstants.CUSTOMER_ADD_NOTES_TO_CENTER_GROUP_CLIENT); activityMap.put("/CustomerNoteAction-preview", SecurityConstants.VIEW); activityMap.put("/CustomerNoteAction-previous", SecurityConstants.VIEW); activityMap.put("/CustomerNoteAction-create", SecurityConstants.VIEW); activityMap.put("/CustomerNoteAction-get", SecurityConstants.VIEW); activityMap.put("/CustomerNoteAction-search", SecurityConstants.VIEW); // mapping for group activityMap.put("/CustomerNoteAction-load-Group", SecurityConstants.GROUP_ADD_NOTE_TO_GROUP); activityMap.put("/CustomerNoteAction-load-Client", SecurityConstants.CLIENT_ADD_NOTE_TO_CLIENT); activityMap.put("/CustomerNoteAction-load-Center", SecurityConstants.CENTER_ADD_NOTE_TO_CENTER); // Customer Historical Data related mapping activityMap.put("/CustomerHistoricalDataAction-load-Group", SecurityConstants.GROUP_ADD_EDIT_HISTORICAL_DATA); activityMap.put("/CustomerHistoricalDataAction-load-Client", SecurityConstants.CIENT_ADD_EDIT_HISTORICAL_DATA); activityMap.put("/CustomerHistoricalDataAction-get", SecurityConstants.VIEW); activityMap.put("/CustomerHistoricalDataAction-preview", SecurityConstants.VIEW); activityMap.put("/CustomerHistoricalDataAction-previous", SecurityConstants.VIEW); activityMap.put("/CustomerHistoricalDataAction-update", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-load-Group", SecurityConstants.GROUP_ADD_EDIT_HISTORICAL_DATA); activityMap.put("/custHistoricalDataAction-load-Client", SecurityConstants.CIENT_ADD_EDIT_HISTORICAL_DATA); activityMap.put("/custHistoricalDataAction-get", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-preview", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-previous", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-update", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-loadHistoricalData-Group", SecurityConstants.GROUP_ADD_EDIT_HISTORICAL_DATA); activityMap.put("/custHistoricalDataAction-loadHistoricalData-Client", SecurityConstants.CIENT_ADD_EDIT_HISTORICAL_DATA); activityMap.put("/custHistoricalDataAction-getHistoricalData", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-previewHistoricalData", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-previousHistoricalData", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-updateHistoricalData", SecurityConstants.VIEW); activityMap.put("/custHistoricalDataAction-cancelHistoricalData", SecurityConstants.VIEW); // personnel related mappings activityMap.put("/PersonnelAction-chooseOffice", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); activityMap.put("/PersonnelAction-load", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); activityMap.put("/PersonnelAction-preview", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-previous", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-create", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); activityMap.put("/PersonnelAction-get", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-manage", SecurityConstants.PERSONNEL_EDIT_PERSONNEL); activityMap.put("/PersonnelAction-update", SecurityConstants.PERSONNEL_EDIT_PERSONNEL); activityMap.put("/PersonnelAction-loadSearch", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-search", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-loadUnLockUser", SecurityConstants.PERSONNEL_UNLOCK_PERSONNEL); activityMap.put("/PersonnelAction-unLockUserAccount", SecurityConstants.PERSONNEL_UNLOCK_PERSONNEL); //m2 personnel related mappings activityMap.put("/PersonAction-get",SecurityConstants.VIEW); activityMap.put("/PersonAction-chooseOffice", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); activityMap.put("/PersonAction-load", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); activityMap.put("/PersonAction-manage", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); activityMap.put("/PersonAction-previewManage", SecurityConstants.VIEW); activityMap.put("/PersonAction-previousManage", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); activityMap.put("/PersonAction-update", SecurityConstants.PERSONNEL_EDIT_PERSONNEL); activityMap.put("/PersonnelAction-prevPersonalInfo", SecurityConstants.VIEW); activityMap.put("/PersonAction-preview", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); activityMap.put("/PersonAction-previous", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); activityMap.put("/PersonAction-create", SecurityConstants.PERSONNEL_CREATE_PERSONNEL); // for your settings link activityMap.put("/PersonnelAction-getDetails", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-editPersonalInfo", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); activityMap.put("/PersonnelAction-previewPersonalInfo", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-prevPersonalInfo", SecurityConstants.VIEW); activityMap.put("/PersonnelAction-updateSettings", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); activityMap.put("/PersonnelAction-loadChangePassword", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); activityMap.put("/PersonnelNotesAction-load", SecurityConstants.PERSONNEL_EDIT_PERSONNEL); activityMap .put("/PersonnelNotesAction-preview", SecurityConstants.VIEW); activityMap.put("/PersonnelNotesAction-previous", SecurityConstants.VIEW); activityMap.put("/PersonnelNotesAction-create", SecurityConstants.PERSONNEL_EDIT_PERSONNEL); activityMap.put("/PersonnelNotesAction-search", SecurityConstants.VIEW); activityMap.put("/PersonnelNotesAction-get", SecurityConstants.VIEW); //M2 personnel notes activityMap.put("/personnelNoteAction-load",SecurityConstants.PERSONNEL_EDIT_PERSONNEL); activityMap.put("/personnelNoteAction-preview", SecurityConstants.VIEW); activityMap.put("/personnelNoteAction-previous",SecurityConstants.VIEW); activityMap.put("/personnelNoteAction-create",SecurityConstants.VIEW); activityMap.put("/personnelNoteAction-search", SecurityConstants.VIEW); // center ralated mappings activityMap.put("/centerAction-chooseOffice", SecurityConstants.CENTER_CREATE_NEW_CENTER); activityMap.put("/centerAction-load", SecurityConstants.CENTER_CREATE_NEW_CENTER); activityMap.put("/centerAction-loadMeeting-CenterCreate", SecurityConstants.MEETING_CREATE_CENTER_MEETING); activityMap.put("/centerAction-loadMeeting-Center", SecurityConstants.MEETING_UPDATE_CENTER_MEETING); activityMap.put("/centerAction-getDetails", SecurityConstants.VIEW); activityMap.put("/centerAction-get", SecurityConstants.VIEW); activityMap.put("/centerAction-loadStatus", SecurityConstants.CENTER_EDIT_STATUS); activityMap.put("/centerAction-updateStatus", SecurityConstants.CENTER_EDIT_STATUS); activityMap .put( "/centerAction-manage", SecurityConstants.CENTER_MODIFY_CENTER_INFORMATION_AND_CHANGE_CENTER_STATUS); activityMap.put("/centerAction-previous", SecurityConstants.VIEW); activityMap.put("/centerAction-preview", SecurityConstants.VIEW); activityMap.put("/centerAction-create", SecurityConstants.CENTER_CREATE_NEW_CENTER); activityMap .put( "/centerAction-update", SecurityConstants.CENTER_MODIFY_CENTER_INFORMATION_AND_CHANGE_CENTER_STATUS); activityMap.put("/centerAction-loadSearch", SecurityConstants.VIEW); activityMap.put("/centerAction-search", SecurityConstants.VIEW); //For M2 Center ------------------------ activityMap.put("/centerCustAction-chooseOffice", SecurityConstants.CENTER_CREATE_NEW_CENTER); activityMap.put("/centerCustAction-load", SecurityConstants.CENTER_CREATE_NEW_CENTER); activityMap.put("/centerCustAction-loadMeeting-CenterCreate", SecurityConstants.MEETING_CREATE_CENTER_MEETING); activityMap.put("/centerCustAction-previous", SecurityConstants.VIEW); activityMap.put("/centerCustAction-preview", SecurityConstants.VIEW); activityMap.put("/centerCustAction-create", SecurityConstants.CENTER_CREATE_NEW_CENTER); activityMap.put( "/centerCustAction-manage", SecurityConstants.CENTER_MODIFY_CENTER_INFORMATION_AND_CHANGE_CENTER_STATUS); activityMap.put("/centerCustAction-editPrevious", SecurityConstants.VIEW); activityMap.put("/centerCustAction-editPreview", SecurityConstants.VIEW); activityMap.put( "/centerCustAction-update", SecurityConstants.CENTER_MODIFY_CENTER_INFORMATION_AND_CHANGE_CENTER_STATUS); activityMap.put("/centerCustAction-get", SecurityConstants.VIEW); // For M2 Center ends // colsed account searchaction in center details page activityMap .put("/closedaccsearchaction-search", SecurityConstants.VIEW); // CustomerSearch // activityMap.put("/CustomerSearchAction-validate",SecurityConstants.VIEW); // client creation action activityMap .put("/clientCreationAction-preLoad", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-load", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-chooseOffice", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-setDefaultFormedByPersonnel", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-next", SecurityConstants.VIEW); activityMap .put("/clientCreationAction-preview", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-prevPersonalInfo", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-prevMFIInfo", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-create", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-get", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-getDetails", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-loadStatus", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-loadTransfer", SecurityConstants.CIENT_CHANGE_GROUP_MEMBERSHIP); activityMap.put("/clientCreationAction-loadBranchTransfer", SecurityConstants.CIENT_TRANSFER_THE_CLIENT); activityMap.put("/clientCreationAction-editMFIInfo", SecurityConstants.CIENT_EDIT_MFI_INFORMATION); activityMap.put("/clientCreationAction-editPersonalInfo", SecurityConstants.CLIENT_UPDATE_PERSONNEL_INFO); activityMap.put("/clientCreationAction-update", SecurityConstants.CLIENT_UPDATE_PERSONNEL_INFO); activityMap.put("/clientCreationAction-updateMfi", SecurityConstants.CIENT_EDIT_MFI_INFORMATION); activityMap.put("/clientCreationAction-loadMeeting-ClientCreate", SecurityConstants.MEETING_CREATE_CLIENT_MEETING); activityMap.put("/clientCreationAction-loadMeeting-Client", SecurityConstants.MEETING_UPDATE_CLIENT_MEETING); activityMap.put("/clientCreationAction-previous", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-retrievePictureOnPreview", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-retrievePicture", SecurityConstants.VIEW); activityMap.put("/clientCreationAction-showPicture", SecurityConstants.VIEW); activityMap .put( "/clientCreationAction-loadHistoricalData", SecurityConstants.CUSTOMER_ADD_HISTORICAL_DATA_TO_CENTER_GROUP_CLIENT); activityMap.put("/clientStatusAction-load", SecurityConstants.VIEW); activityMap.put("/clientStatusAction-preview", SecurityConstants.VIEW); activityMap.put("/clientStatusAction-previous", SecurityConstants.VIEW); activityMap.put("/clientStatusAction-update", SecurityConstants.VIEW); activityMap.put("/clientTransferAction-loadParents",SecurityConstants.CIENT_CHANGE_GROUP_MEMBERSHIP); activityMap.put("/clientTransferAction-loadBranches",SecurityConstants.CIENT_TRANSFER_THE_CLIENT); activityMap.put("/clientTransferAction-previewBranchTransfer",SecurityConstants.VIEW); activityMap.put("/clientTransferAction-previewParentTransfer",SecurityConstants.VIEW); activityMap.put("/clientTransferAction-updateParent", SecurityConstants.CIENT_CHANGE_GROUP_MEMBERSHIP); activityMap.put("/clientTransferAction-transferToBranch",SecurityConstants.CIENT_TRANSFER_THE_CLIENT); activityMap.put("/groupTransferAction-loadParents",SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); activityMap.put("/groupTransferAction-loadBranches",SecurityConstants.GROUP_TRANSFER_THE_GROUP); activityMap.put("/groupTransferAction-previewBranchTransfer",SecurityConstants.VIEW); activityMap.put("/groupTransferAction-previewParentTransfer",SecurityConstants.VIEW); activityMap.put("/groupTransferAction-transferToCenter", SecurityConstants.GROUP_CHANGE_CENTER_MEMBERSHIP); activityMap.put("/groupTransferAction-transferToBranch",SecurityConstants.GROUP_TRANSFER_THE_GROUP); // meeting action activityMap.put("/MeetingAction-load", SecurityConstants.VIEW); activityMap.put("/MeetingAction-loadMeeting-Group", SecurityConstants.MEETING_UPDATE_GROUP_MEETING); activityMap.put("/MeetingAction-loadMeeting-Client", SecurityConstants.MEETING_UPDATE_CLIENT_MEETING); activityMap.put("/MeetingAction-create", SecurityConstants.VIEW); activityMap.put("/MeetingAction-get-Group", SecurityConstants.MEETING_UPDATE_GROUP_MEETING); activityMap.put("/MeetingAction-get-Client", SecurityConstants.MEETING_UPDATE_CLIENT_MEETING); activityMap.put("/MeetingAction-get-Center", SecurityConstants.MEETING_UPDATE_CENTER_MEETING); activityMap.put("/MeetingAction-update", SecurityConstants.VIEW); activityMap.put("/MeetingAction-preview", SecurityConstants.VIEW); activityMap.put("/MeetingAction-previous", SecurityConstants.VIEW); // product categories mapping activityMap.put("/productCategoryAction-load", SecurityConstants.DEFINE_NEW_PRODUCT_CATEGORIES); activityMap.put("/productCategoryAction-createPreview", SecurityConstants.VIEW); activityMap.put("/productCategoryAction-create", SecurityConstants.DEFINE_NEW_PRODUCT_CATEGORIES); activityMap.put("/productCategoryAction-get", SecurityConstants.VIEW); activityMap.put("/productCategoryAction-managePreview", SecurityConstants.VIEW); activityMap.put("/productCategoryAction-manage", SecurityConstants.EDIT_PRODUCT_CATEGORIES); activityMap.put("/productCategoryAction-update", SecurityConstants.EDIT_PRODUCT_CATEGORIES); activityMap.put("/productCategoryAction-getAllCategories", SecurityConstants.VIEW); activityMap.put("/productCategoryAction-createPrevious", SecurityConstants.VIEW); activityMap.put("/productCategoryAction-managePrevious", SecurityConstants.VIEW); // saving product mappeings activityMap.put("/savingsprdaction-search", SecurityConstants.VIEW); activityMap.put("/savingsprdaction-load", SecurityConstants.DEFINE_NEW_SAVING_PRODUCT_INSTANCE); activityMap.put("/savingsprdaction-preview", SecurityConstants.VIEW); activityMap.put("/savingsprdaction-previous", SecurityConstants.VIEW); activityMap.put("/savingsprdaction-create", SecurityConstants.DEFINE_NEW_SAVING_PRODUCT_INSTANCE); activityMap.put("/savingsprdaction-get", SecurityConstants.VIEW); activityMap.put("/savingsprdaction-manage", SecurityConstants.EDIT_SAVING_PRODUCT); activityMap.put("/savingsprdaction-update", SecurityConstants.EDIT_SAVING_PRODUCT); activityMap.put("/savingsproductaction-search", SecurityConstants.VIEW); activityMap.put("/savingsproductaction-load", SecurityConstants.DEFINE_NEW_SAVING_PRODUCT_INSTANCE); activityMap.put("/savingsproductaction-preview", SecurityConstants.VIEW); activityMap.put("/savingsproductaction-previous", SecurityConstants.VIEW); activityMap.put("/savingsproductaction-create", SecurityConstants.DEFINE_NEW_SAVING_PRODUCT_INSTANCE); activityMap.put("/savingsproductaction-get", SecurityConstants.VIEW); activityMap.put("/savingsproductaction-cancelCreate", SecurityConstants.VIEW); activityMap.put("/savingsproductaction-manage", SecurityConstants.EDIT_SAVING_PRODUCT); activityMap.put("/savingsproductaction-update", SecurityConstants.EDIT_SAVING_PRODUCT); // view lateness mappings activityMap.put("/prdconfigurationaction-search", SecurityConstants.VIEW); activityMap.put("/prdconfigurationaction-update", SecurityConstants.EDIT_PRODUCT_CATEGORIES); // loan product categories activityMap.put("/loanprdaction-load", SecurityConstants.DEFINE_NEW_LOAN_PRODUCT_INSTANCE); activityMap.put("/loanprdaction-preview", SecurityConstants.VIEW); activityMap.put("/loanprdaction-previous", SecurityConstants.VIEW); activityMap.put("/loanprdaction-create", SecurityConstants.DEFINE_NEW_LOAN_PRODUCT_INSTANCE); activityMap.put("/loanprdaction-search", SecurityConstants.VIEW); activityMap.put("/loanprdaction-get", SecurityConstants.VIEW); activityMap.put("/loanprdaction-manage", SecurityConstants.EDIT_LOAN_PRODUCT); activityMap.put("/loanprdaction-update", SecurityConstants.EDIT_LOAN_PRODUCT); // Fee mapping activityMap.put("/feesAction-search", SecurityConstants.VIEW); activityMap.put("/feesAction-load", SecurityConstants.FEES_CREATE_FEES); activityMap.put("/feesAction-preview", SecurityConstants.VIEW); activityMap.put("/feesAction-create", SecurityConstants.FEES_CREATE_FEES); activityMap.put("/feesAction-get", SecurityConstants.VIEW); activityMap.put("/feesAction-manage", SecurityConstants.FEES_EDIT_FEES); activityMap.put("/feesAction-update", SecurityConstants.FEES_EDIT_FEES); activityMap.put("/feesAction-previous", SecurityConstants.VIEW); activityMap.put("/feeaction-search", SecurityConstants.VIEW); activityMap.put("/feeaction-load", SecurityConstants.FEES_CREATE_FEES); activityMap.put("/feeaction-preview", SecurityConstants.VIEW); activityMap.put("/feeaction-editPreview", SecurityConstants.VIEW); activityMap .put("/feeaction-create", SecurityConstants.FEES_CREATE_FEES); activityMap.put("/feeaction-get", SecurityConstants.VIEW); activityMap.put("/feeaction-manage", SecurityConstants.FEES_EDIT_FEES); activityMap.put("/feeaction-update", SecurityConstants.FEES_EDIT_FEES); activityMap.put("/feeaction-previous", SecurityConstants.VIEW); activityMap.put("/feeaction-editPrevious", SecurityConstants.VIEW); activityMap.put("/feeaction-viewAll", SecurityConstants.VIEW); activityMap.put("/feeaction-cancelCreate", SecurityConstants.VIEW); activityMap.put("/feeaction-cancelEdit", SecurityConstants.VIEW); // checklist mapping activityMap.put("/checkListAction-loadall", SecurityConstants.VIEW); activityMap.put("/checkListAction-load", SecurityConstants.CHECKLIST_CREATE_CHECKLIST); activityMap.put("/checkListAction-create", SecurityConstants.CHECKLIST_CREATE_CHECKLIST); activityMap.put("/checkListAction-preview", SecurityConstants.VIEW); activityMap.put("/checkListAction-previous", SecurityConstants.VIEW); activityMap.put("/checkListAction-previous", SecurityConstants.CHECKLIST_CREATE_CHECKLIST); activityMap.put("/checkListAction-loadParent", SecurityConstants.VIEW); activityMap.put("/checkListAction-get", SecurityConstants.VIEW); activityMap.put("/checkListAction-manage", SecurityConstants.CHECKLIST_EDIT_CHECKLIST); activityMap.put("/checkListAction-update", SecurityConstants.CHECKLIST_EDIT_CHECKLIST); // mapping for search before loan activityMap.put("/AccountsSearchAction-load", SecurityConstants.VIEW); activityMap.put("/AccountsSearchAction-search", SecurityConstants.VIEW); // mapping for loan activityMap.put("/loanAction-getPrdOfferings", SecurityConstants.VIEW); activityMap.put("/loanAction-load", SecurityConstants.VIEW); activityMap.put("/loanAction-next", SecurityConstants.VIEW); activityMap.put("/loanAction-preview", SecurityConstants.VIEW); activityMap.put("/loanAction-previous", SecurityConstants.VIEW); activityMap.put("/loanAction-get", SecurityConstants.VIEW); activityMap.put("/loanAction-manage", SecurityConstants.LOAN_UPDATE_LOAN); activityMap.put("/loanAction-update", SecurityConstants.LOAN_UPDATE_LOAN); activityMap.put("/loanAction-getLoanChangeLog", SecurityConstants.VIEW); activityMap.put("/loanAction-search", SecurityConstants.VIEW); activityMap.put("/loanAction-create", SecurityConstants.VIEW); // mapping for loanActivity activityMap.put("/loanAccountAction-getAllActivity", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-get",SecurityConstants.VIEW); activityMap.put("/loanAccountAction-getLoanRepaymentSchedule",SecurityConstants.VIEW); activityMap.put("/loanAccountAction-viewStatusHistory", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-manage", SecurityConstants.LOAN_UPDATE_LOAN); activityMap.put("/loanAccountAction-managePreview",SecurityConstants.VIEW); activityMap.put("/loanAccountAction-managePrevious",SecurityConstants.VIEW); activityMap.put("/loanAccountAction-cancel",SecurityConstants.VIEW); activityMap.put("/loanAccountAction-update", SecurityConstants.LOAN_UPDATE_LOAN); activityMap.put("/loanAccountAction-getPrdOfferings", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-load", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-schedulePreview", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-preview", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-previous", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-create", SecurityConstants.VIEW); // mapping for account status::TO BE REMOVED activityMap.put("/LoanStatusAction-load", SecurityConstants.VIEW); activityMap.put("/LoanStatusAction-preview", SecurityConstants.VIEW); activityMap.put("/LoanStatusAction-previous", SecurityConstants.VIEW); activityMap.put("/LoanStatusAction-update", SecurityConstants.VIEW); activityMap.put("/LoanStatusAction-search", SecurityConstants.VIEW); activityMap.put("/LoanStatusAction-writeOff", SecurityConstants.VIEW); // mapping for account status activityMap.put("/editStatusAction-load", SecurityConstants.VIEW); activityMap.put("/editStatusAction-preview", SecurityConstants.VIEW); activityMap.put("/editStatusAction-previous", SecurityConstants.VIEW); activityMap.put("/editStatusAction-update", SecurityConstants.VIEW); //mapping for custAction activityMap.put("/custAction-getClosedAccounts", SecurityConstants.VIEW); activityMap.put("/custAction-getBackToDetailsPage", SecurityConstants.VIEW); // mapping for account notes activityMap.put("/AccountNotesAction-load", SecurityConstants.LOAN_CAN_ADD_NOTES_TO_LOAN); activityMap.put("/AccountNotesAction-preview", SecurityConstants.VIEW); activityMap.put("/AccountNotesAction-previous", SecurityConstants.VIEW); activityMap.put("/AccountNotesAction-get", SecurityConstants.VIEW); activityMap.put("/AccountNotesAction-search", SecurityConstants.VIEW); activityMap.put("/AccountNotesAction-create", SecurityConstants.LOAN_CAN_ADD_NOTES_TO_LOAN); // mapping for apply payment activityMap.put("/accountTrxn-load", SecurityConstants.APPLY_PAYMENT_TO_CLIENT_GROUP_CENTERS_LOANS); activityMap.put("/accountTrxn-create", SecurityConstants.APPLY_PAYMENT_TO_CLIENT_GROUP_CENTERS_LOANS); activityMap.put("/accountTrxn-preview", SecurityConstants.VIEW); activityMap.put("/accountTrxn-getInstallmentHistory", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-getInstallmentDetails", SecurityConstants.VIEW); activityMap.put("/accountTrxn-previous", SecurityConstants.VIEW); // apply charges activityMap.put("/AccountsApplyChargesAction-load", SecurityConstants.APPLY_CHARGES_TO_CLIENT_GROUP_CENTERS_LOANS); activityMap.put("/AccountsApplyChargesAction-create", SecurityConstants.APPLY_CHARGES_TO_CLIENT_GROUP_CENTERS_LOANS); // fund mapping activityMap.put("/fundAction-load", SecurityConstants.FUNDS_CREATE_FUNDS); activityMap.put("/fundAction-create", SecurityConstants.FUNDS_CREATE_FUNDS); activityMap.put("/fundAction-preview", SecurityConstants.VIEW); activityMap.put("/fundAction-getAllFunds", SecurityConstants.VIEW); activityMap.put("/fundAction-get", SecurityConstants.VIEW); activityMap.put("/fundAction-update", SecurityConstants.FUNDS_EDIT_FUNDS); activityMap.put("/fundAction-previous", SecurityConstants.FUNDS_CREATE_FUNDS); activityMap.put("/fundAction-manage", SecurityConstants.FUNDS_EDIT_FUNDS); // mapping for bulk entry activityMap.put("/bulkentryaction-load", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-preview", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-previous", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-get", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-getLastMeetingDateForCustomer", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-create", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-loadLoanOfficers", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-loadCustomerList", SecurityConstants.VIEW); activityMap.put("/bulkentryaction-validate", SecurityConstants.VIEW); // removing fees activityMap.put("/accountAppAction-removeFees", SecurityConstants.LOAN_REMOVE_FEE_TYPE_ATTACHED_TO_ACCOUNT); activityMap.put("/accountAppAction-getTrxnHistory", SecurityConstants.VIEW); // mapping for savings account activityMap.put("/savingsAction-getPrdOfferings", SecurityConstants.VIEW); activityMap.put("/savingsAction-load", SecurityConstants.VIEW); activityMap.put("/savingsAction-reLoad", SecurityConstants.VIEW); activityMap.put("/savingsAction-preview", SecurityConstants.VIEW); activityMap.put("/savingsAction-previous", SecurityConstants.VIEW); activityMap.put("/savingsAction-create", SecurityConstants.VIEW); activityMap.put("/savingsAction-get", SecurityConstants.VIEW); activityMap.put("/savingsAction-getStatusHistory", SecurityConstants.VIEW); activityMap.put("/savingsAction-edit", SecurityConstants.SAVINGS_UPDATE_SAVINGS); activityMap.put("/savingsAction-editPreview", SecurityConstants.SAVINGS_UPDATE_SAVINGS); activityMap.put("/savingsAction-editPrevious", SecurityConstants.SAVINGS_UPDATE_SAVINGS); activityMap.put("/savingsAction-update", SecurityConstants.SAVINGS_UPDATE_SAVINGS); activityMap.put("/savingsAction-getRecentActivity", SecurityConstants.VIEW); activityMap.put("/savingsAction-getTransactionHistory", SecurityConstants.VIEW); activityMap.put("/savingsAction-getDepositDueDetails", SecurityConstants.VIEW); activityMap.put("/savingsAction-waiveAmountDue", SecurityConstants.SAVINGS_CANWAIVE_DUEAMOUNT); activityMap.put("/savingsAction-waiveAmountOverDue", SecurityConstants.SAVINGS_CANWAIVE_OVERDUEAMOUNT); // close savings account activityMap.put("/savingsClosureAction-load", SecurityConstants.SAVINGS_CLOSE_SAVINGS_ACCOUNT); activityMap.put("/savingsClosureAction-preview", SecurityConstants.SAVINGS_CLOSE_SAVINGS_ACCOUNT); activityMap.put("/savingsClosureAction-previous", SecurityConstants.SAVINGS_CLOSE_SAVINGS_ACCOUNT); activityMap.put("/savingsClosureAction-close", SecurityConstants.SAVINGS_CLOSE_SAVINGS_ACCOUNT); // savings accountadjustment activityMap.put("/savingsApplyAdjustmentAction-load", SecurityConstants.SAVINGS_APPLY_ADJUSTMENT); activityMap.put("/savingsApplyAdjustmentAction-preview", SecurityConstants.SAVINGS_APPLY_ADJUSTMENT); activityMap.put("/savingsApplyAdjustmentAction-previous", SecurityConstants.SAVINGS_APPLY_ADJUSTMENT); activityMap.put("/savingsApplyAdjustmentAction-adjustLastUserAction", SecurityConstants.SAVINGS_APPLY_ADJUSTMENT); // entries for apply adjustment. activityMap.put("/applyAdjustment-loadAdjustment", SecurityConstants.LOAN_MAKE_ADJUSTMENT_ENTRY_TO_ACCOUNT); activityMap.put("/applyAdjustment-previewAdjustment", SecurityConstants.LOAN_MAKE_ADJUSTMENT_ENTRY_TO_ACCOUNT); activityMap.put("/applyAdjustment-applyAdjustment", SecurityConstants.LOAN_MAKE_ADJUSTMENT_ENTRY_TO_ACCOUNT); activityMap.put("/applyAdjustment-cancelAdjustment", SecurityConstants.LOAN_MAKE_ADJUSTMENT_ENTRY_TO_ACCOUNT); // mapping for repaying loan account activityMap.put("/repayLoanAction-loadRepayment", SecurityConstants.LOAN_CAN_REPAY_LOAN); activityMap.put("/repayLoanAction-preview", SecurityConstants.LOAN_CAN_REPAY_LOAN); activityMap.put("/repayLoanAction-previous", SecurityConstants.LOAN_CAN_REPAY_LOAN); activityMap.put("/repayLoanAction-makeRepayment", SecurityConstants.LOAN_CAN_REPAY_LOAN); // mapping for reports activityMap.put("/reportsAction-load", SecurityConstants.VIEW); activityMap.put("/reportsAction-report_designer", SecurityConstants.CLIENTSDETAILVIEW); activityMap.put("/reportsAction-product_history", SecurityConstants.CLIENTSPRODUCTHISTORY); activityMap.put("/reportsAction-branch_performance", SecurityConstants.BRANCHPERFORMANCE); activityMap.put("/reportsAction-area_performance", SecurityConstants.AREAPERFORMANCE); activityMap.put("/reportsAction-collection_sheet", SecurityConstants.COLLECTIONSHEET); activityMap.put("/reportsAction-loan_distribution", SecurityConstants.LOANDISTRIBUTION); activityMap.put("/reportsAction-branch_disbursement", SecurityConstants.BRANCHDISBURSEMENT); activityMap.put("/reportsAction-staffwise_report", SecurityConstants.STAFFWISEREPORT); activityMap.put("/reportsAction-branchwise_report", SecurityConstants.BRANCHWISEREPORT); activityMap.put("/reportsAction-analysis", SecurityConstants.ANALYSIS); activityMap.put("/reportsAction-kendra_meeting", SecurityConstants.KENDRA_MEETING); activityMap.put("/reportsAction-administerreports_path", SecurityConstants.ADMINISTER_REPORTS); // entries for apply adjustment for customer. activityMap .put( "/custApplyAdjustment-loadAdjustment-Client", SecurityConstants.CIENT_MAKE_ADJUSTMENT_ENTRIES_TO_CLIENT_ACCOUNT); activityMap.put("/custApplyAdjustment-previewAdjustment-Client", SecurityConstants.VIEW); activityMap.put("/custApplyAdjustment-applyAdjustment-Client", SecurityConstants.VIEW); activityMap.put("/custApplyAdjustment-cancelAdjustment-Client", SecurityConstants.VIEW); activityMap .put( "/custApplyAdjustment-loadAdjustment-Group", SecurityConstants.GROUP_MAKE_ADJUSTMENT_ENTRIES_TO_GROUP_ACCOUNT); activityMap.put("/custApplyAdjustment-previewAdjustment-Group", SecurityConstants.VIEW); activityMap.put("/custApplyAdjustment-applyAdjustment-Group", SecurityConstants.VIEW); activityMap.put("/custApplyAdjustment-cancelAdjustment-Group", SecurityConstants.VIEW); activityMap .put( "/custApplyAdjustment-loadAdjustment-Center", SecurityConstants.CENTER_MAKE_ADJUSTMENT_ENTRIES_TO_CENTER_ACCOUNT); activityMap.put("/custApplyAdjustment-previewAdjustment-Center", SecurityConstants.VIEW); activityMap.put("/custApplyAdjustment-applyAdjustment-Center", SecurityConstants.VIEW); activityMap.put("/custApplyAdjustment-cancelAdjustment-Center", SecurityConstants.VIEW); activityMap.put("/customerAction-forwardWaiveChargeDue", SecurityConstants.VIEW); activityMap.put("/customerAction-forwardWaiveChargeOverDue", SecurityConstants.VIEW); activityMap.put("/customerAction-waiveChargeDue-Client", SecurityConstants.CIENT_WAIVE_FEE_INSTALLMENT); activityMap.put("/customerAction-waiveChargeOverDue-Client", SecurityConstants.CIENT_WAIVE_FEE_INSTALLMENT); activityMap.put("/customerAction-waiveChargeDue-Group", SecurityConstants.GROUP_WAIVE_FEE_INSTALLMENT); activityMap.put("/customerAction-waiveChargeOverDue-Group", SecurityConstants.GROUP_WAIVE_FEE_INSTALLMENT); activityMap.put("/customerAction-waiveChargeDue-Center", SecurityConstants.CENTER_WAIVE_FEE_INSTALLMENT); activityMap.put("/customerAction-waiveChargeOverDue-Center", SecurityConstants.CENTER_WAIVE_FEE_INSTALLMENT); activityMap.put("/customerAction-getAllActivity", SecurityConstants.VIEW); activityMap.put("/customerAction-getAllClosedAccounts", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-waiveChargeDue", SecurityConstants.LOAN_WAIVE_FEE_INSTALLMENT); activityMap.put("/loanAccountAction-waiveChargeDue", SecurityConstants.LOAN_WAIVE_PANELTY); activityMap.put("/loanAccountAction-forwardWaiveCharge", SecurityConstants.VIEW); activityMap.put("/loanAccountAction-waiveChargeOverDue", SecurityConstants.LOAN_WAIVE_FEE_INSTALLMENT); activityMap.put("/loanAccountAction-waiveChargeOverDue", SecurityConstants.LOAN_WAIVE_PANELTY); // mapping for accountPayment activityMap.put("/applyPaymentAction-load-Loan", SecurityConstants.LOAN_MAKE_PAYMENT_TO_ACCOUNT); activityMap.put("/applyPaymentAction-load-Center", SecurityConstants.CENTER_MAKE_PAYMENTS_TO_CENTER_ACCOUNT); activityMap.put("/applyPaymentAction-load-Group", SecurityConstants.GROUP_MAKE_PAYMENT_TO_GROUP_ACCOUNT); activityMap.put("/applyPaymentAction-load-Client", SecurityConstants.CIENT_MAKE_PAYMENT_TO_CLIENT_ACCOUNT); activityMap.put("/applyPaymentAction-preview", SecurityConstants.VIEW); activityMap.put("/applyPaymentAction-previous",SecurityConstants.VIEW); activityMap.put("/applyPaymentAction-applyPayment",SecurityConstants.VIEW); //mapping fro loan disbursal activityMap.put("/loanDisbursmentAction-load", SecurityConstants.LOAN_CAN_DISBURSE_LOAN); activityMap.put("/loanDisbursmentAction-preview", SecurityConstants.VIEW); activityMap.put("/loanDisbursmentAction-previous",SecurityConstants.VIEW); activityMap.put("/loanDisbursmentAction-update",SecurityConstants.VIEW); //mapping for savings deposit/withdrawal activityMap.put("/savingsDepositWithdrawalAction-load", SecurityConstants.SAVINGS_CAN_MAKE_DEPOSIT_WITHDRAWAL); activityMap.put("/savingsDepositWithdrawalAction-reLoad", SecurityConstants.SAVINGS_CAN_MAKE_DEPOSIT_WITHDRAWAL); activityMap.put("/savingsDepositWithdrawalAction-preview", SecurityConstants.VIEW); activityMap.put("/savingsDepositWithdrawalAction-previous",SecurityConstants.VIEW); activityMap.put("/savingsDepositWithdrawalAction-makePayment",SecurityConstants.VIEW); // mapping for notes activityMap.put("/notesAction-load-Savings", SecurityConstants.SAVINGS_CAN_ADD_NOTES_TO_SAVINGS); activityMap.put("/notesAction-load-Loan", SecurityConstants.LOAN_CAN_ADD_NOTES_TO_LOAN); activityMap.put("/notesAction-preview", SecurityConstants.VIEW); activityMap.put("/notesAction-previous", SecurityConstants.VIEW); activityMap.put("/notesAction-get", SecurityConstants.VIEW); activityMap.put("/notesAction-search", SecurityConstants.VIEW); activityMap.put("/notesAction-create-Savings", SecurityConstants.SAVINGS_CAN_ADD_NOTES_TO_SAVINGS); //mapping for editing customer status activityMap.put("/editCustomerStatusAction-load-Center", SecurityConstants.CENTER_EDIT_STATUS); activityMap.put("/editCustomerStatusAction-preview", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-previous", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-update", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-load-Client", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-loadStatus-Group", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-previewStatus", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-previousStatus", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-updateStatus", SecurityConstants.VIEW); activityMap.put("/editCustomerStatusAction-cancelStatus", SecurityConstants.VIEW); activityMap.put("/notesAction-create-Loan", SecurityConstants.LOAN_CAN_ADD_NOTES_TO_LOAN); // apply charges activityMap.put("/applyChargeAction-load", SecurityConstants.VIEW); activityMap.put("/applyChargeAction-update", SecurityConstants.APPLY_CHARGES_TO_CLIENT_GROUP_CENTERS_LOANS); //mapping for adding customer notes activityMap.put("/customerNotesAction-load-Center", SecurityConstants.CENTER_ADD_NOTE_TO_CENTER); activityMap.put("/customerNotesAction-preview", SecurityConstants.VIEW); activityMap.put("/customerNotesAction-previous", SecurityConstants.VIEW); activityMap.put("/customerNotesAction-create", SecurityConstants.VIEW); activityMap.put("/customerNotesAction-search", SecurityConstants.VIEW); activityMap.put("/customerNotesAction-load-Group", SecurityConstants.GROUP_ADD_NOTE_TO_GROUP); activityMap.put("/customerNotesAction-load-Client", SecurityConstants.CLIENT_ADD_NOTE_TO_CLIENT); // client creation action- migration activityMap.put("/clientCustAction-load", SecurityConstants.VIEW); activityMap.put("/clientCustAction-chooseOffice", SecurityConstants.VIEW); activityMap.put("/clientCustAction-next", SecurityConstants.VIEW); activityMap .put("/clientCustAction-preview", SecurityConstants.VIEW); activityMap.put("/clientCustAction-previewPersonalInfo", SecurityConstants.VIEW); activityMap.put("/clientCustAction-retrievePictureOnPreview", SecurityConstants.VIEW); activityMap.put("/clientCustAction-prevPersonalInfo", SecurityConstants.VIEW); activityMap.put("/clientCustAction-prevMFIInfo", SecurityConstants.VIEW); activityMap.put("/clientCustAction-prevMeeting", SecurityConstants.VIEW); activityMap.put("/clientCustAction-create", SecurityConstants.VIEW); activityMap.put("/clientCustAction-loadMeeting-ClientCreate", SecurityConstants.MEETING_CREATE_CLIENT_MEETING); activityMap.put("/clientCustAction-get", SecurityConstants.VIEW); activityMap.put("/clientCustAction-editPersonalInfo", SecurityConstants.CLIENT_UPDATE_PERSONNEL_INFO); activityMap.put("/clientCustAction-previewEditPersonalInfo", SecurityConstants.VIEW); activityMap.put("/clientCustAction-prevEditPersonalInfo", SecurityConstants.VIEW); activityMap.put("/clientCustAction-updatePersonalInfo", SecurityConstants.CLIENT_UPDATE_PERSONNEL_INFO); activityMap.put("/clientCustAction-editMfiInfo", SecurityConstants.CIENT_EDIT_MFI_INFORMATION); activityMap.put("/clientCustAction-previewEditMfiInfo", SecurityConstants.VIEW); activityMap.put("/clientCustAction-prevEditMfiInfo", SecurityConstants.VIEW); activityMap.put("/clientCustAction-updateMfiInfo", SecurityConstants.CIENT_EDIT_MFI_INFORMATION); activityMap.put("/clientCustAction-loadMeeting-Client", SecurityConstants.MEETING_UPDATE_CLIENT_MEETING); activityMap.put("/clientCustAction-retrievePicture", SecurityConstants.VIEW); activityMap.put("/clientCustAction-showPicture", SecurityConstants.VIEW); activityMap.put("/ChangeAccountStatus-load", SecurityConstants.VIEW); activityMap.put("/ChangeAccountStatus-searchResults", SecurityConstants.VIEW); activityMap.put("/ChangeAccountStatus-update", SecurityConstants.VIEW); activityMap.put("/ChangeAccountStatus-getLoanOfficers", SecurityConstants.VIEW); // Group related mappings for M2 activityMap.put("/groupCustAction-hierarchyCheck", SecurityConstants.VIEW); activityMap.put("/groupCustAction-chooseOffice",SecurityConstants.VIEW); activityMap.put("/groupCustAction-load", SecurityConstants.VIEW); activityMap.put("/groupCustAction-loadMeeting-GroupCreate",SecurityConstants.MEETING_CREATE_GROUP_MEETING); activityMap.put("/groupCustAction-preview", SecurityConstants.VIEW); activityMap.put("/groupCustAction-previous", SecurityConstants.VIEW); activityMap.put("/groupCustAction-create", SecurityConstants.VIEW); activityMap.put("/groupCustAction-getDetails", SecurityConstants.VIEW); activityMap.put("/groupCustAction-get", SecurityConstants.VIEW); activityMap.put("/groupCustAction-manage",SecurityConstants.GROUP_EDIT_GROUP); activityMap.put("/groupCustAction-previewManage",SecurityConstants.VIEW); activityMap.put("/groupCustAction-previousManage",SecurityConstants.VIEW); activityMap.put("/groupCustAction-update",SecurityConstants.GROUP_EDIT_GROUP); // for your settings new action class activityMap.put("/yourSettings-get", SecurityConstants.VIEW); activityMap.put("/yourSettings-manage", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); activityMap.put("/yourSettings-preview", SecurityConstants.VIEW); activityMap.put("/yourSettings-previous", SecurityConstants.VIEW); activityMap.put("/yourSettings-update", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); activityMap.put("/yourSettings-loadChangePassword", SecurityConstants.PERSONNEL_EDIT_SELF_INFO); //for CustomerAccountAction activityMap.put("/customerAccountAction-load", SecurityConstants.VIEW); }
diff --git a/solver/src/main/java/solver/constraints/propagators/unary/PropMemberBound.java b/solver/src/main/java/solver/constraints/propagators/unary/PropMemberBound.java index e58d5e636..df5825a4f 100644 --- a/solver/src/main/java/solver/constraints/propagators/unary/PropMemberBound.java +++ b/solver/src/main/java/solver/constraints/propagators/unary/PropMemberBound.java @@ -1,104 +1,108 @@ /** * Copyright (c) 1999-2011, Ecole des Mines de Nantes * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Ecole des Mines de Nantes nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package solver.constraints.propagators.unary; import choco.kernel.ESat; import solver.Solver; import solver.constraints.Constraint; import solver.constraints.propagators.Propagator; import solver.constraints.propagators.PropagatorPriority; import solver.exception.ContradictionException; import solver.explanations.Deduction; import solver.explanations.Explanation; import solver.recorders.fine.AbstractFineEventRecorder; import solver.variables.EventType; import solver.variables.IntVar; /** * <br/> * * @author Charles Prud'homme * @since 26 nov. 2010 */ public class PropMemberBound extends Propagator<IntVar> { final int lb, ub; public PropMemberBound(IntVar var, int lb, int ub, Solver solver, Constraint<IntVar, Propagator<IntVar>> intVarPropagatorConstraint, PropagatorPriority priority, boolean reactOnPromotion) { super(new IntVar[]{var}, solver, intVarPropagatorConstraint, priority, reactOnPromotion); this.lb = lb; this.ub = ub; } @Override public void propagate(int evtmask) throws ContradictionException { // with views such as abs(...), the prop can be not entailed after initial propagation + if(lb <= vars[0].getLB() && ub >= vars[0].getUB()){ + this.setPassive(); + return; + } boolean change = vars[0].updateLowerBound(lb, this); - change &= vars[0].updateUpperBound(ub, this); + change |= vars[0].updateUpperBound(ub, this); if(change){ this.setPassive(); } } @Override public void propagate(AbstractFineEventRecorder eventRecorder, int varIdx, int mask) throws ContradictionException { propagate(EventType.FULL_PROPAGATION.mask); } @Override public int getPropagationConditions(int vIdx) { if (vars[vIdx].hasEnumeratedDomain()) { return EventType.INT_ALL_MASK(); } return EventType.INSTANTIATE.mask + EventType.BOUND.mask; } @Override public ESat isEntailed() { if(vars[0].getLB() >= lb && vars[0].getUB() <= ub){ return ESat.TRUE; }else if(vars[0].getUB() < lb || vars[0].getLB() > ub){ return ESat.FALSE; } return ESat.UNDEFINED; } @Override public String toString() { return vars[0].getName() + " in [" + lb + "," + ub + "]"; } @Override public Explanation explain(Deduction d) { return new Explanation(this); } }
false
true
public void propagate(int evtmask) throws ContradictionException { // with views such as abs(...), the prop can be not entailed after initial propagation boolean change = vars[0].updateLowerBound(lb, this); change &= vars[0].updateUpperBound(ub, this); if(change){ this.setPassive(); } }
public void propagate(int evtmask) throws ContradictionException { // with views such as abs(...), the prop can be not entailed after initial propagation if(lb <= vars[0].getLB() && ub >= vars[0].getUB()){ this.setPassive(); return; } boolean change = vars[0].updateLowerBound(lb, this); change |= vars[0].updateUpperBound(ub, this); if(change){ this.setPassive(); } }
diff --git a/src/com/example/bigthought/BigThought.java b/src/com/example/bigthought/BigThought.java index 4dec057..dd0699d 100644 --- a/src/com/example/bigthought/BigThought.java +++ b/src/com/example/bigthought/BigThought.java @@ -1,484 +1,484 @@ package com.example.bigthought; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Date; import java.util.Random; import com.example.bigthought.R.drawable; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.text.format.DateFormat; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; //import com.androidworks.R; //import com.androidworks.R; public class BigThought extends Activity { final int RESULT_LOAD_IMAGE = 1; final int PIC_CROP = 2; final int CAMERA_CAPTURE = 3; final int PHOTO_PICKED = 4; private Uri picUri; private EditText inputEditText; // private Bitmap uploadPic; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { File testFolder = new File( Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/BigThoughtPhoto"); testFolder.mkdirs(); // VERY IMPORTANT testFolder.canRead(); } catch (Exception e) { Toast.makeText(this, "Screw it", Toast.LENGTH_LONG).show(); } Button openButton = (Button) findViewById(R.id.openButton); openButton.setOnClickListener(openButtonOnClickListener); Button shareButton = (Button) findViewById(R.id.shareButton); shareButton.setOnClickListener(shareButtonOnClickListener); Button cameraButton = (Button) findViewById(R.id.cameraButton); cameraButton.setOnClickListener(cameraButtonOnClickListener); inputEditText = (EditText) findViewById(R.id.inputEditText); inputEditText.setOnClickListener(inputEditTextOnClickListener); // inputEditText.setText("Insert your deep thought here"); } public OnClickListener openButtonOnClickListener = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent i = new Intent( Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, RESULT_LOAD_IMAGE); } }; public OnClickListener inputEditTextOnClickListener = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub inputEditText.setText(""); inputEditText.setTextColor(0xFF000000); } }; public OnClickListener cameraButtonOnClickListener = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub // use standard intent to capture an image Intent captureIntent = new Intent( android.provider.MediaStore.ACTION_IMAGE_CAPTURE); // we will handle the returned data in onActivityResult startActivityForResult(captureIntent, CAMERA_CAPTURE); } }; public OnClickListener shareButtonOnClickListener = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub share(); } }; private void share() { Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); // Bitmap sharePic; String path = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/BigThoughtPhoto/toShare.png"; File sharePic = new File(path); Uri uri = Uri.fromFile(sharePic); sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject here"); sharingIntent.putExtra(android.content.Intent.EXTRA_STREAM, uri); sharingIntent.setType("image/*"); startActivity(Intent.createChooser(sharingIntent, "Share via")); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); - if (requestCode == RESULT_LOAD_IMAGE) { + if (requestCode == RESULT_LOAD_IMAGE && resultCode==RESULT_OK) { // get the Uri for the captured image picUri = data.getData(); // carry out the crop operation crop(picUri); } // user is returning from cropping the image - else if (requestCode == PIC_CROP) { + else if (requestCode == PIC_CROP && resultCode==RESULT_OK) { // get the returned data Uri picUri = Uri.fromFile(getTempFile()); String mText = inputEditText.getText().toString(); // Bundle extras = data.getExtras(); // get the cropped bitmap Bitmap thePic = null; try { thePic = MediaStore.Images.Media.getBitmap( this.getContentResolver(), picUri); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Bitmap bmp = postProcessing(this, thePic, mText); // Naming by date Date d = new Date(); CharSequence s = DateFormat .format("MM-dd-yy hh:mm:ss", d.getTime()); String fileName = "/" + s.toString() + ".png"; String sharePic = "/toShare.png"; try { File testFolder = new File( Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/BigThoughtPhoto"); testFolder.mkdirs(); // VERY IMPORTANT testFolder.canRead(); try { FileOutputStream out = new FileOutputStream( testFolder.getAbsolutePath() + fileName); bmp.compress(Bitmap.CompressFormat.PNG, 90, out); FileOutputStream toShare = new FileOutputStream( testFolder.getAbsolutePath() + sharePic); bmp.compress(Bitmap.CompressFormat.PNG, 90, toShare); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } // retrieve a reference to the ImageView ImageView picView = (ImageView) findViewById(R.id.imageView1); // display the returned cropped image picView.setImageBitmap(bmp); } - else if (requestCode == CAMERA_CAPTURE) { + else if (requestCode == CAMERA_CAPTURE && resultCode==RESULT_OK) { // get the Uri for the captured image picUri = data.getData(); // carry out the crop operation crop(picUri); } } private void crop(Uri picUri) { try { Uri tempUri = Uri.fromFile(getTempFile()); Intent cropIntent = new Intent("com.android.camera.action.CROP"); // indicate image type and Uri cropIntent.setDataAndType(picUri, "image/*"); // set crop properties cropIntent.putExtra("crop", "true"); // indicate aspect of desired crop cropIntent.putExtra("aspectX", 1); cropIntent.putExtra("aspectY", 1); // indicate output X and Y cropIntent.putExtra("outputX", 500); cropIntent.putExtra("outputY", 500); // retrieve data on return // cropIntent.putExtra("return-data", true); cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri); cropIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); // End test // done cropping, return out the result startActivityForResult(cropIntent, PIC_CROP); } catch (ActivityNotFoundException anfe) { // display an error message String errorMessage = "Your device sucks"; Toast toast = Toast .makeText(this, errorMessage, Toast.LENGTH_SHORT); toast.show(); } } private File getTempFile() { if (isSDCARDMounted()) { File f = new File( Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/BigThoughtPhoto/temp.tmp"); try { f.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block Toast.makeText(this, "IOerror", Toast.LENGTH_LONG).show(); } return f; } else { return null; } } private boolean isSDCARDMounted() { String status = Environment.getExternalStorageState(); if (status.equals(Environment.MEDIA_MOUNTED)) return true; return false; } public Bitmap postProcessing(Context mContext, Bitmap bitmap, String mText) { int canvasSize = 530; int margin = 15; int fontSize = 30; Typeface fontFormat = Typeface.create("Helvetica", Typeface.BOLD); try { Resources resources = mContext.getResources(); float scale = resources.getDisplayMetrics().density; android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig(); // set default bitmap config if none if (bitmapConfig == null) { bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888; } // resource bitmaps are imutable, // so we need to convert it to mutable one bitmap = bitmap.copy(bitmapConfig, true); // bitmap = BitmapFactory.decodeResource(this.getResources(), // R.drawable.noise); bitmap = colorBlend(bitmap); //bitmap=addNoise(bitmap); bitmap=addVignete(bitmap); // Test frame Bitmap frame = Bitmap.createBitmap(canvasSize, canvasSize, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(frame); canvas.drawColor(getResources().getColor(R.color.light)); canvas.drawBitmap(bitmap, margin, margin, null); // done testing frame // Canvas canvas = new Canvas(bitmap); // new antialised Paint Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); // text color - #3D3D3D paint.setColor(getResources().getColor(R.color.light)); // text size in pixels paint.setAlpha(255); paint.setTypeface(fontFormat); paint.setTextAlign(Align.CENTER); // text shadow paint.setShadowLayer(1f, 0f, 1f, Color.DKGRAY); // draw text to the Canvas center Rect bounds = new Rect(); paint.getTextBounds(mText, 0, mText.length(), bounds); Log.d("value", String.valueOf(bounds.width())+"h: "+String.valueOf(bitmap.getHeight())+"w: "+String.valueOf(bitmap.getWidth())); double width_factor=180.0/bounds.width(); double height_factor=50.0/bounds.height(); double factor=Math.min(width_factor, height_factor); if(factor>1){ factor=1; } Log.d("code", String.valueOf(factor)+":"+ String.valueOf(paint.getTextSize())); paint.setTextSize((int) (fontSize *factor)); int x = (bitmap.getWidth() - bounds.width()) / 6; int y = (bitmap.getHeight() + bounds.height()) / 5; canvas.drawText(mText, 265, 175, paint); return frame; } catch (Exception e) { // TODO: handle exception return null; } } public Bitmap vintage(Bitmap source) { // get image size int COLOR_MIN = 0x00; int COLOR_MAX = 0xFF; int width = source.getWidth(); int height = source.getHeight(); int[] pixels = new int[width * height]; // get pixel array from source source.getPixels(pixels, 0, width, 0, 0, width, height); // a random object Random random = new Random(); int index = 0; // iteration through pixels for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { // get current index in 2D-matrix index = y * width + x; // get random color int randColor = Color.rgb(random.nextInt(COLOR_MAX), random.nextInt(COLOR_MAX), random.nextInt(COLOR_MAX)); // OR pixels[index] |= randColor; } } // output bitmap Bitmap bmOut = Bitmap.createBitmap(width, height, source.getConfig()); bmOut.setPixels(pixels, 0, width, 0, 0, width, height); return bmOut; } public Bitmap addNoise(Bitmap source) { // MUST create folder drawable Bitmap original = source; Bitmap mask = BitmapFactory.decodeResource(getResources(),drawable.noise); Bitmap result = Bitmap.createBitmap(mask.getWidth(), mask.getHeight(),Bitmap.Config.ARGB_8888); Canvas mCanvas = new Canvas(result); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); //Useable mode: Overlay, multiply paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.OVERLAY)); mCanvas.drawBitmap(original, 0, 0, null); mCanvas.drawBitmap(mask, 0, 0, paint); paint.setXfermode(null); return result; } public Bitmap addVignete(Bitmap source) { Bitmap original = source; Bitmap mask = BitmapFactory.decodeResource(getResources(),drawable.mask); Bitmap result = Bitmap.createBitmap(mask.getWidth(), mask.getHeight(),Bitmap.Config.ARGB_8888); Canvas mCanvas = new Canvas(result); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); //Useable mode: Overlay, multiply paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.OVERLAY)); mCanvas.drawBitmap(original, 0, 0, null); mCanvas.drawBitmap(mask, 0, 0, paint); paint.setXfermode(null); return result; } public Bitmap colorBlend(Bitmap source) { int[] rValue = { 52, 53, 54, 59, 73, 101, 134, 164, 186, 205, 219, 231, 240, 245, 249, 250, 255 }; int[] gValue = { 45, 51, 64, 79, 97, 117, 137, 155, 170, 182, 194, 202, 210, 215, 218, 250, 255 }; int[] bValue = { 96, 102, 108, 115, 124, 133, 141, 146, 156, 159, 166, 170, 172, 175, 176, 177, 255 }; for (int i = 0; i < 500; i++) { for (int j = 0; j < 500; j++) { int p = source.getPixel(i, j); //Log.d("pointvalue", String.valueOf(p)); int R = (p >> 16) & 0xff; int G = (p >> 8) & 0xff; int B = p & 0xff; // if (true) { // Log.d("value", String.valueOf(R) + String.valueOf(G) // + String.valueOf(B)); // } // red channel int r = (rValue[R / 16 + 1] - rValue[R / 16]) * (R % 16) / 16 + rValue[R / 16]; int g = (gValue[G / 16 + 1] - gValue[G / 16]) * (G % 16) / 16 + gValue[G / 16]; int b = (bValue[B / 16 + 1] - bValue[B / 16]) * (B % 16) / 16 + bValue[B / 16]; // if (true) { // Log.d("code", String.valueOf(r) + String.valueOf(g) // + String.valueOf(b)); // } int color = Color.argb(255, r, g, b); source.setPixel(i, j, color); } } return source; } public int transformRed(int Rxy, int x, int y) { return Rxy; } public static Bitmap applyGaussianBlur(Bitmap src) { double[][] GaussianBlurConfig = new double[][] { { 1, 2, 1 }, { 2, 4, 2 }, { 1, 2, 1 } }; ConvolutionMatrix convMatrix = new ConvolutionMatrix(3); convMatrix.applyConfig(GaussianBlurConfig); convMatrix.Factor = 16; convMatrix.Offset = 0; return ConvolutionMatrix.computeConvolution3x3(src, convMatrix); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.big_thought, menu); return true; } // }
false
true
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_LOAD_IMAGE) { // get the Uri for the captured image picUri = data.getData(); // carry out the crop operation crop(picUri); } // user is returning from cropping the image else if (requestCode == PIC_CROP) { // get the returned data Uri picUri = Uri.fromFile(getTempFile()); String mText = inputEditText.getText().toString(); // Bundle extras = data.getExtras(); // get the cropped bitmap Bitmap thePic = null; try { thePic = MediaStore.Images.Media.getBitmap( this.getContentResolver(), picUri); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Bitmap bmp = postProcessing(this, thePic, mText); // Naming by date Date d = new Date(); CharSequence s = DateFormat .format("MM-dd-yy hh:mm:ss", d.getTime()); String fileName = "/" + s.toString() + ".png"; String sharePic = "/toShare.png"; try { File testFolder = new File( Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/BigThoughtPhoto"); testFolder.mkdirs(); // VERY IMPORTANT testFolder.canRead(); try { FileOutputStream out = new FileOutputStream( testFolder.getAbsolutePath() + fileName); bmp.compress(Bitmap.CompressFormat.PNG, 90, out); FileOutputStream toShare = new FileOutputStream( testFolder.getAbsolutePath() + sharePic); bmp.compress(Bitmap.CompressFormat.PNG, 90, toShare); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } // retrieve a reference to the ImageView ImageView picView = (ImageView) findViewById(R.id.imageView1); // display the returned cropped image picView.setImageBitmap(bmp); } else if (requestCode == CAMERA_CAPTURE) { // get the Uri for the captured image picUri = data.getData(); // carry out the crop operation crop(picUri); } }
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_LOAD_IMAGE && resultCode==RESULT_OK) { // get the Uri for the captured image picUri = data.getData(); // carry out the crop operation crop(picUri); } // user is returning from cropping the image else if (requestCode == PIC_CROP && resultCode==RESULT_OK) { // get the returned data Uri picUri = Uri.fromFile(getTempFile()); String mText = inputEditText.getText().toString(); // Bundle extras = data.getExtras(); // get the cropped bitmap Bitmap thePic = null; try { thePic = MediaStore.Images.Media.getBitmap( this.getContentResolver(), picUri); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Bitmap bmp = postProcessing(this, thePic, mText); // Naming by date Date d = new Date(); CharSequence s = DateFormat .format("MM-dd-yy hh:mm:ss", d.getTime()); String fileName = "/" + s.toString() + ".png"; String sharePic = "/toShare.png"; try { File testFolder = new File( Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/BigThoughtPhoto"); testFolder.mkdirs(); // VERY IMPORTANT testFolder.canRead(); try { FileOutputStream out = new FileOutputStream( testFolder.getAbsolutePath() + fileName); bmp.compress(Bitmap.CompressFormat.PNG, 90, out); FileOutputStream toShare = new FileOutputStream( testFolder.getAbsolutePath() + sharePic); bmp.compress(Bitmap.CompressFormat.PNG, 90, toShare); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } // retrieve a reference to the ImageView ImageView picView = (ImageView) findViewById(R.id.imageView1); // display the returned cropped image picView.setImageBitmap(bmp); } else if (requestCode == CAMERA_CAPTURE && resultCode==RESULT_OK) { // get the Uri for the captured image picUri = data.getData(); // carry out the crop operation crop(picUri); } }
diff --git a/atlas-web/src/main/java/uk/ac/ebi/gxa/requesthandlers/query/ExperimentsPopupRequestHandler.java b/atlas-web/src/main/java/uk/ac/ebi/gxa/requesthandlers/query/ExperimentsPopupRequestHandler.java index a7f718f58..60e17983d 100644 --- a/atlas-web/src/main/java/uk/ac/ebi/gxa/requesthandlers/query/ExperimentsPopupRequestHandler.java +++ b/atlas-web/src/main/java/uk/ac/ebi/gxa/requesthandlers/query/ExperimentsPopupRequestHandler.java @@ -1,212 +1,211 @@ /* * Copyright 2008-2010 Microarray Informatics Team, EMBL-European Bioinformatics Institute * * 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. * * * For further details of the Gene Expression Atlas project, including source code, * downloads and documentation, please see: * * http://gxa.github.com/gxa */ package uk.ac.ebi.gxa.requesthandlers.query; import ae3.dao.AtlasSolrDAO; import ae3.model.AtlasExperiment; import ae3.model.AtlasGene; import ae3.service.AtlasStatisticsQueryService; import ae3.service.structuredquery.Constants; import uk.ac.ebi.gxa.efo.Efo; import uk.ac.ebi.gxa.efo.EfoTerm; import uk.ac.ebi.gxa.properties.AtlasProperties; import uk.ac.ebi.gxa.requesthandlers.base.AbstractRestRequestHandler; import uk.ac.ebi.gxa.statistics.Attribute; import uk.ac.ebi.gxa.statistics.Experiment; import uk.ac.ebi.gxa.statistics.StatisticsQueryUtils; import uk.ac.ebi.gxa.utils.EscapeUtil; import uk.ac.ebi.microarray.atlas.model.ExpressionAnalysis; import javax.servlet.http.HttpServletRequest; import java.util.*; import static uk.ac.ebi.gxa.statistics.StatisticsType.*; /** * @author pashky */ public class ExperimentsPopupRequestHandler extends AbstractRestRequestHandler { private AtlasSolrDAO atlasSolrDAO; private Efo efo; private AtlasProperties atlasProperties; private AtlasStatisticsQueryService atlasStatisticsQueryService; public void setDao(AtlasSolrDAO atlasSolrDAO) { this.atlasSolrDAO = atlasSolrDAO; } public void setEfo(Efo efo) { this.efo = efo; } public void setAtlasProperties(AtlasProperties atlasProperties) { this.atlasProperties = atlasProperties; } public void setAtlasStatisticsQueryService(AtlasStatisticsQueryService atlasStatisticsQueryService) { this.atlasStatisticsQueryService = atlasStatisticsQueryService; } public Object process(HttpServletRequest request) { Map<String, Object> jsResult = new HashMap<String, Object>(); String geneIdKey = request.getParameter("gene"); String factor = request.getParameter("ef"); String factorValue = request.getParameter("efv"); if (geneIdKey != null && factor != null && factorValue != null) { final long geneId = Long.parseLong(geneIdKey); boolean isEfo = Constants.EFO_FACTOR_NAME.equals(factor); jsResult.put("ef", factor); jsResult.put("eftext", atlasProperties.getCuratedEf(factor)); jsResult.put("efv", factorValue); if (isEfo) { EfoTerm term = efo.getTermById(factorValue); if (term != null) { jsResult.put("efv", term.getTerm()); - factorValue = term.getTerm(); } } Attribute attr = StatisticsQueryUtils.getAttribute(factor, factorValue, isEfo, UP_DOWN); AtlasSolrDAO.AtlasGeneResult result = atlasSolrDAO.getGeneById(geneId); if (!result.isFound()) { throw new IllegalArgumentException("Atlas gene " + geneId + " not found"); } AtlasGene gene = result.getGene(); Map<String, Object> jsGene = new HashMap<String, Object>(); jsGene.put("id", gene.getGeneId()); jsGene.put("identifier", gene.getGeneIdentifier()); jsGene.put("name", gene.getGeneName()); jsResult.put("gene", jsGene); List<Experiment> experiments = atlasStatisticsQueryService.getExperimentsSortedByPvalueTRank(gene.getGeneId(), attr, -1, -1); Map<Long, Map<String, List<Experiment>>> exmap = new HashMap<Long, Map<String, List<Experiment>>>(); for (Experiment experiment : experiments) { Long experimentId = experiment.getExperimentId(); Map<String, List<Experiment>> efmap = exmap.get(experimentId); if (efmap == null) { exmap.put(experimentId, efmap = new HashMap<String, List<Experiment>>()); } List<Experiment> list = efmap.get(experiment.getHighestRankAttribute().getEf()); if (list == null) { efmap.put(experiment.getHighestRankAttribute().getEf(), list = new ArrayList<Experiment>()); } list.add(experiment); } for (Map<String, List<Experiment>> ef : exmap.values()) { for (List<Experiment> e : ef.values()) { Collections.sort(e, new Comparator<Experiment>() { public int compare(Experiment o1, Experiment o2) { return o1.getpValTStatRank().compareTo(o2.getpValTStatRank()); } }); } } @SuppressWarnings("unchecked") List<Map.Entry<Long, Map<String, List<Experiment>>>> exps = new ArrayList<Map.Entry<Long, Map<String, List<Experiment>>>>(exmap.entrySet()); Collections.sort(exps, new Comparator<Map.Entry<Long, Map<String, List<Experiment>>>>() { public int compare(Map.Entry<Long, Map<String, List<Experiment>>> o1, Map.Entry<Long, Map<String, List<Experiment>>> o2) { double minp1 = 1; for (Map.Entry<String, List<Experiment>> ef : o1.getValue().entrySet()) { minp1 = Math.min(minp1, ef.getValue().get(0).getpValTStatRank().getPValue()); } double minp2 = 1; for (Map.Entry<String, List<Experiment>> ef : o2.getValue().entrySet()) { minp2 = Math.min(minp2, ef.getValue().get(0).getpValTStatRank().getPValue()); } return minp1 < minp2 ? -1 : 1; } }); List<Map> jsExps = new ArrayList<Map>(); for (Map.Entry<Long, Map<String, List<Experiment>>> e : exps) { AtlasExperiment aexp = atlasSolrDAO.getExperimentById(e.getKey()); if (aexp != null) { Map<String, Object> jsExp = new HashMap<String, Object>(); jsExp.put("accession", aexp.getAccession()); jsExp.put("name", aexp.getDescription()); jsExp.put("id", e.getKey()); List<Map> jsEfs = new ArrayList<Map>(); for (Map.Entry<String, List<Experiment>> ef : e.getValue().entrySet()) { Map<String, Object> jsEf = new HashMap<String, Object>(); jsEf.put("ef", ef.getKey()); jsEf.put("eftext", atlasProperties.getCuratedEf(ef.getKey())); List<Map> jsEfvs = new ArrayList<Map>(); for (Experiment exp : ef.getValue()) { Map<String, Object> jsEfv = new HashMap<String, Object>(); boolean isNo = ExpressionAnalysis.isNo(exp.getpValTStatRank().getPValue(), exp.getpValTStatRank().getTStatRank()); boolean isUp = ExpressionAnalysis.isUp(exp.getpValTStatRank().getPValue(), exp.getpValTStatRank().getTStatRank()); jsEfv.put("efv", exp.getHighestRankAttribute().getEfv()); jsEfv.put("isexp", isNo ? "no" : (isUp ? "up" : "dn")); jsEfv.put("pvalue", exp.getpValTStatRank().getPValue()); jsEfvs.add(jsEfv); } jsEf.put("efvs", jsEfvs); if (!jsEfvs.isEmpty()) jsEfs.add(jsEf); } jsExp.put("efs", jsEfs); jsExps.add(jsExp); } } jsResult.put("experiments", jsExps); // TODO: we might be better off with one entity encapsulating the expression stats long start = System.currentTimeMillis(); attr.setStatType(NON_D_E); int numNo = atlasStatisticsQueryService.getExperimentCountsForGene(attr, geneId); attr.setStatType(UP); int numUp = atlasStatisticsQueryService.getExperimentCountsForGene(attr, geneId); attr.setStatType(DOWN); int numDn = atlasStatisticsQueryService.getExperimentCountsForGene(attr, geneId); log.debug("Obtained counts for gene: " + geneId + " and attribute: " + attr + " in: " + (System.currentTimeMillis() - start) + " ms"); jsResult.put("numUp", numUp); jsResult.put("numDn", numDn); jsResult.put("numNo", numNo); } return jsResult; } }
true
true
public Object process(HttpServletRequest request) { Map<String, Object> jsResult = new HashMap<String, Object>(); String geneIdKey = request.getParameter("gene"); String factor = request.getParameter("ef"); String factorValue = request.getParameter("efv"); if (geneIdKey != null && factor != null && factorValue != null) { final long geneId = Long.parseLong(geneIdKey); boolean isEfo = Constants.EFO_FACTOR_NAME.equals(factor); jsResult.put("ef", factor); jsResult.put("eftext", atlasProperties.getCuratedEf(factor)); jsResult.put("efv", factorValue); if (isEfo) { EfoTerm term = efo.getTermById(factorValue); if (term != null) { jsResult.put("efv", term.getTerm()); factorValue = term.getTerm(); } } Attribute attr = StatisticsQueryUtils.getAttribute(factor, factorValue, isEfo, UP_DOWN); AtlasSolrDAO.AtlasGeneResult result = atlasSolrDAO.getGeneById(geneId); if (!result.isFound()) { throw new IllegalArgumentException("Atlas gene " + geneId + " not found"); } AtlasGene gene = result.getGene(); Map<String, Object> jsGene = new HashMap<String, Object>(); jsGene.put("id", gene.getGeneId()); jsGene.put("identifier", gene.getGeneIdentifier()); jsGene.put("name", gene.getGeneName()); jsResult.put("gene", jsGene); List<Experiment> experiments = atlasStatisticsQueryService.getExperimentsSortedByPvalueTRank(gene.getGeneId(), attr, -1, -1); Map<Long, Map<String, List<Experiment>>> exmap = new HashMap<Long, Map<String, List<Experiment>>>(); for (Experiment experiment : experiments) { Long experimentId = experiment.getExperimentId(); Map<String, List<Experiment>> efmap = exmap.get(experimentId); if (efmap == null) { exmap.put(experimentId, efmap = new HashMap<String, List<Experiment>>()); } List<Experiment> list = efmap.get(experiment.getHighestRankAttribute().getEf()); if (list == null) { efmap.put(experiment.getHighestRankAttribute().getEf(), list = new ArrayList<Experiment>()); } list.add(experiment); } for (Map<String, List<Experiment>> ef : exmap.values()) { for (List<Experiment> e : ef.values()) { Collections.sort(e, new Comparator<Experiment>() { public int compare(Experiment o1, Experiment o2) { return o1.getpValTStatRank().compareTo(o2.getpValTStatRank()); } }); } } @SuppressWarnings("unchecked") List<Map.Entry<Long, Map<String, List<Experiment>>>> exps = new ArrayList<Map.Entry<Long, Map<String, List<Experiment>>>>(exmap.entrySet()); Collections.sort(exps, new Comparator<Map.Entry<Long, Map<String, List<Experiment>>>>() { public int compare(Map.Entry<Long, Map<String, List<Experiment>>> o1, Map.Entry<Long, Map<String, List<Experiment>>> o2) { double minp1 = 1; for (Map.Entry<String, List<Experiment>> ef : o1.getValue().entrySet()) { minp1 = Math.min(minp1, ef.getValue().get(0).getpValTStatRank().getPValue()); } double minp2 = 1; for (Map.Entry<String, List<Experiment>> ef : o2.getValue().entrySet()) { minp2 = Math.min(minp2, ef.getValue().get(0).getpValTStatRank().getPValue()); } return minp1 < minp2 ? -1 : 1; } }); List<Map> jsExps = new ArrayList<Map>(); for (Map.Entry<Long, Map<String, List<Experiment>>> e : exps) { AtlasExperiment aexp = atlasSolrDAO.getExperimentById(e.getKey()); if (aexp != null) { Map<String, Object> jsExp = new HashMap<String, Object>(); jsExp.put("accession", aexp.getAccession()); jsExp.put("name", aexp.getDescription()); jsExp.put("id", e.getKey()); List<Map> jsEfs = new ArrayList<Map>(); for (Map.Entry<String, List<Experiment>> ef : e.getValue().entrySet()) { Map<String, Object> jsEf = new HashMap<String, Object>(); jsEf.put("ef", ef.getKey()); jsEf.put("eftext", atlasProperties.getCuratedEf(ef.getKey())); List<Map> jsEfvs = new ArrayList<Map>(); for (Experiment exp : ef.getValue()) { Map<String, Object> jsEfv = new HashMap<String, Object>(); boolean isNo = ExpressionAnalysis.isNo(exp.getpValTStatRank().getPValue(), exp.getpValTStatRank().getTStatRank()); boolean isUp = ExpressionAnalysis.isUp(exp.getpValTStatRank().getPValue(), exp.getpValTStatRank().getTStatRank()); jsEfv.put("efv", exp.getHighestRankAttribute().getEfv()); jsEfv.put("isexp", isNo ? "no" : (isUp ? "up" : "dn")); jsEfv.put("pvalue", exp.getpValTStatRank().getPValue()); jsEfvs.add(jsEfv); } jsEf.put("efvs", jsEfvs); if (!jsEfvs.isEmpty()) jsEfs.add(jsEf); } jsExp.put("efs", jsEfs); jsExps.add(jsExp); } } jsResult.put("experiments", jsExps); // TODO: we might be better off with one entity encapsulating the expression stats long start = System.currentTimeMillis(); attr.setStatType(NON_D_E); int numNo = atlasStatisticsQueryService.getExperimentCountsForGene(attr, geneId); attr.setStatType(UP); int numUp = atlasStatisticsQueryService.getExperimentCountsForGene(attr, geneId); attr.setStatType(DOWN); int numDn = atlasStatisticsQueryService.getExperimentCountsForGene(attr, geneId); log.debug("Obtained counts for gene: " + geneId + " and attribute: " + attr + " in: " + (System.currentTimeMillis() - start) + " ms"); jsResult.put("numUp", numUp); jsResult.put("numDn", numDn); jsResult.put("numNo", numNo); } return jsResult; }
public Object process(HttpServletRequest request) { Map<String, Object> jsResult = new HashMap<String, Object>(); String geneIdKey = request.getParameter("gene"); String factor = request.getParameter("ef"); String factorValue = request.getParameter("efv"); if (geneIdKey != null && factor != null && factorValue != null) { final long geneId = Long.parseLong(geneIdKey); boolean isEfo = Constants.EFO_FACTOR_NAME.equals(factor); jsResult.put("ef", factor); jsResult.put("eftext", atlasProperties.getCuratedEf(factor)); jsResult.put("efv", factorValue); if (isEfo) { EfoTerm term = efo.getTermById(factorValue); if (term != null) { jsResult.put("efv", term.getTerm()); } } Attribute attr = StatisticsQueryUtils.getAttribute(factor, factorValue, isEfo, UP_DOWN); AtlasSolrDAO.AtlasGeneResult result = atlasSolrDAO.getGeneById(geneId); if (!result.isFound()) { throw new IllegalArgumentException("Atlas gene " + geneId + " not found"); } AtlasGene gene = result.getGene(); Map<String, Object> jsGene = new HashMap<String, Object>(); jsGene.put("id", gene.getGeneId()); jsGene.put("identifier", gene.getGeneIdentifier()); jsGene.put("name", gene.getGeneName()); jsResult.put("gene", jsGene); List<Experiment> experiments = atlasStatisticsQueryService.getExperimentsSortedByPvalueTRank(gene.getGeneId(), attr, -1, -1); Map<Long, Map<String, List<Experiment>>> exmap = new HashMap<Long, Map<String, List<Experiment>>>(); for (Experiment experiment : experiments) { Long experimentId = experiment.getExperimentId(); Map<String, List<Experiment>> efmap = exmap.get(experimentId); if (efmap == null) { exmap.put(experimentId, efmap = new HashMap<String, List<Experiment>>()); } List<Experiment> list = efmap.get(experiment.getHighestRankAttribute().getEf()); if (list == null) { efmap.put(experiment.getHighestRankAttribute().getEf(), list = new ArrayList<Experiment>()); } list.add(experiment); } for (Map<String, List<Experiment>> ef : exmap.values()) { for (List<Experiment> e : ef.values()) { Collections.sort(e, new Comparator<Experiment>() { public int compare(Experiment o1, Experiment o2) { return o1.getpValTStatRank().compareTo(o2.getpValTStatRank()); } }); } } @SuppressWarnings("unchecked") List<Map.Entry<Long, Map<String, List<Experiment>>>> exps = new ArrayList<Map.Entry<Long, Map<String, List<Experiment>>>>(exmap.entrySet()); Collections.sort(exps, new Comparator<Map.Entry<Long, Map<String, List<Experiment>>>>() { public int compare(Map.Entry<Long, Map<String, List<Experiment>>> o1, Map.Entry<Long, Map<String, List<Experiment>>> o2) { double minp1 = 1; for (Map.Entry<String, List<Experiment>> ef : o1.getValue().entrySet()) { minp1 = Math.min(minp1, ef.getValue().get(0).getpValTStatRank().getPValue()); } double minp2 = 1; for (Map.Entry<String, List<Experiment>> ef : o2.getValue().entrySet()) { minp2 = Math.min(minp2, ef.getValue().get(0).getpValTStatRank().getPValue()); } return minp1 < minp2 ? -1 : 1; } }); List<Map> jsExps = new ArrayList<Map>(); for (Map.Entry<Long, Map<String, List<Experiment>>> e : exps) { AtlasExperiment aexp = atlasSolrDAO.getExperimentById(e.getKey()); if (aexp != null) { Map<String, Object> jsExp = new HashMap<String, Object>(); jsExp.put("accession", aexp.getAccession()); jsExp.put("name", aexp.getDescription()); jsExp.put("id", e.getKey()); List<Map> jsEfs = new ArrayList<Map>(); for (Map.Entry<String, List<Experiment>> ef : e.getValue().entrySet()) { Map<String, Object> jsEf = new HashMap<String, Object>(); jsEf.put("ef", ef.getKey()); jsEf.put("eftext", atlasProperties.getCuratedEf(ef.getKey())); List<Map> jsEfvs = new ArrayList<Map>(); for (Experiment exp : ef.getValue()) { Map<String, Object> jsEfv = new HashMap<String, Object>(); boolean isNo = ExpressionAnalysis.isNo(exp.getpValTStatRank().getPValue(), exp.getpValTStatRank().getTStatRank()); boolean isUp = ExpressionAnalysis.isUp(exp.getpValTStatRank().getPValue(), exp.getpValTStatRank().getTStatRank()); jsEfv.put("efv", exp.getHighestRankAttribute().getEfv()); jsEfv.put("isexp", isNo ? "no" : (isUp ? "up" : "dn")); jsEfv.put("pvalue", exp.getpValTStatRank().getPValue()); jsEfvs.add(jsEfv); } jsEf.put("efvs", jsEfvs); if (!jsEfvs.isEmpty()) jsEfs.add(jsEf); } jsExp.put("efs", jsEfs); jsExps.add(jsExp); } } jsResult.put("experiments", jsExps); // TODO: we might be better off with one entity encapsulating the expression stats long start = System.currentTimeMillis(); attr.setStatType(NON_D_E); int numNo = atlasStatisticsQueryService.getExperimentCountsForGene(attr, geneId); attr.setStatType(UP); int numUp = atlasStatisticsQueryService.getExperimentCountsForGene(attr, geneId); attr.setStatType(DOWN); int numDn = atlasStatisticsQueryService.getExperimentCountsForGene(attr, geneId); log.debug("Obtained counts for gene: " + geneId + " and attribute: " + attr + " in: " + (System.currentTimeMillis() - start) + " ms"); jsResult.put("numUp", numUp); jsResult.put("numDn", numDn); jsResult.put("numNo", numNo); } return jsResult; }
diff --git a/WEB-INF/lps/server/src/org/openlaszlo/compiler/ToplevelCompiler.java b/WEB-INF/lps/server/src/org/openlaszlo/compiler/ToplevelCompiler.java index 88eef925..c932bd74 100644 --- a/WEB-INF/lps/server/src/org/openlaszlo/compiler/ToplevelCompiler.java +++ b/WEB-INF/lps/server/src/org/openlaszlo/compiler/ToplevelCompiler.java @@ -1,326 +1,326 @@ /* ***************************************************************************** * ToplevelCompiler.java * ****************************************************************************/ /* J_LZ_COPYRIGHT_BEGIN ******************************************************* * Copyright 2001-2007 Laszlo Systems, Inc. All Rights Reserved. * * Use is subject to license terms. * * J_LZ_COPYRIGHT_END *********************************************************/ package org.openlaszlo.compiler; import java.util.*; import java.io.*; import org.jdom.Element; import org.openlaszlo.compiler.ViewCompiler.*; import org.openlaszlo.server.*; import org.openlaszlo.utils.*; import org.jdom.*; import org.apache.log4j.*; /** Compiler for <code>canvas</code> and <code>library</code> elements. */ abstract class ToplevelCompiler extends ElementCompiler { /** Logger */ private static Logger mLogger = Logger.getLogger(ToplevelCompiler.class); ToplevelCompiler(CompilationEnvironment env) { super(env); } /** Returns true if the element is capable of acting as a toplevel * element. This is independent of whether it's positioned as a * toplevel element; CompilerUtils.isTopLevel() tests for position * as well. */ static boolean isElement(Element element) { return CanvasCompiler.isElement(element) || LibraryCompiler.isElement(element) || SwitchCompiler.isElement(element); } public void compile(Element element) { for (Iterator iter = element.getChildren().iterator(); iter.hasNext(); ) { Element child = (Element) iter.next(); if (!NodeModel.isPropertyElement(child)) { Compiler.compileElement(child, mEnv); } } } /** Parses out user class definitions. * * <p> * Iterates the direct children of the top level of the DOM tree and * look for elements named "class", find the "name" and "extends" * attributes, and enter them in the ViewSchema. * * Also check for the "validate" attribute, to optionally disable validator. * * @param visited {canonical filenames} for libraries whose * schemas have been visited; used to prevent recursive * processing. * */ void updateSchema(Element element, ViewSchema schema, Set visited) { setValidateProperty(element, mEnv); Iterator iterator = element.getChildren().iterator(); while (iterator.hasNext()) { Element child = (Element) iterator.next(); if (!NodeModel.isPropertyElement(child)) { Compiler.updateSchema(child, mEnv, schema, visited); } } } /** * Look for the "validate" attribute on canvas or at top level of imported libraries * * We look these places for the validate attribute: * <li> canvas (root) element * <li> direct child atttribute of canvas * @param root source code document root * @param env the CompilationEnvironment */ void setValidateProperty(Element root , CompilationEnvironment env) { String validate = CompilationEnvironment.VALIDATE_PROPERTY; // Look for canvas attribute if (root.getAttributeValue(validate) != null) { if ("false".equals(root.getAttributeValue("validate"))) { env.setProperty(validate, false); } else { env.setProperty(validate, true); } } // Look for direct canvas children <attribute name="validate" value="false"> for (Iterator iter = root.getChildren().iterator(); iter.hasNext(); ) { Element child = (Element) iter.next(); if (child.getName().equals("attribute") && validate.equals(child.getAttributeValue("name"))) { if ("false".equals(child.getAttributeValue("value"))) { env.setProperty(validate, false); } } } } static void collectReferences(CompilationEnvironment env, Element element, Set defined, Set referenced) { Set visited = new HashSet(); ViewCompiler.collectLayoutElement(element, referenced); collectReferences(env, element, defined, referenced, visited); } /** This also collects "attribute", "method", and HTML element * names, but that's okay since none of them has an autoinclude * entry. */ static void collectReferences(CompilationEnvironment env, Element element, Set defined, Set referenced, Set libsVisited) { ElementCompiler compiler = Compiler.getElementCompiler(element, env); if (compiler instanceof ToplevelCompiler) { if (compiler instanceof LibraryCompiler || compiler instanceof ImportCompiler ) { Element library = LibraryCompiler.resolveLibraryElement(element, env, libsVisited, false); if (library != null) { element = library; } } for (Iterator iter = element.getChildren().iterator(); iter.hasNext(); ) { collectReferences(env, (Element) iter.next(), defined, referenced, libsVisited); } } else if (compiler instanceof ClassCompiler || compiler instanceof InterfaceCompiler) { String name = element.getAttributeValue("name"); if (name != null) { defined.add(name); } String superclass = element.getAttributeValue("extends"); if (superclass != null) { referenced.add(superclass); } ViewCompiler.collectElementNames(element, referenced); } else if (compiler instanceof ViewCompiler) { ViewCompiler.collectElementNames(element, referenced); } } static List getLibraries(CompilationEnvironment env, Element element, Map explanations, Set autoIncluded, Set visited) { List libraryNames = new ArrayList(); String librariesAttr = element.getAttributeValue("libraries"); String base = new File(Parser.getSourcePathname(element)).getParent(); if (librariesAttr != null) { for (StringTokenizer st = new StringTokenizer(librariesAttr); st.hasMoreTokens();) { String name = (String) st.nextToken(); libraryNames.add(name); } } // figure out which tags are referenced but not defined, and // look up their libraries in the autoincludes file { Set defined = new HashSet(); Set referenced = new HashSet(); collectReferences(env, element, defined, referenced, visited); // keep the keys sorted so the order is deterministic for qa Set additionalLibraries = new TreeSet(); Map autoincludes = env.getSchema().sAutoincludes; Map canonicalAuto = new HashMap(); try { for (Iterator iter = autoincludes.keySet().iterator(); iter.hasNext(); ) { String key = (String) iter.next(); canonicalAuto.put(key, env.resolveLibrary((String)autoincludes.get(key), base).getCanonicalFile()); } } catch (IOException e) { throw new CompilationError(element, e); } // iterate undefined references for (Iterator iter = referenced.iterator(); iter.hasNext(); ) { String key = (String) iter.next(); if (autoincludes.containsKey(key)) { String value = (String) autoincludes.get(key); // Ensure that a library that was explicitly // included that would have been auto-included is // emitted where the auto-include would have been. if (defined.contains(key)) { File canonical = (File)canonicalAuto.get(key); if (visited.contains(canonical)) { // Annotate as explicit if (explanations != null) { explanations.put(value, "explicit include"); } // but include as auto additionalLibraries.add(value); } } else { if (explanations != null) { explanations.put(value, "reference to <" + key + "> tag"); } additionalLibraries.add(value); } } } // If not linking, consider all external libraries as // 'auto' if (autoIncluded != null) { try { - String basePrefix = (new File(base)).getCanonicalPath(); + String basePrefix = (new File((base != null) ? base : ".")).getCanonicalPath(); for (Iterator i = visited.iterator(); i.hasNext(); ) { File file = (File)i.next(); String path = file.getCanonicalPath(); if (! path.startsWith(basePrefix)) { autoIncluded.add(file); } } } catch (IOException e) { throw new CompilationError(element, e); } } libraryNames.addAll(additionalLibraries); } // Turn the library names into pathnames List libraries = new ArrayList(); for (Iterator iter = libraryNames.iterator(); iter.hasNext(); ) { String name = (String) iter.next(); try { File file = env.resolveLibrary(name, base).getCanonicalFile(); libraries.add(file); if (autoIncluded != null) { autoIncluded.add(file); } } catch (IOException e) { throw new CompilationError(element, e); } } // add the debugger, if canvas debug=true if (env.getBooleanProperty(env.DEBUG_PROPERTY)) { if (explanations != null) { explanations.put("debugger", "the canvas debug attribute is true"); } String pathname = LPS.getComponentsDirectory() + File.separator + "debugger" + File.separator + "debugger.lzx"; libraries.add(new File(pathname)); } return libraries; } List getLibraries(Element element) { return getLibraries(mEnv, element, null, null, new HashSet()); } static String getBaseLibraryName (CompilationEnvironment env) { // returns 5 or 6; coerce to string String swfversion = "" + env.getSWFVersionInt(); // Load the appropriate LFC Library according to debug, // profile, or krank // We will now have LFC library with swf version encoded after // the base name like: // LFC6.lzl // LFC5-debug.lzl // etc. String ext = swfversion; ext += env.getBooleanProperty(env.PROFILE_PROPERTY)?"-profile":""; ext += env.getBooleanProperty(env.DEBUG_PROPERTY)?"-debug":""; return "LFC" + ext + ".lzl"; } static void handleAutoincludes(CompilationEnvironment env, Element element) { // import required libraries, and collect explanations as to // why they were required Canvas canvas = env.getCanvas(); String baseLibraryName = getBaseLibraryName(env); String baseLibraryBecause = "Required for all applications"; Map explanations = new HashMap(); for (Iterator iter = getLibraries(env, element, explanations, null, new HashSet()).iterator(); iter.hasNext(); ) { File file = (File) iter.next(); Compiler.importLibrary(file, env); } // canvas info += <include name= explanation= [size=]/> for LFC Element info = new Element("include"); info.setAttribute("name", baseLibraryName); info.setAttribute("explanation", baseLibraryBecause); try { info.setAttribute("size", "" + FileUtils.getSize(env.resolveLibrary(baseLibraryName, ""))); } catch (Exception e) { mLogger.error( /* (non-Javadoc) * @i18n.test * @org-mes="exception getting library size" */ org.openlaszlo.i18n.LaszloMessages.getMessage( ToplevelCompiler.class.getName(),"051018-228") , e); } canvas.addInfo(info); // canvas info += <include name= explanation=/> for each library for (Iterator iter = explanations.entrySet().iterator(); iter.hasNext(); ) { Map.Entry entry = (Map.Entry) iter.next(); info = new Element("include"); info.setAttribute("name", entry.getKey().toString()); info.setAttribute("explanation", entry.getValue().toString()); canvas.addInfo(info); } } }
true
true
static List getLibraries(CompilationEnvironment env, Element element, Map explanations, Set autoIncluded, Set visited) { List libraryNames = new ArrayList(); String librariesAttr = element.getAttributeValue("libraries"); String base = new File(Parser.getSourcePathname(element)).getParent(); if (librariesAttr != null) { for (StringTokenizer st = new StringTokenizer(librariesAttr); st.hasMoreTokens();) { String name = (String) st.nextToken(); libraryNames.add(name); } } // figure out which tags are referenced but not defined, and // look up their libraries in the autoincludes file { Set defined = new HashSet(); Set referenced = new HashSet(); collectReferences(env, element, defined, referenced, visited); // keep the keys sorted so the order is deterministic for qa Set additionalLibraries = new TreeSet(); Map autoincludes = env.getSchema().sAutoincludes; Map canonicalAuto = new HashMap(); try { for (Iterator iter = autoincludes.keySet().iterator(); iter.hasNext(); ) { String key = (String) iter.next(); canonicalAuto.put(key, env.resolveLibrary((String)autoincludes.get(key), base).getCanonicalFile()); } } catch (IOException e) { throw new CompilationError(element, e); } // iterate undefined references for (Iterator iter = referenced.iterator(); iter.hasNext(); ) { String key = (String) iter.next(); if (autoincludes.containsKey(key)) { String value = (String) autoincludes.get(key); // Ensure that a library that was explicitly // included that would have been auto-included is // emitted where the auto-include would have been. if (defined.contains(key)) { File canonical = (File)canonicalAuto.get(key); if (visited.contains(canonical)) { // Annotate as explicit if (explanations != null) { explanations.put(value, "explicit include"); } // but include as auto additionalLibraries.add(value); } } else { if (explanations != null) { explanations.put(value, "reference to <" + key + "> tag"); } additionalLibraries.add(value); } } } // If not linking, consider all external libraries as // 'auto' if (autoIncluded != null) { try { String basePrefix = (new File(base)).getCanonicalPath(); for (Iterator i = visited.iterator(); i.hasNext(); ) { File file = (File)i.next(); String path = file.getCanonicalPath(); if (! path.startsWith(basePrefix)) { autoIncluded.add(file); } } } catch (IOException e) { throw new CompilationError(element, e); } } libraryNames.addAll(additionalLibraries); } // Turn the library names into pathnames List libraries = new ArrayList(); for (Iterator iter = libraryNames.iterator(); iter.hasNext(); ) { String name = (String) iter.next(); try { File file = env.resolveLibrary(name, base).getCanonicalFile(); libraries.add(file); if (autoIncluded != null) { autoIncluded.add(file); } } catch (IOException e) { throw new CompilationError(element, e); } } // add the debugger, if canvas debug=true if (env.getBooleanProperty(env.DEBUG_PROPERTY)) { if (explanations != null) { explanations.put("debugger", "the canvas debug attribute is true"); } String pathname = LPS.getComponentsDirectory() + File.separator + "debugger" + File.separator + "debugger.lzx"; libraries.add(new File(pathname)); } return libraries; }
static List getLibraries(CompilationEnvironment env, Element element, Map explanations, Set autoIncluded, Set visited) { List libraryNames = new ArrayList(); String librariesAttr = element.getAttributeValue("libraries"); String base = new File(Parser.getSourcePathname(element)).getParent(); if (librariesAttr != null) { for (StringTokenizer st = new StringTokenizer(librariesAttr); st.hasMoreTokens();) { String name = (String) st.nextToken(); libraryNames.add(name); } } // figure out which tags are referenced but not defined, and // look up their libraries in the autoincludes file { Set defined = new HashSet(); Set referenced = new HashSet(); collectReferences(env, element, defined, referenced, visited); // keep the keys sorted so the order is deterministic for qa Set additionalLibraries = new TreeSet(); Map autoincludes = env.getSchema().sAutoincludes; Map canonicalAuto = new HashMap(); try { for (Iterator iter = autoincludes.keySet().iterator(); iter.hasNext(); ) { String key = (String) iter.next(); canonicalAuto.put(key, env.resolveLibrary((String)autoincludes.get(key), base).getCanonicalFile()); } } catch (IOException e) { throw new CompilationError(element, e); } // iterate undefined references for (Iterator iter = referenced.iterator(); iter.hasNext(); ) { String key = (String) iter.next(); if (autoincludes.containsKey(key)) { String value = (String) autoincludes.get(key); // Ensure that a library that was explicitly // included that would have been auto-included is // emitted where the auto-include would have been. if (defined.contains(key)) { File canonical = (File)canonicalAuto.get(key); if (visited.contains(canonical)) { // Annotate as explicit if (explanations != null) { explanations.put(value, "explicit include"); } // but include as auto additionalLibraries.add(value); } } else { if (explanations != null) { explanations.put(value, "reference to <" + key + "> tag"); } additionalLibraries.add(value); } } } // If not linking, consider all external libraries as // 'auto' if (autoIncluded != null) { try { String basePrefix = (new File((base != null) ? base : ".")).getCanonicalPath(); for (Iterator i = visited.iterator(); i.hasNext(); ) { File file = (File)i.next(); String path = file.getCanonicalPath(); if (! path.startsWith(basePrefix)) { autoIncluded.add(file); } } } catch (IOException e) { throw new CompilationError(element, e); } } libraryNames.addAll(additionalLibraries); } // Turn the library names into pathnames List libraries = new ArrayList(); for (Iterator iter = libraryNames.iterator(); iter.hasNext(); ) { String name = (String) iter.next(); try { File file = env.resolveLibrary(name, base).getCanonicalFile(); libraries.add(file); if (autoIncluded != null) { autoIncluded.add(file); } } catch (IOException e) { throw new CompilationError(element, e); } } // add the debugger, if canvas debug=true if (env.getBooleanProperty(env.DEBUG_PROPERTY)) { if (explanations != null) { explanations.put("debugger", "the canvas debug attribute is true"); } String pathname = LPS.getComponentsDirectory() + File.separator + "debugger" + File.separator + "debugger.lzx"; libraries.add(new File(pathname)); } return libraries; }
diff --git a/org.knime.knip.tracking/src/org/knime/knip/tracking/nodes/transition/transitionEnumerator/TransitionEnumeratorNodeModel.java b/org.knime.knip.tracking/src/org/knime/knip/tracking/nodes/transition/transitionEnumerator/TransitionEnumeratorNodeModel.java index 1314ccf..05728ca 100644 --- a/org.knime.knip.tracking/src/org/knime/knip/tracking/nodes/transition/transitionEnumerator/TransitionEnumeratorNodeModel.java +++ b/org.knime.knip.tracking/src/org/knime/knip/tracking/nodes/transition/transitionEnumerator/TransitionEnumeratorNodeModel.java @@ -1,169 +1,173 @@ package org.knime.knip.tracking.nodes.transition.transitionEnumerator; import java.io.File; import java.io.IOException; import net.imglib2.meta.ImgPlus; import net.imglib2.type.NativeType; import net.imglib2.type.numeric.IntegerType; import org.knime.core.data.DataCell; import org.knime.core.data.DataRow; import org.knime.core.data.DataTableSpec; import org.knime.core.data.container.DataContainer; import org.knime.core.data.def.DefaultRow; import org.knime.core.data.def.DoubleCell; import org.knime.core.data.def.StringCell; import org.knime.core.node.BufferedDataTable; import org.knime.core.node.CanceledExecutionException; import org.knime.core.node.ExecutionContext; import org.knime.core.node.ExecutionMonitor; import org.knime.core.node.InvalidSettingsException; import org.knime.core.node.NodeModel; import org.knime.core.node.NodeSettingsRO; import org.knime.core.node.NodeSettingsWO; import org.knime.core.node.defaultnodesettings.SettingsModelString; import org.knime.knip.base.data.img.ImgPlusCellFactory; import org.knime.knip.base.data.img.ImgPlusValue; import org.knime.knip.base.node.NodeUtils; import org.knime.knip.tracking.data.features.FeatureProvider; import org.knime.knip.tracking.data.graph.TransitionGraph; import org.knime.knip.tracking.data.graph.renderer.TransitionGraphRenderer; import org.knime.network.core.knime.cell.GraphCellFactory; import org.knime.network.core.knime.cell.GraphValue; /** * This is the model implementation of TransitionEnumerator. Enumerates all * possible transitions of a given transition graph. * * @author Stephan Sellien */ public class TransitionEnumeratorNodeModel<T extends NativeType<T> & IntegerType<T>> extends NodeModel { /** * Constructor for the node model. */ protected TransitionEnumeratorNodeModel() { super(2, 1); } /** * {@inheritDoc} */ @Override protected BufferedDataTable[] execute(final BufferedDataTable[] inData, final ExecutionContext exec) throws Exception { DataContainer cont = exec.createDataContainer(inData[0] .getDataTableSpec()); int graphColIdx = NodeUtils.autoColumnSelection(inData[0] .getDataTableSpec(), new SettingsModelString("bla", null), GraphValue.class, this.getClass(), new Integer[0]); if (inData[1].getRowCount() < 1) { throw new InvalidSettingsException( "Input table #2 must contain the original image."); } @SuppressWarnings("unchecked") ImgPlus<T> baseImg = ((ImgPlusValue<T>) inData[1].iterator().next() .getCell(0)).getImgPlus(); + int count = 0; for (DataRow row : inData[0]) { + exec.checkCanceled(); + exec.setProgress((double)count/inData[0].getRowCount(), "Processing row #" + (count+1)); TransitionGraph tg = new TransitionGraph( ((GraphValue) row.getCell(graphColIdx)).getView()); int variantCounter = 0; for (TransitionGraph tgVariant : TransitionGraph .createAllPossibleGraphs(tg)) { DataCell[] cells = new DataCell[cont.getTableSpec() .getNumColumns()]; cells[0] = new ImgPlusCellFactory(exec) .createCell(TransitionGraphRenderer .renderTransitionGraph(tg, baseImg, tgVariant)); cells[1] = new StringCell(tgVariant.toString()); cells[2] = new StringCell(tgVariant.toNodeString()); cells[3] = GraphCellFactory.createCell(tgVariant.getNet()); double[] distVec = FeatureProvider.getFeatureVector(tgVariant); for (int i = 0; i < distVec.length; i++) { cells[i + 4] = new DoubleCell(distVec[i]); } cells[cells.length - 1] = row.getCell(row.getNumCells() - 1); cont.addRowToTable(new DefaultRow(row.getKey() + ";" + variantCounter, cells)); variantCounter++; } + count++; } cont.close(); return new BufferedDataTable[] { exec.createBufferedDataTable( cont.getTable(), exec) }; } /** * {@inheritDoc} */ @Override protected void reset() { } /** * {@inheritDoc} */ @Override protected DataTableSpec[] configure(final DataTableSpec[] inSpecs) throws InvalidSettingsException { if (!inSpecs[0].containsCompatibleType(GraphValue.class)) throw new InvalidSettingsException( "Input table #1 must contain a transition graph column"); if (!inSpecs[1].containsCompatibleType(ImgPlusValue.class)) throw new InvalidSettingsException( "Input table #2 must contain the original image."); return new DataTableSpec[] { inSpecs[0] }; } /** * {@inheritDoc} */ @Override protected void saveSettingsTo(final NodeSettingsWO settings) { } /** * {@inheritDoc} */ @Override protected void loadValidatedSettingsFrom(final NodeSettingsRO settings) throws InvalidSettingsException { } /** * {@inheritDoc} */ @Override protected void validateSettings(final NodeSettingsRO settings) throws InvalidSettingsException { } /** * {@inheritDoc} */ @Override protected void loadInternals(final File internDir, final ExecutionMonitor exec) throws IOException, CanceledExecutionException { } /** * {@inheritDoc} */ @Override protected void saveInternals(final File internDir, final ExecutionMonitor exec) throws IOException, CanceledExecutionException { } }
false
true
protected BufferedDataTable[] execute(final BufferedDataTable[] inData, final ExecutionContext exec) throws Exception { DataContainer cont = exec.createDataContainer(inData[0] .getDataTableSpec()); int graphColIdx = NodeUtils.autoColumnSelection(inData[0] .getDataTableSpec(), new SettingsModelString("bla", null), GraphValue.class, this.getClass(), new Integer[0]); if (inData[1].getRowCount() < 1) { throw new InvalidSettingsException( "Input table #2 must contain the original image."); } @SuppressWarnings("unchecked") ImgPlus<T> baseImg = ((ImgPlusValue<T>) inData[1].iterator().next() .getCell(0)).getImgPlus(); for (DataRow row : inData[0]) { TransitionGraph tg = new TransitionGraph( ((GraphValue) row.getCell(graphColIdx)).getView()); int variantCounter = 0; for (TransitionGraph tgVariant : TransitionGraph .createAllPossibleGraphs(tg)) { DataCell[] cells = new DataCell[cont.getTableSpec() .getNumColumns()]; cells[0] = new ImgPlusCellFactory(exec) .createCell(TransitionGraphRenderer .renderTransitionGraph(tg, baseImg, tgVariant)); cells[1] = new StringCell(tgVariant.toString()); cells[2] = new StringCell(tgVariant.toNodeString()); cells[3] = GraphCellFactory.createCell(tgVariant.getNet()); double[] distVec = FeatureProvider.getFeatureVector(tgVariant); for (int i = 0; i < distVec.length; i++) { cells[i + 4] = new DoubleCell(distVec[i]); } cells[cells.length - 1] = row.getCell(row.getNumCells() - 1); cont.addRowToTable(new DefaultRow(row.getKey() + ";" + variantCounter, cells)); variantCounter++; } } cont.close(); return new BufferedDataTable[] { exec.createBufferedDataTable( cont.getTable(), exec) }; }
protected BufferedDataTable[] execute(final BufferedDataTable[] inData, final ExecutionContext exec) throws Exception { DataContainer cont = exec.createDataContainer(inData[0] .getDataTableSpec()); int graphColIdx = NodeUtils.autoColumnSelection(inData[0] .getDataTableSpec(), new SettingsModelString("bla", null), GraphValue.class, this.getClass(), new Integer[0]); if (inData[1].getRowCount() < 1) { throw new InvalidSettingsException( "Input table #2 must contain the original image."); } @SuppressWarnings("unchecked") ImgPlus<T> baseImg = ((ImgPlusValue<T>) inData[1].iterator().next() .getCell(0)).getImgPlus(); int count = 0; for (DataRow row : inData[0]) { exec.checkCanceled(); exec.setProgress((double)count/inData[0].getRowCount(), "Processing row #" + (count+1)); TransitionGraph tg = new TransitionGraph( ((GraphValue) row.getCell(graphColIdx)).getView()); int variantCounter = 0; for (TransitionGraph tgVariant : TransitionGraph .createAllPossibleGraphs(tg)) { DataCell[] cells = new DataCell[cont.getTableSpec() .getNumColumns()]; cells[0] = new ImgPlusCellFactory(exec) .createCell(TransitionGraphRenderer .renderTransitionGraph(tg, baseImg, tgVariant)); cells[1] = new StringCell(tgVariant.toString()); cells[2] = new StringCell(tgVariant.toNodeString()); cells[3] = GraphCellFactory.createCell(tgVariant.getNet()); double[] distVec = FeatureProvider.getFeatureVector(tgVariant); for (int i = 0; i < distVec.length; i++) { cells[i + 4] = new DoubleCell(distVec[i]); } cells[cells.length - 1] = row.getCell(row.getNumCells() - 1); cont.addRowToTable(new DefaultRow(row.getKey() + ";" + variantCounter, cells)); variantCounter++; } count++; } cont.close(); return new BufferedDataTable[] { exec.createBufferedDataTable( cont.getTable(), exec) }; }
diff --git a/src/main/java/timetracker/ChromatticService.java b/src/main/java/timetracker/ChromatticService.java index 4c9e9b2..7cfeb06 100644 --- a/src/main/java/timetracker/ChromatticService.java +++ b/src/main/java/timetracker/ChromatticService.java @@ -1,76 +1,79 @@ package timetracker; import org.chromattic.api.Chromattic; import org.chromattic.api.ChromatticBuilder; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.nodetype.ExtendedNodeTypeManager; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.jcr.impl.core.ExtendedNamespaceRegistry; import timetracker.integration.CurrentRepositoryLifeCycle; import timetracker.model.*; import javax.inject.Inject; import javax.jcr.Session; import java.io.InputStream; public class ChromatticService { Chromattic chromattic; RepositoryService repoService_; @Inject public ChromatticService(RepositoryService repositoryService) { repoService_ = repositoryService; } public Chromattic init() { registerNodetypes(repoService_); ChromatticBuilder builder = ChromatticBuilder.create(); builder.add(Task.class); builder.add(User.class); builder.add(Week.class); builder.add(Column.class); builder.add(Columns.class); builder.setOptionValue(ChromatticBuilder.SESSION_LIFECYCLE_CLASSNAME, CurrentRepositoryLifeCycle.class.getName()); builder.setOptionValue(ChromatticBuilder.CREATE_ROOT_NODE, true); builder.setOptionValue(ChromatticBuilder.ROOT_NODE_PATH, "/Documents"); chromattic = builder.build(); return chromattic; } private void registerNodetypes(RepositoryService repoService) { SessionProvider sessionProvider = SessionProvider.createSystemProvider(); try { //get info Session session = sessionProvider.getSession("dms-system", repoService.getCurrentRepository()); ExtendedNamespaceRegistry namespaceRegistry = (ExtendedNamespaceRegistry) session.getWorkspace().getNamespaceRegistry(); - if (namespaceRegistry.getNamespacePrefixByURI("http://juzu.org/jcr/timetracker")==null) + try { + String prefix = namespaceRegistry.getNamespacePrefixByURI("http://juzu.org/jcr/timetracker"); + } catch (javax.jcr.NamespaceException nse) { namespaceRegistry.registerNamespace("tt", "http://juzu.org/jcr/timetracker"); + } ExtendedNodeTypeManager nodeTypeManager = (ExtendedNodeTypeManager) session.getWorkspace().getNodeTypeManager(); InputStream is = ChromatticService.class.getResourceAsStream("model/nodetypes.xml"); nodeTypeManager.registerNodeTypes(is, ExtendedNodeTypeManager.REPLACE_IF_EXISTS); } catch (Exception e) { e.printStackTrace(); } finally { sessionProvider.close(); } } }
false
true
private void registerNodetypes(RepositoryService repoService) { SessionProvider sessionProvider = SessionProvider.createSystemProvider(); try { //get info Session session = sessionProvider.getSession("dms-system", repoService.getCurrentRepository()); ExtendedNamespaceRegistry namespaceRegistry = (ExtendedNamespaceRegistry) session.getWorkspace().getNamespaceRegistry(); if (namespaceRegistry.getNamespacePrefixByURI("http://juzu.org/jcr/timetracker")==null) namespaceRegistry.registerNamespace("tt", "http://juzu.org/jcr/timetracker"); ExtendedNodeTypeManager nodeTypeManager = (ExtendedNodeTypeManager) session.getWorkspace().getNodeTypeManager(); InputStream is = ChromatticService.class.getResourceAsStream("model/nodetypes.xml"); nodeTypeManager.registerNodeTypes(is, ExtendedNodeTypeManager.REPLACE_IF_EXISTS); } catch (Exception e) { e.printStackTrace(); } finally { sessionProvider.close(); } }
private void registerNodetypes(RepositoryService repoService) { SessionProvider sessionProvider = SessionProvider.createSystemProvider(); try { //get info Session session = sessionProvider.getSession("dms-system", repoService.getCurrentRepository()); ExtendedNamespaceRegistry namespaceRegistry = (ExtendedNamespaceRegistry) session.getWorkspace().getNamespaceRegistry(); try { String prefix = namespaceRegistry.getNamespacePrefixByURI("http://juzu.org/jcr/timetracker"); } catch (javax.jcr.NamespaceException nse) { namespaceRegistry.registerNamespace("tt", "http://juzu.org/jcr/timetracker"); } ExtendedNodeTypeManager nodeTypeManager = (ExtendedNodeTypeManager) session.getWorkspace().getNodeTypeManager(); InputStream is = ChromatticService.class.getResourceAsStream("model/nodetypes.xml"); nodeTypeManager.registerNodeTypes(is, ExtendedNodeTypeManager.REPLACE_IF_EXISTS); } catch (Exception e) { e.printStackTrace(); } finally { sessionProvider.close(); } }
diff --git a/gcscripts/gcwarriorsguild/SelectorGui.java b/gcscripts/gcwarriorsguild/SelectorGui.java index 7562b93..6c7722b 100644 --- a/gcscripts/gcwarriorsguild/SelectorGui.java +++ b/gcscripts/gcwarriorsguild/SelectorGui.java @@ -1,94 +1,94 @@ package gcscripts.gcwarriorsguild; import gcapi.utils.Logger; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; public class SelectorGui extends JFrame { private JComboBox optionsBox; private JComboBox defendersBox; private final int PADDING = 10; private Logger logger; private static final String[] OPTIONS = new String[] { "Collect tokens", "Collect defenders" }; private static final String[] DEFENDERS = new String[] { "Bronze", "Iron", "Steel", "Black", "Mithril", "Adamant", "Rune", "Dragon" }; public SelectorGui(Logger logger) { - this.logger = logger; + //this.logger = logger; - this.logger.log("Initialised selection GUI"); + //this.logger.log("Initialised selection GUI"); setTitle("GC Warriors' Guild - Select action"); setPreferredSize(new Dimension(200, 100)); setResizable(false); setLayout(new FlowLayout(FlowLayout.LEADING, PADDING, PADDING)); setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); JPanel contentPane = new JPanel(); optionsBox = new JComboBox(getOptions()); defendersBox = new JComboBox(getDefenders()); optionsBox.setSelectedIndex(0); optionsBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (optionsBox.getSelectedIndex() == 1) { defendersBox.setEnabled(true); } else { defendersBox.setEnabled(false); } } }); JButton startButton = new JButton("Start script"); startButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispatchEvent(new WindowEvent(SelectorGui.this, WindowEvent.WINDOW_CLOSING)); } }); defendersBox.setEnabled(false); setContentPane(contentPane); contentPane.add(optionsBox); contentPane.add(defendersBox); contentPane.add(startButton); pack(); setVisible(true); } public JComboBox getOptionsBox() { return optionsBox; } public JComboBox getDefendersBox() { return defendersBox; } public String[] getOptions() { return OPTIONS; } public String[] getDefenders() { return DEFENDERS; } }
false
true
public SelectorGui(Logger logger) { this.logger = logger; this.logger.log("Initialised selection GUI"); setTitle("GC Warriors' Guild - Select action"); setPreferredSize(new Dimension(200, 100)); setResizable(false); setLayout(new FlowLayout(FlowLayout.LEADING, PADDING, PADDING)); setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); JPanel contentPane = new JPanel(); optionsBox = new JComboBox(getOptions()); defendersBox = new JComboBox(getDefenders()); optionsBox.setSelectedIndex(0); optionsBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (optionsBox.getSelectedIndex() == 1) { defendersBox.setEnabled(true); } else { defendersBox.setEnabled(false); } } }); JButton startButton = new JButton("Start script"); startButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispatchEvent(new WindowEvent(SelectorGui.this, WindowEvent.WINDOW_CLOSING)); } }); defendersBox.setEnabled(false); setContentPane(contentPane); contentPane.add(optionsBox); contentPane.add(defendersBox); contentPane.add(startButton); pack(); setVisible(true); }
public SelectorGui(Logger logger) { //this.logger = logger; //this.logger.log("Initialised selection GUI"); setTitle("GC Warriors' Guild - Select action"); setPreferredSize(new Dimension(200, 100)); setResizable(false); setLayout(new FlowLayout(FlowLayout.LEADING, PADDING, PADDING)); setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); JPanel contentPane = new JPanel(); optionsBox = new JComboBox(getOptions()); defendersBox = new JComboBox(getDefenders()); optionsBox.setSelectedIndex(0); optionsBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (optionsBox.getSelectedIndex() == 1) { defendersBox.setEnabled(true); } else { defendersBox.setEnabled(false); } } }); JButton startButton = new JButton("Start script"); startButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispatchEvent(new WindowEvent(SelectorGui.this, WindowEvent.WINDOW_CLOSING)); } }); defendersBox.setEnabled(false); setContentPane(contentPane); contentPane.add(optionsBox); contentPane.add(defendersBox); contentPane.add(startButton); pack(); setVisible(true); }
diff --git a/FlexAscParser/src_converter/Main2.java b/FlexAscParser/src_converter/Main2.java index 1a56c04..3d8d5e5 100644 --- a/FlexAscParser/src_converter/Main2.java +++ b/FlexAscParser/src_converter/Main2.java @@ -1,2171 +1,2171 @@ import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Stack; import macromedia.asc.parser.ApplyTypeExprNode; import macromedia.asc.parser.ArgumentListNode; import macromedia.asc.parser.BinaryExpressionNode; import macromedia.asc.parser.BreakStatementNode; import macromedia.asc.parser.CallExpressionNode; import macromedia.asc.parser.CaseLabelNode; import macromedia.asc.parser.ClassDefinitionNode; import macromedia.asc.parser.CoerceNode; import macromedia.asc.parser.ConditionalExpressionNode; import macromedia.asc.parser.DeleteExpressionNode; import macromedia.asc.parser.DoStatementNode; import macromedia.asc.parser.ExpressionStatementNode; import macromedia.asc.parser.ForStatementNode; import macromedia.asc.parser.FunctionCommonNode; import macromedia.asc.parser.FunctionDefinitionNode; import macromedia.asc.parser.FunctionNameNode; import macromedia.asc.parser.GetExpressionNode; import macromedia.asc.parser.HasNextNode; import macromedia.asc.parser.IdentifierNode; import macromedia.asc.parser.IfStatementNode; import macromedia.asc.parser.ImportDirectiveNode; import macromedia.asc.parser.IncrementNode; import macromedia.asc.parser.InterfaceDefinitionNode; import macromedia.asc.parser.ListNode; import macromedia.asc.parser.LiteralArrayNode; import macromedia.asc.parser.LiteralBooleanNode; import macromedia.asc.parser.LiteralNullNode; import macromedia.asc.parser.LiteralNumberNode; import macromedia.asc.parser.LiteralObjectNode; import macromedia.asc.parser.LiteralRegExpNode; import macromedia.asc.parser.LiteralStringNode; import macromedia.asc.parser.MemberExpressionNode; import macromedia.asc.parser.MetaDataNode; import macromedia.asc.parser.Node; import macromedia.asc.parser.PackageDefinitionNode; import macromedia.asc.parser.ParameterListNode; import macromedia.asc.parser.ParameterNode; import macromedia.asc.parser.Parser; import macromedia.asc.parser.ProgramNode; import macromedia.asc.parser.QualifiedIdentifierNode; import macromedia.asc.parser.ReturnStatementNode; import macromedia.asc.parser.SelectorNode; import macromedia.asc.parser.SetExpressionNode; import macromedia.asc.parser.StatementListNode; import macromedia.asc.parser.StoreRegisterNode; import macromedia.asc.parser.SuperExpressionNode; import macromedia.asc.parser.SuperStatementNode; import macromedia.asc.parser.SwitchStatementNode; import macromedia.asc.parser.ThisExpressionNode; import macromedia.asc.parser.ThrowStatementNode; import macromedia.asc.parser.Tokens; import macromedia.asc.parser.TryStatementNode; import macromedia.asc.parser.UnaryExpressionNode; import macromedia.asc.parser.VariableBindingNode; import macromedia.asc.parser.VariableDefinitionNode; import macromedia.asc.parser.WhileStatementNode; import macromedia.asc.util.Context; import macromedia.asc.util.ContextStatics; import macromedia.asc.util.ObjectList; import bc.builtin.BuiltinClasses; import bc.code.FileWriteDestination; import bc.code.ListWriteDestination; import bc.code.WriteDestination; import bc.help.BcCodeCs; import bc.help.BcNodeHelper; import bc.lang.BcClassDefinitionNode; import bc.lang.BcFuncParam; import bc.lang.BcFunctionDeclaration; import bc.lang.BcFunctionTypeNode; import bc.lang.BcInterfaceDefinitionNode; import bc.lang.BcMemberExpressionNode; import bc.lang.BcTypeNode; import bc.lang.BcVariableDeclaration; import bc.lang.BcVectorTypeNode; public class Main2 { private static FileWriteDestination src; private static ListWriteDestination impl; private static WriteDestination dest; private static Stack<WriteDestination> destStack; private static BcClassDefinitionNode lastBcClass; private static BcFunctionDeclaration lastBcFunction; private static final String classObject = "Object"; private static final String classString = "String"; private static final String classVector = "Vector"; private static final String classDictionary = "Dictionary"; private static final String classXML = "XML"; private static final String classXMLList = "XMLList"; private static List<BcVariableDeclaration> declaredVars; private static List<BcClassDefinitionNode> bcClasses; private static Map<String, BcClassDefinitionNode> builtinClasses; // builtin classes private static Map<String, BcFunctionDeclaration> bcBuitinFunctions; // top level functions // FIXME: filter class names private static String[] builtinClassesNames = { "Object", "Array", "Dictionary", "Sprite", "Rectangle", "Stage", "Event", "MouseEvent", "KeyboardEvent", "DisplayObject", "DisplayObjectContainer", "MovieClip", "TextField", "TextFormat", "DropShadowFilter", "Bitmap", "Sound", "SoundTransform", "SoundChannel", "ColorTransform", "BitmapData", "ByteArray", "Class", "RegExp", "URLRequest", "Loader", "URLLoader", "IOErrorEvent", "*", "SharedObject", "Shape", "Graphics", "BlurFilter", "Point", "Math", "StageAlign", "StageScaleMode", "StageQuality", "StageDisplayState", "PixelSnapping", "TextFieldAutoSize", "Mouse", "Keyboard", }; static { builtinClasses = new HashMap<String, BcClassDefinitionNode>(); bcBuitinFunctions = new HashMap<String, BcFunctionDeclaration>(); for (String className : builtinClassesNames) { builtinClasses.put(className, new BcClassDefinitionNode(BcTypeNode.create(className))); } try { List<BcClassDefinitionNode> classes = BuiltinClasses.load(new File("as_classes")); for (BcClassDefinitionNode bcClass : classes) { if (bcClass.getName().equals(BuiltinClasses.TOPLEVEL_DUMMY_CLASS_NAME)) { List<BcFunctionDeclaration> bcTopLevelFunctions = bcClass.getFunctions(); for (BcFunctionDeclaration bcFunc : bcTopLevelFunctions) { bcBuitinFunctions.put(bcFunc.getName(), bcFunc); } } else { builtinClasses.put(bcClass.getName(), bcClass); } } } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { File outputDir = new File(args[0]); String[] filenames = new String[args.length - 1]; System.arraycopy(args, 1, filenames, 0, filenames.length); try { collect(filenames); process(); write(outputDir); } catch (IOException e) { e.printStackTrace(); } } private static void collect(String[] filenames) throws IOException { bcClasses = new ArrayList<BcClassDefinitionNode>(); for (int i = 0; i < filenames.length; ++i) { collect(new File(filenames[i])); } } private static void collect(File file) throws IOException { if (file.isDirectory()) { File[] files = file.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { String filename = pathname.getName(); if (pathname.isDirectory()) return !filename.equals(".svn"); return filename.endsWith(".as"); } }); for (File child : files) { collect(child); } } else { collectSource(file); } } private static void collectSource(File file) throws IOException { ContextStatics statics = new ContextStatics(); Context cx = new Context(statics); FileInputStream in = new FileInputStream(file); Parser parser = new Parser(cx, in, file.getPath()); ProgramNode programNode = parser.parseProgram(); in.close(); // NodePrinter printer = new NodePrinter(); // printer.evaluate(cx, programNode); for (Node node : programNode.statements.items) { dest = new ListWriteDestination(); destStack = new Stack<WriteDestination>(); if (node instanceof InterfaceDefinitionNode) { BcInterfaceDefinitionNode bcInterface = collect((InterfaceDefinitionNode) node); bcClasses.add(bcInterface); } else if (node instanceof ClassDefinitionNode) { BcClassDefinitionNode bcClass = collect((ClassDefinitionNode) node); bcClasses.add(bcClass); } else if (node instanceof ImportDirectiveNode || node instanceof PackageDefinitionNode || node instanceof MetaDataNode) { // nothing } } } private static BcInterfaceDefinitionNode collect(InterfaceDefinitionNode interfaceDefinitionNode) { String interfaceDeclaredName = interfaceDefinitionNode.name.name; declaredVars = new ArrayList<BcVariableDeclaration>(); BcTypeNode interfaceType = BcTypeNode.create(interfaceDeclaredName); BcInterfaceDefinitionNode bcInterface = new BcInterfaceDefinitionNode(interfaceType); bcInterface.setDeclaredVars(declaredVars); lastBcClass = bcInterface; ObjectList<Node> items = interfaceDefinitionNode.statements.items; // collect the stuff for (Node node : items) { if (node instanceof FunctionDefinitionNode) { bcInterface.add(collect((FunctionDefinitionNode) node)); } else { assert false; } } lastBcClass = null; return bcInterface; } private static BcClassDefinitionNode collect(ClassDefinitionNode classDefinitionNode) { String classDeclaredName = classDefinitionNode.name.name; declaredVars = new ArrayList<BcVariableDeclaration>(); BcTypeNode classType = BcTypeNode.create(classDeclaredName); BcClassDefinitionNode bcClass = new BcClassDefinitionNode(classType); bcClass.setDeclaredVars(declaredVars); lastBcClass = bcClass; // super type Node baseclass = classDefinitionNode.baseclass; if (baseclass != null) { BcTypeNode bcSuperType = extractBcType(baseclass); bcClass.setExtendsType(bcSuperType); } // interfaces if (classDefinitionNode.interfaces != null) { for (Node interfaceNode : classDefinitionNode.interfaces.items) { BcTypeNode interfaceType = extractBcType(interfaceNode); bcClass.addInterface(interfaceType); } } // collect members ObjectList<Node> items = classDefinitionNode.statements.items; for (Node node : items) { if (node instanceof FunctionDefinitionNode) { bcClass.add(collect((FunctionDefinitionNode) node)); } else if (node instanceof VariableDefinitionNode) { bcClass.add(collect((VariableDefinitionNode)node)); } else if (node instanceof MetaDataNode) { } else if (node instanceof ExpressionStatementNode) { assert false : "Top level ExpressionStatementNode"; } else { assert false : node.getClass(); } } lastBcClass = null; declaredVars = null; return bcClass; } private static BcVariableDeclaration collect(VariableDefinitionNode node) { assert node.list.items.size() == 1 : node.list.items.size(); VariableBindingNode varBindNode = (VariableBindingNode) node.list.items.get(0); BcTypeNode bcType = extractBcType(varBindNode.variable.type); String bcIdentifier = BcNodeHelper.extractBcIdentifier(varBindNode.variable.identifier); BcVariableDeclaration bcVar = new BcVariableDeclaration(bcType, bcIdentifier); bcVar.setConst(node.kind == Tokens.CONST_TOKEN); bcVar.setModifiers(BcNodeHelper.extractModifiers(varBindNode.attrs)); bcVar.setInitializerNode(varBindNode.initializer); declaredVars.add(bcVar); return bcVar; } private static BcFunctionDeclaration collect(FunctionDefinitionNode functionDefinitionNode) { FunctionNameNode functionNameNode = functionDefinitionNode.name; String name = functionNameNode.identifier.name; BcFunctionDeclaration bcFunc = new BcFunctionDeclaration(name); if (functionNameNode.kind == Tokens.GET_TOKEN) { bcFunc.setGetter(); } else if(functionNameNode.kind == Tokens.SET_TOKEN) { bcFunc.setSetter(); } boolean isConstructor = lastBcClass != null && name.equals(lastBcClass.getName()); bcFunc.setConstructorFlag(isConstructor); bcFunc.setModifiers(BcNodeHelper.extractModifiers(functionDefinitionNode.attrs)); ArrayList<BcVariableDeclaration> declaredVars = new ArrayList<BcVariableDeclaration>(); bcFunc.setDeclaredVars(declaredVars); // get function params ParameterListNode parameterNode = functionDefinitionNode.fexpr.signature.parameter; if (parameterNode != null) { ObjectList<ParameterNode> params = parameterNode.items; for (ParameterNode param : params) { BcFuncParam bcParam = new BcFuncParam(extractBcType(param.type), param.identifier.name); if (param.init != null) { bcParam.setDefaultInitializer(param.init); } bcFunc.addParam(bcParam); declaredVars.add(bcParam); } } // get function return type Node returnTypeNode = functionDefinitionNode.fexpr.signature.result; if (returnTypeNode != null) { BcTypeNode bcReturnType = extractBcType(returnTypeNode); bcFunc.setReturnType(bcReturnType); } bcFunc.setStatements(functionDefinitionNode.fexpr.body); return bcFunc; } private static void process() { Collection<BcTypeNode> values = BcTypeNode.uniqueTypes.values(); for (BcTypeNode type : values) { process(type); } for (BcClassDefinitionNode bcClass : bcClasses) { if (bcClass.isInterface()) { process((BcInterfaceDefinitionNode)bcClass); } else { process(bcClass); } } } private static void process(BcInterfaceDefinitionNode bcInterface) { List<BcVariableDeclaration> oldDeclaredVars = declaredVars; declaredVars = bcInterface.getDeclaredVars(); } private static void process(BcClassDefinitionNode bcClass) { System.out.println("Process: " + bcClass.getName()); declaredVars = bcClass.getDeclaredVars(); lastBcClass = bcClass; List<BcVariableDeclaration> fields = bcClass.getFields(); for (BcVariableDeclaration bcField : fields) { process(bcField); } List<BcFunctionDeclaration> functions = bcClass.getFunctions(); for (BcFunctionDeclaration bcFunc : functions) { process(bcFunc); } lastBcClass = null; declaredVars = null; } private static void process(BcVariableDeclaration bcVar) { BcTypeNode varType = bcVar.getType(); String varId = bcVar.getIdentifier(); dest.writef("%s %s", BcCodeCs.type(varType.getName()), BcCodeCs.identifier(varId)); Node initializer = bcVar.getInitializerNode(); if (initializer != null) { ListWriteDestination initializerDest = new ListWriteDestination(); pushDest(initializerDest); process(initializer); popDest(); bcVar.setInitializer(initializerDest); bcVar.setIntegralInitializerFlag(BcNodeHelper.isIntegralLiteralNode(initializer)); dest.write(" = " + initializerDest); } dest.writeln(";"); } private static void process(Node node) { assert node != null; if (node instanceof MemberExpressionNode) process((MemberExpressionNode)node); else if (node instanceof SelectorNode) process((SelectorNode)node); else if (node instanceof IdentifierNode) process((IdentifierNode)node); else if (node instanceof ExpressionStatementNode) process((ExpressionStatementNode)node); else if (node instanceof VariableBindingNode) process((VariableBindingNode)node); else if (node instanceof VariableDefinitionNode) process((VariableDefinitionNode)node); else if (node instanceof LiteralNumberNode || node instanceof LiteralBooleanNode || node instanceof LiteralNullNode || node instanceof LiteralObjectNode || node instanceof LiteralStringNode || node instanceof LiteralRegExpNode || node instanceof LiteralArrayNode) processLiteral(node); else if (node instanceof BinaryExpressionNode) process((BinaryExpressionNode)node); else if (node instanceof UnaryExpressionNode) process((UnaryExpressionNode)node); else if (node instanceof IfStatementNode) process((IfStatementNode)node); else if (node instanceof ConditionalExpressionNode) process((ConditionalExpressionNode)node); else if (node instanceof WhileStatementNode) process((WhileStatementNode)node); else if (node instanceof ForStatementNode) process((ForStatementNode)node); else if (node instanceof DoStatementNode) process((DoStatementNode)node); else if (node instanceof SwitchStatementNode) process((SwitchStatementNode)node); else if (node instanceof TryStatementNode) process((TryStatementNode)node); else if (node instanceof ReturnStatementNode) process((ReturnStatementNode)node); else if (node instanceof BreakStatementNode) process((BreakStatementNode)node); else if (node instanceof ThisExpressionNode) process((ThisExpressionNode)node); else if (node instanceof SuperExpressionNode) process((SuperExpressionNode)node); else if (node instanceof ThrowStatementNode) process((ThrowStatementNode)node); else if (node instanceof SuperStatementNode) process((SuperStatementNode)node); else if (node instanceof ListNode) process((ListNode)node); else if (node instanceof StatementListNode) process((StatementListNode)node); else if (node instanceof ArgumentListNode) process((ArgumentListNode)node); else if (node instanceof FunctionCommonNode) process((FunctionCommonNode)node); else assert false : node.getClass(); } private static void process(StatementListNode statementsNode) { writeBlockOpen(dest); ObjectList<Node> items = statementsNode.items; for (Node node : items) { process(node); } writeBlockClose(dest); } private static void process(ArgumentListNode node) { int itemIndex = 0; for (Node arg : node.items) { process(arg); if (++itemIndex < node.items.size()) { dest.write(", "); } } } private static void process(FunctionCommonNode node) { System.err.println("Fix me!!! FunctionCommonNode"); } private static BcVariableDeclaration process(VariableDefinitionNode node) { VariableBindingNode varBindNode = (VariableBindingNode) node.list.items.get(0); BcTypeNode varType = extractBcType(varBindNode.variable.type); String bcIdentifier = BcNodeHelper.extractBcIdentifier(varBindNode.variable.identifier); BcVariableDeclaration bcVar = new BcVariableDeclaration(varType, bcIdentifier); bcVar.setConst(node.kind == Tokens.CONST_TOKEN); bcVar.setModifiers(BcNodeHelper.extractModifiers(varBindNode.attrs)); dest.writef("%s %s", BcCodeCs.type(varType.getName()), BcCodeCs.identifier(bcIdentifier)); if (varBindNode.initializer != null) { ListWriteDestination initializer = new ListWriteDestination(); pushDest(initializer); process(varBindNode.initializer); popDest(); bcVar.setInitializer(initializer); bcVar.setIntegralInitializerFlag(BcNodeHelper.isIntegralLiteralNode(varBindNode.initializer)); dest.write(" = " + initializer); } dest.writeln(";"); declaredVars.add(bcVar); return bcVar; } // dirty hack: we need to check the recursion depth private static MemberExpressionNode rootMemberNode; private static void process(MemberExpressionNode node) { Node base = node.base; SelectorNode selector = node.selector; if (rootMemberNode == null) { rootMemberNode = node; } if (base != null) { process(base); if (selector instanceof GetExpressionNode || selector instanceof CallExpressionNode || selector instanceof SetExpressionNode) { dest.write("."); } } if (selector != null) { process(selector); } rootMemberNode = null; } private static void process(SelectorNode node) { if (node instanceof DeleteExpressionNode) process((DeleteExpressionNode)node); else if (node instanceof GetExpressionNode) process((GetExpressionNode)node); else if (node instanceof CallExpressionNode) process((CallExpressionNode)node); else if (node instanceof SetExpressionNode) process((SetExpressionNode)node); else if (node instanceof ApplyTypeExprNode) process((ApplyTypeExprNode)node); else if (node instanceof IncrementNode) process((IncrementNode)node); else assert false : node.getClass(); } private static void process(DeleteExpressionNode node) { ListWriteDestination expr = new ListWriteDestination(); pushDest(expr); process(node.expr); popDest(); assert node.getMode() == Tokens.LEFTBRACKET_TOKEN; dest.writef(".remove(%s)", expr); } private static void process(GetExpressionNode node) { ListWriteDestination exprDest = new ListWriteDestination(); pushDest(exprDest); process(node.expr); popDest(); String expr = exprDest.toString(); if (node.getMode() == Tokens.LEFTBRACKET_TOKEN) { ListWriteDestination argsDest = new ListWriteDestination(); pushDest(argsDest); process(node.expr); popDest(); dest.writef("%s[%s]", expr, argsDest); } else { dest.write(expr); } } private static BcTypeNode findIdentifierType(String name) { if (BcCodeCs.canBeClass(name)) { BcClassDefinitionNode bcClass = findClass(name); if (bcClass != null) { return bcClass.getClassType(); } } BcVariableDeclaration bcVar = findVariable(name); if (bcVar != null) { return bcVar.getType(); } BcFunctionDeclaration bcFunc = findFunction(name); if (bcFunc != null) { return bcFunc.getReturnType(); } return null; } private static BcVariableDeclaration findVariable(String name) { BcVariableDeclaration bcVar = findLocalVar(name); if (bcVar != null) { return bcVar; } return lastBcClass.findField(name); } private static BcVariableDeclaration findLocalVar(String name) { if (lastBcFunction == null) { return null; } return lastBcFunction.findVariable(name); } private static void process(CallExpressionNode node) { ListWriteDestination exprDest = new ListWriteDestination(); pushDest(exprDest); process(node.expr); popDest(); String expr = exprDest.toString(); ListWriteDestination argsDest = new ListWriteDestination(); if (node.args != null) { pushDest(argsDest); process(node.args); popDest(); } BcTypeNode type = extractBcType(node.expr); assert type != null : node.expr.getClass(); if (node.is_new) { if (type instanceof BcVectorTypeNode) { BcVectorTypeNode vectorType = (BcVectorTypeNode) type; ObjectList<Node> args; if (node.args != null && (args = node.args.items).size() == 1 && args.get(0) instanceof LiteralArrayNode) { LiteralArrayNode arrayNode = (LiteralArrayNode) args.get(0); ArgumentListNode elementlist = arrayNode.elementlist; WriteDestination initDest = new ListWriteDestination(); pushDest(initDest); for (Node elementNode : elementlist.items) { initDest.write(".a("); process(elementNode); initDest.write(")"); } popDest(); dest.write(BcCodeCs.construct(vectorType, elementlist.size()) + initDest); } else { dest.write(BcCodeCs.construct(vectorType, argsDest)); } } else { dest.write(BcCodeCs.construct(type, argsDest.toString())); } } else if (node.expr instanceof MemberExpressionNode && ((MemberExpressionNode) node.expr).selector instanceof ApplyTypeExprNode) { assert type instanceof BcVectorTypeNode; BcVectorTypeNode bcVector = (BcVectorTypeNode) type; Node argNode = node.args.items.get(0); if (argNode instanceof LiteralArrayNode) { LiteralArrayNode arrayNode = (LiteralArrayNode) argNode; ArgumentListNode elementlist = arrayNode.elementlist; WriteDestination initDest = new ListWriteDestination(); pushDest(initDest); for (Node elementNode : elementlist.items) { initDest.write(" << "); process(elementNode); } popDest(); dest.write(BcCodeCs.construct(bcVector, elementlist.size()) + initDest); } else { dest.write(BcCodeCs.construct(type, 1) + " << " + argsDest); } } else { if (node.getMode() == Tokens.EMPTY_TOKEN && node.args != null && node.args.items.size() == 1) { if (BcCodeCs.canBeClass(type) || BcCodeCs.isBasicType(type)) { dest.writef("((%s)(%s))", BcCodeCs.type(exprDest.toString()), argsDest); } else { dest.writef("%s(%s)", exprDest, argsDest); } } else { dest.writef("%s(%s)", exprDest, argsDest); } } } private static void process(SetExpressionNode node) { ListWriteDestination exprDest = new ListWriteDestination(); pushDest(exprDest); process(node.expr); popDest(); ListWriteDestination argsDest = new ListWriteDestination(); pushDest(argsDest); process(node.args); popDest(); if (node.getMode() == Tokens.LEFTBRACKET_TOKEN) { dest.writef("[%s] = %s", exprDest, argsDest); } else { dest.writef("%s = %s", exprDest, argsDest); } } private static void process(ApplyTypeExprNode node) { ListWriteDestination expr = new ListWriteDestination(); pushDest(expr); process(node.expr); popDest(); String typeName = ((IdentifierNode)node.expr).name; StringBuilder typeBuffer = new StringBuilder(typeName); ListNode typeArgs = node.typeArgs; int genericCount = typeArgs.items.size(); if (genericCount > 0) { typeBuffer.append("<"); int genericIndex = 0; for (Node genericTypeNode : typeArgs.items) { BcTypeNode genericType = extractBcType(genericTypeNode); typeBuffer.append(BcCodeCs.type(genericType)); if (++genericIndex < genericCount) { typeBuffer.append(","); } } typeBuffer.append(">"); } String type = typeBuffer.toString(); dest.write(type); } private static void process(IncrementNode node) { ListWriteDestination expr = new ListWriteDestination(); pushDest(expr); process(node.expr); popDest(); String op = Tokens.tokenToString[-node.op]; if (node.isPostfix) { dest.write(expr + op); } else { dest.write(op + expr); } } private static void process(IdentifierNode node) { if (node.isAttr()) { dest.write("attribute(\""); dest.write(node.name); dest.write("\")"); } else { dest.write(node.name); } } private static void process(VariableBindingNode node) { System.err.println("Fix me!!! VariableBindingNode"); } private static void processLiteral(Node node) { if (node instanceof LiteralNumberNode) { LiteralNumberNode numberNode = (LiteralNumberNode) node; dest.write(numberNode.value); if (numberNode.value.indexOf('.') != -1) { dest.write("f"); } } else if (node instanceof LiteralNullNode) { dest.write(BcCodeCs.NULL); } else if (node instanceof LiteralBooleanNode) { LiteralBooleanNode booleanNode = (LiteralBooleanNode) node; dest.write(booleanNode.value ? "true" : "false"); } else if (node instanceof LiteralStringNode) { LiteralStringNode stringNode = (LiteralStringNode) node; dest.writef("\"%s\"", stringNode.value); } else if (node instanceof LiteralRegExpNode) { assert false : "LiteralRegExpNode"; } else if (node instanceof LiteralArrayNode) { LiteralArrayNode arrayNode = (LiteralArrayNode) node; ArgumentListNode elementlist = arrayNode.elementlist; BcTypeNode type = null; WriteDestination elementDest = new ListWriteDestination(); pushDest(elementDest); int elementIndex = 0; for (Node elementNode : elementlist.items) { process(elementNode); if (++elementIndex < elementlist.items.size()) { elementDest.write(", "); } } popDest(); dest.writef("__NEWARRAY(Foo, %s)", elementDest); } else if (node instanceof LiteralObjectNode) { assert false : "LiteralObjectNode"; } else { assert false : node.getClass(); } } private static void process(IfStatementNode node) { ListWriteDestination condDest = new ListWriteDestination(); pushDest(condDest); process(node.condition); popDest(); dest.writelnf("if(%s)", condDest); if (node.thenactions != null) { ListWriteDestination thenDest = new ListWriteDestination(); pushDest(thenDest); process(node.thenactions); popDest(); dest.writeln(thenDest); } else { writeEmptyBlock(); } if (node.elseactions != null) { ListWriteDestination elseDest = new ListWriteDestination(); pushDest(elseDest); process(node.elseactions); popDest(); dest.writeln("else"); dest.writeln(elseDest); } } private static void process(ConditionalExpressionNode node) { ListWriteDestination condDest = new ListWriteDestination(); pushDest(condDest); process(node.condition); popDest(); ListWriteDestination thenDest = new ListWriteDestination(); pushDest(thenDest); process(node.thenexpr); popDest(); ListWriteDestination elseDest = new ListWriteDestination(); pushDest(elseDest); process(node.elseexpr); popDest(); dest.writef("((%s) ? (%s) : (%s))", condDest, thenDest, elseDest); } private static void process(WhileStatementNode node) { ListWriteDestination exprDest = new ListWriteDestination(); pushDest(exprDest); process(node.expr); popDest(); dest.writelnf("while(%s)", exprDest); if (node.statement != null) { ListWriteDestination statementDest = new ListWriteDestination(); pushDest(statementDest); process(node.statement); popDest(); dest.writeln(statementDest); } else { writeEmptyBlock(); } } private static void process(ForStatementNode node) { boolean isForEach = node.test instanceof HasNextNode; if (isForEach) { // get iterable collection expression assert node.initialize != null; assert node.initialize instanceof ListNode : node.initialize.getClass(); ListNode list = (ListNode) node.initialize; assert list.items.size() == 2 : list.items.size(); StoreRegisterNode register = (StoreRegisterNode) list.items.get(1); CoerceNode coerce = (CoerceNode) register.expr; ListWriteDestination collection = new ListWriteDestination(); pushDest(collection); process(coerce.expr); popDest(); BcTypeNode collectionType = evaluateType(coerce.expr); assert collectionType != null; assert node.statement != null; assert node.statement instanceof StatementListNode : node.statement.getClass(); StatementListNode statements = (StatementListNode) node.statement; assert statements.items.size() == 2; // get iteration ExpressionStatementNode child1 = (ExpressionStatementNode) statements.items.get(0); MemberExpressionNode child2 = (MemberExpressionNode) child1.expr; SetExpressionNode child3 = (SetExpressionNode) child2.selector; String loopVarName = null; if (child3.expr instanceof QualifiedIdentifierNode) { QualifiedIdentifierNode identifier = (QualifiedIdentifierNode) child3.expr; loopVarName = BcCodeCs.identifier(identifier.name); } else if (child3.expr instanceof IdentifierNode) { IdentifierNode identifier = (IdentifierNode) child3.expr; loopVarName = BcCodeCs.identifier(identifier.name); } else { assert false : child3.expr.getClass(); } BcVariableDeclaration loopVar = findDeclaredVar(loopVarName); assert loopVar != null : loopVarName; // get loop body - dest.writelnf("foreach (%s %s in %s)", BcCodeCs.type(collectionType), loopVarName, collection); + dest.writelnf("foreach (%s %s in %s)", BcCodeCs.type(loopVar.getType()), loopVarName, collection); Node bodyNode = statements.items.get(1); if (bodyNode != null) { assert bodyNode instanceof StatementListNode : bodyNode.getClass(); StatementListNode statementsNode = (StatementListNode) bodyNode; writeBlockOpen(dest); ObjectList<Node> items = statementsNode.items; for (Node itemNode : items) { process(itemNode); } writeBlockClose(dest); } else { writeEmptyBlock(); } } else { ListWriteDestination initialize = new ListWriteDestination(); ListWriteDestination test = new ListWriteDestination(); ListWriteDestination increment = new ListWriteDestination(); if (node.initialize != null) { pushDest(initialize); process(node.initialize); popDest(); } if (node.test != null) { pushDest(test); process(node.test); popDest(); } if (node.increment != null) { increment = new ListWriteDestination(); pushDest(increment); process(node.increment); popDest(); } dest.writelnf("for (%s; %s; %s)", initialize, test, increment); process(node.statement); } } private static void process(DoStatementNode node) { } private static void process(SwitchStatementNode node) { ListWriteDestination expr = new ListWriteDestination(); pushDest(expr); process(node.expr); popDest(); dest.writelnf("switch(%s)", expr); writeBlockOpen(dest); if (node.statements != null) { ObjectList<Node> statements = node.statements.items; for (Node statement : statements) { if (statement instanceof CaseLabelNode) { CaseLabelNode caseLabel = (CaseLabelNode)statement; Node label = caseLabel.label; if (label == null) { dest.writeln("default:"); } else { ListWriteDestination caseDest = new ListWriteDestination(); pushDest(caseDest); process(label); popDest(); dest.writelnf("case %s:", caseDest); } writeBlockOpen(dest); } else if (statement instanceof BreakStatementNode) { process(statement); writeBlockClose(dest); } else { process(statement); } } } writeBlockClose(dest); } private static void process(TryStatementNode node) { } private static void process(ThrowStatementNode node) { } private static void process(BinaryExpressionNode node) { ListWriteDestination ldest = new ListWriteDestination(); ListWriteDestination rdest = new ListWriteDestination(); pushDest(ldest); process(node.lhs); popDest(); pushDest(rdest); process(node.rhs); popDest(); if (node.op == Tokens.IS_TOKEN) { dest.write(BcCodeCs.operatorIs(ldest, rdest)); } else if (node.op == Tokens.AS_TOKEN) { assert false; } else { dest.writef("%s %s %s", ldest, Tokens.tokenToString[-node.op], rdest); } } private static void process(UnaryExpressionNode node) { ListWriteDestination expr = new ListWriteDestination(); pushDest(expr); process(node.expr); popDest(); switch (node.op) { case Tokens.NOT_TOKEN: dest.writef("!(%s)", expr); break; case Tokens.MINUS_TOKEN: dest.writef("-%s", expr); break; default: assert false : node.op; } } private static void process(ReturnStatementNode node) { assert !node.finallyInserted; dest.write("return"); if (node.expr != null) { dest.write(" "); process(node.expr); } dest.writeln(";"); } private static void process(BreakStatementNode node) { dest.write("break"); if (node.id != null) { String id = BcCodeCs.identifier(node.id); dest.write(" " + id); } dest.writeln(";"); } private static void process(ThisExpressionNode node) { dest.write("this"); } private static void process(SuperExpressionNode node) { String extendsClass = BcCodeCs.type(lastBcClass.getExtendsType()); dest.write(extendsClass); } private static void process(SuperStatementNode node) { ArgumentListNode args = node.call.args; ListWriteDestination argsDest = new ListWriteDestination(); if (args != null) { pushDest(argsDest); int itemIndex = 0; for (Node arg : args.items) { process(arg); if (++itemIndex < args.items.size()) { dest.write(", "); } } popDest(); } dest.writelnf("%s(%s);", BcCodeCs.superCallMarker, argsDest); } private static void process(BcFunctionDeclaration bcFunc) { List<BcVariableDeclaration> oldDeclaredVars = declaredVars; lastBcFunction = bcFunc; declaredVars = bcFunc.getDeclaredVars(); // get function statements ListWriteDestination body = new ListWriteDestination(); pushDest(body); process(bcFunc.getStatements()); popDest(); List<String> lines = body.getLines(); String lastLine = lines.get(lines.size() - 2); if (lastLine.contains("return;")) { lines.remove(lines.size() - 2); } bcFunc.setBody(body); declaredVars = oldDeclaredVars; lastBcFunction = null; } private static void process(ExpressionStatementNode node) { process(node.expr); dest.writeln(";"); } private static void process(ListNode node) { ObjectList<Node> items = node.items; for (Node item : items) { process(item); } } private static void process(BcTypeNode typeNode) { if (!typeNode.isIntegral() && !typeNode.hasClassNode()) { BcClassDefinitionNode classNode = findClass(typeNode.getNameEx()); assert classNode != null : typeNode.getNameEx(); typeNode.setClassNode(classNode); } } private static BcClassDefinitionNode findClass(String name) { BcClassDefinitionNode builtinClass = findBuiltinClass(name); if (builtinClass != null) { return builtinClass; } for (BcClassDefinitionNode bcClass : bcClasses) { if (bcClass.getClassType().getName().equals(name)) { return bcClass; } } return null; } private static BcClassDefinitionNode findBuiltinClass(String name) { return builtinClasses.get(name); } private static BcFunctionDeclaration findBuiltinFunc(String name) { return bcBuitinFunctions.get(name); } private static BcFunctionTypeNode findFunctionType(String identifier) { BcTypeNode foundType = findVariableType(identifier); if (foundType instanceof BcFunctionTypeNode) { return (BcFunctionTypeNode) foundType; } return null; } private static BcTypeNode findVariableType(String indentifier) { if (indentifier.equals("this")) { return BcTypeNode.create(lastBcClass.getName()); } BcTypeNode foundType = null; if (lastBcFunction != null) { foundType = findVariableType(lastBcFunction.getDeclaredVars(), indentifier); if (foundType != null) { return foundType; } } return findVariableType(lastBcClass.getDeclaredVars(), indentifier); } private static BcTypeNode findVariableType(List<BcVariableDeclaration> vars, String indentifier) { for (BcVariableDeclaration var : vars) { if (var.getIdentifier().equals(indentifier)) { return var.getType(); } } return null; } private static void write(File outputDir) throws IOException { for (BcClassDefinitionNode bcClass : bcClasses) { if (bcClass.isInterface()) { writeIntefaceDefinition(bcClass, outputDir); } else { writeClassDefinition(bcClass, outputDir); } } } private static void writeIntefaceDefinition(BcClassDefinitionNode bcClass, File outputDir) throws IOException { String className = getClassName(bcClass); String classExtends = getBaseClassName(bcClass); src = new FileWriteDestination(new File(outputDir, className + ".cs")); impl = null; List<BcTypeNode> headerTypes = getHeaderTypedefs(bcClass); src.writeln("namespace bc"); writeBlockOpen(src); src.writelnf("public interface %s : %s", className, classExtends); writeBlockOpen(src); writeInterfaceFunctions(bcClass); writeBlockClose(src); writeBlockClose(src); src.close(); } private static void writeInterfaceFunctions(BcClassDefinitionNode bcClass) { List<BcFunctionDeclaration> functions = bcClass.getFunctions(); for (BcFunctionDeclaration bcFunc : functions) { String type = bcFunc.hasReturnType() ? BcCodeCs.typeRef(bcFunc.getReturnType()) : "void"; String name = BcCodeCs.identifier(bcFunc.getName()); if (bcFunc.isConstructor()) { continue; } src.writef("%s %s(", type, name); StringBuilder paramsBuffer = new StringBuilder(); StringBuilder argsBuffer = new StringBuilder(); List<BcFuncParam> params = bcFunc.getParams(); int paramIndex = 0; for (BcFuncParam bcParam : params) { String paramType = BcCodeCs.type(bcParam.getType()); String paramName = BcCodeCs.identifier(bcParam.getIdentifier()); paramsBuffer.append(String.format("%s %s", paramType, paramName)); argsBuffer.append(paramName); if (++paramIndex < params.size()) { paramsBuffer.append(", "); argsBuffer.append(", "); } } src.write(paramsBuffer); src.writeln(");"); } } private static void writeClassDefinition(BcClassDefinitionNode bcClass, File outputDir) throws IOException { String className = getClassName(bcClass); String classExtends = getBaseClassName(bcClass); src = new FileWriteDestination(new File(outputDir, className + ".cs")); impl = new ListWriteDestination(); List<BcTypeNode> headerTypes = getHeaderTypedefs(bcClass); List<BcTypeNode> implTypes = getImplementationTypedefs(bcClass); src.writeln("namespace bc"); writeBlockOpen(src); src.writelnf("public class %s : %s", className, classExtends); writeBlockOpen(src); writeFields(bcClass); writeFunctions(bcClass); writeBlockClose(src); writeBlockClose(src); src.close(); } private static void writeHeaderTypes(WriteDestination dst, List<BcTypeNode> types) { for (BcTypeNode bcType : types) { if (bcType instanceof BcVectorTypeNode) { BcVectorTypeNode vectorType = (BcVectorTypeNode) bcType; String genericName = BcCodeCs.type(vectorType.getGeneric()); String typeName = BcCodeCs.type(bcType); dst.writelnf("typedef %s<%s> %s;", BcCodeCs.type(BcCodeCs.VECTOR_TYPE), BcCodeCs.type(genericName), typeName); dst.writelnf("typedef %s::Ref %s;", typeName, BcCodeCs.type(typeName)); } else { String typeName = BcCodeCs.type(bcType); dst.writelnf("__TYPEREF_DEF(%s)", typeName); } } } private static void writeImplementationTypes(WriteDestination dst, List<BcTypeNode> types) { for (BcTypeNode type : types) { if (type instanceof BcVectorTypeNode) { System.err.println("Fix me!!! Vector in implementation"); } else { String typeName = BcCodeCs.type(type); dst.writelnf("#include \"%s.h\"", typeName); } } } private static void writeFields(BcClassDefinitionNode bcClass) { List<BcVariableDeclaration> fields = bcClass.getFields(); impl.writeln(); for (BcVariableDeclaration bcField : fields) { String type = BcCodeCs.type(bcField.getType()); String name = BcCodeCs.identifier(bcField.getIdentifier()); src.write(bcField.getVisiblity() + " "); if (bcField.isStatic()) { src.write("static "); } if (bcField.isConst()) { src.write("const "); } src.writef("%s %s", type, name); if (bcField.hasInitializer()) { src.writef(" = %s", bcField.getInitializer()); } src.writeln(";"); } } private static void writeFunctions(BcClassDefinitionNode bcClass) { List<BcFunctionDeclaration> functions = bcClass.getFunctions(); for (BcFunctionDeclaration bcFunc : functions) { String type = bcFunc.hasReturnType() ? BcCodeCs.type(bcFunc.getReturnType()) : "void"; String name = BcCodeCs.identifier(bcFunc.getName()); src.write(bcFunc.getVisiblity() + " "); if (!bcFunc.isConstructor()) { if (bcFunc.isStatic()) { src.write("static "); } else { src.write("virtual "); } src.write(type + " "); } src.writef("%s(", name); StringBuilder paramsBuffer = new StringBuilder(); List<BcFuncParam> params = bcFunc.getParams(); int paramIndex = 0; for (BcFuncParam bcParam : params) { String paramType = BcCodeCs.type(bcParam.getType()); String paramName = BcCodeCs.identifier(bcParam.getIdentifier()); paramsBuffer.append(String.format("%s %s", paramType, paramName)); if (++paramIndex < params.size()) { paramsBuffer.append(", "); } } src.write(paramsBuffer); src.writeln(")"); src.writeln(bcFunc.getBody()); } } private static void writeBlockOpen(WriteDestination dest) { dest.writeln("{"); dest.incTab(); } private static void writeBlockClose(WriteDestination dest) { dest.decTab(); dest.writeln("}"); } private static void writeEmptyBlock() { writeEmptyBlock(dest); } private static void writeBlankLine(WriteDestination dest) { dest.writeln(); } private static void writeBlankLine() { src.writeln(); impl.writeln(); } private static void writeEmptyBlock(WriteDestination dest) { writeBlockOpen(dest); writeBlockClose(dest); } private static void pushDest(WriteDestination newDest) { destStack.push(dest); dest = newDest; } private static void popDest() { dest = destStack.pop(); } /////////////////////////////////////////////////////////////// // Helpers private static BcFunctionDeclaration findFunction(String name) { return lastBcClass.findFunction(name); } private static BcVariableDeclaration findDeclaredVar(String name) { assert declaredVars != null; for (BcVariableDeclaration var : declaredVars) { if (var.getIdentifier().equals(name)) return var; } return null; } private static List<BcTypeNode> getHeaderTypedefs(BcClassDefinitionNode bcClass) { List<BcTypeNode> includes = new ArrayList<BcTypeNode>(); tryAddUniqueType(includes, bcClass.getClassType()); if (bcClass.hasInterfaces()) { List<BcTypeNode> interfaces = bcClass.getInterfaces(); for (BcTypeNode bcInterface : interfaces) { tryAddUniqueType(includes, bcInterface); } } List<BcVariableDeclaration> classVars = bcClass.getDeclaredVars(); for (BcVariableDeclaration bcVar : classVars) { BcTypeNode type = bcVar.getType(); tryAddUniqueType(includes, type); } List<BcFunctionDeclaration> functions = bcClass.getFunctions(); for (BcFunctionDeclaration bcFunc : functions) { if (bcFunc.hasReturnType()) { BcTypeNode returnType = bcFunc.getReturnType(); tryAddUniqueType(includes, returnType); } List<BcFuncParam> params = bcFunc.getParams(); for (BcFuncParam param : params) { BcTypeNode type = param.getType(); tryAddUniqueType(includes, type); } } return includes; } private static List<BcTypeNode> getImplementationTypedefs(BcClassDefinitionNode bcClass) { List<BcTypeNode> includes = new ArrayList<BcTypeNode>(); List<BcFunctionDeclaration> functions = bcClass.getFunctions(); for (BcFunctionDeclaration bcFunc : functions) { List<BcVariableDeclaration> funcVars = bcFunc.getDeclaredVars(); for (BcVariableDeclaration var : funcVars) { BcTypeNode type = var.getType(); tryAddUniqueType(includes, type); } } return includes; } private static void tryAddUniqueType(List<BcTypeNode> types, BcTypeNode type) { if (BcCodeCs.canBeClass(type)) { if (type instanceof BcVectorTypeNode) { BcVectorTypeNode vectorType = (BcVectorTypeNode) type; tryAddUniqueType(types, vectorType.getGeneric()); } if (!types.contains(type)) { types.add(type); } } } private static String getClassName(BcClassDefinitionNode bcClass) { return BcCodeCs.type(bcClass.getName()); } private static String getBaseClassName(BcClassDefinitionNode bcClass) { if (bcClass.hasExtendsType()) { return BcCodeCs.type(bcClass.getExtendsType()); } return BcCodeCs.type(classObject); } public static BcTypeNode evaluateType(Node node) { if (node instanceof IdentifierNode) { IdentifierNode identifier = (IdentifierNode) node; return findIdentifierType(BcCodeCs.identifier(identifier)); } if (node instanceof LiteralNumberNode) { LiteralNumberNode numberNode = (LiteralNumberNode) node; return numberNode.value.indexOf('.') != -1 ? BcTypeNode.create("float") : BcTypeNode.create("int"); } if (node instanceof LiteralStringNode) { return BcTypeNode.create(classString); } if (node instanceof LiteralBooleanNode) { return BcTypeNode.create("BOOL"); } if (node instanceof LiteralNullNode) { return BcTypeNode.create("null"); } if (node instanceof ListNode) { ListNode listNode = (ListNode) node; assert listNode.items.size() == 1; return evaluateType(listNode.items.get(0)); } if (node instanceof ThisExpressionNode) { assert lastBcClass != null; return lastBcClass.getClassType(); } if (node instanceof MemberExpressionNode) { return evaluateMemberExpression((MemberExpressionNode) node); } if (node instanceof GetExpressionNode) { GetExpressionNode get = (GetExpressionNode) node; return evaluateType(get.expr); } if (node instanceof ArgumentListNode) { ArgumentListNode args = (ArgumentListNode) node; assert args.size() == 1; return evaluateType(args.items.get(0)); } // MemberExpressionNode expr = null; // if (node instanceof TypeExpressionNode) // { // TypeExpressionNode typeNode = (TypeExpressionNode) node; // expr = (MemberExpressionNode) typeNode.expr; // } // else if (node instanceof MemberExpressionNode) // { // expr = (MemberExpressionNode) node; // } // else // { // BcDebug.implementMe(node); // } // // if (expr.selector instanceof GetExpressionNode) // { // GetExpressionNode selector = (GetExpressionNode) expr.selector; // String name = ((IdentifierNode)selector.expr).name; // if (name.equals("Function")) // { // assert false; // return new BcFunctionTypeNode(); // } // // return BcTypeNode.create(name); // } // // if (expr.selector instanceof ApplyTypeExprNode) // { // ApplyTypeExprNode selector = (ApplyTypeExprNode) expr.selector; // String typeName = ((IdentifierNode)selector.expr).name; // // ListNode typeArgs = selector.typeArgs; // assert typeArgs.size() == 1; // // BcTypeNode genericType = extractBcType(typeArgs.items.get(0)); // return new BcVectorTypeNode(typeName, genericType); // } // // assert false : expr.selector.getClass(); return null; } private static BcTypeNode evaluateMemberExpression(MemberExpressionNode node) { BcClassDefinitionNode baseClass = lastBcClass; boolean hasCallTarget = node.base != null; if (hasCallTarget) { if (node.base instanceof MemberExpressionNode) { assert node.base instanceof MemberExpressionNode; BcTypeNode baseType = evaluateMemberExpression((MemberExpressionNode) node.base); assert baseType != null; baseClass = baseType.getClassNode(); assert baseClass != null; } else if (node.base instanceof ThisExpressionNode) { // we're good } else if (node.base instanceof SuperExpressionNode) { baseClass = baseClass.getExtendsType().getClassNode(); // get supertype } else if (node.base instanceof ListNode) { ListNode list = (ListNode) node.base; assert list.size() == 1 : list.size(); assert list.items.get(0) instanceof MemberExpressionNode; BcTypeNode baseType = evaluateMemberExpression((MemberExpressionNode) list.items.get(0)); assert baseType != null; baseClass = baseType.getClassNode(); assert baseClass != null; } else { assert false; } } if (node.selector instanceof SelectorNode) { SelectorNode selector = (SelectorNode) node.selector; if (selector.expr instanceof IdentifierNode) { IdentifierNode identifier = (IdentifierNode) selector.expr; BcTypeNode identifierType = findIdentifierType(baseClass, identifier, hasCallTarget); if (identifierType != null) { return identifierType; } else { if (baseClass.getName().equals(classXML)) { return BcTypeNode.create(classXMLList); // dirty hack } else if (BcCodeCs.identifier(identifier).equals(BcCodeCs.thisCallMarker)) { return lastBcClass.getClassType(); // this referes to the current class } else if (baseClass.getName().endsWith(classObject)) { return BcTypeNode.create(classObject); } } } else if (selector.expr instanceof ArgumentListNode) { BcTypeNode baseClassType = baseClass.getClassType(); if (baseClassType instanceof BcVectorTypeNode) { BcVectorTypeNode bcVector = (BcVectorTypeNode) baseClassType; return bcVector.getGeneric(); } else { return BcTypeNode.create(classObject); // no generics } } else { assert false; } } else { assert false; } return null; } private static BcTypeNode findIdentifierType(BcClassDefinitionNode baseClass, IdentifierNode identifier, boolean hasCallTarget) { if (identifier.isAttr()) { return BcTypeNode.create(classString); // hack } String name = BcNodeHelper.extractBcIdentifier(identifier); // check if it's class if (BcCodeCs.canBeClass(name)) { BcClassDefinitionNode bcClass = findClass(name); if (bcClass != null) { return bcClass.getClassType(); } } else if (BcCodeCs.isBasicType(name)) { return BcTypeNode.create(name); } // search for local variable if (!hasCallTarget && lastBcFunction != null) { BcVariableDeclaration bcVar = lastBcFunction.findVariable(name); if (bcVar != null) return bcVar.getType(); } // search for function BcFunctionDeclaration bcFunc = baseClass.findFunction(name); if (bcFunc != null || (bcFunc = findBuiltinFunc(name)) != null) { if (bcFunc.hasReturnType()) { return bcFunc.getReturnType(); } return BcTypeNode.create("void"); } // search for field BcVariableDeclaration bcField = baseClass.findField(name); if (bcField != null) { return bcField.getType(); } return null; } private static BcTypeNode extractBcType(Node node) { BcTypeNode bcType = BcNodeHelper.extractBcType(node); if (bcType instanceof BcVectorTypeNode) { BcClassDefinitionNode vectorGenericClass = findBuiltinClass(classVector).clone(); vectorGenericClass.setClassType(bcType); builtinClasses.put(bcType.getNameEx(), vectorGenericClass); bcType.setClassNode(vectorGenericClass); } BcTypeNode.add(bcType.getNameEx(), bcType); return bcType; } private static void generateFunctor(WriteDestination dest, String className) { // BcClassDefinitionNode bcClass = new BcClassDefinitionNode("Functor"); // bcClass.setExtendsType(new BcTypeNode("Object")); // // List<String> targetModifiers = new ArrayList<String>(); // targetModifiers.add("private"); // // BcVariableDeclaration targetVar = new BcVariableDeclaration(new BcTypeNode("Object"), new BcIdentifierNode("target")); // targetVar.setModifiers(targetModifiers); // bcClass.add(targetVar); // // List<String> operatorModifiers = new ArrayList<String>(); // operatorModifiers.add("public"); // // BcFunctionDeclaration operatorFunc = new BcFunctionDeclaration("operator()"); // operatorFunc.setModifiers(operatorModifiers); } }
true
true
private static void process(ForStatementNode node) { boolean isForEach = node.test instanceof HasNextNode; if (isForEach) { // get iterable collection expression assert node.initialize != null; assert node.initialize instanceof ListNode : node.initialize.getClass(); ListNode list = (ListNode) node.initialize; assert list.items.size() == 2 : list.items.size(); StoreRegisterNode register = (StoreRegisterNode) list.items.get(1); CoerceNode coerce = (CoerceNode) register.expr; ListWriteDestination collection = new ListWriteDestination(); pushDest(collection); process(coerce.expr); popDest(); BcTypeNode collectionType = evaluateType(coerce.expr); assert collectionType != null; assert node.statement != null; assert node.statement instanceof StatementListNode : node.statement.getClass(); StatementListNode statements = (StatementListNode) node.statement; assert statements.items.size() == 2; // get iteration ExpressionStatementNode child1 = (ExpressionStatementNode) statements.items.get(0); MemberExpressionNode child2 = (MemberExpressionNode) child1.expr; SetExpressionNode child3 = (SetExpressionNode) child2.selector; String loopVarName = null; if (child3.expr instanceof QualifiedIdentifierNode) { QualifiedIdentifierNode identifier = (QualifiedIdentifierNode) child3.expr; loopVarName = BcCodeCs.identifier(identifier.name); } else if (child3.expr instanceof IdentifierNode) { IdentifierNode identifier = (IdentifierNode) child3.expr; loopVarName = BcCodeCs.identifier(identifier.name); } else { assert false : child3.expr.getClass(); } BcVariableDeclaration loopVar = findDeclaredVar(loopVarName); assert loopVar != null : loopVarName; // get loop body dest.writelnf("foreach (%s %s in %s)", BcCodeCs.type(collectionType), loopVarName, collection); Node bodyNode = statements.items.get(1); if (bodyNode != null) { assert bodyNode instanceof StatementListNode : bodyNode.getClass(); StatementListNode statementsNode = (StatementListNode) bodyNode; writeBlockOpen(dest); ObjectList<Node> items = statementsNode.items; for (Node itemNode : items) { process(itemNode); } writeBlockClose(dest); } else { writeEmptyBlock(); } } else { ListWriteDestination initialize = new ListWriteDestination(); ListWriteDestination test = new ListWriteDestination(); ListWriteDestination increment = new ListWriteDestination(); if (node.initialize != null) { pushDest(initialize); process(node.initialize); popDest(); } if (node.test != null) { pushDest(test); process(node.test); popDest(); } if (node.increment != null) { increment = new ListWriteDestination(); pushDest(increment); process(node.increment); popDest(); } dest.writelnf("for (%s; %s; %s)", initialize, test, increment); process(node.statement); } }
private static void process(ForStatementNode node) { boolean isForEach = node.test instanceof HasNextNode; if (isForEach) { // get iterable collection expression assert node.initialize != null; assert node.initialize instanceof ListNode : node.initialize.getClass(); ListNode list = (ListNode) node.initialize; assert list.items.size() == 2 : list.items.size(); StoreRegisterNode register = (StoreRegisterNode) list.items.get(1); CoerceNode coerce = (CoerceNode) register.expr; ListWriteDestination collection = new ListWriteDestination(); pushDest(collection); process(coerce.expr); popDest(); BcTypeNode collectionType = evaluateType(coerce.expr); assert collectionType != null; assert node.statement != null; assert node.statement instanceof StatementListNode : node.statement.getClass(); StatementListNode statements = (StatementListNode) node.statement; assert statements.items.size() == 2; // get iteration ExpressionStatementNode child1 = (ExpressionStatementNode) statements.items.get(0); MemberExpressionNode child2 = (MemberExpressionNode) child1.expr; SetExpressionNode child3 = (SetExpressionNode) child2.selector; String loopVarName = null; if (child3.expr instanceof QualifiedIdentifierNode) { QualifiedIdentifierNode identifier = (QualifiedIdentifierNode) child3.expr; loopVarName = BcCodeCs.identifier(identifier.name); } else if (child3.expr instanceof IdentifierNode) { IdentifierNode identifier = (IdentifierNode) child3.expr; loopVarName = BcCodeCs.identifier(identifier.name); } else { assert false : child3.expr.getClass(); } BcVariableDeclaration loopVar = findDeclaredVar(loopVarName); assert loopVar != null : loopVarName; // get loop body dest.writelnf("foreach (%s %s in %s)", BcCodeCs.type(loopVar.getType()), loopVarName, collection); Node bodyNode = statements.items.get(1); if (bodyNode != null) { assert bodyNode instanceof StatementListNode : bodyNode.getClass(); StatementListNode statementsNode = (StatementListNode) bodyNode; writeBlockOpen(dest); ObjectList<Node> items = statementsNode.items; for (Node itemNode : items) { process(itemNode); } writeBlockClose(dest); } else { writeEmptyBlock(); } } else { ListWriteDestination initialize = new ListWriteDestination(); ListWriteDestination test = new ListWriteDestination(); ListWriteDestination increment = new ListWriteDestination(); if (node.initialize != null) { pushDest(initialize); process(node.initialize); popDest(); } if (node.test != null) { pushDest(test); process(node.test); popDest(); } if (node.increment != null) { increment = new ListWriteDestination(); pushDest(increment); process(node.increment); popDest(); } dest.writelnf("for (%s; %s; %s)", initialize, test, increment); process(node.statement); } }
diff --git a/src/main/java/org/elasticsearch/cluster/metadata/MetaDataMappingService.java b/src/main/java/org/elasticsearch/cluster/metadata/MetaDataMappingService.java index f8611e7ed6c..bebb71fd0f7 100644 --- a/src/main/java/org/elasticsearch/cluster/metadata/MetaDataMappingService.java +++ b/src/main/java/org/elasticsearch/cluster/metadata/MetaDataMappingService.java @@ -1,603 +1,605 @@ /* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch 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.elasticsearch.cluster.metadata; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.elasticsearch.action.support.master.MasterNodeOperationRequest; import org.elasticsearch.cluster.*; import org.elasticsearch.cluster.action.index.NodeMappingCreatedAction; import org.elasticsearch.cluster.routing.IndexRoutingTable; import org.elasticsearch.common.Priority; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.compress.CompressedString; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.ConcurrentCollections; import org.elasticsearch.index.Index; import org.elasticsearch.index.mapper.DocumentMapper; import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.mapper.MergeMappingException; import org.elasticsearch.index.percolator.PercolatorService; import org.elasticsearch.index.service.IndexService; import org.elasticsearch.indices.IndexMissingException; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.indices.InvalidTypeNameException; import org.elasticsearch.indices.TypeMissingException; import java.util.*; import java.util.concurrent.BlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static com.google.common.collect.Maps.newHashMap; import static org.elasticsearch.cluster.ClusterState.newClusterStateBuilder; import static org.elasticsearch.cluster.metadata.IndexMetaData.newIndexMetaDataBuilder; import static org.elasticsearch.cluster.metadata.MetaData.newMetaDataBuilder; import static org.elasticsearch.index.mapper.DocumentMapper.MergeFlags.mergeFlags; /** * */ public class MetaDataMappingService extends AbstractComponent { private final ClusterService clusterService; private final IndicesService indicesService; private final NodeMappingCreatedAction mappingCreatedAction; private final BlockingQueue<Object> refreshOrUpdateQueue = ConcurrentCollections.newBlockingQueue(); @Inject public MetaDataMappingService(Settings settings, ClusterService clusterService, IndicesService indicesService, NodeMappingCreatedAction mappingCreatedAction) { super(settings); this.clusterService = clusterService; this.indicesService = indicesService; this.mappingCreatedAction = mappingCreatedAction; } static class RefreshTask { final String index; final String[] types; RefreshTask(String index, String[] types) { this.index = index; this.types = types; } } static class UpdateTask { final String index; final String type; final CompressedString mappingSource; final Listener listener; UpdateTask(String index, String type, CompressedString mappingSource, Listener listener) { this.index = index; this.type = type; this.mappingSource = mappingSource; this.listener = listener; } } /** * Batch method to apply all the queued refresh or update operations. The idea is to try and batch as much * as possible so we won't create the same index all the time for example for the updates on the same mapping * and generate a single cluster change event out of all of those. */ ClusterState executeRefreshOrUpdate(final ClusterState currentState) throws Exception { List<Object> allTasks = new ArrayList<Object>(); refreshOrUpdateQueue.drainTo(allTasks); if (allTasks.isEmpty()) { return currentState; } // break down to tasks per index, so we can optimize the on demand index service creation // to only happen for the duration of a single index processing of its respective events Map<String, List<Object>> tasksPerIndex = Maps.newHashMap(); for (Object task : allTasks) { String index = null; if (task instanceof UpdateTask) { index = ((UpdateTask) task).index; } else if (task instanceof RefreshTask) { index = ((RefreshTask) task).index; } else { logger.warn("illegal state, got wrong mapping task type [{}]", task); } if (index != null) { List<Object> indexTasks = tasksPerIndex.get(index); if (indexTasks == null) { indexTasks = new ArrayList<Object>(); tasksPerIndex.put(index, indexTasks); } indexTasks.add(task); } } boolean dirty = false; MetaData.Builder mdBuilder = newMetaDataBuilder().metaData(currentState.metaData()); for (Map.Entry<String, List<Object>> entry : tasksPerIndex.entrySet()) { String index = entry.getKey(); List<Object> tasks = entry.getValue(); boolean removeIndex = false; // keep track of what we already refreshed, no need to refresh it again... Set<String> processedRefreshes = Sets.newHashSet(); try { for (Object task : tasks) { if (task instanceof RefreshTask) { RefreshTask refreshTask = (RefreshTask) task; final IndexMetaData indexMetaData = mdBuilder.get(index); if (indexMetaData == null) { // index got delete on us, ignore... continue; } IndexService indexService = indicesService.indexService(index); if (indexService == null) { // we need to create the index here, and add the current mapping to it, so we can merge indexService = indicesService.createIndex(indexMetaData.index(), indexMetaData.settings(), currentState.nodes().localNode().id()); removeIndex = true; for (String type : refreshTask.types) { // only add the current relevant mapping (if exists) if (indexMetaData.mappings().containsKey(type)) { // don't apply the default mapping, it has been applied when the mapping was created indexService.mapperService().merge(type, indexMetaData.mappings().get(type).source().string(), false); } } } IndexMetaData.Builder indexMetaDataBuilder = newIndexMetaDataBuilder(indexMetaData); List<String> updatedTypes = Lists.newArrayList(); for (String type : refreshTask.types) { if (processedRefreshes.contains(type)) { continue; } DocumentMapper mapper = indexService.mapperService().documentMapper(type); if (!mapper.mappingSource().equals(indexMetaData.mappings().get(type).source())) { updatedTypes.add(type); indexMetaDataBuilder.putMapping(new MappingMetaData(mapper)); } processedRefreshes.add(type); } if (updatedTypes.isEmpty()) { continue; } logger.warn("[{}] re-syncing mappings with cluster state for types [{}]", index, updatedTypes); mdBuilder.put(indexMetaDataBuilder); dirty = true; } else if (task instanceof UpdateTask) { UpdateTask updateTask = (UpdateTask) task; String type = updateTask.type; CompressedString mappingSource = updateTask.mappingSource; // first, check if it really needs to be updated final IndexMetaData indexMetaData = mdBuilder.get(index); if (indexMetaData == null) { // index got delete on us, ignore... continue; } if (indexMetaData.mappings().containsKey(type) && indexMetaData.mapping(type).source().equals(mappingSource)) { continue; } IndexService indexService = indicesService.indexService(index); if (indexService == null) { // we need to create the index here, and add the current mapping to it, so we can merge indexService = indicesService.createIndex(indexMetaData.index(), indexMetaData.settings(), currentState.nodes().localNode().id()); removeIndex = true; // only add the current relevant mapping (if exists) if (indexMetaData.mappings().containsKey(type)) { indexService.mapperService().merge(type, indexMetaData.mappings().get(type).source().string(), false); } } DocumentMapper updatedMapper = indexService.mapperService().merge(type, mappingSource.string(), false); processedRefreshes.add(type); // if we end up with the same mapping as the original once, ignore if (indexMetaData.mappings().containsKey(type) && indexMetaData.mapping(type).source().equals(updatedMapper.mappingSource())) { continue; } // build the updated mapping source if (logger.isDebugEnabled()) { try { logger.debug("[{}] update_mapping [{}] (dynamic) with source [{}]", index, type, updatedMapper.mappingSource().string()); } catch (Exception e) { // ignore } } else if (logger.isInfoEnabled()) { logger.info("[{}] update_mapping [{}] (dynamic)", index, type); } mdBuilder.put(newIndexMetaDataBuilder(indexMetaData).putMapping(new MappingMetaData(updatedMapper))); dirty = true; } else { logger.warn("illegal state, got wrong mapping task type [{}]", task); } } } finally { if (removeIndex) { indicesService.removeIndex(index, "created for mapping processing"); } for (Object task : tasks) { if (task instanceof UpdateTask) { ((UpdateTask) task).listener.onResponse(new Response(true)); } } } } if (!dirty) { return currentState; } return newClusterStateBuilder().state(currentState).metaData(mdBuilder).build(); } /** * Refreshes mappings if they are not the same between original and parsed version */ public void refreshMapping(final String index, final String... types) { refreshOrUpdateQueue.add(new RefreshTask(index, types)); clusterService.submitStateUpdateTask("refresh-mapping [" + index + "][" + Arrays.toString(types) + "]", Priority.HIGH, new ClusterStateUpdateTask() { @Override public void onFailure(String source, Throwable t) { logger.warn("failure during [{}]", t, source); } @Override public ClusterState execute(ClusterState currentState) throws Exception { return executeRefreshOrUpdate(currentState); } }); } public void updateMapping(final String index, final String type, final CompressedString mappingSource, final Listener listener) { refreshOrUpdateQueue.add(new UpdateTask(index, type, mappingSource, listener)); clusterService.submitStateUpdateTask("update-mapping [" + index + "][" + type + "]", Priority.HIGH, new ProcessedClusterStateUpdateTask() { @Override public void onFailure(String source, Throwable t) { listener.onFailure(t); } @Override public ClusterState execute(final ClusterState currentState) throws Exception { return executeRefreshOrUpdate(currentState); } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { listener.onResponse(new Response(true)); } }); } public void removeMapping(final RemoveRequest request, final Listener listener) { clusterService.submitStateUpdateTask("remove-mapping [" + request.mappingType + "]", Priority.HIGH, new TimeoutClusterStateUpdateTask() { @Override public TimeValue timeout() { return request.masterTimeout; } @Override public void onFailure(String source, Throwable t) { listener.onFailure(t); } @Override public ClusterState execute(ClusterState currentState) { if (request.indices.length == 0) { throw new IndexMissingException(new Index("_all")); } MetaData.Builder builder = newMetaDataBuilder().metaData(currentState.metaData()); boolean changed = false; String latestIndexWithout = null; for (String indexName : request.indices) { IndexMetaData indexMetaData = currentState.metaData().index(indexName); if (indexMetaData != null) { if (indexMetaData.mappings().containsKey(request.mappingType)) { builder.put(newIndexMetaDataBuilder(indexMetaData).removeMapping(request.mappingType)); changed = true; } else { latestIndexWithout = indexMetaData.index(); } } } if (!changed) { throw new TypeMissingException(new Index(latestIndexWithout), request.mappingType); } logger.info("[{}] remove_mapping [{}]", request.indices, request.mappingType); return ClusterState.builder().state(currentState).metaData(builder).build(); } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { listener.onResponse(new Response(true)); } }); } public void putMapping(final PutRequest request, final Listener listener) { final AtomicBoolean notifyOnPostProcess = new AtomicBoolean(); clusterService.submitStateUpdateTask("put-mapping [" + request.mappingType + "]", Priority.HIGH, new TimeoutClusterStateUpdateTask() { @Override public TimeValue timeout() { return request.masterTimeout; } @Override public void onFailure(String source, Throwable t) { listener.onFailure(t); } @Override public ClusterState execute(final ClusterState currentState) throws Exception { List<String> indicesToClose = Lists.newArrayList(); try { if (request.indices.length == 0) { throw new IndexMissingException(new Index("_all")); } for (String index : request.indices) { if (!currentState.metaData().hasIndex(index)) { throw new IndexMissingException(new Index(index)); } } // pre create indices here and add mappings to them so we can merge the mappings here if needed for (String index : request.indices) { if (indicesService.hasIndex(index)) { continue; } final IndexMetaData indexMetaData = currentState.metaData().index(index); IndexService indexService = indicesService.createIndex(indexMetaData.index(), indexMetaData.settings(), currentState.nodes().localNode().id()); indicesToClose.add(indexMetaData.index()); // only add the current relevant mapping (if exists) if (indexMetaData.mappings().containsKey(request.mappingType)) { indexService.mapperService().merge(request.mappingType, indexMetaData.mappings().get(request.mappingType).source().string(), false); } } Map<String, DocumentMapper> newMappers = newHashMap(); Map<String, DocumentMapper> existingMappers = newHashMap(); for (String index : request.indices) { IndexService indexService = indicesService.indexService(index); if (indexService != null) { // try and parse it (no need to add it here) so we can bail early in case of parsing exception DocumentMapper newMapper = indexService.mapperService().parse(request.mappingType, request.mappingSource); newMappers.put(index, newMapper); DocumentMapper existingMapper = indexService.mapperService().documentMapper(request.mappingType); if (existingMapper != null) { // first, simulate DocumentMapper.MergeResult mergeResult = existingMapper.merge(newMapper, mergeFlags().simulate(true)); // if we have conflicts, and we are not supposed to ignore them, throw an exception if (!request.ignoreConflicts && mergeResult.hasConflicts()) { throw new MergeMappingException(mergeResult.conflicts()); } existingMappers.put(index, existingMapper); } } else { throw new IndexMissingException(new Index(index)); } } String mappingType = request.mappingType; if (mappingType == null) { mappingType = newMappers.values().iterator().next().type(); } else if (!mappingType.equals(newMappers.values().iterator().next().type())) { throw new InvalidTypeNameException("Type name provided does not match type name within mapping definition"); } if (!MapperService.DEFAULT_MAPPING.equals(mappingType) && !PercolatorService.Constants.TYPE_NAME.equals(mappingType) && mappingType.charAt(0) == '_') { throw new InvalidTypeNameException("Document mapping type name can't start with '_'"); } final Map<String, MappingMetaData> mappings = newHashMap(); for (Map.Entry<String, DocumentMapper> entry : newMappers.entrySet()) { String index = entry.getKey(); // do the actual merge here on the master, and update the mapping source DocumentMapper newMapper = entry.getValue(); IndexService indexService = indicesService.indexService(index); CompressedString existingSource = null; if (existingMappers.containsKey(entry.getKey())) { existingSource = existingMappers.get(entry.getKey()).mappingSource(); } DocumentMapper mergedMapper = indexService.mapperService().merge(newMapper.type(), newMapper.mappingSource().string(), false); CompressedString updatedSource = mergedMapper.mappingSource(); if (existingSource != null) { if (existingSource.equals(updatedSource)) { // same source, no changes, ignore it } else { // use the merged mapping source mappings.put(index, new MappingMetaData(mergedMapper)); if (logger.isDebugEnabled()) { logger.debug("[{}] update_mapping [{}] with source [{}]", index, mergedMapper.type(), updatedSource); } else if (logger.isInfoEnabled()) { logger.info("[{}] update_mapping [{}]", index, mergedMapper.type()); } } } else { mappings.put(index, new MappingMetaData(mergedMapper)); if (logger.isDebugEnabled()) { logger.debug("[{}] create_mapping [{}] with source [{}]", index, newMapper.type(), updatedSource); } else if (logger.isInfoEnabled()) { logger.info("[{}] create_mapping [{}]", index, newMapper.type()); } } } if (mappings.isEmpty()) { + // no changes, return + listener.onResponse(new Response(true)); return currentState; } MetaData.Builder builder = newMetaDataBuilder().metaData(currentState.metaData()); for (String indexName : request.indices) { IndexMetaData indexMetaData = currentState.metaData().index(indexName); if (indexMetaData == null) { throw new IndexMissingException(new Index(indexName)); } MappingMetaData mappingMd = mappings.get(indexName); if (mappingMd != null) { builder.put(newIndexMetaDataBuilder(indexMetaData).putMapping(mappingMd)); } } ClusterState updatedState = newClusterStateBuilder().state(currentState).metaData(builder).build(); // wait for responses from other nodes if needed int counter = 0; for (String index : request.indices) { IndexRoutingTable indexRoutingTable = updatedState.routingTable().index(index); if (indexRoutingTable != null) { counter += indexRoutingTable.numberOfNodesShardsAreAllocatedOn(updatedState.nodes().masterNodeId()); } } if (counter == 0) { notifyOnPostProcess.set(true); return updatedState; } mappingCreatedAction.add(new CountDownListener(counter, listener), request.timeout); return updatedState; } finally { for (String index : indicesToClose) { indicesService.removeIndex(index, "created for mapping processing"); } } } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { if (notifyOnPostProcess.get()) { listener.onResponse(new Response(true)); } } }); } public static interface Listener { void onResponse(Response response); void onFailure(Throwable t); } public static class RemoveRequest { final String[] indices; final String mappingType; TimeValue masterTimeout = MasterNodeOperationRequest.DEFAULT_MASTER_NODE_TIMEOUT; public RemoveRequest(String[] indices, String mappingType) { this.indices = indices; this.mappingType = mappingType; } public RemoveRequest masterTimeout(TimeValue masterTimeout) { this.masterTimeout = masterTimeout; return this; } } public static class PutRequest { final String[] indices; final String mappingType; final String mappingSource; boolean ignoreConflicts = false; TimeValue timeout = TimeValue.timeValueSeconds(10); TimeValue masterTimeout = MasterNodeOperationRequest.DEFAULT_MASTER_NODE_TIMEOUT; public PutRequest(String[] indices, String mappingType, String mappingSource) { this.indices = indices; this.mappingType = mappingType; this.mappingSource = mappingSource; } public PutRequest ignoreConflicts(boolean ignoreConflicts) { this.ignoreConflicts = ignoreConflicts; return this; } public PutRequest timeout(TimeValue timeout) { this.timeout = timeout; return this; } public PutRequest masterTimeout(TimeValue masterTimeout) { this.masterTimeout = masterTimeout; return this; } } public static class Response { private final boolean acknowledged; public Response(boolean acknowledged) { this.acknowledged = acknowledged; } public boolean acknowledged() { return acknowledged; } } private class CountDownListener implements NodeMappingCreatedAction.Listener { private final AtomicBoolean notified = new AtomicBoolean(); private final AtomicInteger countDown; private final Listener listener; public CountDownListener(int countDown, Listener listener) { this.countDown = new AtomicInteger(countDown); this.listener = listener; } @Override public void onNodeMappingCreated(NodeMappingCreatedAction.NodeMappingCreatedResponse response) { if (countDown.decrementAndGet() == 0) { mappingCreatedAction.remove(this); if (notified.compareAndSet(false, true)) { listener.onResponse(new Response(true)); } } } @Override public void onTimeout() { mappingCreatedAction.remove(this); if (notified.compareAndSet(false, true)) { listener.onResponse(new Response(false)); } } } }
true
true
public void putMapping(final PutRequest request, final Listener listener) { final AtomicBoolean notifyOnPostProcess = new AtomicBoolean(); clusterService.submitStateUpdateTask("put-mapping [" + request.mappingType + "]", Priority.HIGH, new TimeoutClusterStateUpdateTask() { @Override public TimeValue timeout() { return request.masterTimeout; } @Override public void onFailure(String source, Throwable t) { listener.onFailure(t); } @Override public ClusterState execute(final ClusterState currentState) throws Exception { List<String> indicesToClose = Lists.newArrayList(); try { if (request.indices.length == 0) { throw new IndexMissingException(new Index("_all")); } for (String index : request.indices) { if (!currentState.metaData().hasIndex(index)) { throw new IndexMissingException(new Index(index)); } } // pre create indices here and add mappings to them so we can merge the mappings here if needed for (String index : request.indices) { if (indicesService.hasIndex(index)) { continue; } final IndexMetaData indexMetaData = currentState.metaData().index(index); IndexService indexService = indicesService.createIndex(indexMetaData.index(), indexMetaData.settings(), currentState.nodes().localNode().id()); indicesToClose.add(indexMetaData.index()); // only add the current relevant mapping (if exists) if (indexMetaData.mappings().containsKey(request.mappingType)) { indexService.mapperService().merge(request.mappingType, indexMetaData.mappings().get(request.mappingType).source().string(), false); } } Map<String, DocumentMapper> newMappers = newHashMap(); Map<String, DocumentMapper> existingMappers = newHashMap(); for (String index : request.indices) { IndexService indexService = indicesService.indexService(index); if (indexService != null) { // try and parse it (no need to add it here) so we can bail early in case of parsing exception DocumentMapper newMapper = indexService.mapperService().parse(request.mappingType, request.mappingSource); newMappers.put(index, newMapper); DocumentMapper existingMapper = indexService.mapperService().documentMapper(request.mappingType); if (existingMapper != null) { // first, simulate DocumentMapper.MergeResult mergeResult = existingMapper.merge(newMapper, mergeFlags().simulate(true)); // if we have conflicts, and we are not supposed to ignore them, throw an exception if (!request.ignoreConflicts && mergeResult.hasConflicts()) { throw new MergeMappingException(mergeResult.conflicts()); } existingMappers.put(index, existingMapper); } } else { throw new IndexMissingException(new Index(index)); } } String mappingType = request.mappingType; if (mappingType == null) { mappingType = newMappers.values().iterator().next().type(); } else if (!mappingType.equals(newMappers.values().iterator().next().type())) { throw new InvalidTypeNameException("Type name provided does not match type name within mapping definition"); } if (!MapperService.DEFAULT_MAPPING.equals(mappingType) && !PercolatorService.Constants.TYPE_NAME.equals(mappingType) && mappingType.charAt(0) == '_') { throw new InvalidTypeNameException("Document mapping type name can't start with '_'"); } final Map<String, MappingMetaData> mappings = newHashMap(); for (Map.Entry<String, DocumentMapper> entry : newMappers.entrySet()) { String index = entry.getKey(); // do the actual merge here on the master, and update the mapping source DocumentMapper newMapper = entry.getValue(); IndexService indexService = indicesService.indexService(index); CompressedString existingSource = null; if (existingMappers.containsKey(entry.getKey())) { existingSource = existingMappers.get(entry.getKey()).mappingSource(); } DocumentMapper mergedMapper = indexService.mapperService().merge(newMapper.type(), newMapper.mappingSource().string(), false); CompressedString updatedSource = mergedMapper.mappingSource(); if (existingSource != null) { if (existingSource.equals(updatedSource)) { // same source, no changes, ignore it } else { // use the merged mapping source mappings.put(index, new MappingMetaData(mergedMapper)); if (logger.isDebugEnabled()) { logger.debug("[{}] update_mapping [{}] with source [{}]", index, mergedMapper.type(), updatedSource); } else if (logger.isInfoEnabled()) { logger.info("[{}] update_mapping [{}]", index, mergedMapper.type()); } } } else { mappings.put(index, new MappingMetaData(mergedMapper)); if (logger.isDebugEnabled()) { logger.debug("[{}] create_mapping [{}] with source [{}]", index, newMapper.type(), updatedSource); } else if (logger.isInfoEnabled()) { logger.info("[{}] create_mapping [{}]", index, newMapper.type()); } } } if (mappings.isEmpty()) { return currentState; } MetaData.Builder builder = newMetaDataBuilder().metaData(currentState.metaData()); for (String indexName : request.indices) { IndexMetaData indexMetaData = currentState.metaData().index(indexName); if (indexMetaData == null) { throw new IndexMissingException(new Index(indexName)); } MappingMetaData mappingMd = mappings.get(indexName); if (mappingMd != null) { builder.put(newIndexMetaDataBuilder(indexMetaData).putMapping(mappingMd)); } } ClusterState updatedState = newClusterStateBuilder().state(currentState).metaData(builder).build(); // wait for responses from other nodes if needed int counter = 0; for (String index : request.indices) { IndexRoutingTable indexRoutingTable = updatedState.routingTable().index(index); if (indexRoutingTable != null) { counter += indexRoutingTable.numberOfNodesShardsAreAllocatedOn(updatedState.nodes().masterNodeId()); } } if (counter == 0) { notifyOnPostProcess.set(true); return updatedState; } mappingCreatedAction.add(new CountDownListener(counter, listener), request.timeout); return updatedState; } finally { for (String index : indicesToClose) { indicesService.removeIndex(index, "created for mapping processing"); } } } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { if (notifyOnPostProcess.get()) { listener.onResponse(new Response(true)); } } }); }
public void putMapping(final PutRequest request, final Listener listener) { final AtomicBoolean notifyOnPostProcess = new AtomicBoolean(); clusterService.submitStateUpdateTask("put-mapping [" + request.mappingType + "]", Priority.HIGH, new TimeoutClusterStateUpdateTask() { @Override public TimeValue timeout() { return request.masterTimeout; } @Override public void onFailure(String source, Throwable t) { listener.onFailure(t); } @Override public ClusterState execute(final ClusterState currentState) throws Exception { List<String> indicesToClose = Lists.newArrayList(); try { if (request.indices.length == 0) { throw new IndexMissingException(new Index("_all")); } for (String index : request.indices) { if (!currentState.metaData().hasIndex(index)) { throw new IndexMissingException(new Index(index)); } } // pre create indices here and add mappings to them so we can merge the mappings here if needed for (String index : request.indices) { if (indicesService.hasIndex(index)) { continue; } final IndexMetaData indexMetaData = currentState.metaData().index(index); IndexService indexService = indicesService.createIndex(indexMetaData.index(), indexMetaData.settings(), currentState.nodes().localNode().id()); indicesToClose.add(indexMetaData.index()); // only add the current relevant mapping (if exists) if (indexMetaData.mappings().containsKey(request.mappingType)) { indexService.mapperService().merge(request.mappingType, indexMetaData.mappings().get(request.mappingType).source().string(), false); } } Map<String, DocumentMapper> newMappers = newHashMap(); Map<String, DocumentMapper> existingMappers = newHashMap(); for (String index : request.indices) { IndexService indexService = indicesService.indexService(index); if (indexService != null) { // try and parse it (no need to add it here) so we can bail early in case of parsing exception DocumentMapper newMapper = indexService.mapperService().parse(request.mappingType, request.mappingSource); newMappers.put(index, newMapper); DocumentMapper existingMapper = indexService.mapperService().documentMapper(request.mappingType); if (existingMapper != null) { // first, simulate DocumentMapper.MergeResult mergeResult = existingMapper.merge(newMapper, mergeFlags().simulate(true)); // if we have conflicts, and we are not supposed to ignore them, throw an exception if (!request.ignoreConflicts && mergeResult.hasConflicts()) { throw new MergeMappingException(mergeResult.conflicts()); } existingMappers.put(index, existingMapper); } } else { throw new IndexMissingException(new Index(index)); } } String mappingType = request.mappingType; if (mappingType == null) { mappingType = newMappers.values().iterator().next().type(); } else if (!mappingType.equals(newMappers.values().iterator().next().type())) { throw new InvalidTypeNameException("Type name provided does not match type name within mapping definition"); } if (!MapperService.DEFAULT_MAPPING.equals(mappingType) && !PercolatorService.Constants.TYPE_NAME.equals(mappingType) && mappingType.charAt(0) == '_') { throw new InvalidTypeNameException("Document mapping type name can't start with '_'"); } final Map<String, MappingMetaData> mappings = newHashMap(); for (Map.Entry<String, DocumentMapper> entry : newMappers.entrySet()) { String index = entry.getKey(); // do the actual merge here on the master, and update the mapping source DocumentMapper newMapper = entry.getValue(); IndexService indexService = indicesService.indexService(index); CompressedString existingSource = null; if (existingMappers.containsKey(entry.getKey())) { existingSource = existingMappers.get(entry.getKey()).mappingSource(); } DocumentMapper mergedMapper = indexService.mapperService().merge(newMapper.type(), newMapper.mappingSource().string(), false); CompressedString updatedSource = mergedMapper.mappingSource(); if (existingSource != null) { if (existingSource.equals(updatedSource)) { // same source, no changes, ignore it } else { // use the merged mapping source mappings.put(index, new MappingMetaData(mergedMapper)); if (logger.isDebugEnabled()) { logger.debug("[{}] update_mapping [{}] with source [{}]", index, mergedMapper.type(), updatedSource); } else if (logger.isInfoEnabled()) { logger.info("[{}] update_mapping [{}]", index, mergedMapper.type()); } } } else { mappings.put(index, new MappingMetaData(mergedMapper)); if (logger.isDebugEnabled()) { logger.debug("[{}] create_mapping [{}] with source [{}]", index, newMapper.type(), updatedSource); } else if (logger.isInfoEnabled()) { logger.info("[{}] create_mapping [{}]", index, newMapper.type()); } } } if (mappings.isEmpty()) { // no changes, return listener.onResponse(new Response(true)); return currentState; } MetaData.Builder builder = newMetaDataBuilder().metaData(currentState.metaData()); for (String indexName : request.indices) { IndexMetaData indexMetaData = currentState.metaData().index(indexName); if (indexMetaData == null) { throw new IndexMissingException(new Index(indexName)); } MappingMetaData mappingMd = mappings.get(indexName); if (mappingMd != null) { builder.put(newIndexMetaDataBuilder(indexMetaData).putMapping(mappingMd)); } } ClusterState updatedState = newClusterStateBuilder().state(currentState).metaData(builder).build(); // wait for responses from other nodes if needed int counter = 0; for (String index : request.indices) { IndexRoutingTable indexRoutingTable = updatedState.routingTable().index(index); if (indexRoutingTable != null) { counter += indexRoutingTable.numberOfNodesShardsAreAllocatedOn(updatedState.nodes().masterNodeId()); } } if (counter == 0) { notifyOnPostProcess.set(true); return updatedState; } mappingCreatedAction.add(new CountDownListener(counter, listener), request.timeout); return updatedState; } finally { for (String index : indicesToClose) { indicesService.removeIndex(index, "created for mapping processing"); } } } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { if (notifyOnPostProcess.get()) { listener.onResponse(new Response(true)); } } }); }
diff --git a/src/mapred/org/apache/hadoop/mapreduce/security/TokenCache.java b/src/mapred/org/apache/hadoop/mapreduce/security/TokenCache.java index 376e1659a..95270f9df 100644 --- a/src/mapred/org/apache/hadoop/mapreduce/security/TokenCache.java +++ b/src/mapred/org/apache/hadoop/mapreduce/security/TokenCache.java @@ -1,225 +1,227 @@ /** * 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.hadoop.mapreduce.security; import java.io.IOException; import java.net.URI; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.HftpFileSystem; import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier; import org.apache.hadoop.hdfs.server.namenode.NameNode; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.JobTracker; import org.apache.hadoop.mapreduce.security.token.JobTokenIdentifier; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.security.KerberosName; import org.apache.hadoop.security.SecurityUtil; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.TokenIdentifier; /** * This class provides user facing APIs for transferring secrets from * the job client to the tasks. * The secrets can be stored just before submission of jobs and read during * the task execution. */ //@InterfaceStability.Evolving public class TokenCache { private static final Log LOG = LogFactory.getLog(TokenCache.class); /** * auxiliary method to get user's secret keys.. * @param alias * @return secret key from the storage */ public static byte[] getSecretKey(Credentials credentials, Text alias) { if(credentials == null) return null; return credentials.getSecretKey(alias); } /** * Convenience method to obtain delegation tokens from namenodes * corresponding to the paths passed. * @param ps array of paths * @param conf configuration * @throws IOException */ public static void obtainTokensForNamenodes(Credentials credentials, Path [] ps, Configuration conf) throws IOException { if (!UserGroupInformation.isSecurityEnabled()) { return; } obtainTokensForNamenodesInternal(credentials, ps, conf); } static void obtainTokensForNamenodesInternal(Credentials credentials, Path [] ps, Configuration conf) throws IOException { // get jobtracker principal id (for the renewer) KerberosName jtKrbName = new KerberosName(conf.get(JobTracker.JT_USER_NAME, "")); Text delegTokenRenewer = new Text(jtKrbName.getShortName()); boolean notReadFile = true; for(Path p: ps) { //TODO: Connecting to the namenode is not required in the case, //where we already have the credentials in the file FileSystem fs = FileSystem.get(p.toUri(), conf); if(fs instanceof DistributedFileSystem) { DistributedFileSystem dfs = (DistributedFileSystem)fs; URI uri = fs.getUri(); String fs_addr = SecurityUtil.buildDTServiceName(uri, NameNode.DEFAULT_PORT); // see if we already have the token Token<DelegationTokenIdentifier> token = TokenCache.getDelegationToken(credentials, fs_addr); if(token != null) { LOG.debug("DT for " + token.getService() + " is already present"); continue; } if (notReadFile) { //read the file only once String binaryTokenFilename = conf.get("mapreduce.job.credentials.binary"); if (binaryTokenFilename != null) { credentials.readTokenStorageFile(new Path("file:///" + binaryTokenFilename), conf); } notReadFile = false; token = TokenCache.getDelegationToken(credentials, fs_addr); if(token != null) { LOG.debug("DT for " + token.getService() + " is already present"); continue; } } // get the token token = dfs.getDelegationToken(delegTokenRenewer); if(token==null) { LOG.warn("Token from " + fs_addr + " is null"); continue; } token.setService(new Text(fs_addr)); credentials.addToken(new Text(fs_addr), token); LOG.info("Got dt for " + p + ";uri="+ fs_addr + ";t.service="+token.getService()); } else if (fs instanceof HftpFileSystem) { String fs_addr = SecurityUtil.buildDTServiceName(fs.getUri(), NameNode.DEFAULT_PORT); Token<DelegationTokenIdentifier> token = TokenCache.getDelegationToken(credentials, fs_addr); if(token != null) { LOG.debug("DT for " + token.getService() + " is already present"); continue; } //the initialize method of hftp, called via FileSystem.get() done //earlier gets a delegation token Token<? extends TokenIdentifier> t = ((HftpFileSystem) fs).getDelegationToken(); - credentials.addToken(new Text(fs_addr), t); + if (t != null) { + credentials.addToken(new Text(fs_addr), t); - // in this case port in fs_addr is port for hftp request, but - // token's port is for RPC - // to find the correct DT we need to know the mapping between Hftp port - // and RPC one. hence this new setting in the conf. - URI uri = ((HftpFileSystem) fs).getUri(); - String key = HftpFileSystem.HFTP_SERVICE_NAME_KEY+ - SecurityUtil.buildDTServiceName(uri, NameNode.DEFAULT_PORT); - conf.set(key, t.getService().toString()); - LOG.info("GOT dt for " + p + " and stored in conf as " + key + "=" - + t.getService()); + // in this case port in fs_addr is port for hftp request, but + // token's port is for RPC + // to find the correct DT we need to know the mapping between Hftp port + // and RPC one. hence this new setting in the conf. + URI uri = ((HftpFileSystem) fs).getUri(); + String key = HftpFileSystem.HFTP_SERVICE_NAME_KEY+ + SecurityUtil.buildDTServiceName(uri, NameNode.DEFAULT_PORT); + conf.set(key, t.getService().toString()); + LOG.info("GOT dt for " + p + " and stored in conf as " + key + "=" + + t.getService()); + } } } } /** * file name used on HDFS for generated job token */ //@InterfaceAudience.Private public static final String JOB_TOKEN_HDFS_FILE = "jobToken"; /** * conf setting for job tokens cache file name */ //@InterfaceAudience.Private public static final String JOB_TOKENS_FILENAME = "mapreduce.job.jobTokenFile"; private static final Text JOB_TOKEN = new Text("ShuffleAndJobToken"); /** * * @param namenode * @return delegation token */ @SuppressWarnings("unchecked") //@InterfaceAudience.Private public static Token<DelegationTokenIdentifier> getDelegationToken(Credentials credentials, String namenode) { return (Token<DelegationTokenIdentifier>) credentials.getToken(new Text(namenode)); } /** * load job token from a file * @param conf * @throws IOException */ //@InterfaceAudience.Private public static Credentials loadTokens(String jobTokenFile, JobConf conf) throws IOException { Path localJobTokenFile = new Path ("file:///" + jobTokenFile); Credentials ts = new Credentials(); ts.readTokenStorageFile(localJobTokenFile, conf); if(LOG.isDebugEnabled()) { LOG.debug("Task: Loaded jobTokenFile from: "+localJobTokenFile.toUri().getPath() +"; num of sec keys = " + ts.numberOfSecretKeys() + " Number of tokens " + ts.numberOfTokens()); } return ts; } /** * store job token * @param t */ //@InterfaceAudience.Private public static void setJobToken(Token<? extends TokenIdentifier> t, Credentials credentials) { credentials.addToken(JOB_TOKEN, t); } /** * * @return job token */ //@InterfaceAudience.Private @SuppressWarnings("unchecked") public static Token<JobTokenIdentifier> getJobToken(Credentials credentials) { return (Token<JobTokenIdentifier>) credentials.getToken(JOB_TOKEN); } }
false
true
static void obtainTokensForNamenodesInternal(Credentials credentials, Path [] ps, Configuration conf) throws IOException { // get jobtracker principal id (for the renewer) KerberosName jtKrbName = new KerberosName(conf.get(JobTracker.JT_USER_NAME, "")); Text delegTokenRenewer = new Text(jtKrbName.getShortName()); boolean notReadFile = true; for(Path p: ps) { //TODO: Connecting to the namenode is not required in the case, //where we already have the credentials in the file FileSystem fs = FileSystem.get(p.toUri(), conf); if(fs instanceof DistributedFileSystem) { DistributedFileSystem dfs = (DistributedFileSystem)fs; URI uri = fs.getUri(); String fs_addr = SecurityUtil.buildDTServiceName(uri, NameNode.DEFAULT_PORT); // see if we already have the token Token<DelegationTokenIdentifier> token = TokenCache.getDelegationToken(credentials, fs_addr); if(token != null) { LOG.debug("DT for " + token.getService() + " is already present"); continue; } if (notReadFile) { //read the file only once String binaryTokenFilename = conf.get("mapreduce.job.credentials.binary"); if (binaryTokenFilename != null) { credentials.readTokenStorageFile(new Path("file:///" + binaryTokenFilename), conf); } notReadFile = false; token = TokenCache.getDelegationToken(credentials, fs_addr); if(token != null) { LOG.debug("DT for " + token.getService() + " is already present"); continue; } } // get the token token = dfs.getDelegationToken(delegTokenRenewer); if(token==null) { LOG.warn("Token from " + fs_addr + " is null"); continue; } token.setService(new Text(fs_addr)); credentials.addToken(new Text(fs_addr), token); LOG.info("Got dt for " + p + ";uri="+ fs_addr + ";t.service="+token.getService()); } else if (fs instanceof HftpFileSystem) { String fs_addr = SecurityUtil.buildDTServiceName(fs.getUri(), NameNode.DEFAULT_PORT); Token<DelegationTokenIdentifier> token = TokenCache.getDelegationToken(credentials, fs_addr); if(token != null) { LOG.debug("DT for " + token.getService() + " is already present"); continue; } //the initialize method of hftp, called via FileSystem.get() done //earlier gets a delegation token Token<? extends TokenIdentifier> t = ((HftpFileSystem) fs).getDelegationToken(); credentials.addToken(new Text(fs_addr), t); // in this case port in fs_addr is port for hftp request, but // token's port is for RPC // to find the correct DT we need to know the mapping between Hftp port // and RPC one. hence this new setting in the conf. URI uri = ((HftpFileSystem) fs).getUri(); String key = HftpFileSystem.HFTP_SERVICE_NAME_KEY+ SecurityUtil.buildDTServiceName(uri, NameNode.DEFAULT_PORT); conf.set(key, t.getService().toString()); LOG.info("GOT dt for " + p + " and stored in conf as " + key + "=" + t.getService()); } } }
static void obtainTokensForNamenodesInternal(Credentials credentials, Path [] ps, Configuration conf) throws IOException { // get jobtracker principal id (for the renewer) KerberosName jtKrbName = new KerberosName(conf.get(JobTracker.JT_USER_NAME, "")); Text delegTokenRenewer = new Text(jtKrbName.getShortName()); boolean notReadFile = true; for(Path p: ps) { //TODO: Connecting to the namenode is not required in the case, //where we already have the credentials in the file FileSystem fs = FileSystem.get(p.toUri(), conf); if(fs instanceof DistributedFileSystem) { DistributedFileSystem dfs = (DistributedFileSystem)fs; URI uri = fs.getUri(); String fs_addr = SecurityUtil.buildDTServiceName(uri, NameNode.DEFAULT_PORT); // see if we already have the token Token<DelegationTokenIdentifier> token = TokenCache.getDelegationToken(credentials, fs_addr); if(token != null) { LOG.debug("DT for " + token.getService() + " is already present"); continue; } if (notReadFile) { //read the file only once String binaryTokenFilename = conf.get("mapreduce.job.credentials.binary"); if (binaryTokenFilename != null) { credentials.readTokenStorageFile(new Path("file:///" + binaryTokenFilename), conf); } notReadFile = false; token = TokenCache.getDelegationToken(credentials, fs_addr); if(token != null) { LOG.debug("DT for " + token.getService() + " is already present"); continue; } } // get the token token = dfs.getDelegationToken(delegTokenRenewer); if(token==null) { LOG.warn("Token from " + fs_addr + " is null"); continue; } token.setService(new Text(fs_addr)); credentials.addToken(new Text(fs_addr), token); LOG.info("Got dt for " + p + ";uri="+ fs_addr + ";t.service="+token.getService()); } else if (fs instanceof HftpFileSystem) { String fs_addr = SecurityUtil.buildDTServiceName(fs.getUri(), NameNode.DEFAULT_PORT); Token<DelegationTokenIdentifier> token = TokenCache.getDelegationToken(credentials, fs_addr); if(token != null) { LOG.debug("DT for " + token.getService() + " is already present"); continue; } //the initialize method of hftp, called via FileSystem.get() done //earlier gets a delegation token Token<? extends TokenIdentifier> t = ((HftpFileSystem) fs).getDelegationToken(); if (t != null) { credentials.addToken(new Text(fs_addr), t); // in this case port in fs_addr is port for hftp request, but // token's port is for RPC // to find the correct DT we need to know the mapping between Hftp port // and RPC one. hence this new setting in the conf. URI uri = ((HftpFileSystem) fs).getUri(); String key = HftpFileSystem.HFTP_SERVICE_NAME_KEY+ SecurityUtil.buildDTServiceName(uri, NameNode.DEFAULT_PORT); conf.set(key, t.getService().toString()); LOG.info("GOT dt for " + p + " and stored in conf as " + key + "=" + t.getService()); } } } }
diff --git a/installer/ant-lib-src/org/netbeans/installer/javafx/FirstFNameTask.java b/installer/ant-lib-src/org/netbeans/installer/javafx/FirstFNameTask.java index 92afd599..896cb102 100644 --- a/installer/ant-lib-src/org/netbeans/installer/javafx/FirstFNameTask.java +++ b/installer/ant-lib-src/org/netbeans/installer/javafx/FirstFNameTask.java @@ -1,29 +1,34 @@ package org.netbeans.installer.javafx; import java.io.File; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; /** * * @author Adam */ public class FirstFNameTask extends Task { String property; File dir; public void setProperty(String property) { this.property = property; } public void setDir(File dir) { this.dir = dir; } @Override public void execute() throws BuildException { String[] f = dir.list(); - if (f != null && f.length > 0) getProject().setNewProperty(property, f[0]); + if (f != null && f.length > 0) + for (int i=0; i<f.length; i++) + if (!f[i].startsWith(".")) { + getProject().setNewProperty(property, f[i]); + return; + } } }
true
true
public void execute() throws BuildException { String[] f = dir.list(); if (f != null && f.length > 0) getProject().setNewProperty(property, f[0]); }
public void execute() throws BuildException { String[] f = dir.list(); if (f != null && f.length > 0) for (int i=0; i<f.length; i++) if (!f[i].startsWith(".")) { getProject().setNewProperty(property, f[i]); return; } }
diff --git a/src/dev/ukanth/ufirewall/Api.java b/src/dev/ukanth/ufirewall/Api.java index 378a268b..cc93053c 100644 --- a/src/dev/ukanth/ufirewall/Api.java +++ b/src/dev/ukanth/ufirewall/Api.java @@ -1,2024 +1,2023 @@ /** * * All iptables "communication" is handled by this class. * * Copyright (C) 2009-2011 Rodrigo Zechin Rosauro * Copyright (C) 2011-2012 Umakanthan Chandran * * 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/>. * * @author Rodrigo Zechin Rosauro, Umakanthan Chandran * @version 1.2 */ package dev.ukanth.ufirewall; import java.io.BufferedReader; 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.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.StringTokenizer; import java.util.concurrent.ExecutionException; import java.util.concurrent.RejectedExecutionException; import android.Manifest; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Environment; import android.preference.PreferenceManager; import android.provider.Settings; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.util.SparseArray; import android.widget.Toast; import dev.ukanth.ufirewall.MainActivity.GetAppList; import eu.chainfire.libsuperuser.Shell.SU; /** * Contains shared programming interfaces. * All iptables "communication" is handled by this class. */ public final class Api { /** application logcat tag */ public static final String TAG = "AFWall"; /** special application UID used to indicate "any application" */ public static final int SPECIAL_UID_ANY = -10; /** special application UID used to indicate the Linux Kernel */ public static final int SPECIAL_UID_KERNEL = -11; /** special application UID used for dnsmasq DHCP/DNS */ public static final int SPECIAL_UID_TETHER = -12; /** root script filename */ //private static final String SCRIPT_FILE = "afwall.sh"; // Preferences public static String PREFS_NAME = "AFWallPrefs"; public static final String PREF_FIREWALL_STATUS = "AFWallStaus"; public static final String DEFAULT_PREFS_NAME = "AFWallPrefs"; //for import/export rules public static final String PREF_3G_PKG = "AllowedPKG3G"; public static final String PREF_WIFI_PKG = "AllowedPKGWifi"; public static final String PREF_ROAMING_PKG = "AllowedPKGRoaming"; public static final String PREF_VPN_PKG = "AllowedPKGVPN"; public static final String PREF_LAN_PKG = "AllowedPKGLAN"; //revertback to old approach for performance public static final String PREF_3G_PKG_UIDS = "AllowedPKG3G_UIDS"; public static final String PREF_WIFI_PKG_UIDS = "AllowedPKGWifi_UIDS"; public static final String PREF_ROAMING_PKG_UIDS = "AllowedPKGRoaming_UIDS"; public static final String PREF_VPN_PKG_UIDS = "AllowedPKGVPN_UIDS"; public static final String PREF_LAN_PKG_UIDS = "AllowedPKGLAN_UIDS"; public static final String PREF_PASSWORD = "Password"; public static final String PREF_CUSTOMSCRIPT = "CustomScript"; public static final String PREF_CUSTOMSCRIPT2 = "CustomScript2"; // Executed on shutdown public static final String PREF_MODE = "BlockMode"; public static final String PREF_ENABLED = "Enabled"; // Modes public static final String MODE_WHITELIST = "whitelist"; public static final String MODE_BLACKLIST = "blacklist"; // Messages public static final String STATUS_CHANGED_MSG = "dev.ukanth.ufirewall.intent.action.STATUS_CHANGED"; public static final String TOGGLE_REQUEST_MSG = "dev.ukanth.ufirewall.intent.action.TOGGLE_REQUEST"; public static final String CUSTOM_SCRIPT_MSG = "dev.ukanth.ufirewall.intent.action.CUSTOM_SCRIPT"; // Message extras (parameters) public static final String STATUS_EXTRA = "dev.ukanth.ufirewall.intent.extra.STATUS"; public static final String SCRIPT_EXTRA = "dev.ukanth.ufirewall.intent.extra.SCRIPT"; public static final String SCRIPT2_EXTRA = "dev.ukanth.ufirewall.intent.extra.SCRIPT2"; private static final String ITFS_WIFI[] = InterfaceTracker.ITFS_WIFI; private static final String ITFS_3G[] = InterfaceTracker.ITFS_3G; private static final String ITFS_VPN[] = InterfaceTracker.ITFS_VPN; //private static final int BUFF_LEN = 0; // Cached applications public static List<PackageInfoData> applications = null; //for custom scripts //private static final String SCRIPT_FILE = "afwall_custom.sh"; static Hashtable<String, LogEntry> logEntriesHash = new Hashtable<String, LogEntry>(); static List<LogEntry> logEntriesList = new ArrayList<LogEntry>(); public static String ipPath = null; public static boolean setv6 = false; private static Map<String,Integer> specialApps = null; //public static boolean isUSBEnable = false; public static String getIpPath() { return ipPath; } /** * Display a simple alert box * @param ctx context * @param msg message */ public static void alert(Context ctx, CharSequence msgText) { if (ctx != null) { Toast.makeText(ctx, msgText, Toast.LENGTH_SHORT).show(); } } public static void alertDialog(final Context ctx, String msgText) { if (ctx != null) { AlertDialog.Builder builder = new AlertDialog.Builder(ctx); builder.setMessage(msgText) .setCancelable(false) .setPositiveButton(ctx.getString(R.string.OK), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } } static String customScriptHeader(Context ctx) { final String dir = ctx.getDir("bin",0).getAbsolutePath(); final String myiptables = dir + "/iptables_armv5"; final String mybusybox = dir + "/busybox_g1"; return "" + "IPTABLES="+ myiptables + "\n" + "BUSYBOX="+mybusybox+"\n" + ""; } static void setIpTablePath(Context ctx,boolean setv6) { final String dir = ctx.getDir("bin", 0).getAbsolutePath(); final String defaultPath = "iptables "; final String defaultIPv6Path = "ip6tables "; final String myiptables = dir + "/iptables_armv5 "; final SharedPreferences appprefs = PreferenceManager .getDefaultSharedPreferences(ctx); final boolean enableIPv6 = appprefs.getBoolean("enableIPv6", false); final String ip_preference = appprefs.getString("ip_path", "2"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { Api.ipPath = defaultPath; } else { if(ip_preference.equals("2")) { Api.ipPath = myiptables; } else { Api.ipPath = defaultPath; } } if (setv6 && enableIPv6) { Api.setv6 = true; Api.ipPath = defaultIPv6Path; } else { Api.setv6 = false; } } static String getBusyBoxPath(Context ctx) { final String dir = ctx.getDir("bin",0).getAbsolutePath(); String busybox = "busybox "; final SharedPreferences appprefs = PreferenceManager.getDefaultSharedPreferences(ctx); final String busybox_preference = appprefs.getString("bb_path", "2"); if(busybox_preference.equals("2")) { busybox = dir + "/busybox_g1 "; } return busybox; } /** * Copies a raw resource file, given its ID to the given location * @param ctx context * @param resid resource id * @param file destination file * @param mode file permissions (E.g.: "755") * @throws IOException on error * @throws InterruptedException when interrupted */ private static void copyRawFile(Context ctx, int resid, File file, String mode) throws IOException, InterruptedException { final String abspath = file.getAbsolutePath(); // Write the iptables binary final FileOutputStream out = new FileOutputStream(file); final InputStream is = ctx.getResources().openRawResource(resid); byte buf[] = new byte[1024]; int len; while ((len = is.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); is.close(); // Change the permissions Runtime.getRuntime().exec("chmod "+mode+" "+abspath).waitFor(); } public static void replaceAll(StringBuilder builder, String from, String to ) { int index = builder.indexOf(from); while (index != -1) { builder.replace(index, index + from.length(), to); index += to.length(); // Move to the end of the replacement index = builder.indexOf(from, index); } } /** * Look up uid for each user by name, and if he exists, append an iptables rule. * @param listCommands current list of iptables commands to execute * @param users list of users to whom the rule applies * @param prefix "iptables" command and the portion of the rule preceding "-m owner --uid-owner X" * @param suffix the remainder of the iptables rule, following "-m owner --uid-owner X" */ private static void addRuleForUsers(List<String> listCommands, String users[], String prefix, String suffix) { for (String user : users) { int uid = android.os.Process.getUidForName(user); if (uid != -1) listCommands.add(prefix + " -m owner --uid-owner " + uid + " " + suffix); } } /** * Purge and re-add all rules (internal implementation). * @param ctx application context (mandatory) * @param uidsWifi list of selected UIDs for WIFI to allow or disallow (depending on the working mode) * @param uids3g list of selected UIDs for 2G/3G to allow or disallow (depending on the working mode) * @param showErrors indicates if errors should be alerted */ private static boolean applyIptablesRulesImpl(final Context ctx, List<Integer> uidsWifi, List<Integer> uids3g, List<Integer> uidsRoam, List<Integer> uidsVPN, List<Integer> uidsLAN, final boolean showErrors) { if (ctx == null) { return false; } assertBinaries(ctx, showErrors); final SharedPreferences appprefs = PreferenceManager.getDefaultSharedPreferences(ctx); final InterfaceDetails cfg = InterfaceTracker.getCurrentCfg(ctx); final boolean enableVPN = appprefs.getBoolean("enableVPN", false); final boolean enableLAN = appprefs.getBoolean("enableLAN", false) && !cfg.isTethered; final boolean enableRoam = appprefs.getBoolean("enableRoam", true); final SharedPreferences prefs = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); final boolean whitelist = prefs.getString(PREF_MODE, MODE_WHITELIST).equals(MODE_WHITELIST); final boolean blacklist = !whitelist; final boolean logenabled = appprefs.getBoolean("enableFirewallLog",true); //final boolean isVPNEnabled = appprefs.getBoolean("enableVPNProfile",false); //String iptargets = getTargets(ctx); StringBuilder customScript = new StringBuilder(ctx.getSharedPreferences(Api.PREFS_NAME, Context.MODE_PRIVATE).getString(Api.PREF_CUSTOMSCRIPT, "")); try { int code; String busybox = getBusyBoxPath(ctx); String grep = busybox + " grep"; final List<String> listCommands = new ArrayList<String>(); listCommands.add(ipPath + " -L afwall >/dev/null 2>/dev/null || " + ipPath + " --new afwall || exit" ); listCommands.add(ipPath + " -L afwall-3g >/dev/null 2>/dev/null ||" + ipPath + "--new afwall-3g || exit" ); listCommands.add(ipPath + " -L afwall-wifi >/dev/null 2>/dev/null || " + ipPath + " --new afwall-wifi || exit" ); listCommands.add(ipPath + " -L afwall-lan >/dev/null 2>/dev/null || " + ipPath + " --new afwall-lan || exit" ); listCommands.add(ipPath + " -L afwall-vpn >/dev/null 2>/dev/null || " + ipPath + " --new afwall-vpn || exit" ); listCommands.add(ipPath + " -L afwall-reject >/dev/null 2>/dev/null || " + ipPath + " --new afwall-reject || exit" ); listCommands.add(ipPath + " -L OUTPUT | " + grep + " -q afwall || " + ipPath + " -A OUTPUT -j afwall || exit"); listCommands.add(ipPath + " -F afwall || exit " ); listCommands.add(ipPath + " -F afwall-3g || exit "); listCommands.add(ipPath + " -F afwall-wifi || exit "); listCommands.add(ipPath + " -F afwall-lan || exit "); listCommands.add(ipPath + " -F afwall-vpn || exit "); listCommands.add(ipPath + " -F afwall-reject || exit 10"); listCommands.add(ipPath + " -A afwall -m owner --uid-owner 0 -p udp --dport 53 -j RETURN || exit"); listCommands.add((ipPath + " -D OUTPUT -j afwall")); listCommands.add((ipPath + " -I OUTPUT 1 -j afwall")); //this will make sure the only afwall will be able to control the OUTPUT chain, regardless of any firewall installed! //listCommands.add((ipPath + " --flush OUTPUT || exit")); // Check if logging is enabled if (logenabled) { listCommands.add((ipPath + " -A afwall-reject -m limit --limit 1000/min -j LOG --log-prefix \"{AFL}\" --log-level 4 --log-uid ")); } listCommands.add((ipPath + " -A afwall-reject -j REJECT || exit")); //now reenable everything after restart listCommands.add((ipPath + " -P INPUT ACCEPT")); listCommands.add((ipPath + " -P OUTPUT ACCEPT")); listCommands.add((ipPath + " -P FORWARD ACCEPT")); if (customScript.length() > 0) { replaceAll(customScript, "$IPTABLES", " " +ipPath ); listCommands.add(customScript.toString()); } for (final String itf : ITFS_3G) { listCommands.add((ipPath + " -A afwall -o ".concat(itf).concat(" -j afwall-3g || exit"))); } for (final String itf : ITFS_WIFI) { if(enableLAN) { if(setv6 && !cfg.lanMaskV6.equals("")) { listCommands.add(ipPath + " -A afwall -d " + cfg.lanMaskV6 + " -o " + itf + " -j afwall-lan || exit"); listCommands.add(ipPath + " -A afwall '!' -d " + cfg.lanMaskV6 + " -o " + itf+ " -j afwall-wifi || exit"); } if(!setv6 && !cfg.lanMaskV4.equals("")) { listCommands.add(ipPath + " -A afwall -d " + cfg.lanMaskV4 + " -o " + itf + " -j afwall-lan || exit"); listCommands.add(ipPath + " -A afwall '!' -d "+ cfg.lanMaskV4 + " -o " + itf + " -j afwall-wifi || exit"); } } else { listCommands.add((ipPath + " -A afwall -o ".concat(itf).concat(" -j afwall-wifi || exit"))); } } if(enableVPN) { for (final String itf : ITFS_VPN) { listCommands.add((ipPath + " -A afwall -o ".concat(itf).concat(" -j afwall-vpn || exit"))); } } final String targetRule = (whitelist ? "RETURN" : "afwall-reject"); final boolean any_3g = uids3g.indexOf(SPECIAL_UID_ANY) >= 0; final boolean any_wifi = uidsWifi.indexOf(SPECIAL_UID_ANY) >= 0; final boolean any_lan = uidsLAN.indexOf(SPECIAL_UID_ANY) >= 0; final boolean any_vpn = uidsVPN.indexOf(SPECIAL_UID_ANY) >= 0; if (whitelist && !any_wifi) { addRuleForUsers(listCommands, new String[]{"dhcp","wifi"}, ipPath + " -A afwall-wifi", "-j RETURN || exit"); } //now 3g rules! if (any_3g) { if (blacklist) { /* block any application on this interface */ listCommands.add((ipPath + " -A afwall-3g -j "+(targetRule)+(" || exit"))); } } else { /* release/block individual applications on this interface */ if(cfg.isRoaming && enableRoam) { for (final Integer uid : uidsRoam) { if (uid !=null && uid >= 0) listCommands.add((ipPath + " -A afwall-3g -m owner --uid-owner "+(uid)+(" -j ")+(targetRule)+(" || exit"))); } } else { for (final Integer uid : uids3g) { if (uid !=null && uid >= 0) listCommands.add((ipPath + " -A afwall-3g -m owner --uid-owner "+(uid)+(" -j ")+(targetRule)+(" || exit"))); } } } //now wifi rules! - // if the wifi interface is down, reject all outbound packets without logging them - if (!cfg.allowWifi) { - listCommands.add(ipPath + " -A afwall-wifi -j REJECT || exit"); - } else if (any_wifi) { + //--if the wifi interface is down, reject all outbound packets without logging them-- + //revert back to old approach + if (any_wifi) { if (blacklist) { /* block any application on this interface */ listCommands.add((ipPath + " -A afwall-wifi -j "+(targetRule)+(" || exit"))); } } else { /* release/block individual applications on this interface */ for (final Integer uid : uidsWifi) { if (uid !=null && uid >= 0) listCommands.add((ipPath + " -A afwall-wifi -m owner --uid-owner "+(uid)+(" -j ")+(targetRule)+(" || exit"))); } } //now LAN rules! if (enableLAN) { if (!cfg.allowWifi) { listCommands.add(ipPath + " -A afwall-lan -j REJECT || exit"); } else if (any_lan) { if (blacklist) { /* block any application on this interface */ listCommands.add((ipPath + " -A afwall-lan -j "+(targetRule)+(" || exit"))); } } else { /* release/block individual applications on this interface */ for (final Integer uid : uidsLAN) { if (uid != null && uid >= 0) listCommands.add((ipPath + " -A afwall-lan -m owner --uid-owner " + uid + " -j " + targetRule + " || exit")); } // NOTE: we still need to open a hole for DNS lookups // This falls through to the wifi rules if the app is not whitelisted for LAN access if (whitelist) { listCommands.add(ipPath + " -A afwall-lan -p udp --dport 53 -j RETURN || exit"); } } } //now vpn rules! if(enableVPN) { if (any_vpn) { if (blacklist) { /* block any application on this interface */ listCommands.add((ipPath + " -A afwall-vpn -j "+(targetRule)+(" || exit"))); } } else { /* release/block individual applications on this interface */ for (final Integer uid : uidsVPN) { if (uid !=null && uid >= 0) listCommands.add((ipPath + " -A afwall-vpn -m owner --uid-owner "+(uid)+(" -j ")+(targetRule)+(" || exit"))); } } } // note that this can only blacklist DNS/DHCP services, not all tethered traffic if (cfg.isTethered && ((blacklist && (any_wifi || any_3g)) || (uids3g.indexOf(SPECIAL_UID_TETHER) >= 0) || (uidsWifi.indexOf(SPECIAL_UID_TETHER) >= 0))) { String users[] = { "root", "nobody" }; String action = " -j " + targetRule + " || exit"; // DHCP replies to client addRuleForUsers(listCommands, users, ipPath + " -A afwall-wifi","-p udp --sport=67 --dport=68" + action); // DNS replies to client addRuleForUsers(listCommands, users, ipPath + " -A afwall-wifi","-p udp --sport=53" + action); addRuleForUsers(listCommands, users, ipPath + " -A afwall-wifi","-p tcp --sport=53" + action); // DNS requests to upstream servers addRuleForUsers(listCommands, users, ipPath + " -A afwall-3g","-p udp --dport=53" + action); addRuleForUsers(listCommands, users, ipPath + " -A afwall-3g","-p tcp --dport=53" + action); } if (whitelist) { if (!any_3g) { if (uids3g.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-3g -m owner --uid-owner 0:999999999 -j afwall-reject || exit")); } else { listCommands.add((ipPath + " -A afwall-3g -j afwall-reject || exit")); } } if (!any_wifi) { if (uidsWifi.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-wifi -m owner --uid-owner 0:999999999 -j afwall-reject || exit")); } else { listCommands.add((ipPath + " -A afwall-wifi -j afwall-reject || exit")); } } if (enableVPN && !any_vpn) { if (uidsVPN.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-vpn -m owner --uid-owner 0:999999999 -j afwall-reject || exit")); } else { listCommands.add((ipPath + " -A afwall-vpn -j afwall-reject || exit")); } } if (enableLAN && !any_lan) { if (uidsLAN.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-lan -m owner --uid-owner 0:999999999 -j afwall-reject || exit")); } else { listCommands.add((ipPath + " -A afwall-lan -j afwall-reject || exit")); } } } else { if (uids3g.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-3g -m owner --uid-owner 0:999999999 -j RETURN || exit")); listCommands.add((ipPath + " -A afwall-3g -j afwall-reject || exit")); } if (uidsWifi.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-wifi -m owner --uid-owner 0:999999999 -j RETURN || exit")); listCommands.add((ipPath + " -A afwall-wifi -j afwall-reject || exit")); } if (enableVPN && uidsVPN.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-vpn -m owner --uid-owner 0:999999999 -j RETURN || exit")); listCommands.add((ipPath + " -A afwall-vpn -j afwall-reject || exit")); } if (enableLAN && uidsLAN.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-lan -m owner --uid-owner 0:999999999 -j RETURN || exit")); listCommands.add((ipPath + " -A afwall-lan -j afwall-reject || exit")); } } //active defence final StringBuilder res = new StringBuilder(); code = runScriptAsRoot(ctx, listCommands, res); if (showErrors && code != 0) { String msg = res.toString(); // Remove unnecessary help message from output if (msg.indexOf("\nTry `iptables -h' or 'iptables --help' for more information.") != -1) { msg = msg.replace("\nTry `iptables -h' or 'iptables --help' for more information.", ""); } alert(ctx, ctx.getString(R.string.error_apply) + code + "\n\n" + msg.trim() ); } else { return true; } } catch (Exception e) { Log.e(TAG, "Exception while applying rules: " + e.getMessage()); if (showErrors) alert(ctx, ctx.getString(R.string.error_refresh) + e); } return false; } private static List<Integer> getUidListFromPref(Context ctx,final String pks) { initSpecial(); final PackageManager pm = ctx.getPackageManager(); final List<Integer> uids = new ArrayList<Integer>(); final StringTokenizer tok = new StringTokenizer(pks, "|"); while (tok.hasMoreTokens()) { final String pkg = tok.nextToken(); if (pkg != null && pkg.length() > 0) { try { if (pkg.startsWith("dev.afwall.special")) { uids.add(specialApps.get(pkg)); } else { uids.add(pm.getApplicationInfo(pkg, 0).uid); } } catch (Exception ex) { } } } Collections.sort(uids); return uids; } /** * Purge and re-add all saved rules (not in-memory ones). * This is much faster than just calling "applyIptablesRules", since it don't need to read installed applications. * @param ctx application context (mandatory) * @param showErrors indicates if errors should be alerted */ public static boolean applySavedIptablesRules(Context ctx, boolean showErrors) { if (ctx == null) { return false; } initSpecial(); final SharedPreferences prefs = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); final String savedPkg_wifi_uid = prefs.getString(PREF_WIFI_PKG_UIDS, ""); final String savedPkg_3g_uid = prefs.getString(PREF_3G_PKG_UIDS, ""); final String savedPkg_roam_uid = prefs.getString(PREF_ROAMING_PKG_UIDS, ""); final String savedPkg_vpn_uid = prefs.getString(PREF_VPN_PKG_UIDS, ""); final String savedPkg_lan_uid = prefs.getString(PREF_LAN_PKG_UIDS, ""); final SharedPreferences appprefs = PreferenceManager.getDefaultSharedPreferences(ctx); final boolean enableIPv6 = appprefs.getBoolean("enableIPv6", false); boolean returnValue = false; setIpTablePath(ctx,false); returnValue = applyIptablesRulesImpl(ctx, getListFromPref(savedPkg_wifi_uid), getListFromPref(savedPkg_3g_uid), getListFromPref(savedPkg_roam_uid), getListFromPref(savedPkg_vpn_uid), getListFromPref(savedPkg_lan_uid), showErrors); if (enableIPv6) { setIpTablePath(ctx,true); returnValue = applyIptablesRulesImpl(ctx, getListFromPref(savedPkg_wifi_uid), getListFromPref(savedPkg_3g_uid), getListFromPref(savedPkg_roam_uid), getListFromPref(savedPkg_vpn_uid), getListFromPref(savedPkg_lan_uid), showErrors); } return returnValue; } /** * Purge and re-add all rules. * @param ctx application context (mandatory) * @param showErrors indicates if errors should be alerted */ public static boolean applyIptablesRules(Context ctx, boolean showErrors) { if (ctx == null) { return false; } saveRules(ctx); return applySavedIptablesRules(ctx, showErrors); } /** * Save current rules using the preferences storage. * @param ctx application context (mandatory) */ public static void saveRules(Context ctx) { final SharedPreferences defaultPrefs = PreferenceManager.getDefaultSharedPreferences(ctx); final boolean enableVPN = defaultPrefs.getBoolean("enableVPN", false); final boolean enableLAN = defaultPrefs.getBoolean("enableLAN", false); final boolean enableRoam = defaultPrefs.getBoolean("enableRoam", true); final SharedPreferences prefs = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); final List<PackageInfoData> apps = getApps(ctx,null); // Builds a pipe-separated list of names final StringBuilder newpkg_wifi = new StringBuilder(); final StringBuilder newpkg_3g = new StringBuilder(); final StringBuilder newpkg_roam = new StringBuilder(); final StringBuilder newpkg_vpn = new StringBuilder(); final StringBuilder newpkg_lan = new StringBuilder(); for (int i=0; i<apps.size(); i++) { if (apps.get(i).selected_wifi) { if (newpkg_wifi.length() != 0) newpkg_wifi.append('|'); newpkg_wifi.append(apps.get(i).uid); } if (apps.get(i).selected_3g) { if (newpkg_3g.length() != 0) newpkg_3g.append('|'); newpkg_3g.append(apps.get(i).uid); } if (enableRoam && apps.get(i).selected_roam) { if (newpkg_roam.length() != 0) newpkg_roam.append('|'); newpkg_roam.append(apps.get(i).uid); } if (enableVPN && apps.get(i).selected_vpn) { if (newpkg_vpn.length() != 0) newpkg_vpn.append('|'); newpkg_vpn.append(apps.get(i).uid); } if (enableLAN && apps.get(i).selected_lan) { if (newpkg_lan.length() != 0) newpkg_lan.append('|'); newpkg_lan.append(apps.get(i).uid); } } // save the new list of UIDs final Editor edit = prefs.edit(); edit.putString(PREF_WIFI_PKG_UIDS, newpkg_wifi.toString()); edit.putString(PREF_3G_PKG_UIDS, newpkg_3g.toString()); edit.putString(PREF_ROAMING_PKG_UIDS, newpkg_roam.toString()); edit.putString(PREF_VPN_PKG_UIDS, newpkg_vpn.toString()); edit.putString(PREF_LAN_PKG_UIDS, newpkg_lan.toString()); edit.commit(); } /** * Purge all iptables rules. * @param ctx mandatory context * @param showErrors indicates if errors should be alerted * @return true if the rules were purged */ public static boolean purgeVPNRules(Context ctx, boolean showErrors) { final StringBuilder res = new StringBuilder(); try { assertBinaries(ctx, showErrors); // Custom "shutdown" script setIpTablePath(ctx,false); List<String> listCommands = new ArrayList<String>(); listCommands.add((ipPath + " -F afwall-vpn")); int code = runScriptAsRoot(ctx, listCommands, res); if (code == -1) { if(showErrors) alert(ctx, ctx.getString(R.string.error_purge) + code + "\n" + res); return false; } final SharedPreferences appprefs = PreferenceManager .getDefaultSharedPreferences(ctx); final boolean enableIPv6 = appprefs.getBoolean("enableIPv6", false); if (enableIPv6) { setIpTablePath(ctx, true); listCommands.clear(); listCommands.add((ipPath + " -F afwall-vpn")); code = runScriptAsRoot(ctx, listCommands, res); if (code == -1) { if (showErrors) alert(ctx, ctx.getString(R.string.error_purge) + code + "\n" + res); return false; } } return true; } catch (Exception e) { return false; } } /** * Purge all iptables rules. * @param ctx mandatory context * @param showErrors indicates if errors should be alerted * @return true if the rules were purged */ public static boolean purgeIptables(Context ctx, boolean showErrors) { try { assertBinaries(ctx, showErrors); // Custom "shutdown" script setIpTablePath(ctx,false); purgeRules(ctx,showErrors); final SharedPreferences appprefs = PreferenceManager.getDefaultSharedPreferences(ctx); final boolean enableIPv6 = appprefs.getBoolean("enableIPv6", false); if(enableIPv6) { setIpTablePath(ctx,true); purgeRules(ctx,showErrors); } return true; } catch (Exception e) { return false; } } private static boolean purgeRules(Context ctx,boolean showErrors) throws IOException { boolean returnVal = true; final StringBuilder res = new StringBuilder(); List<String> listCommands = new ArrayList<String>(); listCommands.add((ipPath + " -F afwall")); listCommands.add((ipPath + " -F afwall-reject")); listCommands.add((ipPath + " -F afwall-3g")); listCommands.add((ipPath + " -F afwall-wifi")); listCommands.add((ipPath + " -D OUTPUT -j afwall || exit")); final SharedPreferences defaultPrefs = PreferenceManager.getDefaultSharedPreferences(ctx); StringBuilder customScript = new StringBuilder(ctx.getSharedPreferences(Api.PREFS_NAME, Context.MODE_PRIVATE).getString(Api.PREF_CUSTOMSCRIPT2, "")); final boolean enableVPN = defaultPrefs.getBoolean("enableVPN", false); final boolean enableLAN = defaultPrefs.getBoolean("enableLAN", false); if(enableVPN) { listCommands.add((ipPath + " -F afwall-vpn")); } if(enableLAN) { listCommands.add((ipPath + " -F afwall-lan")); } if (customScript.length() > 0) { replaceAll(customScript, "$IPTABLES", " " +ipPath ); listCommands.add(customScript.toString()); } int code = runScriptAsRoot(ctx, listCommands, res); if (code == -1) { if(showErrors) alert(ctx, ctx.getString(R.string.error_purge) + code + "\n" + res); returnVal = false; } return returnVal; } /** * Display iptables rules output * @param ctx application context */ public static String showIptablesRules(Context ctx) { try { final StringBuilder res = new StringBuilder(); setIpTablePath(ctx,false); List<String> listCommands = new ArrayList<String>(); listCommands.add((ipPath + " -L -n")); runScriptAsRoot(ctx, listCommands, res); return res.toString(); } catch (Exception e) { alert(ctx, "error: " + e); } return ""; } /** * Display iptables rules output * @param ctx application context */ public static String showIp6tablesRules(Context ctx) { try { final StringBuilder res = new StringBuilder(); setIpTablePath(ctx,true); List<String> listCommands = new ArrayList<String>(); listCommands.add((ipPath + " -L -n")); runScriptAsRoot(ctx, listCommands, res); return res.toString(); } catch (Exception e) { alert(ctx, "error: " + e); } return ""; } /** * Display logs * @param ctx application context * @return true if the clogs were cleared */ public static boolean clearLog(Context ctx) { try { final StringBuilder res = new StringBuilder(); List<String> listCommands = new ArrayList<String>(); listCommands.add((getBusyBoxPath(ctx) + " dmesg -c >/dev/null || exit")); int code = runScriptAsRoot(ctx, listCommands, res); if (code != 0) { alert(ctx, res); return false; } return true; } catch (Exception e) { alert(ctx, "error: " + e); } return false; } public static class LogEntry { String uid; String src; String dst; int len; int spt; int dpt; int packets; int bytes; @Override public String toString() { return dst + ":" + src+ ":" + len + ":"+ packets; } } /** * Display logs * @param ctx application context */ public static String showLog(Context ctx) { try { StringBuilder res = new StringBuilder(); StringBuilder output = new StringBuilder(); String busybox = getBusyBoxPath(ctx); String grep = busybox + " grep"; List<String> listCommands = new ArrayList<String>(); listCommands.add(getBusyBoxPath(ctx) + "dmesg | " + grep +" {AFL}"); int code = runScriptAsRoot(ctx, listCommands, res); //int code = runScriptAsRoot(ctx, "cat /proc/kmsg", res); if (code != 0) { if (res.length() == 0) { output.append(ctx.getString(R.string.no_log)); } return output.toString(); } final BufferedReader r = new BufferedReader(new StringReader(res.toString())); final Integer unknownUID = -99; res = new StringBuilder(); String line; int start, end; Integer appid; final SparseArray<LogInfo> map = new SparseArray<LogInfo>(); LogInfo loginfo = null; while ((line = r.readLine()) != null) { if (line.indexOf("{AFL}") == -1) continue; appid = unknownUID; if (((start=line.indexOf("UID=")) != -1) && ((end=line.indexOf(" ", start)) != -1)) { appid = Integer.parseInt(line.substring(start+4, end)); } loginfo = map.get(appid); if (loginfo == null) { loginfo = new LogInfo(); map.put(appid, loginfo); } loginfo.totalBlocked += 1; if (((start=line.indexOf("DST=")) != -1) && ((end=line.indexOf(" ", start)) != -1)) { String dst = line.substring(start+4, end); if (loginfo.dstBlocked.containsKey(dst)) { loginfo.dstBlocked.put(dst, loginfo.dstBlocked.get(dst) + 1); } else { loginfo.dstBlocked.put(dst, 1); } } } final List<PackageInfoData> apps = getApps(ctx,null); Integer id; String appName = ""; int appId = -1; int totalBlocked; for(int i = 0; i < map.size(); i++) { StringBuilder address = new StringBuilder(); id = map.keyAt(i); if (id != unknownUID) { for (PackageInfoData app : apps) { if (app.uid == id) { appId = id; appName = app.names.get(0); break; } } } else { appName = "Kernel"; } loginfo = map.valueAt(i); totalBlocked = loginfo.totalBlocked; if (loginfo.dstBlocked.size() > 0) { for (String dst : loginfo.dstBlocked.keySet()) { address.append( dst + "(" + loginfo.dstBlocked.get(dst) + ")"); address.append("\n"); } } res.append("AppID :\t" + appId + "\n" + ctx.getString(R.string.LogAppName) +":\t" + appName + "\n" + ctx.getString(R.string.LogPackBlock) + ":\t" + totalBlocked + "\n"); res.append(address.toString()); res.append("\n\t---------\n"); } if (res.length() == 0) { res.append(ctx.getString(R.string.no_log)); } return res.toString(); //return output.toString(); //alert(ctx, res); } catch (Exception e) { alert(ctx, "error: " + e); } return ""; } /*public static void parseResult(String result) { int pos = 0; String src, dst, len, uid; final BufferedReader r = new BufferedReader(new StringReader(result.toString())); String line; try { while ((line = r.readLine()) != null) { int newline = result.indexOf("\n", pos); pos = line.indexOf("SRC=", pos); //if(pos == -1) continue; int space = line.indexOf(" ", pos); //if(space == -1) continue; src = line.substring(pos + 4, space); pos = line.indexOf("DST=", pos); //if(pos == -1) continue; space = line.indexOf(" ", pos); // if(space == -1) continue; dst = line.substring(pos + 4, space); pos = line.indexOf("LEN=", pos); //if(pos == -1) continue; space = line.indexOf(" ", pos); //if(space == -1) continue; len = line.substring(pos + 4, space); pos = line.indexOf("UID=", pos); //if(pos == -1) continue; space = line.indexOf(" ", pos); //if(space == -1) continue; uid = line.substring(pos + 4, space); LogEntry entry = logEntriesHash.get(uid); if(entry == null) entry = new LogEntry(); entry.uid = uid; entry.src = src; entry.dst = dst; entry.len = new Integer(len).intValue(); entry.packets++; entry.bytes += entry.len * 8; logEntriesHash.put(uid, entry); logEntriesList.add(entry); } } catch (NumberFormatException e) { } catch (IOException e) { } }*/ /** * @param ctx application context (mandatory) * @return a list of applications */ public static List<PackageInfoData> getApps(Context ctx, GetAppList appList) { initSpecial(); if (applications != null && applications.size() > 0) { // return cached instance return applications; } final SharedPreferences defaultPrefs = PreferenceManager.getDefaultSharedPreferences(ctx); final boolean enableVPN = defaultPrefs.getBoolean("enableVPN", false); final boolean enableLAN = defaultPrefs.getBoolean("enableLAN", false); final boolean enableRoam = defaultPrefs.getBoolean("enableRoam", true); final SharedPreferences prefs = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); final String savedPkg_wifi_uid = prefs.getString(PREF_WIFI_PKG_UIDS, ""); final String savedPkg_3g_uid = prefs.getString(PREF_3G_PKG_UIDS, ""); final String savedPkg_roam_uid = prefs.getString(PREF_ROAMING_PKG_UIDS, ""); final String savedPkg_vpn_uid = prefs.getString(PREF_VPN_PKG_UIDS, ""); final String savedPkg_lan_uid = prefs.getString(PREF_LAN_PKG_UIDS, ""); // allowed application names separated by pipe '|' (persisted) final String savedPkg_wifi = prefs.getString(PREF_WIFI_PKG, ""); final String savedPkg_3g = prefs.getString(PREF_3G_PKG, ""); final String savedPkg_roam = prefs.getString(PREF_ROAMING_PKG, ""); final String savedPkg_vpn = prefs.getString(PREF_VPN_PKG, ""); final String savedPkg_lan = prefs.getString(PREF_LAN_PKG, ""); List<Integer> selected_wifi = new ArrayList<Integer>(); List<Integer> selected_3g = new ArrayList<Integer>(); List<Integer> selected_roam = new ArrayList<Integer>(); List<Integer> selected_vpn = new ArrayList<Integer>(); List<Integer> selected_lan = new ArrayList<Integer>(); if (savedPkg_wifi_uid.equals("")) { selected_wifi = getUidListFromPref(ctx, savedPkg_wifi); } else { selected_wifi = getListFromPref(savedPkg_wifi_uid); } if (savedPkg_3g_uid.equals("")) { selected_3g = getUidListFromPref(ctx, savedPkg_3g); } else { selected_3g = getListFromPref(savedPkg_3g_uid); } if (enableRoam) { if (savedPkg_roam_uid.equals("")) { selected_roam = getUidListFromPref(ctx, savedPkg_roam); } else { selected_roam = getListFromPref(savedPkg_roam_uid); } } if (enableVPN) { if (savedPkg_vpn_uid.equals("")) { selected_vpn = getUidListFromPref(ctx, savedPkg_vpn); } else { selected_vpn = getListFromPref(savedPkg_vpn_uid); } } if (enableLAN) { if (savedPkg_lan_uid.equals("")) { selected_lan = getUidListFromPref(ctx, savedPkg_lan); } else { selected_lan = getListFromPref(savedPkg_lan_uid); } } //revert back to old approach int count = 0; try { final PackageManager pkgmanager = ctx.getPackageManager(); final List<ApplicationInfo> installed = pkgmanager.getInstalledApplications(PackageManager.GET_META_DATA); /* 0 - Root 1000 - System 1001 - Radio 1002 - Bluetooth 1003 - Graphics 1004 - Input 1005 - Audio 1006 - Camera 1007 - Log 1008 - Compass 1009 - Mount 1010 - Wi-Fi 1011 - ADB 1012 - Install 1013 - Media 1014 - DHCP 1015 - External Storage 1016 - VPN 1017 - Keystore 1018 - USB Devices 1019 - DRM 1020 - Available 1021 - GPS 1022 - deprecated 1023 - Internal Media Storage 1024 - MTP USB 1025 - NFC 1026 - DRM RPC */ Map<Integer, PackageInfoData> syncMap = new HashMap<Integer, PackageInfoData>(); final Editor edit = prefs.edit(); boolean changed = false; String name = null; String cachekey = null; final String cacheLabel = "cache.label."; PackageInfoData app = null; /*File file = new File(ctx.getDir("data", Context.MODE_PRIVATE), "packageInfo"); if(file.exists()){ syncMap = getObjectFromFile(ctx); }*/ for (final ApplicationInfo apinfo : installed) { count = count+1; if(appList != null ){ appList.doProgress(count); } boolean firstseen = false; app = syncMap.get(apinfo.uid); // filter applications which are not allowed to access the Internet if (app == null && PackageManager.PERMISSION_GRANTED != pkgmanager.checkPermission(Manifest.permission.INTERNET, apinfo.packageName)) { continue; } // try to get the application label from our cache - getApplicationLabel() is horribly slow!!!! cachekey = cacheLabel + apinfo.packageName; name = prefs.getString(cachekey, ""); if (name.length() == 0) { // get label and put on cache name = pkgmanager.getApplicationLabel(apinfo).toString(); edit.putString(cachekey, name); changed = true; firstseen = true; } if (app == null) { app = new PackageInfoData(); app.uid = apinfo.uid; app.names = new ArrayList<String>(); app.names.add(name); app.appinfo = apinfo; app.pkgName = apinfo.packageName; syncMap.put(apinfo.uid, app); } else { app.names.add(name); /*final String newnames[] = new String[app.names.length + 1]; System.arraycopy(app.names, 0, newnames, 0, app.names.length); newnames[app.names.length] = name; app.names = newnames;*/ } app.firstseen = firstseen; // check if this application is selected if (!app.selected_wifi && Collections.binarySearch(selected_wifi, app.uid) >= 0) { app.selected_wifi = true; } if (!app.selected_3g && Collections.binarySearch(selected_3g, app.uid) >= 0) { app.selected_3g = true; } if (enableRoam && !app.selected_roam && Collections.binarySearch(selected_roam, app.uid) >= 0) { app.selected_roam = true; } if (enableVPN && !app.selected_vpn && Collections.binarySearch(selected_vpn, app.uid) >= 0) { app.selected_vpn = true; } if (enableLAN && !app.selected_lan && Collections.binarySearch(selected_lan, app.uid) >= 0) { app.selected_lan = true; } } if (changed) { edit.commit(); } /* add special applications to the list */ //initiate special Apps List<PackageInfoData> specialData = new ArrayList<PackageInfoData>(); specialData.add(new PackageInfoData(SPECIAL_UID_ANY,ctx.getString(R.string.all_item), "dev.afwall.special.any")); specialData.add(new PackageInfoData(SPECIAL_UID_KERNEL,"(Kernel) - Linux kernel", "dev.afwall.special.kernel")); specialData.add(new PackageInfoData(SPECIAL_UID_TETHER,"(Tethering) - DHCP+DNS services", "dev.afwall.special.tether")); specialData.add(new PackageInfoData("root", ctx.getString(R.string.root_item), "dev.afwall.special.root")); specialData.add(new PackageInfoData("media", "Media server", "dev.afwall.special.media")); specialData.add(new PackageInfoData("vpn", "VPN networking", "dev.afwall.special.vpn")); specialData.add(new PackageInfoData("shell", "Linux shell", "dev.afwall.special.shell")); specialData.add(new PackageInfoData("gps", "GPS", "dev.afwall.special.gps")); specialData.add(new PackageInfoData("adb", "ADB(Android Debug Bridge)", "dev.afwall.special.adb")); if(specialApps == null) { specialApps = new HashMap<String, Integer>(); } for (int i=0; i<specialData.size(); i++) { app = specialData.get(i); specialApps.put(app.pkgName, app.uid); if (app.uid != -1 && !syncMap.containsKey(app.uid)) { // check if this application is allowed if (!app.selected_wifi && Collections.binarySearch(selected_wifi, app.uid) >= 0) { app.selected_wifi = true; } if (!app.selected_3g && Collections.binarySearch(selected_3g, app.uid) >= 0) { app.selected_3g = true; } if (enableRoam && !app.selected_roam && Collections.binarySearch(selected_roam, app.uid) >= 0) { app.selected_roam = true; } if (enableVPN && !app.selected_vpn && Collections.binarySearch(selected_vpn, app.uid) >= 0) { app.selected_vpn = true; } if (enableLAN && !app.selected_lan && Collections.binarySearch(selected_lan, app.uid) >= 0) { app.selected_lan = true; } syncMap.put(app.uid, app); } } /* convert the map into an array */ applications = new ArrayList<PackageInfoData>(syncMap.values()); /*if(!file.exists()) { writeObjectToFile(ctx,syncMap); }*/ return applications; } catch (Exception e) { alert(ctx, ctx.getString(R.string.error_common) + e); } return null; } private static List<Integer> getListFromPref(String savedPkg_uid) { final StringTokenizer tok = new StringTokenizer(savedPkg_uid, "|"); List<Integer> listUids = new ArrayList<Integer>(); while(tok.hasMoreTokens()){ final String uid = tok.nextToken(); if (!uid.equals("")) { try { listUids.add(Integer.parseInt(uid)); } catch (Exception ex) { } } } // Sort the array to allow using "Arrays.binarySearch" later Collections.sort(listUids); return listUids; } private static class RunCommand extends AsyncTask<Object, List<String>, Integer> { private int exitCode = -1; @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Integer doInBackground(Object... params) { @SuppressWarnings("unchecked") final List<String> commands = (List<String>) params[0]; final StringBuilder res = (StringBuilder) params[1]; try { if (!SU.available()) return exitCode; if (commands != null && commands.size() > 0) { List<String> output = SU.run(commands); if (output != null) { exitCode = 0; if (output.size() > 0) { for (String str : output) { res.append(str); res.append("\n"); } } } else { exitCode = 1; } } } catch (Exception ex) { if (res != null) res.append("\n" + ex); } return exitCode; } } /** * Runs a script, wither as root or as a regular user (multiple commands separated by "\n"). * @param ctx mandatory context * @param script the script to be executed * @param res the script output response (stdout + stderr) * @param timeout timeout in milliseconds (-1 for none) * @return the script exit code */ public static int runScript(Context ctx, List<String> script, StringBuilder res, long timeout, boolean asroot) { int returnCode = -1; //Log.d(TAG, "In the runScript mode"); try { returnCode = new RunCommand().execute(script, res, ctx).get(); } catch (RejectedExecutionException r) { Log.e(TAG, "runScript failed: " + r.getLocalizedMessage()); } catch (InterruptedException e) { Log.e(TAG, "Caught InterruptedException"); } catch (ExecutionException e) { Log.e(TAG, "runScript failed: " + e.getLocalizedMessage()); } catch (Exception e) { Log.e(TAG, "runScript failed: " + e.getLocalizedMessage()); } return returnCode; } /** * Runs a script as root (multiple commands separated by "\n"). * @param ctx mandatory context * @param script the script to be executed * @param res the script output response (stdout + stderr) * @param timeout timeout in milliseconds (-1 for none) * @return the script exit code */ public static int runScriptAsRoot(Context ctx, List<String> script, StringBuilder res, long timeout) { return runScript(ctx, script, res, timeout, true); } /** * Runs a script as root (multiple commands separated by "\n") with a default timeout of 20 seconds. * @param ctx mandatory context * @param script the script to be executed * @param res the script output response (stdout + stderr) * @param timeout timeout in milliseconds (-1 for none) * @return the script exit code * @throws IOException on any error executing the script, or writing it to disk */ public static int runScriptAsRoot(Context ctx, List<String> script, StringBuilder res) throws IOException { return runScriptAsRoot(ctx, script, res, 40000); } /** * Runs a script as a regular user (multiple commands separated by "\n") with a default timeout of 20 seconds. * @param ctx mandatory context * @param script the script to be executed * @param res the script output response (stdout + stderr) * @param timeout timeout in milliseconds (-1 for none) * @return the script exit code * @throws IOException on any error executing the script, or writing it to disk */ public static int runScript(Context ctx, List<String> script, StringBuilder res) throws IOException { return runScript(ctx, script, res, 40000, false); } /** * Asserts that the binary files are installed in the cache directory. * @param ctx context * @param showErrors indicates if errors should be alerted * @return false if the binary files could not be installed */ public static boolean assertBinaries(Context ctx, boolean showErrors) { boolean changed = false; try { // Check iptables_armv5 File file = new File(ctx.getDir("bin",0), "iptables_armv5"); if (!file.exists() || file.length()!=198652) { copyRawFile(ctx, R.raw.iptables_armv5, file, "755"); changed = true; } // Check busybox file = new File(ctx.getDir("bin",0), "busybox_g1"); if (!file.exists()) { copyRawFile(ctx, R.raw.busybox_g1, file, "755"); changed = true; } // check script file = new File(ctx.getDir("bin",0), "afwallstart"); if (!file.exists()) { copyRawFile(ctx, R.raw.afwallstart, file, "755"); changed = true; } if (changed && showErrors) { displayToasts(ctx, R.string.toast_bin_installed, Toast.LENGTH_LONG); } } catch (Exception e) { if (showErrors) alert(ctx, ctx.getString(R.string.error_binary) + e); return false; } return true; } public static void displayToasts(Context context, int id, int length) { Toast.makeText(context, context.getString(id), length).show(); } public static void displayToasts(Context context, String text, int length) { Toast.makeText(context, text, length).show(); } /** * Check if the firewall is enabled * @param ctx mandatory context * @return boolean */ public static boolean isEnabled(Context ctx) { if (ctx == null) return false; boolean flag = ctx.getSharedPreferences(PREF_FIREWALL_STATUS, Context.MODE_PRIVATE).getBoolean(PREF_ENABLED, false); //Log.d(TAG, "Checking for IsEnabled, Flag:" + flag); return flag; } /** * Defines if the firewall is enabled and broadcasts the new status * @param ctx mandatory context * @param enabled enabled flag */ public static void setEnabled(Context ctx, boolean enabled, boolean showErrors) { if (ctx == null) return; final SharedPreferences prefs = ctx.getSharedPreferences(PREF_FIREWALL_STATUS,Context.MODE_PRIVATE); if (prefs.getBoolean(PREF_ENABLED, false) == enabled) { return; } final Editor edit = prefs.edit(); edit.putBoolean(PREF_ENABLED, enabled); if (!edit.commit()) { if(showErrors)alert(ctx, ctx.getString(R.string.error_write_pref)); return; } /* notify */ final Intent message = new Intent(Api.STATUS_CHANGED_MSG); message.putExtra(Api.STATUS_EXTRA, enabled); ctx.sendBroadcast(message); } private static boolean removePackageRef(Context ctx, String pkg, int pkgRemoved,Editor editor, String store){ final StringBuilder newuids = new StringBuilder(); final StringTokenizer tok = new StringTokenizer(pkg, "|"); boolean changed = false; final String uid_str = pkgRemoved + ""; while (tok.hasMoreTokens()) { final String token = tok.nextToken(); if (uid_str.equals(token)) { //Log.d(TAG, "Removing UID " + token + " from the rules list (package removed)!"); changed = true; } else { if (newuids.length() > 0) newuids.append('|'); newuids.append(token); } } if (changed) { editor.putString(store, newuids.toString()); } return changed; } /** * Called when an application in removed (un-installed) from the system. * This will look for that application in the selected list and update the persisted values if necessary * @param ctx mandatory app context * @param uid UID of the application that has been removed */ public static void applicationRemoved(Context ctx, int pkgRemoved) { final SharedPreferences prefs = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); final Editor editor = prefs.edit(); // allowed application names separated by pipe '|' (persisted) String savedPks_wifi = prefs.getString(PREF_WIFI_PKG_UIDS, ""); String savedPks_3g = prefs.getString(PREF_3G_PKG_UIDS, ""); String savedPks_roam = prefs.getString(PREF_ROAMING_PKG_UIDS, ""); String savedPks_vpn = prefs.getString(PREF_VPN_PKG_UIDS, ""); String savedPks_lan = prefs.getString(PREF_LAN_PKG_UIDS, ""); boolean wChanged,rChanged,gChanged,vChanged = false; // look for the removed application in the "wi-fi" list wChanged = removePackageRef(ctx,savedPks_wifi,pkgRemoved, editor,PREF_WIFI_PKG_UIDS); // look for the removed application in the "3g" list gChanged = removePackageRef(ctx,savedPks_3g,pkgRemoved, editor,PREF_3G_PKG_UIDS); // look for the removed application in roaming list rChanged = removePackageRef(ctx,savedPks_roam,pkgRemoved, editor,PREF_ROAMING_PKG_UIDS); // look for the removed application in vpn list vChanged = removePackageRef(ctx,savedPks_vpn,pkgRemoved, editor,PREF_VPN_PKG_UIDS); // look for the removed application in lan list vChanged = removePackageRef(ctx,savedPks_lan,pkgRemoved, editor,PREF_LAN_PKG_UIDS); if(wChanged || gChanged || rChanged || vChanged) { editor.commit(); if (isEnabled(ctx)) { // .. and also re-apply the rules if the firewall is enabled applySavedIptablesRules(ctx, false); } } } /** * Small structure to hold an application info */ public static final class PackageInfoData { /** linux user id */ int uid; /** application names belonging to this user id */ List<String> names; /** rules saving & load **/ String pkgName; /** indicates if this application is selected for wifi */ boolean selected_wifi; /** indicates if this application is selected for 3g */ boolean selected_3g; /** indicates if this application is selected for roam */ boolean selected_roam; /** indicates if this application is selected for vpn */ boolean selected_vpn; /** indicates if this application is selected for lan */ boolean selected_lan; /** toString cache */ String tostr; /** application info */ ApplicationInfo appinfo; /** cached application icon */ Drawable cached_icon; /** indicates if the icon has been loaded already */ boolean icon_loaded; /** first time seen? */ boolean firstseen; public PackageInfoData() { } public PackageInfoData(int uid, String name, String pkgNameStr) { this.uid = uid; this.names = new ArrayList<String>(); this.names.add(name); this.pkgName = pkgNameStr; } public PackageInfoData(String user, String name, String pkgNameStr) { this(android.os.Process.getUidForName(user), name, pkgNameStr); } /** * Screen representation of this application */ @Override public String toString() { if (tostr == null) { final StringBuilder s = new StringBuilder(); //if (uid > 0) s.append(uid + ": "); for (int i=0; i<names.size(); i++) { if (i != 0) s.append(", "); s.append(names.get(i)); } s.append("\n"); tostr = s.toString(); } return tostr; } public String toStringWithUID() { if (tostr == null) { final StringBuilder s = new StringBuilder(); if (uid > 0) s.append(uid + ": "); for (int i=0; i<names.size(); i++) { if (i != 0) s.append(", "); s.append(names.get(i)); } s.append("\n"); tostr = s.toString(); } return tostr; } } /** * Small internal structure used to hold log information */ private static final class LogInfo { private int totalBlocked; // Total number of packets blocked private HashMap<String, Integer> dstBlocked; // Number of packets blocked per destination IP address private LogInfo() { this.dstBlocked = new HashMap<String, Integer>(); } } public static boolean clearRules(Context ctx) throws IOException{ final StringBuilder res = new StringBuilder(); setIpTablePath(ctx,false); List<String> listCommands = new ArrayList<String>(); listCommands.add((ipPath + " -F")); listCommands.add((ipPath + " -X")); int code = runScriptAsRoot(ctx, listCommands, res); if (code == -1) { alert(ctx, ctx.getString(R.string.error_purge) + code + "\n" + res); return false; } return true; } public static boolean clearipv6Rules(Context ctx) throws IOException{ final StringBuilder res = new StringBuilder(); setIpTablePath(ctx,true); List<String> listCommands = new ArrayList<String>(); listCommands.add((ipPath + " -F")); listCommands.add((ipPath + " -X")); int code = runScriptAsRoot(ctx, listCommands, res); if (code == -1) { alert(ctx, ctx.getString(R.string.error_purge) + code + "\n" + res); return false; } return true; } /*public void RunAsRoot(List<String> cmds) throws IOException{ Process p = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(p.getOutputStream()); for (String tmpCmd : cmds) { os.writeBytes(tmpCmd+"")); } os.writeBytes("exit")); os.flush(); }*/ public static String runSUCommand(String cmd) throws IOException { final StringBuilder res = new StringBuilder(); Process p = Runtime.getRuntime().exec( new String[] { "su", "-c", cmd }); BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream())); String tmp; while ((tmp = stdout.readLine()) != null) { res.append(tmp); res.append(","); } // use inputLine.toString(); here it would have whole source stdout.close(); return res.toString(); } public static boolean applyRulesBeforeShutdown(Context ctx) { final StringBuilder res = new StringBuilder(); final String dir = ctx.getDir("bin", 0).getAbsolutePath(); final String myiptables = dir + "/iptables_armv5 "; List<String> listCommands = new ArrayList<String>(); listCommands.add((myiptables + " -F")); listCommands.add((myiptables + " -X")); listCommands.add((myiptables + " -P INPUT DROP")); listCommands.add((myiptables + " -P OUTPUT DROP")); listCommands.add((myiptables + " -P FORWARD DROP")); try { runScriptAsRoot(ctx, listCommands, res); } catch (IOException e) { } return true; } public static void saveSharedPreferencesToFileConfirm(final Context ctx) { AlertDialog.Builder builder = new AlertDialog.Builder(ctx); builder.setMessage(ctx.getString(R.string.exportConfirm)) .setCancelable(false) .setPositiveButton(ctx.getString(R.string.Yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { if(saveSharedPreferencesToFile(ctx)){ Api.alert(ctx, ctx.getString(R.string.export_rules_success) + " " + Environment.getExternalStorageDirectory().getPath() + "/afwall/"); } else { Api.alert(ctx, ctx.getString(R.string.export_rules_fail) ); } } }) .setNegativeButton(ctx.getString(R.string.No), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } public static boolean saveSharedPreferencesToFile(Context ctx) { boolean res = false; File sdCard = Environment.getExternalStorageDirectory(); File dir = new File (sdCard.getAbsolutePath() + "/afwall/"); dir.mkdirs(); File file = new File(dir, "backup.rules"); ObjectOutputStream output = null; try { output = new ObjectOutputStream(new FileOutputStream(file)); saveRules(ctx); SharedPreferences pref = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); output.writeObject(pref.getAll()); res = true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { if (output != null) { output.flush(); output.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return res; } @SuppressWarnings("unchecked") public static boolean loadSharedPreferencesFromFile(Context ctx) { boolean res = false; File sdCard = Environment.getExternalStorageDirectory(); File dir = new File(sdCard.getAbsolutePath() + "/afwall/"); dir.mkdirs(); File file = new File(dir, "backup.rules"); ObjectInputStream input = null; try { input = new ObjectInputStream(new FileInputStream(file)); Editor prefEdit = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit(); prefEdit.clear(); Map<String, ?> entries = (Map<String, ?>) input.readObject(); for (Entry<String, ?> entry : entries.entrySet()) { Object v = entry.getValue(); String key = entry.getKey(); if (v instanceof Boolean) prefEdit.putBoolean(key, ((Boolean) v).booleanValue()); else if (v instanceof Float) prefEdit.putFloat(key, ((Float) v).floatValue()); else if (v instanceof Integer) prefEdit.putInt(key, ((Integer) v).intValue()); else if (v instanceof Long) prefEdit.putLong(key, ((Long) v).longValue()); else if (v instanceof String) prefEdit.putString(key, ((String) v)); } prefEdit.commit(); res = true; } catch (FileNotFoundException e) { //alert(ctx, "Missing back.rules file"); Log.e(TAG, e.getLocalizedMessage()); } catch (IOException e) { //alert(ctx, "Error reading the backup file"); Log.e(TAG, e.getLocalizedMessage()); } catch (ClassNotFoundException e) { Log.e(TAG, e.getLocalizedMessage()); } finally { try { if (input != null) { input.close(); } } catch (IOException ex) { Log.e(TAG, ex.getLocalizedMessage()); } } return res; } /*public static int getIptablesVersion(Context ctx){ SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(ctx); int number = prefs.getInt("iptablesv", 0); if (number == 0) { try { final StringBuilder res = new StringBuilder(); ArrayList<CommandCapture> listCommands = new ArrayList<CommandCapture>(); listCommands.add(("iptables --version")); runScriptAsRoot(ctx, listCommands, res); try { String inputLine = res.toString(); Pattern pattern = Pattern.compile("[0-9]+(\\.[0-9]+)+$"); Matcher matcher = pattern.matcher(inputLine.toString()); String numberStr = null; while (matcher.find()) { numberStr = matcher.group(); } if (numberStr != null) { number = Integer.parseInt(numberStr.replace(".", "")); } final Editor edit = prefs.edit(); edit.putInt("iptablesv", number); edit.commit(); } catch (Exception e) { Log.e(TAG, e.getLocalizedMessage()); } } catch (Exception e) { Log.e(TAG, e.getLocalizedMessage()); } } return number; }*/ public static String showIfaces() { String output = null; try { output = runSUCommand("ls /sys/class/net"); } catch (IOException e1) { Log.e(TAG, "IOException: " + e1.getLocalizedMessage()); } if (output != null) { output = output.replace(" ", ","); } return output; } @SuppressLint("InlinedApi") public static void showInstalledAppDetails(Context context, String packageName) { final String SCHEME = "package"; final String APP_PKG_NAME_21 = "com.android.settings.ApplicationPkgName"; final String APP_PKG_NAME_22 = "pkg"; final String APP_DETAILS_PACKAGE_NAME = "com.android.settings"; final String APP_DETAILS_CLASS_NAME = "com.android.settings.InstalledAppDetails"; Intent intent = new Intent(); final int apiLevel = Build.VERSION.SDK_INT; if (apiLevel >= 9) { // above 2.3 intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts(SCHEME, packageName, null); intent.setData(uri); } else { // below 2.3 final String appPkgName = (apiLevel == 8 ? APP_PKG_NAME_22 : APP_PKG_NAME_21); intent.setAction(Intent.ACTION_VIEW); intent.setClassName(APP_DETAILS_PACKAGE_NAME, APP_DETAILS_CLASS_NAME); intent.putExtra(appPkgName, packageName); } context.startActivity(intent); } public static boolean hasRootAccess(Context ctx, boolean showErrors) { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(ctx); boolean isRoot = prefs.getBoolean("isRootAvail", false); if (!isRoot) { try { // Run an empty script just to check root access int returnCode = new SUCheck().execute(null, null).get(); if (returnCode == 0) { isRoot = true; Editor edit = prefs.edit(); edit.putBoolean("isRootAvail", true); edit.commit(); } else { if (showErrors) { alert(ctx, ctx.getString(R.string.error_su)); } } } catch (Exception e) { } } return isRoot; } public static boolean isNetfilterSupported() { if ((new File("/proc/config.gz")).exists() == false) { if ((new File("/proc/net/netfilter")).exists() == false) return false; if ((new File("/proc/net/ip_tables_targets")).exists() == false) return false; } return true; } private static void initSpecial() { if(specialApps == null || specialApps.size() == 0){ specialApps = new HashMap<String, Integer>(); specialApps.put("dev.afwall.special.any",SPECIAL_UID_ANY); specialApps.put("dev.afwall.special.kernel",SPECIAL_UID_KERNEL); specialApps.put("dev.afwall.special.tether",SPECIAL_UID_TETHER); specialApps.put("dev.afwall.special.root",android.os.Process.getUidForName("root")); specialApps.put("dev.afwall.special.media",android.os.Process.getUidForName("media")); specialApps.put("dev.afwall.special.vpn",android.os.Process.getUidForName("vpn")); specialApps.put("dev.afwall.special.shell",android.os.Process.getUidForName("shell")); specialApps.put("dev.afwall.special.gps",android.os.Process.getUidForName("gps")); specialApps.put("dev.afwall.special.adb",android.os.Process.getUidForName("adb")); } } public static void sendNotification(Context context,String title, String message) { NotificationManager mNotificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); int icon = R.drawable.notification_icon; final int HELLO_ID = 24556; Intent appIntent = new Intent(context, MainActivity.class); PendingIntent in = PendingIntent.getActivity(context, 0, appIntent, 0); NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setSmallIcon(icon) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setContentTitle(title) .setContentText(message); //Notification n = builder.build(); //Notification notification = new Notification(icon, tickerText, when); builder.setContentIntent(in); /*notification.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS; PendingIntent contentIntent = PendingIntent.getActivity(context, 0, appIntent, 0); notification.setLatestEventInfo(context, tickerText, context.getString(R.string.notification_new), contentIntent);*/ mNotificationManager.notify(HELLO_ID, builder.build()); } public static void updateLanguage(Context context, String lang) { if (!"".equals(lang)) { Locale locale = new Locale(lang); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; context.getResources().updateConfiguration(config, null); } } private static class SUCheck extends AsyncTask<Object, Object, Integer> { private int exitCode = -1; @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Integer doInBackground(Object... params) { try { if (SU.available()) exitCode = 0; } catch (Exception ex) { } return exitCode; } } public static String getTargets(Context context) { String busybox = getBusyBoxPath(context); String grep = busybox + " grep"; final StringBuilder res = new StringBuilder(); List<String> listCommands = new ArrayList<String>(); listCommands.add(grep + " \\.\\* /proc/net/ip_tables_targets"); try { runScriptAsRoot(context, listCommands, res); }catch(Exception e){ Log.d("getTargets: " , e.getLocalizedMessage()); } return res.toString(); } /*@SuppressWarnings("unchecked") private static Map<Integer, PackageInfoData> getObjectFromFile(Context ctx) { Map<Integer, PackageInfoData> entries = new HashMap<Integer, PackageInfoData>(); Looper.prepare(); // now new caching technique to improve the performance File file = new File(ctx.getDir("data", Context.MODE_PRIVATE), "packageInfo"); ObjectInputStream input; try { input = new ObjectInputStream(new FileInputStream(file)); entries = (Map) input.readObject(); } catch (FileNotFoundException e) { } catch (IOException e) { } catch (ClassNotFoundException e) { e.printStackTrace(); } return entries; } private static void writeObjectToFile(Context ctx, Map<Integer, PackageInfoData> syncMap) { Looper.prepare(); // now new caching technique to improve the performance File file = new File(ctx.getDir("data", Context.MODE_PRIVATE), "packageInfo"); ObjectOutputStream outputStream; try { outputStream = new ObjectOutputStream(new FileOutputStream(file)); outputStream.writeObject(syncMap); outputStream.flush(); outputStream.close(); } catch (FileNotFoundException e) { } catch (IOException e) { } }*/ }
true
true
private static boolean applyIptablesRulesImpl(final Context ctx, List<Integer> uidsWifi, List<Integer> uids3g, List<Integer> uidsRoam, List<Integer> uidsVPN, List<Integer> uidsLAN, final boolean showErrors) { if (ctx == null) { return false; } assertBinaries(ctx, showErrors); final SharedPreferences appprefs = PreferenceManager.getDefaultSharedPreferences(ctx); final InterfaceDetails cfg = InterfaceTracker.getCurrentCfg(ctx); final boolean enableVPN = appprefs.getBoolean("enableVPN", false); final boolean enableLAN = appprefs.getBoolean("enableLAN", false) && !cfg.isTethered; final boolean enableRoam = appprefs.getBoolean("enableRoam", true); final SharedPreferences prefs = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); final boolean whitelist = prefs.getString(PREF_MODE, MODE_WHITELIST).equals(MODE_WHITELIST); final boolean blacklist = !whitelist; final boolean logenabled = appprefs.getBoolean("enableFirewallLog",true); //final boolean isVPNEnabled = appprefs.getBoolean("enableVPNProfile",false); //String iptargets = getTargets(ctx); StringBuilder customScript = new StringBuilder(ctx.getSharedPreferences(Api.PREFS_NAME, Context.MODE_PRIVATE).getString(Api.PREF_CUSTOMSCRIPT, "")); try { int code; String busybox = getBusyBoxPath(ctx); String grep = busybox + " grep"; final List<String> listCommands = new ArrayList<String>(); listCommands.add(ipPath + " -L afwall >/dev/null 2>/dev/null || " + ipPath + " --new afwall || exit" ); listCommands.add(ipPath + " -L afwall-3g >/dev/null 2>/dev/null ||" + ipPath + "--new afwall-3g || exit" ); listCommands.add(ipPath + " -L afwall-wifi >/dev/null 2>/dev/null || " + ipPath + " --new afwall-wifi || exit" ); listCommands.add(ipPath + " -L afwall-lan >/dev/null 2>/dev/null || " + ipPath + " --new afwall-lan || exit" ); listCommands.add(ipPath + " -L afwall-vpn >/dev/null 2>/dev/null || " + ipPath + " --new afwall-vpn || exit" ); listCommands.add(ipPath + " -L afwall-reject >/dev/null 2>/dev/null || " + ipPath + " --new afwall-reject || exit" ); listCommands.add(ipPath + " -L OUTPUT | " + grep + " -q afwall || " + ipPath + " -A OUTPUT -j afwall || exit"); listCommands.add(ipPath + " -F afwall || exit " ); listCommands.add(ipPath + " -F afwall-3g || exit "); listCommands.add(ipPath + " -F afwall-wifi || exit "); listCommands.add(ipPath + " -F afwall-lan || exit "); listCommands.add(ipPath + " -F afwall-vpn || exit "); listCommands.add(ipPath + " -F afwall-reject || exit 10"); listCommands.add(ipPath + " -A afwall -m owner --uid-owner 0 -p udp --dport 53 -j RETURN || exit"); listCommands.add((ipPath + " -D OUTPUT -j afwall")); listCommands.add((ipPath + " -I OUTPUT 1 -j afwall")); //this will make sure the only afwall will be able to control the OUTPUT chain, regardless of any firewall installed! //listCommands.add((ipPath + " --flush OUTPUT || exit")); // Check if logging is enabled if (logenabled) { listCommands.add((ipPath + " -A afwall-reject -m limit --limit 1000/min -j LOG --log-prefix \"{AFL}\" --log-level 4 --log-uid ")); } listCommands.add((ipPath + " -A afwall-reject -j REJECT || exit")); //now reenable everything after restart listCommands.add((ipPath + " -P INPUT ACCEPT")); listCommands.add((ipPath + " -P OUTPUT ACCEPT")); listCommands.add((ipPath + " -P FORWARD ACCEPT")); if (customScript.length() > 0) { replaceAll(customScript, "$IPTABLES", " " +ipPath ); listCommands.add(customScript.toString()); } for (final String itf : ITFS_3G) { listCommands.add((ipPath + " -A afwall -o ".concat(itf).concat(" -j afwall-3g || exit"))); } for (final String itf : ITFS_WIFI) { if(enableLAN) { if(setv6 && !cfg.lanMaskV6.equals("")) { listCommands.add(ipPath + " -A afwall -d " + cfg.lanMaskV6 + " -o " + itf + " -j afwall-lan || exit"); listCommands.add(ipPath + " -A afwall '!' -d " + cfg.lanMaskV6 + " -o " + itf+ " -j afwall-wifi || exit"); } if(!setv6 && !cfg.lanMaskV4.equals("")) { listCommands.add(ipPath + " -A afwall -d " + cfg.lanMaskV4 + " -o " + itf + " -j afwall-lan || exit"); listCommands.add(ipPath + " -A afwall '!' -d "+ cfg.lanMaskV4 + " -o " + itf + " -j afwall-wifi || exit"); } } else { listCommands.add((ipPath + " -A afwall -o ".concat(itf).concat(" -j afwall-wifi || exit"))); } } if(enableVPN) { for (final String itf : ITFS_VPN) { listCommands.add((ipPath + " -A afwall -o ".concat(itf).concat(" -j afwall-vpn || exit"))); } } final String targetRule = (whitelist ? "RETURN" : "afwall-reject"); final boolean any_3g = uids3g.indexOf(SPECIAL_UID_ANY) >= 0; final boolean any_wifi = uidsWifi.indexOf(SPECIAL_UID_ANY) >= 0; final boolean any_lan = uidsLAN.indexOf(SPECIAL_UID_ANY) >= 0; final boolean any_vpn = uidsVPN.indexOf(SPECIAL_UID_ANY) >= 0; if (whitelist && !any_wifi) { addRuleForUsers(listCommands, new String[]{"dhcp","wifi"}, ipPath + " -A afwall-wifi", "-j RETURN || exit"); } //now 3g rules! if (any_3g) { if (blacklist) { /* block any application on this interface */ listCommands.add((ipPath + " -A afwall-3g -j "+(targetRule)+(" || exit"))); } } else { /* release/block individual applications on this interface */ if(cfg.isRoaming && enableRoam) { for (final Integer uid : uidsRoam) { if (uid !=null && uid >= 0) listCommands.add((ipPath + " -A afwall-3g -m owner --uid-owner "+(uid)+(" -j ")+(targetRule)+(" || exit"))); } } else { for (final Integer uid : uids3g) { if (uid !=null && uid >= 0) listCommands.add((ipPath + " -A afwall-3g -m owner --uid-owner "+(uid)+(" -j ")+(targetRule)+(" || exit"))); } } } //now wifi rules! // if the wifi interface is down, reject all outbound packets without logging them if (!cfg.allowWifi) { listCommands.add(ipPath + " -A afwall-wifi -j REJECT || exit"); } else if (any_wifi) { if (blacklist) { /* block any application on this interface */ listCommands.add((ipPath + " -A afwall-wifi -j "+(targetRule)+(" || exit"))); } } else { /* release/block individual applications on this interface */ for (final Integer uid : uidsWifi) { if (uid !=null && uid >= 0) listCommands.add((ipPath + " -A afwall-wifi -m owner --uid-owner "+(uid)+(" -j ")+(targetRule)+(" || exit"))); } } //now LAN rules! if (enableLAN) { if (!cfg.allowWifi) { listCommands.add(ipPath + " -A afwall-lan -j REJECT || exit"); } else if (any_lan) { if (blacklist) { /* block any application on this interface */ listCommands.add((ipPath + " -A afwall-lan -j "+(targetRule)+(" || exit"))); } } else { /* release/block individual applications on this interface */ for (final Integer uid : uidsLAN) { if (uid != null && uid >= 0) listCommands.add((ipPath + " -A afwall-lan -m owner --uid-owner " + uid + " -j " + targetRule + " || exit")); } // NOTE: we still need to open a hole for DNS lookups // This falls through to the wifi rules if the app is not whitelisted for LAN access if (whitelist) { listCommands.add(ipPath + " -A afwall-lan -p udp --dport 53 -j RETURN || exit"); } } } //now vpn rules! if(enableVPN) { if (any_vpn) { if (blacklist) { /* block any application on this interface */ listCommands.add((ipPath + " -A afwall-vpn -j "+(targetRule)+(" || exit"))); } } else { /* release/block individual applications on this interface */ for (final Integer uid : uidsVPN) { if (uid !=null && uid >= 0) listCommands.add((ipPath + " -A afwall-vpn -m owner --uid-owner "+(uid)+(" -j ")+(targetRule)+(" || exit"))); } } } // note that this can only blacklist DNS/DHCP services, not all tethered traffic if (cfg.isTethered && ((blacklist && (any_wifi || any_3g)) || (uids3g.indexOf(SPECIAL_UID_TETHER) >= 0) || (uidsWifi.indexOf(SPECIAL_UID_TETHER) >= 0))) { String users[] = { "root", "nobody" }; String action = " -j " + targetRule + " || exit"; // DHCP replies to client addRuleForUsers(listCommands, users, ipPath + " -A afwall-wifi","-p udp --sport=67 --dport=68" + action); // DNS replies to client addRuleForUsers(listCommands, users, ipPath + " -A afwall-wifi","-p udp --sport=53" + action); addRuleForUsers(listCommands, users, ipPath + " -A afwall-wifi","-p tcp --sport=53" + action); // DNS requests to upstream servers addRuleForUsers(listCommands, users, ipPath + " -A afwall-3g","-p udp --dport=53" + action); addRuleForUsers(listCommands, users, ipPath + " -A afwall-3g","-p tcp --dport=53" + action); } if (whitelist) { if (!any_3g) { if (uids3g.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-3g -m owner --uid-owner 0:999999999 -j afwall-reject || exit")); } else { listCommands.add((ipPath + " -A afwall-3g -j afwall-reject || exit")); } } if (!any_wifi) { if (uidsWifi.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-wifi -m owner --uid-owner 0:999999999 -j afwall-reject || exit")); } else { listCommands.add((ipPath + " -A afwall-wifi -j afwall-reject || exit")); } } if (enableVPN && !any_vpn) { if (uidsVPN.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-vpn -m owner --uid-owner 0:999999999 -j afwall-reject || exit")); } else { listCommands.add((ipPath + " -A afwall-vpn -j afwall-reject || exit")); } } if (enableLAN && !any_lan) { if (uidsLAN.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-lan -m owner --uid-owner 0:999999999 -j afwall-reject || exit")); } else { listCommands.add((ipPath + " -A afwall-lan -j afwall-reject || exit")); } } } else { if (uids3g.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-3g -m owner --uid-owner 0:999999999 -j RETURN || exit")); listCommands.add((ipPath + " -A afwall-3g -j afwall-reject || exit")); } if (uidsWifi.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-wifi -m owner --uid-owner 0:999999999 -j RETURN || exit")); listCommands.add((ipPath + " -A afwall-wifi -j afwall-reject || exit")); } if (enableVPN && uidsVPN.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-vpn -m owner --uid-owner 0:999999999 -j RETURN || exit")); listCommands.add((ipPath + " -A afwall-vpn -j afwall-reject || exit")); } if (enableLAN && uidsLAN.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-lan -m owner --uid-owner 0:999999999 -j RETURN || exit")); listCommands.add((ipPath + " -A afwall-lan -j afwall-reject || exit")); } } //active defence final StringBuilder res = new StringBuilder(); code = runScriptAsRoot(ctx, listCommands, res); if (showErrors && code != 0) { String msg = res.toString(); // Remove unnecessary help message from output if (msg.indexOf("\nTry `iptables -h' or 'iptables --help' for more information.") != -1) { msg = msg.replace("\nTry `iptables -h' or 'iptables --help' for more information.", ""); } alert(ctx, ctx.getString(R.string.error_apply) + code + "\n\n" + msg.trim() ); } else { return true; } } catch (Exception e) { Log.e(TAG, "Exception while applying rules: " + e.getMessage()); if (showErrors) alert(ctx, ctx.getString(R.string.error_refresh) + e); } return false; } private static List<Integer> getUidListFromPref(Context ctx,final String pks) { initSpecial(); final PackageManager pm = ctx.getPackageManager(); final List<Integer> uids = new ArrayList<Integer>(); final StringTokenizer tok = new StringTokenizer(pks, "|"); while (tok.hasMoreTokens()) { final String pkg = tok.nextToken(); if (pkg != null && pkg.length() > 0) { try { if (pkg.startsWith("dev.afwall.special")) { uids.add(specialApps.get(pkg)); } else { uids.add(pm.getApplicationInfo(pkg, 0).uid); } } catch (Exception ex) { } } } Collections.sort(uids); return uids; } /** * Purge and re-add all saved rules (not in-memory ones). * This is much faster than just calling "applyIptablesRules", since it don't need to read installed applications. * @param ctx application context (mandatory) * @param showErrors indicates if errors should be alerted */ public static boolean applySavedIptablesRules(Context ctx, boolean showErrors) { if (ctx == null) { return false; } initSpecial(); final SharedPreferences prefs = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); final String savedPkg_wifi_uid = prefs.getString(PREF_WIFI_PKG_UIDS, ""); final String savedPkg_3g_uid = prefs.getString(PREF_3G_PKG_UIDS, ""); final String savedPkg_roam_uid = prefs.getString(PREF_ROAMING_PKG_UIDS, ""); final String savedPkg_vpn_uid = prefs.getString(PREF_VPN_PKG_UIDS, ""); final String savedPkg_lan_uid = prefs.getString(PREF_LAN_PKG_UIDS, ""); final SharedPreferences appprefs = PreferenceManager.getDefaultSharedPreferences(ctx); final boolean enableIPv6 = appprefs.getBoolean("enableIPv6", false); boolean returnValue = false; setIpTablePath(ctx,false); returnValue = applyIptablesRulesImpl(ctx, getListFromPref(savedPkg_wifi_uid), getListFromPref(savedPkg_3g_uid), getListFromPref(savedPkg_roam_uid), getListFromPref(savedPkg_vpn_uid), getListFromPref(savedPkg_lan_uid), showErrors); if (enableIPv6) { setIpTablePath(ctx,true); returnValue = applyIptablesRulesImpl(ctx, getListFromPref(savedPkg_wifi_uid), getListFromPref(savedPkg_3g_uid), getListFromPref(savedPkg_roam_uid), getListFromPref(savedPkg_vpn_uid), getListFromPref(savedPkg_lan_uid), showErrors); } return returnValue; } /** * Purge and re-add all rules. * @param ctx application context (mandatory) * @param showErrors indicates if errors should be alerted */ public static boolean applyIptablesRules(Context ctx, boolean showErrors) { if (ctx == null) { return false; } saveRules(ctx); return applySavedIptablesRules(ctx, showErrors); } /** * Save current rules using the preferences storage. * @param ctx application context (mandatory) */ public static void saveRules(Context ctx) { final SharedPreferences defaultPrefs = PreferenceManager.getDefaultSharedPreferences(ctx); final boolean enableVPN = defaultPrefs.getBoolean("enableVPN", false); final boolean enableLAN = defaultPrefs.getBoolean("enableLAN", false); final boolean enableRoam = defaultPrefs.getBoolean("enableRoam", true); final SharedPreferences prefs = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); final List<PackageInfoData> apps = getApps(ctx,null); // Builds a pipe-separated list of names final StringBuilder newpkg_wifi = new StringBuilder(); final StringBuilder newpkg_3g = new StringBuilder(); final StringBuilder newpkg_roam = new StringBuilder(); final StringBuilder newpkg_vpn = new StringBuilder(); final StringBuilder newpkg_lan = new StringBuilder(); for (int i=0; i<apps.size(); i++) { if (apps.get(i).selected_wifi) { if (newpkg_wifi.length() != 0) newpkg_wifi.append('|'); newpkg_wifi.append(apps.get(i).uid); } if (apps.get(i).selected_3g) { if (newpkg_3g.length() != 0) newpkg_3g.append('|'); newpkg_3g.append(apps.get(i).uid); } if (enableRoam && apps.get(i).selected_roam) { if (newpkg_roam.length() != 0) newpkg_roam.append('|'); newpkg_roam.append(apps.get(i).uid); } if (enableVPN && apps.get(i).selected_vpn) { if (newpkg_vpn.length() != 0) newpkg_vpn.append('|'); newpkg_vpn.append(apps.get(i).uid); } if (enableLAN && apps.get(i).selected_lan) { if (newpkg_lan.length() != 0) newpkg_lan.append('|'); newpkg_lan.append(apps.get(i).uid); } } // save the new list of UIDs final Editor edit = prefs.edit(); edit.putString(PREF_WIFI_PKG_UIDS, newpkg_wifi.toString()); edit.putString(PREF_3G_PKG_UIDS, newpkg_3g.toString()); edit.putString(PREF_ROAMING_PKG_UIDS, newpkg_roam.toString()); edit.putString(PREF_VPN_PKG_UIDS, newpkg_vpn.toString()); edit.putString(PREF_LAN_PKG_UIDS, newpkg_lan.toString()); edit.commit(); } /** * Purge all iptables rules. * @param ctx mandatory context * @param showErrors indicates if errors should be alerted * @return true if the rules were purged */ public static boolean purgeVPNRules(Context ctx, boolean showErrors) { final StringBuilder res = new StringBuilder(); try { assertBinaries(ctx, showErrors); // Custom "shutdown" script setIpTablePath(ctx,false); List<String> listCommands = new ArrayList<String>(); listCommands.add((ipPath + " -F afwall-vpn")); int code = runScriptAsRoot(ctx, listCommands, res); if (code == -1) { if(showErrors) alert(ctx, ctx.getString(R.string.error_purge) + code + "\n" + res); return false; } final SharedPreferences appprefs = PreferenceManager .getDefaultSharedPreferences(ctx); final boolean enableIPv6 = appprefs.getBoolean("enableIPv6", false); if (enableIPv6) { setIpTablePath(ctx, true); listCommands.clear(); listCommands.add((ipPath + " -F afwall-vpn")); code = runScriptAsRoot(ctx, listCommands, res); if (code == -1) { if (showErrors) alert(ctx, ctx.getString(R.string.error_purge) + code + "\n" + res); return false; } } return true; } catch (Exception e) { return false; } } /** * Purge all iptables rules. * @param ctx mandatory context * @param showErrors indicates if errors should be alerted * @return true if the rules were purged */ public static boolean purgeIptables(Context ctx, boolean showErrors) { try { assertBinaries(ctx, showErrors); // Custom "shutdown" script setIpTablePath(ctx,false); purgeRules(ctx,showErrors); final SharedPreferences appprefs = PreferenceManager.getDefaultSharedPreferences(ctx); final boolean enableIPv6 = appprefs.getBoolean("enableIPv6", false); if(enableIPv6) { setIpTablePath(ctx,true); purgeRules(ctx,showErrors); } return true; } catch (Exception e) { return false; } } private static boolean purgeRules(Context ctx,boolean showErrors) throws IOException { boolean returnVal = true; final StringBuilder res = new StringBuilder(); List<String> listCommands = new ArrayList<String>(); listCommands.add((ipPath + " -F afwall")); listCommands.add((ipPath + " -F afwall-reject")); listCommands.add((ipPath + " -F afwall-3g")); listCommands.add((ipPath + " -F afwall-wifi")); listCommands.add((ipPath + " -D OUTPUT -j afwall || exit")); final SharedPreferences defaultPrefs = PreferenceManager.getDefaultSharedPreferences(ctx); StringBuilder customScript = new StringBuilder(ctx.getSharedPreferences(Api.PREFS_NAME, Context.MODE_PRIVATE).getString(Api.PREF_CUSTOMSCRIPT2, "")); final boolean enableVPN = defaultPrefs.getBoolean("enableVPN", false); final boolean enableLAN = defaultPrefs.getBoolean("enableLAN", false); if(enableVPN) { listCommands.add((ipPath + " -F afwall-vpn")); } if(enableLAN) { listCommands.add((ipPath + " -F afwall-lan")); } if (customScript.length() > 0) { replaceAll(customScript, "$IPTABLES", " " +ipPath ); listCommands.add(customScript.toString()); } int code = runScriptAsRoot(ctx, listCommands, res); if (code == -1) { if(showErrors) alert(ctx, ctx.getString(R.string.error_purge) + code + "\n" + res); returnVal = false; } return returnVal; } /** * Display iptables rules output * @param ctx application context */ public static String showIptablesRules(Context ctx) { try { final StringBuilder res = new StringBuilder(); setIpTablePath(ctx,false); List<String> listCommands = new ArrayList<String>(); listCommands.add((ipPath + " -L -n")); runScriptAsRoot(ctx, listCommands, res); return res.toString(); } catch (Exception e) { alert(ctx, "error: " + e); } return ""; } /** * Display iptables rules output * @param ctx application context */ public static String showIp6tablesRules(Context ctx) { try { final StringBuilder res = new StringBuilder(); setIpTablePath(ctx,true); List<String> listCommands = new ArrayList<String>(); listCommands.add((ipPath + " -L -n")); runScriptAsRoot(ctx, listCommands, res); return res.toString(); } catch (Exception e) { alert(ctx, "error: " + e); } return ""; } /** * Display logs * @param ctx application context * @return true if the clogs were cleared */ public static boolean clearLog(Context ctx) { try { final StringBuilder res = new StringBuilder(); List<String> listCommands = new ArrayList<String>(); listCommands.add((getBusyBoxPath(ctx) + " dmesg -c >/dev/null || exit")); int code = runScriptAsRoot(ctx, listCommands, res); if (code != 0) { alert(ctx, res); return false; } return true; } catch (Exception e) { alert(ctx, "error: " + e); } return false; } public static class LogEntry { String uid; String src; String dst; int len; int spt; int dpt; int packets; int bytes; @Override public String toString() { return dst + ":" + src+ ":" + len + ":"+ packets; } } /** * Display logs * @param ctx application context */ public static String showLog(Context ctx) { try { StringBuilder res = new StringBuilder(); StringBuilder output = new StringBuilder(); String busybox = getBusyBoxPath(ctx); String grep = busybox + " grep"; List<String> listCommands = new ArrayList<String>(); listCommands.add(getBusyBoxPath(ctx) + "dmesg | " + grep +" {AFL}"); int code = runScriptAsRoot(ctx, listCommands, res); //int code = runScriptAsRoot(ctx, "cat /proc/kmsg", res); if (code != 0) { if (res.length() == 0) { output.append(ctx.getString(R.string.no_log)); } return output.toString(); } final BufferedReader r = new BufferedReader(new StringReader(res.toString())); final Integer unknownUID = -99; res = new StringBuilder(); String line; int start, end; Integer appid; final SparseArray<LogInfo> map = new SparseArray<LogInfo>(); LogInfo loginfo = null; while ((line = r.readLine()) != null) { if (line.indexOf("{AFL}") == -1) continue; appid = unknownUID; if (((start=line.indexOf("UID=")) != -1) && ((end=line.indexOf(" ", start)) != -1)) { appid = Integer.parseInt(line.substring(start+4, end)); } loginfo = map.get(appid); if (loginfo == null) { loginfo = new LogInfo(); map.put(appid, loginfo); } loginfo.totalBlocked += 1; if (((start=line.indexOf("DST=")) != -1) && ((end=line.indexOf(" ", start)) != -1)) { String dst = line.substring(start+4, end); if (loginfo.dstBlocked.containsKey(dst)) { loginfo.dstBlocked.put(dst, loginfo.dstBlocked.get(dst) + 1); } else { loginfo.dstBlocked.put(dst, 1); } } } final List<PackageInfoData> apps = getApps(ctx,null); Integer id; String appName = ""; int appId = -1; int totalBlocked; for(int i = 0; i < map.size(); i++) { StringBuilder address = new StringBuilder(); id = map.keyAt(i); if (id != unknownUID) { for (PackageInfoData app : apps) { if (app.uid == id) { appId = id; appName = app.names.get(0); break; } } } else { appName = "Kernel"; } loginfo = map.valueAt(i); totalBlocked = loginfo.totalBlocked; if (loginfo.dstBlocked.size() > 0) { for (String dst : loginfo.dstBlocked.keySet()) { address.append( dst + "(" + loginfo.dstBlocked.get(dst) + ")"); address.append("\n"); } } res.append("AppID :\t" + appId + "\n" + ctx.getString(R.string.LogAppName) +":\t" + appName + "\n" + ctx.getString(R.string.LogPackBlock) + ":\t" + totalBlocked + "\n"); res.append(address.toString()); res.append("\n\t---------\n"); } if (res.length() == 0) { res.append(ctx.getString(R.string.no_log)); } return res.toString(); //return output.toString(); //alert(ctx, res); } catch (Exception e) { alert(ctx, "error: " + e); } return ""; } /*public static void parseResult(String result) { int pos = 0; String src, dst, len, uid; final BufferedReader r = new BufferedReader(new StringReader(result.toString())); String line; try { while ((line = r.readLine()) != null) { int newline = result.indexOf("\n", pos); pos = line.indexOf("SRC=", pos); //if(pos == -1) continue; int space = line.indexOf(" ", pos); //if(space == -1) continue; src = line.substring(pos + 4, space); pos = line.indexOf("DST=", pos); //if(pos == -1) continue; space = line.indexOf(" ", pos); // if(space == -1) continue; dst = line.substring(pos + 4, space); pos = line.indexOf("LEN=", pos); //if(pos == -1) continue; space = line.indexOf(" ", pos); //if(space == -1) continue; len = line.substring(pos + 4, space); pos = line.indexOf("UID=", pos); //if(pos == -1) continue; space = line.indexOf(" ", pos); //if(space == -1) continue; uid = line.substring(pos + 4, space); LogEntry entry = logEntriesHash.get(uid); if(entry == null) entry = new LogEntry(); entry.uid = uid; entry.src = src; entry.dst = dst; entry.len = new Integer(len).intValue(); entry.packets++; entry.bytes += entry.len * 8; logEntriesHash.put(uid, entry); logEntriesList.add(entry); } } catch (NumberFormatException e) { } catch (IOException e) { } }*/
private static boolean applyIptablesRulesImpl(final Context ctx, List<Integer> uidsWifi, List<Integer> uids3g, List<Integer> uidsRoam, List<Integer> uidsVPN, List<Integer> uidsLAN, final boolean showErrors) { if (ctx == null) { return false; } assertBinaries(ctx, showErrors); final SharedPreferences appprefs = PreferenceManager.getDefaultSharedPreferences(ctx); final InterfaceDetails cfg = InterfaceTracker.getCurrentCfg(ctx); final boolean enableVPN = appprefs.getBoolean("enableVPN", false); final boolean enableLAN = appprefs.getBoolean("enableLAN", false) && !cfg.isTethered; final boolean enableRoam = appprefs.getBoolean("enableRoam", true); final SharedPreferences prefs = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); final boolean whitelist = prefs.getString(PREF_MODE, MODE_WHITELIST).equals(MODE_WHITELIST); final boolean blacklist = !whitelist; final boolean logenabled = appprefs.getBoolean("enableFirewallLog",true); //final boolean isVPNEnabled = appprefs.getBoolean("enableVPNProfile",false); //String iptargets = getTargets(ctx); StringBuilder customScript = new StringBuilder(ctx.getSharedPreferences(Api.PREFS_NAME, Context.MODE_PRIVATE).getString(Api.PREF_CUSTOMSCRIPT, "")); try { int code; String busybox = getBusyBoxPath(ctx); String grep = busybox + " grep"; final List<String> listCommands = new ArrayList<String>(); listCommands.add(ipPath + " -L afwall >/dev/null 2>/dev/null || " + ipPath + " --new afwall || exit" ); listCommands.add(ipPath + " -L afwall-3g >/dev/null 2>/dev/null ||" + ipPath + "--new afwall-3g || exit" ); listCommands.add(ipPath + " -L afwall-wifi >/dev/null 2>/dev/null || " + ipPath + " --new afwall-wifi || exit" ); listCommands.add(ipPath + " -L afwall-lan >/dev/null 2>/dev/null || " + ipPath + " --new afwall-lan || exit" ); listCommands.add(ipPath + " -L afwall-vpn >/dev/null 2>/dev/null || " + ipPath + " --new afwall-vpn || exit" ); listCommands.add(ipPath + " -L afwall-reject >/dev/null 2>/dev/null || " + ipPath + " --new afwall-reject || exit" ); listCommands.add(ipPath + " -L OUTPUT | " + grep + " -q afwall || " + ipPath + " -A OUTPUT -j afwall || exit"); listCommands.add(ipPath + " -F afwall || exit " ); listCommands.add(ipPath + " -F afwall-3g || exit "); listCommands.add(ipPath + " -F afwall-wifi || exit "); listCommands.add(ipPath + " -F afwall-lan || exit "); listCommands.add(ipPath + " -F afwall-vpn || exit "); listCommands.add(ipPath + " -F afwall-reject || exit 10"); listCommands.add(ipPath + " -A afwall -m owner --uid-owner 0 -p udp --dport 53 -j RETURN || exit"); listCommands.add((ipPath + " -D OUTPUT -j afwall")); listCommands.add((ipPath + " -I OUTPUT 1 -j afwall")); //this will make sure the only afwall will be able to control the OUTPUT chain, regardless of any firewall installed! //listCommands.add((ipPath + " --flush OUTPUT || exit")); // Check if logging is enabled if (logenabled) { listCommands.add((ipPath + " -A afwall-reject -m limit --limit 1000/min -j LOG --log-prefix \"{AFL}\" --log-level 4 --log-uid ")); } listCommands.add((ipPath + " -A afwall-reject -j REJECT || exit")); //now reenable everything after restart listCommands.add((ipPath + " -P INPUT ACCEPT")); listCommands.add((ipPath + " -P OUTPUT ACCEPT")); listCommands.add((ipPath + " -P FORWARD ACCEPT")); if (customScript.length() > 0) { replaceAll(customScript, "$IPTABLES", " " +ipPath ); listCommands.add(customScript.toString()); } for (final String itf : ITFS_3G) { listCommands.add((ipPath + " -A afwall -o ".concat(itf).concat(" -j afwall-3g || exit"))); } for (final String itf : ITFS_WIFI) { if(enableLAN) { if(setv6 && !cfg.lanMaskV6.equals("")) { listCommands.add(ipPath + " -A afwall -d " + cfg.lanMaskV6 + " -o " + itf + " -j afwall-lan || exit"); listCommands.add(ipPath + " -A afwall '!' -d " + cfg.lanMaskV6 + " -o " + itf+ " -j afwall-wifi || exit"); } if(!setv6 && !cfg.lanMaskV4.equals("")) { listCommands.add(ipPath + " -A afwall -d " + cfg.lanMaskV4 + " -o " + itf + " -j afwall-lan || exit"); listCommands.add(ipPath + " -A afwall '!' -d "+ cfg.lanMaskV4 + " -o " + itf + " -j afwall-wifi || exit"); } } else { listCommands.add((ipPath + " -A afwall -o ".concat(itf).concat(" -j afwall-wifi || exit"))); } } if(enableVPN) { for (final String itf : ITFS_VPN) { listCommands.add((ipPath + " -A afwall -o ".concat(itf).concat(" -j afwall-vpn || exit"))); } } final String targetRule = (whitelist ? "RETURN" : "afwall-reject"); final boolean any_3g = uids3g.indexOf(SPECIAL_UID_ANY) >= 0; final boolean any_wifi = uidsWifi.indexOf(SPECIAL_UID_ANY) >= 0; final boolean any_lan = uidsLAN.indexOf(SPECIAL_UID_ANY) >= 0; final boolean any_vpn = uidsVPN.indexOf(SPECIAL_UID_ANY) >= 0; if (whitelist && !any_wifi) { addRuleForUsers(listCommands, new String[]{"dhcp","wifi"}, ipPath + " -A afwall-wifi", "-j RETURN || exit"); } //now 3g rules! if (any_3g) { if (blacklist) { /* block any application on this interface */ listCommands.add((ipPath + " -A afwall-3g -j "+(targetRule)+(" || exit"))); } } else { /* release/block individual applications on this interface */ if(cfg.isRoaming && enableRoam) { for (final Integer uid : uidsRoam) { if (uid !=null && uid >= 0) listCommands.add((ipPath + " -A afwall-3g -m owner --uid-owner "+(uid)+(" -j ")+(targetRule)+(" || exit"))); } } else { for (final Integer uid : uids3g) { if (uid !=null && uid >= 0) listCommands.add((ipPath + " -A afwall-3g -m owner --uid-owner "+(uid)+(" -j ")+(targetRule)+(" || exit"))); } } } //now wifi rules! //--if the wifi interface is down, reject all outbound packets without logging them-- //revert back to old approach if (any_wifi) { if (blacklist) { /* block any application on this interface */ listCommands.add((ipPath + " -A afwall-wifi -j "+(targetRule)+(" || exit"))); } } else { /* release/block individual applications on this interface */ for (final Integer uid : uidsWifi) { if (uid !=null && uid >= 0) listCommands.add((ipPath + " -A afwall-wifi -m owner --uid-owner "+(uid)+(" -j ")+(targetRule)+(" || exit"))); } } //now LAN rules! if (enableLAN) { if (!cfg.allowWifi) { listCommands.add(ipPath + " -A afwall-lan -j REJECT || exit"); } else if (any_lan) { if (blacklist) { /* block any application on this interface */ listCommands.add((ipPath + " -A afwall-lan -j "+(targetRule)+(" || exit"))); } } else { /* release/block individual applications on this interface */ for (final Integer uid : uidsLAN) { if (uid != null && uid >= 0) listCommands.add((ipPath + " -A afwall-lan -m owner --uid-owner " + uid + " -j " + targetRule + " || exit")); } // NOTE: we still need to open a hole for DNS lookups // This falls through to the wifi rules if the app is not whitelisted for LAN access if (whitelist) { listCommands.add(ipPath + " -A afwall-lan -p udp --dport 53 -j RETURN || exit"); } } } //now vpn rules! if(enableVPN) { if (any_vpn) { if (blacklist) { /* block any application on this interface */ listCommands.add((ipPath + " -A afwall-vpn -j "+(targetRule)+(" || exit"))); } } else { /* release/block individual applications on this interface */ for (final Integer uid : uidsVPN) { if (uid !=null && uid >= 0) listCommands.add((ipPath + " -A afwall-vpn -m owner --uid-owner "+(uid)+(" -j ")+(targetRule)+(" || exit"))); } } } // note that this can only blacklist DNS/DHCP services, not all tethered traffic if (cfg.isTethered && ((blacklist && (any_wifi || any_3g)) || (uids3g.indexOf(SPECIAL_UID_TETHER) >= 0) || (uidsWifi.indexOf(SPECIAL_UID_TETHER) >= 0))) { String users[] = { "root", "nobody" }; String action = " -j " + targetRule + " || exit"; // DHCP replies to client addRuleForUsers(listCommands, users, ipPath + " -A afwall-wifi","-p udp --sport=67 --dport=68" + action); // DNS replies to client addRuleForUsers(listCommands, users, ipPath + " -A afwall-wifi","-p udp --sport=53" + action); addRuleForUsers(listCommands, users, ipPath + " -A afwall-wifi","-p tcp --sport=53" + action); // DNS requests to upstream servers addRuleForUsers(listCommands, users, ipPath + " -A afwall-3g","-p udp --dport=53" + action); addRuleForUsers(listCommands, users, ipPath + " -A afwall-3g","-p tcp --dport=53" + action); } if (whitelist) { if (!any_3g) { if (uids3g.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-3g -m owner --uid-owner 0:999999999 -j afwall-reject || exit")); } else { listCommands.add((ipPath + " -A afwall-3g -j afwall-reject || exit")); } } if (!any_wifi) { if (uidsWifi.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-wifi -m owner --uid-owner 0:999999999 -j afwall-reject || exit")); } else { listCommands.add((ipPath + " -A afwall-wifi -j afwall-reject || exit")); } } if (enableVPN && !any_vpn) { if (uidsVPN.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-vpn -m owner --uid-owner 0:999999999 -j afwall-reject || exit")); } else { listCommands.add((ipPath + " -A afwall-vpn -j afwall-reject || exit")); } } if (enableLAN && !any_lan) { if (uidsLAN.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-lan -m owner --uid-owner 0:999999999 -j afwall-reject || exit")); } else { listCommands.add((ipPath + " -A afwall-lan -j afwall-reject || exit")); } } } else { if (uids3g.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-3g -m owner --uid-owner 0:999999999 -j RETURN || exit")); listCommands.add((ipPath + " -A afwall-3g -j afwall-reject || exit")); } if (uidsWifi.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-wifi -m owner --uid-owner 0:999999999 -j RETURN || exit")); listCommands.add((ipPath + " -A afwall-wifi -j afwall-reject || exit")); } if (enableVPN && uidsVPN.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-vpn -m owner --uid-owner 0:999999999 -j RETURN || exit")); listCommands.add((ipPath + " -A afwall-vpn -j afwall-reject || exit")); } if (enableLAN && uidsLAN.indexOf(SPECIAL_UID_KERNEL) >= 0) { listCommands.add((ipPath + " -A afwall-lan -m owner --uid-owner 0:999999999 -j RETURN || exit")); listCommands.add((ipPath + " -A afwall-lan -j afwall-reject || exit")); } } //active defence final StringBuilder res = new StringBuilder(); code = runScriptAsRoot(ctx, listCommands, res); if (showErrors && code != 0) { String msg = res.toString(); // Remove unnecessary help message from output if (msg.indexOf("\nTry `iptables -h' or 'iptables --help' for more information.") != -1) { msg = msg.replace("\nTry `iptables -h' or 'iptables --help' for more information.", ""); } alert(ctx, ctx.getString(R.string.error_apply) + code + "\n\n" + msg.trim() ); } else { return true; } } catch (Exception e) { Log.e(TAG, "Exception while applying rules: " + e.getMessage()); if (showErrors) alert(ctx, ctx.getString(R.string.error_refresh) + e); } return false; } private static List<Integer> getUidListFromPref(Context ctx,final String pks) { initSpecial(); final PackageManager pm = ctx.getPackageManager(); final List<Integer> uids = new ArrayList<Integer>(); final StringTokenizer tok = new StringTokenizer(pks, "|"); while (tok.hasMoreTokens()) { final String pkg = tok.nextToken(); if (pkg != null && pkg.length() > 0) { try { if (pkg.startsWith("dev.afwall.special")) { uids.add(specialApps.get(pkg)); } else { uids.add(pm.getApplicationInfo(pkg, 0).uid); } } catch (Exception ex) { } } } Collections.sort(uids); return uids; } /** * Purge and re-add all saved rules (not in-memory ones). * This is much faster than just calling "applyIptablesRules", since it don't need to read installed applications. * @param ctx application context (mandatory) * @param showErrors indicates if errors should be alerted */ public static boolean applySavedIptablesRules(Context ctx, boolean showErrors) { if (ctx == null) { return false; } initSpecial(); final SharedPreferences prefs = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); final String savedPkg_wifi_uid = prefs.getString(PREF_WIFI_PKG_UIDS, ""); final String savedPkg_3g_uid = prefs.getString(PREF_3G_PKG_UIDS, ""); final String savedPkg_roam_uid = prefs.getString(PREF_ROAMING_PKG_UIDS, ""); final String savedPkg_vpn_uid = prefs.getString(PREF_VPN_PKG_UIDS, ""); final String savedPkg_lan_uid = prefs.getString(PREF_LAN_PKG_UIDS, ""); final SharedPreferences appprefs = PreferenceManager.getDefaultSharedPreferences(ctx); final boolean enableIPv6 = appprefs.getBoolean("enableIPv6", false); boolean returnValue = false; setIpTablePath(ctx,false); returnValue = applyIptablesRulesImpl(ctx, getListFromPref(savedPkg_wifi_uid), getListFromPref(savedPkg_3g_uid), getListFromPref(savedPkg_roam_uid), getListFromPref(savedPkg_vpn_uid), getListFromPref(savedPkg_lan_uid), showErrors); if (enableIPv6) { setIpTablePath(ctx,true); returnValue = applyIptablesRulesImpl(ctx, getListFromPref(savedPkg_wifi_uid), getListFromPref(savedPkg_3g_uid), getListFromPref(savedPkg_roam_uid), getListFromPref(savedPkg_vpn_uid), getListFromPref(savedPkg_lan_uid), showErrors); } return returnValue; } /** * Purge and re-add all rules. * @param ctx application context (mandatory) * @param showErrors indicates if errors should be alerted */ public static boolean applyIptablesRules(Context ctx, boolean showErrors) { if (ctx == null) { return false; } saveRules(ctx); return applySavedIptablesRules(ctx, showErrors); } /** * Save current rules using the preferences storage. * @param ctx application context (mandatory) */ public static void saveRules(Context ctx) { final SharedPreferences defaultPrefs = PreferenceManager.getDefaultSharedPreferences(ctx); final boolean enableVPN = defaultPrefs.getBoolean("enableVPN", false); final boolean enableLAN = defaultPrefs.getBoolean("enableLAN", false); final boolean enableRoam = defaultPrefs.getBoolean("enableRoam", true); final SharedPreferences prefs = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); final List<PackageInfoData> apps = getApps(ctx,null); // Builds a pipe-separated list of names final StringBuilder newpkg_wifi = new StringBuilder(); final StringBuilder newpkg_3g = new StringBuilder(); final StringBuilder newpkg_roam = new StringBuilder(); final StringBuilder newpkg_vpn = new StringBuilder(); final StringBuilder newpkg_lan = new StringBuilder(); for (int i=0; i<apps.size(); i++) { if (apps.get(i).selected_wifi) { if (newpkg_wifi.length() != 0) newpkg_wifi.append('|'); newpkg_wifi.append(apps.get(i).uid); } if (apps.get(i).selected_3g) { if (newpkg_3g.length() != 0) newpkg_3g.append('|'); newpkg_3g.append(apps.get(i).uid); } if (enableRoam && apps.get(i).selected_roam) { if (newpkg_roam.length() != 0) newpkg_roam.append('|'); newpkg_roam.append(apps.get(i).uid); } if (enableVPN && apps.get(i).selected_vpn) { if (newpkg_vpn.length() != 0) newpkg_vpn.append('|'); newpkg_vpn.append(apps.get(i).uid); } if (enableLAN && apps.get(i).selected_lan) { if (newpkg_lan.length() != 0) newpkg_lan.append('|'); newpkg_lan.append(apps.get(i).uid); } } // save the new list of UIDs final Editor edit = prefs.edit(); edit.putString(PREF_WIFI_PKG_UIDS, newpkg_wifi.toString()); edit.putString(PREF_3G_PKG_UIDS, newpkg_3g.toString()); edit.putString(PREF_ROAMING_PKG_UIDS, newpkg_roam.toString()); edit.putString(PREF_VPN_PKG_UIDS, newpkg_vpn.toString()); edit.putString(PREF_LAN_PKG_UIDS, newpkg_lan.toString()); edit.commit(); } /** * Purge all iptables rules. * @param ctx mandatory context * @param showErrors indicates if errors should be alerted * @return true if the rules were purged */ public static boolean purgeVPNRules(Context ctx, boolean showErrors) { final StringBuilder res = new StringBuilder(); try { assertBinaries(ctx, showErrors); // Custom "shutdown" script setIpTablePath(ctx,false); List<String> listCommands = new ArrayList<String>(); listCommands.add((ipPath + " -F afwall-vpn")); int code = runScriptAsRoot(ctx, listCommands, res); if (code == -1) { if(showErrors) alert(ctx, ctx.getString(R.string.error_purge) + code + "\n" + res); return false; } final SharedPreferences appprefs = PreferenceManager .getDefaultSharedPreferences(ctx); final boolean enableIPv6 = appprefs.getBoolean("enableIPv6", false); if (enableIPv6) { setIpTablePath(ctx, true); listCommands.clear(); listCommands.add((ipPath + " -F afwall-vpn")); code = runScriptAsRoot(ctx, listCommands, res); if (code == -1) { if (showErrors) alert(ctx, ctx.getString(R.string.error_purge) + code + "\n" + res); return false; } } return true; } catch (Exception e) { return false; } } /** * Purge all iptables rules. * @param ctx mandatory context * @param showErrors indicates if errors should be alerted * @return true if the rules were purged */ public static boolean purgeIptables(Context ctx, boolean showErrors) { try { assertBinaries(ctx, showErrors); // Custom "shutdown" script setIpTablePath(ctx,false); purgeRules(ctx,showErrors); final SharedPreferences appprefs = PreferenceManager.getDefaultSharedPreferences(ctx); final boolean enableIPv6 = appprefs.getBoolean("enableIPv6", false); if(enableIPv6) { setIpTablePath(ctx,true); purgeRules(ctx,showErrors); } return true; } catch (Exception e) { return false; } } private static boolean purgeRules(Context ctx,boolean showErrors) throws IOException { boolean returnVal = true; final StringBuilder res = new StringBuilder(); List<String> listCommands = new ArrayList<String>(); listCommands.add((ipPath + " -F afwall")); listCommands.add((ipPath + " -F afwall-reject")); listCommands.add((ipPath + " -F afwall-3g")); listCommands.add((ipPath + " -F afwall-wifi")); listCommands.add((ipPath + " -D OUTPUT -j afwall || exit")); final SharedPreferences defaultPrefs = PreferenceManager.getDefaultSharedPreferences(ctx); StringBuilder customScript = new StringBuilder(ctx.getSharedPreferences(Api.PREFS_NAME, Context.MODE_PRIVATE).getString(Api.PREF_CUSTOMSCRIPT2, "")); final boolean enableVPN = defaultPrefs.getBoolean("enableVPN", false); final boolean enableLAN = defaultPrefs.getBoolean("enableLAN", false); if(enableVPN) { listCommands.add((ipPath + " -F afwall-vpn")); } if(enableLAN) { listCommands.add((ipPath + " -F afwall-lan")); } if (customScript.length() > 0) { replaceAll(customScript, "$IPTABLES", " " +ipPath ); listCommands.add(customScript.toString()); } int code = runScriptAsRoot(ctx, listCommands, res); if (code == -1) { if(showErrors) alert(ctx, ctx.getString(R.string.error_purge) + code + "\n" + res); returnVal = false; } return returnVal; } /** * Display iptables rules output * @param ctx application context */ public static String showIptablesRules(Context ctx) { try { final StringBuilder res = new StringBuilder(); setIpTablePath(ctx,false); List<String> listCommands = new ArrayList<String>(); listCommands.add((ipPath + " -L -n")); runScriptAsRoot(ctx, listCommands, res); return res.toString(); } catch (Exception e) { alert(ctx, "error: " + e); } return ""; } /** * Display iptables rules output * @param ctx application context */ public static String showIp6tablesRules(Context ctx) { try { final StringBuilder res = new StringBuilder(); setIpTablePath(ctx,true); List<String> listCommands = new ArrayList<String>(); listCommands.add((ipPath + " -L -n")); runScriptAsRoot(ctx, listCommands, res); return res.toString(); } catch (Exception e) { alert(ctx, "error: " + e); } return ""; } /** * Display logs * @param ctx application context * @return true if the clogs were cleared */ public static boolean clearLog(Context ctx) { try { final StringBuilder res = new StringBuilder(); List<String> listCommands = new ArrayList<String>(); listCommands.add((getBusyBoxPath(ctx) + " dmesg -c >/dev/null || exit")); int code = runScriptAsRoot(ctx, listCommands, res); if (code != 0) { alert(ctx, res); return false; } return true; } catch (Exception e) { alert(ctx, "error: " + e); } return false; } public static class LogEntry { String uid; String src; String dst; int len; int spt; int dpt; int packets; int bytes; @Override public String toString() { return dst + ":" + src+ ":" + len + ":"+ packets; } } /** * Display logs * @param ctx application context */ public static String showLog(Context ctx) { try { StringBuilder res = new StringBuilder(); StringBuilder output = new StringBuilder(); String busybox = getBusyBoxPath(ctx); String grep = busybox + " grep"; List<String> listCommands = new ArrayList<String>(); listCommands.add(getBusyBoxPath(ctx) + "dmesg | " + grep +" {AFL}"); int code = runScriptAsRoot(ctx, listCommands, res); //int code = runScriptAsRoot(ctx, "cat /proc/kmsg", res); if (code != 0) { if (res.length() == 0) { output.append(ctx.getString(R.string.no_log)); } return output.toString(); } final BufferedReader r = new BufferedReader(new StringReader(res.toString())); final Integer unknownUID = -99; res = new StringBuilder(); String line; int start, end; Integer appid; final SparseArray<LogInfo> map = new SparseArray<LogInfo>(); LogInfo loginfo = null; while ((line = r.readLine()) != null) { if (line.indexOf("{AFL}") == -1) continue; appid = unknownUID; if (((start=line.indexOf("UID=")) != -1) && ((end=line.indexOf(" ", start)) != -1)) { appid = Integer.parseInt(line.substring(start+4, end)); } loginfo = map.get(appid); if (loginfo == null) { loginfo = new LogInfo(); map.put(appid, loginfo); } loginfo.totalBlocked += 1; if (((start=line.indexOf("DST=")) != -1) && ((end=line.indexOf(" ", start)) != -1)) { String dst = line.substring(start+4, end); if (loginfo.dstBlocked.containsKey(dst)) { loginfo.dstBlocked.put(dst, loginfo.dstBlocked.get(dst) + 1); } else { loginfo.dstBlocked.put(dst, 1); } } } final List<PackageInfoData> apps = getApps(ctx,null); Integer id; String appName = ""; int appId = -1; int totalBlocked; for(int i = 0; i < map.size(); i++) { StringBuilder address = new StringBuilder(); id = map.keyAt(i); if (id != unknownUID) { for (PackageInfoData app : apps) { if (app.uid == id) { appId = id; appName = app.names.get(0); break; } } } else { appName = "Kernel"; } loginfo = map.valueAt(i); totalBlocked = loginfo.totalBlocked; if (loginfo.dstBlocked.size() > 0) { for (String dst : loginfo.dstBlocked.keySet()) { address.append( dst + "(" + loginfo.dstBlocked.get(dst) + ")"); address.append("\n"); } } res.append("AppID :\t" + appId + "\n" + ctx.getString(R.string.LogAppName) +":\t" + appName + "\n" + ctx.getString(R.string.LogPackBlock) + ":\t" + totalBlocked + "\n"); res.append(address.toString()); res.append("\n\t---------\n"); } if (res.length() == 0) { res.append(ctx.getString(R.string.no_log)); } return res.toString(); //return output.toString(); //alert(ctx, res); } catch (Exception e) { alert(ctx, "error: " + e); } return ""; } /*public static void parseResult(String result) { int pos = 0; String src, dst, len, uid; final BufferedReader r = new BufferedReader(new StringReader(result.toString())); String line; try { while ((line = r.readLine()) != null) { int newline = result.indexOf("\n", pos); pos = line.indexOf("SRC=", pos); //if(pos == -1) continue; int space = line.indexOf(" ", pos); //if(space == -1) continue; src = line.substring(pos + 4, space); pos = line.indexOf("DST=", pos); //if(pos == -1) continue; space = line.indexOf(" ", pos); // if(space == -1) continue; dst = line.substring(pos + 4, space); pos = line.indexOf("LEN=", pos); //if(pos == -1) continue; space = line.indexOf(" ", pos); //if(space == -1) continue; len = line.substring(pos + 4, space); pos = line.indexOf("UID=", pos); //if(pos == -1) continue; space = line.indexOf(" ", pos); //if(space == -1) continue; uid = line.substring(pos + 4, space); LogEntry entry = logEntriesHash.get(uid); if(entry == null) entry = new LogEntry(); entry.uid = uid; entry.src = src; entry.dst = dst; entry.len = new Integer(len).intValue(); entry.packets++; entry.bytes += entry.len * 8; logEntriesHash.put(uid, entry); logEntriesList.add(entry); } } catch (NumberFormatException e) { } catch (IOException e) { } }*/
diff --git a/src/vooga/fighter/model/loaders/ObjectLoader.java b/src/vooga/fighter/model/loaders/ObjectLoader.java index 4e3addb6..3932e240 100644 --- a/src/vooga/fighter/model/loaders/ObjectLoader.java +++ b/src/vooga/fighter/model/loaders/ObjectLoader.java @@ -1,120 +1,122 @@ package vooga.fighter.model.loaders; import java.awt.Dimension; import java.awt.Rectangle; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import util.Pixmap; import vooga.fighter.model.objects.GameObject; import vooga.fighter.model.utils.State; /** * Abstract class with shared methods that all ObjectLoader-derived classes may need. * * @author Dayvid, alanni * */ public abstract class ObjectLoader { private File myObjectFile; private Document myDocument; /** * Points to the xml file that the loader will be parsing * * @param objectPath */ public ObjectLoader (String objectPath) { myObjectFile = new File(objectPath); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; try { dBuilder = dbFactory.newDocumentBuilder(); myDocument = dBuilder.parse(myObjectFile); myDocument.getDocumentElement().normalize(); } catch (Exception e) { myDocument = null; e.printStackTrace(); } } /** * Loads object based on the id given * @param id */ public abstract void load(String Name); /** * Returns the xml document which the loader points to * @return */ protected Document getDocument() { return myDocument; } /** * Returns the string attribute value of the specified tag for the specified mode. * @param node * @param tag * @return */ protected String getAttributeValue(Node node, String tag) { return node.getAttributes().getNamedItem(tag).getTextContent(); } /** * Returns the value of the child node with the specified tag for the element. * @param tag * @param element * @return */ protected String getChildValue(String tag, Element element) { NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes(); Node node = (Node) nodes.item(0); return node.getNodeValue(); } /** * Loads and adds states for the GameObject. * @param stateNodes * @param myObject */ protected void addStates(NodeList stateNodes, GameObject myObject) { for (int i = 0; i < stateNodes.getLength(); i++) { Element state = (Element) stateNodes.item(i); String stateName = getAttributeValue(stateNodes.item(i), "stateName"); NodeList frameNodes = state.getElementsByTagName("frame"); State newState = new State(myObject, frameNodes.getLength()); getImageAndHitboxProperties(frameNodes, newState); myObject.addState(stateName, newState); } } /** * Loads frames and states for the objects */ protected void getImageAndHitboxProperties(NodeList frameNodes, State newState){ for (int j = 0; j < frameNodes.getLength(); j++) { - newState.populateImage(new Pixmap(getAttributeValue(frameNodes.item(j), "image")), j); + if (frameNodes.item(j).getAttributes().getNamedItem("image") != null) { + newState.populateImage(new Pixmap(getAttributeValue(frameNodes.item(j), "image")), j); + } Element frame = (Element) frameNodes.item(j); NodeList hitboxNodes = frame.getElementsByTagName("hitbox"); for (int k=0; k<hitboxNodes.getLength(); k++){ newState.populateRectangle(new Rectangle(Integer.parseInt(getAttributeValue(hitboxNodes.item(k), "cornerX")), Integer.parseInt(getAttributeValue(hitboxNodes.item(k), "cornerY")), Integer.parseInt(getAttributeValue(hitboxNodes.item(k), "rectX")), Integer.parseInt(getAttributeValue(hitboxNodes.item(k), "rectY"))), j); newState.populateSize(new Dimension(Integer.parseInt(getAttributeValue(hitboxNodes.item(k), "rectX")), Integer.parseInt(getAttributeValue(hitboxNodes.item(k), "rectY"))), j); } } } }
true
true
protected void getImageAndHitboxProperties(NodeList frameNodes, State newState){ for (int j = 0; j < frameNodes.getLength(); j++) { newState.populateImage(new Pixmap(getAttributeValue(frameNodes.item(j), "image")), j); Element frame = (Element) frameNodes.item(j); NodeList hitboxNodes = frame.getElementsByTagName("hitbox"); for (int k=0; k<hitboxNodes.getLength(); k++){ newState.populateRectangle(new Rectangle(Integer.parseInt(getAttributeValue(hitboxNodes.item(k), "cornerX")), Integer.parseInt(getAttributeValue(hitboxNodes.item(k), "cornerY")), Integer.parseInt(getAttributeValue(hitboxNodes.item(k), "rectX")), Integer.parseInt(getAttributeValue(hitboxNodes.item(k), "rectY"))), j); newState.populateSize(new Dimension(Integer.parseInt(getAttributeValue(hitboxNodes.item(k), "rectX")), Integer.parseInt(getAttributeValue(hitboxNodes.item(k), "rectY"))), j); } } }
protected void getImageAndHitboxProperties(NodeList frameNodes, State newState){ for (int j = 0; j < frameNodes.getLength(); j++) { if (frameNodes.item(j).getAttributes().getNamedItem("image") != null) { newState.populateImage(new Pixmap(getAttributeValue(frameNodes.item(j), "image")), j); } Element frame = (Element) frameNodes.item(j); NodeList hitboxNodes = frame.getElementsByTagName("hitbox"); for (int k=0; k<hitboxNodes.getLength(); k++){ newState.populateRectangle(new Rectangle(Integer.parseInt(getAttributeValue(hitboxNodes.item(k), "cornerX")), Integer.parseInt(getAttributeValue(hitboxNodes.item(k), "cornerY")), Integer.parseInt(getAttributeValue(hitboxNodes.item(k), "rectX")), Integer.parseInt(getAttributeValue(hitboxNodes.item(k), "rectY"))), j); newState.populateSize(new Dimension(Integer.parseInt(getAttributeValue(hitboxNodes.item(k), "rectX")), Integer.parseInt(getAttributeValue(hitboxNodes.item(k), "rectY"))), j); } } }
diff --git a/spring-batch-admin-manager/src/test/java/org/springframework/batch/admin/web/views/JobExecutionViewTests.java b/spring-batch-admin-manager/src/test/java/org/springframework/batch/admin/web/views/JobExecutionViewTests.java index 347648c..246559d 100644 --- a/spring-batch-admin-manager/src/test/java/org/springframework/batch/admin/web/views/JobExecutionViewTests.java +++ b/spring-batch-admin-manager/src/test/java/org/springframework/batch/admin/web/views/JobExecutionViewTests.java @@ -1,107 +1,107 @@ /* * Copyright 2009-2010 the original author or authors. * * 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 org.springframework.batch.admin.web.views; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.HashMap; import java.util.TimeZone; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.batch.admin.web.JobExecutionInfo; import org.springframework.batch.admin.web.StepExecutionInfo; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.test.MetaDataInstanceFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.WebApplicationContextLoader; import org.springframework.validation.BindingResult; import org.springframework.validation.MapBindingResult; import org.springframework.web.servlet.View; @ContextConfiguration(loader = WebApplicationContextLoader.class, inheritLocations = false, locations = "AbstractManagerViewTests-context.xml") @RunWith(SpringJUnit4ClassRunner.class) public class JobExecutionViewTests extends AbstractManagerViewTests { private final HashMap<String, Object> model = new HashMap<String, Object>(); @Autowired @Qualifier("jobs/execution") private View view; @Test public void testLaunchViewWithJobExecution() throws Exception { JobExecution jobExecution = MetaDataInstanceFactory.createJobExecutionWithStepExecutions(123L, Arrays.asList( "foo", "bar")); model.put("jobExecutionInfo", new JobExecutionInfo(jobExecution, TimeZone.getTimeZone("GMT"))); model.put("stepExecutionInfos", Arrays.asList(new StepExecutionInfo(jobExecution.getStepExecutions().iterator() .next(), TimeZone.getTimeZone("GMT")), new StepExecutionInfo("job", 123L, "bar", TimeZone.getTimeZone("GMT")))); model.put(BindingResult.MODEL_KEY_PREFIX + "stopRequest", new MapBindingResult(model, "stopRequest")); view.render(model, request, response); String content = response.getContentAsString(); // System.err.println(content); assertTrue(content.contains("Details for Job Execution")); assertTrue(content.contains("<input type=\"hidden\" name=\"_method\" value=\"DELETE\"/>")); assertTrue(content.contains("<a href=\"/batch/jobs/executions/123/steps\"/>")); - assertTrue(content.contains("<a href=\"/batch/jobs/executions/123/steps/1234\"/>")); + assertTrue(content.contains("<a href=\"/batch/jobs/executions/123/steps/1234/progress\"/>")); assertTrue(content.contains("<td>ID</td>")); } @Test public void testLaunchViewWithNotRestartable() throws Exception { JobExecution execution = MetaDataInstanceFactory.createJobExecution("job", 12L, 123L, "foo=bar"); execution.setStatus(BatchStatus.STARTED); model.put("jobExecutionInfo", new JobExecutionInfo(execution, TimeZone.getTimeZone("GMT"))); view.render(model, request, response); String content = response.getContentAsString(); // System.err.println(content); assertFalse(content.contains("restartForm")); assertTrue(content.contains("<input id=\"stop\" type=\"submit\" value=\"Stop\" name=\"stop\" />")); } @Test public void testLaunchViewWithStopped() throws Exception { JobExecution execution = MetaDataInstanceFactory.createJobExecution("job", 12345L, 1233456L, "foo=bar"); execution.setStatus(BatchStatus.STOPPED); model.put("jobExecutionInfo", new JobExecutionInfo(execution, TimeZone.getTimeZone("GMT"))); view.render(model, request, response); String content = response.getContentAsString(); // System.err.println(content); assertTrue(content.contains("restartForm")); assertTrue(content.contains("/batch/jobs/job/12345/executions")); assertTrue(content.contains("/batch/jobs/executions/1233456/steps")); assertTrue(content.contains("<input id=\"stop\" type=\"submit\" value=\"Abandon\" name=\"abandon\" />")); } @Test public void testLaunchViewWithAbandonable() throws Exception { JobExecution execution = MetaDataInstanceFactory.createJobExecution("job", 12L, 123L, "foo=bar"); execution.setStatus(BatchStatus.STOPPING); model.put("jobExecutionInfo", new JobExecutionInfo(execution, TimeZone.getTimeZone("GMT"))); view.render(model, request, response); String content = response.getContentAsString(); // System.err.println(content); assertFalse(content.contains("restartForm")); assertTrue(content.contains("<input id=\"stop\" type=\"submit\" value=\"Abandon\" name=\"abandon\" />")); } }
true
true
public void testLaunchViewWithJobExecution() throws Exception { JobExecution jobExecution = MetaDataInstanceFactory.createJobExecutionWithStepExecutions(123L, Arrays.asList( "foo", "bar")); model.put("jobExecutionInfo", new JobExecutionInfo(jobExecution, TimeZone.getTimeZone("GMT"))); model.put("stepExecutionInfos", Arrays.asList(new StepExecutionInfo(jobExecution.getStepExecutions().iterator() .next(), TimeZone.getTimeZone("GMT")), new StepExecutionInfo("job", 123L, "bar", TimeZone.getTimeZone("GMT")))); model.put(BindingResult.MODEL_KEY_PREFIX + "stopRequest", new MapBindingResult(model, "stopRequest")); view.render(model, request, response); String content = response.getContentAsString(); // System.err.println(content); assertTrue(content.contains("Details for Job Execution")); assertTrue(content.contains("<input type=\"hidden\" name=\"_method\" value=\"DELETE\"/>")); assertTrue(content.contains("<a href=\"/batch/jobs/executions/123/steps\"/>")); assertTrue(content.contains("<a href=\"/batch/jobs/executions/123/steps/1234\"/>")); assertTrue(content.contains("<td>ID</td>")); }
public void testLaunchViewWithJobExecution() throws Exception { JobExecution jobExecution = MetaDataInstanceFactory.createJobExecutionWithStepExecutions(123L, Arrays.asList( "foo", "bar")); model.put("jobExecutionInfo", new JobExecutionInfo(jobExecution, TimeZone.getTimeZone("GMT"))); model.put("stepExecutionInfos", Arrays.asList(new StepExecutionInfo(jobExecution.getStepExecutions().iterator() .next(), TimeZone.getTimeZone("GMT")), new StepExecutionInfo("job", 123L, "bar", TimeZone.getTimeZone("GMT")))); model.put(BindingResult.MODEL_KEY_PREFIX + "stopRequest", new MapBindingResult(model, "stopRequest")); view.render(model, request, response); String content = response.getContentAsString(); // System.err.println(content); assertTrue(content.contains("Details for Job Execution")); assertTrue(content.contains("<input type=\"hidden\" name=\"_method\" value=\"DELETE\"/>")); assertTrue(content.contains("<a href=\"/batch/jobs/executions/123/steps\"/>")); assertTrue(content.contains("<a href=\"/batch/jobs/executions/123/steps/1234/progress\"/>")); assertTrue(content.contains("<td>ID</td>")); }
diff --git a/src/org/openstreetmap/josm/actions/SplitWayAction.java b/src/org/openstreetmap/josm/actions/SplitWayAction.java index 04ac3953..136b5558 100644 --- a/src/org/openstreetmap/josm/actions/SplitWayAction.java +++ b/src/org/openstreetmap/josm/actions/SplitWayAction.java @@ -1,295 +1,300 @@ // License: GPL. Copyright 2007 by Immanuel Scholz and others package org.openstreetmap.josm.actions; import static org.openstreetmap.josm.tools.I18n.tr; import static org.openstreetmap.josm.tools.I18n.trn; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.Map.Entry; import javax.swing.JOptionPane; import org.openstreetmap.josm.Main; import org.openstreetmap.josm.command.AddCommand; import org.openstreetmap.josm.command.ChangeCommand; import org.openstreetmap.josm.command.Command; import org.openstreetmap.josm.command.SequenceCommand; import org.openstreetmap.josm.data.SelectionChangedListener; import org.openstreetmap.josm.data.osm.DataSet; import org.openstreetmap.josm.data.osm.Node; import org.openstreetmap.josm.data.osm.OsmPrimitive; import org.openstreetmap.josm.data.osm.Relation; import org.openstreetmap.josm.data.osm.RelationMember; import org.openstreetmap.josm.data.osm.Way; import org.openstreetmap.josm.data.osm.visitor.NameVisitor; import org.openstreetmap.josm.data.osm.visitor.Visitor; /** * Splits a way into multiple ways (all identical except for their node list). * * Ways are just split at the selected nodes. The nodes remain in their * original order. Selected nodes at the end of a way are ignored. */ public class SplitWayAction extends JosmAction implements SelectionChangedListener { private Way selectedWay; private List<Node> selectedNodes; /** * Create a new SplitWayAction. */ public SplitWayAction() { super(tr("Split Way"), "splitway", tr("Split a way at the selected node."), KeyEvent.VK_P, 0, true); DataSet.selListeners.add(this); } /** * Called when the action is executed. * * This method performs an expensive check whether the selection clearly defines one * of the split actions outlined above, and if yes, calls the splitWay method. */ public void actionPerformed(ActionEvent e) { Collection<OsmPrimitive> selection = Main.ds.getSelected(); if (!checkSelection(selection)) { JOptionPane.showMessageDialog(Main.parent, tr("The current selection cannot be used for splitting.")); return; } selectedWay = null; selectedNodes = null; Visitor splitVisitor = new Visitor(){ public void visit(Node n) { if (selectedNodes == null) selectedNodes = new LinkedList<Node>(); selectedNodes.add(n); } public void visit(Way w) { selectedWay = w; } public void visit(Relation e) { // enties are not considered } }; for (OsmPrimitive p : selection) p.visit(splitVisitor); // If only nodes are selected, try to guess which way to split. This works if there // is exactly one way that all nodes are part of. if (selectedWay == null && selectedNodes != null) { HashMap<Way, Integer> wayOccurenceCounter = new HashMap<Way, Integer>(); for (Node n : selectedNodes) { for (Way w : Main.ds.ways) { if (w.deleted || w.incomplete) continue; int last = w.nodes.size()-1; if(last <= 0) continue; // zero or one node ways Boolean circular = w.nodes.get(0).equals(w.nodes.get(last)); int i = 0; for (Node wn : w.nodes) { if ((circular || (i > 0 && i < last)) && n.equals(wn)) { Integer old = wayOccurenceCounter.get(w); wayOccurenceCounter.put(w, (old == null) ? 1 : old+1); break; } i++; } } } if (wayOccurenceCounter.isEmpty()) { JOptionPane.showMessageDialog(Main.parent, trn("The selected node is no inner part of any way.", "The selected nodes are no inner part of any way.", selectedNodes.size())); return; } for (Entry<Way, Integer> entry : wayOccurenceCounter.entrySet()) { if (entry.getValue().equals(selectedNodes.size())) { if (selectedWay != null) { JOptionPane.showMessageDialog(Main.parent, tr("There is more than one way using the node(s) you selected. Please select the way also.")); return; } selectedWay = entry.getKey(); } } if (selectedWay == null) { JOptionPane.showMessageDialog(Main.parent, tr("The selected nodes do not share the same way.")); return; } // If a way and nodes are selected, verify that the nodes are part of the way. } else if (selectedWay != null && selectedNodes != null) { HashSet<Node> nds = new HashSet<Node>(selectedNodes); for (Node n : selectedWay.nodes) { nds.remove(n); } if (!nds.isEmpty()) { JOptionPane.showMessageDialog(Main.parent, trn("The selected way does not contain the selected node.", "The selected way does not contain all the selected nodes.", selectedNodes.size())); return; } } // and then do the work. splitWay(); } /** * Checks if the selection consists of something we can work with. * Checks only if the number and type of items selected looks good; * does not check whether the selected items are really a valid * input for splitting (this would be too expensive to be carried * out from the selectionChanged listener). */ private boolean checkSelection(Collection<? extends OsmPrimitive> selection) { boolean way = false; boolean node = false; for (OsmPrimitive p : selection) { if (p instanceof Way && !way) { way = true; } else if (p instanceof Node) { node = true; } else { return false; } } return node; } /** * Split a way into two or more parts, starting at a selected node. */ private void splitWay() { // We take our way's list of nodes and copy them to a way chunk (a // list of nodes). Whenever we stumble upon a selected node, we start // a new way chunk. Set<Node> nodeSet = new HashSet<Node>(selectedNodes); List<List<Node>> wayChunks = new LinkedList<List<Node>>(); List<Node> currentWayChunk = new ArrayList<Node>(); wayChunks.add(currentWayChunk); Iterator<Node> it = selectedWay.nodes.iterator(); while (it.hasNext()) { Node currentNode = it.next(); boolean atEndOfWay = currentWayChunk.isEmpty() || !it.hasNext(); currentWayChunk.add(currentNode); if (nodeSet.contains(currentNode) && !atEndOfWay) { currentWayChunk = new ArrayList<Node>(); currentWayChunk.add(currentNode); wayChunks.add(currentWayChunk); } } // Handle circular ways specially. // If you split at a circular way at two nodes, you just want to split // it at these points, not also at the former endpoint. // So if the last node is the same first node, join the last and the // first way chunk. List<Node> lastWayChunk = wayChunks.get(wayChunks.size() - 1); if (wayChunks.size() >= 2 && wayChunks.get(0).get(0) == lastWayChunk.get(lastWayChunk.size() - 1) && !nodeSet.contains(wayChunks.get(0).get(0))) { if (wayChunks.size() == 2) { JOptionPane.showMessageDialog(Main.parent, tr("You must select two or more nodes to split a circular way.")); return; } lastWayChunk.remove(lastWayChunk.size() - 1); lastWayChunk.addAll(wayChunks.get(0)); wayChunks.remove(wayChunks.size() - 1); wayChunks.set(0, lastWayChunk); } if (wayChunks.size() < 2) { if(wayChunks.get(0).get(0) == wayChunks.get(0).get(wayChunks.get(0).size()-1)) JOptionPane.showMessageDialog(Main.parent, tr("You must select two or more nodes to split a circular way.")); else JOptionPane.showMessageDialog(Main.parent, tr("The way cannot be split at the selected nodes. (Hint: Select nodes in the middle of the way.)")); return; } //Main.debug("wayChunks.size(): " + wayChunks.size()); //Main.debug("way id: " + selectedWay.id); // build a list of commands, and also a new selection list Collection<Command> commandList = new ArrayList<Command>(wayChunks.size()); Collection<Way> newSelection = new ArrayList<Way>(wayChunks.size()); Iterator<List<Node>> chunkIt = wayChunks.iterator(); // First, change the original way Way changedWay = new Way(selectedWay); changedWay.nodes.clear(); changedWay.nodes.addAll(chunkIt.next()); commandList.add(new ChangeCommand(selectedWay, changedWay)); newSelection.add(selectedWay); + Collection<Way> newWays = new ArrayList<Way>(); // Second, create new ways while (chunkIt.hasNext()) { Way wayToAdd = new Way(); if (selectedWay.keys != null) { wayToAdd.keys = new HashMap<String, String>(selectedWay.keys); wayToAdd.checkTagged(); wayToAdd.checkDirectionTagged(); } + newWays.add(wayToAdd); wayToAdd.nodes.addAll(chunkIt.next()); commandList.add(new AddCommand(wayToAdd)); //Main.debug("wayToAdd: " + wayToAdd); newSelection.add(wayToAdd); - Boolean warnme=false; - // now copy all relations to new way also - for (Relation r : Main.ds.relations) { - if (r.deleted || r.incomplete) continue; - for (RelationMember rm : r.members) { - if (rm.member instanceof Way) { - if (rm.member == selectedWay) + } + Boolean warnme=false; + // now copy all relations to new way also + for (Relation r : Main.ds.relations) { + if (r.deleted || r.incomplete) continue; + for (RelationMember rm : r.members) { + if (rm.member instanceof Way) { + if (rm.member == selectedWay) + { + Relation c = new Relation(r); + for(Way wayToAdd : newWays) { - Relation c = new Relation(r); RelationMember em = new RelationMember(); em.member = wayToAdd; em.role = rm.role; if(em.role.length() > 0) warnme = true; c.members.add(em); - commandList.add(new ChangeCommand(r, c)); - break; } + commandList.add(new ChangeCommand(r, c)); + break; } } } - if(warnme) - JOptionPane.showMessageDialog(Main.parent, tr("A role based relation membership was copied to both new ways.\nYou should verify this and correct it when necessary.")); } + if(warnme) + JOptionPane.showMessageDialog(Main.parent, tr("A role based relation membership was copied to all new ways.\nYou should verify this and correct it when necessary.")); NameVisitor v = new NameVisitor(); v.visit(selectedWay); Main.main.undoRedo.add( new SequenceCommand(tr("Split way {0} into {1} parts", v.name, wayChunks.size()), commandList)); Main.ds.setSelected(newSelection); } /** * Enable the "split way" menu option if the selection looks like we could use it. */ public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) { setEnabled(checkSelection(newSelection)); } }
false
true
private void splitWay() { // We take our way's list of nodes and copy them to a way chunk (a // list of nodes). Whenever we stumble upon a selected node, we start // a new way chunk. Set<Node> nodeSet = new HashSet<Node>(selectedNodes); List<List<Node>> wayChunks = new LinkedList<List<Node>>(); List<Node> currentWayChunk = new ArrayList<Node>(); wayChunks.add(currentWayChunk); Iterator<Node> it = selectedWay.nodes.iterator(); while (it.hasNext()) { Node currentNode = it.next(); boolean atEndOfWay = currentWayChunk.isEmpty() || !it.hasNext(); currentWayChunk.add(currentNode); if (nodeSet.contains(currentNode) && !atEndOfWay) { currentWayChunk = new ArrayList<Node>(); currentWayChunk.add(currentNode); wayChunks.add(currentWayChunk); } } // Handle circular ways specially. // If you split at a circular way at two nodes, you just want to split // it at these points, not also at the former endpoint. // So if the last node is the same first node, join the last and the // first way chunk. List<Node> lastWayChunk = wayChunks.get(wayChunks.size() - 1); if (wayChunks.size() >= 2 && wayChunks.get(0).get(0) == lastWayChunk.get(lastWayChunk.size() - 1) && !nodeSet.contains(wayChunks.get(0).get(0))) { if (wayChunks.size() == 2) { JOptionPane.showMessageDialog(Main.parent, tr("You must select two or more nodes to split a circular way.")); return; } lastWayChunk.remove(lastWayChunk.size() - 1); lastWayChunk.addAll(wayChunks.get(0)); wayChunks.remove(wayChunks.size() - 1); wayChunks.set(0, lastWayChunk); } if (wayChunks.size() < 2) { if(wayChunks.get(0).get(0) == wayChunks.get(0).get(wayChunks.get(0).size()-1)) JOptionPane.showMessageDialog(Main.parent, tr("You must select two or more nodes to split a circular way.")); else JOptionPane.showMessageDialog(Main.parent, tr("The way cannot be split at the selected nodes. (Hint: Select nodes in the middle of the way.)")); return; } //Main.debug("wayChunks.size(): " + wayChunks.size()); //Main.debug("way id: " + selectedWay.id); // build a list of commands, and also a new selection list Collection<Command> commandList = new ArrayList<Command>(wayChunks.size()); Collection<Way> newSelection = new ArrayList<Way>(wayChunks.size()); Iterator<List<Node>> chunkIt = wayChunks.iterator(); // First, change the original way Way changedWay = new Way(selectedWay); changedWay.nodes.clear(); changedWay.nodes.addAll(chunkIt.next()); commandList.add(new ChangeCommand(selectedWay, changedWay)); newSelection.add(selectedWay); // Second, create new ways while (chunkIt.hasNext()) { Way wayToAdd = new Way(); if (selectedWay.keys != null) { wayToAdd.keys = new HashMap<String, String>(selectedWay.keys); wayToAdd.checkTagged(); wayToAdd.checkDirectionTagged(); } wayToAdd.nodes.addAll(chunkIt.next()); commandList.add(new AddCommand(wayToAdd)); //Main.debug("wayToAdd: " + wayToAdd); newSelection.add(wayToAdd); Boolean warnme=false; // now copy all relations to new way also for (Relation r : Main.ds.relations) { if (r.deleted || r.incomplete) continue; for (RelationMember rm : r.members) { if (rm.member instanceof Way) { if (rm.member == selectedWay) { Relation c = new Relation(r); RelationMember em = new RelationMember(); em.member = wayToAdd; em.role = rm.role; if(em.role.length() > 0) warnme = true; c.members.add(em); commandList.add(new ChangeCommand(r, c)); break; } } } } if(warnme) JOptionPane.showMessageDialog(Main.parent, tr("A role based relation membership was copied to both new ways.\nYou should verify this and correct it when necessary.")); } NameVisitor v = new NameVisitor(); v.visit(selectedWay); Main.main.undoRedo.add( new SequenceCommand(tr("Split way {0} into {1} parts", v.name, wayChunks.size()), commandList)); Main.ds.setSelected(newSelection); }
private void splitWay() { // We take our way's list of nodes and copy them to a way chunk (a // list of nodes). Whenever we stumble upon a selected node, we start // a new way chunk. Set<Node> nodeSet = new HashSet<Node>(selectedNodes); List<List<Node>> wayChunks = new LinkedList<List<Node>>(); List<Node> currentWayChunk = new ArrayList<Node>(); wayChunks.add(currentWayChunk); Iterator<Node> it = selectedWay.nodes.iterator(); while (it.hasNext()) { Node currentNode = it.next(); boolean atEndOfWay = currentWayChunk.isEmpty() || !it.hasNext(); currentWayChunk.add(currentNode); if (nodeSet.contains(currentNode) && !atEndOfWay) { currentWayChunk = new ArrayList<Node>(); currentWayChunk.add(currentNode); wayChunks.add(currentWayChunk); } } // Handle circular ways specially. // If you split at a circular way at two nodes, you just want to split // it at these points, not also at the former endpoint. // So if the last node is the same first node, join the last and the // first way chunk. List<Node> lastWayChunk = wayChunks.get(wayChunks.size() - 1); if (wayChunks.size() >= 2 && wayChunks.get(0).get(0) == lastWayChunk.get(lastWayChunk.size() - 1) && !nodeSet.contains(wayChunks.get(0).get(0))) { if (wayChunks.size() == 2) { JOptionPane.showMessageDialog(Main.parent, tr("You must select two or more nodes to split a circular way.")); return; } lastWayChunk.remove(lastWayChunk.size() - 1); lastWayChunk.addAll(wayChunks.get(0)); wayChunks.remove(wayChunks.size() - 1); wayChunks.set(0, lastWayChunk); } if (wayChunks.size() < 2) { if(wayChunks.get(0).get(0) == wayChunks.get(0).get(wayChunks.get(0).size()-1)) JOptionPane.showMessageDialog(Main.parent, tr("You must select two or more nodes to split a circular way.")); else JOptionPane.showMessageDialog(Main.parent, tr("The way cannot be split at the selected nodes. (Hint: Select nodes in the middle of the way.)")); return; } //Main.debug("wayChunks.size(): " + wayChunks.size()); //Main.debug("way id: " + selectedWay.id); // build a list of commands, and also a new selection list Collection<Command> commandList = new ArrayList<Command>(wayChunks.size()); Collection<Way> newSelection = new ArrayList<Way>(wayChunks.size()); Iterator<List<Node>> chunkIt = wayChunks.iterator(); // First, change the original way Way changedWay = new Way(selectedWay); changedWay.nodes.clear(); changedWay.nodes.addAll(chunkIt.next()); commandList.add(new ChangeCommand(selectedWay, changedWay)); newSelection.add(selectedWay); Collection<Way> newWays = new ArrayList<Way>(); // Second, create new ways while (chunkIt.hasNext()) { Way wayToAdd = new Way(); if (selectedWay.keys != null) { wayToAdd.keys = new HashMap<String, String>(selectedWay.keys); wayToAdd.checkTagged(); wayToAdd.checkDirectionTagged(); } newWays.add(wayToAdd); wayToAdd.nodes.addAll(chunkIt.next()); commandList.add(new AddCommand(wayToAdd)); //Main.debug("wayToAdd: " + wayToAdd); newSelection.add(wayToAdd); } Boolean warnme=false; // now copy all relations to new way also for (Relation r : Main.ds.relations) { if (r.deleted || r.incomplete) continue; for (RelationMember rm : r.members) { if (rm.member instanceof Way) { if (rm.member == selectedWay) { Relation c = new Relation(r); for(Way wayToAdd : newWays) { RelationMember em = new RelationMember(); em.member = wayToAdd; em.role = rm.role; if(em.role.length() > 0) warnme = true; c.members.add(em); } commandList.add(new ChangeCommand(r, c)); break; } } } } if(warnme) JOptionPane.showMessageDialog(Main.parent, tr("A role based relation membership was copied to all new ways.\nYou should verify this and correct it when necessary.")); NameVisitor v = new NameVisitor(); v.visit(selectedWay); Main.main.undoRedo.add( new SequenceCommand(tr("Split way {0} into {1} parts", v.name, wayChunks.size()), commandList)); Main.ds.setSelected(newSelection); }
diff --git a/src/main/java/fr/dutra/confluence2wordpress/macro/TOCMacro.java b/src/main/java/fr/dutra/confluence2wordpress/macro/TOCMacro.java index 4f8a20a..7132a01 100755 --- a/src/main/java/fr/dutra/confluence2wordpress/macro/TOCMacro.java +++ b/src/main/java/fr/dutra/confluence2wordpress/macro/TOCMacro.java @@ -1,75 +1,79 @@ /** * Copyright 2011-2012 Alexandre Dutra * * 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 fr.dutra.confluence2wordpress.macro; import java.util.Map; import com.atlassian.confluence.content.render.xhtml.ConversionContext; import com.atlassian.confluence.core.ContentEntityObject; import com.atlassian.confluence.macro.Macro; import com.atlassian.confluence.macro.MacroExecutionException; import com.atlassian.confluence.setup.settings.SettingsManager; import fr.dutra.confluence2wordpress.core.toc.Heading; import fr.dutra.confluence2wordpress.core.toc.TOCBuilder; import fr.dutra.confluence2wordpress.core.toc.TOCException; import fr.dutra.confluence2wordpress.core.velocity.VelocityHelper; import fr.dutra.confluence2wordpress.util.UrlUtils; public class TOCMacro implements Macro { private SettingsManager settingsManager; private VelocityHelper velocityHelper = new VelocityHelper(); private static final String ORDERED = "ordered"; public TOCMacro(SettingsManager settingsManager) { this.settingsManager = settingsManager; } @Override public String execute(Map<String, String> paramMap, String paramString, ConversionContext paramConversionContext) throws MacroExecutionException { ContentEntityObject page = paramConversionContext.getEntity(); + if(page == null) { + //page can be null if we are in a template + return ""; + } String storage = page.getBodyAsString(); TOCBuilder builder = new TOCBuilder(); Heading toc; try { toc = builder.buildTOC(storage, paramConversionContext.getPageContext()); } catch (TOCException e) { throw new MacroExecutionException(e); } Boolean ordered = Boolean.valueOf(paramMap.get(ORDERED)); String baseUrl = settingsManager.getGlobalSettings().getBaseUrl(); String absolute = UrlUtils.absolutize(page.getUrlPath(), baseUrl); return velocityHelper.generateTOC(toc, ordered, absolute); } @Override public BodyType getBodyType() { return BodyType.NONE; } @Override public OutputType getOutputType() { return OutputType.BLOCK; } }
true
true
public String execute(Map<String, String> paramMap, String paramString, ConversionContext paramConversionContext) throws MacroExecutionException { ContentEntityObject page = paramConversionContext.getEntity(); String storage = page.getBodyAsString(); TOCBuilder builder = new TOCBuilder(); Heading toc; try { toc = builder.buildTOC(storage, paramConversionContext.getPageContext()); } catch (TOCException e) { throw new MacroExecutionException(e); } Boolean ordered = Boolean.valueOf(paramMap.get(ORDERED)); String baseUrl = settingsManager.getGlobalSettings().getBaseUrl(); String absolute = UrlUtils.absolutize(page.getUrlPath(), baseUrl); return velocityHelper.generateTOC(toc, ordered, absolute); }
public String execute(Map<String, String> paramMap, String paramString, ConversionContext paramConversionContext) throws MacroExecutionException { ContentEntityObject page = paramConversionContext.getEntity(); if(page == null) { //page can be null if we are in a template return ""; } String storage = page.getBodyAsString(); TOCBuilder builder = new TOCBuilder(); Heading toc; try { toc = builder.buildTOC(storage, paramConversionContext.getPageContext()); } catch (TOCException e) { throw new MacroExecutionException(e); } Boolean ordered = Boolean.valueOf(paramMap.get(ORDERED)); String baseUrl = settingsManager.getGlobalSettings().getBaseUrl(); String absolute = UrlUtils.absolutize(page.getUrlPath(), baseUrl); return velocityHelper.generateTOC(toc, ordered, absolute); }
diff --git a/webui/src/main/java/taxonomy/webui/client/widget/TxShell.java b/webui/src/main/java/taxonomy/webui/client/widget/TxShell.java index 3d22277..306a89e 100644 --- a/webui/src/main/java/taxonomy/webui/client/widget/TxShell.java +++ b/webui/src/main/java/taxonomy/webui/client/widget/TxShell.java @@ -1,94 +1,96 @@ /* * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package taxonomy.webui.client.widget; import taxonomy.resources.client.model.VNaturalObject; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.sencha.gxt.core.client.util.Margins; import com.sencha.gxt.widget.core.client.TabItemConfig; import com.sencha.gxt.widget.core.client.TabPanel; import com.sencha.gxt.widget.core.client.container.BorderLayoutContainer; import com.sencha.gxt.widget.core.client.container.MarginData; /** * @author <a href="mailto:[email protected]">Nguyen Thanh Hai</a> * @version $Id$ * */ public class TxShell extends BorderLayoutContainer { /** . */ static TabPanel center; @Inject public TxShell() { monitorWindowResize = true; Window.enableScrolling(false); setPixelSize(Window.getClientWidth(), Window.getClientHeight()); setStateful(false); setStateId("explorerLayout"); // BorderLayoutStateHandler state = new BorderLayoutStateHandler(this); // state.loadState(); HTML north = new HTML(); north.setHTML("<div id='demo-theme'></div><div id=demo-title>Taxonomy Web Base Application</div>"); north.getElement().setId("demo-header"); BorderLayoutData northData = new BorderLayoutData(35); setNorthWidget(north, northData); setSouthWidget(new OperatorToolbar(), new BorderLayoutData(40)); MarginData centerData = new MarginData(); centerData.setMargins(new Margins(5)); center = new TabPanel(); center.setTabScroll(true); center.setCloseContextMenu(true); center.addSelectionHandler(new SelectionHandler<Widget>() { @Override public void onSelection(SelectionEvent<Widget> event) { if(event.getSelectedItem() instanceof ModelGridPanel) { OperatorToolbar.rootPanel = (ModelGridPanel)event.getSelectedItem(); if(OperatorToolbar.rootPanel.getCheckBoxSelectionModel().getSelectedItems().size() == 0) { OperatorToolbar.disableModifyButton(); + } else { + OperatorToolbar.enableModifyButton(); } } } }); TabItemConfig tabConfig = new TabItemConfig(Tables.NATURALOBJECT.getName(), true); ModelGridPanel<VNaturalObject> panel = ModelGridFactory.createNObject(); center.add(panel, tabConfig); center.setActiveWidget(panel); setCenterWidget(center, centerData); } @Override protected void onWindowResize(int width, int height) { setPixelSize(width, height); } }
true
true
public TxShell() { monitorWindowResize = true; Window.enableScrolling(false); setPixelSize(Window.getClientWidth(), Window.getClientHeight()); setStateful(false); setStateId("explorerLayout"); // BorderLayoutStateHandler state = new BorderLayoutStateHandler(this); // state.loadState(); HTML north = new HTML(); north.setHTML("<div id='demo-theme'></div><div id=demo-title>Taxonomy Web Base Application</div>"); north.getElement().setId("demo-header"); BorderLayoutData northData = new BorderLayoutData(35); setNorthWidget(north, northData); setSouthWidget(new OperatorToolbar(), new BorderLayoutData(40)); MarginData centerData = new MarginData(); centerData.setMargins(new Margins(5)); center = new TabPanel(); center.setTabScroll(true); center.setCloseContextMenu(true); center.addSelectionHandler(new SelectionHandler<Widget>() { @Override public void onSelection(SelectionEvent<Widget> event) { if(event.getSelectedItem() instanceof ModelGridPanel) { OperatorToolbar.rootPanel = (ModelGridPanel)event.getSelectedItem(); if(OperatorToolbar.rootPanel.getCheckBoxSelectionModel().getSelectedItems().size() == 0) { OperatorToolbar.disableModifyButton(); } } } }); TabItemConfig tabConfig = new TabItemConfig(Tables.NATURALOBJECT.getName(), true); ModelGridPanel<VNaturalObject> panel = ModelGridFactory.createNObject(); center.add(panel, tabConfig); center.setActiveWidget(panel); setCenterWidget(center, centerData); }
public TxShell() { monitorWindowResize = true; Window.enableScrolling(false); setPixelSize(Window.getClientWidth(), Window.getClientHeight()); setStateful(false); setStateId("explorerLayout"); // BorderLayoutStateHandler state = new BorderLayoutStateHandler(this); // state.loadState(); HTML north = new HTML(); north.setHTML("<div id='demo-theme'></div><div id=demo-title>Taxonomy Web Base Application</div>"); north.getElement().setId("demo-header"); BorderLayoutData northData = new BorderLayoutData(35); setNorthWidget(north, northData); setSouthWidget(new OperatorToolbar(), new BorderLayoutData(40)); MarginData centerData = new MarginData(); centerData.setMargins(new Margins(5)); center = new TabPanel(); center.setTabScroll(true); center.setCloseContextMenu(true); center.addSelectionHandler(new SelectionHandler<Widget>() { @Override public void onSelection(SelectionEvent<Widget> event) { if(event.getSelectedItem() instanceof ModelGridPanel) { OperatorToolbar.rootPanel = (ModelGridPanel)event.getSelectedItem(); if(OperatorToolbar.rootPanel.getCheckBoxSelectionModel().getSelectedItems().size() == 0) { OperatorToolbar.disableModifyButton(); } else { OperatorToolbar.enableModifyButton(); } } } }); TabItemConfig tabConfig = new TabItemConfig(Tables.NATURALOBJECT.getName(), true); ModelGridPanel<VNaturalObject> panel = ModelGridFactory.createNObject(); center.add(panel, tabConfig); center.setActiveWidget(panel); setCenterWidget(center, centerData); }
diff --git a/oseille/src/lobstre/oseille/commands/RebaseOperation.java b/oseille/src/lobstre/oseille/commands/RebaseOperation.java index 174a8ca..0161ae8 100644 --- a/oseille/src/lobstre/oseille/commands/RebaseOperation.java +++ b/oseille/src/lobstre/oseille/commands/RebaseOperation.java @@ -1,48 +1,48 @@ package lobstre.oseille.commands; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.util.Collection; import java.util.List; import lobstre.oseille.Command; import lobstre.oseille.model.Account; import lobstre.oseille.model.Operation; import lobstre.oseille.parser.Parser; public class RebaseOperation implements Command { @Override public void accepts (final List<String> arguments, final Collection<String> errors, final String fileName) { if (arguments.size () != 2) { errors.add ("Usage : rebase-operation fromIndex toIndex"); } else { final int from = Integer.parseInt (arguments.get (0)); final int to = Integer.parseInt (arguments.get (1)); if (from == to) { errors.add ("fromIndex must be different from to toIndex"); } } } @Override public void execute (final String fileName, final List<String> arguments) throws IOException, ParseException { final File file = new File (fileName); final Account acc = Parser.read (file); + final List<Operation> opers = acc.getOperations (); final int from = Integer.parseInt (arguments.get (0)); - final int to = Integer.parseInt (arguments.get (0)); + final int to = Integer.parseInt (arguments.get (1)); - final List<Operation> opers = acc.getOperations (); final Operation out = opers.get (to); final Operation in = opers.get (from); opers.set (to, in); opers.set (from, out); ListAccount.renderOperations (acc); Parser.write (acc, file); } }
false
true
public void execute (final String fileName, final List<String> arguments) throws IOException, ParseException { final File file = new File (fileName); final Account acc = Parser.read (file); final int from = Integer.parseInt (arguments.get (0)); final int to = Integer.parseInt (arguments.get (0)); final List<Operation> opers = acc.getOperations (); final Operation out = opers.get (to); final Operation in = opers.get (from); opers.set (to, in); opers.set (from, out); ListAccount.renderOperations (acc); Parser.write (acc, file); }
public void execute (final String fileName, final List<String> arguments) throws IOException, ParseException { final File file = new File (fileName); final Account acc = Parser.read (file); final List<Operation> opers = acc.getOperations (); final int from = Integer.parseInt (arguments.get (0)); final int to = Integer.parseInt (arguments.get (1)); final Operation out = opers.get (to); final Operation in = opers.get (from); opers.set (to, in); opers.set (from, out); ListAccount.renderOperations (acc); Parser.write (acc, file); }
diff --git a/src/main/java/fr/ybo/ybotv/android/service/HttpService.java b/src/main/java/fr/ybo/ybotv/android/service/HttpService.java index bbbcfbf..6d42b65 100644 --- a/src/main/java/fr/ybo/ybotv/android/service/HttpService.java +++ b/src/main/java/fr/ybo/ybotv/android/service/HttpService.java @@ -1,72 +1,76 @@ package fr.ybo.ybotv.android.service; import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; import fr.ybo.ybotv.android.exception.YboTvErreurReseau; import fr.ybo.ybotv.android.exception.YboTvException; import fr.ybo.ybotv.android.util.HttpUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.MalformedURLException; import java.net.URLEncoder; import java.util.List; public abstract class HttpService { private static final int MAX_RETRY = 5; public <T> T getObjects(String url, TypeToken<T> typeToken) throws YboTvErreurReseau { int countRetry = 0; while (countRetry < MAX_RETRY - 1) { countRetry++; try { return getObjectsWithoutRetry(url, typeToken); } catch (YboTvErreurReseau erreurReseau) { Log.e("YboTv", "Erreur réseau (" + countRetry + ") en accédant à l'url : " + url); Log.e("YboTv", Log.getStackTraceString(erreurReseau)); } } return getObjectsWithoutRetry(url, typeToken); } protected <T> T getObjectsWithoutRetry(String url, TypeToken<T> typeToken) throws YboTvErreurReseau { Reader reader = null; try { Log.d("YboTv", "Url demandee : " + url); HttpClient client = HttpUtils.getHttpClient(); HttpUriRequest request = new HttpGet(url.replaceAll(" ", "%20")); request.addHeader("Accept", "application/json"); HttpResponse reponse = client.execute(request); reader = new InputStreamReader(reponse.getEntity().getContent()); GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); - return gson.fromJson(reader, typeToken.getType()); + T retour = gson.fromJson(reader, typeToken.getType()); + if (retour == null) { + throw new YboTvErreurReseau("Null object in respose"); + } + return retour; } catch (MalformedURLException e) { throw new YboTvException(e); } catch (IOException e) { throw new YboTvErreurReseau(e); } catch (JsonSyntaxException e) { throw new YboTvErreurReseau(e); } finally { if (reader != null) { try { reader.close(); } catch (Exception ignore) {} } } } }
true
true
protected <T> T getObjectsWithoutRetry(String url, TypeToken<T> typeToken) throws YboTvErreurReseau { Reader reader = null; try { Log.d("YboTv", "Url demandee : " + url); HttpClient client = HttpUtils.getHttpClient(); HttpUriRequest request = new HttpGet(url.replaceAll(" ", "%20")); request.addHeader("Accept", "application/json"); HttpResponse reponse = client.execute(request); reader = new InputStreamReader(reponse.getEntity().getContent()); GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); return gson.fromJson(reader, typeToken.getType()); } catch (MalformedURLException e) { throw new YboTvException(e); } catch (IOException e) { throw new YboTvErreurReseau(e); } catch (JsonSyntaxException e) { throw new YboTvErreurReseau(e); } finally { if (reader != null) { try { reader.close(); } catch (Exception ignore) {} } } }
protected <T> T getObjectsWithoutRetry(String url, TypeToken<T> typeToken) throws YboTvErreurReseau { Reader reader = null; try { Log.d("YboTv", "Url demandee : " + url); HttpClient client = HttpUtils.getHttpClient(); HttpUriRequest request = new HttpGet(url.replaceAll(" ", "%20")); request.addHeader("Accept", "application/json"); HttpResponse reponse = client.execute(request); reader = new InputStreamReader(reponse.getEntity().getContent()); GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); T retour = gson.fromJson(reader, typeToken.getType()); if (retour == null) { throw new YboTvErreurReseau("Null object in respose"); } return retour; } catch (MalformedURLException e) { throw new YboTvException(e); } catch (IOException e) { throw new YboTvErreurReseau(e); } catch (JsonSyntaxException e) { throw new YboTvErreurReseau(e); } finally { if (reader != null) { try { reader.close(); } catch (Exception ignore) {} } } }
diff --git a/src/org/opensolaris/opengrok/analysis/sql/SQLAnalyzer.java b/src/org/opensolaris/opengrok/analysis/sql/SQLAnalyzer.java index 44bdb07..94b95a6 100644 --- a/src/org/opensolaris/opengrok/analysis/sql/SQLAnalyzer.java +++ b/src/org/opensolaris/opengrok/analysis/sql/SQLAnalyzer.java @@ -1,69 +1,69 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * See LICENSE.txt included in this distribution for the specific * language governing permissions and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2007 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ package org.opensolaris.opengrok.analysis.sql; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.Writer; import org.opensolaris.opengrok.analysis.FileAnalyzerFactory; import org.opensolaris.opengrok.analysis.plain.PlainAnalyzer; import org.opensolaris.opengrok.configuration.Project; import org.opensolaris.opengrok.history.Annotation; public class SQLAnalyzer extends PlainAnalyzer { private final SQLXref xref = new SQLXref((Reader)null); public SQLAnalyzer(FileAnalyzerFactory factory) { super(factory); } /** * Write a cross referenced HTML file. * @param out Writer to write HTML cross-reference */ public void writeXref(Writer out) throws IOException { xref.reInit(content, len); xref.project = project; - // @TODO xref.setDefs(defs); + xref.setDefs(defs); xref.write(out); } /** * Write a cross referenced HTML file. Reads the source from * an input stream. * * @param in input source * @param out output xref writer * @param annotation annotation for the file (could be null) */ static void writeXref(InputStream in, Writer out, Annotation annotation, Project project) throws IOException { SQLXref xref = new SQLXref(in); xref.annotation = annotation; xref.project = project; xref.write(out); } }
true
true
public void writeXref(Writer out) throws IOException { xref.reInit(content, len); xref.project = project; // @TODO xref.setDefs(defs); xref.write(out); }
public void writeXref(Writer out) throws IOException { xref.reInit(content, len); xref.project = project; xref.setDefs(defs); xref.write(out); }
diff --git a/tools/cts-reference-app-lib/src/android/cts/refapp/ReferenceAppTestCase.java b/tools/cts-reference-app-lib/src/android/cts/refapp/ReferenceAppTestCase.java index fc5cd5af..203b6909 100644 --- a/tools/cts-reference-app-lib/src/android/cts/refapp/ReferenceAppTestCase.java +++ b/tools/cts-reference-app-lib/src/android/cts/refapp/ReferenceAppTestCase.java @@ -1,87 +1,88 @@ /* * Copyright (C) 2008 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.cts.refapp; import android.app.Activity; import android.test.ActivityInstrumentationTestCase2; import android.util.Log; import java.lang.InterruptedException; import java.lang.Thread; /** * Base Class that provides common functionality for all Reference Application Tests. */ public class ReferenceAppTestCase<T extends Activity> extends ActivityInstrumentationTestCase2<T> { /** The time to wait for the test host to finish taking the snapshot. */ private static final int SNAPSHOT_TIMEOUT_MS = 1000; /** The default time that the applicaiton has to start in. */ private static final int DEFAULT_MAX_STATUP_TIME_MS = 5000; private int maxStartupTimeMs; /** * Create a ReferenceAppTestCase for the specified activity. * * @param pkg the java package the class is contained in. * @param activityClass the class of the activity to instrument. * @param maxStartupTimeMs the startup time the activity should start in. */ public ReferenceAppTestCase(String pkg, Class<T> activityClass, int maxStartupTimeMs) { super(pkg, activityClass); this.maxStartupTimeMs = maxStartupTimeMs; } /** * Create a ReferenceAppTestCase for the specified activity. * * @param pkg the java package the class is contained in. * @param activityClass the class of the activity to instrument. */ public ReferenceAppTestCase(String pkg, Class<T> activityClass) { this(pkg, activityClass, DEFAULT_MAX_STATUP_TIME_MS); } public void testActivityStartupTime() { // Test activity startup time. long start = System.currentTimeMillis(); Activity activity = getActivity(); long end = System.currentTimeMillis(); long startupTime = end - start; - assertTrue("Activity Startup took more than 5 seconds", - startupTime <= 5000); + assertTrue("Activity Startup took more than " + maxStartupTimeMs + + " ms", + startupTime <= maxStartupTimeMs); } /** * Allows tests to record screen snapshots for inclusion in the * CTS test report. * * @param name the name to save the snapshot under */ public void takeSnapshot(String name) { // request a snapshot from the CTS host Log.d("ReferenceAppTestCase", "takeSnapshot:" + name); // Give the host enough time to take the picture try { Thread.sleep(SNAPSHOT_TIMEOUT_MS); } catch (InterruptedException e) { // ok } } }
true
true
public void testActivityStartupTime() { // Test activity startup time. long start = System.currentTimeMillis(); Activity activity = getActivity(); long end = System.currentTimeMillis(); long startupTime = end - start; assertTrue("Activity Startup took more than 5 seconds", startupTime <= 5000); }
public void testActivityStartupTime() { // Test activity startup time. long start = System.currentTimeMillis(); Activity activity = getActivity(); long end = System.currentTimeMillis(); long startupTime = end - start; assertTrue("Activity Startup took more than " + maxStartupTimeMs + " ms", startupTime <= maxStartupTimeMs); }
diff --git a/continuum-webapp/src/main/java/org/apache/maven/continuum/web/view/BuildCell.java b/continuum-webapp/src/main/java/org/apache/maven/continuum/web/view/BuildCell.java index ad0d546fa..fb1aec56f 100644 --- a/continuum-webapp/src/main/java/org/apache/maven/continuum/web/view/BuildCell.java +++ b/continuum-webapp/src/main/java/org/apache/maven/continuum/web/view/BuildCell.java @@ -1,103 +1,103 @@ package org.apache.maven.continuum.web.view; /* * Copyright 2004-2005 The Apache Software Foundation. * * 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. */ import com.opensymphony.webwork.views.util.UrlHelper; import org.apache.maven.continuum.web.model.SummaryProjectModel; import org.extremecomponents.table.bean.Column; import org.extremecomponents.table.cell.DisplayCell; import org.extremecomponents.table.core.TableModel; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.PageContext; import java.util.HashMap; /** * Used in Summary view * * @author <a href="mailto:[email protected]">Emmanuel Venisse</a> * @version $Id$ */ public class BuildCell extends DisplayCell { protected String getCellValue( TableModel tableModel, Column column ) { SummaryProjectModel project = (SummaryProjectModel) tableModel.getCurrentRowBean(); String contextPath = tableModel.getContext().getContextPath(); int buildNumber = project.getBuildNumber(); String result = "<div align=\"center\">"; if ( project.isInQueue() ) { result += "<img src=\"" + contextPath + "/images/inqueue.gif\" alt=\"In Queue\" title=\"In Queue\" border=\"0\">"; } else { if ( project.getState() == 1 || project.getState() == 10 || project.getState() == 2 || project.getState() == 3 || project.getState() == 4 ) { if ( project.getBuildNumber() > 0 ) { HashMap params = new HashMap(); params.put( "projectId", new Integer( project.getId() ) ); params.put( "projectName", project.getName() ); params.put( "buildId", new Integer( buildNumber ) ); PageContext pageContext = (PageContext) tableModel.getContext().getContextObject(); HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); HttpServletResponse response = (HttpServletResponse) pageContext.getResponse(); String url = UrlHelper.buildUrl( "/buildResult.action", request, response, params ); - result += "<a href=\"" + url + ">" + project.getBuildNumber() + "</a>"; + result += "<a href=\"" + url + "\">" + project.getBuildNumber() + "</a>"; } else { result += "&nbsp;"; } } else if ( project.getState() == 6 ) { result += "<img src=\"" + contextPath + "/images/building.gif\" alt=\"Building\" title=\"Building\" border=\"0\">"; } else if ( project.getState() == 7 ) { result += "<img src=\"" + contextPath + "/images/checkingout.gif\" alt=\"Checking Out sources\" title=\"Checking Out sources\" border=\"0\">"; } else if ( project.getState() == 8 ) { result += "<img src=\"" + contextPath + "/images/checkingout.gif\" alt=\"Updating sources\" title=\"Updating sources\" border=\"0\">"; } else { result += "<img src=\"" + contextPath + "/images/inqueue.gif\" alt=\"In Queue\" title=\"In Queue\" border=\"0\">"; } } return result + "</div>"; } }
true
true
protected String getCellValue( TableModel tableModel, Column column ) { SummaryProjectModel project = (SummaryProjectModel) tableModel.getCurrentRowBean(); String contextPath = tableModel.getContext().getContextPath(); int buildNumber = project.getBuildNumber(); String result = "<div align=\"center\">"; if ( project.isInQueue() ) { result += "<img src=\"" + contextPath + "/images/inqueue.gif\" alt=\"In Queue\" title=\"In Queue\" border=\"0\">"; } else { if ( project.getState() == 1 || project.getState() == 10 || project.getState() == 2 || project.getState() == 3 || project.getState() == 4 ) { if ( project.getBuildNumber() > 0 ) { HashMap params = new HashMap(); params.put( "projectId", new Integer( project.getId() ) ); params.put( "projectName", project.getName() ); params.put( "buildId", new Integer( buildNumber ) ); PageContext pageContext = (PageContext) tableModel.getContext().getContextObject(); HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); HttpServletResponse response = (HttpServletResponse) pageContext.getResponse(); String url = UrlHelper.buildUrl( "/buildResult.action", request, response, params ); result += "<a href=\"" + url + ">" + project.getBuildNumber() + "</a>"; } else { result += "&nbsp;"; } } else if ( project.getState() == 6 ) { result += "<img src=\"" + contextPath + "/images/building.gif\" alt=\"Building\" title=\"Building\" border=\"0\">"; } else if ( project.getState() == 7 ) { result += "<img src=\"" + contextPath + "/images/checkingout.gif\" alt=\"Checking Out sources\" title=\"Checking Out sources\" border=\"0\">"; } else if ( project.getState() == 8 ) { result += "<img src=\"" + contextPath + "/images/checkingout.gif\" alt=\"Updating sources\" title=\"Updating sources\" border=\"0\">"; } else { result += "<img src=\"" + contextPath + "/images/inqueue.gif\" alt=\"In Queue\" title=\"In Queue\" border=\"0\">"; } } return result + "</div>"; }
protected String getCellValue( TableModel tableModel, Column column ) { SummaryProjectModel project = (SummaryProjectModel) tableModel.getCurrentRowBean(); String contextPath = tableModel.getContext().getContextPath(); int buildNumber = project.getBuildNumber(); String result = "<div align=\"center\">"; if ( project.isInQueue() ) { result += "<img src=\"" + contextPath + "/images/inqueue.gif\" alt=\"In Queue\" title=\"In Queue\" border=\"0\">"; } else { if ( project.getState() == 1 || project.getState() == 10 || project.getState() == 2 || project.getState() == 3 || project.getState() == 4 ) { if ( project.getBuildNumber() > 0 ) { HashMap params = new HashMap(); params.put( "projectId", new Integer( project.getId() ) ); params.put( "projectName", project.getName() ); params.put( "buildId", new Integer( buildNumber ) ); PageContext pageContext = (PageContext) tableModel.getContext().getContextObject(); HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); HttpServletResponse response = (HttpServletResponse) pageContext.getResponse(); String url = UrlHelper.buildUrl( "/buildResult.action", request, response, params ); result += "<a href=\"" + url + "\">" + project.getBuildNumber() + "</a>"; } else { result += "&nbsp;"; } } else if ( project.getState() == 6 ) { result += "<img src=\"" + contextPath + "/images/building.gif\" alt=\"Building\" title=\"Building\" border=\"0\">"; } else if ( project.getState() == 7 ) { result += "<img src=\"" + contextPath + "/images/checkingout.gif\" alt=\"Checking Out sources\" title=\"Checking Out sources\" border=\"0\">"; } else if ( project.getState() == 8 ) { result += "<img src=\"" + contextPath + "/images/checkingout.gif\" alt=\"Updating sources\" title=\"Updating sources\" border=\"0\">"; } else { result += "<img src=\"" + contextPath + "/images/inqueue.gif\" alt=\"In Queue\" title=\"In Queue\" border=\"0\">"; } } return result + "</div>"; }
diff --git a/api/src/test/java/org/openmrs/reporting/ReportObjectServiceTest.java b/api/src/test/java/org/openmrs/reporting/ReportObjectServiceTest.java index 3ca31acb..759b8367 100644 --- a/api/src/test/java/org/openmrs/reporting/ReportObjectServiceTest.java +++ b/api/src/test/java/org/openmrs/reporting/ReportObjectServiceTest.java @@ -1,40 +1,40 @@ package org.openmrs.reporting; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.openmrs.Concept; import org.openmrs.api.PatientSetService; import org.openmrs.api.context.Context; import org.openmrs.cohort.CohortSearchHistory; import org.openmrs.test.BaseContextSensitiveTest; import org.openmrs.test.Verifies; public class ReportObjectServiceTest extends BaseContextSensitiveTest { /** * @see {@link ReportObjectService#saveSearchHistory(CohortSearchHistory)} * */ @Test @Verifies(value = "should save history successfully", method = "saveSearchHistory(CohortSearchHistory)") public void saveSearchHistory_shouldSaveHistorySuccessfully() throws Exception { // make a patient search object PatientSearch search = new PatientSearch(); search.setFilterClass(ObsPatientFilter.class); List<SearchArgument> args = new ArrayList<SearchArgument>(); args.add(new SearchArgument("timeModifier", "ANY", PatientSetService.TimeModifier.class)); args.add(new SearchArgument("question", Context.getConceptService().getConceptByName("CD4 COUNT").getConceptId() .toString(), Concept.class)); - args.add(new SearchArgument("withinLastDays", "${howManyDays}", Integer.class)); + args.add(new SearchArgument("withinLastDays", "1", Integer.class)); //one indicates the number of days search.setArguments(args); // save the object to the database CohortSearchHistory history = new CohortSearchHistory(); history.setName("Some name"); history.setDescription("a description"); history.addSearchItem(search); Context.getReportObjectService().saveSearchHistory(history); } }
true
true
public void saveSearchHistory_shouldSaveHistorySuccessfully() throws Exception { // make a patient search object PatientSearch search = new PatientSearch(); search.setFilterClass(ObsPatientFilter.class); List<SearchArgument> args = new ArrayList<SearchArgument>(); args.add(new SearchArgument("timeModifier", "ANY", PatientSetService.TimeModifier.class)); args.add(new SearchArgument("question", Context.getConceptService().getConceptByName("CD4 COUNT").getConceptId() .toString(), Concept.class)); args.add(new SearchArgument("withinLastDays", "${howManyDays}", Integer.class)); search.setArguments(args); // save the object to the database CohortSearchHistory history = new CohortSearchHistory(); history.setName("Some name"); history.setDescription("a description"); history.addSearchItem(search); Context.getReportObjectService().saveSearchHistory(history); }
public void saveSearchHistory_shouldSaveHistorySuccessfully() throws Exception { // make a patient search object PatientSearch search = new PatientSearch(); search.setFilterClass(ObsPatientFilter.class); List<SearchArgument> args = new ArrayList<SearchArgument>(); args.add(new SearchArgument("timeModifier", "ANY", PatientSetService.TimeModifier.class)); args.add(new SearchArgument("question", Context.getConceptService().getConceptByName("CD4 COUNT").getConceptId() .toString(), Concept.class)); args.add(new SearchArgument("withinLastDays", "1", Integer.class)); //one indicates the number of days search.setArguments(args); // save the object to the database CohortSearchHistory history = new CohortSearchHistory(); history.setName("Some name"); history.setDescription("a description"); history.addSearchItem(search); Context.getReportObjectService().saveSearchHistory(history); }
diff --git a/Core/src/java/ho/module/teamAnalyzer/manager/MatchManager.java b/Core/src/java/ho/module/teamAnalyzer/manager/MatchManager.java index 1ea9f32b..758906f4 100644 --- a/Core/src/java/ho/module/teamAnalyzer/manager/MatchManager.java +++ b/Core/src/java/ho/module/teamAnalyzer/manager/MatchManager.java @@ -1,177 +1,182 @@ // %3449686638:hoplugins.teamAnalyzer.manager% package ho.module.teamAnalyzer.manager; import ho.core.db.DBManager; import ho.core.model.match.MatchKurzInfo; import ho.core.module.config.ModuleConfig; import ho.module.matches.SpielePanel; import ho.module.teamAnalyzer.SystemManager; import ho.module.teamAnalyzer.ui.TeamAnalyzerPanel; import ho.module.teamAnalyzer.vo.Match; import ho.module.teamAnalyzer.vo.MatchDetail; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; /** * TODO Missing Class Documentation * * @author TODO Author Name */ public class MatchManager { //~ Static fields/initializers ----------------------------------------------------------------- private static MatchList matches = null; //~ Methods ------------------------------------------------------------------------------------ /** * TODO Missing Method Documentation * * @return TODO Missing Return Method Documentation */ public static List<Match> getAllMatches() { return matches.getMatches(); } /** * TODO Missing Method Documentation * * @return TODO Missing Return Method Documentation */ public static List<MatchDetail> getMatchDetails() { List<Match> filteredMatches = getSelectedMatches(); MatchPopulator matchPopulator = new MatchPopulator(); return matchPopulator.populate(filteredMatches); } /** * TODO Missing Method Documentation * * @return TODO Missing Return Method Documentation */ public static List<Match> getSelectedMatches() { if (matches == null) { loadActiveTeamMatchList(); } return matches.filterMatches(TeamAnalyzerPanel.filter); } /** * TODO Missing Method Documentation */ public static void clean() { loadActiveTeamMatchList(); } /** * TODO Missing Method Documentation */ public static void loadActiveTeamMatchList() { matches = new MatchList(); SortedSet<Match> sortedMatches = loadMatchList(); for (Iterator<Match> iter = sortedMatches.iterator(); iter.hasNext();) { Match element = iter.next(); matches.addMatch(element); } } /** * TODO Missing Method Documentation * * @return TODO Missing Return Method Documentation */ private static List<Match> getTeamMatch() { List<Match> teamMatches = new ArrayList<Match>(); String oldName = SystemManager.getActiveTeamName(); MatchKurzInfo[] matchKurtzInfo = DBManager.instance().getMatchesKurzInfo(SystemManager .getActiveTeamId(), SpielePanel.NUR_EIGENE_SPIELE, false); for (int i = 0; i < matchKurtzInfo.length; i++) { MatchKurzInfo matchInfo = matchKurtzInfo[i]; if (matchInfo.getMatchStatus() != MatchKurzInfo.FINISHED) { continue; } Match match = new Match(matchInfo); String temp; if (match.getHomeId() == SystemManager.getActiveTeamId()) { temp = match.getHomeTeam(); } else { temp = match.getAwayTeam(); } if (ModuleConfig.instance().getBoolean(SystemManager.ISCHECKTEAMNAME)) { // Fix for missing last dot! String oldShort = oldName.substring(0, oldName.length() - 1); if (oldShort.equalsIgnoreCase(temp)) { temp = oldName; } if (!temp.equalsIgnoreCase(oldName)) { - if (match.getWeek() > 14) { + /* Team name can be changed the name between seasons + * without being bot in between. Team name can be changed + * after the 14th league game which makes that game the + * last possible match to hold old name. + */ + if (match.getWeek() > 13) { oldName = temp; } else { return teamMatches; } } } teamMatches.add(match); } return teamMatches; } /** * TODO Missing Method Documentation * * @return TODO Missing Return Method Documentation */ private static SortedSet<Match> loadMatchList() { Map<String,Match> matchIds = new HashMap<String,Match>(); for (Iterator<Match> iter = getTeamMatch().iterator(); iter.hasNext();) { Match match = iter.next(); if (!matchIds.containsKey(match.getMatchId() + "")) { matchIds.put(match.getMatchId() + "", match); } } Collection<Match> matchList = matchIds.values(); SortedSet<Match> sorted = getSortedSet(matchList, new MatchComparator()); return sorted; } private static<T> SortedSet<T> getSortedSet(Collection<T> beans, Comparator<T> comparator) { final SortedSet<T> set = new TreeSet<T>(comparator); if ((beans != null) && (beans.size() > 0)) { set.addAll(beans); } return set; } }
true
true
private static List<Match> getTeamMatch() { List<Match> teamMatches = new ArrayList<Match>(); String oldName = SystemManager.getActiveTeamName(); MatchKurzInfo[] matchKurtzInfo = DBManager.instance().getMatchesKurzInfo(SystemManager .getActiveTeamId(), SpielePanel.NUR_EIGENE_SPIELE, false); for (int i = 0; i < matchKurtzInfo.length; i++) { MatchKurzInfo matchInfo = matchKurtzInfo[i]; if (matchInfo.getMatchStatus() != MatchKurzInfo.FINISHED) { continue; } Match match = new Match(matchInfo); String temp; if (match.getHomeId() == SystemManager.getActiveTeamId()) { temp = match.getHomeTeam(); } else { temp = match.getAwayTeam(); } if (ModuleConfig.instance().getBoolean(SystemManager.ISCHECKTEAMNAME)) { // Fix for missing last dot! String oldShort = oldName.substring(0, oldName.length() - 1); if (oldShort.equalsIgnoreCase(temp)) { temp = oldName; } if (!temp.equalsIgnoreCase(oldName)) { if (match.getWeek() > 14) { oldName = temp; } else { return teamMatches; } } } teamMatches.add(match); } return teamMatches; }
private static List<Match> getTeamMatch() { List<Match> teamMatches = new ArrayList<Match>(); String oldName = SystemManager.getActiveTeamName(); MatchKurzInfo[] matchKurtzInfo = DBManager.instance().getMatchesKurzInfo(SystemManager .getActiveTeamId(), SpielePanel.NUR_EIGENE_SPIELE, false); for (int i = 0; i < matchKurtzInfo.length; i++) { MatchKurzInfo matchInfo = matchKurtzInfo[i]; if (matchInfo.getMatchStatus() != MatchKurzInfo.FINISHED) { continue; } Match match = new Match(matchInfo); String temp; if (match.getHomeId() == SystemManager.getActiveTeamId()) { temp = match.getHomeTeam(); } else { temp = match.getAwayTeam(); } if (ModuleConfig.instance().getBoolean(SystemManager.ISCHECKTEAMNAME)) { // Fix for missing last dot! String oldShort = oldName.substring(0, oldName.length() - 1); if (oldShort.equalsIgnoreCase(temp)) { temp = oldName; } if (!temp.equalsIgnoreCase(oldName)) { /* Team name can be changed the name between seasons * without being bot in between. Team name can be changed * after the 14th league game which makes that game the * last possible match to hold old name. */ if (match.getWeek() > 13) { oldName = temp; } else { return teamMatches; } } } teamMatches.add(match); } return teamMatches; }
diff --git a/beddit_alarm/src/ohtu/beddit/views/timepicker/CustomTimePicker.java b/beddit_alarm/src/ohtu/beddit/views/timepicker/CustomTimePicker.java index fcb059e..b812e87 100644 --- a/beddit_alarm/src/ohtu/beddit/views/timepicker/CustomTimePicker.java +++ b/beddit_alarm/src/ohtu/beddit/views/timepicker/CustomTimePicker.java @@ -1,320 +1,321 @@ package ohtu.beddit.views.timepicker; import android.content.Context; import android.graphics.*; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import ohtu.beddit.alarm.AlarmTimeChangedListener; import ohtu.beddit.alarm.AlarmTimePicker; import java.util.LinkedList; import java.util.List; /** * Created with IntelliJ IDEA. * User: psaikko * Date: 21.5.2012 * Time: 13:49 * To change this template use File | Settings | File Templates. */ public class CustomTimePicker extends View implements AlarmTimePicker, AnimationFinishedListener { int minSize; // sizes as a fraction of the clock's radius private final static float GRAB_POINT_SIZE = 0.1f; private final static float HAND_WIDTH = 0.02f; private final static float HOUR_HAND_LENGTH = 0.55f; private final static float CLOCK_NUMBER_SIZE = 0.2f; private final static float BAR_HEIGHT = 0.25f; // as a fraction of bar height private final static float SPACER_SIZE = 0.2f; private final static double MINUTE_INCREMENT = Math.PI / 30.0; private final static double HOUR_INCREMENT = Math.PI / 6.0; private final static int MAX_INTERVAL = 45; private int initialMinutes = 0; private int initialHours = 0; private int initialInterval = 0; private boolean componentsCreated = false; private boolean enabled = true; private boolean is24Hour = true; private List<AlarmTimeChangedListener> alarmTimeChangedListeners = new LinkedList<AlarmTimeChangedListener>(); Slider intervalSlider; AnalogClock analogClock; TimeDisplay timeDisplay; MinuteHand minuteHand; HourHand hourHand; List<Movable> movables = new LinkedList<Movable>(); public CustomTimePicker(Context context, AttributeSet attrs) { super(context, attrs); this.minSize = Integer.parseInt(attrs.getAttributeValue("http://schemas.android.com/apk/res/ohtu.beddit", "minSize")); initializePaints(); } protected void onDraw(Canvas c) { analogClock.draw(c); minuteHand.draw(c); hourHand.draw(c); timeDisplay.draw(c); intervalSlider.draw(c); } public boolean onTouchEvent(MotionEvent me) { if (enabled) { boolean eventHandled = false; float x = me.getX(), y = me.getY(); switch (me.getAction()) { case (MotionEvent.ACTION_UP): for (Movable mv : movables) { if (mv.wasClicked()) mv.animate(mv.createTargetFromClick(x, y), this); mv.releaseClick(); if (mv.isGrabbed()) { mv.releaseGrab(); for (AlarmTimeChangedListener l : alarmTimeChangedListeners) l.onAlarmTimeChanged(hourHand.getValue(), minuteHand.getValue(), intervalSlider.getValue()); } } eventHandled = true; break; case (MotionEvent.ACTION_DOWN): for (Movable mv : movables) if (eventHandled = mv.grab(x, y)) return true; for (Movable mv : movables) if (eventHandled = mv.click(x, y)) return true; break; case (MotionEvent.ACTION_MOVE): for (Movable mv : movables) if (mv.isGrabbed()) mv.updatePositionFromClick(x, y); eventHandled = true; break; } invalidate(); return eventHandled; } else { return false; } } Paint linePaint = new Paint(); Paint timePaint = new Paint(); Paint clockFaceLinePaint = new Paint(); Paint backgroundPaint = new Paint(); Paint intervalArcPaint = new Paint(); private void initializePaints() { linePaint.setAntiAlias(true); linePaint.setColor(Color.BLACK); linePaint.setStyle(Paint.Style.STROKE); timePaint.setAntiAlias(true); timePaint.setColor(Color.BLACK); clockFaceLinePaint.setColor(Color.BLACK - (70 << 24)); clockFaceLinePaint.setAntiAlias(true); intervalArcPaint.setColor(Color.argb(255,255,89,0)); backgroundPaint.setColor(Color.WHITE); intervalArcPaint.setAntiAlias(true); backgroundPaint.setAntiAlias(true); } private void createComponents() { - float radius = getHeight() >= (1 + BAR_HEIGHT) * getWidth() ? - getWidth() * 0.5f : Math.min(getWidth(), getHeight()) * (0.5f - BAR_HEIGHT); + float radius = (getHeight() / 2) * (1-BAR_HEIGHT); + if (radius*2 > getWidth()) + radius = getWidth() / 2; float barHeight = (radius * BAR_HEIGHT)*(1-SPACER_SIZE); float barSpacer = barHeight * SPACER_SIZE; float midX = getWidth() / 2f; float midY = getHeight() / 2f; float grabPointSize = radius * GRAB_POINT_SIZE; // update scaled paint attributes linePaint.setStrokeWidth(radius * HAND_WIDTH); timePaint.setTextSize(barHeight); clockFaceLinePaint.setTextSize(radius * CLOCK_NUMBER_SIZE); // create individual view components intervalSlider = new Slider(midX - radius * 0.9f, midY + radius + barSpacer, radius * 1.8f, barHeight, MAX_INTERVAL, initialInterval, linePaint, grabPointSize, this); hourHand = new HourHand(midX, midY, initialHours, HOUR_INCREMENT, radius * HOUR_HAND_LENGTH, linePaint, grabPointSize, this); minuteHand = new MinuteHand(midX, midY, initialMinutes, MINUTE_INCREMENT, radius, linePaint, grabPointSize, this, hourHand); analogClock = new AnalogClock(midX, midY, radius, intervalArcPaint, backgroundPaint, clockFaceLinePaint, minuteHand, hourHand); timeDisplay = new TimeDisplay(midX, midY - radius - barSpacer, timePaint, is24Hour); // link components together intervalSlider.addListener(analogClock); hourHand.addListener(timeDisplay); minuteHand.addListener(hourHand); minuteHand.addListener(timeDisplay); // make sure we have the right initial values analogClock.onValueChanged(initialInterval); hourHand.onMinuteChanged(initialMinutes); timeDisplay.onHourChanged(initialHours); timeDisplay.onMinuteChanged(initialMinutes); movables.clear(); movables.add(hourHand); movables.add(minuteHand); movables.add(intervalSlider); componentsCreated = true; } private int measureWidth(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { result = specSize; } else { result = minSize; if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } return result; } private int measureHeight(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { result = specSize; } else { result = minSize; if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } return result; } @Override public void onAnimationFinished() { for (AlarmTimeChangedListener l : alarmTimeChangedListeners) l.onAlarmTimeChanged(hourHand.getValue(), minuteHand.getValue(), intervalSlider.getValue()); } //<editor-fold overrides> @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec)); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); createComponents(); } @Override public int getHours() { if (componentsCreated) return hourHand.getValue(); else return initialHours; } @Override public int getMinutes() { if (componentsCreated) return minuteHand.getValue(); else return initialMinutes; } @Override public int getInterval() { if (componentsCreated) return intervalSlider.getValue(); else return initialInterval; } @Override public void setHours(int hours) { if (componentsCreated) hourHand.setValue(hours); else initialHours = hours; } @Override public void setMinutes(int minutes) { if (componentsCreated) minuteHand.setValue(minutes); else initialMinutes = minutes; } @Override public void setInterval(int interval) { if (componentsCreated) intervalSlider.setValue(interval); else initialInterval = interval; } @Override public void setEnabled(boolean enabled) { this.enabled = enabled; } @Override public boolean isEnabled() { return enabled; } @Override public void setBackgroundColor(int c) { backgroundPaint.setColor(c); } @Override public void setForegroundColor(int c) { linePaint.setColor(c); timePaint.setColor(c); clockFaceLinePaint.setColor(c - (64 << 24)); } @Override public void setSpecialColor(int c) { intervalArcPaint.setColor(c); } @Override public void set24HourMode(boolean b) { if (componentsCreated) timeDisplay.setIs24Hour(b); else is24Hour = b; } @Override public void addAlarmTimeChangedListener(AlarmTimeChangedListener l) { alarmTimeChangedListeners.add(l); } //</editor-fold> }
true
true
private void createComponents() { float radius = getHeight() >= (1 + BAR_HEIGHT) * getWidth() ? getWidth() * 0.5f : Math.min(getWidth(), getHeight()) * (0.5f - BAR_HEIGHT); float barHeight = (radius * BAR_HEIGHT)*(1-SPACER_SIZE); float barSpacer = barHeight * SPACER_SIZE; float midX = getWidth() / 2f; float midY = getHeight() / 2f; float grabPointSize = radius * GRAB_POINT_SIZE; // update scaled paint attributes linePaint.setStrokeWidth(radius * HAND_WIDTH); timePaint.setTextSize(barHeight); clockFaceLinePaint.setTextSize(radius * CLOCK_NUMBER_SIZE); // create individual view components intervalSlider = new Slider(midX - radius * 0.9f, midY + radius + barSpacer, radius * 1.8f, barHeight, MAX_INTERVAL, initialInterval, linePaint, grabPointSize, this); hourHand = new HourHand(midX, midY, initialHours, HOUR_INCREMENT, radius * HOUR_HAND_LENGTH, linePaint, grabPointSize, this); minuteHand = new MinuteHand(midX, midY, initialMinutes, MINUTE_INCREMENT, radius, linePaint, grabPointSize, this, hourHand); analogClock = new AnalogClock(midX, midY, radius, intervalArcPaint, backgroundPaint, clockFaceLinePaint, minuteHand, hourHand); timeDisplay = new TimeDisplay(midX, midY - radius - barSpacer, timePaint, is24Hour); // link components together intervalSlider.addListener(analogClock); hourHand.addListener(timeDisplay); minuteHand.addListener(hourHand); minuteHand.addListener(timeDisplay); // make sure we have the right initial values analogClock.onValueChanged(initialInterval); hourHand.onMinuteChanged(initialMinutes); timeDisplay.onHourChanged(initialHours); timeDisplay.onMinuteChanged(initialMinutes); movables.clear(); movables.add(hourHand); movables.add(minuteHand); movables.add(intervalSlider); componentsCreated = true; }
private void createComponents() { float radius = (getHeight() / 2) * (1-BAR_HEIGHT); if (radius*2 > getWidth()) radius = getWidth() / 2; float barHeight = (radius * BAR_HEIGHT)*(1-SPACER_SIZE); float barSpacer = barHeight * SPACER_SIZE; float midX = getWidth() / 2f; float midY = getHeight() / 2f; float grabPointSize = radius * GRAB_POINT_SIZE; // update scaled paint attributes linePaint.setStrokeWidth(radius * HAND_WIDTH); timePaint.setTextSize(barHeight); clockFaceLinePaint.setTextSize(radius * CLOCK_NUMBER_SIZE); // create individual view components intervalSlider = new Slider(midX - radius * 0.9f, midY + radius + barSpacer, radius * 1.8f, barHeight, MAX_INTERVAL, initialInterval, linePaint, grabPointSize, this); hourHand = new HourHand(midX, midY, initialHours, HOUR_INCREMENT, radius * HOUR_HAND_LENGTH, linePaint, grabPointSize, this); minuteHand = new MinuteHand(midX, midY, initialMinutes, MINUTE_INCREMENT, radius, linePaint, grabPointSize, this, hourHand); analogClock = new AnalogClock(midX, midY, radius, intervalArcPaint, backgroundPaint, clockFaceLinePaint, minuteHand, hourHand); timeDisplay = new TimeDisplay(midX, midY - radius - barSpacer, timePaint, is24Hour); // link components together intervalSlider.addListener(analogClock); hourHand.addListener(timeDisplay); minuteHand.addListener(hourHand); minuteHand.addListener(timeDisplay); // make sure we have the right initial values analogClock.onValueChanged(initialInterval); hourHand.onMinuteChanged(initialMinutes); timeDisplay.onHourChanged(initialHours); timeDisplay.onMinuteChanged(initialMinutes); movables.clear(); movables.add(hourHand); movables.add(minuteHand); movables.add(intervalSlider); componentsCreated = true; }
diff --git a/src/jvm/com/twitter/maple/hbase/HBaseTap.java b/src/jvm/com/twitter/maple/hbase/HBaseTap.java index 15f4936..bd7c0c4 100644 --- a/src/jvm/com/twitter/maple/hbase/HBaseTap.java +++ b/src/jvm/com/twitter/maple/hbase/HBaseTap.java @@ -1,278 +1,278 @@ /* * Copyright (c) 2009 Concurrent, Inc. * * This work has been released into the public domain * by the copyright holder. This applies worldwide. * * In case this is not legally possible: * The copyright holder grants any entity the right * to use this work for any purpose, without any * conditions, unless such conditions are required by law. */ package com.twitter.maple.hbase; import cascading.flow.FlowProcess; import cascading.tap.SinkMode; import cascading.tap.Tap; import cascading.tap.hadoop.io.HadoopTupleEntrySchemeCollector; import cascading.tap.hadoop.io.HadoopTupleEntrySchemeIterator; import cascading.tuple.TupleEntryCollector; import cascading.tuple.TupleEntryIterator; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.mapreduce.TableOutputFormat; import org.apache.hadoop.mapred.FileInputFormat; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.RecordReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import java.io.IOException; import java.util.Map.Entry; import java.util.UUID; /** * The HBaseTap class is a {@link Tap} subclass. It is used in conjunction with * the {@HBaseFullScheme} to allow for the reading and writing * of data to and from a HBase cluster. */ public class HBaseTap extends Tap<JobConf, RecordReader, OutputCollector> { /** Field LOG */ private static final Logger LOG = LoggerFactory.getLogger(HBaseTap.class); private final String id = UUID.randomUUID().toString(); /** Field SCHEME */ public static final String SCHEME = "hbase"; /** Field hBaseAdmin */ private transient HBaseAdmin hBaseAdmin; /** Field hostName */ private String quorumNames; /** Field tableName */ private String tableName; /** * Constructor HBaseTap creates a new HBaseTap instance. * * @param tableName * of type String * @param HBaseFullScheme * of type HBaseFullScheme */ public HBaseTap(String tableName, HBaseScheme HBaseFullScheme) { super(HBaseFullScheme, SinkMode.UPDATE); this.tableName = tableName; } /** * Constructor HBaseTap creates a new HBaseTap instance. * * @param tableName * of type String * @param HBaseFullScheme * of type HBaseFullScheme * @param sinkMode * of type SinkMode */ public HBaseTap(String tableName, HBaseScheme HBaseFullScheme, SinkMode sinkMode) { super(HBaseFullScheme, sinkMode); this.tableName = tableName; } /** * Constructor HBaseTap creates a new HBaseTap instance. * * @param tableName * of type String * @param HBaseFullScheme * of type HBaseFullScheme */ public HBaseTap(String quorumNames, String tableName, HBaseScheme HBaseFullScheme) { super(HBaseFullScheme, SinkMode.UPDATE); this.quorumNames = quorumNames; this.tableName = tableName; } /** * Constructor HBaseTap creates a new HBaseTap instance. * * @param tableName * of type String * @param HBaseFullScheme * of type HBaseFullScheme * @param sinkMode * of type SinkMode */ public HBaseTap(String quorumNames, String tableName, HBaseScheme HBaseFullScheme, SinkMode sinkMode) { super(HBaseFullScheme, sinkMode); this.quorumNames = quorumNames; this.tableName = tableName; } /** * Method getTableName returns the tableName of this HBaseTap object. * * @return the tableName (type String) of this HBaseTap object. */ public String getTableName() { return tableName; } public Path getPath() { return new Path(SCHEME + ":/" + tableName.replaceAll(":", "_")); } private HBaseAdmin getHBaseAdmin(JobConf conf) throws MasterNotRunningException, ZooKeeperConnectionException { if (hBaseAdmin == null) { Configuration hbaseConf = HBaseConfiguration.create(conf); hBaseAdmin = new HBaseAdmin(hbaseConf); } return hBaseAdmin; } @Override public void sinkConfInit(FlowProcess<JobConf> process, JobConf conf) { if(quorumNames != null) { conf.set("hbase.zookeeper.quorum", quorumNames); } LOG.debug("sinking to table: {}", tableName); if (isReplace() && conf.get("mapred.task.partition") == null) { try { deleteResource(conf); } catch (IOException e) { throw new RuntimeException("could not delete resource: " + e); } } else if (isUpdate()) { try { createResource(conf); } catch (IOException e) { - throw new RuntimeException(tableName + " does not exist !"); + throw new RuntimeException(tableName + " does not exist !", e); } } conf.set(TableOutputFormat.OUTPUT_TABLE, tableName); super.sinkConfInit(process, conf); } @Override public String getIdentifier() { return id; } @Override public TupleEntryIterator openForRead(FlowProcess<JobConf> jobConfFlowProcess, RecordReader recordReader) throws IOException { return new HadoopTupleEntrySchemeIterator(jobConfFlowProcess, this, recordReader); } @Override public TupleEntryCollector openForWrite(FlowProcess<JobConf> jobConfFlowProcess, OutputCollector outputCollector) throws IOException { HBaseTapCollector hBaseCollector = new HBaseTapCollector( jobConfFlowProcess, this ); hBaseCollector.prepare(); return hBaseCollector; } @Override public boolean createResource(JobConf jobConf) throws IOException { HBaseAdmin hBaseAdmin = getHBaseAdmin(jobConf); if (hBaseAdmin.tableExists(tableName)) { return true; } LOG.info("creating hbase table: {}", tableName); HTableDescriptor tableDescriptor = new HTableDescriptor(tableName); String[] familyNames = ((HBaseScheme) getScheme()).getFamilyNames(); for (String familyName : familyNames) { tableDescriptor.addFamily(new HColumnDescriptor(familyName)); } hBaseAdmin.createTable(tableDescriptor); return true; } @Override public boolean deleteResource(JobConf jobConf) throws IOException { // eventually keep table meta-data to source table create HBaseAdmin hBaseAdmin = getHBaseAdmin(jobConf); if (!hBaseAdmin.tableExists(tableName)) { return true; } LOG.info("deleting hbase table: {}", tableName); hBaseAdmin.disableTable(tableName); hBaseAdmin.deleteTable(tableName); return true; } @Override public boolean resourceExists(JobConf jobConf) throws IOException { return getHBaseAdmin(jobConf).tableExists(tableName); } @Override public long getModifiedTime(JobConf jobConf) throws IOException { return System.currentTimeMillis(); // currently unable to find last mod time // on a table } @Override public void sourceConfInit(FlowProcess<JobConf> process, JobConf conf) { if(quorumNames != null) { conf.set("hbase.zookeeper.quorum", quorumNames); } LOG.debug("sourcing from table: {}", tableName); FileInputFormat.addInputPaths(conf, tableName); super.sourceConfInit(process, conf); } @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null || getClass() != object.getClass()) { return false; } if (!super.equals(object)) { return false; } HBaseTap hBaseTap = (HBaseTap) object; if (tableName != null ? !tableName.equals(hBaseTap.tableName) : hBaseTap.tableName != null) { return false; } return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (tableName != null ? tableName.hashCode() : 0); return result; } }
true
true
public void sinkConfInit(FlowProcess<JobConf> process, JobConf conf) { if(quorumNames != null) { conf.set("hbase.zookeeper.quorum", quorumNames); } LOG.debug("sinking to table: {}", tableName); if (isReplace() && conf.get("mapred.task.partition") == null) { try { deleteResource(conf); } catch (IOException e) { throw new RuntimeException("could not delete resource: " + e); } } else if (isUpdate()) { try { createResource(conf); } catch (IOException e) { throw new RuntimeException(tableName + " does not exist !"); } } conf.set(TableOutputFormat.OUTPUT_TABLE, tableName); super.sinkConfInit(process, conf); }
public void sinkConfInit(FlowProcess<JobConf> process, JobConf conf) { if(quorumNames != null) { conf.set("hbase.zookeeper.quorum", quorumNames); } LOG.debug("sinking to table: {}", tableName); if (isReplace() && conf.get("mapred.task.partition") == null) { try { deleteResource(conf); } catch (IOException e) { throw new RuntimeException("could not delete resource: " + e); } } else if (isUpdate()) { try { createResource(conf); } catch (IOException e) { throw new RuntimeException(tableName + " does not exist !", e); } } conf.set(TableOutputFormat.OUTPUT_TABLE, tableName); super.sinkConfInit(process, conf); }
diff --git a/api-maven/src/test/java/org/jboss/shrinkwrap/resolver/api/maven/coordinate/MavenDependencyImplTestCase.java b/api-maven/src/test/java/org/jboss/shrinkwrap/resolver/api/maven/coordinate/MavenDependencyImplTestCase.java index c77ed9e..b24d76b 100644 --- a/api-maven/src/test/java/org/jboss/shrinkwrap/resolver/api/maven/coordinate/MavenDependencyImplTestCase.java +++ b/api-maven/src/test/java/org/jboss/shrinkwrap/resolver/api/maven/coordinate/MavenDependencyImplTestCase.java @@ -1,207 +1,207 @@ /* * JBoss, Home of Professional Open Source * Copyright 2012, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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 org.jboss.shrinkwrap.resolver.api.maven.coordinate; import java.util.Iterator; import java.util.Set; import org.jboss.shrinkwrap.resolver.api.maven.PackagingType; import org.jboss.shrinkwrap.resolver.api.maven.ScopeType; import org.junit.Assert; import org.junit.Test; /** * Tests asserting that the {@link MavenDependencyImpl} is working as contracted * * @author <a href="mailto:[email protected]">Andrew Lee Rubinger</a> */ public class MavenDependencyImplTestCase { @Test public void equalsByValueNoExclusions() { final MavenCoordinate coordinate = this.createCoordinate(); final ScopeType scope = ScopeType.RUNTIME; final boolean optional = true; final MavenDependency dependency1 = new MavenDependencyImpl(coordinate, scope, optional); final MavenDependency dependency2 = new MavenDependencyImpl(coordinate, scope, optional); Assert.assertEquals(dependency1, dependency2); } @Test public void equalsByValueExclusions() { final MavenCoordinate coordinate = this.createCoordinate(); final ScopeType scope = ScopeType.RUNTIME; final boolean optional = true; final MavenDependencyExclusion exclusion1 = new MavenDependencyExclusionImpl("groupId1", "artifactId1"); final MavenDependencyExclusion exclusion2 = new MavenDependencyExclusionImpl("groupId2", "artifactId2"); final MavenDependency dependency1 = new MavenDependencyImpl(coordinate, scope, optional, exclusion1, exclusion2); final MavenDependency dependency2 = new MavenDependencyImpl(coordinate, scope, optional, exclusion1, exclusion2); Assert.assertEquals(dependency1, dependency2); } @Test public void equalsByValueExclusionsUnordered() { final MavenCoordinate coordinate = this.createCoordinate(); final ScopeType scope = ScopeType.RUNTIME; final boolean optional = true; final MavenDependencyExclusion exclusion11 = new MavenDependencyExclusionImpl("groupId1", "artifactId1"); final MavenDependencyExclusion exclusion12 = new MavenDependencyExclusionImpl("groupId2", "artifactId2"); final MavenDependencyExclusion exclusion21 = new MavenDependencyExclusionImpl("groupId1", "artifactId1"); final MavenDependencyExclusion exclusion22 = new MavenDependencyExclusionImpl("groupId2", "artifactId2"); final MavenDependency dependency1 = new MavenDependencyImpl(coordinate, scope, optional, exclusion11, exclusion12); final MavenDependency dependency2 = new MavenDependencyImpl(coordinate, scope, optional, exclusion22, exclusion21); Assert.assertEquals(dependency1, dependency2); } @Test public void notEqualsByValueExclusions() { final MavenCoordinate coordinate = this.createCoordinate(); final ScopeType scope = ScopeType.RUNTIME; final boolean optional = true; final MavenDependencyExclusion exclusion1 = new MavenDependencyExclusionImpl("groupId1", "artifactId1"); final MavenDependencyExclusion exclusion2 = new MavenDependencyExclusionImpl("wrong", "artifactId2"); final MavenDependency dependency1 = new MavenDependencyImpl(coordinate, scope, optional, exclusion1); final MavenDependency dependency2 = new MavenDependencyImpl(coordinate, scope, optional, exclusion2); Assert.assertTrue(dependency1.equals(dependency2)); } @Test public void notEqualsByValueExclusionsMismatchThis() { final MavenCoordinate coordinate = this.createCoordinate(); final ScopeType scope = ScopeType.RUNTIME; final boolean optional = true; final MavenDependencyExclusion exclusion = new MavenDependencyExclusionImpl("groupId1", "artifactId1"); final MavenDependency dependency1 = new MavenDependencyImpl(coordinate, scope, optional); final MavenDependency dependency2 = new MavenDependencyImpl(coordinate, scope, optional, exclusion); Assert.assertTrue(dependency1.equals(dependency2)); } @Test public void notEqualsByValueExclusionsMismatchThat() { final MavenCoordinate coordinate = this.createCoordinate(); final ScopeType scope = ScopeType.RUNTIME; final boolean optional = true; final MavenDependencyExclusion exclusion = new MavenDependencyExclusionImpl("groupId1", "artifactId1"); final MavenDependency dependency1 = new MavenDependencyImpl(coordinate, scope, optional, exclusion); final MavenDependency dependency2 = new MavenDependencyImpl(coordinate, scope, optional); Assert.assertTrue(dependency1.equals(dependency2)); } @Test public void notEqualsByValueCoordinate() { final MavenCoordinate coordinate = this.createCoordinate(); final ScopeType scope = ScopeType.RUNTIME; final boolean optional = true; final MavenDependency dependency1 = new MavenDependencyImpl(coordinate, scope, optional); final MavenDependency dependency2 = new MavenDependencyImpl(new MavenCoordinateImpl("g", "a", "v", null, "c"), scope, optional); Assert.assertFalse(dependency1.equals(dependency2)); } @Test public void notEqualsByValueScope() { final MavenCoordinate coordinate = this.createCoordinate(); final ScopeType scope = ScopeType.RUNTIME; final boolean optional = true; final MavenDependency dependency1 = new MavenDependencyImpl(coordinate, scope, optional); final MavenDependency dependency2 = new MavenDependencyImpl(coordinate, ScopeType.IMPORT, optional); Assert.assertTrue(dependency1.equals(dependency2)); } @Test public void notEqualsByValueOptional() { final MavenCoordinate coordinate = this.createCoordinate(); final ScopeType scope = ScopeType.RUNTIME; final boolean optional = true; final MavenDependency dependency1 = new MavenDependencyImpl(coordinate, scope, optional); final MavenDependency dependency2 = new MavenDependencyImpl(coordinate, scope, false); Assert.assertTrue(dependency1.equals(dependency2)); } @Test public void equalHashCodes() { final MavenCoordinate coordinate = this.createCoordinate(); final ScopeType scope = ScopeType.RUNTIME; final boolean optional = true; final MavenDependencyExclusion exclusion1 = new MavenDependencyExclusionImpl("groupId1", "artifactId1"); final MavenDependencyExclusion exclusion2 = new MavenDependencyExclusionImpl("groupId2", "artifactId2"); final MavenDependency dependency1 = new MavenDependencyImpl(coordinate, scope, optional, exclusion1, exclusion2); final MavenDependency dependency2 = new MavenDependencyImpl(coordinate, scope, optional, exclusion1, exclusion2); Assert.assertTrue(dependency1.hashCode() == dependency2.hashCode()); } @Test public void properties() { final String groupId = "groupId"; final String artifactId = "artifactId"; final String version = "version"; final PackagingType packaging = PackagingType.POM; final String classifier = "classifier"; final ScopeType scope = ScopeType.IMPORT; final boolean optional = true; final MavenCoordinate coordinate = new MavenCoordinateImpl(groupId, artifactId, version, packaging, classifier); final MavenDependencyExclusion exclusion1 = new MavenDependencyExclusionImpl("groupId1", "artifactId1"); final MavenDependencyExclusion exclusion2 = new MavenDependencyExclusionImpl("groupId2", "artifactId2"); final MavenDependency dependency = new MavenDependencyImpl(coordinate, scope, optional, exclusion1, exclusion2); Assert.assertEquals(groupId, dependency.getGroupId()); Assert.assertEquals(artifactId, dependency.getArtifactId()); Assert.assertEquals(version, dependency.getVersion()); Assert.assertEquals(packaging, dependency.getPackaging()); Assert.assertEquals(classifier, dependency.getClassifier()); final Set<MavenDependencyExclusion> exclusions = dependency.getExclusions(); Assert.assertEquals(2, exclusions.size()); final Iterator<MavenDependencyExclusion> it = exclusions.iterator(); final MavenDependencyExclusion roundtrip1 = it.next(); - Assert.assertEquals(exclusion1, roundtrip1); + Assert.assertTrue(exclusions.contains(roundtrip1)); final MavenDependencyExclusion roundtrip2 = it.next(); - Assert.assertEquals(exclusion2, roundtrip2); + Assert.assertTrue(exclusions.contains(roundtrip2)); Assert.assertEquals(groupId + ":" + artifactId + ":" + packaging.toString() + ":" + classifier + ":" + version, dependency.toCanonicalForm()); } @Test public void prohibitAddingExclusions() { final MavenCoordinate coordinate = this.createCoordinate(); final MavenDependency dependency = new MavenDependencyImpl(coordinate, null, true); final MavenDependencyExclusion exclusion = new MavenDependencyExclusionImpl("g", "a"); boolean gotExpectedException = false; try { dependency.getExclusions().add(exclusion); } catch (final UnsupportedOperationException uoe) { gotExpectedException = true; } Assert.assertTrue(gotExpectedException); } @Test public void defaultScope() { final MavenCoordinate coordinate = this.createCoordinate(); final boolean optional = true; final MavenDependency dependency = new MavenDependencyImpl(coordinate, null, optional); Assert.assertEquals(ScopeType.COMPILE, dependency.getScope()); } private MavenCoordinate createCoordinate() { final String groupId = "groupId"; final String artifactId = "artifactId"; final String version = "version"; final PackagingType packaging = PackagingType.POM; final String classifier = "classifier"; final MavenCoordinate coordinate = new MavenCoordinateImpl(groupId, artifactId, version, packaging, classifier); return coordinate; } }
false
true
public void properties() { final String groupId = "groupId"; final String artifactId = "artifactId"; final String version = "version"; final PackagingType packaging = PackagingType.POM; final String classifier = "classifier"; final ScopeType scope = ScopeType.IMPORT; final boolean optional = true; final MavenCoordinate coordinate = new MavenCoordinateImpl(groupId, artifactId, version, packaging, classifier); final MavenDependencyExclusion exclusion1 = new MavenDependencyExclusionImpl("groupId1", "artifactId1"); final MavenDependencyExclusion exclusion2 = new MavenDependencyExclusionImpl("groupId2", "artifactId2"); final MavenDependency dependency = new MavenDependencyImpl(coordinate, scope, optional, exclusion1, exclusion2); Assert.assertEquals(groupId, dependency.getGroupId()); Assert.assertEquals(artifactId, dependency.getArtifactId()); Assert.assertEquals(version, dependency.getVersion()); Assert.assertEquals(packaging, dependency.getPackaging()); Assert.assertEquals(classifier, dependency.getClassifier()); final Set<MavenDependencyExclusion> exclusions = dependency.getExclusions(); Assert.assertEquals(2, exclusions.size()); final Iterator<MavenDependencyExclusion> it = exclusions.iterator(); final MavenDependencyExclusion roundtrip1 = it.next(); Assert.assertEquals(exclusion1, roundtrip1); final MavenDependencyExclusion roundtrip2 = it.next(); Assert.assertEquals(exclusion2, roundtrip2); Assert.assertEquals(groupId + ":" + artifactId + ":" + packaging.toString() + ":" + classifier + ":" + version, dependency.toCanonicalForm()); }
public void properties() { final String groupId = "groupId"; final String artifactId = "artifactId"; final String version = "version"; final PackagingType packaging = PackagingType.POM; final String classifier = "classifier"; final ScopeType scope = ScopeType.IMPORT; final boolean optional = true; final MavenCoordinate coordinate = new MavenCoordinateImpl(groupId, artifactId, version, packaging, classifier); final MavenDependencyExclusion exclusion1 = new MavenDependencyExclusionImpl("groupId1", "artifactId1"); final MavenDependencyExclusion exclusion2 = new MavenDependencyExclusionImpl("groupId2", "artifactId2"); final MavenDependency dependency = new MavenDependencyImpl(coordinate, scope, optional, exclusion1, exclusion2); Assert.assertEquals(groupId, dependency.getGroupId()); Assert.assertEquals(artifactId, dependency.getArtifactId()); Assert.assertEquals(version, dependency.getVersion()); Assert.assertEquals(packaging, dependency.getPackaging()); Assert.assertEquals(classifier, dependency.getClassifier()); final Set<MavenDependencyExclusion> exclusions = dependency.getExclusions(); Assert.assertEquals(2, exclusions.size()); final Iterator<MavenDependencyExclusion> it = exclusions.iterator(); final MavenDependencyExclusion roundtrip1 = it.next(); Assert.assertTrue(exclusions.contains(roundtrip1)); final MavenDependencyExclusion roundtrip2 = it.next(); Assert.assertTrue(exclusions.contains(roundtrip2)); Assert.assertEquals(groupId + ":" + artifactId + ":" + packaging.toString() + ":" + classifier + ":" + version, dependency.toCanonicalForm()); }
diff --git a/src/haven/Skeleton.java b/src/haven/Skeleton.java index 2eec4aef..ab1c51a9 100644 --- a/src/haven/Skeleton.java +++ b/src/haven/Skeleton.java @@ -1,600 +1,604 @@ /* * This file is part of the Haven & Hearth game client. * Copyright (C) 2009 Fredrik Tolf <[email protected]>, and * Björn Johannessen <[email protected]> * * Redistribution and/or modification of this file is subject to the * terms of the GNU Lesser General Public License, version 3, as * published by the Free Software Foundation. * * 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. * * Other parts of this source tree adhere to other copying * rights. Please see the file `COPYING' in the root directory of the * source tree for details. * * A copy the GNU Lesser General Public License is distributed along * with the source tree of which this file is a part in the file * `doc/LPGL-3'. If it is missing for any reason, please see the Free * Software Foundation's website at <http://www.fsf.org/>, or write * to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ package haven; import java.util.*; import javax.media.opengl.*; public class Skeleton { public final Map<String, Bone> bones = new HashMap<String, Bone>(); public final Bone[] blist; /* Topologically sorted */ public final Pose bindpose; public Skeleton(Collection<Bone> bones) { Set<Bone> bset = new HashSet<Bone>(bones); blist = new Bone[bones.size()]; int idx = 0; for(Bone b : bones) this.bones.put(b.name, b); while(!bset.isEmpty()) { boolean f = false; for(Iterator<Bone> i = bset.iterator(); i.hasNext();) { Bone b = i.next(); boolean has; if(b.parent == null) { has = true; } else { has = false; for(Bone p : blist) { if(p == b.parent) { has = true; break; } } } if(has) { blist[b.idx = idx++] = b; i.remove(); f = true; } } if(!f) throw(new RuntimeException("Cyclical bone hierarchy")); } bindpose = mkbindpose(); } public static class Bone { public String name; public Coord3f ipos, irax; public float irang; public Bone parent; public int idx; public Bone(String name, Coord3f ipos, Coord3f irax, float irang) { this.name = name; this.ipos = ipos; this.irax = irax; this.irang = irang; } } private static float[] rotasq(float[] q, float[] axis, float angle) { float m = (float)Math.sin(angle / 2.0); q[0] = (float)Math.cos(angle / 2.0); q[1] = m * axis[0]; q[2] = m * axis[1]; q[3] = m * axis[2]; return(q); } private static float[] qqmul(float[] d, float[] a, float[] b) { float aw = a[0], ax = a[1], ay = a[2], az = a[3]; float bw = b[0], bx = b[1], by = b[2], bz = b[3]; d[0] = (aw * bw) - (ax * bx) - (ay * by) - (az * bz); d[1] = (aw * bx) + (ax * bw) + (ay * bz) - (az * by); d[2] = (aw * by) - (ax * bz) + (ay * bw) + (az * bx); d[3] = (aw * bz) + (ax * by) - (ay * bx) + (az * bw); return(d); } private static float[] vqrot(float[] d, float[] v, float[] q) { float vx = v[0], vy = v[1], vz = v[2]; float qw = q[0], qx = q[1], qy = q[2], qz = q[3]; /* I dearly wonder how the JIT's common-subexpression * eliminator does on these. */ d[0] = (qw * qw * vx) + (2 * qw * qy * vz) - (2 * qw * qz * vy) + (qx * qx * vx) + (2 * qx * qy * vy) + (2 * qx * qz * vz) - (qz * qz * vx) - (qy * qy * vx); d[1] = (2 * qx * qy * vx) + (qy * qy * vy) + (2 * qy * qz * vz) + (2 * qw * qz * vx) - (qz * qz * vy) + (qw * qw * vy) - (2 * qw * qx * vz) - (qx * qx * vy); d[2] = (2 * qx * qz * vx) + (2 * qy * qz * vy) + (qz * qz * vz) - (2 * qw * qy * vx) - (qy * qy * vz) + (2 * qw * qx * vy) - (qx * qx * vz) + (qw * qw * vz); return(d); } private static float[] vset(float[] d, float[] s) { d[0] = s[0]; d[1] = s[1]; d[2] = s[2]; return(d); } private static float[] qset(float[] d, float[] s) { d[0] = s[0]; d[1] = s[1]; d[2] = s[2]; d[3] = s[3]; return(d); } private static float[] vinv(float[] d, float[] s) { d[0] = -s[0]; d[1] = -s[1]; d[2] = -s[2]; return(d); } private static float[] qinv(float[] d, float[] s) { /* Assumes |s| = 1.0 */ d[0] = s[0]; d[1] = -s[1]; d[2] = -s[2]; d[3] = -s[3]; return(d); } private static float[] vvadd(float[] d, float[] a, float[] b) { float ax = a[0], ay = a[1], az = a[2]; float bx = b[0], by = b[1], bz = b[2]; d[0] = ax + bx; d[1] = ay + by; d[2] = az + bz; return(d); } private static float[] qqslerp(float[] d, float[] a, float[] b, float t) { float aw = a[0], ax = a[1], ay = a[2], az = a[3]; float bw = b[0], bx = b[1], by = b[2], bz = b[3]; if((aw == bw) && (ax == bx) && (ay == by) && (az == bz)) return(qset(d, a)); float cos = (aw * bw) + (ax * bx) + (ay * by) + (az * bz); if(cos < 0) { bw = -bw; bx = -bx; by = -by; bz = -bz; cos = -cos; } float d0, d1; if(cos > 0.9999f) { /* Reasonable threshold? Is this function even critical * for performance? */ d0 = 1.0f - t; d1 = t; } else { float da = (float)Math.acos(Utils.clip(cos, 0.0, 1.0)); float nf = 1.0f / (float)Math.sin(da); d0 = (float)Math.sin((1.0f - t) * da) * nf; d1 = (float)Math.sin(t * da) * nf; } d[0] = (d0 * aw) + (d1 * bw); d[1] = (d0 * ax) + (d1 * bx); d[2] = (d0 * ay) + (d1 * by); d[3] = (d0 * az) + (d1 * bz); return(d); } public Pose mkbindpose() { Pose p = new Pose(); for(int i = 0; i < blist.length; i++) { Bone b = blist[i]; p.lpos[i][0] = b.ipos.x; p.lpos[i][1] = b.ipos.y; p.lpos[i][2] = b.ipos.z; rotasq(p.lrot[i], b.irax.to3a(), b.irang); } p.gbuild(); return(p); } public class Pose { public float[][] lpos, gpos; public float[][] lrot, grot; private Pose from = null; public int seq = 0; private Pose() { int nb = blist.length; lpos = new float[nb][3]; gpos = new float[nb][3]; lrot = new float[nb][4]; grot = new float[nb][4]; } public Pose(Pose from) { this(); this.from = from; reset(); gbuild(); } public Skeleton skel() { return(Skeleton.this); } public void reset() { for(int i = 0; i < blist.length; i++) { vset(lpos[i], from.lpos[i]); qset(lrot[i], from.lrot[i]); } } public void gbuild() { int nb = blist.length; for(int i = 0; i < nb; i++) { Bone b = blist[i]; if(b.parent == null) { gpos[i][0] = lpos[i][0]; gpos[i][1] = lpos[i][1]; gpos[i][2] = lpos[i][2]; grot[i][0] = lrot[i][0]; grot[i][1] = lrot[i][1]; grot[i][2] = lrot[i][2]; grot[i][3] = lrot[i][3]; } else { int pi = b.parent.idx; qqmul(grot[i], grot[pi], lrot[i]); vqrot(gpos[i], lpos[i], grot[pi]); vvadd(gpos[i], gpos[i], gpos[pi]); } } seq++; } public void blend(Pose o, float d) { for(int i = 0; i < blist.length; i++) { qqslerp(lrot[i], lrot[i], o.lrot[i], d); lpos[i][0] = lpos[i][0] + ((o.lpos[i][0] - lpos[i][0]) * d); lpos[i][1] = lpos[i][1] + ((o.lpos[i][1] - lpos[i][1]) * d); lpos[i][2] = lpos[i][2] + ((o.lpos[i][2] - lpos[i][2]) * d); } } public Location bonetrans(final int bone) { return(new Location() { public void xf(GOut g) { GL gl = g.gl; gl.glTranslatef(gpos[bone][0], gpos[bone][1], gpos[bone][2]); float ang = (float)Math.acos(grot[bone][0]) * 2.0f; gl.glRotatef((float)(ang / Math.PI * 180.0), grot[bone][1], grot[bone][2], grot[bone][3]); } }); } public void boneoff(int bone, float[] offtrans) { /* It would be nice if these "new float"s get * stack-allocated. */ float[] rot = new float[4], xlate = new float[3]; rot = qqmul(rot, grot[bone], qinv(rot, bindpose.grot[bone])); xlate = vvadd(xlate, gpos[bone], vqrot(xlate, vinv(xlate, bindpose.gpos[bone]), rot)); offtrans[3] = 0; offtrans[7] = 0; offtrans[11] = 0; offtrans[15] = 1; offtrans[12] = xlate[0]; offtrans[13] = xlate[1]; offtrans[14] = xlate[2]; /* I must admit I don't /quite/ understand why the * rotation needs to be inverted... */ float w = -rot[0], x = rot[1], y = rot[2], z = rot[3]; float xw = x * w * 2, xx = x * x * 2, xy = x * y * 2, xz = x * z * 2; float yw = y * w * 2, yy = y * y * 2, yz = y * z * 2; float zw = z * w * 2, zz = z * z * 2; offtrans[ 0] = 1 - (yy + zz); offtrans[ 5] = 1 - (xx + zz); offtrans[10] = 1 - (xx + yy); offtrans[ 1] = xy - zw; offtrans[ 2] = xz + yw; offtrans[ 4] = xy + zw; offtrans[ 6] = yz - xw; offtrans[ 8] = xz - yw; offtrans[ 9] = yz + xw; } public final Rendered debug = new Rendered() { public void draw(GOut g) { GL gl = g.gl; g.st.put(Light.lighting, null); g.state(States.xray); g.apply(); gl.glBegin(GL.GL_LINES); for(int i = 0; i < blist.length; i++) { if(blist[i].parent != null) { int pi = blist[i].parent.idx; gl.glColor3f(1.0f, 0.0f, 0.0f); gl.glVertex3f(gpos[pi][0], gpos[pi][1], gpos[pi][2]); gl.glColor3f(0.0f, 1.0f, 0.0f); gl.glVertex3f(gpos[i][0], gpos[i][1], gpos[i][2]); } } gl.glEnd(); } public Order setup(RenderList rl) { return(last); } }; } public class PoseMod { public float[][] lpos, lrot; public PoseMod() { int nb = blist.length; lpos = new float[nb][3]; lrot = new float[nb][4]; for(int i = 0; i < nb; i++) lrot[i][0] = 1; } public void reset() { for(int i = 0; i < blist.length; i++) { lpos[i][0] = 0; lpos[i][1] = 0; lpos[i][2] = 0; lrot[i][0] = 1; lrot[i][1] = 0; lrot[i][2] = 0; lrot[i][3] = 0; } } public void rot(int bone, float ang, float ax, float ay, float az) { float[] x = {ax, ay, az}; qqmul(lrot[bone], lrot[bone], rotasq(new float[4], x, ang)); } public void apply(Pose p) { for(int i = 0; i < blist.length; i++) { vvadd(p.lpos[i], p.lpos[i], lpos[i]); qqmul(p.lrot[i], p.lrot[i], lrot[i]); } } public void tick(float dt) { } } public static class Res extends Resource.Layer { public final Skeleton s; public Res(Resource res, byte[] buf) { res.super(); Map<String, Bone> bones = new HashMap<String, Bone>(); Map<Bone, String> pm = new HashMap<Bone, String>(); int[] off = {0}; while(off[0] < buf.length) { String bnm = Utils.strd(buf, off); Coord3f pos = new Coord3f((float)Utils.floatd(buf, off[0]), (float)Utils.floatd(buf, off[0] + 5), (float)Utils.floatd(buf, off[0] + 10)); off[0] += 15; Coord3f rax = new Coord3f((float)Utils.floatd(buf, off[0]), (float)Utils.floatd(buf, off[0] + 5), (float)Utils.floatd(buf, off[0] + 10)).norm(); off[0] += 15; float rang = (float)Utils.floatd(buf, off[0]); off[0] += 5; String bp = Utils.strd(buf, off); Bone b = new Bone(bnm, pos, rax, rang); if(bones.put(bnm, b) != null) throw(new RuntimeException("Duplicate bone name: " + b.name)); pm.put(b, bp); } for(Bone b : bones.values()) { String bp = pm.get(b); if(bp.length() == 0) { b.parent = null; } else { if((b.parent = bones.get(bp)) == null) throw(new Resource.LoadException("Parent bone " + bp + " not found for " + b.name, getres())); } } s = new Skeleton(bones.values()); } public void init() {} } public class TrackMod extends PoseMod { public final Track[] tracks; public final float len; public final boolean stat; public final WrapMode mode; public boolean done; public float time = 0.0f; public boolean speedmod = false; public double nspeed = 0.0; private boolean back = false; public TrackMod(Track[] tracks, float len, WrapMode mode) { this.tracks = tracks; this.len = len; this.mode = mode; for(Track t : tracks) { if((t != null) && (t.frames.length > 1)) { stat = false; return; } } stat = true; aupdate(0.0f); } public void aupdate(float time) { if(time > len) time = len; reset(); for(int i = 0; i < tracks.length; i++) { Track t = tracks[i]; if((t == null) || (t.frames.length == 0)) continue; if(t.frames.length == 1) { qset(lrot[i], t.frames[0].rot); vset(lpos[i], t.frames[0].trans); } else { Track.Frame cf, nf; float ct, nt; int l = 0, r = t.frames.length; while(true) { /* c should never be able to be >= frames.length */ int c = l + ((r - l) >> 1); ct = t.frames[c].time; nt = (c < t.frames.length - 1)?(t.frames[c + 1].time):len; if(ct > time) { r = c; } else if(nt < time) { l = c + 1; } else { cf = t.frames[c]; nf = t.frames[(c + 1) % t.frames.length]; break; } } - float d = (time - ct) / (nt - ct); + float d; + if(nt == ct) + d = 0; + else + d = (time - ct) / (nt - ct); qqslerp(lrot[i], cf.rot, nf.rot, d); lpos[i][0] = cf.trans[0] + ((nf.trans[0] - cf.trans[0]) * d); lpos[i][1] = cf.trans[1] + ((nf.trans[1] - cf.trans[1]) * d); lpos[i][2] = cf.trans[2] + ((nf.trans[2] - cf.trans[2]) * d); } } } public void tick(float dt) { float nt = time + (back?-dt:dt); switch(mode) { case LOOP: nt %= len; break; case ONCE: if(nt > len) { nt = len; done = true; } break; case PONG: if(!back && (nt > len)) { nt = len; back = true; } else if(back && (nt < 0)) { nt = 0; done = true; } break; case PONGLOOP: if(!back && (nt > len)) { nt = len; back = true; } else if(back && (nt < 0)) { nt = 0; back = false; } break; } this.time = nt; if(!stat) aupdate(this.time); } } public static class Track { public final String bone; public final Frame[] frames; public static class Frame { public final float time; public final float[] trans, rot; public Frame(float time, float[] trans, float[] rot) { this.time = time; this.trans = trans; this.rot = rot; } } public Track(String bone, Frame[] frames) { this.bone = bone; this.frames = frames; } } public static class ResPose extends Resource.Layer { public final int id; public final float len; public final Track[] tracks; public final double nspeed; public ResPose(Resource res, byte[] buf) { res.super(); this.id = Utils.int16d(buf, 0); int fl = buf[2]; this.len = (float)Utils.floatd(buf, 3); int[] off = {8}; if((fl & 1) != 0) { nspeed = Utils.floatd(buf, off[0]); off[0] += 5; } else { nspeed = -1; } Collection<Track> tracks = new LinkedList<Track>(); while(off[0] < buf.length) { String bnm = Utils.strd(buf, off); Track.Frame[] frames = new Track.Frame[Utils.uint16d(buf, off[0])]; off[0] += 2; for(int i = 0; i < frames.length; i++) { float tm = (float)Utils.floatd(buf, off[0]); off[0] += 5; float[] trans = new float[3]; for(int o = 0; o < 3; o++) { trans[o] = (float)Utils.floatd(buf, off[0]); off[0] += 5; } float rang = (float)Utils.floatd(buf, off[0]); off[0] += 5; float[] rax = new float[3]; for(int o = 0; o < 3; o++) { rax[o] = (float)Utils.floatd(buf, off[0]); off[0] += 5; } frames[i] = new Track.Frame(tm, trans, rotasq(new float[4], rax, rang)); } tracks.add(new Track(bnm, frames)); } this.tracks = tracks.toArray(new Track[0]); } public TrackMod forskel(Skeleton skel, WrapMode mode) { Track[] remap = new Track[skel.blist.length]; for(Track t : tracks) remap[skel.bones.get(t.bone).idx] = t; TrackMod ret = skel.new TrackMod(remap, len, mode); if(nspeed > 0) { ret.speedmod = true; ret.nspeed = nspeed; } return(ret); } public void init() {} } public static class BoneOffset extends Resource.Layer { public final String bone; public final Coord3f off, rax; public final float rang; public BoneOffset(Resource res, byte[] buf) { res.super(); int[] off = {0}; this.bone = Utils.strd(buf, off); this.off = new Coord3f((float)Utils.floatd(buf, off[0]), (float)Utils.floatd(buf, off[0] + 5), (float)Utils.floatd(buf, off[0] + 10)); off[0] += 15; this.rax = new Coord3f((float)Utils.floatd(buf, off[0]), (float)Utils.floatd(buf, off[0] + 5), (float)Utils.floatd(buf, off[0] + 10)); off[0] += 15; this.rang = (float)Utils.floatd(buf, off[0]); } public void init() { } public class Transform extends Location { public void xf(GOut g) { GL gl = g.gl; gl.glTranslatef(off.x, off.y, off.z); gl.glRotatef(rang * 180.0f / (float)Math.PI, rax.x, rax.y, rax.z); gl.glRotatef(90.0f, 1.0f, 0.0f, 0.0f); } } public Location xf() { return(new Transform()); /* return(Transform.seq(Transform.xlate(off), Transform.rot(rax, rang))); */ } } }
true
true
public void aupdate(float time) { if(time > len) time = len; reset(); for(int i = 0; i < tracks.length; i++) { Track t = tracks[i]; if((t == null) || (t.frames.length == 0)) continue; if(t.frames.length == 1) { qset(lrot[i], t.frames[0].rot); vset(lpos[i], t.frames[0].trans); } else { Track.Frame cf, nf; float ct, nt; int l = 0, r = t.frames.length; while(true) { /* c should never be able to be >= frames.length */ int c = l + ((r - l) >> 1); ct = t.frames[c].time; nt = (c < t.frames.length - 1)?(t.frames[c + 1].time):len; if(ct > time) { r = c; } else if(nt < time) { l = c + 1; } else { cf = t.frames[c]; nf = t.frames[(c + 1) % t.frames.length]; break; } } float d = (time - ct) / (nt - ct); qqslerp(lrot[i], cf.rot, nf.rot, d); lpos[i][0] = cf.trans[0] + ((nf.trans[0] - cf.trans[0]) * d); lpos[i][1] = cf.trans[1] + ((nf.trans[1] - cf.trans[1]) * d); lpos[i][2] = cf.trans[2] + ((nf.trans[2] - cf.trans[2]) * d); } } }
public void aupdate(float time) { if(time > len) time = len; reset(); for(int i = 0; i < tracks.length; i++) { Track t = tracks[i]; if((t == null) || (t.frames.length == 0)) continue; if(t.frames.length == 1) { qset(lrot[i], t.frames[0].rot); vset(lpos[i], t.frames[0].trans); } else { Track.Frame cf, nf; float ct, nt; int l = 0, r = t.frames.length; while(true) { /* c should never be able to be >= frames.length */ int c = l + ((r - l) >> 1); ct = t.frames[c].time; nt = (c < t.frames.length - 1)?(t.frames[c + 1].time):len; if(ct > time) { r = c; } else if(nt < time) { l = c + 1; } else { cf = t.frames[c]; nf = t.frames[(c + 1) % t.frames.length]; break; } } float d; if(nt == ct) d = 0; else d = (time - ct) / (nt - ct); qqslerp(lrot[i], cf.rot, nf.rot, d); lpos[i][0] = cf.trans[0] + ((nf.trans[0] - cf.trans[0]) * d); lpos[i][1] = cf.trans[1] + ((nf.trans[1] - cf.trans[1]) * d); lpos[i][2] = cf.trans[2] + ((nf.trans[2] - cf.trans[2]) * d); } } }
diff --git a/src/net/zionsoft/obadiah/BibleReader.java b/src/net/zionsoft/obadiah/BibleReader.java index 36da9c6..f6b169a 100644 --- a/src/net/zionsoft/obadiah/BibleReader.java +++ b/src/net/zionsoft/obadiah/BibleReader.java @@ -1,165 +1,171 @@ package net.zionsoft.obadiah; import java.io.File; import java.io.FileInputStream; import org.json.JSONArray; import org.json.JSONObject; public class BibleReader { public static BibleReader getInstance() { if (instance == null) instance = new BibleReader(); return instance; } public void setRootDir(File rootDir) { m_rootDir = rootDir; refresh(); } public void refresh() { try { File[] directories = m_rootDir.listFiles(); final int length = directories.length; if (length == 0) return; boolean hasTranslationsFile = false; for (int i = 0; i < length; ++i) { if (directories[i].isFile()) { hasTranslationsFile = true; break; } } - if (hasTranslationsFile) - m_installedTranslations = new TranslationInfo[length - 1]; - else - m_installedTranslations = new TranslationInfo[length]; + if (hasTranslationsFile) { + if (length > 1) + m_installedTranslations = new TranslationInfo[length - 1]; + else + return; + } else { + if (length > 0) + m_installedTranslations = new TranslationInfo[length]; + else return; + } for (int i = 0, index = 0; i < length; ++i) { if (directories[i].isFile()) continue; FileInputStream fis = new FileInputStream(new File(directories[i], BOOKS_FILE)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); m_installedTranslations[index] = new TranslationInfo(); m_installedTranslations[index].path = directories[i].getAbsolutePath(); JSONObject booksInfoObject = new JSONObject(new String(buffer, "UTF8")); m_installedTranslations[index].name = booksInfoObject.getString("name"); JSONArray booksArray = booksInfoObject.getJSONArray("books"); final int booksCount = booksArray.length(); m_installedTranslations[index].bookName = new String[booksCount]; for (int j = 0; j < booksCount; ++j) m_installedTranslations[index].bookName[j] = booksArray.getString(j); ++index; } } catch (Exception e) { e.printStackTrace(); } } public TranslationInfo[] installedTranslations() { return m_installedTranslations; } public void selectTranslation(String translation) { if (m_installedTranslations == null || m_installedTranslations.length == 0) return; if (translation == null) { m_selectedTranslation = m_installedTranslations[0].path; return; } int length = m_installedTranslations.length; for (int i = 0; i < length; ++i) { String path = m_installedTranslations[i].path; if (m_installedTranslations[i].path.endsWith(translation)) { m_selectedTranslation = path; return; } } } public TranslationInfo selectedTranslation() { if (m_selectedTranslation == null) { if (m_installedTranslations != null && m_installedTranslations.length > 0) { m_selectedTranslation = m_installedTranslations[0].path; return m_installedTranslations[0]; } else { return null; } } int length = m_installedTranslations.length; for (int i = 0; i < length; ++i) { if (m_installedTranslations[i].path == m_selectedTranslation) return m_installedTranslations[i]; } return null; } public int chapterCount(int book) { if (book < 0 || book >= CHAPTER_COUNT.length) return 0; return CHAPTER_COUNT[book]; } public String[] verses(int book, int chapter) { try { String path = m_selectedTranslation + "/" + book + "-" + chapter + ".json"; FileInputStream fis = new FileInputStream(new File(path)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); JSONObject jsonObject = new JSONObject(new String(buffer, "UTF8")); JSONArray paragraphArray = jsonObject.getJSONArray("verses"); int paragraphCount = paragraphArray.length(); String[] paragraphs = new String[paragraphCount]; for (int i = 0; i < paragraphCount; ++i) paragraphs[i] = paragraphArray.getString(i); return paragraphs; } catch (Exception e) { e.printStackTrace(); return null; } } private BibleReader() { // do nothing } static { CHAPTER_COUNT = new int[] { 50, 40, 27, 36, 34, 24, 21, 4, 31, 24, 22, 25, 29, 36, 10, 13, 10, 42, 150, 31, 12, 8, 66, 52, 5, 48, 12, 14, 3, 9, 1, 4, 7, 3, 3, 3, 2, 14, 4, 28, 16, 24, 21, 28, 16, 16, 13, 6, 6, 4, 4, 5, 3, 6, 4, 3, 1, 13, 5, 5, 3, 5, 1, 1, 1, 22 }; } private static final int[] CHAPTER_COUNT; private static final String BOOKS_FILE = "books.json"; private static BibleReader instance; private File m_rootDir; private String m_selectedTranslation; private TranslationInfo[] m_installedTranslations; }
true
true
public void refresh() { try { File[] directories = m_rootDir.listFiles(); final int length = directories.length; if (length == 0) return; boolean hasTranslationsFile = false; for (int i = 0; i < length; ++i) { if (directories[i].isFile()) { hasTranslationsFile = true; break; } } if (hasTranslationsFile) m_installedTranslations = new TranslationInfo[length - 1]; else m_installedTranslations = new TranslationInfo[length]; for (int i = 0, index = 0; i < length; ++i) { if (directories[i].isFile()) continue; FileInputStream fis = new FileInputStream(new File(directories[i], BOOKS_FILE)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); m_installedTranslations[index] = new TranslationInfo(); m_installedTranslations[index].path = directories[i].getAbsolutePath(); JSONObject booksInfoObject = new JSONObject(new String(buffer, "UTF8")); m_installedTranslations[index].name = booksInfoObject.getString("name"); JSONArray booksArray = booksInfoObject.getJSONArray("books"); final int booksCount = booksArray.length(); m_installedTranslations[index].bookName = new String[booksCount]; for (int j = 0; j < booksCount; ++j) m_installedTranslations[index].bookName[j] = booksArray.getString(j); ++index; } } catch (Exception e) { e.printStackTrace(); } }
public void refresh() { try { File[] directories = m_rootDir.listFiles(); final int length = directories.length; if (length == 0) return; boolean hasTranslationsFile = false; for (int i = 0; i < length; ++i) { if (directories[i].isFile()) { hasTranslationsFile = true; break; } } if (hasTranslationsFile) { if (length > 1) m_installedTranslations = new TranslationInfo[length - 1]; else return; } else { if (length > 0) m_installedTranslations = new TranslationInfo[length]; else return; } for (int i = 0, index = 0; i < length; ++i) { if (directories[i].isFile()) continue; FileInputStream fis = new FileInputStream(new File(directories[i], BOOKS_FILE)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); m_installedTranslations[index] = new TranslationInfo(); m_installedTranslations[index].path = directories[i].getAbsolutePath(); JSONObject booksInfoObject = new JSONObject(new String(buffer, "UTF8")); m_installedTranslations[index].name = booksInfoObject.getString("name"); JSONArray booksArray = booksInfoObject.getJSONArray("books"); final int booksCount = booksArray.length(); m_installedTranslations[index].bookName = new String[booksCount]; for (int j = 0; j < booksCount; ++j) m_installedTranslations[index].bookName[j] = booksArray.getString(j); ++index; } } catch (Exception e) { e.printStackTrace(); } }
diff --git a/src/main/java/com/jadventure/game/menus/DebugMenu.java b/src/main/java/com/jadventure/game/menus/DebugMenu.java index b40e082..0499e51 100644 --- a/src/main/java/com/jadventure/game/menus/DebugMenu.java +++ b/src/main/java/com/jadventure/game/menus/DebugMenu.java @@ -1,48 +1,47 @@ package com.jadventure.game.menus; import com.jadventure.game.menus.Menus; import com.jadventure.game.entities.Player; import java.util.Scanner; /** * Created with IntelliJ IDEA. * User: Hawk554 * Date: 11/12/13 * Time: 2:15 PM */ public class DebugMenu extends Menus { public static Player player; public DebugMenu(Player p) { - this.menuID = 90; player = p; this.menuItems.add(new MenuItem("pAttack", "Modify Player Attack")); this.menuItems.add(new MenuItem("pHealth", "Modify Player Health")); this.menuItems.add(new MenuItem("pMaxHealth", "Modify Player Max Health")); this.menuItems.add(new MenuItem("pArmour", "Modify Player Armour")); this.menuItems.add(new MenuItem("pLevel", "Modify Player Level")); this.menuItems.add(new MenuItem("pGold", "Modify Player Gold")); this.menuItems.add(new MenuItem("pGold", "Modify Player Backpack")); this.menuItems.add(new MenuItem("Stats", "Display current player stats")); this.menuItems.add(new MenuItem("Exit", "Exits Debug Menu")); boolean continueMenu = true; // == true not neccessary below while (continueMenu) { MenuItem selectedItem = displayMenu(this.menuItems); testOption(selectedItem); //if the person didn't select exit, the game continues continueMenu = !didSelectExit(selectedItem); } } private static boolean didSelectExit(MenuItem m){ return (m.getKey().equalsIgnoreCase("exit")); } private static void testOption(MenuItem m){ Scanner input = new Scanner(System.in); String key = m.getKey(); //put the options in here, check PlayerMenu for equivelent code } }
true
true
public DebugMenu(Player p) { this.menuID = 90; player = p; this.menuItems.add(new MenuItem("pAttack", "Modify Player Attack")); this.menuItems.add(new MenuItem("pHealth", "Modify Player Health")); this.menuItems.add(new MenuItem("pMaxHealth", "Modify Player Max Health")); this.menuItems.add(new MenuItem("pArmour", "Modify Player Armour")); this.menuItems.add(new MenuItem("pLevel", "Modify Player Level")); this.menuItems.add(new MenuItem("pGold", "Modify Player Gold")); this.menuItems.add(new MenuItem("pGold", "Modify Player Backpack")); this.menuItems.add(new MenuItem("Stats", "Display current player stats")); this.menuItems.add(new MenuItem("Exit", "Exits Debug Menu")); boolean continueMenu = true; // == true not neccessary below while (continueMenu) { MenuItem selectedItem = displayMenu(this.menuItems); testOption(selectedItem); //if the person didn't select exit, the game continues continueMenu = !didSelectExit(selectedItem); } }
public DebugMenu(Player p) { player = p; this.menuItems.add(new MenuItem("pAttack", "Modify Player Attack")); this.menuItems.add(new MenuItem("pHealth", "Modify Player Health")); this.menuItems.add(new MenuItem("pMaxHealth", "Modify Player Max Health")); this.menuItems.add(new MenuItem("pArmour", "Modify Player Armour")); this.menuItems.add(new MenuItem("pLevel", "Modify Player Level")); this.menuItems.add(new MenuItem("pGold", "Modify Player Gold")); this.menuItems.add(new MenuItem("pGold", "Modify Player Backpack")); this.menuItems.add(new MenuItem("Stats", "Display current player stats")); this.menuItems.add(new MenuItem("Exit", "Exits Debug Menu")); boolean continueMenu = true; // == true not neccessary below while (continueMenu) { MenuItem selectedItem = displayMenu(this.menuItems); testOption(selectedItem); //if the person didn't select exit, the game continues continueMenu = !didSelectExit(selectedItem); } }
diff --git a/module/org.restlet.test/src/org/restlet/test/ReferenceTestCase.java b/module/org.restlet.test/src/org/restlet/test/ReferenceTestCase.java index 5abad85c4..0e0f9f359 100644 --- a/module/org.restlet.test/src/org/restlet/test/ReferenceTestCase.java +++ b/module/org.restlet.test/src/org/restlet/test/ReferenceTestCase.java @@ -1,331 +1,335 @@ /* * Copyright 2005-2006 Noelios Consulting. * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). You may not use this file except in * compliance with the License. * * You can obtain a copy of the license at * http://www.opensource.org/licenses/cddl1.txt See the License for the specific * language governing permissions and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at http://www.opensource.org/licenses/cddl1.txt If * applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] */ package org.restlet.test; import java.io.IOException; import org.restlet.data.Reference; /** * Test {@link org.restlet.data.Reference}. * * @author Jerome Louvel ([email protected]) * @author Lars Heuer (heuer[at]semagia.com) <a * href="http://www.semagia.com/">Semagia</a> */ public class ReferenceTestCase extends RestletTestCase { protected final static String DEFAULT_SCHEME = "http"; protected final static String DEFAULT_SCHEMEPART = "//"; /** * Tests the URI parsing. */ public void testParsing() throws IOException { String base = "http://a/b/c/d;p?q"; String uri01 = "g:h"; String uri02 = "g"; String uri03 = "./g"; String uri04 = "g/"; String uri05 = "/g"; String uri06 = "//g"; String uri07 = "?y"; String uri08 = "g?y"; String uri09 = "#s"; String uri10 = "g#s"; String uri11 = "g?y#s"; String uri12 = ";x"; String uri13 = "g;x"; String uri14 = "g;x?y#s"; String uri15 = ""; String uri16 = "."; String uri17 = "./"; String uri18 = ".."; String uri19 = "../"; String uri20 = "../g"; String uri21 = "../.."; String uri22 = "../../"; String uri23 = "../../g"; String uri24 = "../../../g"; String uri25 = "../../../../g"; String uri26 = "/./g"; String uri27 = "/../g"; String uri28 = "g."; String uri29 = ".g"; String uri30 = "g.."; String uri31 = "..g"; String uri32 = "./../g"; String uri33 = "./g/."; String uri34 = "g/./h"; String uri35 = "g/../h"; String uri36 = "g;x=1/./y"; String uri37 = "g;x=1/../y"; String uri101 = "g:h"; String uri102 = "http://a/b/c/g"; String uri103 = "http://a/b/c/g"; String uri104 = "http://a/b/c/g/"; String uri105 = "http://a/g"; String uri106 = "http://g"; String uri107 = "http://a/b/c/d;p?y"; String uri108 = "http://a/b/c/g?y"; String uri109 = "http://a/b/c/d;p?q#s"; String uri110 = "http://a/b/c/g#s"; String uri111 = "http://a/b/c/g?y#s"; String uri112 = "http://a/b/c/;x"; String uri113 = "http://a/b/c/g;x"; String uri114 = "http://a/b/c/g;x?y#s"; String uri115 = "http://a/b/c/d;p?q"; String uri116 = "http://a/b/c/"; String uri117 = "http://a/b/c/"; String uri118 = "http://a/b/"; String uri119 = "http://a/b/"; String uri120 = "http://a/b/g"; String uri121 = "http://a/"; String uri122 = "http://a/"; String uri123 = "http://a/g"; String uri124 = "http://a/g"; String uri125 = "http://a/g"; String uri126 = "http://a/g"; String uri127 = "http://a/g"; String uri128 = "http://a/b/c/g."; String uri129 = "http://a/b/c/.g"; String uri130 = "http://a/b/c/g.."; String uri131 = "http://a/b/c/..g"; String uri132 = "http://a/b/g"; String uri133 = "http://a/b/c/g/"; String uri134 = "http://a/b/c/g/h"; String uri135 = "http://a/b/c/h"; String uri136 = "http://a/b/c/g;x=1/y"; String uri137 = "http://a/b/c/y"; // Test the parsing of references into its components testRef0("foo://example.com:8042/over/there?name=ferret#nose", "foo", "example.com:8042", "/over/there", "name=ferret", "nose"); testRef0("urn:example:animal:ferret:nose", "urn", null, "example:animal:ferret:nose", null, null); testRef0("mailto:[email protected]", "mailto", null, "[email protected]", null, null); testRef0("foo://info.example.com?fred", "foo", "info.example.com", null, "fred", null); testRef0("*", null, null, "*", null, null); + testRef0("http://localhost?query", "http", "localhost", null, "query", null); + testRef0("http://localhost#?query", "http", "localhost", null, null, "?query"); + testRef0("http://localhost/?query", "http", "localhost", "/", "query", null); + testRef0("http://localhost/#?query", "http", "localhost", "/", null, "?query"); // Test the resolution of relative references testRef1(base, uri01, uri101); testRef1(base, uri02, uri102); testRef1(base, uri03, uri103); testRef1(base, uri04, uri104); testRef1(base, uri05, uri105); testRef1(base, uri06, uri106); testRef1(base, uri07, uri107); testRef1(base, uri08, uri108); testRef1(base, uri09, uri109); testRef1(base, uri10, uri110); testRef1(base, uri11, uri111); testRef1(base, uri12, uri112); testRef1(base, uri13, uri113); testRef1(base, uri14, uri114); testRef1(base, uri15, uri115); testRef1(base, uri16, uri116); testRef1(base, uri17, uri117); testRef1(base, uri18, uri118); testRef1(base, uri19, uri119); testRef1(base, uri20, uri120); testRef1(base, uri21, uri121); testRef1(base, uri22, uri122); testRef1(base, uri23, uri123); testRef1(base, uri24, uri124); testRef1(base, uri25, uri125); testRef1(base, uri26, uri126); testRef1(base, uri27, uri127); testRef1(base, uri28, uri128); testRef1(base, uri29, uri129); testRef1(base, uri30, uri130); testRef1(base, uri31, uri131); testRef1(base, uri32, uri132); testRef1(base, uri33, uri133); testRef1(base, uri34, uri134); testRef1(base, uri35, uri135); testRef1(base, uri36, uri136); testRef1(base, uri37, uri137); // Test the relativization of absolute references testRef2(base, uri102, uri02); testRef2(base, uri104, uri04); testRef2(base, uri107, uri07); testRef2(base, uri108, uri08); testRef2(base, uri109, uri09); testRef2(base, uri110, uri10); testRef2(base, uri111, uri11); testRef2(base, uri112, uri12); testRef2(base, uri113, uri13); testRef2(base, uri114, uri14); testRef2(base, uri116, uri16); testRef2(base, uri118, uri18); testRef2(base, uri120, uri20); testRef2(base, uri121, uri21); testRef2(base, uri123, uri23); } /** * Tests the parsing of a reference into its components * * @param reference * @param scheme * @param authority * @param path * @param query * @param fragment */ private void testRef0(String reference, String scheme, String authority, String path, String query, String fragment) { Reference ref = new Reference(reference); assertEquals(scheme, ref.getScheme()); assertEquals(authority, ref.getAuthority()); assertEquals(path, ref.getPath()); assertEquals(query, ref.getQuery()); assertEquals(fragment, ref.getFragment()); } /** * Test the resolution of relative references. * * @param baseUri * @param relativeUri * @param expectedAbsoluteUri */ private void testRef1(String baseUri, String relativeUri, String expectedAbsoluteUri) { Reference baseRef = new Reference(baseUri); Reference relativeRef = new Reference(baseRef, relativeUri); Reference absoluteRef = relativeRef.getTargetRef(); assertEquals(expectedAbsoluteUri, absoluteRef.toString()); } /** * Test the relativization of absolute references * * @param baseUri * @param absoluteUri * @param expectedRelativeUri */ private void testRef2(String baseUri, String absoluteUri, String expectedRelativeUri) { Reference baseRef = new Reference(baseUri); Reference absoluteRef = new Reference(absoluteUri); Reference relativeRef = absoluteRef.getRelativeRef(baseRef); assertEquals(expectedRelativeUri, relativeRef.toString()); } /** * Returns a reference with uri == http:// * * @return Reference instance. */ protected Reference getReference() { Reference ref = new Reference(); ref.setScheme(DEFAULT_SCHEME); ref.setSchemeSpecificPart(DEFAULT_SCHEMEPART); return ref; } /** * Returns a reference that is initialized with http://www.restlet.org. * * @return Reference instance. */ protected Reference getDefaultReference() { Reference ref = getReference(); ref.setHostDomain("www.restlet.org"); return ref; } /** * Equality tests. */ public void testEquals() throws Exception { Reference ref1 = getDefaultReference(); Reference ref2 = getDefaultReference(); assertTrue(ref1.equals(ref2)); assertEquals(ref1, ref2); } /** * Test references that are unequal. */ public void testUnEquals() throws Exception { String uri1 = "http://www.restlet.org/"; String uri2 = "http://www.restlet.net/"; Reference ref1 = new Reference(uri1); Reference ref2 = new Reference(uri2); assertFalse(ref1.equals(ref2)); assertFalse(ref1.equals(null)); } /** * Test hostname getting/setting. */ public void testHostName() throws Exception { Reference ref = getReference(); String host = "www.restlet.org"; ref.setHostDomain(host); assertEquals(host, ref.getHostDomain()); host = "restlet.org"; ref.setHostDomain(host); assertEquals(host, ref.getHostDomain()); } /** * Test port getting/setting. */ public void testPort() throws Exception { Reference ref = getDefaultReference(); int port = 8080; ref.setHostPort(port); assertEquals(port, ref.getHostPort().intValue()); port = 9090; ref.setHostPort(port); assertEquals(port, ref.getHostPort().intValue()); } /** * Test scheme getting/setting. */ public void testScheme() throws Exception { Reference ref = getDefaultReference(); assertEquals(DEFAULT_SCHEME, ref.getScheme()); String scheme = "https"; ref.setScheme(scheme); assertEquals(scheme, ref.getScheme()); ref.setScheme(DEFAULT_SCHEME); assertEquals(DEFAULT_SCHEME, ref.getScheme()); } /** * Test scheme specific part getting/setting. */ public void testSchemeSpecificPart() throws Exception { Reference ref = getDefaultReference(); String part = "//www.restlet.org"; assertEquals(part, ref.getSchemeSpecificPart()); part = "//www.restlet.net"; ref.setSchemeSpecificPart(part); assertEquals(part, ref.getSchemeSpecificPart()); } }
true
true
public void testParsing() throws IOException { String base = "http://a/b/c/d;p?q"; String uri01 = "g:h"; String uri02 = "g"; String uri03 = "./g"; String uri04 = "g/"; String uri05 = "/g"; String uri06 = "//g"; String uri07 = "?y"; String uri08 = "g?y"; String uri09 = "#s"; String uri10 = "g#s"; String uri11 = "g?y#s"; String uri12 = ";x"; String uri13 = "g;x"; String uri14 = "g;x?y#s"; String uri15 = ""; String uri16 = "."; String uri17 = "./"; String uri18 = ".."; String uri19 = "../"; String uri20 = "../g"; String uri21 = "../.."; String uri22 = "../../"; String uri23 = "../../g"; String uri24 = "../../../g"; String uri25 = "../../../../g"; String uri26 = "/./g"; String uri27 = "/../g"; String uri28 = "g."; String uri29 = ".g"; String uri30 = "g.."; String uri31 = "..g"; String uri32 = "./../g"; String uri33 = "./g/."; String uri34 = "g/./h"; String uri35 = "g/../h"; String uri36 = "g;x=1/./y"; String uri37 = "g;x=1/../y"; String uri101 = "g:h"; String uri102 = "http://a/b/c/g"; String uri103 = "http://a/b/c/g"; String uri104 = "http://a/b/c/g/"; String uri105 = "http://a/g"; String uri106 = "http://g"; String uri107 = "http://a/b/c/d;p?y"; String uri108 = "http://a/b/c/g?y"; String uri109 = "http://a/b/c/d;p?q#s"; String uri110 = "http://a/b/c/g#s"; String uri111 = "http://a/b/c/g?y#s"; String uri112 = "http://a/b/c/;x"; String uri113 = "http://a/b/c/g;x"; String uri114 = "http://a/b/c/g;x?y#s"; String uri115 = "http://a/b/c/d;p?q"; String uri116 = "http://a/b/c/"; String uri117 = "http://a/b/c/"; String uri118 = "http://a/b/"; String uri119 = "http://a/b/"; String uri120 = "http://a/b/g"; String uri121 = "http://a/"; String uri122 = "http://a/"; String uri123 = "http://a/g"; String uri124 = "http://a/g"; String uri125 = "http://a/g"; String uri126 = "http://a/g"; String uri127 = "http://a/g"; String uri128 = "http://a/b/c/g."; String uri129 = "http://a/b/c/.g"; String uri130 = "http://a/b/c/g.."; String uri131 = "http://a/b/c/..g"; String uri132 = "http://a/b/g"; String uri133 = "http://a/b/c/g/"; String uri134 = "http://a/b/c/g/h"; String uri135 = "http://a/b/c/h"; String uri136 = "http://a/b/c/g;x=1/y"; String uri137 = "http://a/b/c/y"; // Test the parsing of references into its components testRef0("foo://example.com:8042/over/there?name=ferret#nose", "foo", "example.com:8042", "/over/there", "name=ferret", "nose"); testRef0("urn:example:animal:ferret:nose", "urn", null, "example:animal:ferret:nose", null, null); testRef0("mailto:[email protected]", "mailto", null, "[email protected]", null, null); testRef0("foo://info.example.com?fred", "foo", "info.example.com", null, "fred", null); testRef0("*", null, null, "*", null, null); // Test the resolution of relative references testRef1(base, uri01, uri101); testRef1(base, uri02, uri102); testRef1(base, uri03, uri103); testRef1(base, uri04, uri104); testRef1(base, uri05, uri105); testRef1(base, uri06, uri106); testRef1(base, uri07, uri107); testRef1(base, uri08, uri108); testRef1(base, uri09, uri109); testRef1(base, uri10, uri110); testRef1(base, uri11, uri111); testRef1(base, uri12, uri112); testRef1(base, uri13, uri113); testRef1(base, uri14, uri114); testRef1(base, uri15, uri115); testRef1(base, uri16, uri116); testRef1(base, uri17, uri117); testRef1(base, uri18, uri118); testRef1(base, uri19, uri119); testRef1(base, uri20, uri120); testRef1(base, uri21, uri121); testRef1(base, uri22, uri122); testRef1(base, uri23, uri123); testRef1(base, uri24, uri124); testRef1(base, uri25, uri125); testRef1(base, uri26, uri126); testRef1(base, uri27, uri127); testRef1(base, uri28, uri128); testRef1(base, uri29, uri129); testRef1(base, uri30, uri130); testRef1(base, uri31, uri131); testRef1(base, uri32, uri132); testRef1(base, uri33, uri133); testRef1(base, uri34, uri134); testRef1(base, uri35, uri135); testRef1(base, uri36, uri136); testRef1(base, uri37, uri137); // Test the relativization of absolute references testRef2(base, uri102, uri02); testRef2(base, uri104, uri04); testRef2(base, uri107, uri07); testRef2(base, uri108, uri08); testRef2(base, uri109, uri09); testRef2(base, uri110, uri10); testRef2(base, uri111, uri11); testRef2(base, uri112, uri12); testRef2(base, uri113, uri13); testRef2(base, uri114, uri14); testRef2(base, uri116, uri16); testRef2(base, uri118, uri18); testRef2(base, uri120, uri20); testRef2(base, uri121, uri21); testRef2(base, uri123, uri23); }
public void testParsing() throws IOException { String base = "http://a/b/c/d;p?q"; String uri01 = "g:h"; String uri02 = "g"; String uri03 = "./g"; String uri04 = "g/"; String uri05 = "/g"; String uri06 = "//g"; String uri07 = "?y"; String uri08 = "g?y"; String uri09 = "#s"; String uri10 = "g#s"; String uri11 = "g?y#s"; String uri12 = ";x"; String uri13 = "g;x"; String uri14 = "g;x?y#s"; String uri15 = ""; String uri16 = "."; String uri17 = "./"; String uri18 = ".."; String uri19 = "../"; String uri20 = "../g"; String uri21 = "../.."; String uri22 = "../../"; String uri23 = "../../g"; String uri24 = "../../../g"; String uri25 = "../../../../g"; String uri26 = "/./g"; String uri27 = "/../g"; String uri28 = "g."; String uri29 = ".g"; String uri30 = "g.."; String uri31 = "..g"; String uri32 = "./../g"; String uri33 = "./g/."; String uri34 = "g/./h"; String uri35 = "g/../h"; String uri36 = "g;x=1/./y"; String uri37 = "g;x=1/../y"; String uri101 = "g:h"; String uri102 = "http://a/b/c/g"; String uri103 = "http://a/b/c/g"; String uri104 = "http://a/b/c/g/"; String uri105 = "http://a/g"; String uri106 = "http://g"; String uri107 = "http://a/b/c/d;p?y"; String uri108 = "http://a/b/c/g?y"; String uri109 = "http://a/b/c/d;p?q#s"; String uri110 = "http://a/b/c/g#s"; String uri111 = "http://a/b/c/g?y#s"; String uri112 = "http://a/b/c/;x"; String uri113 = "http://a/b/c/g;x"; String uri114 = "http://a/b/c/g;x?y#s"; String uri115 = "http://a/b/c/d;p?q"; String uri116 = "http://a/b/c/"; String uri117 = "http://a/b/c/"; String uri118 = "http://a/b/"; String uri119 = "http://a/b/"; String uri120 = "http://a/b/g"; String uri121 = "http://a/"; String uri122 = "http://a/"; String uri123 = "http://a/g"; String uri124 = "http://a/g"; String uri125 = "http://a/g"; String uri126 = "http://a/g"; String uri127 = "http://a/g"; String uri128 = "http://a/b/c/g."; String uri129 = "http://a/b/c/.g"; String uri130 = "http://a/b/c/g.."; String uri131 = "http://a/b/c/..g"; String uri132 = "http://a/b/g"; String uri133 = "http://a/b/c/g/"; String uri134 = "http://a/b/c/g/h"; String uri135 = "http://a/b/c/h"; String uri136 = "http://a/b/c/g;x=1/y"; String uri137 = "http://a/b/c/y"; // Test the parsing of references into its components testRef0("foo://example.com:8042/over/there?name=ferret#nose", "foo", "example.com:8042", "/over/there", "name=ferret", "nose"); testRef0("urn:example:animal:ferret:nose", "urn", null, "example:animal:ferret:nose", null, null); testRef0("mailto:[email protected]", "mailto", null, "[email protected]", null, null); testRef0("foo://info.example.com?fred", "foo", "info.example.com", null, "fred", null); testRef0("*", null, null, "*", null, null); testRef0("http://localhost?query", "http", "localhost", null, "query", null); testRef0("http://localhost#?query", "http", "localhost", null, null, "?query"); testRef0("http://localhost/?query", "http", "localhost", "/", "query", null); testRef0("http://localhost/#?query", "http", "localhost", "/", null, "?query"); // Test the resolution of relative references testRef1(base, uri01, uri101); testRef1(base, uri02, uri102); testRef1(base, uri03, uri103); testRef1(base, uri04, uri104); testRef1(base, uri05, uri105); testRef1(base, uri06, uri106); testRef1(base, uri07, uri107); testRef1(base, uri08, uri108); testRef1(base, uri09, uri109); testRef1(base, uri10, uri110); testRef1(base, uri11, uri111); testRef1(base, uri12, uri112); testRef1(base, uri13, uri113); testRef1(base, uri14, uri114); testRef1(base, uri15, uri115); testRef1(base, uri16, uri116); testRef1(base, uri17, uri117); testRef1(base, uri18, uri118); testRef1(base, uri19, uri119); testRef1(base, uri20, uri120); testRef1(base, uri21, uri121); testRef1(base, uri22, uri122); testRef1(base, uri23, uri123); testRef1(base, uri24, uri124); testRef1(base, uri25, uri125); testRef1(base, uri26, uri126); testRef1(base, uri27, uri127); testRef1(base, uri28, uri128); testRef1(base, uri29, uri129); testRef1(base, uri30, uri130); testRef1(base, uri31, uri131); testRef1(base, uri32, uri132); testRef1(base, uri33, uri133); testRef1(base, uri34, uri134); testRef1(base, uri35, uri135); testRef1(base, uri36, uri136); testRef1(base, uri37, uri137); // Test the relativization of absolute references testRef2(base, uri102, uri02); testRef2(base, uri104, uri04); testRef2(base, uri107, uri07); testRef2(base, uri108, uri08); testRef2(base, uri109, uri09); testRef2(base, uri110, uri10); testRef2(base, uri111, uri11); testRef2(base, uri112, uri12); testRef2(base, uri113, uri13); testRef2(base, uri114, uri14); testRef2(base, uri116, uri16); testRef2(base, uri118, uri18); testRef2(base, uri120, uri20); testRef2(base, uri121, uri21); testRef2(base, uri123, uri23); }
diff --git a/src/main/java/org/got5/tapestry5/jquery/services/impl/JavaScriptFilesConfigurationImpl.java b/src/main/java/org/got5/tapestry5/jquery/services/impl/JavaScriptFilesConfigurationImpl.java index 4cd87480..b7c9901e 100644 --- a/src/main/java/org/got5/tapestry5/jquery/services/impl/JavaScriptFilesConfigurationImpl.java +++ b/src/main/java/org/got5/tapestry5/jquery/services/impl/JavaScriptFilesConfigurationImpl.java @@ -1,30 +1,29 @@ package org.got5.tapestry5.jquery.services.impl; import java.util.Map; import org.apache.tapestry5.Asset; import org.apache.tapestry5.ioc.internal.util.InternalUtils; import org.apache.tapestry5.services.AssetSource; import org.got5.tapestry5.jquery.services.JavaScriptFilesConfiguration; public class JavaScriptFilesConfigurationImpl implements JavaScriptFilesConfiguration { private Map<String, String> javaScriptFilesConfiguration; private AssetSource as; public JavaScriptFilesConfigurationImpl(Map<String, String> javaScriptFilesConfiguration, AssetSource as) { super(); this.javaScriptFilesConfiguration = javaScriptFilesConfiguration; this.as = as; } public Asset getAsset(Asset original) { - for(String key : javaScriptFilesConfiguration.keySet()){ - if(original.getResource().getFile().endsWith(key)){ - return InternalUtils.isBlank(javaScriptFilesConfiguration.get(key)) ? null : this.as.getExpandedAsset(javaScriptFilesConfiguration.get(key)); - } + if(javaScriptFilesConfiguration.containsKey(original.getResource().getFile())) { + String assetPath = javaScriptFilesConfiguration.get(original.getResource().getFile()); + return InternalUtils.isBlank(assetPath) ? null : this.as.getExpandedAsset(assetPath); } return original; } }
true
true
public Asset getAsset(Asset original) { for(String key : javaScriptFilesConfiguration.keySet()){ if(original.getResource().getFile().endsWith(key)){ return InternalUtils.isBlank(javaScriptFilesConfiguration.get(key)) ? null : this.as.getExpandedAsset(javaScriptFilesConfiguration.get(key)); } } return original; }
public Asset getAsset(Asset original) { if(javaScriptFilesConfiguration.containsKey(original.getResource().getFile())) { String assetPath = javaScriptFilesConfiguration.get(original.getResource().getFile()); return InternalUtils.isBlank(assetPath) ? null : this.as.getExpandedAsset(assetPath); } return original; }
diff --git a/app/src/nl/digitalica/skydivekompasroos/CanopyDetailsActivity.java b/app/src/nl/digitalica/skydivekompasroos/CanopyDetailsActivity.java index df18399..312daf4 100644 --- a/app/src/nl/digitalica/skydivekompasroos/CanopyDetailsActivity.java +++ b/app/src/nl/digitalica/skydivekompasroos/CanopyDetailsActivity.java @@ -1,81 +1,82 @@ package nl.digitalica.skydivekompasroos; import java.util.HashMap; import java.util.List; import android.os.Bundle; import android.util.Log; import android.widget.TextView; public class CanopyDetailsActivity extends KompasroosBaseActivity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_canopydetails); Bundle extras = getIntent().getExtras(); String canopyKey = extras.getString(CANOPYKEYEXTRA); List<Canopy> thisCanopy = Canopy.getCanopiesInList(canopyKey, this); HashMap<String, Manufacturer> manufacturers = Manufacturer .getManufacturerHash(CanopyDetailsActivity.this); if (thisCanopy.size() != 1) Log.e(LOG_TAG, "Onjuist aantal op basis van key " + canopyKey); Canopy canopy = thisCanopy.get(0); Manufacturer manufacturer = manufacturers.get(canopy.manufacturer); String url = manufacturer.url; if (canopy.url != null && !canopy.url.equals("")) url = canopy.url; // if we have a canopy url use that. TextView tvName = (TextView) findViewById(R.id.textViewNameText); TextView tvCategory = (TextView) findViewById(R.id.textViewCategoryText); TextView tvExperience = (TextView) findViewById(R.id.textViewExperienceText); TextView tvCells = (TextView) findViewById(R.id.textViewCellsText); TextView tvSizes = (TextView) findViewById(R.id.textViewSizesText); TextView tvUrl = (TextView) findViewById(R.id.textViewUrlText); TextView tvManufacturer = (TextView) findViewById(R.id.textViewManufacturerText); TextView tvManufacturerCountry = (TextView) findViewById(R.id.textViewManufacturerCountryText); TextView tvProduction = (TextView) findViewById(R.id.textViewProductionText); TextView tvRemarks = (TextView) findViewById(R.id.textViewRemarksText); tvName.setText(canopy.name); tvName.setBackgroundDrawable(backgroundDrawableForAcceptance(canopy .acceptablility(currentMaxCategory, currentWeight))); tvCategory.setText(Integer.toString(canopy.category)); String[] jumperCategories = getResources().getStringArray( R.array.jumperCategories); tvExperience.setText(jumperCategories[canopy.category]); tvCells.setText(canopy.cells); String sizes = ""; if (canopy.minSize != null && !canopy.minSize.equals("")) if (canopy.maxSize != null && !canopy.maxSize.equals("")) { // TODO: change to format string in strings for translation - sizes = canopy.minSize + " tot " + canopy.maxSize + " sqft"; + sizes = canopy.minSize + " tot en met " + canopy.maxSize + + " sqft"; } tvSizes.setText(sizes); tvUrl.setText(url); tvManufacturer.setText(canopy.manufacturer); tvManufacturerCountry.setText(manufacturer.countryFullName()); StringBuilder remarks = new StringBuilder(); if (canopy.remarks != null && !canopy.remarks.equals("")) { remarks.append(canopy.remarks); remarks.append(System.getProperty("line.separator")); } if (manufacturer.remarks != null && !manufacturer.remarks.equals("")) remarks.append(manufacturer.remarks); // TODO: move strings below to resource file (using string format?) String geproduceerd = ""; if (canopy.firstYearOfProduction != null && !canopy.firstYearOfProduction.equals("")) { geproduceerd = "vanaf " + canopy.firstYearOfProduction; if (canopy.lastYearOfProduction != null && !canopy.lastYearOfProduction.equals("")) geproduceerd += " tot en met " + canopy.lastYearOfProduction; } tvProduction.setText(geproduceerd); tvRemarks.setText(remarks.toString()); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_canopydetails); Bundle extras = getIntent().getExtras(); String canopyKey = extras.getString(CANOPYKEYEXTRA); List<Canopy> thisCanopy = Canopy.getCanopiesInList(canopyKey, this); HashMap<String, Manufacturer> manufacturers = Manufacturer .getManufacturerHash(CanopyDetailsActivity.this); if (thisCanopy.size() != 1) Log.e(LOG_TAG, "Onjuist aantal op basis van key " + canopyKey); Canopy canopy = thisCanopy.get(0); Manufacturer manufacturer = manufacturers.get(canopy.manufacturer); String url = manufacturer.url; if (canopy.url != null && !canopy.url.equals("")) url = canopy.url; // if we have a canopy url use that. TextView tvName = (TextView) findViewById(R.id.textViewNameText); TextView tvCategory = (TextView) findViewById(R.id.textViewCategoryText); TextView tvExperience = (TextView) findViewById(R.id.textViewExperienceText); TextView tvCells = (TextView) findViewById(R.id.textViewCellsText); TextView tvSizes = (TextView) findViewById(R.id.textViewSizesText); TextView tvUrl = (TextView) findViewById(R.id.textViewUrlText); TextView tvManufacturer = (TextView) findViewById(R.id.textViewManufacturerText); TextView tvManufacturerCountry = (TextView) findViewById(R.id.textViewManufacturerCountryText); TextView tvProduction = (TextView) findViewById(R.id.textViewProductionText); TextView tvRemarks = (TextView) findViewById(R.id.textViewRemarksText); tvName.setText(canopy.name); tvName.setBackgroundDrawable(backgroundDrawableForAcceptance(canopy .acceptablility(currentMaxCategory, currentWeight))); tvCategory.setText(Integer.toString(canopy.category)); String[] jumperCategories = getResources().getStringArray( R.array.jumperCategories); tvExperience.setText(jumperCategories[canopy.category]); tvCells.setText(canopy.cells); String sizes = ""; if (canopy.minSize != null && !canopy.minSize.equals("")) if (canopy.maxSize != null && !canopy.maxSize.equals("")) { // TODO: change to format string in strings for translation sizes = canopy.minSize + " tot " + canopy.maxSize + " sqft"; } tvSizes.setText(sizes); tvUrl.setText(url); tvManufacturer.setText(canopy.manufacturer); tvManufacturerCountry.setText(manufacturer.countryFullName()); StringBuilder remarks = new StringBuilder(); if (canopy.remarks != null && !canopy.remarks.equals("")) { remarks.append(canopy.remarks); remarks.append(System.getProperty("line.separator")); } if (manufacturer.remarks != null && !manufacturer.remarks.equals("")) remarks.append(manufacturer.remarks); // TODO: move strings below to resource file (using string format?) String geproduceerd = ""; if (canopy.firstYearOfProduction != null && !canopy.firstYearOfProduction.equals("")) { geproduceerd = "vanaf " + canopy.firstYearOfProduction; if (canopy.lastYearOfProduction != null && !canopy.lastYearOfProduction.equals("")) geproduceerd += " tot en met " + canopy.lastYearOfProduction; } tvProduction.setText(geproduceerd); tvRemarks.setText(remarks.toString()); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_canopydetails); Bundle extras = getIntent().getExtras(); String canopyKey = extras.getString(CANOPYKEYEXTRA); List<Canopy> thisCanopy = Canopy.getCanopiesInList(canopyKey, this); HashMap<String, Manufacturer> manufacturers = Manufacturer .getManufacturerHash(CanopyDetailsActivity.this); if (thisCanopy.size() != 1) Log.e(LOG_TAG, "Onjuist aantal op basis van key " + canopyKey); Canopy canopy = thisCanopy.get(0); Manufacturer manufacturer = manufacturers.get(canopy.manufacturer); String url = manufacturer.url; if (canopy.url != null && !canopy.url.equals("")) url = canopy.url; // if we have a canopy url use that. TextView tvName = (TextView) findViewById(R.id.textViewNameText); TextView tvCategory = (TextView) findViewById(R.id.textViewCategoryText); TextView tvExperience = (TextView) findViewById(R.id.textViewExperienceText); TextView tvCells = (TextView) findViewById(R.id.textViewCellsText); TextView tvSizes = (TextView) findViewById(R.id.textViewSizesText); TextView tvUrl = (TextView) findViewById(R.id.textViewUrlText); TextView tvManufacturer = (TextView) findViewById(R.id.textViewManufacturerText); TextView tvManufacturerCountry = (TextView) findViewById(R.id.textViewManufacturerCountryText); TextView tvProduction = (TextView) findViewById(R.id.textViewProductionText); TextView tvRemarks = (TextView) findViewById(R.id.textViewRemarksText); tvName.setText(canopy.name); tvName.setBackgroundDrawable(backgroundDrawableForAcceptance(canopy .acceptablility(currentMaxCategory, currentWeight))); tvCategory.setText(Integer.toString(canopy.category)); String[] jumperCategories = getResources().getStringArray( R.array.jumperCategories); tvExperience.setText(jumperCategories[canopy.category]); tvCells.setText(canopy.cells); String sizes = ""; if (canopy.minSize != null && !canopy.minSize.equals("")) if (canopy.maxSize != null && !canopy.maxSize.equals("")) { // TODO: change to format string in strings for translation sizes = canopy.minSize + " tot en met " + canopy.maxSize + " sqft"; } tvSizes.setText(sizes); tvUrl.setText(url); tvManufacturer.setText(canopy.manufacturer); tvManufacturerCountry.setText(manufacturer.countryFullName()); StringBuilder remarks = new StringBuilder(); if (canopy.remarks != null && !canopy.remarks.equals("")) { remarks.append(canopy.remarks); remarks.append(System.getProperty("line.separator")); } if (manufacturer.remarks != null && !manufacturer.remarks.equals("")) remarks.append(manufacturer.remarks); // TODO: move strings below to resource file (using string format?) String geproduceerd = ""; if (canopy.firstYearOfProduction != null && !canopy.firstYearOfProduction.equals("")) { geproduceerd = "vanaf " + canopy.firstYearOfProduction; if (canopy.lastYearOfProduction != null && !canopy.lastYearOfProduction.equals("")) geproduceerd += " tot en met " + canopy.lastYearOfProduction; } tvProduction.setText(geproduceerd); tvRemarks.setText(remarks.toString()); }
diff --git a/src/com/duckcult/conway/gol/Board.java b/src/com/duckcult/conway/gol/Board.java index c0dc99c..0c5325f 100644 --- a/src/com/duckcult/conway/gol/Board.java +++ b/src/com/duckcult/conway/gol/Board.java @@ -1,451 +1,451 @@ package com.duckcult.conway.gol; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes.Usage; public class Board { public static final double PERCENT_ALIVE = 0.5; ArrayList<ArrayList<Cell>> grid; private int height; private int width; /** * File based constructor. * assumes the file is a space delimited grid representation where alive is 1, dead is 0. * @param f * @throws FileNotFoundException */ public Board(File f) throws FileNotFoundException { Scanner fileScan = new Scanner(f); grid = new ArrayList<ArrayList<Cell>>(); String [] line; ArrayList<Cell>temp; do { line = fileScan.nextLine().split(" "); temp = new ArrayList<Cell>(); temp.ensureCapacity(line.length); for (String s: line) { temp.add(new BasicCell(s.equals("1"))); } grid.add(temp); } while(fileScan.hasNext()); height = grid.size(); width = grid.get(0).size(); } public Board(int height, int width) { this(height, width, 0); } private Board(int height, int width, int flag) { initBoard(height,width,flag); } public static Board emptyBoard(int height, int width) { return new Board(height,width,1); } public static Board allLive(int height, int width) { return new Board(height,width,2); } //simple mutator methods //private void setWrap(int type){wrap = type;} //simple accessor methods public int getWidth(){return width;} public int getHeight(){return height;} public Cell getCell(int x, int y){return grid.get(y).get(x);} private void initBoard(int height, int width, int flag) { grid = new ArrayList<ArrayList<Cell>>(height); for (int i=0; i<height;i++){ switch(flag) { case 1: grid.add(emptyRow(width)); case 2: grid.add(fullRow(width)); default: grid.add(randomRow(width)); } } this.height = height; this.width = width; } private ArrayList<Cell> fullRow (int length) { ArrayList<Cell> temp = new ArrayList<Cell>(length); for (int i=0;i<length;i++) temp.add(new BasicCell(true)); return temp; } private ArrayList<Cell> randomRow(int length) { ArrayList<Cell> temp = new ArrayList<Cell>(length); for (int i=0; i<length;i++){ temp.add(new BasicCell(Math.random()>PERCENT_ALIVE)); } return temp; } private ArrayList<Cell> emptyRow(int length) { ArrayList<Cell> temp = new ArrayList<Cell>(length); for (int i=0;i<length;i++) temp.add(new BasicCell()); return temp; } public void advanceBoard() { for (int i = 0; i < grid.size()-1; i++) { grid.set(i, grid.get(i+1)); } grid.set(grid.size()-1, randomRow(width)); } public void update() { for(int i = 0; i < height; i++) { ArrayList<Cell> temp = grid.get(i); for (int j = 0; j < width; j++) { temp.get(j).check(getNeighbors(j,i)); } } } /** * Returns the neighbors of a cell collapsed into a single array. * Their positions map to: * [[0 1 2] * [3 _ 4] * [5 6 7]] * @param x * @param y * @return */ private ArrayList<Cell> getNeighbors(int x, int y) { ArrayList<Cell> temp = new ArrayList<Cell>(); if(x>0 && y>0) temp.add(getCell(x-1,y-1)); if(x<width-1 && y<height-1)temp.add(getCell(x+1,y+1)); if(x>0) temp.add(getCell(x-1,y)); if(y>0) temp.add(getCell(x,y-1)); if(x<width-1 && y>0) temp.add(getCell(x+1,y-1)); if(x<width-1 && y<height-1) temp.add(getCell(x+1,y+1)); if(x<width-1) temp.add(getCell(x+1,y)); if(y<height-1) temp.add(getCell(x,y+1)); return temp; } /** * Returns a 1D arrayList of meshes of the board for rendering * the arraylist is ordered left then up. * @param depth * @return */ public ArrayList<Mesh> toMeshes(float depth) { ArrayList<Mesh> ret = new ArrayList<Mesh>(height*width); float squareSize = 2f/(float)width; float l = -1; float r = squareSize-1; float t = 2f/(float)height-1; float b = -1; for (int i = 0; i < height; i++) { l = -1; - r=2f/(float)-1; + r=squareSize-1; for (int j = 0; j < width; j++) { if(getCell(j,i).isAlive()) { Mesh m = new Mesh(true,4,4, new VertexAttribute(Usage.Position,3,"a_position"), new VertexAttribute(Usage.ColorPacked, 4, "a_color")); - //System.out.println("l="+l+" r="+r+" t="+t+" b="+b); + System.out.println("l="+l+" r="+r+" t="+t+" b="+b); m.setVertices(new float[] {l, b, depth, getCell(j,i).getColor().toFloatBits(), r, b, depth, getCell(j,i).getColor().toFloatBits(), l, t, depth, getCell(j,i).getColor().toFloatBits(), r, t, depth, getCell(j,i).getColor().toFloatBits() }); m.setIndices(new short[] {0,1,2,3}); ret.add(m); } l = r; r += squareSize; } b = t; t+=squareSize; //t += ((float)2)/(float)height; } return ret; } public ArrayList<Mesh> updateMeshes(ArrayList<Mesh> current) { int i = 0; int j = 0; float [] verts = new float[16]; for (Mesh m : current) { m.getVertices(verts); verts[3] = getCell(j,i).getColor().toFloatBits(); verts[7] = getCell(j,i).getColor().toFloatBits(); verts[11] = getCell(j,i).getColor().toFloatBits(); verts[15] = getCell(j,i).getColor().toFloatBits(); m.setVertices(verts); if(j<width-1) j++; else { j=0; if(i<height-1) i++; } } return current; } //rotates a coordinate on the center of its axis, used in klien bottle private int rotateOnAxis (int coord, int max) { return (max-1)-coord; } //basic toString method, doesn't actually work since objectification the toStrings for each cell would be wrong public String toString(){ String ret = ""; for (int i = 0; i < grid.size(); i++){ ArrayList<Cell> temp = grid.get(i); for (int j = 0; j < temp.size(); j++){ ret = ret + temp.get(j); } ret = ret + "\n"; } return ret; } //a method that checks to see if everything is dead and returns true if so public boolean extinct(){ for (int i = 0; i < grid.size(); i++){ ArrayList<Cell> temp = grid.get(i); for (int j =0; j < temp.size(); j++){ if (temp.get(j).isAlive()) return false; } } return true; } public void setCells(int x, int y, Cell[][] cells) { for (int i = 0; i < cells.length; i++) { for (int j = 0; j < cells[0].length; j++) { if(cells[i][j]!=null){ grid.get(y).set(x, cells[i][j]); } x++; } y++; } } public boolean checkCells(int x, int y, Cell[][]cells) { for (int i = 0; i < cells.length; i++) { for (int j = 0; j < cells[0].length; j++) { if(cells[i][j]!=null && grid.get(x).get(y).isAlive()) return true; x++; } y++; } return false; } public ArrayList<ArrayList<Cell>> getSubgrid(int x, int y, int width, int height) { ArrayList<ArrayList<Cell>> ret = new ArrayList<ArrayList<Cell>> (height); for (int i = y; i < height; i++) { ret.add((ArrayList<Cell>) grid.get(i).subList(x, x+width)); } return ret; } //sets up the board for the closed box setting. /*private void initBoardBox(int pRow, int pCol, int ratio) { int temp; this.row = pRow+2; this.col = pCol+2; grid = new Cell [row][col]; for (int i =0; i < row; i++){ for (int j = 0; j < col; j++){ if (j==0 || j == col-1 || i==0 || i==row-1) grid[i][j] = new WallCell(); else{ temp = Math.abs(fate.nextInt()%100); if (temp < ratio) grid[i][j] = new BasicCell (true, CellProfile.getRandomProfile()); else grid[i][j] = new BasicCell (false, CellProfile.getRandomProfile()); } } } } private void initBoardGlobe(int pRow, int pCol, int ratio) { int temp; this.row = pRow; this.col = pCol+2; grid = new Cell [row][col]; for (int i =0; i < row; i++){ for (int j = 0; j < col; j++){ if (i==0 || i==row-1) grid[i][j] = new WallCell(); else{ temp = Math.abs(fate.nextInt()%100); if (temp < ratio) grid[i][j] = new BasicCell (true, CellProfile.getRandomProfile()); else grid[i][j] = new BasicCell (false, CellProfile.getRandomProfile()); } } } } private void initBoardNoWalls(int pRow, int pCol, int ratio) { int temp; this.row = pRow; this.col = pCol; grid = new Cell [row][col]; for (int i =0; i < row; i++){ for (int j = 0; j < col; j++){ temp = Math.abs(fate.nextInt()%100); if (temp < ratio) grid[i][j] = new BasicCell (true, CellProfile.getRandomProfile()); else grid[i][j] = new BasicCell (false, CellProfile.getRandomProfile()); } } }*/ // /*controls a single turn iteration public void turn(){ switch (wrap){ case 0: for (int i = 1; i < row-1; i++){ for (int j = 1; j < col-1;j++){ grid[i][j].check(getNeighbors(i,j)); } } break; case 1: for (int i = 1; i < row-1; i++){ for (int j = 0; j < col;j++){ grid[i][j].check(getNeighbors(i,j)); } } break; case 2: case 3: for (int i = 1; i < row; i++) { for(int j = 0; j < col; j++) { grid[i][j].check(getNeighbors(i,j)); } } default: for (int i = 1; i < row-1; i++){ for (int j = 1; j < col-1;j++){ grid[i][j].check(getNeighbors(i,j)); } } break; } return; }*/ /*collects a 2D array of neighbor Cells to pass to the check method private Cell[][] getNeighbors(int cRow,int cCol) { Cell[][] neighbors = new Cell[3][3]; switch (wrap){ case 0: neighbors = getNeighborsBox(cRow, cCol,neighbors); break; case 1: neighbors = getNeighborsGlobe(cRow, cCol, neighbors); break; case 2: neighbors = getNeighborsTorus(cRow, cCol, neighbors); break; case 3: neighbors = getNeighborsKlein(cRow, cCol, neighbors); break; default: neighbors = getNeighborsBox(cRow,cCol,neighbors); } return neighbors; }*/ /* //collects the neighbors of a cell in the closed box wrap setting, assumes a dead cell buffer private Cell[][] getNeighborsBox(int cRow,int cCol, Cell[][] neighbors) { neighbors[0][0] = grid[cRow-1][cCol-1]; neighbors[0][1] = grid[cRow-1][cCol]; neighbors[0][2] = grid[cRow-1][cCol+1]; neighbors[1][0] = grid[cRow][cCol-1]; neighbors[1][2] = grid[cRow][cCol+1]; neighbors[2][0] = grid[cRow+1][cCol-1]; neighbors[2][1] = grid[cRow+1][cCol]; neighbors[2][2] = grid[cRow+1][cCol+1]; return neighbors; } //collects the neighbors of a cell for the globe wrap setting private Cell[][] getNeighborsGlobe(int cRow,int cCol, Cell[][] neighbors) { int preRow = cRow-1; int nexRow = cRow+1; int preCol = (cCol==0 ? col-1 : cCol-1); int nexCol = (cCol==col-1 ? 0 : cCol+1); neighbors[0][0] = grid[preRow][preCol]; neighbors[0][1] = grid[preRow][cCol]; neighbors[0][2] = grid[preRow][nexCol]; neighbors[1][0] = grid[cRow][preCol]; neighbors[1][2] = grid[cRow][nexCol]; neighbors[2][0] = grid[nexRow][preCol]; neighbors[2][1] = grid[nexRow][cCol]; neighbors[2][2] = grid[nexRow][nexCol]; return neighbors; } //collects the neighbors of a cell for the torus wrap setting private Cell[][] getNeighborsTorus(int cRow, int cCol, Cell[][] neighbors) { int preRow = (cRow==0 ? row-1 : cRow-1); int preCol = (cCol==0 ? col-1 : cCol-1); int nexRow = (cRow==row-1 ? 0 : cRow+1); int nexCol = (cCol==col-1 ? 0 : cCol+1); neighbors[0][0] = grid[preRow][preCol]; neighbors[0][1] = grid[preRow][cCol]; neighbors[0][2] = grid[preRow][nexCol]; neighbors[1][0] = grid[cRow][preCol]; neighbors[1][2] = grid[cRow][nexCol]; neighbors[2][0] = grid[nexRow][preCol]; neighbors[2][1] = grid[nexRow][cCol]; neighbors[2][2] = grid[nexRow][nexCol]; return neighbors; } //collects the neighbors of a cell for the klein bottle wrap setting private Cell[][] getNeighborsKlein(int cRow, int cCol, Cell[][] neighbors) { int nexRow = (cRow==row-1 ? 0 : cRow+1); int preRow = (cRow==0 ? row-1 : cRow-1); if (nexRow==0 || preRow==row-1) cCol = rotateOnAxis(cCol, col); int preCol = (cCol==0 ? col-1 : cCol-1); int nexCol = (cCol==col-1 ? 0 : cCol+1); neighbors[0][0] = grid[preRow][preCol]; neighbors[0][1] = grid[preRow][cCol]; neighbors[0][2] = grid[preRow][nexCol]; neighbors[1][0] = grid[cRow][preCol]; neighbors[1][2] = grid[cRow][nexCol]; neighbors[2][0] = grid[nexRow][preCol]; neighbors[2][1] = grid[nexRow][cCol]; neighbors[2][2] = grid[nexRow][nexCol]; return neighbors; } */ }
false
true
public ArrayList<Mesh> toMeshes(float depth) { ArrayList<Mesh> ret = new ArrayList<Mesh>(height*width); float squareSize = 2f/(float)width; float l = -1; float r = squareSize-1; float t = 2f/(float)height-1; float b = -1; for (int i = 0; i < height; i++) { l = -1; r=2f/(float)-1; for (int j = 0; j < width; j++) { if(getCell(j,i).isAlive()) { Mesh m = new Mesh(true,4,4, new VertexAttribute(Usage.Position,3,"a_position"), new VertexAttribute(Usage.ColorPacked, 4, "a_color")); //System.out.println("l="+l+" r="+r+" t="+t+" b="+b); m.setVertices(new float[] {l, b, depth, getCell(j,i).getColor().toFloatBits(), r, b, depth, getCell(j,i).getColor().toFloatBits(), l, t, depth, getCell(j,i).getColor().toFloatBits(), r, t, depth, getCell(j,i).getColor().toFloatBits() }); m.setIndices(new short[] {0,1,2,3}); ret.add(m); } l = r; r += squareSize; } b = t; t+=squareSize; //t += ((float)2)/(float)height; } return ret; }
public ArrayList<Mesh> toMeshes(float depth) { ArrayList<Mesh> ret = new ArrayList<Mesh>(height*width); float squareSize = 2f/(float)width; float l = -1; float r = squareSize-1; float t = 2f/(float)height-1; float b = -1; for (int i = 0; i < height; i++) { l = -1; r=squareSize-1; for (int j = 0; j < width; j++) { if(getCell(j,i).isAlive()) { Mesh m = new Mesh(true,4,4, new VertexAttribute(Usage.Position,3,"a_position"), new VertexAttribute(Usage.ColorPacked, 4, "a_color")); System.out.println("l="+l+" r="+r+" t="+t+" b="+b); m.setVertices(new float[] {l, b, depth, getCell(j,i).getColor().toFloatBits(), r, b, depth, getCell(j,i).getColor().toFloatBits(), l, t, depth, getCell(j,i).getColor().toFloatBits(), r, t, depth, getCell(j,i).getColor().toFloatBits() }); m.setIndices(new short[] {0,1,2,3}); ret.add(m); } l = r; r += squareSize; } b = t; t+=squareSize; //t += ((float)2)/(float)height; } return ret; }
diff --git a/src/realms/yanel-website/src/java/org/wyona/yanel/website/menu/impl/YanelWebsiteMenu.java b/src/realms/yanel-website/src/java/org/wyona/yanel/website/menu/impl/YanelWebsiteMenu.java index 43e12a534..549c43dbb 100644 --- a/src/realms/yanel-website/src/java/org/wyona/yanel/website/menu/impl/YanelWebsiteMenu.java +++ b/src/realms/yanel-website/src/java/org/wyona/yanel/website/menu/impl/YanelWebsiteMenu.java @@ -1,96 +1,100 @@ package org.wyona.yanel.website.menu.impl; import org.apache.log4j.Logger; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.api.attributes.TranslatableV1; import org.wyona.yanel.core.api.attributes.VersionableV2; import org.wyona.yanel.core.attributes.versionable.RevisionInformation; import org.wyona.yanel.core.map.Map; import org.wyona.yanel.core.util.ResourceAttributeHelper; import org.wyona.yanel.servlet.menu.Menu; import org.wyona.yanel.servlet.menu.impl.RevisionInformationMenuItem; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.Arrays; import java.util.List; /** * */ public class YanelWebsiteMenu extends Menu { private static Logger log = Logger.getLogger(YanelWebsiteMenu.class); /** * Get toolbar menus */ public String getMenus(Resource resource, HttpServletRequest request, Map map, String reservedPrefix) throws ServletException, IOException, Exception { String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(resource.getPath()); StringBuffer sb= new StringBuffer(); sb.append("<ul><li>"); sb.append("<div id=\"yaneltoolbar_menutitle\">File</div>"); sb.append("<ul>"); sb.append("<li class=\"haschild\"><a href=\"" + backToRealm + "create-new-page.html\">New&#160;&#160;&#160;</a><ul><li><a href=\"" + backToRealm + "create-new-page.html?resource-type=http%3A%2F%2Fwww.wyona.org%2Fyanel%2Fresource%2F1.0%3A%3Axml\">Standard page (XHTML)</a></li><li><a href=\"" + backToRealm + "create-new-page.html?resource-type=http%3A%2F%2Fwww.wyona.org%2Fyanel%2Fresource%2F1.0%3A%3Awiki\">Wiki page</a></li><li><a href=\"" + backToRealm + "create-new-page.html?resource-type=http%3A%2F%2Fwww.wyona.org%2Fyanel%2Fresource%2F1.0%3A%3Afile\">File</a></li></ul></li>"); if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Modifiable", "2")) { sb.append("<li><a href=\"?yanel.resource.usecase=delete\">Delete this page</a></li>"); } sb.append("<li class=\"haschild\">New language&#160;&#160;&#160;<ul>"); if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Translatable", "1")) { TranslatableV1 translatable = (TranslatableV1)resource; List existingLanguages = Arrays.asList(translatable.getLanguages()); String[] realmLanguages = resource.getRealm().getLanguages(); for (int i = 0; i < realmLanguages.length; i++) { if (!existingLanguages.contains(realmLanguages[i])) { sb.append("<li>"); sb.append(realmLanguages[i]); sb.append("</li>"); } } } //sb.append("<li>German</li><li>Mandarin</li>"); sb.append("</ul></li>"); sb.append("<li>Publish</li>"); sb.append("</ul>"); sb.append("</li></ul>"); sb.append("<ul><li>"); sb.append("<div id=\"yaneltoolbar_menutitle\">Edit</div><ul>"); sb.append("<li class=\"haschild\">Open with&#160;&#160;&#160;"); sb.append("<ul><li>Source editor</li>"); sb.append("<li class=\"haschild\">WYSIWYG editor&#160;&#160;&#160;"); sb.append("<ul>"); if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Modifiable", "2")) { sb.append("<li><a href=\"" + backToRealm + "usecases/xinha.html?edit-path=" + resource.getPath() + "\">Edit page with Xinha&#160;&#160;&#160;</a></li>"); sb.append("<li><a href=\"" + backToRealm + "usecases/tinymce.html?edit-path=" + resource.getPath() + "\">Edit page with tinyMCE&#160;&#160;&#160;</a></li>"); } else { sb.append("<li><a>Edit page with Xinha&#160;&#160;&#160;</a></li>"); sb.append("<li><a>Edit page with tinyMCE&#160;&#160;&#160;</a></li>"); } sb.append("<li><a href=\"http://www.yulup.org\">Edit page with Yulup&#160;&#160;&#160;</a></li>"); sb.append("</ul></li>"); // End of WYSIWYG editor sb.append("</ul></li>"); if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) { RevisionInformation[] revisions = ((VersionableV2) resource).getRevisions(); if (revisions != null && revisions.length > 0) { sb.append("<li class=\"haschild\">Revisions&#160;&#160;&#160;<ul>"); for (int i = revisions.length -1; i >= 0; i--) { + boolean mostRecent = false; + boolean oldestRevision = false; + if (i == revisions.length -1) mostRecent = true; + if (i == 0) oldestRevision = true; sb.append((new RevisionInformationMenuItem(resource, revisions[i], - resource.getRequestedLanguage())).toHTML()); + resource.getRequestedLanguage())).toHTML(mostRecent, oldestRevision)); } sb.append("</ul></li>"); } } sb.append("</ul>"); sb.append("</li></ul>"); return sb.toString(); } }
false
true
public String getMenus(Resource resource, HttpServletRequest request, Map map, String reservedPrefix) throws ServletException, IOException, Exception { String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(resource.getPath()); StringBuffer sb= new StringBuffer(); sb.append("<ul><li>"); sb.append("<div id=\"yaneltoolbar_menutitle\">File</div>"); sb.append("<ul>"); sb.append("<li class=\"haschild\"><a href=\"" + backToRealm + "create-new-page.html\">New&#160;&#160;&#160;</a><ul><li><a href=\"" + backToRealm + "create-new-page.html?resource-type=http%3A%2F%2Fwww.wyona.org%2Fyanel%2Fresource%2F1.0%3A%3Axml\">Standard page (XHTML)</a></li><li><a href=\"" + backToRealm + "create-new-page.html?resource-type=http%3A%2F%2Fwww.wyona.org%2Fyanel%2Fresource%2F1.0%3A%3Awiki\">Wiki page</a></li><li><a href=\"" + backToRealm + "create-new-page.html?resource-type=http%3A%2F%2Fwww.wyona.org%2Fyanel%2Fresource%2F1.0%3A%3Afile\">File</a></li></ul></li>"); if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Modifiable", "2")) { sb.append("<li><a href=\"?yanel.resource.usecase=delete\">Delete this page</a></li>"); } sb.append("<li class=\"haschild\">New language&#160;&#160;&#160;<ul>"); if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Translatable", "1")) { TranslatableV1 translatable = (TranslatableV1)resource; List existingLanguages = Arrays.asList(translatable.getLanguages()); String[] realmLanguages = resource.getRealm().getLanguages(); for (int i = 0; i < realmLanguages.length; i++) { if (!existingLanguages.contains(realmLanguages[i])) { sb.append("<li>"); sb.append(realmLanguages[i]); sb.append("</li>"); } } } //sb.append("<li>German</li><li>Mandarin</li>"); sb.append("</ul></li>"); sb.append("<li>Publish</li>"); sb.append("</ul>"); sb.append("</li></ul>"); sb.append("<ul><li>"); sb.append("<div id=\"yaneltoolbar_menutitle\">Edit</div><ul>"); sb.append("<li class=\"haschild\">Open with&#160;&#160;&#160;"); sb.append("<ul><li>Source editor</li>"); sb.append("<li class=\"haschild\">WYSIWYG editor&#160;&#160;&#160;"); sb.append("<ul>"); if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Modifiable", "2")) { sb.append("<li><a href=\"" + backToRealm + "usecases/xinha.html?edit-path=" + resource.getPath() + "\">Edit page with Xinha&#160;&#160;&#160;</a></li>"); sb.append("<li><a href=\"" + backToRealm + "usecases/tinymce.html?edit-path=" + resource.getPath() + "\">Edit page with tinyMCE&#160;&#160;&#160;</a></li>"); } else { sb.append("<li><a>Edit page with Xinha&#160;&#160;&#160;</a></li>"); sb.append("<li><a>Edit page with tinyMCE&#160;&#160;&#160;</a></li>"); } sb.append("<li><a href=\"http://www.yulup.org\">Edit page with Yulup&#160;&#160;&#160;</a></li>"); sb.append("</ul></li>"); // End of WYSIWYG editor sb.append("</ul></li>"); if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) { RevisionInformation[] revisions = ((VersionableV2) resource).getRevisions(); if (revisions != null && revisions.length > 0) { sb.append("<li class=\"haschild\">Revisions&#160;&#160;&#160;<ul>"); for (int i = revisions.length -1; i >= 0; i--) { sb.append((new RevisionInformationMenuItem(resource, revisions[i], resource.getRequestedLanguage())).toHTML()); } sb.append("</ul></li>"); } } sb.append("</ul>"); sb.append("</li></ul>"); return sb.toString(); }
public String getMenus(Resource resource, HttpServletRequest request, Map map, String reservedPrefix) throws ServletException, IOException, Exception { String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(resource.getPath()); StringBuffer sb= new StringBuffer(); sb.append("<ul><li>"); sb.append("<div id=\"yaneltoolbar_menutitle\">File</div>"); sb.append("<ul>"); sb.append("<li class=\"haschild\"><a href=\"" + backToRealm + "create-new-page.html\">New&#160;&#160;&#160;</a><ul><li><a href=\"" + backToRealm + "create-new-page.html?resource-type=http%3A%2F%2Fwww.wyona.org%2Fyanel%2Fresource%2F1.0%3A%3Axml\">Standard page (XHTML)</a></li><li><a href=\"" + backToRealm + "create-new-page.html?resource-type=http%3A%2F%2Fwww.wyona.org%2Fyanel%2Fresource%2F1.0%3A%3Awiki\">Wiki page</a></li><li><a href=\"" + backToRealm + "create-new-page.html?resource-type=http%3A%2F%2Fwww.wyona.org%2Fyanel%2Fresource%2F1.0%3A%3Afile\">File</a></li></ul></li>"); if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Modifiable", "2")) { sb.append("<li><a href=\"?yanel.resource.usecase=delete\">Delete this page</a></li>"); } sb.append("<li class=\"haschild\">New language&#160;&#160;&#160;<ul>"); if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Translatable", "1")) { TranslatableV1 translatable = (TranslatableV1)resource; List existingLanguages = Arrays.asList(translatable.getLanguages()); String[] realmLanguages = resource.getRealm().getLanguages(); for (int i = 0; i < realmLanguages.length; i++) { if (!existingLanguages.contains(realmLanguages[i])) { sb.append("<li>"); sb.append(realmLanguages[i]); sb.append("</li>"); } } } //sb.append("<li>German</li><li>Mandarin</li>"); sb.append("</ul></li>"); sb.append("<li>Publish</li>"); sb.append("</ul>"); sb.append("</li></ul>"); sb.append("<ul><li>"); sb.append("<div id=\"yaneltoolbar_menutitle\">Edit</div><ul>"); sb.append("<li class=\"haschild\">Open with&#160;&#160;&#160;"); sb.append("<ul><li>Source editor</li>"); sb.append("<li class=\"haschild\">WYSIWYG editor&#160;&#160;&#160;"); sb.append("<ul>"); if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Modifiable", "2")) { sb.append("<li><a href=\"" + backToRealm + "usecases/xinha.html?edit-path=" + resource.getPath() + "\">Edit page with Xinha&#160;&#160;&#160;</a></li>"); sb.append("<li><a href=\"" + backToRealm + "usecases/tinymce.html?edit-path=" + resource.getPath() + "\">Edit page with tinyMCE&#160;&#160;&#160;</a></li>"); } else { sb.append("<li><a>Edit page with Xinha&#160;&#160;&#160;</a></li>"); sb.append("<li><a>Edit page with tinyMCE&#160;&#160;&#160;</a></li>"); } sb.append("<li><a href=\"http://www.yulup.org\">Edit page with Yulup&#160;&#160;&#160;</a></li>"); sb.append("</ul></li>"); // End of WYSIWYG editor sb.append("</ul></li>"); if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) { RevisionInformation[] revisions = ((VersionableV2) resource).getRevisions(); if (revisions != null && revisions.length > 0) { sb.append("<li class=\"haschild\">Revisions&#160;&#160;&#160;<ul>"); for (int i = revisions.length -1; i >= 0; i--) { boolean mostRecent = false; boolean oldestRevision = false; if (i == revisions.length -1) mostRecent = true; if (i == 0) oldestRevision = true; sb.append((new RevisionInformationMenuItem(resource, revisions[i], resource.getRequestedLanguage())).toHTML(mostRecent, oldestRevision)); } sb.append("</ul></li>"); } } sb.append("</ul>"); sb.append("</li></ul>"); return sb.toString(); }
diff --git a/src/main/java/net/rcarz/jiraclient/RestClient.java b/src/main/java/net/rcarz/jiraclient/RestClient.java index f088402..1bbc1b9 100644 --- a/src/main/java/net/rcarz/jiraclient/RestClient.java +++ b/src/main/java/net/rcarz/jiraclient/RestClient.java @@ -1,371 +1,374 @@ /** * jira-client - a simple JIRA REST client * Copyright (c) 2013 Bob Carroll ([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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.rcarz.jiraclient; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.util.Map; import net.sf.json.JSON; import net.sf.json.JSONObject; import net.sf.json.JSONSerializer; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; /** * A simple REST client that speaks JSON. */ public class RestClient { private HttpClient httpClient = null; private ICredentials creds = null; private URI uri = null; /** * Creates a REST client instance with a URI. * * @param httpclient Underlying HTTP client to use * @param uri Base URI of the remote REST service */ public RestClient(HttpClient httpclient, URI uri) { this(httpclient, null, uri); } /** * Creates an authenticated REST client instance with a URI. * * @param httpclient Underlying HTTP client to use * @param creds Credentials to send with each request * @param uri Base URI of the remote REST service */ public RestClient(HttpClient httpclient, ICredentials creds, URI uri) { this.httpClient = httpclient; this.creds = creds; this.uri = uri; } /** * Build a URI from a path. * * @param path Path to append to the base URI * * @return the full URI * * @throws URISyntaxException when the path is invalid */ public URI buildURI(String path) throws URISyntaxException { return buildURI(path, null); } /** * Build a URI from a path and query parmeters. * * @param path Path to append to the base URI * @param params Map of key value pairs * * @return the full URI * * @throws URISyntaxException when the path is invalid */ public URI buildURI(String path, Map<String, String> params) throws URISyntaxException { URIBuilder ub = new URIBuilder(uri); ub.setPath(ub.getPath() + path); if (params != null) { for (Map.Entry<String, String> ent : params.entrySet()) ub.addParameter(ent.getKey(), ent.getValue()); } return ub.build(); } private JSON request(HttpRequestBase req) throws RestException, IOException { req.addHeader("Accept", "application/json"); if (creds != null) creds.authenticate(req); HttpResponse resp = httpClient.execute(req); HttpEntity ent = resp.getEntity(); StringBuilder result = new StringBuilder(); if (ent != null) { - BufferedReader br = new BufferedReader(new InputStreamReader(ent.getContent())); + InputStreamReader isr = ent.getContentEncoding() != null ? + new InputStreamReader(ent.getContent(), ent.getContentEncoding().getValue()) : + new InputStreamReader(ent.getContent()); + BufferedReader br = new BufferedReader(isr); String line = ""; while ((line = br.readLine()) != null) result.append(line); } StatusLine sl = resp.getStatusLine(); if (sl.getStatusCode() >= 300) throw new RestException(sl.getReasonPhrase(), sl.getStatusCode(), result.toString()); return result.length() > 0 ? JSONSerializer.toJSON(result.toString()): null; } private JSON request(HttpEntityEnclosingRequestBase req, String payload) throws RestException, IOException { if (payload != null) { StringEntity ent = null; try { ent = new StringEntity(payload, "UTF-8"); ent.setContentType("application/json"); } catch (UnsupportedEncodingException ex) { /* utf-8 should always be supported... */ } req.addHeader("Content-Type", "application/json"); req.setEntity(ent); } return request(req); } private JSON request(HttpEntityEnclosingRequestBase req, File file) throws RestException, IOException { if (file != null) { File fileUpload = file; req.setHeader("X-Atlassian-Token","nocheck"); MultipartEntity ent = new MultipartEntity(); ent.addPart("file", new FileBody(fileUpload)); req.setEntity(ent); } return request(req); } private JSON request(HttpEntityEnclosingRequestBase req, JSON payload) throws RestException, IOException { return request(req, payload != null ? payload.toString() : null); } /** * Executes an HTTP DELETE with the given URI. * * @param uri Full URI of the remote endpoint * * @return JSON-encoded result or null when there's no content returned * * @throws RestException when an HTTP-level error occurs * @throws IOException when an error reading the response occurs */ public JSON delete(URI uri) throws RestException, IOException { return request(new HttpDelete(uri)); } /** * Executes an HTTP DELETE with the given path. * * @param path Path to be appended to the URI supplied in the construtor * * @return JSON-encoded result or null when there's no content returned * * @throws RestException when an HTTP-level error occurs * @throws IOException when an error reading the response occurs * @throws URISyntaxException when an error occurred appending the path to the URI */ public JSON delete(String path) throws RestException, IOException, URISyntaxException { return delete(buildURI(path)); } /** * Executes an HTTP GET with the given URI. * * @param uri Full URI of the remote endpoint * * @return JSON-encoded result or null when there's no content returned * * @throws RestException when an HTTP-level error occurs * @throws IOException when an error reading the response occurs */ public JSON get(URI uri) throws RestException, IOException { return request(new HttpGet(uri)); } /** * Executes an HTTP GET with the given path. * * @param path Path to be appended to the URI supplied in the construtor * * @return JSON-encoded result or null when there's no content returned * * @throws RestException when an HTTP-level error occurs * @throws IOException when an error reading the response occurs * @throws URISyntaxException when an error occurred appending the path to the URI */ public JSON get(String path) throws RestException, IOException, URISyntaxException { return get(buildURI(path)); } /** * Executes an HTTP POST with the given URI and payload. * * @param uri Full URI of the remote endpoint * @param payload JSON-encoded data to send to the remote service * * @return JSON-encoded result or null when there's no content returned * * @throws RestException when an HTTP-level error occurs * @throws IOException when an error reading the response occurs */ public JSON post(URI uri, JSON payload) throws RestException, IOException { return request(new HttpPost(uri), payload); } /** * Executes an HTTP POST with the given URI and payload. * * At least one JIRA REST endpoint expects malformed JSON. The payload * argument is quoted and sent to the server with the application/json * Content-Type header. You should not use this function when proper JSON * is expected. * * @see https://jira.atlassian.com/browse/JRA-29304 * * @param uri Full URI of the remote endpoint * @param payload Raw string to send to the remote service * * @return JSON-encoded result or null when there's no content returned * * @throws RestException when an HTTP-level error occurs * @throws IOException when an error reading the response occurs */ public JSON post(URI uri, String payload) throws RestException, IOException { String quoted = null; if(payload != null && !payload.equals(new JSONObject())){ quoted = String.format("\"%s\"", payload); } return request(new HttpPost(uri), quoted); } /** * Executes an HTTP POST with the given path and payload. * * @param path Path to be appended to the URI supplied in the construtor * @param payload JSON-encoded data to send to the remote service * * @return JSON-encoded result or null when there's no content returned * * @throws RestException when an HTTP-level error occurs * @throws IOException when an error reading the response occurs * @throws URISyntaxException when an error occurred appending the path to the URI */ public JSON post(String path, JSON payload) throws RestException, IOException, URISyntaxException { return post(buildURI(path), payload); } /** * Executes an HTTP POST with the given path. * * @param path Path to be appended to the URI supplied in the construtor * * @return JSON-encoded result or null when there's no content returned * * @throws RestException when an HTTP-level error occurs * @throws IOException when an error reading the response occurs * @throws URISyntaxException when an error occurred appending the path to the URI */ public JSON post(String path) throws RestException, IOException, URISyntaxException { return post(buildURI(path), new JSONObject()); } /** * Executes an HTTP POST with the given path and file payload. * * @param uri Full URI of the remote endpoint * @param file java.io.File * * @throws URISyntaxException * @throws IOException * @throws RestException */ public JSON post(String path, File file) throws RestException, IOException, URISyntaxException{ return request(new HttpPost(buildURI(path)), file); } /** * Executes an HTTP PUT with the given URI and payload. * * @param uri Full URI of the remote endpoint * @param payload JSON-encoded data to send to the remote service * * @return JSON-encoded result or null when there's no content returned * * @throws RestException when an HTTP-level error occurs * @throws IOException when an error reading the response occurs */ public JSON put(URI uri, JSON payload) throws RestException, IOException { return request(new HttpPut(uri), payload); } /** * Executes an HTTP PUT with the given path and payload. * * @param path Path to be appended to the URI supplied in the construtor * @param payload JSON-encoded data to send to the remote service * * @return JSON-encoded result or null when there's no content returned * * @throws RestException when an HTTP-level error occurs * @throws IOException when an error reading the response occurs * @throws URISyntaxException when an error occurred appending the path to the URI */ public JSON put(String path, JSON payload) throws RestException, IOException, URISyntaxException { return put(buildURI(path), payload); } /** * Exposes the http client. * * @return the httpClient property */ public HttpClient getHttpClient(){ return this.httpClient; } }
true
true
private JSON request(HttpRequestBase req) throws RestException, IOException { req.addHeader("Accept", "application/json"); if (creds != null) creds.authenticate(req); HttpResponse resp = httpClient.execute(req); HttpEntity ent = resp.getEntity(); StringBuilder result = new StringBuilder(); if (ent != null) { BufferedReader br = new BufferedReader(new InputStreamReader(ent.getContent())); String line = ""; while ((line = br.readLine()) != null) result.append(line); } StatusLine sl = resp.getStatusLine(); if (sl.getStatusCode() >= 300) throw new RestException(sl.getReasonPhrase(), sl.getStatusCode(), result.toString()); return result.length() > 0 ? JSONSerializer.toJSON(result.toString()): null; }
private JSON request(HttpRequestBase req) throws RestException, IOException { req.addHeader("Accept", "application/json"); if (creds != null) creds.authenticate(req); HttpResponse resp = httpClient.execute(req); HttpEntity ent = resp.getEntity(); StringBuilder result = new StringBuilder(); if (ent != null) { InputStreamReader isr = ent.getContentEncoding() != null ? new InputStreamReader(ent.getContent(), ent.getContentEncoding().getValue()) : new InputStreamReader(ent.getContent()); BufferedReader br = new BufferedReader(isr); String line = ""; while ((line = br.readLine()) != null) result.append(line); } StatusLine sl = resp.getStatusLine(); if (sl.getStatusCode() >= 300) throw new RestException(sl.getReasonPhrase(), sl.getStatusCode(), result.toString()); return result.length() > 0 ? JSONSerializer.toJSON(result.toString()): null; }
diff --git a/jboss-5/src/main/java/org/mobicents/ha/javax/sip/SipStackImpl.java b/jboss-5/src/main/java/org/mobicents/ha/javax/sip/SipStackImpl.java index 733122b..89240f5 100644 --- a/jboss-5/src/main/java/org/mobicents/ha/javax/sip/SipStackImpl.java +++ b/jboss-5/src/main/java/org/mobicents/ha/javax/sip/SipStackImpl.java @@ -1,142 +1,149 @@ /* * JBoss, Home of Professional Open Source * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.mobicents.ha.javax.sip; import gov.nist.core.StackLogger; import java.util.Properties; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.sip.PeerUnavailableException; import javax.sip.ProviderDoesNotExistException; import javax.sip.SipException; import org.mobicents.ha.javax.sip.cache.SipCache; /** * This class extends the ClusteredSipStack to provide an implementation backed by JBoss Cache 3.X * * @author [email protected] * */ public class SipStackImpl extends ClusteredSipStackImpl implements SipStackImplMBean, NotificationListener { public static String JAIN_SIP_MBEAN_NAME = "org.mobicents.jain.sip:type=sip-stack,name="; public static String LOG4J_SERVICE_MBEAN_NAME = "jboss.system:service=Logging,type=Log4jService"; ObjectName oname = null; MBeanServer mbeanServer = null; boolean isMBeanServerNotAvailable = false; public SipStackImpl(Properties configurationProperties) throws PeerUnavailableException { super(updateConfigProperties(configurationProperties)); } private static final Properties updateConfigProperties(Properties configurationProperties) { if(configurationProperties.getProperty(ClusteredSipStack.CACHE_CLASS_NAME_PROPERTY) == null) { configurationProperties.setProperty(ClusteredSipStack.CACHE_CLASS_NAME_PROPERTY, SipCache.SIP_DEFAULT_CACHE_CLASS_NAME); } return configurationProperties; } public int getNumberOfClientTransactions() { return getClientTransactionTableSize(); } public int getNumberOfDialogs() { return dialogTable.size(); } public int getNumberOfEarlyDialogs() { return earlyDialogTable.size(); } public int getNumberOfServerTransactions() { return getServerTransactionTableSize(); } @Override public void start() throws ProviderDoesNotExistException, SipException { super.start(); String mBeanName=JAIN_SIP_MBEAN_NAME + stackName; try { oname = new ObjectName(mBeanName); if (getMBeanServer() != null && !getMBeanServer().isRegistered(oname)) { getMBeanServer().registerMBean(this, oname); if(getStackLogger().isLoggingEnabled(StackLogger.TRACE_INFO)) { getStackLogger().logInfo("Adding notification listener for logging mbean \"" + LOG4J_SERVICE_MBEAN_NAME + "\" to server " + getMBeanServer()); } - getMBeanServer().addNotificationListener(new ObjectName(LOG4J_SERVICE_MBEAN_NAME), this, null, null); } } catch (Exception e) { getStackLogger().logError("Could not register the stack as an MBean under the following name", e); throw new SipException("Could not register the stack as an MBean under the following name " + mBeanName + ", cause: " + e.getMessage(), e); } + try { + if(getStackLogger().isLoggingEnabled(StackLogger.TRACE_INFO)) { + getStackLogger().logInfo("Adding notification listener for logging mbean \"" + LOG4J_SERVICE_MBEAN_NAME + "\" to server " + getMBeanServer()); + } + getMBeanServer().addNotificationListener(new ObjectName(LOG4J_SERVICE_MBEAN_NAME), this, null, null); + } catch (Exception e) { + getStackLogger().logWarning("Could not register the stack as a Notification Listener of " + LOG4J_SERVICE_MBEAN_NAME + " runtime changes to log4j.xml won't affect SIP Stack Logging"); + } } @Override public void stop() { String mBeanName=JAIN_SIP_MBEAN_NAME + stackName; try { if (oname != null && getMBeanServer() != null && getMBeanServer().isRegistered(oname)) { getMBeanServer().unregisterMBean(oname); } } catch (Exception e) { getStackLogger().logError("Could not unregister the stack as an MBean under the following name" + mBeanName); } super.stop(); } /** * Get the current MBean Server. * * @return * @throws Exception */ protected MBeanServer getMBeanServer() throws Exception { if (mbeanServer == null && !isMBeanServerNotAvailable) { try { mbeanServer = (MBeanServer) MBeanServerFactory.findMBeanServer(null).get(0); } catch (Exception e) { getStackLogger().logStackTrace(StackLogger.TRACE_DEBUG); getStackLogger().logWarning("No Mbean Server available, so JMX statistics won't be available"); isMBeanServerNotAvailable = true; } } return mbeanServer; } public boolean isLocalMode() { return getSipCache().inLocalMode(); } /* * (non-Javadoc) * @see javax.management.NotificationListener#handleNotification(javax.management.Notification, java.lang.Object) */ public void handleNotification(Notification notification, Object handback) { getStackLogger().setStackProperties(super.getConfigurationProperties()); } }
false
true
public void start() throws ProviderDoesNotExistException, SipException { super.start(); String mBeanName=JAIN_SIP_MBEAN_NAME + stackName; try { oname = new ObjectName(mBeanName); if (getMBeanServer() != null && !getMBeanServer().isRegistered(oname)) { getMBeanServer().registerMBean(this, oname); if(getStackLogger().isLoggingEnabled(StackLogger.TRACE_INFO)) { getStackLogger().logInfo("Adding notification listener for logging mbean \"" + LOG4J_SERVICE_MBEAN_NAME + "\" to server " + getMBeanServer()); } getMBeanServer().addNotificationListener(new ObjectName(LOG4J_SERVICE_MBEAN_NAME), this, null, null); } } catch (Exception e) { getStackLogger().logError("Could not register the stack as an MBean under the following name", e); throw new SipException("Could not register the stack as an MBean under the following name " + mBeanName + ", cause: " + e.getMessage(), e); } }
public void start() throws ProviderDoesNotExistException, SipException { super.start(); String mBeanName=JAIN_SIP_MBEAN_NAME + stackName; try { oname = new ObjectName(mBeanName); if (getMBeanServer() != null && !getMBeanServer().isRegistered(oname)) { getMBeanServer().registerMBean(this, oname); if(getStackLogger().isLoggingEnabled(StackLogger.TRACE_INFO)) { getStackLogger().logInfo("Adding notification listener for logging mbean \"" + LOG4J_SERVICE_MBEAN_NAME + "\" to server " + getMBeanServer()); } } } catch (Exception e) { getStackLogger().logError("Could not register the stack as an MBean under the following name", e); throw new SipException("Could not register the stack as an MBean under the following name " + mBeanName + ", cause: " + e.getMessage(), e); } try { if(getStackLogger().isLoggingEnabled(StackLogger.TRACE_INFO)) { getStackLogger().logInfo("Adding notification listener for logging mbean \"" + LOG4J_SERVICE_MBEAN_NAME + "\" to server " + getMBeanServer()); } getMBeanServer().addNotificationListener(new ObjectName(LOG4J_SERVICE_MBEAN_NAME), this, null, null); } catch (Exception e) { getStackLogger().logWarning("Could not register the stack as a Notification Listener of " + LOG4J_SERVICE_MBEAN_NAME + " runtime changes to log4j.xml won't affect SIP Stack Logging"); } }
diff --git a/basiclti-common/src/java/org/sakaiproject/basiclti/util/ShaUtil.java b/basiclti-common/src/java/org/sakaiproject/basiclti/util/ShaUtil.java index e6333ab..46521f1 100644 --- a/basiclti-common/src/java/org/sakaiproject/basiclti/util/ShaUtil.java +++ b/basiclti-common/src/java/org/sakaiproject/basiclti/util/ShaUtil.java @@ -1,94 +1,94 @@ /** * $URL$ * $Id$ * * Copyright (c) 2010 The Sakai Foundation * * Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.sakaiproject.basiclti.util; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class ShaUtil { private static final char[] TOHEX = "0123456789abcdef".toCharArray(); public static final String UTF8 = "UTF8"; public static String sha1Hash(final String tohash) { byte[] b = null; try { b = tohash.getBytes("UTF-8"); MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); b = sha1.digest(b); } catch (UnsupportedEncodingException e) { throw new Error(e); } catch (NoSuchAlgorithmException e) { throw new Error(e); } return byteToHex(b); } public static String sha256Hash(final String tohash) { byte[] b = null; try { b = tohash.getBytes("UTF-8"); MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); b = sha256.digest(b); } catch (UnsupportedEncodingException e) { throw new Error(e); } catch (NoSuchAlgorithmException e) { throw new Error(e); } return byteToHex(b); } public static String byteToHex(final byte[] base) { if (base != null) { char[] c = new char[base.length * 2]; int i = 0; for (byte b : base) { int j = b; j = j + 128; c[i++] = TOHEX[j / 0x10]; c[i++] = TOHEX[j % 0x10]; } return new String(c); } else { return null; } } public static void main(String[] args) { - final String sample1 = "12345:/sites/foo/bar !@#$%^&*()_+|}{\":?><[]\';/.,'����������Э��ҹ������ό�ĩ����ɾֳ���ÍŽ"; - final String sample2 = "12345:/sites/foo/bar !@#$%^&*()_+|}{\":?><[]\';/.,'����������Э��ҹ������ό�ĩ����ɾֳ���ÍŽ"; - final String sample3 = "12345:/sites/foo/bar !@#$%^&*()_+|}{\":?><[]\';/.,'����������Э��ҹ������ό�ĩ����ɾֳ���Í��"; + final String sample1 = "12345:/sites/foo/bar !@#$%^&*()_+|}{\":?><[]\';/.,'Áª£¢°¤¦¥»¼Ð­ÇÔÒ¹¿ö¬ ¨«ÏŒ¶Ä©úÆûÂɾֳ²µ÷ÍŽ"; + final String sample2 = "12345:/sites/foo/bar !@#$%^&*()_+|}{\":?><[]\';/.,'Áª£¢°¤¦¥»¼Ð­ÇÔÒ¹¿ö¬ ¨«ÏŒ¶Ä©úÆûÂɾֳ²µ÷ÍŽ"; + final String sample3 = "12345:/sites/foo/bar !@#$%^&*()_+|}{\":?><[]\';/.,'Áª£¢°¤¦¥»¼Ð­ÇÔÒ¹¿ö¬ ¨«ÏŒ¶Ä©úÆûÂɾֳ²µ÷ÍÅÅ"; final String sample1Hash = sha1Hash(sample1); final String sample2Hash = sha1Hash(sample2); final String sample3Hash = sha1Hash(sample3); System.out.println(sample1Hash); System.out.println(sample2Hash); System.out.println(sample3Hash); assert (sample1Hash.equals(sample2Hash)); System.out.println(sample1Hash.equals(sample2Hash) + "=(sample1Hash.equals(sample2Hash))"); assert (!sample3Hash.equals(sample1Hash)); System.out.println(!sample3Hash.equals(sample1Hash) + "=(!sample3Hash.equals(sample1Hash))"); assert (null == byteToHex(null)); final boolean testNull = (null == byteToHex(null)); System.out.println(testNull + "=(null == byteToHex(null))"); } }
true
true
public static void main(String[] args) { final String sample1 = "12345:/sites/foo/bar !@#$%^&*()_+|}{\":?><[]\';/.,'����������Э��ҹ������ό�ĩ����ɾֳ���ÍŽ"; final String sample2 = "12345:/sites/foo/bar !@#$%^&*()_+|}{\":?><[]\';/.,'����������Э��ҹ������ό�ĩ����ɾֳ���ÍŽ"; final String sample3 = "12345:/sites/foo/bar !@#$%^&*()_+|}{\":?><[]\';/.,'����������Э��ҹ������ό�ĩ����ɾֳ���Í��"; final String sample1Hash = sha1Hash(sample1); final String sample2Hash = sha1Hash(sample2); final String sample3Hash = sha1Hash(sample3); System.out.println(sample1Hash); System.out.println(sample2Hash); System.out.println(sample3Hash); assert (sample1Hash.equals(sample2Hash)); System.out.println(sample1Hash.equals(sample2Hash) + "=(sample1Hash.equals(sample2Hash))"); assert (!sample3Hash.equals(sample1Hash)); System.out.println(!sample3Hash.equals(sample1Hash) + "=(!sample3Hash.equals(sample1Hash))"); assert (null == byteToHex(null)); final boolean testNull = (null == byteToHex(null)); System.out.println(testNull + "=(null == byteToHex(null))"); }
public static void main(String[] args) { final String sample1 = "12345:/sites/foo/bar !@#$%^&*()_+|}{\":?><[]\';/.,'Áª£¢°¤¦¥»¼Ð­ÇÔÒ¹¿ö¬ ¨«ÏŒ¶Ä©úÆûÂɾֳ²µ÷ÍŽ"; final String sample2 = "12345:/sites/foo/bar !@#$%^&*()_+|}{\":?><[]\';/.,'Áª£¢°¤¦¥»¼Ð­ÇÔÒ¹¿ö¬ ¨«ÏŒ¶Ä©úÆûÂɾֳ²µ÷ÍŽ"; final String sample3 = "12345:/sites/foo/bar !@#$%^&*()_+|}{\":?><[]\';/.,'Áª£¢°¤¦¥»¼Ð­ÇÔÒ¹¿ö¬ ¨«ÏŒ¶Ä©úÆûÂɾֳ²µ÷ÍÅÅ"; final String sample1Hash = sha1Hash(sample1); final String sample2Hash = sha1Hash(sample2); final String sample3Hash = sha1Hash(sample3); System.out.println(sample1Hash); System.out.println(sample2Hash); System.out.println(sample3Hash); assert (sample1Hash.equals(sample2Hash)); System.out.println(sample1Hash.equals(sample2Hash) + "=(sample1Hash.equals(sample2Hash))"); assert (!sample3Hash.equals(sample1Hash)); System.out.println(!sample3Hash.equals(sample1Hash) + "=(!sample3Hash.equals(sample1Hash))"); assert (null == byteToHex(null)); final boolean testNull = (null == byteToHex(null)); System.out.println(testNull + "=(null == byteToHex(null))"); }
diff --git a/trunk/org/xbill/DNS/Master.java b/trunk/org/xbill/DNS/Master.java index 574ec85..c795a9c 100644 --- a/trunk/org/xbill/DNS/Master.java +++ b/trunk/org/xbill/DNS/Master.java @@ -1,427 +1,427 @@ // Copyright (c) 1999-2004 Brian Wellington ([email protected]) package org.xbill.DNS; import java.io.*; import java.util.*; /** * A DNS master file parser. This incrementally parses the file, returning * one record at a time. When directives are seen, they are added to the * state and used when parsing future records. * * @author Brian Wellington */ public class Master { private Name origin; private File file; private Record last = null; private long defaultTTL; private Master included = null; private Tokenizer st; private int currentType; private int currentDClass; private long currentTTL; private boolean needSOATTL; private Generator generator; private List generators; private boolean noExpandGenerate; Master(File file, Name origin, long initialTTL) throws IOException { if (origin != null && !origin.isAbsolute()) { throw new RelativeNameException(origin); } this.file = file; st = new Tokenizer(file); this.origin = origin; defaultTTL = initialTTL; } /** * Initializes the master file reader and opens the specified master file. * @param filename The master file. * @param origin The initial origin to append to relative names. * @param ttl The initial default TTL. * @throws IOException The master file could not be opened. */ public Master(String filename, Name origin, long ttl) throws IOException { this(new File(filename), origin, ttl); } /** * Initializes the master file reader and opens the specified master file. * @param filename The master file. * @param origin The initial origin to append to relative names. * @throws IOException The master file could not be opened. */ public Master(String filename, Name origin) throws IOException { this(new File(filename), origin, -1); } /** * Initializes the master file reader and opens the specified master file. * @param filename The master file. * @throws IOException The master file could not be opened. */ public Master(String filename) throws IOException { this(new File(filename), null, -1); } /** * Initializes the master file reader. * @param in The input stream containing a master file. * @param origin The initial origin to append to relative names. * @param ttl The initial default TTL. */ public Master(InputStream in, Name origin, long ttl) { if (origin != null && !origin.isAbsolute()) { throw new RelativeNameException(origin); } st = new Tokenizer(in); this.origin = origin; defaultTTL = ttl; } /** * Initializes the master file reader. * @param in The input stream containing a master file. * @param origin The initial origin to append to relative names. */ public Master(InputStream in, Name origin) { this(in, origin, -1); } /** * Initializes the master file reader. * @param in The input stream containing a master file. */ public Master(InputStream in) { this(in, null, -1); } private Name parseName(String s, Name origin) throws TextParseException { try { return Name.fromString(s, origin); } catch (TextParseException e) { throw st.exception(e.getMessage()); } } private void parseTTLClassAndType() throws IOException { String s; boolean seen_class = false; // This is a bit messy, since any of the following are legal: // class ttl type // ttl class type // class type // ttl type // type seen_class = false; s = st.getString(); if ((currentDClass = DClass.value(s)) >= 0) { s = st.getString(); seen_class = true; } currentTTL = -1; try { currentTTL = TTL.parseTTL(s); s = st.getString(); } catch (NumberFormatException e) { if (defaultTTL >= 0) currentTTL = defaultTTL; else if (last != null) currentTTL = last.getTTL(); } if (!seen_class) { if ((currentDClass = DClass.value(s)) >= 0) { s = st.getString(); } else { currentDClass = DClass.IN; } } if ((currentType = Type.value(s)) < 0) throw st.exception("Invalid type '" + s + "'"); // BIND allows a missing TTL for the initial SOA record, and uses // the SOA minimum value. If the SOA is not the first record, // this is an error. if (currentTTL < 0) { if (currentType != Type.SOA) throw st.exception("missing TTL"); needSOATTL = true; currentTTL = 0; } } private long parseUInt32(String s) { if (!Character.isDigit(s.charAt(0))) return -1; try { long l = Long.parseLong(s); if (l < 0 || l > 0xFFFFFFFFL) return -1; return l; } catch (NumberFormatException e) { return -1; } } private void startGenerate() throws IOException { String s; int n; // The first field is of the form start-end[/step] // Regexes would be useful here. s = st.getIdentifier(); n = s.indexOf("-"); if (n < 0) throw st.exception("Invalid $GENERATE range specifier: " + s); String startstr = s.substring(0, n); String endstr = s.substring(n + 1); String stepstr = null; n = endstr.indexOf("/"); if (n >= 0) { stepstr = endstr.substring(n + 1); endstr = endstr.substring(0, n); } long start = parseUInt32(startstr); long end = parseUInt32(endstr); long step; if (stepstr != null) step = parseUInt32(stepstr); else step = 1; if (start < 0 || end < 0 || start > end || step <= 0) throw st.exception("Invalid $GENERATE range specifier: " + s); // The next field is the name specification. String nameSpec = st.getIdentifier(); // Then the ttl/class/type, in the same form as a normal record. // Only some types are supported. parseTTLClassAndType(); if (!Generator.supportedType(currentType)) throw st.exception("$GENERATE does not support " + Type.string(currentType) + " records"); // Next comes the rdata specification. String rdataSpec = st.getIdentifier(); // That should be the end. However, we don't want to move past the // line yet, so put back the EOL after reading it. st.getEOL(); st.unget(); generator = new Generator(start, end, step, nameSpec, currentType, currentDClass, currentTTL, rdataSpec, origin); if (generators == null) generators = new ArrayList(1); generators.add(generator); } private void endGenerate() throws IOException { // Read the EOL that we put back before. st.getEOL(); generator = null; } private Record nextGenerated() throws IOException { try { return generator.nextRecord(); } catch (Tokenizer.TokenizerException e) { throw st.exception("Parsing $GENERATE: " + e.getBaseMessage()); } catch (TextParseException e) { throw st.exception("Parsing $GENERATE: " + e.getMessage()); } } /** * Returns the next record in the master file. This will process any * directives before the next record. * @return The next record. * @throws IOException The master file could not be read, or was syntactically * invalid. */ public Record _nextRecord() throws IOException { Tokenizer.Token token; String s; if (included != null) { Record rec = included.nextRecord(); if (rec != null) return rec; included = null; } if (generator != null) { Record rec = nextGenerated(); if (rec != null) return rec; endGenerate(); } while (true) { Name name; token = st.get(true, false); if (token.type == Tokenizer.WHITESPACE) { Tokenizer.Token next = st.get(); - if (token.type == Tokenizer.EOL) + if (next.type == Tokenizer.EOL) continue; - else if (token.type == Tokenizer.EOF) + else if (next.type == Tokenizer.EOF) return null; else st.unget(); if (last == null) throw st.exception("no owner"); name = last.getName(); } else if (token.type == Tokenizer.EOL) continue; else if (token.type == Tokenizer.EOF) return null; else if (((String) token.value).charAt(0) == '$') { s = token.value; if (s.equalsIgnoreCase("$ORIGIN")) { origin = st.getName(Name.root); st.getEOL(); continue; } else if (s.equalsIgnoreCase("$TTL")) { defaultTTL = st.getTTL(); st.getEOL(); continue; } else if (s.equalsIgnoreCase("$INCLUDE")) { String filename = st.getString(); File newfile; if (file != null) { String parent = file.getParent(); newfile = new File(parent, filename); } else { newfile = new File(filename); } Name incorigin = origin; token = st.get(); if (token.isString()) { incorigin = parseName(token.value, Name.root); st.getEOL(); } included = new Master(newfile, incorigin, defaultTTL); /* * If we continued, we wouldn't be looking in * the new file. Recursing works better. */ return nextRecord(); } else if (s.equalsIgnoreCase("$GENERATE")) { if (generator != null) throw new IllegalStateException ("cannot nest $GENERATE"); startGenerate(); if (noExpandGenerate) { endGenerate(); continue; } return nextGenerated(); } else { throw st.exception("Invalid directive: " + s); } } else { s = token.value; name = parseName(s, origin); if (last != null && name.equals(last.getName())) { name = last.getName(); } } parseTTLClassAndType(); last = Record.fromString(name, currentType, currentDClass, currentTTL, st, origin); if (needSOATTL) { long ttl = ((SOARecord)last).getMinimum(); last.setTTL(ttl); defaultTTL = ttl; needSOATTL = false; } return last; } } /** * Returns the next record in the master file. This will process any * directives before the next record. * @return The next record. * @throws IOException The master file could not be read, or was syntactically * invalid. */ public Record nextRecord() throws IOException { Record rec = null; try { rec = _nextRecord(); } finally { if (rec == null) { st.close(); } } return rec; } /** * Specifies whether $GENERATE statements should be expanded. Whether * expanded or not, the specifications for generated records are available * by calling {@link #generators}. This must be called before a $GENERATE * statement is seen during iteration to have an effect. */ public void expandGenerate(boolean wantExpand) { noExpandGenerate = !wantExpand; } /** * Returns an iterator over the generators specified in the master file; that * is, the parsed contents of $GENERATE statements. * @see Generator */ public Iterator generators() { if (generators != null) return Collections.unmodifiableList(generators).iterator(); else return Collections.EMPTY_LIST.iterator(); } protected void finalize() { st.close(); } }
false
true
public Record _nextRecord() throws IOException { Tokenizer.Token token; String s; if (included != null) { Record rec = included.nextRecord(); if (rec != null) return rec; included = null; } if (generator != null) { Record rec = nextGenerated(); if (rec != null) return rec; endGenerate(); } while (true) { Name name; token = st.get(true, false); if (token.type == Tokenizer.WHITESPACE) { Tokenizer.Token next = st.get(); if (token.type == Tokenizer.EOL) continue; else if (token.type == Tokenizer.EOF) return null; else st.unget(); if (last == null) throw st.exception("no owner"); name = last.getName(); } else if (token.type == Tokenizer.EOL) continue; else if (token.type == Tokenizer.EOF) return null; else if (((String) token.value).charAt(0) == '$') { s = token.value; if (s.equalsIgnoreCase("$ORIGIN")) { origin = st.getName(Name.root); st.getEOL(); continue; } else if (s.equalsIgnoreCase("$TTL")) { defaultTTL = st.getTTL(); st.getEOL(); continue; } else if (s.equalsIgnoreCase("$INCLUDE")) { String filename = st.getString(); File newfile; if (file != null) { String parent = file.getParent(); newfile = new File(parent, filename); } else { newfile = new File(filename); } Name incorigin = origin; token = st.get(); if (token.isString()) { incorigin = parseName(token.value, Name.root); st.getEOL(); } included = new Master(newfile, incorigin, defaultTTL); /* * If we continued, we wouldn't be looking in * the new file. Recursing works better. */ return nextRecord(); } else if (s.equalsIgnoreCase("$GENERATE")) { if (generator != null) throw new IllegalStateException ("cannot nest $GENERATE"); startGenerate(); if (noExpandGenerate) { endGenerate(); continue; } return nextGenerated(); } else { throw st.exception("Invalid directive: " + s); } } else { s = token.value; name = parseName(s, origin); if (last != null && name.equals(last.getName())) { name = last.getName(); } } parseTTLClassAndType(); last = Record.fromString(name, currentType, currentDClass, currentTTL, st, origin); if (needSOATTL) { long ttl = ((SOARecord)last).getMinimum(); last.setTTL(ttl); defaultTTL = ttl; needSOATTL = false; } return last; } }
public Record _nextRecord() throws IOException { Tokenizer.Token token; String s; if (included != null) { Record rec = included.nextRecord(); if (rec != null) return rec; included = null; } if (generator != null) { Record rec = nextGenerated(); if (rec != null) return rec; endGenerate(); } while (true) { Name name; token = st.get(true, false); if (token.type == Tokenizer.WHITESPACE) { Tokenizer.Token next = st.get(); if (next.type == Tokenizer.EOL) continue; else if (next.type == Tokenizer.EOF) return null; else st.unget(); if (last == null) throw st.exception("no owner"); name = last.getName(); } else if (token.type == Tokenizer.EOL) continue; else if (token.type == Tokenizer.EOF) return null; else if (((String) token.value).charAt(0) == '$') { s = token.value; if (s.equalsIgnoreCase("$ORIGIN")) { origin = st.getName(Name.root); st.getEOL(); continue; } else if (s.equalsIgnoreCase("$TTL")) { defaultTTL = st.getTTL(); st.getEOL(); continue; } else if (s.equalsIgnoreCase("$INCLUDE")) { String filename = st.getString(); File newfile; if (file != null) { String parent = file.getParent(); newfile = new File(parent, filename); } else { newfile = new File(filename); } Name incorigin = origin; token = st.get(); if (token.isString()) { incorigin = parseName(token.value, Name.root); st.getEOL(); } included = new Master(newfile, incorigin, defaultTTL); /* * If we continued, we wouldn't be looking in * the new file. Recursing works better. */ return nextRecord(); } else if (s.equalsIgnoreCase("$GENERATE")) { if (generator != null) throw new IllegalStateException ("cannot nest $GENERATE"); startGenerate(); if (noExpandGenerate) { endGenerate(); continue; } return nextGenerated(); } else { throw st.exception("Invalid directive: " + s); } } else { s = token.value; name = parseName(s, origin); if (last != null && name.equals(last.getName())) { name = last.getName(); } } parseTTLClassAndType(); last = Record.fromString(name, currentType, currentDClass, currentTTL, st, origin); if (needSOATTL) { long ttl = ((SOARecord)last).getMinimum(); last.setTTL(ttl); defaultTTL = ttl; needSOATTL = false; } return last; } }
diff --git a/src/main/java/net/minecraft/client/gui/InputFix_GuiScreenFix.java b/src/main/java/net/minecraft/client/gui/InputFix_GuiScreenFix.java index 4ca15fe..193d4a4 100644 --- a/src/main/java/net/minecraft/client/gui/InputFix_GuiScreenFix.java +++ b/src/main/java/net/minecraft/client/gui/InputFix_GuiScreenFix.java @@ -1,86 +1,85 @@ package net.minecraft.client.gui; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.Properties; import org.lwjgl.input.Keyboard; public class InputFix_GuiScreenFix { public static String encoding; static { try { Properties a = new Properties(); a.load(new FileInputStream(new File("inputfix.properties"))); encoding = a.getProperty("encoding", "GBK"); } catch (FileNotFoundException e) { Properties a = new Properties(); a.setProperty("encoding", "GBK"); try { a.store(new FileOutputStream(new File("inputfix.properties")), null); } catch (Throwable t) { t.printStackTrace(); } } catch (Throwable t) { encoding = "GBK"; } } public static void handleKeyboardInput(GuiScreen gui) { if (Keyboard.getEventKeyState()) { do { int k = Keyboard.getEventKey(); char c = Keyboard.getEventCharacter(); if (k == 87) { gui.mc.toggleFullscreen(); return; } if (gui.isMacOs && k == 28 && c == 0) { k = 29; } - if ((byte) c < 0 && Keyboard.next()) + if (c > 0x7F && c <= 0xFF) { + Keyboard.next(); int k2 = Keyboard.getEventKey(); char c2 = Keyboard.getEventCharacter(); try { c2 = new String(new byte[] { (byte) c, (byte) c2 }, encoding).charAt(0); gui.keyTyped(c2, k); } catch (Throwable t) { gui.keyTyped(c, k); gui.keyTyped(c2, k2); } + continue; } - else - { - gui.keyTyped(c, k); - } + gui.keyTyped(c, k); } while (Keyboard.next()); } } }
false
true
public static void handleKeyboardInput(GuiScreen gui) { if (Keyboard.getEventKeyState()) { do { int k = Keyboard.getEventKey(); char c = Keyboard.getEventCharacter(); if (k == 87) { gui.mc.toggleFullscreen(); return; } if (gui.isMacOs && k == 28 && c == 0) { k = 29; } if ((byte) c < 0 && Keyboard.next()) { int k2 = Keyboard.getEventKey(); char c2 = Keyboard.getEventCharacter(); try { c2 = new String(new byte[] { (byte) c, (byte) c2 }, encoding).charAt(0); gui.keyTyped(c2, k); } catch (Throwable t) { gui.keyTyped(c, k); gui.keyTyped(c2, k2); } } else { gui.keyTyped(c, k); } } while (Keyboard.next()); } }
public static void handleKeyboardInput(GuiScreen gui) { if (Keyboard.getEventKeyState()) { do { int k = Keyboard.getEventKey(); char c = Keyboard.getEventCharacter(); if (k == 87) { gui.mc.toggleFullscreen(); return; } if (gui.isMacOs && k == 28 && c == 0) { k = 29; } if (c > 0x7F && c <= 0xFF) { Keyboard.next(); int k2 = Keyboard.getEventKey(); char c2 = Keyboard.getEventCharacter(); try { c2 = new String(new byte[] { (byte) c, (byte) c2 }, encoding).charAt(0); gui.keyTyped(c2, k); } catch (Throwable t) { gui.keyTyped(c, k); gui.keyTyped(c2, k2); } continue; } gui.keyTyped(c, k); } while (Keyboard.next()); } }
diff --git a/src/screencapture/PictureWriterThread.java b/src/screencapture/PictureWriterThread.java index c7f817a..33c7f57 100755 --- a/src/screencapture/PictureWriterThread.java +++ b/src/screencapture/PictureWriterThread.java @@ -1,107 +1,107 @@ package screencapture; import java.io.File; import java.io.IOException; import java.util.concurrent.ConcurrentLinkedQueue; import javax.imageio.ImageIO; public class PictureWriterThread extends Thread { private ConcurrentLinkedQueue<PicNode> data; private volatile boolean running; /** * Default Constructor * Creates a new ConcurrentLinkedQueue to hold data taken from the PictureTakerThread. * Sets running to true; This makes our loop in run tick. */ public PictureWriterThread(ConcurrentLinkedQueue<PicNode> data) { this.data = data; this.running = true; } /** * Main operation of the PictureWriterThread. * Converts the data from the PictureTakerThread and turns them into images. */ @Override public void run() { // TODO: DEBUG prints out that the PictureWriterThread has started. System.out.println("PictureWriter has started."); // Sets a node that is going to be reused many times to null. PicNode pn = null; try { // TODO: DEBUG variable holds timer information. long before = 0; while(running) { write(pn, before); sleep(0); } // Write out everything left in the buffer. while(!data.isEmpty()) { write(pn, before); sleep(0); } // TODO: DEBUG prints out that the PictureWriterThread has ended. System.out.println("PictureWriterThread has ended."); } catch(IOException ex) { - System.out.println("Unable to create Binary stream."); + System.out.println("Error occurred creating the image."); } } /** * Creates a .jpg image of the next file in the ConcurrentLinkedQueue data. * @param pn A PictureNode used to hold the data removed from the ConcurrentLinkedQueue. */ private synchronized void write(PicNode pn, long before) throws IOException { if(data != null && !data.isEmpty()) { // Debug Timing before = System.currentTimeMillis(); pn = data.remove(); ImageIO.write(pn.IMAGE, "jpg", new File(pn.FILE_NAME)); System.out.println("Write DT: " + (System.currentTimeMillis() - before)); } } /** * Ends the main loop in the run method. */ public synchronized void kill() { this.running = false; } /** * @return If there is still data in the ConcurrentLinkedQueue return true. */ public synchronized boolean hasData() { return (this.data.size() > 0 ? true : false); } /** * Method to sleep the thread. * @param millis Contains the amount of milli seconds we want to sleep for. */ private void sleep(int millis) { try { Thread.sleep(millis); } catch(Exception ex) { System.out.println("Error Sleeping. Thread may have been interupted."); } } }
true
true
public void run() { // TODO: DEBUG prints out that the PictureWriterThread has started. System.out.println("PictureWriter has started."); // Sets a node that is going to be reused many times to null. PicNode pn = null; try { // TODO: DEBUG variable holds timer information. long before = 0; while(running) { write(pn, before); sleep(0); } // Write out everything left in the buffer. while(!data.isEmpty()) { write(pn, before); sleep(0); } // TODO: DEBUG prints out that the PictureWriterThread has ended. System.out.println("PictureWriterThread has ended."); } catch(IOException ex) { System.out.println("Unable to create Binary stream."); } }
public void run() { // TODO: DEBUG prints out that the PictureWriterThread has started. System.out.println("PictureWriter has started."); // Sets a node that is going to be reused many times to null. PicNode pn = null; try { // TODO: DEBUG variable holds timer information. long before = 0; while(running) { write(pn, before); sleep(0); } // Write out everything left in the buffer. while(!data.isEmpty()) { write(pn, before); sleep(0); } // TODO: DEBUG prints out that the PictureWriterThread has ended. System.out.println("PictureWriterThread has ended."); } catch(IOException ex) { System.out.println("Error occurred creating the image."); } }
diff --git a/src/com/undeadscythes/udsplugin/SaveablePlayer.java b/src/com/undeadscythes/udsplugin/SaveablePlayer.java index ed6a5b1..7a090f5 100644 --- a/src/com/undeadscythes/udsplugin/SaveablePlayer.java +++ b/src/com/undeadscythes/udsplugin/SaveablePlayer.java @@ -1,1424 +1,1424 @@ package com.undeadscythes.udsplugin; import com.undeadscythes.udsplugin.Region.RegionType; import com.undeadscythes.udsplugin.eventhandlers.AsyncPlayerChat.Channel; import java.io.*; import java.util.*; import java.util.logging.*; import org.apache.commons.lang.*; import org.bukkit.*; import org.bukkit.block.*; import org.bukkit.entity.*; import org.bukkit.inventory.*; /** * An extension of Minecraft players adding various fields and methods. * @author UndeadScythes */ public class SaveablePlayer implements Saveable { /** * A player rank granting permission. * @author UndeadScythes */ public enum PlayerRank { DEFAULT(ChatColor.WHITE, 0), MEMBER(ChatColor.GREEN, 1), VIP(ChatColor.DARK_PURPLE, 1), WARDEN(ChatColor.AQUA, 2), MOD(ChatColor.DARK_AQUA, 3), ADMIN(ChatColor.YELLOW, 4), OWNER(ChatColor.GOLD, 5), NONE(null, 5); private ChatColor color; private int ranking; PlayerRank(final ChatColor color, final int rank) { this.color = color; this.ranking = rank; } /** * Get the chat color associated to this rank. * @return The rank's chat color. */ public ChatColor getColor() { return color; } /** * Get player rank by integer ranking. * @param ranking Integer ranking. * @return Player rank or <code>null</code> if there is no match. */ public static PlayerRank getByRanking(final int ranking) { for(PlayerRank rank : values()) { if(rank.ranking == ranking) { return rank; } } return null; } /** * Get the rank above this one. * @param rank Player rank. * @return The rank above. */ public static PlayerRank getAbove(final PlayerRank rank) { return getByRanking(rank.ranking + 1); } /** * Get the rank below this one. * @param rank Player rank. * @return The rank below. */ public static PlayerRank getBelow(final PlayerRank rank) { return getByRanking(rank.ranking - 1); } /** * Get player rank by name. * @param string Rank name. * @return Player rank, <code>null</code> if there is no match. */ public static PlayerRank getByName(final String string) { for(PlayerRank rank : values()) { if(rank.name().equals(string.toUpperCase())) { return rank; } } return null; } @Override public String toString() { return StringUtils.capitalize(name().toLowerCase()); } } /** * File name of player file. */ public final static String PATH = "players.csv"; /** * Current record version. */ public final static int VERSION = 1; private transient String name; private transient Player base; private transient String nick; private transient long timeLogged = 0; private transient Location back = null; private transient boolean godMode = false; private transient boolean lockdownPass = false; private long lastDamageCaused = 0; private SaveablePlayer challenger = null; private int wager = 0; private transient long prizeClaim = 0; private Location checkPoint = null; private transient ChatRoom chatRoom = null; // Is this field never modified? private final transient Set<SaveablePlayer> ignoredPlayers = new HashSet<SaveablePlayer>(); private transient Channel channel = Channel.PUBLIC; private final transient LinkedList<Long> lastChats = new LinkedList<Long>(); private transient ItemStack[] inventoryCopy = null; private transient ItemStack[] armorCopy = null; private transient UUID selectedPet = null; private SaveablePlayer whisperer = null; private int powertoolID = 0; private transient String powertoolCmd = ""; private Clan clan = null; private int bounty = 0; private int money = 0; private PlayerRank rank = PlayerRank.DEFAULT; private transient long vipTime = 0; private transient int vipSpawns = 0; private long jailTime = 0; private long jailSentence = 0; private transient int bail = 0; /** * Initialise a brand new player extension. * @param player Player to connect to this extension. */ public SaveablePlayer(final Player player) { base = player; nick = player.getName(); name = player.getName(); } /** * Initialise an extended player from a string record. * @param record A line from a save file. */ public SaveablePlayer(final String record) { final String[] recordSplit = record.split("\t"); name = recordSplit[0]; bounty = Integer.parseInt(recordSplit[1]); money = Integer.parseInt(recordSplit[2]); rank = PlayerRank.getByName(recordSplit[3]); vipTime = Long.parseLong(recordSplit[4]); vipSpawns = Integer.parseInt(recordSplit[5]); jailTime = Long.parseLong(recordSplit[6]); jailSentence = Long.parseLong(recordSplit[7]); bail = Integer.parseInt(recordSplit[8]); nick = recordSplit[9]; timeLogged = Long.parseLong(recordSplit[10]); } @Override public String getRecord() { final List<String> record = new ArrayList<String>(); record.add(name); record.add(Integer.toString(bounty)); record.add(Integer.toString(money)); record.add(rank.toString()); record.add(Long.toString(vipTime)); record.add(Integer.toString(vipSpawns)); record.add(Long.toString(jailTime)); record.add(Long.toString(jailSentence)); record.add(Integer.toString(bail)); record.add(nick); record.add(Long.toString(timeLogged)); return StringUtils.join(record.toArray(), "\t"); } @Override public String toString() { Bukkit.getLogger().info("Implicit Player.toString()."); // Implicit .toString() return name; } /** * Warp an existing player with these extensions. * @param player Player to wrap. */ public void wrapPlayer(final Player player) { base = player; player.setDisplayName(nick); } /** * Increment logged time. * @param time Time to add. */ public void addTime(final long time) { timeLogged += time; } /** * Toggle this players lockdown pass. */ public void toggleLockdownPass() { lockdownPass ^= true; } /** * Get this players selected pet. * @return Pet UUID. */ public UUID getSelectedPet() { return selectedPet; } /** * Set this players selected pet. * @param id Pet UUID */ public void selectPet(final UUID id) { selectedPet = id; } /** * Set the player that this player is whispering with. * @param player Player whispering. */ public void setWhisperer(final SaveablePlayer player) { whisperer = player; } /** * Get this players duel wager. * @return Duel wager. */ public int getWager() { return wager; } /** * Check if this player is wearing scuba gear. * @return <code>true</code> if the player is wearing scuba gear, <code>false</code> otherwise. */ public boolean hasScuba() { return base == null ? false : base.getInventory().getHelmet().getType().equals(Material.GLASS); } /** * Set the player that this player is whispering with. * @return Player whispering. */ public SaveablePlayer getWhisperer() { return whisperer; } /** * * @param search * @return */ public int countItems(final ItemStack search) { if(base == null) { return 0; } else { final ItemStack[] inventory = base.getInventory().getContents(); int count = 0; for(int i = 0; i < inventory.length; i++) { final ItemStack item = inventory[i]; if(item != null && item.getType() == search.getType() && item.getData().getData() == search.getData().getData()) { count += item.getAmount(); } } return count; } } /** * * @return */ public int getPowertoolID() { return powertoolID; } /** * * @return */ public String getPowertool() { return powertoolCmd; } /** * */ public void claimPrize() { prizeClaim = System.currentTimeMillis(); } /** * * @return */ public boolean hasClaimedPrize() { return (prizeClaim + Timer.DAY > System.currentTimeMillis()); } /** * * @return */ public WESession forceSession() { WESession session = UDSPlugin.getSessions().get(getName()); if(session == null) { session = new WESession(); UDSPlugin.getSessions().put(getName(), session); } return session; } /** * * @param ID */ public void setPowertoolID(final int ID) { powertoolID = ID; } /** * * @param cmd */ public void setPowertool(final String cmd) { powertoolCmd = cmd; } /** * * @return */ public Player getBase() { return base; } /** * Sets the base player reference to <code>null</code>. */ public void nullBase() { base = null; } /** * Get the players saved inventory. * @return The players saved inventory, <code>null</code> if none exists. */ public ItemStack[] getInventoryCopy() { return inventoryCopy.clone(); } /** * * @param location * @return */ public boolean isInShop(final Location location) { for(Region region : UDSPlugin.getShops().values()) { if(location.toVector().isInAABB(region.getV1(), region.getV2())) { return true; } } return false; } /** * * @param clan */ public void setClan(final Clan clan) { this.clan = clan; } /** * Save this players inventory for later retrieval. */ public void saveInventory() { if(base != null) { inventoryCopy = base.getInventory().getContents(); } } /** * */ public void saveItems() { saveInventory(); saveArmor(); } /** * Load this players armor. */ public void loadArmor() { if(base != null) { base.getInventory().setArmorContents(armorCopy); armorCopy = new ItemStack[0]; } } /** * */ public void endChallenge() { wager = 0; challenger = null; } /** * Load this players inventory. */ public void loadInventory() { if(base != null) { base.getInventory().setContents(inventoryCopy); inventoryCopy = new ItemStack[0]; } } /** * Save this players armor for later retrieval. */ public void saveArmor() { if(base != null) { armorCopy = base.getInventory().getArmorContents(); } } /** * Get this players bail. * @return This players bail. */ public int getBail() { return bail; } /** * */ public void loadItems() { loadInventory(); loadArmor(); } /** * Update the chat times with a new value. * @return <code>true</code> if chat events are not occurring too frequently, <code>false</code> otherwise. */ public boolean newChat() { if(lastChats.size() > 5) { lastChats.removeFirst(); } lastChats.offerLast(System.currentTimeMillis()); if(lastChats.size() == 5 && lastChats.getLast() - lastChats.getFirst() < 3000) { return false; } return true; } /** * * @return */ public String getTimeLogged() { return timeToString(timeLogged); } /** * * @return */ public String getLastSeen() { if(base == null) { final OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(name); if(offlinePlayer == null) { return "Unknown"; } else { return timeToString(System.currentTimeMillis() - Bukkit.getOfflinePlayer(name).getLastPlayed()); } } else { return timeToString(System.currentTimeMillis() - base.getLastPlayed()); } } /** * Construct an English reading string of the remaining VIP time. * @return English reading string. */ public String getVIPTimeString() { return timeToString(Config.vipTime - System.currentTimeMillis() - getVIPTime()); } /** * * @param time * @return */ public String timeToString(final long time) { long timeRemaining = time; String timeString = ""; if(timeRemaining >= Timer.DAY) { final int days = (int)(timeRemaining / Timer.DAY); - timeString = timeString.concat(days + (days == 1 ? " day" : " days ")); + timeString = timeString.concat(days + (days == 1 ? " day " : " days ")); timeRemaining -= days * Timer.DAY; } if(timeRemaining >= Timer.HOUR) { final int hours = (int)(timeRemaining / Timer.HOUR); - timeString = timeString.concat(hours + (hours == 1 ? " hour" : " hours ")); + timeString = timeString.concat(hours + (hours == 1 ? " hour " : " hours ")); timeRemaining -= hours * Timer.HOUR; } if(timeRemaining >= Timer.MINUTE) { final int minutes = (int)(timeRemaining / Timer.MINUTE); - timeString = timeString.concat(minutes + (minutes == 1 ? " minute" : " minutes ")); + timeString = timeString.concat(minutes + (minutes == 1 ? " minute " : " minutes ")); timeRemaining -= minutes * Timer.MINUTE; } if(timeRemaining >= Timer.SECOND) { final int seconds = (int)(timeRemaining / Timer.SECOND); - timeString = timeString.concat(seconds + (seconds == 1 ? " second" : " seconds ")); + timeString = timeString.concat(seconds + (seconds == 1 ? " second " : " seconds ")); timeRemaining -= seconds * Timer.SECOND; } return timeString; } /** * Use up some the players VIP daily item spawns. * @param amount The amount of spawns to use up. * @return The number of spawns remaining. */ public int useVIPSpawns(final int amount) { vipSpawns -= amount; return vipSpawns; } /** * Set the players back warp point to their current location. */ public void setBackPoint() { if(base != null) { back = base.getLocation(); } } /** * * @param location */ public void setBackPoint(final Location location) { back = location; } /** * Toggle this players game mode. * @return <code>true</code> if the players game mode is now set to creative, <code>false</code> otherwise. */ public boolean toggleGameMode() { if(base == null) { return false; } else { if(base.getGameMode().equals(GameMode.SURVIVAL)) { base.setGameMode(GameMode.CREATIVE); return true; } else { base.setGameMode(GameMode.SURVIVAL); return false; } } } /** * Get a players monetary value. * @return A players monetary value. */ public int getMoney() { return money; } /** * Get the chat room this player is currently in. * @return The players chat room. */ public ChatRoom getChatRoom() { return chatRoom; } /** * Take a player out of jail and perform all the necessary operations. */ public void release() { jailTime = 0; jailSentence = 0; if(!quietTeleport(UDSPlugin.getWarps().get("jailout"))) { BufferedWriter out; try { out = new BufferedWriter(new FileWriter(UDSPlugin.TICKET_PATH, true)); out.write("No jail out warp point has been placed. Use '/setwarp jailout' to do this."); out.close(); } catch (IOException ex) { Logger.getLogger(SaveablePlayer.class.getName()).log(Level.SEVERE, null, ex); } } } /** * Put a player in jail and perform all the necessary operations. * @param sentence Time in minutes to jail the player. * @param bail Bail to set. * @throws IOException */ public void jail(final long sentence, final int bail) { if(base != null) { base.getWorld().strikeLightningEffect(base.getLocation()); quietTeleport(UDSPlugin.getWarps().get("jailin")); jailTime = System.currentTimeMillis(); jailSentence = sentence * Timer.MINUTE; this.bail = bail; base.sendMessage(Color.MESSAGE + "You have been jailed for " + sentence + " minutes."); if(bail != 0) { base.sendMessage(Color.MESSAGE + "If you can afford it, use /paybail to get out early for " + bail + " " + Config.currencies + "."); } } } /** * Get the first region that the player is currently inside. * @param type Optional type of region to check, <code>null</code> to search all regions. * @return The first region the player is in, <code>null</code> otherwise. */ public Region getCurrentRegion(final RegionType type) { if(base != null) { if(type == Region.RegionType.CITY) { for(Region region : UDSPlugin.getCities().values()) { if(base.getLocation().toVector().isInAABB(region.getV1(), region.getV2())) { return region; } } } else if(type == Region.RegionType.SHOP) { for(Region region : UDSPlugin.getShops().values()) { if(base.getLocation().toVector().isInAABB(region.getV1(), region.getV2())) { return region; } } } } return null; } /** * Demote a player. * @return Players new rank, <code>null</code> if no change. */ public PlayerRank demote() { final PlayerRank newRank = PlayerRank.getBelow(rank); if(newRank != null) { rank = newRank; } return newRank; } /** * Promote a player. * @return Players new rank, <code>null</code> if no change. */ public PlayerRank promote() { final PlayerRank newRank = PlayerRank.getAbove(rank); if(newRank != null) { rank = newRank; } return newRank; } /** * Get the players current chat channel. * @return The players chat channel. */ public Channel getChannel() { return channel; } /** * Get this players saved checkpoint. * @return This players checkpoint. */ public Location getCheckPoint() { return checkPoint; } /** * * @param location */ public void setCheckPoint(final Location location) { checkPoint = location; } /** * Check if a player is engaged in a duel with another player. * @return <code>true</code> if the player is engaged in a duel, <code>false</code> otherwise. */ public boolean isDuelling() { return challenger != null; } /** * * @param challenger */ public void setChallenger(final SaveablePlayer challenger) { this.challenger = challenger; } /** * * @return */ public SaveablePlayer getChallenger() { return challenger; } /** * Check if a player can build in a given location. * @param location * @return */ public boolean canBuildHere(final Location location) { boolean contained = false; for(Region region : UDSPlugin.getRegions().values()) { if(location.toVector().isInAABB(region.getV1(), region.getV2())) { if(((region.getRank() != null && rank.compareTo(region.getRank()) >= 0)) || region.isOwner(this) || region.hasMember(this)) { return true; } contained = true; } } return !contained; } /** * Give a player an item stack, any items that don't fit in the inventory are dropped at the players feet. * @param item Item to give the player. */ public void giveAndDrop(final ItemStack item) { if(base != null) { final Map<Integer, ItemStack> drops = base.getInventory().addItem(item); for(ItemStack drop : drops.values()) { base.getWorld().dropItemNaturally(base.getLocation(), drop); } } } /** * Add a player to a list of players this player is ignoring. * @param player Player to ignore. * @return <code>true</code> if this player was not already being ignored, <code>false</code> otherwise. */ public boolean ignorePlayer(final SaveablePlayer player) { return ignoredPlayers.add(player); } /** * Remove a player from a list of players this player is ignoring. * @param player Player to stop ignoring. * @return <code>true</code> if this player was being ignored, <code>false</code> otherwise. */ public boolean unignorePlayer(final SaveablePlayer player) { return ignoredPlayers.remove(player); } /** * Check to see if this player is ignoring a player. * @param player Player to check. * @return <code>true</code> if this player is ignoring that player, <code>false</code> otherwise. */ public boolean isIgnoringPlayer(final SaveablePlayer player) { return ignoredPlayers.contains(player); } /** * Get the last time this player caused damage to another player. * @return The last time this player did damage to another player. */ public long getLastDamageCaused() { return lastDamageCaused; } /** * Set the last time this player caused damage to another player to now. */ public void setLastDamageCaused() { lastDamageCaused = System.currentTimeMillis(); } /** * Get this players total bounty. * @return Players bounty. */ public int getBounty() { return bounty; } /** * Set the bounty on a player. * @param bounty Bounty to set. */ public void setBounty(final int bounty) { this.bounty = bounty; } /** * Add a bounty to this player. * @param bounty New bounty. */ public void addBounty(final int bounty) { this.bounty += bounty; } /** * Get the last recorded location of the player. * @return The last recorded location of the player. */ public Location getBack() { return back; } /** * Get a player current rank. * @return Player rank. */ public PlayerRank getRank() { return rank; } /** * Set the player rank. * @param rank The rank to set. */ public void setRank(final PlayerRank rank) { this.rank = rank; } /** * Check to see if a player belongs to a clan. * @return <code>true</code> if a player is in a clan, <code>false</code> otherwise. */ public boolean isInClan() { return clan != null; } /** * Teleport to the point indicated by a warp. * @param warp Warp to teleport to. */ public void teleport(final Warp warp) { if(base != null) { base.teleport(warp.getLocation()); } } /** * Get the name of the clan the player is a member of. * @return Clan name. */ public Clan getClan() { return clan; } /** * Storage of nick name kept in extension for offline access. * @return Player nick name. */ public String getNick() { return nick; } /** * Toggle the players chat channel. * @param channel Channel to toggle. * @return <code>true</code> if channel was toggled on, <code>false</code> if channel switched back to public. */ public boolean toggleChannel(final Channel channel) { if(this.channel.equals(channel)) { this.channel = Channel.PUBLIC; return false; } else { this.channel = channel; return true; } } /** * Check whether this player has a lockdown pass. * @return Has player got lockdown pass. */ public boolean hasLockdownPass() { return lockdownPass; } /** * Get the time when this player rented VIP status. * @return When VIP was rented. */ public long getVIPTime() { return vipTime; } /** * Set when a player rented VIP status. * @param time Time to set. */ public void setVIPTime(final long time) { vipTime = time; } /** * Get the number of free item spawns this player has left. * @return Number of spawns left. */ public int getVIPSpawns() { return vipSpawns; } /** * Set the number of free VIP item spawns a player has remaining. * @param spawns Number of spawns to set. */ public void setVIPSpawns(final int spawns) { vipSpawns = spawns; } /** * Get the time that this player was put in jail. * @return Players jail time. */ public long getJailTime() { return jailTime; } /** * Set when a player was put in jail. * @param time Jail time. */ public void setJailTime(final long time) { jailTime = time; } /** * Get how long this player was sentenced to jail for. * @return Players sentence. */ public long getJailSentence() { return jailSentence; } /** * Set the length of a players jail sentence. * @param sentence Length of sentence. */ public void setJailSentence(final long sentence) { jailSentence = sentence; } /** * Check if a player is currently in jail. * @return <code>true</code> if a player is in jail, <code>false</code> otherwise. */ public boolean isJailed() { return (jailTime > 0); } /** * Check if a player currently has god mode enabled. * @return God mode setting. */ public boolean hasGodMode() { return godMode; } /** * Toggle a players god mode. * @return Players current god mode setting. */ public boolean toggleGodMode() { godMode ^= true; return godMode; } /** * Set a players god mode. * @param mode God mode setting. */ public void setGodMode(final boolean mode) { godMode = mode; } /** * Send a message in a particular channel. * @param channel Channel to send message in. * @param message Message to send. */ public void chat(final Channel channel, final String message) { if(base != null) { final Channel temp = this.channel; this.channel = channel; base.chat(message); this.channel = temp; } } /** * Check if a player can afford to pay some value. * @param price Price to pay. * @return <code>true</code> if player has enough money, <code>false</code> otherwise. */ public boolean canAfford(final int price) { return (money >= price); } /** * * @param wager */ public void setWager(final int wager) { this.wager = wager; } /** * Debit the players account the amount passed. * @param amount Amount to debit. */ public void debit(final int amount) { money -= amount; } /** * Credit the players account the amount passed. * @param amount Amount to credit. */ public void credit(final int amount) { money += amount; } /** * Set a players account. * @param amount Amount to set. */ public void setMoney(final int amount) { money = amount; } /** * Check if a player has a rank. * @param rank Rank to check. * @return <code>true</code> if player has rank, <code>false</code> otherwise. */ public boolean hasRank(final PlayerRank rank) { return this.rank.compareTo(rank) >= 0; } /** * Teleport a player but reserve pitch and yaw of player. * @param location Location to teleport to. */ public void move(final Location location) { if(base != null) { final Location destination = location; destination.setPitch(base.getLocation().getPitch()); destination.setYaw(base.getLocation().getYaw()); base.teleport(destination); } } /** * Teleport a player but fail quietly if location is <code>null</code>. * @param location Location to teleport player to. * @return <code>true</code> if location is not <code>null</code>, <code>false</code> otherwise. */ public boolean quietTeleport(final Location location) { if(location == null) { return false; } else { if(base != null) { base.teleport(location); } return true; } } /** * Teleport a player but fail quietly if warp or location are <code>null</code>. * @param warp Warp to teleport player to. * @return <code>true</code> if warp and location are not <code>null</code>, <code>false</code> otherwise. */ public boolean quietTeleport(final Warp warp) { if(warp == null) { return false; } else { if(base == null) { return warp.getLocation() != null; } else { return base.teleport(warp.getLocation()); } } } /** * Check if this player has a permission. * @param perm The permission to check. * @return <code>true</code> if the player has the permission, <code>false</code> otherwise. */ public boolean hasPermission(final Perm perm) { if(perm.isHereditary()) { return perm.getRank().compareTo(rank) <= 0; } else { return perm.getRank().equals(rank); } } /** * * @param name */ public void setDisplayName(final String name) { nick = name; } /** * * @return */ public String getName() { return base == null ? name : base.getName(); } /** * * @param message */ public void sendMessage(final String message) { if(base != null) { base.sendMessage(message); } } /** * * @return */ public boolean isOnline() { return base == null ? false : base.isOnline(); } /** * * @param level */ public void setFoodLevel(final int level) { if(base != null) { base.setFoodLevel(level); } } /** * * @return */ public Location getLocation() { return base == null ? null : base.getLocation(); } /** * * @return */ public World getWorld() { return base == null ? null : base.getWorld(); } /** * * @return */ public long getLastPlayed() { return base == null ? Bukkit.getOfflinePlayer(name).getLastPlayed() : base.getLastPlayed(); } /** * * @param message */ public void kickPlayer(final String message) { if(base != null) { base.kickPlayer(message); } } /** * * @param banned */ public void setBanned(final boolean banned) { if(base == null) { Bukkit.getOfflinePlayer(name).setBanned(banned); } else { base.setBanned(banned); } } /** * * @return */ public boolean isBanned() { return base == null ? Bukkit.getOfflinePlayer(name).isBanned() : base.isBanned(); } /** * * @return */ public PlayerInventory getInventory() { return base == null ? null : base.getInventory(); } /** * * @param location * @return */ public boolean teleport(final Location location) { return base == null? false : base.teleport(location); } /** * * @return */ public ItemStack getItemInHand() { return base == null ? null : base.getItemInHand(); } /** * * @param command * @return */ public boolean performCommand(final String command) { return base == null ? false : base.performCommand(command); } /** * * @return */ public boolean isOp() { return base == null ? false : base.isOp(); } /** * * @return */ public boolean isSneaking() { return base == null ? false : base.isSneaking(); } /** * * @param item */ public void setItemInHand(final ItemStack item) { if(base != null) { base.setItemInHand(item); } } /** * * @param transparent * @param range * @return */ public Block getTargetBlock(final HashSet<Byte> transparent, final int range) { return base == null ? null : base.getTargetBlock(transparent, range); } /** * * @param transparent * @param range * @return */ public List<Block> getLastTwoTargetBlocks(final HashSet<Byte> transparent, final int range) { return base == null ? null : base.getLastTwoTargetBlocks(transparent, range); } /** * * @return */ public Player getKiller() { return base == null ? null : base.getKiller(); } /** * * @return */ public GameMode getGameMode() { return base == null ? null : base.getGameMode(); } /** * */ @SuppressWarnings("deprecation") public void updateInventory() { if(base != null) { base.updateInventory(); } } /** * * @param player */ public void teleport(final SaveablePlayer player) { if(base != null) { base.teleport(player.getBase()); } } /** * * @param entity */ public void teleportHere(final Entity entity) { if(base != null) { entity.teleport(base); } } /** * * @param pet */ public void setPet(final Tameable pet) { if(base != null) { pet.setOwner(base); } } /** * * @param levels */ public void giveExpLevels(final int levels) { if(base != null) { base.giveExpLevels(levels); } } /** * * @param exp */ public void setExp(final int exp) { if(base != null) { base.setExp(exp); } } /** * * @param level */ public void setLevel(final int level) { if(base != null) { base.setLevel(level); } } /** * * @return */ public int getLevel() { return base == null ? 0 : base.getLevel(); } /** * * @return */ public int getMaxHealth() { return base == null ? 0 : base.getMaxHealth(); } /** * * @param health */ public void setHealth(final int health) { if(base != null) { base.setHealth(health); } } }
false
true
public String timeToString(final long time) { long timeRemaining = time; String timeString = ""; if(timeRemaining >= Timer.DAY) { final int days = (int)(timeRemaining / Timer.DAY); timeString = timeString.concat(days + (days == 1 ? " day" : " days ")); timeRemaining -= days * Timer.DAY; } if(timeRemaining >= Timer.HOUR) { final int hours = (int)(timeRemaining / Timer.HOUR); timeString = timeString.concat(hours + (hours == 1 ? " hour" : " hours ")); timeRemaining -= hours * Timer.HOUR; } if(timeRemaining >= Timer.MINUTE) { final int minutes = (int)(timeRemaining / Timer.MINUTE); timeString = timeString.concat(minutes + (minutes == 1 ? " minute" : " minutes ")); timeRemaining -= minutes * Timer.MINUTE; } if(timeRemaining >= Timer.SECOND) { final int seconds = (int)(timeRemaining / Timer.SECOND); timeString = timeString.concat(seconds + (seconds == 1 ? " second" : " seconds ")); timeRemaining -= seconds * Timer.SECOND; } return timeString; }
public String timeToString(final long time) { long timeRemaining = time; String timeString = ""; if(timeRemaining >= Timer.DAY) { final int days = (int)(timeRemaining / Timer.DAY); timeString = timeString.concat(days + (days == 1 ? " day " : " days ")); timeRemaining -= days * Timer.DAY; } if(timeRemaining >= Timer.HOUR) { final int hours = (int)(timeRemaining / Timer.HOUR); timeString = timeString.concat(hours + (hours == 1 ? " hour " : " hours ")); timeRemaining -= hours * Timer.HOUR; } if(timeRemaining >= Timer.MINUTE) { final int minutes = (int)(timeRemaining / Timer.MINUTE); timeString = timeString.concat(minutes + (minutes == 1 ? " minute " : " minutes ")); timeRemaining -= minutes * Timer.MINUTE; } if(timeRemaining >= Timer.SECOND) { final int seconds = (int)(timeRemaining / Timer.SECOND); timeString = timeString.concat(seconds + (seconds == 1 ? " second " : " seconds ")); timeRemaining -= seconds * Timer.SECOND; } return timeString; }
diff --git a/core/pog-string-based/src/main/java/org/overture/pog/visitor/PogParamDefinitionVisitor.java b/core/pog-string-based/src/main/java/org/overture/pog/visitor/PogParamDefinitionVisitor.java index 0e6b9ffbfc..e419834d83 100644 --- a/core/pog-string-based/src/main/java/org/overture/pog/visitor/PogParamDefinitionVisitor.java +++ b/core/pog-string-based/src/main/java/org/overture/pog/visitor/PogParamDefinitionVisitor.java @@ -1,684 +1,684 @@ package org.overture.pog.visitor; import java.util.LinkedList; import java.util.List; import org.overture.ast.analysis.AnalysisException; import org.overture.ast.analysis.QuestionAnswerAdaptor; import org.overture.ast.definitions.AAssignmentDefinition; import org.overture.ast.definitions.AClassClassDefinition; import org.overture.ast.definitions.AClassInvariantDefinition; import org.overture.ast.definitions.AEqualsDefinition; import org.overture.ast.definitions.AExplicitFunctionDefinition; import org.overture.ast.definitions.AExplicitOperationDefinition; import org.overture.ast.definitions.AImplicitFunctionDefinition; import org.overture.ast.definitions.AImplicitOperationDefinition; import org.overture.ast.definitions.AInstanceVariableDefinition; import org.overture.ast.definitions.APerSyncDefinition; import org.overture.ast.definitions.AStateDefinition; import org.overture.ast.definitions.ATypeDefinition; import org.overture.ast.definitions.AValueDefinition; import org.overture.ast.definitions.PDefinition; import org.overture.ast.definitions.SClassDefinition; import org.overture.ast.definitions.traces.PTraceCoreDefinition; import org.overture.ast.definitions.traces.PTraceDefinition; import org.overture.ast.expressions.PExp; import org.overture.ast.lex.LexNameList; import org.overture.ast.node.INode; import org.overture.ast.patterns.AIdentifierPattern; import org.overture.ast.patterns.AIgnorePattern; import org.overture.ast.patterns.APatternListTypePair; import org.overture.ast.patterns.PPattern; import org.overture.ast.types.AOperationType; import org.overture.ast.types.AUnionType; import org.overture.ast.types.PType; import org.overture.ast.util.PTypeSet; import org.overture.pog.obligation.FuncPostConditionObligation; import org.overture.pog.obligation.OperationPostConditionObligation; import org.overture.pog.obligation.POContextStack; import org.overture.pog.obligation.POFunctionDefinitionContext; import org.overture.pog.obligation.POFunctionResultContext; import org.overture.pog.obligation.PONameContext; import org.overture.pog.obligation.POOperationDefinitionContext; import org.overture.pog.obligation.ParameterPatternObligation; import org.overture.pog.obligation.ProofObligationList; import org.overture.pog.obligation.SatisfiabilityObligation; import org.overture.pog.obligation.StateInvariantObligation; import org.overture.pog.obligation.SubTypeObligation; import org.overture.pog.obligation.ValueBindingObligation; import org.overture.pog.util.POException; import org.overture.typechecker.TypeComparator; import org.overture.typechecker.assistant.definition.PDefinitionAssistantTC; import org.overture.typechecker.assistant.pattern.PPatternAssistantTC; import org.overture.typechecker.assistant.pattern.PPatternListAssistantTC; import org.overture.typechecker.assistant.type.PTypeAssistantTC; public class PogParamDefinitionVisitor<Q extends POContextStack, A extends ProofObligationList> extends QuestionAnswerAdaptor<POContextStack, ProofObligationList> { /** * */ private static final long serialVersionUID = -3086193431700309588L; final private QuestionAnswerAdaptor<POContextStack, ProofObligationList> rootVisitor; final private QuestionAnswerAdaptor<POContextStack, ProofObligationList> mainVisitor; public PogParamDefinitionVisitor( QuestionAnswerAdaptor<POContextStack, ProofObligationList> parentVisitor, QuestionAnswerAdaptor<POContextStack, ProofObligationList> mainVisitor) { this.rootVisitor = parentVisitor; this.mainVisitor = mainVisitor; } public PogParamDefinitionVisitor( QuestionAnswerAdaptor<POContextStack, ProofObligationList> parentVisitor) { this.rootVisitor = parentVisitor; this.mainVisitor = this; } @Override // from [1] pg. 35 we have an: // explicit function definition = identifier, // [ type variable list ], �:�, function type, // identifier, parameters list, �==�, // function body, // [ �pre�, expression ], // [ �post�, expression ], // [ �measure�, name ] ; public ProofObligationList caseAExplicitFunctionDefinition( AExplicitFunctionDefinition node, POContextStack question) throws AnalysisException { try { ProofObligationList obligations = new ProofObligationList(); LexNameList pids = new LexNameList(); boolean matchNeeded = false; // add all defined names from the function parameter list for (List<PPattern> patterns : node.getParamPatternList()) { for (PPattern p : patterns) for (PDefinition def : p.getDefinitions()) pids.add(def.getName()); if (!PPatternListAssistantTC.alwaysMatches(patterns)) { matchNeeded = true; } } // check for duplicates if (pids.hasDuplicates() || matchNeeded) { obligations.add(new ParameterPatternObligation(node, question)); } // do proof obligations for the pre-condition PExp precondition = node.getPrecondition(); if (precondition != null) { question.push(new POFunctionDefinitionContext(node, false)); obligations.addAll(precondition.apply(rootVisitor, question)); question.pop(); } // do proof obligations for the post-condition PExp postcondition = node.getPostcondition(); if (postcondition != null) { question.push(new POFunctionDefinitionContext(node, false)); obligations.add(new FuncPostConditionObligation(node, question)); question.push(new POFunctionResultContext(node)); obligations.addAll(postcondition.apply(rootVisitor, question)); question.pop(); question.pop(); } // do proof obligations for the function body question.push(new POFunctionDefinitionContext(node, true)); PExp body = node.getBody(); int sizeBefore = question.size(); obligations.addAll(body.apply(rootVisitor, question)); assert sizeBefore <= question.size(); // do proof obligation for the return type if (node.getIsUndefined() || !TypeComparator.isSubType(node.getActualResult(), node.getExpectedResult())) { obligations.add(new SubTypeObligation(node, node.getExpectedResult(), node.getActualResult(), question)); } question.pop(); return obligations; } catch (Exception e) { throw new POException(node, e); } } @Override public ProofObligationList defaultSClassDefinition(SClassDefinition node, POContextStack question) throws AnalysisException { try { ProofObligationList proofObligationList = new ProofObligationList(); for (PDefinition def : node.getDefinitions()) { proofObligationList.addAll(def.apply(mainVisitor, question)); } return proofObligationList; } catch (Exception e) { throw new POException(node, e); } } @Override public ProofObligationList caseAClassInvariantDefinition( AClassInvariantDefinition node, POContextStack question) throws AnalysisException { try { ProofObligationList list = new ProofObligationList(); if (!node.getClassDefinition().getHasContructors()) { list.add(new StateInvariantObligation(node, question)); } return list; } catch (Exception e) { throw new POException(node, e); } } @Override public ProofObligationList caseAEqualsDefinition(AEqualsDefinition node, POContextStack question) throws AnalysisException { try { ProofObligationList list = new ProofObligationList(); PPattern pattern = node.getPattern(); if (pattern != null) { if (!(pattern instanceof AIdentifierPattern) && !(pattern instanceof AIgnorePattern) && node.getExpType() instanceof AUnionType) { PType patternType = PPatternAssistantTC.getPossibleType(pattern); // With unknowns AUnionType ut = (AUnionType) node.getExpType(); PTypeSet set = new PTypeSet(); for (PType u : ut.getTypes()) { if (TypeComparator.compatible(u, patternType)) { set.add(u); } } if (!set.isEmpty()) { PType compatible = set.getType(node.getLocation()); if (!TypeComparator.isSubType(question.checkType(node.getTest(), node.getExpType()), compatible)) { list.add(new ValueBindingObligation(node, question)); list.add(new SubTypeObligation(node.getTest(), compatible, node.getExpType(), question)); } } } } else if (node.getTypebind() != null) { if (!TypeComparator.isSubType(question.checkType(node.getTest(), node.getExpType()), node.getDefType())) { list.add(new SubTypeObligation(node.getTest(), node.getDefType(), node.getExpType(), question)); } } else if (node.getSetbind() != null) { list.addAll(node.getSetbind().getSet().apply(rootVisitor, question)); } list.addAll(node.getTest().apply(rootVisitor, question)); return list; } catch (Exception e) { throw new POException(node, e); } } @Override public ProofObligationList caseAImplicitFunctionDefinition( AImplicitFunctionDefinition node, POContextStack question) throws AnalysisException { try { ProofObligationList obligations = new ProofObligationList(); LexNameList pids = new LexNameList(); boolean matchNeeded = false; for (APatternListTypePair pltp : node.getParamPatterns()) { for (PPattern p : pltp.getPatterns()) { for (PDefinition def : p.getDefinitions()) pids.add(def.getName()); } if (!PPatternListAssistantTC.alwaysMatches(pltp.getPatterns())) { matchNeeded = true; } } if (pids.hasDuplicates() || matchNeeded) { obligations.add(new ParameterPatternObligation(node, question)); } if (node.getPrecondition() != null) { obligations.addAll(node.getPrecondition().apply(rootVisitor, question)); } if (node.getPostcondition() != null) { if (node.getBody() != null) // else satisfiability, below { question.push(new POFunctionDefinitionContext(node, false)); obligations.add(new FuncPostConditionObligation(node, question)); question.pop(); } question.push(new POFunctionResultContext(node)); obligations.addAll(node.getPostcondition().apply(rootVisitor, question)); question.pop(); } if (node.getBody() == null) { if (node.getPostcondition() != null) { question.push(new POFunctionDefinitionContext(node, false)); obligations.add(new SatisfiabilityObligation(node, question)); question.pop(); } } else { question.push(new POFunctionDefinitionContext(node, true)); obligations.addAll(node.getBody().apply(rootVisitor, question)); if (node.getIsUndefined() - || !TypeComparator.isSubType(node.getActualResult(), ((AOperationType) node.getType()).getResult())) + || !TypeComparator.isSubType(node.getActualResult(), node.getType().getResult())) { - obligations.add(new SubTypeObligation(node, ((AOperationType) node.getType()).getResult(), node.getActualResult(), question)); + obligations.add(new SubTypeObligation(node, node.getType().getResult(), node.getActualResult(), question)); } question.pop(); } return obligations; } catch (Exception e) { throw new POException(node, e); } } @Override public ProofObligationList caseAExplicitOperationDefinition( AExplicitOperationDefinition node, POContextStack question) throws AnalysisException { try { ProofObligationList obligations = new ProofObligationList(); LexNameList pids = new LexNameList(); // add all defined names from the function parameter list for (PPattern p : node.getParameterPatterns()) for (PDefinition def : p.getDefinitions()) pids.add(def.getName()); if (pids.hasDuplicates() || !PPatternListAssistantTC.alwaysMatches(node.getParameterPatterns())) { obligations.add(new ParameterPatternObligation(node, question)); } if (node.getPrecondition() != null) { obligations.addAll(node.getPrecondition().apply(rootVisitor, question)); } if (node.getPostcondition() != null) { obligations.addAll(node.getPostcondition().apply(rootVisitor, question)); obligations.add(new OperationPostConditionObligation(node, question)); } obligations.addAll(node.getBody().apply(rootVisitor, question)); if (node.getIsConstructor() && node.getClassDefinition() != null && node.getClassDefinition().getInvariant() != null) { obligations.add(new StateInvariantObligation(node, question)); } if (!node.getIsConstructor() && !TypeComparator.isSubType(node.getActualResult(), ((AOperationType) node.getType()).getResult())) { obligations.add(new SubTypeObligation(node, node.getActualResult(), question)); } return obligations; } catch (Exception e) { throw new POException(node, e); } } @Override public ProofObligationList caseAImplicitOperationDefinition( AImplicitOperationDefinition node, POContextStack question) throws AnalysisException { try { ProofObligationList obligations = new ProofObligationList(); LexNameList pids = new LexNameList(); LinkedList<APatternListTypePair> plist = node.getParameterPatterns(); LinkedList<PPattern> tmpPatterns = new LinkedList<PPattern>(); for (APatternListTypePair tp : plist) { for (PPattern p : tp.getPatterns()) { tmpPatterns.add(p); for (PDefinition def : p.getDefinitions()) pids.add(def.getName()); } } if (pids.hasDuplicates() || !PPatternListAssistantTC.alwaysMatches(tmpPatterns)) { obligations.add(new ParameterPatternObligation(node, question)); } if (node.getPrecondition() != null) { obligations.addAll(node.getPrecondition().apply(rootVisitor, question)); } if (node.getPostcondition() != null) { obligations.addAll(node.getPostcondition().apply(rootVisitor, question)); obligations.add(new OperationPostConditionObligation(node, question)); } if (node.getBody() != null) { obligations.addAll(node.getBody().apply(rootVisitor, question)); if (node.getIsConstructor() && node.getClassDefinition() != null && node.getClassDefinition().getInvariant() != null) { obligations.add(new StateInvariantObligation(node, question)); } if (!node.getIsConstructor() && !TypeComparator.isSubType(node.getActualResult(), ((AOperationType) node.getType()).getResult())) { obligations.add(new SubTypeObligation(node, node.getActualResult(), question)); } } else { if (node.getPostcondition() != null) { question.push(new POOperationDefinitionContext(node, false, node.getStateDefinition())); obligations.add(new SatisfiabilityObligation(node, node.getStateDefinition(), question)); question.pop(); } } return obligations; } catch (Exception e) { throw new POException(node, e); } } @Override public ProofObligationList caseAAssignmentDefinition( AAssignmentDefinition node, POContextStack question) throws AnalysisException { try { ProofObligationList obligations = new ProofObligationList(); PExp expression = node.getExpression(); PType type = node.getType(); PType expType = node.getExpType(); obligations.addAll(expression.apply(rootVisitor, question)); if (!TypeComparator.isSubType(question.checkType(expression, expType), type)) { obligations.add(new SubTypeObligation(expression, type, expType, question)); } return obligations; } catch (Exception e) { throw new POException(node, e); } } @Override public ProofObligationList defaultPDefinition(PDefinition node, POContextStack question) { return new ProofObligationList(); } public ProofObligationList caseAInstanceVariableDefinition( AInstanceVariableDefinition node, POContextStack question) throws AnalysisException { try { ProofObligationList obligations = new ProofObligationList(); PExp expression = node.getExpression(); PType type = node.getType(); PType expType = node.getExpType(); obligations.addAll(expression.apply(rootVisitor, question)); if (!TypeComparator.isSubType(question.checkType(expression, expType), type)) { obligations.add(new SubTypeObligation(expression, type, expType, question)); } return obligations; } catch (Exception e) { throw new POException(node, e); } } @Override public ProofObligationList caseAPerSyncDefinition(APerSyncDefinition node, POContextStack question) throws AnalysisException { try { question.push(new PONameContext(new LexNameList(node.getOpname()))); ProofObligationList list = node.getGuard().apply(rootVisitor, question); question.pop(); return list; } catch (Exception e) { throw new POException(node, e); } } @Override public ProofObligationList caseAStateDefinition(AStateDefinition node, POContextStack question) throws AnalysisException { try { ProofObligationList list = new ProofObligationList(); if (node.getInvdef() != null) { list.addAll(node.getInvdef().apply(mainVisitor, question)); } return list; } catch (Exception e) { throw new POException(node, e); } } @Override public ProofObligationList caseATypeDefinition(ATypeDefinition node, POContextStack question) throws AnalysisException { try { ProofObligationList list = new ProofObligationList(); AExplicitFunctionDefinition invDef = node.getInvdef(); if (invDef != null) { list.addAll(invDef.apply(mainVisitor, question)); } return list; } catch (Exception e) { throw new POException(node, e); } } @Override public ProofObligationList caseAValueDefinition(AValueDefinition node, POContextStack question) throws AnalysisException { try { ProofObligationList obligations = new ProofObligationList(); PExp exp = node.getExpression(); obligations.addAll(exp.apply(rootVisitor, question)); PPattern pattern = node.getPattern(); PType type = node.getType(); if (!(pattern instanceof AIdentifierPattern) && !(pattern instanceof AIgnorePattern) && PTypeAssistantTC.isUnion(type)) { PType patternType = PPatternAssistantTC.getPossibleType(pattern); AUnionType ut = PTypeAssistantTC.getUnion(type); PTypeSet set = new PTypeSet(); for (PType u : ut.getTypes()) { if (TypeComparator.compatible(u, patternType)) set.add(u); } if (!set.isEmpty()) { PType compatible = set.getType(node.getLocation()); if (!TypeComparator.isSubType(type, compatible)) { obligations.add(new ValueBindingObligation(node, question)); obligations.add(new SubTypeObligation(exp, compatible, type, question)); } } } if (!TypeComparator.isSubType(question.checkType(exp, node.getExpType()), type)) { obligations.add(new SubTypeObligation(exp, type, node.getExpType(), question)); } return obligations; } catch (Exception e) { throw new POException(node, e); } } @Override public ProofObligationList defaultPTraceDefinition(PTraceDefinition node, POContextStack question) { return new ProofObligationList(); } @Override public ProofObligationList defaultPTraceCoreDefinition( PTraceCoreDefinition node, POContextStack question) { return new ProofObligationList(); } @Override public ProofObligationList caseAClassClassDefinition( AClassClassDefinition node, POContextStack question) throws AnalysisException { try { ProofObligationList proofObligationList = new ProofObligationList(); for (PDefinition def : node.getDefinitions()) { question.push(new PONameContext(PDefinitionAssistantTC.getVariableNames(def))); proofObligationList.addAll(def.apply(mainVisitor, question)); question.pop(); } return proofObligationList; } catch (Exception e) { throw new POException(node, e); } } @Override public ProofObligationList createNewReturnValue(INode node, POContextStack question) { return new ProofObligationList(); } @Override public ProofObligationList createNewReturnValue(Object node, POContextStack question) { return new ProofObligationList(); } }
false
true
public ProofObligationList caseAImplicitFunctionDefinition( AImplicitFunctionDefinition node, POContextStack question) throws AnalysisException { try { ProofObligationList obligations = new ProofObligationList(); LexNameList pids = new LexNameList(); boolean matchNeeded = false; for (APatternListTypePair pltp : node.getParamPatterns()) { for (PPattern p : pltp.getPatterns()) { for (PDefinition def : p.getDefinitions()) pids.add(def.getName()); } if (!PPatternListAssistantTC.alwaysMatches(pltp.getPatterns())) { matchNeeded = true; } } if (pids.hasDuplicates() || matchNeeded) { obligations.add(new ParameterPatternObligation(node, question)); } if (node.getPrecondition() != null) { obligations.addAll(node.getPrecondition().apply(rootVisitor, question)); } if (node.getPostcondition() != null) { if (node.getBody() != null) // else satisfiability, below { question.push(new POFunctionDefinitionContext(node, false)); obligations.add(new FuncPostConditionObligation(node, question)); question.pop(); } question.push(new POFunctionResultContext(node)); obligations.addAll(node.getPostcondition().apply(rootVisitor, question)); question.pop(); } if (node.getBody() == null) { if (node.getPostcondition() != null) { question.push(new POFunctionDefinitionContext(node, false)); obligations.add(new SatisfiabilityObligation(node, question)); question.pop(); } } else { question.push(new POFunctionDefinitionContext(node, true)); obligations.addAll(node.getBody().apply(rootVisitor, question)); if (node.getIsUndefined() || !TypeComparator.isSubType(node.getActualResult(), ((AOperationType) node.getType()).getResult())) { obligations.add(new SubTypeObligation(node, ((AOperationType) node.getType()).getResult(), node.getActualResult(), question)); } question.pop(); } return obligations; } catch (Exception e) { throw new POException(node, e); } }
public ProofObligationList caseAImplicitFunctionDefinition( AImplicitFunctionDefinition node, POContextStack question) throws AnalysisException { try { ProofObligationList obligations = new ProofObligationList(); LexNameList pids = new LexNameList(); boolean matchNeeded = false; for (APatternListTypePair pltp : node.getParamPatterns()) { for (PPattern p : pltp.getPatterns()) { for (PDefinition def : p.getDefinitions()) pids.add(def.getName()); } if (!PPatternListAssistantTC.alwaysMatches(pltp.getPatterns())) { matchNeeded = true; } } if (pids.hasDuplicates() || matchNeeded) { obligations.add(new ParameterPatternObligation(node, question)); } if (node.getPrecondition() != null) { obligations.addAll(node.getPrecondition().apply(rootVisitor, question)); } if (node.getPostcondition() != null) { if (node.getBody() != null) // else satisfiability, below { question.push(new POFunctionDefinitionContext(node, false)); obligations.add(new FuncPostConditionObligation(node, question)); question.pop(); } question.push(new POFunctionResultContext(node)); obligations.addAll(node.getPostcondition().apply(rootVisitor, question)); question.pop(); } if (node.getBody() == null) { if (node.getPostcondition() != null) { question.push(new POFunctionDefinitionContext(node, false)); obligations.add(new SatisfiabilityObligation(node, question)); question.pop(); } } else { question.push(new POFunctionDefinitionContext(node, true)); obligations.addAll(node.getBody().apply(rootVisitor, question)); if (node.getIsUndefined() || !TypeComparator.isSubType(node.getActualResult(), node.getType().getResult())) { obligations.add(new SubTypeObligation(node, node.getType().getResult(), node.getActualResult(), question)); } question.pop(); } return obligations; } catch (Exception e) { throw new POException(node, e); } }
diff --git a/src/jpcsp/Debugger/DisassemblerModule/Disassembler.java b/src/jpcsp/Debugger/DisassemblerModule/Disassembler.java index c89f4cf7..b9a69d27 100644 --- a/src/jpcsp/Debugger/DisassemblerModule/Disassembler.java +++ b/src/jpcsp/Debugger/DisassemblerModule/Disassembler.java @@ -1,668 +1,670 @@ /* This file is part of jpcsp. Jpcsp 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. Jpcsp 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 Jpcsp. If not, see <http://www.gnu.org/licenses/>. */ package jpcsp.Debugger.DisassemblerModule; import jpcsp.util.OptionPaneMultiple; import java.awt.Point; import jpcsp.Debugger.*; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import javax.swing.DefaultListModel; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.SwingWorker; import jpcsp.Emulator; import jpcsp.GeneralJpcspException; import jpcsp.Memory; import jpcsp.Settings; import jpcsp.util.JpcspDialogManager; import static jpcsp.AllegrexOpcodes.*; import static jpcsp.Debugger.DisassemblerModule.DisHelper.*; /** * * @author shadow */ public class Disassembler extends javax.swing.JInternalFrame implements ClipboardOwner{ Emulator emu; int DebuggerPC; private DefaultListModel model_1 = new DefaultListModel(); //int pcreg; int opcode_address; // store the address of the opcode used for offsetdecode // Processor c; Registers regs; MemoryViewer memview; DisasmOpcodes disOp = new DisasmOpcodes(); ArrayList<Integer> breakpoints = new ArrayList<Integer>(); /* Creates new form Disasembler */ public Disassembler(Emulator emu, Registers regs, MemoryViewer memview) { //this.c = c; this.regs=regs; this.memview=memview; this.emu=emu; DebuggerPC = 0; //pcreg = c.pc; model_1 = new DefaultListModel(); initComponents(); RefreshDebugger(); } /** 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() { DisMenu = new javax.swing.JPopupMenu(); CopyAddress = new javax.swing.JMenuItem(); CopyAll = new javax.swing.JMenuItem(); BranchOrJump = new javax.swing.JMenuItem(); jList1 = new javax.swing.JList(model_1); ResetToPC = new javax.swing.JButton(); JumpTo = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); StepEmu = new javax.swing.JButton(); RunEmu = new javax.swing.JButton(); StopEmu = new javax.swing.JButton(); AddBreakpoint = new javax.swing.JButton(); RemoveBreakpoint = new javax.swing.JButton(); ClearBreakpoints = new javax.swing.JButton(); RunWithBreakPoints = new javax.swing.JButton(); CopyAddress.setText("Copy Address"); CopyAddress.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CopyAddressActionPerformed(evt); } }); DisMenu.add(CopyAddress); CopyAll.setText("Copy All"); CopyAll.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CopyAllActionPerformed(evt); } }); DisMenu.add(CopyAll); BranchOrJump.setText("Copy Branch Or Jump address"); BranchOrJump.setEnabled(false); //disable as default BranchOrJump.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BranchOrJumpActionPerformed(evt); } }); DisMenu.add(BranchOrJump); setClosable(true); setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); setTitle("Disassembler"); addInternalFrameListener(new javax.swing.event.InternalFrameListener() { public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) { formInternalFrameClosing(evt); } public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) { } }); jList1.setFont(new java.awt.Font("Courier New", 0, 11)); jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jList1.addMouseWheelListener(new java.awt.event.MouseWheelListener() { public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) { jList1MouseWheelMoved(evt); } }); jList1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jList1MouseClicked(evt); } }); jList1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jList1KeyPressed(evt); } }); ResetToPC.setText("Reset to PC"); ResetToPC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ResetToPCActionPerformed(evt); } }); JumpTo.setText("Jump to Address"); JumpTo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { JumpToActionPerformed(evt); } }); jButton3.setText("Dump code"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); StepEmu.setText("Step CPU"); StepEmu.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { StepEmuActionPerformed(evt); } }); RunEmu.setText("Run "); RunEmu.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RunEmuActionPerformed(evt); } }); StopEmu.setText("Stop"); StopEmu.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { StopEmuActionPerformed(evt); } }); AddBreakpoint.setText("Add Breakpoint"); AddBreakpoint.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AddBreakpointActionPerformed(evt); } }); RemoveBreakpoint.setText("Remove Breakpoint"); RemoveBreakpoint.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RemoveBreakpointActionPerformed(evt); } }); ClearBreakpoints.setText("Clear Breakpoints"); ClearBreakpoints.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ClearBreakpointsActionPerformed(evt); } }); RunWithBreakPoints.setText("Run With Breakpoints"); RunWithBreakPoints.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RunWithBreakPointsActionPerformed(evt); } }); 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() .addGap(12, 12, 12) .addComponent(jList1, javax.swing.GroupLayout.PREFERRED_SIZE, 456, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(RunEmu, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(StopEmu, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(StepEmu, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(RunWithBreakPoints, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(ClearBreakpoints, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(RemoveBreakpoint, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(AddBreakpoint, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(JumpTo, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(ResetToPC, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(jList1, javax.swing.GroupLayout.PREFERRED_SIZE, 363, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGroup(layout.createSequentialGroup() + .addComponent(jList1, javax.swing.GroupLayout.DEFAULT_SIZE, 367, Short.MAX_VALUE) + .addContainerGap()) .addGroup(layout.createSequentialGroup() .addComponent(RunEmu) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(RunWithBreakPoints) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(StopEmu) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(StepEmu) .addGap(30, 30, 30) .addComponent(ResetToPC) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(JumpTo) .addGap(19, 19, 19) .addComponent(AddBreakpoint) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(RemoveBreakpoint) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(ClearBreakpoints) .addGap(33, 33, 33) - .addComponent(jButton3))) - .addContainerGap()) + .addComponent(jButton3) + .addGap(25, 25, 25)))) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jList1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jList1KeyPressed // TODO add your handling code here: if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_DOWN && jList1.getSelectedIndex() == jList1.getLastVisibleIndex()) { DebuggerPC += 4; RefreshDebugger(); evt.consume(); jList1.setSelectedIndex(jList1.getLastVisibleIndex()); } else if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_UP && jList1.getSelectedIndex() == 0) { DebuggerPC -= 4; RefreshDebugger(); evt.consume(); jList1.setSelectedIndex(0); } else if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_PAGE_UP && jList1.getSelectedIndex() == 0) { DebuggerPC -= 0x68; RefreshDebugger(); evt.consume(); jList1.setSelectedIndex(0); } else if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_PAGE_DOWN && jList1.getSelectedIndex() == jList1.getLastVisibleIndex()) { DebuggerPC += 0x68; RefreshDebugger(); evt.consume(); jList1.setSelectedIndex(jList1.getLastVisibleIndex()); } }//GEN-LAST:event_jList1KeyPressed private void jList1MouseWheelMoved(java.awt.event.MouseWheelEvent evt) {//GEN-FIRST:event_jList1MouseWheelMoved // TODO add your handling code here: if (evt.getWheelRotation() < 0) { evt.consume(); if (jList1.getSelectedIndex() == 0 || jList1.getSelectedIndex() == -1) { DebuggerPC -= 4; RefreshDebugger(); jList1.setSelectedIndex(0); } else { jList1.setSelectedIndex(jList1.getSelectedIndex() - 1); } } else { evt.consume(); if (jList1.getSelectedIndex() == jList1.getLastVisibleIndex()) { DebuggerPC += 4; RefreshDebugger(); jList1.setSelectedIndex(jList1.getLastVisibleIndex()); } else { jList1.setSelectedIndex(jList1.getSelectedIndex() + 1); } } }//GEN-LAST:event_jList1MouseWheelMoved private void ResetToPCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ResetToPCActionPerformed DebuggerPC = emu.getProcessor().pc;//c.pc;// RefreshDebugger(); }//GEN-LAST:event_ResetToPCActionPerformed private void JumpToActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JumpToActionPerformed String input = (String) JOptionPane.showInternalInputDialog(this, "Enter the address to which to jump (Hex)", "Jpcsp", JOptionPane.QUESTION_MESSAGE, null, null, String.format("%08x", emu.getProcessor().pc)); if (input == null) { return; } int value=0; try { value = Integer.parseInt(input, 16); } catch (Exception e) { JOptionPane.showMessageDialog(this, "The Number you enter is not correct"); return; } DebuggerPC = value; RefreshDebugger(); }//GEN-LAST:event_JumpToActionPerformed private void StepEmuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StepEmuActionPerformed try { emu.getProcessor().step(); jpcsp.HLE.ThreadMan.get_instance().step(); } catch(GeneralJpcspException e) { JpcspDialogManager.showError(this, "General Error : " + e.getMessage()); } DebuggerPC = 0; RefreshDebugger(); regs.RefreshRegisters(); memview.RefreshMemory(); }//GEN-LAST:event_StepEmuActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed // TODO add your handling code here: //System.out.println("dump code dialog created"); OptionPaneMultiple opt=new OptionPaneMultiple(Integer.toHexString(DebuggerPC),Integer.toHexString(DebuggerPC + 0x00000068)); if(opt.completed()){ //Here the input can be used to actually dump code System.out.println("Start address: "+opt.getInput()[0]); System.out.println("End address: "+opt.getInput()[1]); System.out.println("File name: "+opt.getInput()[2]); BufferedWriter bufferedWriter = null; try { //Construct the BufferedWriter object bufferedWriter = new BufferedWriter(new FileWriter(opt.getInput()[2])); //Start writing to the output stream bufferedWriter.write("-------JPCSP DISASM-----------"); bufferedWriter.newLine(); int Start = Integer.parseInt(opt.getInput()[0],16); int End = Integer.parseInt(opt.getInput()[1],16); for(int i =Start; i<=End; i+=4) { int memread = Memory.get_instance().read32((int) i); if (memread == 0) { bufferedWriter.write(String.format("%08x : [%08x]: nop", i, memread)); bufferedWriter.newLine(); } else { opcode_address = i; bufferedWriter.write(String.format("%08x : [%08x]: %s", i, memread, disOp.disasm(memread,opcode_address))); bufferedWriter.newLine(); } } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { //Close the BufferedWriter try { if (bufferedWriter != null) { bufferedWriter.flush(); bufferedWriter.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } //System.out.println("dump code dialog done"); opt=null; }//GEN-LAST:event_jButton3ActionPerformed private void CopyAddressActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CopyAddressActionPerformed String value = (String)jList1.getSelectedValue(); String address; if(value.startsWith("<br>")) address = value.substring(4, 12); else address = value.substring(0, 8); StringSelection stringSelection = new StringSelection( address); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(stringSelection, this); }//GEN-LAST:event_CopyAddressActionPerformed private void jList1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseClicked BranchOrJump.setEnabled(false); if (SwingUtilities.isRightMouseButton(evt) && !jList1.isSelectionEmpty() && jList1.locationToIndex(evt.getPoint()) == jList1.getSelectedIndex()) { //check if we can enable branch or jump address copy String line = (String)jList1.getSelectedValue(); int finddot = line.indexOf("]:"); String opcode = line.substring(finddot+3,line.length()); if(opcode.startsWith("b") || opcode.startsWith("j"))//it is definately a branch or jump opcode { BranchOrJump.setEnabled(true); } DisMenu.show(jList1, evt.getX(), evt.getY()); } }//GEN-LAST:event_jList1MouseClicked private void CopyAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CopyAllActionPerformed String value = (String)jList1.getSelectedValue(); StringSelection stringSelection = new StringSelection( value); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(stringSelection, this); }//GEN-LAST:event_CopyAllActionPerformed private void BranchOrJumpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BranchOrJumpActionPerformed String value = (String)jList1.getSelectedValue(); int address = value.indexOf("0x"); if(address==-1) { JpcspDialogManager.showError(this, "Can't find the jump or branch address"); return; } else { String add = value.substring(address+2,value.length()); StringSelection stringSelection = new StringSelection(add); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(stringSelection, this); } }//GEN-LAST:event_BranchOrJumpActionPerformed private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing // System.out.println(this.getLocation()); Point location = getLocation(); //location.x String[] coord = new String[2]; coord[0]=Integer.toString(location.x); coord[1]=Integer.toString(location.y); Settings.get_instance().writeWindowPos("disassembler", coord); }//GEN-LAST:event_formInternalFrameClosing final SwingWorker<Integer,Void> worker = new SwingWorker<Integer,Void>() { @Override public Integer doInBackground() { //start emulator try { if(emu.pause)//emu is paused { emu.resume(); } else { emu.run=true; emu.run(); } }catch(GeneralJpcspException e) { JpcspDialogManager.showError(null, "General Error : " + e.getMessage()); } return 0; } @Override public void done() { emu.pause(); } }; private void RunEmuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RunEmuActionPerformed worker.execute(); }//GEN-LAST:event_RunEmuActionPerformed private void StopEmuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StopEmuActionPerformed worker.cancel(false); DebuggerPC = 0; RefreshDebugger(); regs.RefreshRegisters(); memview.RefreshMemory(); }//GEN-LAST:event_StopEmuActionPerformed private void AddBreakpointActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddBreakpointActionPerformed String value =(String)jList1.getSelectedValue(); if(value.length()>0) { String address = value.substring(0, 8); int addr = Integer.parseInt(address,16); breakpoints.add(addr); DebuggerPC = 0; RefreshDebugger(); } }//GEN-LAST:event_AddBreakpointActionPerformed private void RemoveBreakpointActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RemoveBreakpointActionPerformed String value =(String)jList1.getSelectedValue(); if(value.length()>0) { boolean breakpointexists = value.startsWith("<br>"); if(breakpointexists) { String address = value.substring(4, 12); int addr = Integer.parseInt(address,16); int b = breakpoints.indexOf(addr); breakpoints.remove(b); DebuggerPC = 0; RefreshDebugger(); } } }//GEN-LAST:event_RemoveBreakpointActionPerformed private void ClearBreakpointsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ClearBreakpointsActionPerformed if(!breakpoints.isEmpty()) breakpoints.clear(); }//GEN-LAST:event_ClearBreakpointsActionPerformed final SwingWorker<Integer,Void> worker2 = new SwingWorker<Integer,Void>() { @Override public Integer doInBackground() { //start emulator try { if(emu.pause)//emu is paused { emu.resume(); } else { emu.run=true; while(emu.run) { if(breakpoints.indexOf(emu.getProcessor().pc) != -1) { emu.run=false; DebuggerPC = 0; RefreshDebugger(); regs.RefreshRegisters(); memview.RefreshMemory(); } else emu.getProcessor().step(); } } }catch(GeneralJpcspException e) { JpcspDialogManager.showError(null, "General Error : " + e.getMessage()); } return 0; } @Override public void done() { emu.pause(); } }; private void RunWithBreakPointsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RunWithBreakPointsActionPerformed worker2.execute(); }//GEN-LAST:event_RunWithBreakPointsActionPerformed public void RefreshDebugger() { int t; int cnt; if (DebuggerPC == 0) { DebuggerPC = emu.getProcessor().pc;//0x08900000;//test } model_1.clear(); for (t = DebuggerPC , cnt = 0; t < (DebuggerPC + 0x00000068); t += 0x00000004, cnt++) { int memread = Memory.get_instance().read32((int) t); if (memread == 0) { if(breakpoints.indexOf(t)!=-1) model_1.addElement(String.format("<br>%08x:[%08x]: nop", t, memread)); else model_1.addElement(String.format("%08x:[%08x]: nop", t, memread)); } else { opcode_address = t; if(breakpoints.indexOf(t)!=-1) { // model_1.addElement(String.format("<br>%08x:[%08x]: %s", t, memread, disasm(memread))); model_1.addElement(String.format("<br>%08x:[%08x]: %s", t, memread, disOp.disasm(memread,opcode_address))); } else { // model_1.addElement(String.format("%08x:[%08x]: %s", t, memread, disasm(memread))); model_1.addElement(String.format("%08x:[%08x]: %s", t, memread, disOp.disasm(memread,opcode_address))); } } } } /** * Empty implementation of the ClipboardOwner interface. */ public void lostOwnership( Clipboard aClipboard, Transferable aContents) { //do nothing } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton AddBreakpoint; private javax.swing.JMenuItem BranchOrJump; private javax.swing.JButton ClearBreakpoints; private javax.swing.JMenuItem CopyAddress; private javax.swing.JMenuItem CopyAll; private javax.swing.JPopupMenu DisMenu; private javax.swing.JButton JumpTo; private javax.swing.JButton RemoveBreakpoint; private javax.swing.JButton ResetToPC; private javax.swing.JButton RunEmu; private javax.swing.JButton RunWithBreakPoints; private javax.swing.JButton StepEmu; private javax.swing.JButton StopEmu; private javax.swing.JButton jButton3; private javax.swing.JList jList1; // End of variables declaration//GEN-END:variables }
false
true
private void initComponents() { DisMenu = new javax.swing.JPopupMenu(); CopyAddress = new javax.swing.JMenuItem(); CopyAll = new javax.swing.JMenuItem(); BranchOrJump = new javax.swing.JMenuItem(); jList1 = new javax.swing.JList(model_1); ResetToPC = new javax.swing.JButton(); JumpTo = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); StepEmu = new javax.swing.JButton(); RunEmu = new javax.swing.JButton(); StopEmu = new javax.swing.JButton(); AddBreakpoint = new javax.swing.JButton(); RemoveBreakpoint = new javax.swing.JButton(); ClearBreakpoints = new javax.swing.JButton(); RunWithBreakPoints = new javax.swing.JButton(); CopyAddress.setText("Copy Address"); CopyAddress.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CopyAddressActionPerformed(evt); } }); DisMenu.add(CopyAddress); CopyAll.setText("Copy All"); CopyAll.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CopyAllActionPerformed(evt); } }); DisMenu.add(CopyAll); BranchOrJump.setText("Copy Branch Or Jump address"); BranchOrJump.setEnabled(false); //disable as default BranchOrJump.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BranchOrJumpActionPerformed(evt); } }); DisMenu.add(BranchOrJump); setClosable(true); setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); setTitle("Disassembler"); addInternalFrameListener(new javax.swing.event.InternalFrameListener() { public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) { formInternalFrameClosing(evt); } public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) { } }); jList1.setFont(new java.awt.Font("Courier New", 0, 11)); jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jList1.addMouseWheelListener(new java.awt.event.MouseWheelListener() { public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) { jList1MouseWheelMoved(evt); } }); jList1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jList1MouseClicked(evt); } }); jList1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jList1KeyPressed(evt); } }); ResetToPC.setText("Reset to PC"); ResetToPC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ResetToPCActionPerformed(evt); } }); JumpTo.setText("Jump to Address"); JumpTo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { JumpToActionPerformed(evt); } }); jButton3.setText("Dump code"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); StepEmu.setText("Step CPU"); StepEmu.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { StepEmuActionPerformed(evt); } }); RunEmu.setText("Run "); RunEmu.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RunEmuActionPerformed(evt); } }); StopEmu.setText("Stop"); StopEmu.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { StopEmuActionPerformed(evt); } }); AddBreakpoint.setText("Add Breakpoint"); AddBreakpoint.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AddBreakpointActionPerformed(evt); } }); RemoveBreakpoint.setText("Remove Breakpoint"); RemoveBreakpoint.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RemoveBreakpointActionPerformed(evt); } }); ClearBreakpoints.setText("Clear Breakpoints"); ClearBreakpoints.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ClearBreakpointsActionPerformed(evt); } }); RunWithBreakPoints.setText("Run With Breakpoints"); RunWithBreakPoints.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RunWithBreakPointsActionPerformed(evt); } }); 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() .addGap(12, 12, 12) .addComponent(jList1, javax.swing.GroupLayout.PREFERRED_SIZE, 456, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(RunEmu, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(StopEmu, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(StepEmu, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(RunWithBreakPoints, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(ClearBreakpoints, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(RemoveBreakpoint, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(AddBreakpoint, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(JumpTo, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(ResetToPC, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jList1, javax.swing.GroupLayout.PREFERRED_SIZE, 363, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(RunEmu) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(RunWithBreakPoints) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(StopEmu) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(StepEmu) .addGap(30, 30, 30) .addComponent(ResetToPC) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(JumpTo) .addGap(19, 19, 19) .addComponent(AddBreakpoint) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(RemoveBreakpoint) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(ClearBreakpoints) .addGap(33, 33, 33) .addComponent(jButton3))) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { DisMenu = new javax.swing.JPopupMenu(); CopyAddress = new javax.swing.JMenuItem(); CopyAll = new javax.swing.JMenuItem(); BranchOrJump = new javax.swing.JMenuItem(); jList1 = new javax.swing.JList(model_1); ResetToPC = new javax.swing.JButton(); JumpTo = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); StepEmu = new javax.swing.JButton(); RunEmu = new javax.swing.JButton(); StopEmu = new javax.swing.JButton(); AddBreakpoint = new javax.swing.JButton(); RemoveBreakpoint = new javax.swing.JButton(); ClearBreakpoints = new javax.swing.JButton(); RunWithBreakPoints = new javax.swing.JButton(); CopyAddress.setText("Copy Address"); CopyAddress.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CopyAddressActionPerformed(evt); } }); DisMenu.add(CopyAddress); CopyAll.setText("Copy All"); CopyAll.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CopyAllActionPerformed(evt); } }); DisMenu.add(CopyAll); BranchOrJump.setText("Copy Branch Or Jump address"); BranchOrJump.setEnabled(false); //disable as default BranchOrJump.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BranchOrJumpActionPerformed(evt); } }); DisMenu.add(BranchOrJump); setClosable(true); setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); setTitle("Disassembler"); addInternalFrameListener(new javax.swing.event.InternalFrameListener() { public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) { formInternalFrameClosing(evt); } public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) { } }); jList1.setFont(new java.awt.Font("Courier New", 0, 11)); jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jList1.addMouseWheelListener(new java.awt.event.MouseWheelListener() { public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) { jList1MouseWheelMoved(evt); } }); jList1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jList1MouseClicked(evt); } }); jList1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jList1KeyPressed(evt); } }); ResetToPC.setText("Reset to PC"); ResetToPC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ResetToPCActionPerformed(evt); } }); JumpTo.setText("Jump to Address"); JumpTo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { JumpToActionPerformed(evt); } }); jButton3.setText("Dump code"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); StepEmu.setText("Step CPU"); StepEmu.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { StepEmuActionPerformed(evt); } }); RunEmu.setText("Run "); RunEmu.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RunEmuActionPerformed(evt); } }); StopEmu.setText("Stop"); StopEmu.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { StopEmuActionPerformed(evt); } }); AddBreakpoint.setText("Add Breakpoint"); AddBreakpoint.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AddBreakpointActionPerformed(evt); } }); RemoveBreakpoint.setText("Remove Breakpoint"); RemoveBreakpoint.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RemoveBreakpointActionPerformed(evt); } }); ClearBreakpoints.setText("Clear Breakpoints"); ClearBreakpoints.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ClearBreakpointsActionPerformed(evt); } }); RunWithBreakPoints.setText("Run With Breakpoints"); RunWithBreakPoints.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RunWithBreakPointsActionPerformed(evt); } }); 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() .addGap(12, 12, 12) .addComponent(jList1, javax.swing.GroupLayout.PREFERRED_SIZE, 456, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(RunEmu, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(StopEmu, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(StepEmu, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(RunWithBreakPoints, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(ClearBreakpoints, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(RemoveBreakpoint, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(AddBreakpoint, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(JumpTo, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE) .addComponent(ResetToPC, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jList1, javax.swing.GroupLayout.DEFAULT_SIZE, 367, Short.MAX_VALUE) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addComponent(RunEmu) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(RunWithBreakPoints) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(StopEmu) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(StepEmu) .addGap(30, 30, 30) .addComponent(ResetToPC) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(JumpTo) .addGap(19, 19, 19) .addComponent(AddBreakpoint) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(RemoveBreakpoint) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(ClearBreakpoints) .addGap(33, 33, 33) .addComponent(jButton3) .addGap(25, 25, 25)))) ); pack(); }// </editor-fold>//GEN-END:initComponents
diff --git a/src/test/java/org/elasticsearch/examples/nativescript/script/PopularityScoreScriptTests.java b/src/test/java/org/elasticsearch/examples/nativescript/script/PopularityScoreScriptTests.java index 7ed0596..75ef9ff 100644 --- a/src/test/java/org/elasticsearch/examples/nativescript/script/PopularityScoreScriptTests.java +++ b/src/test/java/org/elasticsearch/examples/nativescript/script/PopularityScoreScriptTests.java @@ -1,91 +1,91 @@ package org.elasticsearch.examples.nativescript.script; import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery; import static org.elasticsearch.index.query.QueryBuilders.matchQuery; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.collect.MapBuilder; import org.elasticsearch.common.lucene.search.function.CombineFunction; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders; import org.junit.Test; /** */ public class PopularityScoreScriptTests extends AbstractSearchScriptTests { @Test public void testPopularityScoring() throws Exception { // Create a new index String mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties") .startObject("name").field("type", "string").endObject() .startObject("number").field("type", "integer").endObject() .endObject().endObject().endObject() .string(); assertAcked(prepareCreate("test") .addMapping("type", mapping)); List<IndexRequestBuilder> indexBuilders = new ArrayList<IndexRequestBuilder>(); // Index 5 records with non-empty number field for (int i = 0; i < 5; i++) { indexBuilders.add( client().prepareIndex("test", "type", Integer.toString(i)) .setSource(XContentFactory.jsonBuilder().startObject() .field("name", "rec " + i) - .field("number", i) + .field("number", i + 1) .endObject())); } // Index a few records with empty number for (int i = 5; i < 10; i++) { indexBuilders.add( client().prepareIndex("test", "type", Integer.toString(i)) .setSource(XContentFactory.jsonBuilder().startObject() .field("name", "rec " + i) .endObject())); } indexRandom(true, indexBuilders); Map<String, Object> params = MapBuilder.<String, Object> newMapBuilder().put("field", "number").map(); // Retrieve first 10 hits SearchResponse searchResponse = client().prepareSearch("test") .setQuery(functionScoreQuery(matchQuery("name", "rec")) .boostMode(CombineFunction.REPLACE) .add(ScoreFunctionBuilders.scriptFunction("popularity", "native", params))) .setSize(10) .addField("name") .execute().actionGet(); assertNoFailures(searchResponse); // There should be 10 hist assertHitCount(searchResponse, 10); // Verify that first 5 hits are sorted from 4 to 0 for (int i = 0; i < 5; i++) { assertThat(searchResponse.getHits().getAt(i).field("name").getValue().toString(), equalTo("rec " + (4 - i))); } // Verify that hit 5 has non-zero score assertThat(searchResponse.getHits().getAt(5).score(), greaterThan(0.0f)); // Verify that the last 5 hits has the same score for (int i = 6; i < 10; i++) { assertThat(searchResponse.getHits().getAt(i).score(), equalTo(searchResponse.getHits().getAt(5).score())); } } }
true
true
public void testPopularityScoring() throws Exception { // Create a new index String mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties") .startObject("name").field("type", "string").endObject() .startObject("number").field("type", "integer").endObject() .endObject().endObject().endObject() .string(); assertAcked(prepareCreate("test") .addMapping("type", mapping)); List<IndexRequestBuilder> indexBuilders = new ArrayList<IndexRequestBuilder>(); // Index 5 records with non-empty number field for (int i = 0; i < 5; i++) { indexBuilders.add( client().prepareIndex("test", "type", Integer.toString(i)) .setSource(XContentFactory.jsonBuilder().startObject() .field("name", "rec " + i) .field("number", i) .endObject())); } // Index a few records with empty number for (int i = 5; i < 10; i++) { indexBuilders.add( client().prepareIndex("test", "type", Integer.toString(i)) .setSource(XContentFactory.jsonBuilder().startObject() .field("name", "rec " + i) .endObject())); } indexRandom(true, indexBuilders); Map<String, Object> params = MapBuilder.<String, Object> newMapBuilder().put("field", "number").map(); // Retrieve first 10 hits SearchResponse searchResponse = client().prepareSearch("test") .setQuery(functionScoreQuery(matchQuery("name", "rec")) .boostMode(CombineFunction.REPLACE) .add(ScoreFunctionBuilders.scriptFunction("popularity", "native", params))) .setSize(10) .addField("name") .execute().actionGet(); assertNoFailures(searchResponse); // There should be 10 hist assertHitCount(searchResponse, 10); // Verify that first 5 hits are sorted from 4 to 0 for (int i = 0; i < 5; i++) { assertThat(searchResponse.getHits().getAt(i).field("name").getValue().toString(), equalTo("rec " + (4 - i))); } // Verify that hit 5 has non-zero score assertThat(searchResponse.getHits().getAt(5).score(), greaterThan(0.0f)); // Verify that the last 5 hits has the same score for (int i = 6; i < 10; i++) { assertThat(searchResponse.getHits().getAt(i).score(), equalTo(searchResponse.getHits().getAt(5).score())); } }
public void testPopularityScoring() throws Exception { // Create a new index String mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties") .startObject("name").field("type", "string").endObject() .startObject("number").field("type", "integer").endObject() .endObject().endObject().endObject() .string(); assertAcked(prepareCreate("test") .addMapping("type", mapping)); List<IndexRequestBuilder> indexBuilders = new ArrayList<IndexRequestBuilder>(); // Index 5 records with non-empty number field for (int i = 0; i < 5; i++) { indexBuilders.add( client().prepareIndex("test", "type", Integer.toString(i)) .setSource(XContentFactory.jsonBuilder().startObject() .field("name", "rec " + i) .field("number", i + 1) .endObject())); } // Index a few records with empty number for (int i = 5; i < 10; i++) { indexBuilders.add( client().prepareIndex("test", "type", Integer.toString(i)) .setSource(XContentFactory.jsonBuilder().startObject() .field("name", "rec " + i) .endObject())); } indexRandom(true, indexBuilders); Map<String, Object> params = MapBuilder.<String, Object> newMapBuilder().put("field", "number").map(); // Retrieve first 10 hits SearchResponse searchResponse = client().prepareSearch("test") .setQuery(functionScoreQuery(matchQuery("name", "rec")) .boostMode(CombineFunction.REPLACE) .add(ScoreFunctionBuilders.scriptFunction("popularity", "native", params))) .setSize(10) .addField("name") .execute().actionGet(); assertNoFailures(searchResponse); // There should be 10 hist assertHitCount(searchResponse, 10); // Verify that first 5 hits are sorted from 4 to 0 for (int i = 0; i < 5; i++) { assertThat(searchResponse.getHits().getAt(i).field("name").getValue().toString(), equalTo("rec " + (4 - i))); } // Verify that hit 5 has non-zero score assertThat(searchResponse.getHits().getAt(5).score(), greaterThan(0.0f)); // Verify that the last 5 hits has the same score for (int i = 6; i < 10; i++) { assertThat(searchResponse.getHits().getAt(i).score(), equalTo(searchResponse.getHits().getAt(5).score())); } }
diff --git a/src/main/java/dungeon/models/Player.java b/src/main/java/dungeon/models/Player.java index af0208c..9c50b8f 100644 --- a/src/main/java/dungeon/models/Player.java +++ b/src/main/java/dungeon/models/Player.java @@ -1,219 +1,219 @@ package dungeon.models; import dungeon.models.messages.Transform; import java.awt.geom.Rectangle2D; public class Player { public static final int SIZE = 900; private final String name; private final int lives; private final int hitPoints; private final int maxHitPoints; /** * Which level is the player currently in? */ private final String levelId; /** * Which room is the player currently in? */ private final String roomId; /** * His position in the room. */ private final Position position; /** * In which room was the player, when he activated the current save point? * * Whenever the player enters a new level, this should be reset to the starting room's id. */ private final String savePointRoomId; /** * At which position was the player, when he activated the current save point? * * Whenever the player enters a new level, this should be reset to the player's position in the starting room. */ private final Position savePointPosition; public Player (String name, int lives, int hitPoints, int maxHitPoints, String levelId, String roomId, Position position, String savePointRoomId, Position savePointPosition) { this.name = name; this.lives = lives; this.hitPoints = hitPoints; this.maxHitPoints = maxHitPoints; this.levelId = levelId; this.roomId = roomId; this.position = position; this.savePointRoomId = savePointRoomId; this.savePointPosition = savePointPosition; } public String getName () { return this.name; } public int getLives () { return this.lives; } public int getHitPoints () { return this.hitPoints; } public int getMaxHitPoints () { return this.maxHitPoints; } public String getLevelId () { return this.levelId; } public String getRoomId () { return this.roomId; } public Position getPosition () { return this.position; } public String getSavePointRoomId () { return this.savePointRoomId; } public Position getSavePointPosition () { return this.savePointPosition; } /** * Checks if the player touches the enemy #enemy. */ public boolean touches (Enemy enemy) { Rectangle2D enemySpace = new Rectangle2D.Float(enemy.getPosition().getX(), enemy.getPosition().getY(), Enemy.SIZE, Enemy.SIZE); return this.playerSpace().intersects(enemySpace); } /** * Checks if the player touches the 1x1 tile at Position (#x, #y). */ public boolean touches (Tile tile) { Rectangle2D tileSpace = new Rectangle2D.Float(tile.getPosition().getX(), tile.getPosition().getY(), Tile.SIZE, Tile.SIZE); return this.playerSpace().intersects(tileSpace); } public boolean touches (SavePoint savePoint) { Rectangle2D savePointSpace = new Rectangle2D.Float(savePoint.getPosition().getX(), savePoint.getPosition().getY(), SavePoint.SIZE, SavePoint.SIZE); return this.playerSpace().intersects(savePointSpace); } /** * Returns a rectangle that represents the space occupied by the player. */ private Rectangle2D playerSpace () { return new Rectangle2D.Float(this.getPosition().getX(), this.getPosition().getY(), Player.SIZE, Player.SIZE); } public Player apply (Transform transform) { String name = this.name; int lives = this.lives; int hitPoints = this.hitPoints; int maxHitPoints = this.maxHitPoints; String levelId = this.levelId; String roomId = this.roomId; Position position = this.position; String savePointRoomId = this.savePointRoomId; Position savePointPosition = this.savePointPosition; if (transform instanceof MoveTransform) { MoveTransform move = (MoveTransform)transform; position = new Position(this.position.getX() + move.xDelta, this.position.getY() + move.yDelta); } else if (transform instanceof HitpointTransform) { HitpointTransform hpTransform = (HitpointTransform)transform; hitPoints += hpTransform.delta; } else if (transform instanceof LivesTransform) { LivesTransform livesTransform = (LivesTransform)transform; - lives +=livesTransform.delta; + lives += livesTransform.delta; } else if (transform instanceof TeleportTransform) { TeleportTransform teleportTransform = (TeleportTransform)transform; roomId = teleportTransform.roomId; position = new Position(teleportTransform.x, teleportTransform.y); - } else if (transform instanceof SavePointTransform) { + } else if (transform instanceof SavePointTransform) { SavePointTransform savePointTransform = (Player.SavePointTransform)transform; roomId = savePointTransform.roomId; position = new Position(savePointTransform.x, savePointTransform.y); } return new Player(name, lives, hitPoints, maxHitPoints, levelId, roomId, position, savePointRoomId, savePointPosition); } public static class MoveTransform implements Transform { private final int xDelta; private final int yDelta; public MoveTransform (int xDelta, int yDelta) { this.xDelta = xDelta; this.yDelta = yDelta; } } public static class HitpointTransform implements Transform { private final int delta; public HitpointTransform (int delta) { this.delta = delta; } } public static class LivesTransform implements Transform { private final int delta; public LivesTransform (int delta) { this.delta = delta; } } public static class TeleportTransform implements Transform { private final String roomId; private final int x; private final int y; public TeleportTransform (String roomId, int x, int y) { this.roomId = roomId; this.x = x; this.y = y; } } public static class SavePointTransform implements Transform { private final String roomId; private final int x; private final int y; public SavePointTransform (String roomId, int x, int y) { this.roomId = roomId; this.x = x; this.y = y; } } }
false
true
public Player apply (Transform transform) { String name = this.name; int lives = this.lives; int hitPoints = this.hitPoints; int maxHitPoints = this.maxHitPoints; String levelId = this.levelId; String roomId = this.roomId; Position position = this.position; String savePointRoomId = this.savePointRoomId; Position savePointPosition = this.savePointPosition; if (transform instanceof MoveTransform) { MoveTransform move = (MoveTransform)transform; position = new Position(this.position.getX() + move.xDelta, this.position.getY() + move.yDelta); } else if (transform instanceof HitpointTransform) { HitpointTransform hpTransform = (HitpointTransform)transform; hitPoints += hpTransform.delta; } else if (transform instanceof LivesTransform) { LivesTransform livesTransform = (LivesTransform)transform; lives +=livesTransform.delta; } else if (transform instanceof TeleportTransform) { TeleportTransform teleportTransform = (TeleportTransform)transform; roomId = teleportTransform.roomId; position = new Position(teleportTransform.x, teleportTransform.y); } else if (transform instanceof SavePointTransform) { SavePointTransform savePointTransform = (Player.SavePointTransform)transform; roomId = savePointTransform.roomId; position = new Position(savePointTransform.x, savePointTransform.y); } return new Player(name, lives, hitPoints, maxHitPoints, levelId, roomId, position, savePointRoomId, savePointPosition); }
public Player apply (Transform transform) { String name = this.name; int lives = this.lives; int hitPoints = this.hitPoints; int maxHitPoints = this.maxHitPoints; String levelId = this.levelId; String roomId = this.roomId; Position position = this.position; String savePointRoomId = this.savePointRoomId; Position savePointPosition = this.savePointPosition; if (transform instanceof MoveTransform) { MoveTransform move = (MoveTransform)transform; position = new Position(this.position.getX() + move.xDelta, this.position.getY() + move.yDelta); } else if (transform instanceof HitpointTransform) { HitpointTransform hpTransform = (HitpointTransform)transform; hitPoints += hpTransform.delta; } else if (transform instanceof LivesTransform) { LivesTransform livesTransform = (LivesTransform)transform; lives += livesTransform.delta; } else if (transform instanceof TeleportTransform) { TeleportTransform teleportTransform = (TeleportTransform)transform; roomId = teleportTransform.roomId; position = new Position(teleportTransform.x, teleportTransform.y); } else if (transform instanceof SavePointTransform) { SavePointTransform savePointTransform = (Player.SavePointTransform)transform; roomId = savePointTransform.roomId; position = new Position(savePointTransform.x, savePointTransform.y); } return new Player(name, lives, hitPoints, maxHitPoints, levelId, roomId, position, savePointRoomId, savePointPosition); }
diff --git a/src/main/java/org/jruby/rack/RackTag.java b/src/main/java/org/jruby/rack/RackTag.java index a379ae3..e9cc967 100644 --- a/src/main/java/org/jruby/rack/RackTag.java +++ b/src/main/java/org/jruby/rack/RackTag.java @@ -1,41 +1,45 @@ package org.jruby.rack; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.jsp.tagext.TagSupport; import javax.servlet.jsp.JspException; public class RackTag extends TagSupport { private String path; private String params; public void setPath(String path) { this.path = path; } public void setParams(String params) { this.params = params; } @Override public int doEndTag() throws JspException { try { RackApplicationFactory factory = (RackApplicationFactory) pageContext.getServletContext().getAttribute(RackServletContextListener.FACTORY_KEY); RackApplication app = factory.getApplication(); try { - RackResponse result = app.call(new HttpServletRequestWrapper((HttpServletRequest) pageContext.getRequest()) { - public String getRequestURI() { return path; } - public String getQueryString() { return params; } - public String getMethod() { return "GET"; } - }); + final HttpServletRequest request = + new HttpServletRequestWrapper((HttpServletRequest) pageContext.getRequest()) { + @Override public String getMethod() { return "GET"; } + @Override public String getRequestURI() { return path + "?" + params; } + @Override public String getPathInfo() { return path; } + @Override public String getQueryString() { return params; } + @Override public String getServletPath() { return ""; } + }; + RackResponse result = app.call(request); pageContext.getOut().write(result.getBody()); } finally { factory.finishedWithApplication(app); } } catch (Exception e) { throw new JspException(e); } return EVAL_PAGE; } }
true
true
public int doEndTag() throws JspException { try { RackApplicationFactory factory = (RackApplicationFactory) pageContext.getServletContext().getAttribute(RackServletContextListener.FACTORY_KEY); RackApplication app = factory.getApplication(); try { RackResponse result = app.call(new HttpServletRequestWrapper((HttpServletRequest) pageContext.getRequest()) { public String getRequestURI() { return path; } public String getQueryString() { return params; } public String getMethod() { return "GET"; } }); pageContext.getOut().write(result.getBody()); } finally { factory.finishedWithApplication(app); } } catch (Exception e) { throw new JspException(e); } return EVAL_PAGE; }
public int doEndTag() throws JspException { try { RackApplicationFactory factory = (RackApplicationFactory) pageContext.getServletContext().getAttribute(RackServletContextListener.FACTORY_KEY); RackApplication app = factory.getApplication(); try { final HttpServletRequest request = new HttpServletRequestWrapper((HttpServletRequest) pageContext.getRequest()) { @Override public String getMethod() { return "GET"; } @Override public String getRequestURI() { return path + "?" + params; } @Override public String getPathInfo() { return path; } @Override public String getQueryString() { return params; } @Override public String getServletPath() { return ""; } }; RackResponse result = app.call(request); pageContext.getOut().write(result.getBody()); } finally { factory.finishedWithApplication(app); } } catch (Exception e) { throw new JspException(e); } return EVAL_PAGE; }
diff --git a/servicemix-core/src/test/java/org/servicemix/jbi/management/task/InstallComponentTaskTest.java b/servicemix-core/src/test/java/org/servicemix/jbi/management/task/InstallComponentTaskTest.java index db72e732e..d8deaaa57 100644 --- a/servicemix-core/src/test/java/org/servicemix/jbi/management/task/InstallComponentTaskTest.java +++ b/servicemix-core/src/test/java/org/servicemix/jbi/management/task/InstallComponentTaskTest.java @@ -1,54 +1,54 @@ /* * Created on Jul 13, 2005 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ package org.servicemix.jbi.management.task; import org.servicemix.jbi.util.FileUtil; import java.io.File; import java.net.URL; /** * * InstallComponentTaskTest */ public class InstallComponentTaskTest extends JbiTaskSupport { private InstallComponentTask installComponentTask; private File rootDir = new File("testWDIR"); /* * @see TestCase#setUp() */ protected void setUp() throws Exception { this.container.setRootDir(rootDir.getPath()); super.setUp(); installComponentTask = new InstallComponentTask(){}; installComponentTask.init(); } /* * @see TestCase#tearDown() */ protected void tearDown() throws Exception { installComponentTask.close(); super.tearDown(); } public void testInstallation() throws Exception { URL url = getClass().getClassLoader().getResource("org/servicemix/jbi/installation/testarchive.jar"); if (url != null) { String file = url.getFile(); - installComponentTask.setArchivePath(file); + installComponentTask.setFile(file); installComponentTask.init(); installComponentTask.execute(); File testFile = new File(rootDir, container.getName() + File.separator + "components" + File.separator + "ComponentTest"); assertTrue(testFile.exists()); FileUtil.deleteFile(rootDir); } } }
true
true
public void testInstallation() throws Exception { URL url = getClass().getClassLoader().getResource("org/servicemix/jbi/installation/testarchive.jar"); if (url != null) { String file = url.getFile(); installComponentTask.setArchivePath(file); installComponentTask.init(); installComponentTask.execute(); File testFile = new File(rootDir, container.getName() + File.separator + "components" + File.separator + "ComponentTest"); assertTrue(testFile.exists()); FileUtil.deleteFile(rootDir); } }
public void testInstallation() throws Exception { URL url = getClass().getClassLoader().getResource("org/servicemix/jbi/installation/testarchive.jar"); if (url != null) { String file = url.getFile(); installComponentTask.setFile(file); installComponentTask.init(); installComponentTask.execute(); File testFile = new File(rootDir, container.getName() + File.separator + "components" + File.separator + "ComponentTest"); assertTrue(testFile.exists()); FileUtil.deleteFile(rootDir); } }
diff --git a/src/com/jonathanaquino/svntimelapseview/SvnLoader.java b/src/com/jonathanaquino/svntimelapseview/SvnLoader.java index e645609..7ff8a10 100644 --- a/src/com/jonathanaquino/svntimelapseview/SvnLoader.java +++ b/src/com/jonathanaquino/svntimelapseview/SvnLoader.java @@ -1,197 +1,197 @@ package com.jonathanaquino.svntimelapseview; import java.io.ByteArrayOutputStream; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNRevisionProperty; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory; import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory; import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl; import org.tmatesoft.svn.core.io.SVNFileRevision; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.io.SVNRepositoryFactory; import org.tmatesoft.svn.core.wc.SVNClientManager; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNWCUtil; import com.jonathanaquino.svntimelapseview.helpers.MiscHelper; /** * Loads revisions from a subversion repository. */ public class SvnLoader { /** Whether revisions are currently being downloaded. */ private volatile boolean loading = false; /** Whether the user has requested that the load be cancelled. */ private volatile boolean cancelled = false; /** Number of revisions downloaded for the current file. */ private volatile int loadedCount = 0; /** Total number of revisions to download for the current file. */ private volatile int totalCount = 0; /** The list of Revisions being downloaded. */ private List revisions; /** * Builds a list of revisions for the given file, using a thread. * * @param filePathOrUrl Subversion URL or working-copy file path * @param username username, or null for anonymous * @param password password, or null for anonymous * @param limit maximum number of revisions to download * @param afterLoad operation to run after the load finishes */ public void loadRevisions(final String filePathOrUrl, final String username, final String password, final int limit, final Closure afterLoad) throws Exception { loading = true; cancelled = false; Thread thread = new Thread(new Runnable() { public void run() { MiscHelper.handleExceptions(new Closure() { public void execute() throws Exception { loadRevisionsProper(filePathOrUrl, username, password, limit, afterLoad); } }); } }); thread.start(); } /** * Builds a list of revisions for the given file. * * @param filePathOrUrl Subversion URL or working-copy file path * @param username username, or null for anonymous * @param password password, or null for anonymous * @param limit maximum number of revisions to download * @param afterLoad operation to run after the load finishes */ private void loadRevisionsProper(String filePathOrUrl, String username, String password, int limit, Closure afterLoad) throws SVNException, Exception { try { loadedCount = totalCount = 0; SVNURL fullUrl = svnUrl(filePathOrUrl, username, password); String url = fullUrl.removePathTail().toString(); String filePath = fullUrl.getPath().replaceAll(".*/", ""); SVNRepository repository = repository(url, username, password); List svnFileRevisions = new ArrayList(repository.getFileRevisions(filePath, null, 0, repository.getLatestRevision())); Collections.reverse(svnFileRevisions); - List svnFileRevisionsToDownload = svnFileRevisions.subList(0, limit); + List svnFileRevisionsToDownload = svnFileRevisions.size() > limit ? svnFileRevisions.subList(0, limit) : svnFileRevisions; totalCount = svnFileRevisionsToDownload.size(); revisions = new ArrayList(); for (Iterator i = svnFileRevisionsToDownload.iterator(); i.hasNext(); ) { SVNFileRevision r = (SVNFileRevision) i.next(); if (cancelled) { break; } Map p = r.getRevisionProperties(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); repository.getFile(r.getPath(), r.getRevision(), null, outputStream); revisions.add(new Revision(r.getRevision(), (String) p.get(SVNRevisionProperty.AUTHOR), formatDate((String) p.get(SVNRevisionProperty.DATE)), (String) p.get(SVNRevisionProperty.LOG), outputStream.toString())); loadedCount++; } Collections.reverse(revisions); afterLoad.execute(); } finally { loading = false; } } /** * Normalizes the given file path or URL. * * @param filePathOrUrl Subversion URL or working-copy file path * @param username username, or null for anonymous * @param password password, or null for anonymous * @return the corresponding Subversion URL */ private SVNURL svnUrl(String filePathOrUrl, String username, String password) throws SVNException { SVNURL svnUrl; if (new File(filePathOrUrl).exists()) { SVNClientManager clientManager = SVNClientManager.newInstance(SVNWCUtil.createDefaultOptions(true), username, password); svnUrl = clientManager.getWCClient().doInfo(new File(filePathOrUrl), SVNRevision.WORKING).getURL(); } else { svnUrl = SVNURL.parseURIEncoded(filePathOrUrl); } return svnUrl; } /** * Formats the value of the date property * * @param date the revision date * @return a friendlier date string */ protected String formatDate(String date) { return date.replaceFirst("(.*)T(.*:.*):.*", "$1 $2"); } /** * Returns the specified Subversion repository * * @param url URL of the Subversion repository or one of its files * @param username username, or null for anonymous * @param password password, or null for anonymous * @return the repository handle */ private SVNRepository repository(String url, String username, String password) throws Exception { DAVRepositoryFactory.setup(); SVNRepositoryFactoryImpl.setup(); /* svn:// and svn+xxx:// */ FSRepositoryFactory.setup(); /* file:// */ SVNRepository repository = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(url)); repository.setAuthenticationManager(SVNWCUtil.createDefaultAuthenticationManager(username, password)); return repository; } /** * Returns whether revisions are currently being downloaded. * * @return whether the SvnLoader is loading revisions */ public boolean isLoading() { return loading; } /** * Returns the number of revisions downloaded so far. * * @return the number of revisions loaded in the current job. */ public int getLoadedCount() { return loadedCount; } /** * Returns the total number of revisions that the current job is downloading. * * @return the number of revisions being downloaded. */ public int getTotalCount() { return totalCount; } /** * Returns the Revisions for the file being examined. * * @return the file's revision history */ public List getRevisions() { return revisions; } /** * Requests that the load be cancelled. */ public void cancel() { cancelled = true; } }
true
true
private void loadRevisionsProper(String filePathOrUrl, String username, String password, int limit, Closure afterLoad) throws SVNException, Exception { try { loadedCount = totalCount = 0; SVNURL fullUrl = svnUrl(filePathOrUrl, username, password); String url = fullUrl.removePathTail().toString(); String filePath = fullUrl.getPath().replaceAll(".*/", ""); SVNRepository repository = repository(url, username, password); List svnFileRevisions = new ArrayList(repository.getFileRevisions(filePath, null, 0, repository.getLatestRevision())); Collections.reverse(svnFileRevisions); List svnFileRevisionsToDownload = svnFileRevisions.subList(0, limit); totalCount = svnFileRevisionsToDownload.size(); revisions = new ArrayList(); for (Iterator i = svnFileRevisionsToDownload.iterator(); i.hasNext(); ) { SVNFileRevision r = (SVNFileRevision) i.next(); if (cancelled) { break; } Map p = r.getRevisionProperties(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); repository.getFile(r.getPath(), r.getRevision(), null, outputStream); revisions.add(new Revision(r.getRevision(), (String) p.get(SVNRevisionProperty.AUTHOR), formatDate((String) p.get(SVNRevisionProperty.DATE)), (String) p.get(SVNRevisionProperty.LOG), outputStream.toString())); loadedCount++; } Collections.reverse(revisions); afterLoad.execute(); } finally { loading = false; } }
private void loadRevisionsProper(String filePathOrUrl, String username, String password, int limit, Closure afterLoad) throws SVNException, Exception { try { loadedCount = totalCount = 0; SVNURL fullUrl = svnUrl(filePathOrUrl, username, password); String url = fullUrl.removePathTail().toString(); String filePath = fullUrl.getPath().replaceAll(".*/", ""); SVNRepository repository = repository(url, username, password); List svnFileRevisions = new ArrayList(repository.getFileRevisions(filePath, null, 0, repository.getLatestRevision())); Collections.reverse(svnFileRevisions); List svnFileRevisionsToDownload = svnFileRevisions.size() > limit ? svnFileRevisions.subList(0, limit) : svnFileRevisions; totalCount = svnFileRevisionsToDownload.size(); revisions = new ArrayList(); for (Iterator i = svnFileRevisionsToDownload.iterator(); i.hasNext(); ) { SVNFileRevision r = (SVNFileRevision) i.next(); if (cancelled) { break; } Map p = r.getRevisionProperties(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); repository.getFile(r.getPath(), r.getRevision(), null, outputStream); revisions.add(new Revision(r.getRevision(), (String) p.get(SVNRevisionProperty.AUTHOR), formatDate((String) p.get(SVNRevisionProperty.DATE)), (String) p.get(SVNRevisionProperty.LOG), outputStream.toString())); loadedCount++; } Collections.reverse(revisions); afterLoad.execute(); } finally { loading = false; } }
diff --git a/MonTransit/src/org/montrealtransit/android/services/nextstop/StmInfoTask.java b/MonTransit/src/org/montrealtransit/android/services/nextstop/StmInfoTask.java index f462b8c9..ea19b7ea 100644 --- a/MonTransit/src/org/montrealtransit/android/services/nextstop/StmInfoTask.java +++ b/MonTransit/src/org/montrealtransit/android/services/nextstop/StmInfoTask.java @@ -1,313 +1,317 @@ package org.montrealtransit.android.services.nextstop; import java.net.HttpURLConnection; import java.net.SocketException; import java.net.URL; import java.net.URLConnection; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.montrealtransit.android.AnalyticsUtils; import org.montrealtransit.android.Constant; import org.montrealtransit.android.MyLog; import org.montrealtransit.android.R; import org.montrealtransit.android.Utils; import org.montrealtransit.android.data.BusStopHours; import org.montrealtransit.android.provider.StmStore; import android.content.Context; import android.text.TextUtils; /** * Next stop provider implementation for the http://www.stm.info/ web site. * @author Mathieu Méa */ public class StmInfoTask extends AbstractNextStopProvider { /** * @see AbstractNextStopProvider#AbstractNextStopProvider(NextStopListener, Context) */ public StmInfoTask(NextStopListener from, Context context) { super(from, context); } /** * The source name */ public static final String SOURCE_NAME = "www.stm.info"; /** * The URL. */ private static final String URL_PART_1_BEFORE_LANG = "http://www2.stm.info/horaires/frmResult.aspx?Langue="; private static final String URL_PART_2_BEFORE_BUS_STOP = "&Arret="; /** * The log tag. */ private static final String TAG = StmInfoTask.class.getSimpleName(); @Override protected Map<String, BusStopHours> doInBackground(StmStore.BusStop... busStops) { - String stopCode = busStops[0].getCode(); - String lineNumber = busStops[0].getLineNumber(); + MyLog.v(TAG, "doInBackground()"); Utils.logAppVersion(this.context); String errorMessage = this.context.getString(R.string.error); // set the default error message Map<String, BusStopHours> hours = new HashMap<String, BusStopHours>(); + if (busStops==null || busStops.length == 0) { + return null; + } + String stopCode = busStops[0].getCode(); + String lineNumber = busStops[0].getLineNumber(); try { publishProgress(context.getString(R.string.downloading_data_from_and_source, StmInfoTask.SOURCE_NAME)); String urlString = URL_PART_1_BEFORE_LANG; if (Utils.getSupportedUserLocale().equals(Locale.FRENCH.toString())) { urlString += "Fr"; } else { urlString += "En"; } urlString += URL_PART_2_BEFORE_BUS_STOP + stopCode; URL url = new URL(urlString); URLConnection urlc = url.openConnection(); MyLog.d(TAG, "URL created: '%s'", url.toString()); HttpURLConnection httpUrlConnection = (HttpURLConnection) urlc; switch (httpUrlConnection.getResponseCode()) { case HttpURLConnection.HTTP_OK: String html = Utils.getInputStreamToString(urlc.getInputStream(), "iso-8859-1"); AnalyticsUtils.dispatch(context); // while we are connected, send the analytics data publishProgress(this.context.getResources().getString(R.string.processing_data)); // FOR each bus line DO for (String line : findAllBusLines(html)) { hours.put(line, getBusStopHoursFromString(html, line)); } // IF the targeted bus line was there DO if (hours.keySet().contains(lineNumber)) { publishProgress(this.context.getResources().getString(R.string.done)); } else { // no information errorMessage = this.context.getString(R.string.bus_stop_no_info_and_source, lineNumber, SOURCE_NAME); publishProgress(errorMessage); hours.put(lineNumber, new BusStopHours(SOURCE_NAME, errorMessage)); AnalyticsUtils.trackEvent(context, AnalyticsUtils.CATEGORY_ERROR, AnalyticsUtils.ACTION_BUS_STOP_REMOVED, busStops[0].getUID(), context.getPackageManager() .getPackageInfo(Constant.PKG, 0).versionCode); } return hours; case HttpURLConnection.HTTP_INTERNAL_ERROR: errorMessage = this.context.getString(R.string.error_http_500_and_source, this.context.getString(R.string.select_next_stop_data_source)); default: MyLog.w(TAG, "ERROR: HTTP URL-Connection Response Code %s (Message: %s)", httpUrlConnection.getResponseCode(), httpUrlConnection.getResponseMessage()); hours.put(lineNumber, new BusStopHours(SOURCE_NAME, errorMessage)); return hours; } } catch (UnknownHostException uhe) { MyLog.w(TAG, uhe, "No Internet Connection!"); publishProgress(this.context.getString(R.string.no_internet)); hours.put(lineNumber, new BusStopHours(SOURCE_NAME, this.context.getString(R.string.no_internet))); return hours; } catch (SocketException se) { MyLog.w(TAG, se, "No Internet Connection!"); publishProgress(this.context.getString(R.string.no_internet)); hours.put(lineNumber, new BusStopHours(SOURCE_NAME, this.context.getString(R.string.no_internet))); return hours; } catch (Exception e) { MyLog.e(TAG, e, "INTERNAL ERROR: Unknown Exception"); publishProgress(errorMessage); hours.put(lineNumber, new BusStopHours(SOURCE_NAME, this.context.getString(R.string.error))); return hours; } } /** * The pattern to extract the bus line number from the HTML source. */ private static final Pattern PATTERN_REGEX_LINE_NUMBER = Pattern .compile("<td[^>]*>(<b[^>]*>)?([0-9]{1,3})(</b>)?</td>"); /** * @param html the HTML source * @return the bus line number included in the HTML source */ private Set<String> findAllBusLines(String html) { MyLog.v(TAG, "findAllBusLines(%s)", html.length()); Set<String> result = new HashSet<String>(); Matcher matcher = PATTERN_REGEX_LINE_NUMBER.matcher(html); while (matcher.find()) { result.add(matcher.group(2)); } return result; } /** * The pattern for the hours. */ private static final Pattern PATTERN_REGEX_FOR_HOURS = Pattern.compile("[0-9]{1,2}[h|:][0-9]{1,2}"); /** * Extract bus stops hours + messages from HTML code. * @param html the HTML code * @param lineNumber the line number */ private BusStopHours getBusStopHoursFromString(String html, String lineNumber) { MyLog.v(TAG, "getBusStopHoursFromString(%s, %s)", html.length(), lineNumber); BusStopHours result = new BusStopHours(SOURCE_NAME); String interestingPart = getInterestingPart(html, lineNumber); // MyLog.d(TAG, "interestingPart:" + interestingPart); if (interestingPart != null) { // find hours Matcher matcher = PATTERN_REGEX_FOR_HOURS.matcher(interestingPart); while (matcher.find()) { // considering 00h00 the standard (instead of the 00:00 provided by m.stm.info in English) String hour = matcher.group().replaceAll(":", "h"); // MyLog.d(TAG, "hour:" + hour); result.addSHour(hour); } // find main message String message = findMessage(interestingPart); if (!TextUtils.isEmpty(message)) { result.addMessageString(message); } // find onClick message Map<String, List<String>> onClickMessages = findOnClickMessages(interestingPart); if (onClickMessages.size() > 0) { if (onClickMessages.size() == 1 && onClickMessages.values().iterator().next().size() == result.getSHours().size()) { // only one message concerning all bus stops result.addMessage2String(onClickMessages.keySet().iterator().next()); } else { String msg = ""; for (String onClickMessage : onClickMessages.keySet()) { List<String> hours = onClickMessages.get(onClickMessage); if (hours != null & hours.size() > 0) { String concernedBusStops = ""; for (String hour : hours) { if (concernedBusStops.length() > 0) { concernedBusStops += " "; } concernedBusStops += hour; } msg = context.getString(R.string.next_bus_stops_note, concernedBusStops, onClickMessage); } else { msg = onClickMessage; } if (result.getMessage().length() <= 0) { result.addMessageString(msg); } else { result.addMessage2String(msg); } } } } } else { MyLog.w(TAG, "Can't find the next bus stops for line %s!", lineNumber); // try to find error API String errorAPIMsg = getErrorAPIMsg(html); if (!TextUtils.isEmpty(errorAPIMsg)) { result.setError(errorAPIMsg); } } MyLog.d(TAG, "result:" + result.serialized()); return result; } /** * The pattern used to extract API error message from HTML code. */ private static final Pattern PATTERN_REGEX_ERROR_API = Pattern .compile("<div id=\"panErreurApi\">[\\s]*<span id=\"lblErreurApi\"[^>]*>(<b[^>]*>)?(<font[^>]*>)?(([^<])*)(</font>)?(</b>)?</span>"); /** * Extract API error message from HTML code. * @param html the HTML code * @return the API error message or <b>NULL</b> */ private String getErrorAPIMsg(String html) { MyLog.v(TAG, "getErrorAPIMsg(%s)", html.length()); String result = null; Matcher matcher = PATTERN_REGEX_ERROR_API.matcher(html); if (matcher.find()) { result = matcher.group(3); } return result; } /** * The pattern used to extract stops message. */ private static final Pattern PATTERN_REGEX_ONCLICK_MESSAGE = Pattern .compile("<a href\\=javascript\\:void\\(0\\) onclick=\"" + "AfficherMessage\\('(([^'])*)'\\)" + "\">(([^<])*)</a>"); // "AfficherMessage\\('(([^'])*)'\\)"); /** * Extract stops message from interesting part of HTML code. * @param interestingPart the interesting part of HTML code * @return a map of message and related stops */ private Map<String, List<String>> findOnClickMessages(String interestingPart) { MyLog.v(TAG, "findOnClickMessage(%s)", interestingPart.length()); Map<String, List<String>> res = new HashMap<String, List<String>>(); Matcher matcher = PATTERN_REGEX_ONCLICK_MESSAGE.matcher(interestingPart); String message; String hour; while (matcher.find()) { message = matcher.group(1); hour = Utils.formatHours(context, matcher.group(3).replaceAll(":", "h")); if (!res.containsKey(message)) { res.put(message, new ArrayList<String>()); } res.get(message).add(hour); } return res; } /** * The pattern used for stop global message. */ private static final Pattern PATTERN_REGEX_NOTE_MESSAGE = Pattern.compile("<tr>[\\s]*" + "<td[^>]*>(<IMG[^>]*>)?[^<]*</td>" + "<td[^>]*>(<b[^>]*>)?[^<]*" + "(</b>)?</td>" + "<td[^>]*>(<b[^>]*>)?[^<]*(</b>)?</td>" + "<td[^>]*>(([^<])*)</td>[\\s]*</tr>"); /** * Find the global bus stop in the interesting part of HTML code. * @param interestingPart the interesting part of HTML code * @return the message or <b>NULL</b> */ private String findMessage(String interestingPart) { MyLog.v(TAG, "findMessage(%s)", interestingPart.length()); String result = null; Matcher matcher = PATTERN_REGEX_NOTE_MESSAGE.matcher(interestingPart); if (matcher.find()) { result = matcher.group(6); } return result; } /** * Find the interesting part of HTML code related to a specific bus line number. * @param html the HTML code * @param lineNumber the bus line number * @return the interesting part of HTML code */ private String getInterestingPart(String html, String lineNumber) { MyLog.v(TAG, "getInterestingPart(%s, %s)", html.length(), lineNumber); String result = null; String regex = "<tr>[\\s]*" + "<td[^>]*>(<IMG[^>]*>)?[^<]*</td>" + "<td[^>]*>(<b[^>]*>)?" + lineNumber + "(</b>)?</td>" + "<td[^>]*>(<b[^>]*>)?[^<]*(</b>)?</td>" + "(" + "<td[^>]*>[<a[^>]*>]?[^<]*[</a>]?[^<]*</td>" + "){0,6}[\\s]*</tr>"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(html); if (matcher.find()) { result = matcher.group(); } return result; } @Override public String getTag() { return TAG; } }
false
true
protected Map<String, BusStopHours> doInBackground(StmStore.BusStop... busStops) { String stopCode = busStops[0].getCode(); String lineNumber = busStops[0].getLineNumber(); Utils.logAppVersion(this.context); String errorMessage = this.context.getString(R.string.error); // set the default error message Map<String, BusStopHours> hours = new HashMap<String, BusStopHours>(); try { publishProgress(context.getString(R.string.downloading_data_from_and_source, StmInfoTask.SOURCE_NAME)); String urlString = URL_PART_1_BEFORE_LANG; if (Utils.getSupportedUserLocale().equals(Locale.FRENCH.toString())) { urlString += "Fr"; } else { urlString += "En"; } urlString += URL_PART_2_BEFORE_BUS_STOP + stopCode; URL url = new URL(urlString); URLConnection urlc = url.openConnection(); MyLog.d(TAG, "URL created: '%s'", url.toString()); HttpURLConnection httpUrlConnection = (HttpURLConnection) urlc; switch (httpUrlConnection.getResponseCode()) { case HttpURLConnection.HTTP_OK: String html = Utils.getInputStreamToString(urlc.getInputStream(), "iso-8859-1"); AnalyticsUtils.dispatch(context); // while we are connected, send the analytics data publishProgress(this.context.getResources().getString(R.string.processing_data)); // FOR each bus line DO for (String line : findAllBusLines(html)) { hours.put(line, getBusStopHoursFromString(html, line)); } // IF the targeted bus line was there DO if (hours.keySet().contains(lineNumber)) { publishProgress(this.context.getResources().getString(R.string.done)); } else { // no information errorMessage = this.context.getString(R.string.bus_stop_no_info_and_source, lineNumber, SOURCE_NAME); publishProgress(errorMessage); hours.put(lineNumber, new BusStopHours(SOURCE_NAME, errorMessage)); AnalyticsUtils.trackEvent(context, AnalyticsUtils.CATEGORY_ERROR, AnalyticsUtils.ACTION_BUS_STOP_REMOVED, busStops[0].getUID(), context.getPackageManager() .getPackageInfo(Constant.PKG, 0).versionCode); } return hours; case HttpURLConnection.HTTP_INTERNAL_ERROR: errorMessage = this.context.getString(R.string.error_http_500_and_source, this.context.getString(R.string.select_next_stop_data_source)); default: MyLog.w(TAG, "ERROR: HTTP URL-Connection Response Code %s (Message: %s)", httpUrlConnection.getResponseCode(), httpUrlConnection.getResponseMessage()); hours.put(lineNumber, new BusStopHours(SOURCE_NAME, errorMessage)); return hours; } } catch (UnknownHostException uhe) { MyLog.w(TAG, uhe, "No Internet Connection!"); publishProgress(this.context.getString(R.string.no_internet)); hours.put(lineNumber, new BusStopHours(SOURCE_NAME, this.context.getString(R.string.no_internet))); return hours; } catch (SocketException se) { MyLog.w(TAG, se, "No Internet Connection!"); publishProgress(this.context.getString(R.string.no_internet)); hours.put(lineNumber, new BusStopHours(SOURCE_NAME, this.context.getString(R.string.no_internet))); return hours; } catch (Exception e) { MyLog.e(TAG, e, "INTERNAL ERROR: Unknown Exception"); publishProgress(errorMessage); hours.put(lineNumber, new BusStopHours(SOURCE_NAME, this.context.getString(R.string.error))); return hours; } }
protected Map<String, BusStopHours> doInBackground(StmStore.BusStop... busStops) { MyLog.v(TAG, "doInBackground()"); Utils.logAppVersion(this.context); String errorMessage = this.context.getString(R.string.error); // set the default error message Map<String, BusStopHours> hours = new HashMap<String, BusStopHours>(); if (busStops==null || busStops.length == 0) { return null; } String stopCode = busStops[0].getCode(); String lineNumber = busStops[0].getLineNumber(); try { publishProgress(context.getString(R.string.downloading_data_from_and_source, StmInfoTask.SOURCE_NAME)); String urlString = URL_PART_1_BEFORE_LANG; if (Utils.getSupportedUserLocale().equals(Locale.FRENCH.toString())) { urlString += "Fr"; } else { urlString += "En"; } urlString += URL_PART_2_BEFORE_BUS_STOP + stopCode; URL url = new URL(urlString); URLConnection urlc = url.openConnection(); MyLog.d(TAG, "URL created: '%s'", url.toString()); HttpURLConnection httpUrlConnection = (HttpURLConnection) urlc; switch (httpUrlConnection.getResponseCode()) { case HttpURLConnection.HTTP_OK: String html = Utils.getInputStreamToString(urlc.getInputStream(), "iso-8859-1"); AnalyticsUtils.dispatch(context); // while we are connected, send the analytics data publishProgress(this.context.getResources().getString(R.string.processing_data)); // FOR each bus line DO for (String line : findAllBusLines(html)) { hours.put(line, getBusStopHoursFromString(html, line)); } // IF the targeted bus line was there DO if (hours.keySet().contains(lineNumber)) { publishProgress(this.context.getResources().getString(R.string.done)); } else { // no information errorMessage = this.context.getString(R.string.bus_stop_no_info_and_source, lineNumber, SOURCE_NAME); publishProgress(errorMessage); hours.put(lineNumber, new BusStopHours(SOURCE_NAME, errorMessage)); AnalyticsUtils.trackEvent(context, AnalyticsUtils.CATEGORY_ERROR, AnalyticsUtils.ACTION_BUS_STOP_REMOVED, busStops[0].getUID(), context.getPackageManager() .getPackageInfo(Constant.PKG, 0).versionCode); } return hours; case HttpURLConnection.HTTP_INTERNAL_ERROR: errorMessage = this.context.getString(R.string.error_http_500_and_source, this.context.getString(R.string.select_next_stop_data_source)); default: MyLog.w(TAG, "ERROR: HTTP URL-Connection Response Code %s (Message: %s)", httpUrlConnection.getResponseCode(), httpUrlConnection.getResponseMessage()); hours.put(lineNumber, new BusStopHours(SOURCE_NAME, errorMessage)); return hours; } } catch (UnknownHostException uhe) { MyLog.w(TAG, uhe, "No Internet Connection!"); publishProgress(this.context.getString(R.string.no_internet)); hours.put(lineNumber, new BusStopHours(SOURCE_NAME, this.context.getString(R.string.no_internet))); return hours; } catch (SocketException se) { MyLog.w(TAG, se, "No Internet Connection!"); publishProgress(this.context.getString(R.string.no_internet)); hours.put(lineNumber, new BusStopHours(SOURCE_NAME, this.context.getString(R.string.no_internet))); return hours; } catch (Exception e) { MyLog.e(TAG, e, "INTERNAL ERROR: Unknown Exception"); publishProgress(errorMessage); hours.put(lineNumber, new BusStopHours(SOURCE_NAME, this.context.getString(R.string.error))); return hours; } }
diff --git a/src/test/java/ru/histone/acceptance/tests/general/NodeNumberFunctionsTest.java b/src/test/java/ru/histone/acceptance/tests/general/NodeNumberFunctionsTest.java index a61db4f..1d35580 100644 --- a/src/test/java/ru/histone/acceptance/tests/general/NodeNumberFunctionsTest.java +++ b/src/test/java/ru/histone/acceptance/tests/general/NodeNumberFunctionsTest.java @@ -1,15 +1,15 @@ package ru.histone.acceptance.tests.general; import org.junit.runner.RunWith; import ru.histone.acceptance.support.AcceptanceTest; import ru.histone.acceptance.support.AcceptanceTestsRunner; @RunWith(AcceptanceTestsRunner.class) public class NodeNumberFunctionsTest extends AcceptanceTest { @Override public String getFileName() { - return "/general/node-number-functions.json"; + return "/general/number.toString.json"; } }
true
true
public String getFileName() { return "/general/node-number-functions.json"; }
public String getFileName() { return "/general/number.toString.json"; }
diff --git a/src/main/java/com/forum/repository/QuestionRepository.java b/src/main/java/com/forum/repository/QuestionRepository.java index c5d099b..2644f4c 100644 --- a/src/main/java/com/forum/repository/QuestionRepository.java +++ b/src/main/java/com/forum/repository/QuestionRepository.java @@ -1,104 +1,105 @@ package com.forum.repository; import com.forum.domain.Question; import com.forum.domain.Tag; import com.forum.domain.User; import java.util.logging.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import javax.sql.DataSource; import java.sql.Timestamp; import java.util.Date; import java.util.List; @Repository public class QuestionRepository { private JdbcTemplate jdbcTemplate; private static Logger logger = Logger.getLogger(QuestionRepository.class.getName()); @Autowired public QuestionRepository(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } public List<Question> getAllQuestions() { String query = "SELECT Q.ID AS QUESTION_ID, Q.TITLE, Q.DESCRIPTION," + " Q.CREATED_AT,Q.*, U.* FROM QUESTION Q JOIN USER U WHERE Q.USER_ID=U.ID ORDER BY Q.ID ASC; "; return jdbcTemplate.query(query,new QuestionRowMapper()); } public Question getById(Integer questionId) { String query = "SELECT Q.ID AS QUESTION_ID, Q.TITLE, Q.DESCRIPTION, " + "Q.CREATED_AT,Q.*, U.* FROM QUESTION Q JOIN USER U WHERE Q.USER_ID=U.ID AND Q.ID = ?"; return (Question) jdbcTemplate.queryForObject(query, new Object[]{questionId}, new QuestionRowMapper()); } public int createQuestion(Question question) { logger.info("question is " + question.toString()); int result =0; + Date createdDate = new Date(); result += jdbcTemplate.update("INSERT INTO QUESTION (TITLE, DESCRIPTION, CREATED_AT, USER_ID) VALUES (?, ?, ?, ?)", - new Object[]{question.getTitle(), question.getDescription(), new Date(), question.getUser().getId()}); + new Object[]{question.getTitle(), question.getDescription(), createdDate, question.getUser().getId()}); for (Tag tag : question.getTags()){ int tagCheck = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM TAG WHERE NAME = ?", tag.getValue()); if(tagCheck == 0){ result += jdbcTemplate.update("INSERT INTO TAG (NAME) VALUES (?)", tag.getValue()); } - int questionID = jdbcTemplate.queryForInt("SELECT ID FROM QUESTION WHERE TITLE = ?", question.getTitle()); + int questionID = jdbcTemplate.queryForInt("SELECT ID FROM QUESTION WHERE TITLE = ? AND CREATED_AT = ? AND USER_ID = ?", question.getTitle(),createdDate,question.getUser().getId()); int tagID = jdbcTemplate.queryForInt("SELECT ID FROM TAG WHERE NAME = ?", tag.getValue()); result += jdbcTemplate.update("INSERT INTO QUESTION_TAG (QUESTION_ID,TAG_ID) VALUES (?,?)", questionID,tagID); } return result; } public List<Question> latestQuestion(int pageNum, int pageSize) { int pageStart = (pageNum - 1) * pageSize; String query = "SELECT Q.ID AS QUESTION_ID, Q.TITLE, Q.DESCRIPTION, " + "Q.CREATED_AT,Q.*, U.* FROM QUESTION Q JOIN USER U WHERE Q.USER_ID=U.ID " + "ORDER BY Q.CREATED_AT DESC LIMIT ?,?"; return jdbcTemplate.query(query, new Object[]{pageStart, pageSize}, new QuestionRowMapper()); } public int getNumberOfQuestionBetweenTimes(Timestamp beginningTime, Timestamp endingTime) { int numberOfQuestionInADay = 0; QuestionRowMapper rowMapper = new QuestionRowMapper(); String query = "SELECT COUNT(ID) FROM QUESTION where CREATED_AT >= ? AND CREATED_AT <= ?"; numberOfQuestionInADay = jdbcTemplate.queryForInt(query, new Object[]{beginningTime, endingTime}); return numberOfQuestionInADay; } public int addLikesById(Integer questionId) { String query = "UPDATE QUESTION SET LIKES=LIKES+1 WHERE ID=?"; return jdbcTemplate.update(query, new Object[]{questionId}); } public int addDisLikesById(Integer questionId) { String query = "UPDATE QUESTION SET DISLIKES=DISLIKES+1 WHERE ID=?"; return jdbcTemplate.update(query, new Object[]{questionId}); } public int addFlagsById(Integer questionId) { String query = "UPDATE QUESTION SET FLAGS=FLAGS+1 WHERE ID=?"; return jdbcTemplate.update(query, new Object[]{questionId}); } }
false
true
public int createQuestion(Question question) { logger.info("question is " + question.toString()); int result =0; result += jdbcTemplate.update("INSERT INTO QUESTION (TITLE, DESCRIPTION, CREATED_AT, USER_ID) VALUES (?, ?, ?, ?)", new Object[]{question.getTitle(), question.getDescription(), new Date(), question.getUser().getId()}); for (Tag tag : question.getTags()){ int tagCheck = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM TAG WHERE NAME = ?", tag.getValue()); if(tagCheck == 0){ result += jdbcTemplate.update("INSERT INTO TAG (NAME) VALUES (?)", tag.getValue()); } int questionID = jdbcTemplate.queryForInt("SELECT ID FROM QUESTION WHERE TITLE = ?", question.getTitle()); int tagID = jdbcTemplate.queryForInt("SELECT ID FROM TAG WHERE NAME = ?", tag.getValue()); result += jdbcTemplate.update("INSERT INTO QUESTION_TAG (QUESTION_ID,TAG_ID) VALUES (?,?)", questionID,tagID); } return result; }
public int createQuestion(Question question) { logger.info("question is " + question.toString()); int result =0; Date createdDate = new Date(); result += jdbcTemplate.update("INSERT INTO QUESTION (TITLE, DESCRIPTION, CREATED_AT, USER_ID) VALUES (?, ?, ?, ?)", new Object[]{question.getTitle(), question.getDescription(), createdDate, question.getUser().getId()}); for (Tag tag : question.getTags()){ int tagCheck = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM TAG WHERE NAME = ?", tag.getValue()); if(tagCheck == 0){ result += jdbcTemplate.update("INSERT INTO TAG (NAME) VALUES (?)", tag.getValue()); } int questionID = jdbcTemplate.queryForInt("SELECT ID FROM QUESTION WHERE TITLE = ? AND CREATED_AT = ? AND USER_ID = ?", question.getTitle(),createdDate,question.getUser().getId()); int tagID = jdbcTemplate.queryForInt("SELECT ID FROM TAG WHERE NAME = ?", tag.getValue()); result += jdbcTemplate.update("INSERT INTO QUESTION_TAG (QUESTION_ID,TAG_ID) VALUES (?,?)", questionID,tagID); } return result; }
diff --git a/trunk/src/om/stdquestion/QContent.java b/trunk/src/om/stdquestion/QContent.java index cd57f5f..b5be479 100644 --- a/trunk/src/om/stdquestion/QContent.java +++ b/trunk/src/om/stdquestion/QContent.java @@ -1,380 +1,379 @@ /* OpenMark online assessment system Copyright (C) 2007 The Open University 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 om.stdquestion; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.*; import java.util.regex.Pattern; import javax.imageio.ImageIO; import om.OmDeveloperException; import om.OmUnexpectedException; import om.question.Resource; import org.w3c.dom.*; import util.xml.XML; /** * Represents current content provided by a question component for use in * output to user. */ public class QContent { /** Output document, used for creating elements etc */ private Document dOutput; /** Element that marks root of stuff which is added inline */ private Element eInlineRoot; /** First node that was added to top level */ private Node nFirstTopLevel=null; /** * Stack of Element; top item is current parent that new nodes should be * added to. */ private Stack<Element> sParents=new Stack<Element>(); /** List of returned resources (QResource) */ private List<Resource> lResources=new LinkedList<Resource>(); /** Stack of text-mode StringBuffers, zero-length if not in text mode */ private Stack<StringBuffer> sTextMode=new Stack<StringBuffer>(); /** MIME type for PNG images */ public final static String MIME_PNG="image/png"; /** Regex matcher for legal filenames */ private final static Pattern FILENAMES=Pattern.compile("^[a-z0-9-_.]+$"); /** * Constructs blank question content. * @param dOutput Output document, used for creating elements etc */ public QContent(Document dOutput) { this.dOutput=dOutput; eInlineRoot=dOutput.createElement("div"); eInlineRoot.setAttribute("id","om"); eInlineRoot.setAttribute("class","om"); sParents.push(eInlineRoot); } /** @return Output document, used for creating elements etc */ public Document getOutputDocument() { return dOutput; } /** * Creates element using output document. (Just a shortcut.) * @param sTagName Tag name of desired element * @return New element */ public Element createElement(String sTagName) { return dOutput.createElement(sTagName); } /** @return Output XHTML element (div tag w/ id='om') */ public Element getXHTML() { return eInlineRoot; } /** @return List of added resources */ public Resource[] getResources() { return lResources.toArray(new Resource[0]); } /** * Checks that a node comes from the right document. * @param n Input node * @throws OmDeveloperException If the node came from somewhere else */ private void checkNode(Node n) throws OmDeveloperException { if(n.getOwnerDocument()!=getOutputDocument()) throw new IllegalArgumentException( "Node must be created with owner document from QContent"); } /** * Call to add an XHTML node that will be placed in the document flow at the place * where this component is positioned. * @param n Root node of content, which should've been created with respect * to the getDocument(). Content will not be cloned, so be sure to create it * afresh each time. * @throws OmDeveloperException */ public void addInlineXHTML(Node n) throws OmDeveloperException { if(!sTextMode.empty()) return; // Ignore in text mode checkNode(n); Element eParent=sParents.peek(); if(eParent==eInlineRoot && nFirstTopLevel!=null) { // Make sure it stays before the 'at end' stuff eParent.insertBefore(n,nFirstTopLevel); } else { eParent.appendChild(n); } } /** * Sets the parent for any calls from now on. After this call, ensure that * unsetParent is always called precisely once, unless an exception is * thrown. * @param e New parent element (must have been added already as part of * addInlineXHTML call!) */ public void setParent(Element e) { if(!sTextMode.empty()) return; // Ignore in text mode sParents.push(e); } /** * Unsets the parent, returning to previous parent. */ public void unsetParent() { if(!sTextMode.empty()) return; // Ignore in text mode sParents.pop(); } /** * Call to set XHTML that will be placed at the top level in the output * document (i.e. at the end of, and a direct child of, the question div). * @param n Root node of content, which should've been created with respect * to the getDocument(). Content will not be cloned, so be sure to create it * afresh each time. * @throws OmDeveloperException */ public void addTopLevelXHTML(Node n) throws OmDeveloperException { if(!sTextMode.empty()) return; // Ignore in text mode checkNode(n); eInlineRoot.appendChild(n); if(nFirstTopLevel==null) nFirstTopLevel=n; } /** * Adds a resource to the output. * <p> * A question does not need to add the same resource more than once within its * lifecycle, i.e. resources do not need to be added with every request. * You may not add a second resource with the same name as a first, unless it * is identical. * @param sFilename Resource filename * @param sMimeType MIME type of resource (see QContent.MIME* constants) * @param abContent Content of resource (QContent.convert*() or QContent.loadResource() may help here) * @throws IllegalArgumentException If the filename isn't valid */ public void addResource( String sFilename,String sMimeType,byte[] abContent) throws IllegalArgumentException { if(!sTextMode.empty()) return; // Ignore in text mode, don't need resources if(!FILENAMES.matcher(sFilename).matches()) throw new IllegalArgumentException("Not a valid resource filename: "+sFilename); - for(Iterator i=lResources.iterator();i.hasNext();) + for(Resource r : lResources) { - Resource r=(Resource)i.next(); if(r.getFilename().equals(sFilename)) { if(!Arrays.equals(abContent,r.getContent())) { throw new IllegalArgumentException( "A different resource has already been added with this filename: "+sFilename); } // OK it was the same, don't add it again return; } } lResources.add(new Resource(sFilename,sMimeType,abContent)); } /** * Adds a resource to the output, loading it from the same location as the * specified reference class file. (This is a shortcut for calling loadResource * and the other addResource method.) * <p> * A question does not need to add the same resource more than once within its * lifecycle, i.e. resources do not need to be added with every request. * You may not add a second resource with the same name as a first, unless it * is identical. * @param sq Question to load resource from * @param sFilename Resource filename or path * @param sMimeType MIME type of resource (see QContent.MIME* constants) * @throws IOException * @throws IllegalArgumentException If the filename isn't valid */ public void addResource( StandardQuestion sq,String sFilename,String sMimeType) throws IOException,IllegalArgumentException { addResource(sFilename,sMimeType,sq.loadResource(sFilename)); } /** * Informs the system that a given XHTML element may be focused on page load. * (This causes appropriate Javascript to be written so that the first such * candidate is focused. The point of doing it here is that components don't * need to know whether they are first or not.) * @param sID ID that will be stored along with the object (for use in JS) * @param sJSObjectExpression JS expression that will obtain object * e.g. document.getElementById('..') - but use the other method if you * just want that behaviour. Expression may contain single, but not double, * quotes (unless you escape double quotes). * @param bPlain True if in plain mode (causes nothing to happen) * @throws OmDeveloperException */ public void informFocusableFullJS(String sID,String sJSObjectExpression,boolean bPlain) throws OmDeveloperException { if(!sTextMode.empty()) return; // Ignore in text mode, definitely not focusable if(bPlain) return; Element eScript=createElement("script"); eScript.setAttribute("type","text/javascript"); XML.createText(eScript,"addFocusable('"+sID+"','"+ sJSObjectExpression.replaceAll("'","\\\\'")+"');"); addInlineXHTML(eScript); } /** * Informs the system that a given XHTML element may be focused on page load. * (This causes appropriate Javascript to be written so that the first such * candidate is focused. The point of doing it here is that components don't * need to know whether they are first or not.) * @param sXHTMLID ID (within XHTML id attribute) of the element that should * be focused * @param bPlain True if in plain mode (causes nothing to happen) * @throws OmDeveloperException */ public void informFocusable(String sXHTMLID,boolean bPlain) throws OmDeveloperException { informFocusableFullJS(sXHTMLID,"document.getElementById('"+sXHTMLID+"')",bPlain); } /** * Converts an image to a PNG file. * @param bi BufferedImage to convert * @return PNG data * @throws OmUnexpectedException Any error in conversion (shouldn't happen, but...) */ public static byte[] convertPNG(BufferedImage bi) throws OmUnexpectedException { try { ByteArrayOutputStream baos=new ByteArrayOutputStream(); ImageIO.setUseCache(false); if(!ImageIO.write(bi,"png",baos)) throw new IOException("No image writer for PNG"); return baos.toByteArray(); } catch(IOException ioe) { throw new OmUnexpectedException(ioe); } } /** * Converts an image to a .jpg file using default compression level. * @param bi BufferedImage to convert * @return JPG data * @throws OmUnexpectedException Any error in conversion (shouldn't happen, but...) */ public static byte[] convertJPG(BufferedImage bi) throws OmUnexpectedException { try { ByteArrayOutputStream baos=new ByteArrayOutputStream(); ImageIO.setUseCache(false); if(!ImageIO.write(bi,"jpg",baos)) throw new IOException("No image writer for JPG"); return baos.toByteArray(); } catch(IOException ioe) { throw new OmUnexpectedException(ioe); } } /** * Turns on text mode, in which any XHTML changes are ignored, and * we start building up the text-equivalent string instead. * <p> * Nesting text mode (calling beginTextMode when already in text mode) is * OK, this starts a separate nested text-equivalent buffer. Begin and end * calls must be paired. */ public void beginTextMode() { sTextMode.push(new StringBuffer()); } /** * Call to add text equivalent. All components should support text equivalents * by using this method as well as addInlineXHTML(). * <p> * The system will automatically add whitespace at the end of this string as * necessary so that text from different components doesn't run together. * @param s Text to add */ public void addTextEquivalent(String s) { // Ignore unless in text mode if(sTextMode.empty()) return; // Ignore empty strings if(s.length()==0) return; StringBuffer sb=sTextMode.peek(); // Add string followed by space if it hasn't got one (so sbTextMode always // ends with whitespace - we trim this later) sb.append(s); if(!Character.isWhitespace(s.charAt(s.length()-1))) sb.append(" "); } /** * Turns off text mode. From this point on, XHTML changes will be included * and text-equivalent strings ignored again. (Unless it's nested in text * mode more than once.) * @return The trimmed contents of the text-equivalent string that was * built up since the beginTextMode() call * @throws OmDeveloperException If you aren't in text mode */ public String endTextMode() throws OmDeveloperException { if(sTextMode.empty()) throw new OmDeveloperException("Not in text mode"); StringBuffer sb=sTextMode.pop(); return sb.toString().trim().replaceAll("\\s+"," "); } }
false
true
public void addResource( String sFilename,String sMimeType,byte[] abContent) throws IllegalArgumentException { if(!sTextMode.empty()) return; // Ignore in text mode, don't need resources if(!FILENAMES.matcher(sFilename).matches()) throw new IllegalArgumentException("Not a valid resource filename: "+sFilename); for(Iterator i=lResources.iterator();i.hasNext();) { Resource r=(Resource)i.next(); if(r.getFilename().equals(sFilename)) { if(!Arrays.equals(abContent,r.getContent())) { throw new IllegalArgumentException( "A different resource has already been added with this filename: "+sFilename); } // OK it was the same, don't add it again return; } } lResources.add(new Resource(sFilename,sMimeType,abContent)); }
public void addResource( String sFilename,String sMimeType,byte[] abContent) throws IllegalArgumentException { if(!sTextMode.empty()) return; // Ignore in text mode, don't need resources if(!FILENAMES.matcher(sFilename).matches()) throw new IllegalArgumentException("Not a valid resource filename: "+sFilename); for(Resource r : lResources) { if(r.getFilename().equals(sFilename)) { if(!Arrays.equals(abContent,r.getContent())) { throw new IllegalArgumentException( "A different resource has already been added with this filename: "+sFilename); } // OK it was the same, don't add it again return; } } lResources.add(new Resource(sFilename,sMimeType,abContent)); }
diff --git a/processor/src/main/java/org/apache/camel/processor/mashup/core/MashupProcessor.java b/processor/src/main/java/org/apache/camel/processor/mashup/core/MashupProcessor.java index 02af35c..a56d5b0 100644 --- a/processor/src/main/java/org/apache/camel/processor/mashup/core/MashupProcessor.java +++ b/processor/src/main/java/org/apache/camel/processor/mashup/core/MashupProcessor.java @@ -1,174 +1,174 @@ package org.apache.camel.processor.mashup.core; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.processor.mashup.api.IExtractor; import org.apache.camel.processor.mashup.model.*; import org.apache.commons.beanutils.*; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileInputStream; /** * Camel processor loading the navigation file and extract data */ public class MashupProcessor implements Processor { private final static transient Logger LOGGER = LoggerFactory.getLogger(MashupProcessor.class); public final static String DEFAULT_STORE = "data/mashup"; public final static String MASHUP_ID_HEADER = "MASHUP_ID"; public final static String MASHUP_STORE_HEADER = "MASHUP_STORE"; public void process(Exchange exchange) throws Exception { LOGGER.trace("Get the Camel in message"); Message in = exchange.getIn(); LOGGER.trace("Get the Camel out message"); Message out = exchange.getOut(); LOGGER.trace("Get the {} header", MASHUP_ID_HEADER); String mashupId = (String) in.getHeader(MASHUP_ID_HEADER); LOGGER.debug("Mashup ID: {}", mashupId); LOGGER.trace("Get the {} header", MASHUP_STORE_HEADER); String store = (String) in.getHeader(MASHUP_STORE_HEADER); LOGGER.debug("Mashup Store: {}", store); LOGGER.debug("Digesting the navigation file {}/{}.xml", store, mashupId); FileInputStream fileInputStream = new FileInputStream(store + "/" + mashupId + ".xml"); Mashup mashup = new Mashup(); mashup.digeste(fileInputStream); LOGGER.trace("Create the HTTP client"); DefaultHttpClient httpClient = new DefaultHttpClient(); CookieStore cookieStore = CookieStore.getInstance(); LOGGER.trace("Iterate in the pages"); for (Page page : mashup.getPages()) { LOGGER.trace("Replacing the headers in the URL"); String url = page.getUrl(); for (String header : in.getHeaders().keySet()) { - url.replace("%" + header + "%", (String) in.getHeader(header)); + url.replace("%" + header + "%", in.getHeader(header).toString()); } LOGGER.trace("Constructing the HTTP request"); HttpUriRequest request = null; if (page.getMethod() != null && page.getMethod().equalsIgnoreCase("POST")) { request = new HttpPost(url); } else { request = new HttpGet(url); } if (mashup.getCookie() != null) { LOGGER.trace("Looking for an existing cookie"); String cookieKey = (String) in.getHeader(mashup.getCookie().getKey()); if (cookieKey == null) { LOGGER.warn("Cookie key " + mashup.getCookie().getKey() + " is not found in the Camel \"in\" header"); } else { BasicClientCookie basicClientCookie = cookieStore.getCookie(cookieKey); if (basicClientCookie == null) { LOGGER.debug("No cookie yet exist for " + cookieKey); } else { LOGGER.debug("A cookie exists for " + cookieKey + " use it for the request"); BasicCookieStore basicCookieStore = new BasicCookieStore(); basicCookieStore.addCookie(basicClientCookie); httpClient.setCookieStore(basicCookieStore); } } } else { LOGGER.warn("No cookie configuration defined"); } HttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); if (mashup.getCookie() != null) { String cookieKey = (String) in.getHeader(mashup.getCookie().getKey()); if (cookieKey == null) { LOGGER.warn("Cookie key " + mashup.getCookie().getKey() + " is not found i nthe Camel \"in\" header"); } else { LOGGER.trace("Populating the cookie store"); Header[] headers = response.getHeaders("Set-Cookie"); for (Header header : headers) { if (header.getName().equals(mashup.getCookie().getName())) { BasicClientCookie basicClientCookie = new BasicClientCookie(mashup.getCookie().getName(), header.getValue()); basicClientCookie.setDomain(mashup.getCookie().getDomain()); basicClientCookie.setPath(mashup.getCookie().getPath()); cookieStore.addCookie(cookieKey, basicClientCookie); break; } } } } if (page.getExtractors() != null && page.getExtractors().size() > 0) { LOGGER.trace("Populate content to be used by extractors"); String content = EntityUtils.toString(entity); try { for (Extractor extractor : page.getExtractors()) { IExtractor extractorBean = this.instantiateExtractor(extractor); String extractedData = extractorBean.extract(content); if (extractor.isMandatory() && (extractedData == null || extractedData.isEmpty())) { throw new IllegalStateException("Extracted data is empty"); } if (extractor.isAppend()) { out.setBody(out.getBody() + "<extract id=\"" + extractor.getId() + "\"><![CDATA[" + extractedData + "]]></extract>"); } } } catch (Exception e) { LOGGER.warn("An exception occurs during the extraction",e); LOGGER.warn("Calling the error handler"); exchange.setException(e); out.setFault(true); out.setBody(null); if (page.getErrorHandler() != null && page.getErrorHandler().getExtractors() != null && page.getErrorHandler().getExtractors().size() > 0) { LOGGER.trace("Processing the error handler extractor"); for (Extractor extractor : page.getErrorHandler().getExtractors()) { IExtractor extractorBean = this.instantiateExtractor(extractor); String extractedData = extractorBean.extract(content); if (extractedData != null) { out.setBody(out.getBody() + extractedData); } } } } } } } /** * Create a new instance of a extractor * * @param extractor the extractor model object. * @return the IExtractor object. */ protected IExtractor instantiateExtractor(Extractor extractor) throws Exception { LOGGER.trace("Create new instance of " + extractor.getClazz() + "extractor"); Class extractorClass = Class.forName(extractor.getClazz()); IExtractor extractorBean = (IExtractor) extractorClass.newInstance(); if (extractor.getProperties() != null) { for (Property property : extractor.getProperties()) { LOGGER.trace("Setting property " + property.getName() + " with value " + property.getValue()); PropertyUtils.setProperty(extractorBean, property.getName(), property.getValue()); } } return extractorBean; } }
true
true
public void process(Exchange exchange) throws Exception { LOGGER.trace("Get the Camel in message"); Message in = exchange.getIn(); LOGGER.trace("Get the Camel out message"); Message out = exchange.getOut(); LOGGER.trace("Get the {} header", MASHUP_ID_HEADER); String mashupId = (String) in.getHeader(MASHUP_ID_HEADER); LOGGER.debug("Mashup ID: {}", mashupId); LOGGER.trace("Get the {} header", MASHUP_STORE_HEADER); String store = (String) in.getHeader(MASHUP_STORE_HEADER); LOGGER.debug("Mashup Store: {}", store); LOGGER.debug("Digesting the navigation file {}/{}.xml", store, mashupId); FileInputStream fileInputStream = new FileInputStream(store + "/" + mashupId + ".xml"); Mashup mashup = new Mashup(); mashup.digeste(fileInputStream); LOGGER.trace("Create the HTTP client"); DefaultHttpClient httpClient = new DefaultHttpClient(); CookieStore cookieStore = CookieStore.getInstance(); LOGGER.trace("Iterate in the pages"); for (Page page : mashup.getPages()) { LOGGER.trace("Replacing the headers in the URL"); String url = page.getUrl(); for (String header : in.getHeaders().keySet()) { url.replace("%" + header + "%", (String) in.getHeader(header)); } LOGGER.trace("Constructing the HTTP request"); HttpUriRequest request = null; if (page.getMethod() != null && page.getMethod().equalsIgnoreCase("POST")) { request = new HttpPost(url); } else { request = new HttpGet(url); } if (mashup.getCookie() != null) { LOGGER.trace("Looking for an existing cookie"); String cookieKey = (String) in.getHeader(mashup.getCookie().getKey()); if (cookieKey == null) { LOGGER.warn("Cookie key " + mashup.getCookie().getKey() + " is not found in the Camel \"in\" header"); } else { BasicClientCookie basicClientCookie = cookieStore.getCookie(cookieKey); if (basicClientCookie == null) { LOGGER.debug("No cookie yet exist for " + cookieKey); } else { LOGGER.debug("A cookie exists for " + cookieKey + " use it for the request"); BasicCookieStore basicCookieStore = new BasicCookieStore(); basicCookieStore.addCookie(basicClientCookie); httpClient.setCookieStore(basicCookieStore); } } } else { LOGGER.warn("No cookie configuration defined"); } HttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); if (mashup.getCookie() != null) { String cookieKey = (String) in.getHeader(mashup.getCookie().getKey()); if (cookieKey == null) { LOGGER.warn("Cookie key " + mashup.getCookie().getKey() + " is not found i nthe Camel \"in\" header"); } else { LOGGER.trace("Populating the cookie store"); Header[] headers = response.getHeaders("Set-Cookie"); for (Header header : headers) { if (header.getName().equals(mashup.getCookie().getName())) { BasicClientCookie basicClientCookie = new BasicClientCookie(mashup.getCookie().getName(), header.getValue()); basicClientCookie.setDomain(mashup.getCookie().getDomain()); basicClientCookie.setPath(mashup.getCookie().getPath()); cookieStore.addCookie(cookieKey, basicClientCookie); break; } } } } if (page.getExtractors() != null && page.getExtractors().size() > 0) { LOGGER.trace("Populate content to be used by extractors"); String content = EntityUtils.toString(entity); try { for (Extractor extractor : page.getExtractors()) { IExtractor extractorBean = this.instantiateExtractor(extractor); String extractedData = extractorBean.extract(content); if (extractor.isMandatory() && (extractedData == null || extractedData.isEmpty())) { throw new IllegalStateException("Extracted data is empty"); } if (extractor.isAppend()) { out.setBody(out.getBody() + "<extract id=\"" + extractor.getId() + "\"><![CDATA[" + extractedData + "]]></extract>"); } } } catch (Exception e) { LOGGER.warn("An exception occurs during the extraction",e); LOGGER.warn("Calling the error handler"); exchange.setException(e); out.setFault(true); out.setBody(null); if (page.getErrorHandler() != null && page.getErrorHandler().getExtractors() != null && page.getErrorHandler().getExtractors().size() > 0) { LOGGER.trace("Processing the error handler extractor"); for (Extractor extractor : page.getErrorHandler().getExtractors()) { IExtractor extractorBean = this.instantiateExtractor(extractor); String extractedData = extractorBean.extract(content); if (extractedData != null) { out.setBody(out.getBody() + extractedData); } } } } } } }
public void process(Exchange exchange) throws Exception { LOGGER.trace("Get the Camel in message"); Message in = exchange.getIn(); LOGGER.trace("Get the Camel out message"); Message out = exchange.getOut(); LOGGER.trace("Get the {} header", MASHUP_ID_HEADER); String mashupId = (String) in.getHeader(MASHUP_ID_HEADER); LOGGER.debug("Mashup ID: {}", mashupId); LOGGER.trace("Get the {} header", MASHUP_STORE_HEADER); String store = (String) in.getHeader(MASHUP_STORE_HEADER); LOGGER.debug("Mashup Store: {}", store); LOGGER.debug("Digesting the navigation file {}/{}.xml", store, mashupId); FileInputStream fileInputStream = new FileInputStream(store + "/" + mashupId + ".xml"); Mashup mashup = new Mashup(); mashup.digeste(fileInputStream); LOGGER.trace("Create the HTTP client"); DefaultHttpClient httpClient = new DefaultHttpClient(); CookieStore cookieStore = CookieStore.getInstance(); LOGGER.trace("Iterate in the pages"); for (Page page : mashup.getPages()) { LOGGER.trace("Replacing the headers in the URL"); String url = page.getUrl(); for (String header : in.getHeaders().keySet()) { url.replace("%" + header + "%", in.getHeader(header).toString()); } LOGGER.trace("Constructing the HTTP request"); HttpUriRequest request = null; if (page.getMethod() != null && page.getMethod().equalsIgnoreCase("POST")) { request = new HttpPost(url); } else { request = new HttpGet(url); } if (mashup.getCookie() != null) { LOGGER.trace("Looking for an existing cookie"); String cookieKey = (String) in.getHeader(mashup.getCookie().getKey()); if (cookieKey == null) { LOGGER.warn("Cookie key " + mashup.getCookie().getKey() + " is not found in the Camel \"in\" header"); } else { BasicClientCookie basicClientCookie = cookieStore.getCookie(cookieKey); if (basicClientCookie == null) { LOGGER.debug("No cookie yet exist for " + cookieKey); } else { LOGGER.debug("A cookie exists for " + cookieKey + " use it for the request"); BasicCookieStore basicCookieStore = new BasicCookieStore(); basicCookieStore.addCookie(basicClientCookie); httpClient.setCookieStore(basicCookieStore); } } } else { LOGGER.warn("No cookie configuration defined"); } HttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); if (mashup.getCookie() != null) { String cookieKey = (String) in.getHeader(mashup.getCookie().getKey()); if (cookieKey == null) { LOGGER.warn("Cookie key " + mashup.getCookie().getKey() + " is not found i nthe Camel \"in\" header"); } else { LOGGER.trace("Populating the cookie store"); Header[] headers = response.getHeaders("Set-Cookie"); for (Header header : headers) { if (header.getName().equals(mashup.getCookie().getName())) { BasicClientCookie basicClientCookie = new BasicClientCookie(mashup.getCookie().getName(), header.getValue()); basicClientCookie.setDomain(mashup.getCookie().getDomain()); basicClientCookie.setPath(mashup.getCookie().getPath()); cookieStore.addCookie(cookieKey, basicClientCookie); break; } } } } if (page.getExtractors() != null && page.getExtractors().size() > 0) { LOGGER.trace("Populate content to be used by extractors"); String content = EntityUtils.toString(entity); try { for (Extractor extractor : page.getExtractors()) { IExtractor extractorBean = this.instantiateExtractor(extractor); String extractedData = extractorBean.extract(content); if (extractor.isMandatory() && (extractedData == null || extractedData.isEmpty())) { throw new IllegalStateException("Extracted data is empty"); } if (extractor.isAppend()) { out.setBody(out.getBody() + "<extract id=\"" + extractor.getId() + "\"><![CDATA[" + extractedData + "]]></extract>"); } } } catch (Exception e) { LOGGER.warn("An exception occurs during the extraction",e); LOGGER.warn("Calling the error handler"); exchange.setException(e); out.setFault(true); out.setBody(null); if (page.getErrorHandler() != null && page.getErrorHandler().getExtractors() != null && page.getErrorHandler().getExtractors().size() > 0) { LOGGER.trace("Processing the error handler extractor"); for (Extractor extractor : page.getErrorHandler().getExtractors()) { IExtractor extractorBean = this.instantiateExtractor(extractor); String extractedData = extractorBean.extract(content); if (extractedData != null) { out.setBody(out.getBody() + extractedData); } } } } } } }
diff --git a/src/tests/com/puppycrawl/tools/checkstyle/checks/j2ee/HomeInterfaceCheckTest.java b/src/tests/com/puppycrawl/tools/checkstyle/checks/j2ee/HomeInterfaceCheckTest.java index a2717703..9a279240 100644 --- a/src/tests/com/puppycrawl/tools/checkstyle/checks/j2ee/HomeInterfaceCheckTest.java +++ b/src/tests/com/puppycrawl/tools/checkstyle/checks/j2ee/HomeInterfaceCheckTest.java @@ -1,24 +1,21 @@ package com.puppycrawl.tools.checkstyle.checks.j2ee; import com.puppycrawl.tools.checkstyle.BaseCheckTestCase; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; public class HomeInterfaceCheckTest extends BaseCheckTestCase { public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RemoteHomeInterfaceCheck.class); final String[] expected = { - "14:18: Home interface 'InputHomeInterface' must have method 'findByPrimaryKey()'.", "20:19: Method 'createSomething' must be non-void.", "20:19: Method 'createSomething' must throw 'java.rmi.RemoteException'.", "20:19: Method 'createSomething' must throw 'javax.ejb.CreateException'.", - "22:19: Method 'findSomething' must be non-void.", "22:19: Method 'findSomething' must throw 'java.rmi.RemoteException'.", - "22:19: Method 'findSomething' must throw 'javax.ejb.FinderException'.", }; verify(checkConfig, getPath("j2ee/InputHomeInterface.java"), expected); } }
false
true
public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RemoteHomeInterfaceCheck.class); final String[] expected = { "14:18: Home interface 'InputHomeInterface' must have method 'findByPrimaryKey()'.", "20:19: Method 'createSomething' must be non-void.", "20:19: Method 'createSomething' must throw 'java.rmi.RemoteException'.", "20:19: Method 'createSomething' must throw 'javax.ejb.CreateException'.", "22:19: Method 'findSomething' must be non-void.", "22:19: Method 'findSomething' must throw 'java.rmi.RemoteException'.", "22:19: Method 'findSomething' must throw 'javax.ejb.FinderException'.", }; verify(checkConfig, getPath("j2ee/InputHomeInterface.java"), expected); }
public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RemoteHomeInterfaceCheck.class); final String[] expected = { "20:19: Method 'createSomething' must be non-void.", "20:19: Method 'createSomething' must throw 'java.rmi.RemoteException'.", "20:19: Method 'createSomething' must throw 'javax.ejb.CreateException'.", "22:19: Method 'findSomething' must throw 'java.rmi.RemoteException'.", }; verify(checkConfig, getPath("j2ee/InputHomeInterface.java"), expected); }
diff --git a/src/java-common/org/xins/common/spec/Parameter.java b/src/java-common/org/xins/common/spec/Parameter.java index 6ab23434e..c358ce69a 100644 --- a/src/java-common/org/xins/common/spec/Parameter.java +++ b/src/java-common/org/xins/common/spec/Parameter.java @@ -1,175 +1,175 @@ /* * $Id$ * * Copyright 2003-2005 Wanadoo Nederland B.V. * See the COPYRIGHT file for redistribution and use restrictions. */ package org.xins.common.spec; import org.xins.common.types.Type; /** * Specification of the parameter. * * @version $Revision$ * @author Anthony Goubard (<a href="mailto:[email protected]">[email protected]</a>) */ public class Parameter { //------------------------------------------------------------------------- // Class functions //------------------------------------------------------------------------- //------------------------------------------------------------------------- // Class fields //------------------------------------------------------------------------- //------------------------------------------------------------------------- // Constructor //------------------------------------------------------------------------- /** * Creates a new instance of Parameter. * * @param reference * the reference class. * @param name * the name of the parameter. * @param type * the type of the parameter. * @param required * <code>true</code> if the parameter is required, <code>false</code> otherwise. * @param description * the description of the parameter. */ Parameter(Class reference, String name, String type, boolean required, String description) { _reference = reference; _parameterName = name; _parameterType = type; _required = required; _description = description; } //------------------------------------------------------------------------- // Fields //------------------------------------------------------------------------- /** * The reference class. */ private final Class _reference; /** * Name of the parameter. */ private final String _parameterName; /** * Type of the parameter. */ private final String _parameterType; /** * Flags indicating if this parameter is required. */ private final boolean _required; /** * Description of the parameter. */ private String _description; //------------------------------------------------------------------------- // Methods //------------------------------------------------------------------------- /** * Gets the name of the parameter. * * @return * The name of the parameter, never <code>null</code>. */ public String getName() { return _parameterName; } /** * Gets the description of the parameter. * * @return * The description of the parameter, never <code>null</code>. */ public String getDescription() { return _description; } /** * Returns whether the parameter is mandatory. * * @return * <code>true</code> if the parameter is requierd, <code>false</code> otherwise. */ public boolean isRequired() { return _required; } /** * Gets the type of the parameter. * * @return * The type of the parameter, never <code>null</code>. * * @throws InvalidSpecificationException * If the type is not recognized. */ public Type getType() throws InvalidSpecificationException { if (_parameterType == null || _parameterType.equals("") || _parameterType.equals("_text")) { return org.xins.common.types.standard.Text.SINGLETON; } else if (_parameterType.equals("_int8")) { return org.xins.common.types.standard.Int8.SINGLETON; } else if (_parameterType.equals("_int16")) { return org.xins.common.types.standard.Int16.SINGLETON; } else if (_parameterType.equals("_int32")) { return org.xins.common.types.standard.Int32.SINGLETON; } else if (_parameterType.equals("_int64")) { return org.xins.common.types.standard.Int64.SINGLETON; } else if (_parameterType.equals("_float32")) { return org.xins.common.types.standard.Float32.SINGLETON; } else if (_parameterType.equals("_float64")) { return org.xins.common.types.standard.Float64.SINGLETON; } else if (_parameterType.equals("_boolean")) { return org.xins.common.types.standard.Boolean.SINGLETON; } else if (_parameterType.equals("_date")) { return org.xins.common.types.standard.Date.SINGLETON; } else if (_parameterType.equals("_timestamp")) { return org.xins.common.types.standard.Timestamp.SINGLETON; } else if (_parameterType.equals("_base64")) { return org.xins.common.types.standard.Base64.SINGLETON; } else if (_parameterType.equals("_descriptor")) { return org.xins.common.types.standard.Descriptor.SINGLETON; } else if (_parameterType.equals("_properties")) { return org.xins.common.types.standard.Properties.SINGLETON; } else if (_parameterType.equals("_url")) { return org.xins.common.types.standard.URL.SINGLETON; } else if (_parameterType.charAt(0) != '_') { String className = _reference.getName(); int truncatePos = className.lastIndexOf(".capi.CAPI"); if (truncatePos == -1) { truncatePos = className.lastIndexOf(".api.APIImpl"); } try { String typeClassName = className.substring(0, truncatePos) + ".types." + _parameterType + ".class"; - Class typeClass = Class.forName(className); + Class typeClass = Class.forName(typeClassName); Type type = (Type) typeClass.getField("SINGLETON").get(null); return type; } catch (Exception ex) { throw new InvalidSpecificationException("Invalid type: " + _parameterType + " ; " + ex.getMessage()); } } throw new InvalidSpecificationException("Invalid type: " + _parameterType + "."); } }
true
true
public Type getType() throws InvalidSpecificationException { if (_parameterType == null || _parameterType.equals("") || _parameterType.equals("_text")) { return org.xins.common.types.standard.Text.SINGLETON; } else if (_parameterType.equals("_int8")) { return org.xins.common.types.standard.Int8.SINGLETON; } else if (_parameterType.equals("_int16")) { return org.xins.common.types.standard.Int16.SINGLETON; } else if (_parameterType.equals("_int32")) { return org.xins.common.types.standard.Int32.SINGLETON; } else if (_parameterType.equals("_int64")) { return org.xins.common.types.standard.Int64.SINGLETON; } else if (_parameterType.equals("_float32")) { return org.xins.common.types.standard.Float32.SINGLETON; } else if (_parameterType.equals("_float64")) { return org.xins.common.types.standard.Float64.SINGLETON; } else if (_parameterType.equals("_boolean")) { return org.xins.common.types.standard.Boolean.SINGLETON; } else if (_parameterType.equals("_date")) { return org.xins.common.types.standard.Date.SINGLETON; } else if (_parameterType.equals("_timestamp")) { return org.xins.common.types.standard.Timestamp.SINGLETON; } else if (_parameterType.equals("_base64")) { return org.xins.common.types.standard.Base64.SINGLETON; } else if (_parameterType.equals("_descriptor")) { return org.xins.common.types.standard.Descriptor.SINGLETON; } else if (_parameterType.equals("_properties")) { return org.xins.common.types.standard.Properties.SINGLETON; } else if (_parameterType.equals("_url")) { return org.xins.common.types.standard.URL.SINGLETON; } else if (_parameterType.charAt(0) != '_') { String className = _reference.getName(); int truncatePos = className.lastIndexOf(".capi.CAPI"); if (truncatePos == -1) { truncatePos = className.lastIndexOf(".api.APIImpl"); } try { String typeClassName = className.substring(0, truncatePos) + ".types." + _parameterType + ".class"; Class typeClass = Class.forName(className); Type type = (Type) typeClass.getField("SINGLETON").get(null); return type; } catch (Exception ex) { throw new InvalidSpecificationException("Invalid type: " + _parameterType + " ; " + ex.getMessage()); } } throw new InvalidSpecificationException("Invalid type: " + _parameterType + "."); }
public Type getType() throws InvalidSpecificationException { if (_parameterType == null || _parameterType.equals("") || _parameterType.equals("_text")) { return org.xins.common.types.standard.Text.SINGLETON; } else if (_parameterType.equals("_int8")) { return org.xins.common.types.standard.Int8.SINGLETON; } else if (_parameterType.equals("_int16")) { return org.xins.common.types.standard.Int16.SINGLETON; } else if (_parameterType.equals("_int32")) { return org.xins.common.types.standard.Int32.SINGLETON; } else if (_parameterType.equals("_int64")) { return org.xins.common.types.standard.Int64.SINGLETON; } else if (_parameterType.equals("_float32")) { return org.xins.common.types.standard.Float32.SINGLETON; } else if (_parameterType.equals("_float64")) { return org.xins.common.types.standard.Float64.SINGLETON; } else if (_parameterType.equals("_boolean")) { return org.xins.common.types.standard.Boolean.SINGLETON; } else if (_parameterType.equals("_date")) { return org.xins.common.types.standard.Date.SINGLETON; } else if (_parameterType.equals("_timestamp")) { return org.xins.common.types.standard.Timestamp.SINGLETON; } else if (_parameterType.equals("_base64")) { return org.xins.common.types.standard.Base64.SINGLETON; } else if (_parameterType.equals("_descriptor")) { return org.xins.common.types.standard.Descriptor.SINGLETON; } else if (_parameterType.equals("_properties")) { return org.xins.common.types.standard.Properties.SINGLETON; } else if (_parameterType.equals("_url")) { return org.xins.common.types.standard.URL.SINGLETON; } else if (_parameterType.charAt(0) != '_') { String className = _reference.getName(); int truncatePos = className.lastIndexOf(".capi.CAPI"); if (truncatePos == -1) { truncatePos = className.lastIndexOf(".api.APIImpl"); } try { String typeClassName = className.substring(0, truncatePos) + ".types." + _parameterType + ".class"; Class typeClass = Class.forName(typeClassName); Type type = (Type) typeClass.getField("SINGLETON").get(null); return type; } catch (Exception ex) { throw new InvalidSpecificationException("Invalid type: " + _parameterType + " ; " + ex.getMessage()); } } throw new InvalidSpecificationException("Invalid type: " + _parameterType + "."); }
diff --git a/src/main/java/com/twistlet/falcon/model/service/PatronServiceImpl.java b/src/main/java/com/twistlet/falcon/model/service/PatronServiceImpl.java index 51c18ee..3f3f806 100644 --- a/src/main/java/com/twistlet/falcon/model/service/PatronServiceImpl.java +++ b/src/main/java/com/twistlet/falcon/model/service/PatronServiceImpl.java @@ -1,410 +1,413 @@ package com.twistlet.falcon.model.service; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.dao.support.DataAccessUtils; import org.springframework.security.authentication.encoding.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.twistlet.falcon.controller.bean.User; import com.twistlet.falcon.model.entity.FalconAppointmentPatron; import com.twistlet.falcon.model.entity.FalconLocation; import com.twistlet.falcon.model.entity.FalconPatron; import com.twistlet.falcon.model.entity.FalconRole; import com.twistlet.falcon.model.entity.FalconService; import com.twistlet.falcon.model.entity.FalconStaff; import com.twistlet.falcon.model.entity.FalconUser; import com.twistlet.falcon.model.entity.FalconUserRole; import com.twistlet.falcon.model.repository.FalconAppointmentPatronRepository; import com.twistlet.falcon.model.repository.FalconPatronRepository; import com.twistlet.falcon.model.repository.FalconUserRepository; import com.twistlet.falcon.model.repository.FalconUserRoleRepository; @Service public class PatronServiceImpl implements PatronService { protected final Logger logger = LoggerFactory.getLogger(getClass()); private final FalconPatronRepository falconPatronRepository; private final FalconUserRepository falconUserRepository; private final FalconUserRoleRepository falconUserRoleRepository; private final FalconAppointmentPatronRepository falconAppointmentPatronRepository; private final PasswordEncoder passwordEncoder; @Autowired public PatronServiceImpl(FalconPatronRepository falconPatronRepository, FalconUserRepository falconUserRepository, FalconUserRoleRepository falconUserRoleRepository, FalconAppointmentPatronRepository falconAppointmentPatronRepository, PasswordEncoder passwordEncoder) { this.falconPatronRepository = falconPatronRepository; this.falconUserRepository = falconUserRepository; this.falconUserRoleRepository = falconUserRoleRepository; this.falconAppointmentPatronRepository = falconAppointmentPatronRepository; this.passwordEncoder = passwordEncoder; } @Override @Transactional(readOnly = true) public List<User> listRegisteredPatrons(FalconUser admin) { List<FalconPatron> falconPatrons = falconPatronRepository.findByFalconUserByAdmin(admin); List<User> patrons = new ArrayList<>(); User user = null; for(FalconPatron falconPatron : falconPatrons){ FalconUser falconUser = falconPatron.getFalconUserByPatron(); user = new User(); user.setName(falconUser.getName() + " (" + falconUser.getNric() + ")"); user.setUsername(falconUser.getUsername()); patrons.add(user); } return patrons; } @Override @Transactional(propagation = Propagation.REQUIRED) public void saveNewPatron(FalconPatron patron) { FalconUser newUser = patron.getFalconUserByPatron(); newUser.setUsername(newUser.getEmail()); final String encodedPassword = passwordEncoder.encodePassword(newUser.getPassword(), newUser.getUsername()); newUser.setPassword(encodedPassword); newUser.setValid(true); FalconRole falconRole = new FalconRole(); falconRole.setRoleName("ROLE_USER"); FalconUserRole falconUserRole = new FalconUserRole(); falconUserRole.setFalconUser(newUser); falconUserRole.setFalconRole(falconRole); FalconUser registeredUser = falconUserRepository.findOne(newUser.getUsername()); if(registeredUser == null){ /** * user does not exist. save user and user_role. We do not validete duplicate hp, nric etc already validated in view */ falconUserRepository.save(newUser); falconUserRoleRepository.save(falconUserRole); }else{ /** * update user to use latest info. comment this if we dont want to update user details */ registeredUser.setNric(newUser.getNric()); registeredUser.setPhone(newUser.getPhone()); registeredUser.setName(newUser.getName()); registeredUser.setSendEmail(newUser.getSendEmail()); registeredUser.setSendSms(newUser.getSendSms()); registeredUser.setValid(true); falconUserRepository.save(registeredUser); } List<FalconPatron> patrons = falconPatronRepository.findByFalconUserByAdminAndFalconUserByPatron(patron.getFalconUserByAdmin(), patron.getFalconUserByPatron()); if(CollectionUtils.isEmpty(patrons) && patron.getFalconUserByAdmin() != null && StringUtils.isNotBlank(patron.getFalconUserByAdmin().getUsername())){ falconPatronRepository.save(patron); } } @Override @Transactional(propagation = Propagation.REQUIRED) public void savePatron(FalconPatron patron) { FalconUser user = patron.getFalconUserByPatron(); FalconUser admin = patron.getFalconUserByAdmin(); String[] names = StringUtils.split(patron.getFalconUserByPatron().getName(), " "); boolean newUser = false; if(StringUtils.isBlank(user.getUsername())){ user.setUsername(user.getEmail()); user.setValid(true); - newUser = true; + } + FalconUser registeredUser = falconUserRepository.findOne(user.getUsername()); + if(registeredUser == null){ + newUser = true; } if(newUser){ if(StringUtils.isBlank(user.getPassword())){ logger.info("password: " + names[0] + " salt:" + user.getUsername()); user.setPassword(passwordEncoder.encodePassword(names[0], user.getUsername())); } patron.setFalconUserByPatron(user); FalconRole falconRole = new FalconRole(); falconRole.setRoleName("ROLE_USER"); FalconUserRole falconUserRole = new FalconUserRole(); falconUserRole.setFalconUser(user); falconUserRole.setFalconRole(falconRole); /** * check if user already exist */ - FalconUser registeredUser = falconUserRepository.findOne(user.getUsername()); if(registeredUser == null){ /** * user does not exist. save user and user_role. We do not validete duplicate hp, nric etc already validated in view */ falconUserRepository.save(user); falconUserRoleRepository.save(falconUserRole); }else{ /** * update user to use latest info. comment this if we dont want to update user details */ registeredUser.setNric(user.getNric()); registeredUser.setPhone(user.getPhone()); registeredUser.setName(user.getName()); registeredUser.setSendEmail(user.getSendEmail()); registeredUser.setSendSms(user.getSendSms()); registeredUser.setValid(true); falconUserRepository.save(registeredUser); } }else{ FalconUser updateUser = falconUserRepository.findOne(user.getUsername()); if(user.getValid() == null){ user.setValid(false); } if(user.getValid() == false){ /** * user trying to delete */ Set<FalconPatron> patrons = updateUser.getFalconPatronsForPatron(); List<FalconPatron> toDeletePatrons = new ArrayList<>(); List<FalconAppointmentPatron> toDeleteAppointments = new ArrayList<>(); for(FalconPatron registeredPatron : patrons){ if(registeredPatron.getFalconUserByAdmin().getUsername().equals(admin.getUsername())){ toDeletePatrons.add(registeredPatron); } List<FalconAppointmentPatron> registeredAppointment = falconAppointmentPatronRepository.findByFalconPatron(registeredPatron); toDeleteAppointments.addAll(registeredAppointment); } if(CollectionUtils.size(toDeletePatrons) < 2){ updateUser.setValid(user.getValid()); } falconAppointmentPatronRepository.delete(toDeleteAppointments); falconPatronRepository.delete(toDeletePatrons); } updateUser.setName(user.getName()); updateUser.setNric(user.getNric()); + updateUser.setPhone(user.getPhone()); updateUser.setEmail(user.getEmail()); updateUser.setSendEmail(user.getSendEmail()); updateUser.setSendSms(user.getSendSms()); falconUserRepository.save(updateUser); } List<FalconPatron> patrons = falconPatronRepository.findByFalconUserByAdminAndFalconUserByPatron(patron.getFalconUserByAdmin(), patron.getFalconUserByPatron()); if(CollectionUtils.isEmpty(patrons) && patron.getFalconUserByAdmin() != null && StringUtils.isNotBlank(patron.getFalconUserByAdmin().getUsername())){ falconPatronRepository.save(patron); } } @Override @Transactional(readOnly = true) public Set<User> listAvailablePatrons(FalconUser admin, Date start, Date end) { List<User> allPatron = listRegisteredPatrons(admin); Set<User> availablePatron = new HashSet<>(); Set<FalconPatron> busyPatrons = falconPatronRepository.findPatronsDateRange(admin, start, end); for(User user: allPatron){ boolean found = false; for(FalconPatron patron : busyPatrons){ if(StringUtils.equals(user.getUsername(), patron.getFalconUserByPatron().getUsername())){ found = true; break; } } if(!found){ availablePatron.add(user); } } return availablePatron; } @Override @Transactional(readOnly = true) public FalconPatron findPatron(String patron, String admin) { FalconUser falconPatron = new FalconUser(); falconPatron.setUsername(patron); FalconUser falconAdmin = new FalconUser(); falconAdmin.setUsername(admin); List<FalconPatron> falconPatrons = falconPatronRepository.findByFalconUserByAdminAndFalconUserByPatron(falconAdmin, falconPatron); FalconPatron uniqeFalconPatron = DataAccessUtils.uniqueResult(falconPatrons); return uniqeFalconPatron; } @Override @Transactional(readOnly = true) public List<FalconPatron> listPatronByAdminNameLike(FalconUser admin, String name) { List<FalconPatron> falconPatrons = falconPatronRepository.findByFalconUserNameLike(admin, name); List<FalconPatron> validPatrons = new ArrayList<>(); for(FalconPatron falconPatron : falconPatrons){ if(StringUtils.equals(falconPatron.getFalconUserByAdmin().getUsername(), admin.getUsername())){ validPatrons.add(falconPatron); } } return validPatrons; } @Override @Transactional(readOnly = true) public List<FalconPatron> listPatronByAdminNricLike(FalconUser admin, String nric) { List<FalconPatron> falconPatrons = falconPatronRepository.findByFalconUserNricLike(admin, nric); List<FalconPatron> validPatrons = new ArrayList<>(); for(FalconPatron falconPatron : falconPatrons){ if(StringUtils.equals(falconPatron.getFalconUserByAdmin().getUsername(), admin.getUsername())){ validPatrons.add(falconPatron); } } return validPatrons; } @Override @Transactional(readOnly = true) public List<FalconPatron> listPatronByAdminEmailLike(FalconUser admin, String email) { List<FalconPatron> falconPatrons = falconPatronRepository.findByFalconUserEmailLike(admin, email); List<FalconPatron> validPatrons = new ArrayList<>(); for(FalconPatron falconPatron : falconPatrons){ if(StringUtils.equals(falconPatron.getFalconUserByAdmin().getUsername(), admin.getUsername())){ validPatrons.add(falconPatron); } } return validPatrons; } @Override @Transactional(readOnly = true) public List<FalconPatron> listPatronByAdminMobileLike(FalconUser admin, String mobile) { List<FalconPatron> falconPatrons = falconPatronRepository.findByFalconUserHpTelLike(admin, mobile); List<FalconPatron> validPatrons = new ArrayList<>(); for(FalconPatron falconPatron : falconPatrons){ if(StringUtils.equals(falconPatron.getFalconUserByAdmin().getUsername(), admin.getUsername())){ validPatrons.add(falconPatron); } } return validPatrons; } @Override @Transactional(readOnly = true) public List<FalconPatron> listPatronByAdminPatronLike(FalconUser admin, FalconUser patron) { List<FalconPatron> patrons = falconPatronRepository.findByFalconUserPatronLike(admin, patron); List<FalconPatron> matchingPatrons = new ArrayList<>(); for(FalconPatron falconPatron : patrons){ falconPatron.getFalconUserByPatron().getName(); if(StringUtils.equals(falconPatron.getFalconUserByAdmin().getUsername(), admin.getUsername())){ matchingPatrons.add(falconPatron); } } if(StringUtils.isNotEmpty(admin.getUsername())){ patrons = matchingPatrons; } return patrons; } @Override @Transactional(propagation = Propagation.REQUIRED) public void deletePatron(FalconPatron patron) { List<FalconPatron> patrons = listPatronByAdminPatronLike(patron.getFalconUserByAdmin(), patron.getFalconUserByPatron()); FalconPatron uniquePatron = null; for(FalconPatron record : patrons){ if(StringUtils.equals(record.getFalconUserByAdmin().getUsername(), patron.getFalconUserByAdmin().getUsername())){ uniquePatron = record; break; } } if(uniquePatron != null){ falconPatronRepository.delete(uniquePatron); if(CollectionUtils.size(patrons) < 2){ falconUserRepository.delete(uniquePatron.getFalconUserByPatron()); } } } @Override @Transactional(readOnly = true) public FalconPatron findPatron(String patron, boolean isAdmin) { FalconUser falconPatron = new FalconUser(); falconPatron.setUsername(patron); List<FalconPatron> falconPatrons = falconPatronRepository.findByFalconUserByPatron(falconPatron); FalconPatron uniqeFalconPatron = null; try { uniqeFalconPatron = DataAccessUtils.uniqueResult(falconPatrons); } catch (IncorrectResultSizeDataAccessException e) { /** * user is registered with multiple or no admin */ if(CollectionUtils.isNotEmpty(falconPatrons)){ uniqeFalconPatron = falconPatrons.get(0); } } FalconUser falconUser = uniqeFalconPatron.getFalconUserByPatron(); FalconUser falconAdmin = uniqeFalconPatron.getFalconUserByAdmin(); logger.info("name: " + falconUser.getName()); logger.info("admin: " + falconAdmin.getName()); FalconPatron theFalconPatron = new FalconPatron(); theFalconPatron.setFalconUserByPatron(falconUser); theFalconPatron.setFalconUserByAdmin(falconAdmin); theFalconPatron.setId(uniqeFalconPatron.getId()); return theFalconPatron; } @Override @Transactional(readOnly = true) public List<FalconUser> listUserByCriteria(FalconUser user) { List<FalconUser> users = falconUserRepository.findByCriteria(user); for(FalconUser falconUser : users){ Set<FalconPatron> registeredPatrons = falconUser.getFalconPatronsForAdmin(); for(FalconPatron patron : registeredPatrons){ patron.getFalconUserByAdmin().getUsername(); } } for(FalconUser falconUser : users){ Set<FalconPatron> registeredPatrons = falconUser.getFalconPatronsForPatron(); for(FalconPatron patron : registeredPatrons){ patron.getFalconUserByAdmin().getUsername(); } } return users; } @Override @Transactional(readOnly = true) public List<FalconPatron> listAllPatronsAdmin(FalconUser patron) { List<FalconPatron> falconPatrons = falconPatronRepository.findByFalconUserByPatron(patron); for(FalconPatron registeredAdmins : falconPatrons){ registeredAdmins.getFalconUserByAdmin().getName(); registeredAdmins.getFalconUserByPatron().getName(); if(CollectionUtils.isNotEmpty(registeredAdmins.getFalconUserByAdmin().getFalconStaffs())){ for(FalconStaff staff : registeredAdmins.getFalconUserByAdmin().getFalconStaffs()){ staff.getName(); staff.getId(); staff.setFalconAppointments(null); staff.setFalconUser(null); } } if(CollectionUtils.isNotEmpty(registeredAdmins.getFalconUserByAdmin().getFalconLocations())){ for(FalconLocation location : registeredAdmins.getFalconUserByAdmin().getFalconLocations()){ location.getName(); location.getId(); location.setFalconAppointments(null); location.setFalconUser(null); } } if(CollectionUtils.isNotEmpty(registeredAdmins.getFalconUserByAdmin().getFalconServices())){ for(FalconService service : registeredAdmins.getFalconUserByAdmin().getFalconServices()){ service.getName(); service.getId(); service.setFalconAppointments(null); service.setFalconUser(null); } } } return falconPatrons; } }
false
true
public void savePatron(FalconPatron patron) { FalconUser user = patron.getFalconUserByPatron(); FalconUser admin = patron.getFalconUserByAdmin(); String[] names = StringUtils.split(patron.getFalconUserByPatron().getName(), " "); boolean newUser = false; if(StringUtils.isBlank(user.getUsername())){ user.setUsername(user.getEmail()); user.setValid(true); newUser = true; } if(newUser){ if(StringUtils.isBlank(user.getPassword())){ logger.info("password: " + names[0] + " salt:" + user.getUsername()); user.setPassword(passwordEncoder.encodePassword(names[0], user.getUsername())); } patron.setFalconUserByPatron(user); FalconRole falconRole = new FalconRole(); falconRole.setRoleName("ROLE_USER"); FalconUserRole falconUserRole = new FalconUserRole(); falconUserRole.setFalconUser(user); falconUserRole.setFalconRole(falconRole); /** * check if user already exist */ FalconUser registeredUser = falconUserRepository.findOne(user.getUsername()); if(registeredUser == null){ /** * user does not exist. save user and user_role. We do not validete duplicate hp, nric etc already validated in view */ falconUserRepository.save(user); falconUserRoleRepository.save(falconUserRole); }else{ /** * update user to use latest info. comment this if we dont want to update user details */ registeredUser.setNric(user.getNric()); registeredUser.setPhone(user.getPhone()); registeredUser.setName(user.getName()); registeredUser.setSendEmail(user.getSendEmail()); registeredUser.setSendSms(user.getSendSms()); registeredUser.setValid(true); falconUserRepository.save(registeredUser); } }else{ FalconUser updateUser = falconUserRepository.findOne(user.getUsername()); if(user.getValid() == null){ user.setValid(false); } if(user.getValid() == false){ /** * user trying to delete */ Set<FalconPatron> patrons = updateUser.getFalconPatronsForPatron(); List<FalconPatron> toDeletePatrons = new ArrayList<>(); List<FalconAppointmentPatron> toDeleteAppointments = new ArrayList<>(); for(FalconPatron registeredPatron : patrons){ if(registeredPatron.getFalconUserByAdmin().getUsername().equals(admin.getUsername())){ toDeletePatrons.add(registeredPatron); } List<FalconAppointmentPatron> registeredAppointment = falconAppointmentPatronRepository.findByFalconPatron(registeredPatron); toDeleteAppointments.addAll(registeredAppointment); } if(CollectionUtils.size(toDeletePatrons) < 2){ updateUser.setValid(user.getValid()); } falconAppointmentPatronRepository.delete(toDeleteAppointments); falconPatronRepository.delete(toDeletePatrons); } updateUser.setName(user.getName()); updateUser.setNric(user.getNric()); updateUser.setEmail(user.getEmail()); updateUser.setSendEmail(user.getSendEmail()); updateUser.setSendSms(user.getSendSms()); falconUserRepository.save(updateUser); } List<FalconPatron> patrons = falconPatronRepository.findByFalconUserByAdminAndFalconUserByPatron(patron.getFalconUserByAdmin(), patron.getFalconUserByPatron()); if(CollectionUtils.isEmpty(patrons) && patron.getFalconUserByAdmin() != null && StringUtils.isNotBlank(patron.getFalconUserByAdmin().getUsername())){ falconPatronRepository.save(patron); } }
public void savePatron(FalconPatron patron) { FalconUser user = patron.getFalconUserByPatron(); FalconUser admin = patron.getFalconUserByAdmin(); String[] names = StringUtils.split(patron.getFalconUserByPatron().getName(), " "); boolean newUser = false; if(StringUtils.isBlank(user.getUsername())){ user.setUsername(user.getEmail()); user.setValid(true); } FalconUser registeredUser = falconUserRepository.findOne(user.getUsername()); if(registeredUser == null){ newUser = true; } if(newUser){ if(StringUtils.isBlank(user.getPassword())){ logger.info("password: " + names[0] + " salt:" + user.getUsername()); user.setPassword(passwordEncoder.encodePassword(names[0], user.getUsername())); } patron.setFalconUserByPatron(user); FalconRole falconRole = new FalconRole(); falconRole.setRoleName("ROLE_USER"); FalconUserRole falconUserRole = new FalconUserRole(); falconUserRole.setFalconUser(user); falconUserRole.setFalconRole(falconRole); /** * check if user already exist */ if(registeredUser == null){ /** * user does not exist. save user and user_role. We do not validete duplicate hp, nric etc already validated in view */ falconUserRepository.save(user); falconUserRoleRepository.save(falconUserRole); }else{ /** * update user to use latest info. comment this if we dont want to update user details */ registeredUser.setNric(user.getNric()); registeredUser.setPhone(user.getPhone()); registeredUser.setName(user.getName()); registeredUser.setSendEmail(user.getSendEmail()); registeredUser.setSendSms(user.getSendSms()); registeredUser.setValid(true); falconUserRepository.save(registeredUser); } }else{ FalconUser updateUser = falconUserRepository.findOne(user.getUsername()); if(user.getValid() == null){ user.setValid(false); } if(user.getValid() == false){ /** * user trying to delete */ Set<FalconPatron> patrons = updateUser.getFalconPatronsForPatron(); List<FalconPatron> toDeletePatrons = new ArrayList<>(); List<FalconAppointmentPatron> toDeleteAppointments = new ArrayList<>(); for(FalconPatron registeredPatron : patrons){ if(registeredPatron.getFalconUserByAdmin().getUsername().equals(admin.getUsername())){ toDeletePatrons.add(registeredPatron); } List<FalconAppointmentPatron> registeredAppointment = falconAppointmentPatronRepository.findByFalconPatron(registeredPatron); toDeleteAppointments.addAll(registeredAppointment); } if(CollectionUtils.size(toDeletePatrons) < 2){ updateUser.setValid(user.getValid()); } falconAppointmentPatronRepository.delete(toDeleteAppointments); falconPatronRepository.delete(toDeletePatrons); } updateUser.setName(user.getName()); updateUser.setNric(user.getNric()); updateUser.setPhone(user.getPhone()); updateUser.setEmail(user.getEmail()); updateUser.setSendEmail(user.getSendEmail()); updateUser.setSendSms(user.getSendSms()); falconUserRepository.save(updateUser); } List<FalconPatron> patrons = falconPatronRepository.findByFalconUserByAdminAndFalconUserByPatron(patron.getFalconUserByAdmin(), patron.getFalconUserByPatron()); if(CollectionUtils.isEmpty(patrons) && patron.getFalconUserByAdmin() != null && StringUtils.isNotBlank(patron.getFalconUserByAdmin().getUsername())){ falconPatronRepository.save(patron); } }
diff --git a/src/java/org/jivesoftware/openfire/ldap/LdapVCardProvider.java b/src/java/org/jivesoftware/openfire/ldap/LdapVCardProvider.java index 2e9390cd..9954dca1 100644 --- a/src/java/org/jivesoftware/openfire/ldap/LdapVCardProvider.java +++ b/src/java/org/jivesoftware/openfire/ldap/LdapVCardProvider.java @@ -1,519 +1,524 @@ /** * $Revision: 1217 $ * $Date: 2005-04-11 14:11:06 -0700 (Mon, 11 Apr 2005) $ * * Copyright (C) 2005 Jive Software. All rights reserved. * * This software is published under the terms of the GNU Public License (GPL), * a copy of which is included in this distribution. */ package org.jivesoftware.openfire.ldap; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Node; import org.jivesoftware.util.*; import org.jivesoftware.openfire.vcard.VCardManager; import org.jivesoftware.openfire.vcard.VCardProvider; import org.jivesoftware.openfire.vcard.DefaultVCardProvider; import org.xmpp.packet.JID; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import java.util.*; /** * Read-only LDAP provider for vCards.Configuration consists of adding a provider:<p/> * * <pre> * &lt;provider&gt; * &lt;vcard&gt; * &lt;className&gt;org.jivesoftware.openfire.ldap.LdapVCardProvider&lt;/className&gt; * &lt;/vcard&gt; * &lt;/provider&gt; * </pre><p/> * * and an xml vcard-mapping to openfire.xml.<p/> * * The vcard attributes can be configured by adding an <code>attrs="attr1,attr2"</code> * attribute to the vcard elements.<p/> * * Arbitrary text can be used for the element values as well as <code>MessageFormat</code> * style placeholders for the ldap attributes. For example, if you wanted to map the LDAP * attribute <code>displayName</code> to the vcard element <code>FN</code>, the xml * nippet would be:<br><pre>&lt;FN attrs=&quot;displayName&quot;&gt;{0}&lt;/FN&gt;</pre><p/> * * The vCard XML must be escaped in CDATA and must also be well formed. It is the exact * XML this provider will send to a client after after stripping <code>attr</code> attributes * and populating the placeholders with the data retrieved from LDAP. This system should * be flexible enough to handle any client's vCard format. An example mapping follows.<br> * <pre> * &lt;ldap&gt; * &lt;vcard-mapping&gt; * &lt;![CDATA[ * &lt;vCard xmlns='vcard-temp'&gt; * &lt;FN attrs=&quot;displayName&quot;&gt;{0}&lt;/FN&gt; * &lt;NICKNAME attrs=&quot;uid&quot;&gt;{0}&lt;/NICKNAME&gt; * &lt;BDAY attrs=&quot;dob&quot;&gt;{0}&lt;/BDAY&gt; * &lt;ADR&gt; * &lt;HOME/&gt; * &lt;EXTADR&gt;Ste 500&lt;/EXTADR&gt; * &lt;STREET&gt;317 SW Alder St&lt;/STREET&gt; * &lt;LOCALITY&gt;Portland&lt;/LOCALITY&gt; * &lt;REGION&gt;Oregon&lt;/REGION&gt; * &lt;PCODE&gt;97204&lt;/PCODE&gt; * &lt;CTRY&gt;USA&lt;/CTRY&gt; * &lt;/ADR&gt; * &lt;TEL&gt; * &lt;HOME/&gt; * &lt;VOICE/&gt; * &lt;NUMBER attrs=&quot;telephoneNumber&quot;&gt;{0}&lt;/NUMBER&gt; * &lt;/TEL&gt; * &lt;EMAIL&gt; * &lt;INTERNET/&gt; * &lt;USERID attrs=&quot;mail&quot;&gt;{0}&lt;/USERID&gt; * &lt;/EMAIL&gt; * &lt;TITLE attrs=&quot;title&quot;&gt;{0}&lt;/TITLE&gt; * &lt;ROLE attrs=&quot;&quot;&gt;{0}&lt;/ROLE&gt; * &lt;ORG&gt; * &lt;ORGNAME attrs=&quot;o&quot;&gt;{0}&lt;/ORGNAME&gt; * &lt;ORGUNIT attrs=&quot;&quot;&gt;{0}&lt;/ORGUNIT&gt; * &lt;/ORG&gt; * &lt;URL attrs=&quot;labeledURI&quot;&gt;{0}&lt;/URL&gt; * &lt;DESC attrs=&quot;uidNumber,homeDirectory,loginShell&quot;&gt; * uid: {0} home: {1} shell: {2} * &lt;/DESC&gt; * &lt;/vCard&gt; * ]]&gt; * &lt;/vcard-mapping&gt; * &lt;/ldap&gt; * </pre><p> * <p/> * An easy way to get the vcard format your client needs, assuming you've been * using the database store, is to do a <code>SELECT value FROM jivevcard WHERE * username='some_user'</code> in your favorite sql querier and paste the result * into the <code>vcard-mapping</code> (don't forget the CDATA). * * @author rkelly */ public class LdapVCardProvider implements VCardProvider, PropertyEventListener { private LdapManager manager; private VCardTemplate template; private Boolean dbStorageEnabled = false; /** * The default vCard provider is used to handle the vCard in the database. vCard * fields that can be overriden are stored in the database. * * This is used/created only if we are storing avatars in the database. */ private DefaultVCardProvider defaultProvider = null; public LdapVCardProvider() { manager = LdapManager.getInstance(); initTemplate(); // Listen to property events so that the template is always up to date PropertyEventDispatcher.addListener(this); // DB vcard provider used for loading properties overwritten in the DB defaultProvider = new DefaultVCardProvider(); // Check of avatars can be overwritten (and stored in the database) dbStorageEnabled = JiveGlobals.getBooleanProperty("ldap.override.avatar", false); } /** * Initializes the VCard template as set by the administrator. */ private void initTemplate() { String property = JiveGlobals.getXMLProperty("ldap.vcard-mapping"); Log.debug("LdapVCardProvider: Found vcard mapping: '" + property); try { // Remove CDATA wrapping element if (property.startsWith("<![CDATA[")) { property = property.substring(9, property.length()-3); } Document document = DocumentHelper.parseText(property); template = new VCardTemplate(document); } catch (Exception e) { Log.error("Error loading vcard mapping: " + e.getMessage()); } Log.debug("LdapVCardProvider: attributes size==" + template.getAttributes().length); } /** * Creates a mapping of requested LDAP attributes to their values for the given user. * * @param username User we are looking up in LDAP. * @return Map of LDAP attribute to setting. */ private Map<String, String> getLdapAttributes(String username) { // Un-escape username username = JID.unescapeNode(username); Map<String, String> map = new HashMap<String, String>(); DirContext ctx = null; try { String userDN = manager.findUserDN(username); ctx = manager.getContext(manager.getUsersBaseDN(username)); Attributes attrs = ctx.getAttributes(userDN, template.getAttributes()); for (String attribute : template.getAttributes()) { javax.naming.directory.Attribute attr = attrs.get(attribute); String value; if (attr == null) { Log.debug("LdapVCardProvider: No ldap value found for attribute '" + attribute + "'"); value = ""; } else { Object ob = attrs.get(attribute).get(); Log.debug("LdapVCardProvider: Found attribute "+attribute+" of type: "+ob.getClass()); if(ob instanceof String) { value = (String)ob; } else { value = Base64.encodeBytes((byte[])ob); } } Log.debug("LdapVCardProvider: Ldap attribute '" + attribute + "'=>'" + value + "'"); map.put(attribute, value); } return map; } catch (Exception e) { Log.error(e); return Collections.emptyMap(); } finally { try { if (ctx != null) { ctx.close(); } } catch (Exception e) { // Ignore. } } } /** * Loads the avatar from LDAP, based off the vcard template. * * If enabled, will replace a blank PHOTO element with one from a DB stored vcard. * * @param username User we are loading the vcard for. * @return The loaded vcard element, or null if none found. */ public Element loadVCard(String username) { // Un-escape username. username = JID.unescapeNode(username); Map<String, String> map = getLdapAttributes(username); Log.debug("LdapVCardProvider: Getting mapped vcard for " + username); Element vcard = new VCard(template).getVCard(map); // If we have a vcard from ldap, but it doesn't have an avatar filled in, then we // may fill it with a locally stored vcard element. if (dbStorageEnabled && vcard != null && (vcard.element("PHOTO") == null || vcard.element("PHOTO").element("BINVAL") == null || vcard.element("PHOTO").element("BINVAL").getText().matches("\\s*"))) { Element avatarElement = loadAvatarFromDatabase(username); if (avatarElement != null) { Log.debug("LdapVCardProvider: Adding avatar element from local storage"); Element currentElement = vcard.element("PHOTO"); if (currentElement != null) { vcard.remove(currentElement); } vcard.add(avatarElement); } } Log.debug("LdapVCardProvider: Returning vcard"); return vcard; } /** * Returns a merged LDAP vCard combined with a PHOTO element provided in specified vCard. * * @param username User whose vCard this is. * @param mergeVCard vCard element that we are merging PHOTO element from into the LDAP vCard. * @return vCard element after merging in PHOTO element to LDAP data. */ private Element getMergedVCard(String username, Element mergeVCard) { // Un-escape username. username = JID.unescapeNode(username); Map<String, String> map = getLdapAttributes(username); Log.debug("LdapVCardProvider: Retrieving LDAP mapped vcard for " + username); Element vcard = new VCard(template).getVCard(map); if (mergeVCard == null) { // No vcard passed in? Hrm. Fine, return LDAP vcard. return vcard; } Element photoElement = mergeVCard.element("PHOTO").createCopy(); if (photoElement == null || photoElement.element("BINVAL") == null || photoElement.element("BINVAL").getText().matches("\\s*")) { // We were passed something null or empty, so lets just return the LDAP based vcard. return vcard; } // Now we need to check that the LDAP vcard doesn't have a PHOTO element that's filled in. if (!((vcard.element("PHOTO") == null || vcard.element("PHOTO").element("BINVAL") == null || vcard.element("PHOTO").element("BINVAL").getText().matches("\\s*")))) { // Hrm, it does, return the original vcard; return vcard; } Log.debug("LdapVCardProvider: Merging avatar element from passed vcard"); Element currentElement = vcard.element("PHOTO"); if (currentElement != null) { vcard.remove(currentElement); } vcard.add(photoElement); return vcard; } /** * Loads the avatar element from the user's DB stored vcard. * * @param username User whose vcard/avatar element we are loading. * @return Loaded avatar element or null if not found. */ private Element loadAvatarFromDatabase(String username) { Element vcardElement = defaultProvider.loadVCard(username); Element avatarElement = null; if (vcardElement != null && vcardElement.element("PHOTO") != null) { avatarElement = vcardElement.element("PHOTO").createCopy(); } return avatarElement; } /** * Handles when a user creates a new vcard. * * @param username User that created a new vcard. * @param vCardElement vCard element containing the new vcard. * @throws UnsupportedOperationException If an invalid field is changed or we are in readonly mode. */ public Element createVCard(String username, Element vCardElement) throws UnsupportedOperationException, AlreadyExistsException { throw new UnsupportedOperationException("LdapVCardProvider: VCard changes not allowed."); } /** * Handles when a user updates their vcard. * * @param username User that updated their vcard. * @param vCardElement vCard element containing the new vcard. * @throws UnsupportedOperationException If an invalid field is changed or we are in readonly mode. */ public Element updateVCard(String username, Element vCardElement) throws UnsupportedOperationException { if (dbStorageEnabled && defaultProvider != null) { if (isValidVCardChange(username, vCardElement)) { Element mergedVCard = getMergedVCard(username, vCardElement); try { defaultProvider.updateVCard(username, mergedVCard); } catch (NotFoundException e) { try { defaultProvider.createVCard(username, mergedVCard); } catch (AlreadyExistsException e1) { // Ignore } } return mergedVCard; } else { throw new UnsupportedOperationException("LdapVCardProvider: Invalid vcard changes."); } } else { throw new UnsupportedOperationException("LdapVCardProvider: VCard changes not allowed."); } } /** * Handles when a user deletes their vcard. * * @param username User that deketed their vcard. * @throws UnsupportedOperationException If an invalid field is changed or we are in readonly mode. */ public void deleteVCard(String username) throws UnsupportedOperationException { throw new UnsupportedOperationException("LdapVCardProvider: Attempted to delete vcard in read-only mode."); } /** * Returns true or false if the change to the existing vcard is valid (only to PHOTO element) * * @param username User who's LDAP-based vcard we will compare with. * @param newvCard New vCard Element we will compare against. * @return True or false if the changes made were valid (only to PHOTO element) */ private Boolean isValidVCardChange(String username, Element newvCard) { if (newvCard == null) { // Well if there's nothing to change, of course it's valid. Log.debug("LdapVCardProvider: No new vcard provided (no changes), accepting."); return true; } // Un-escape username. username = JID.unescapeNode(username); Map<String, String> map = getLdapAttributes(username); // Retrieve LDAP created vcard for comparison Element ldapvCard = new VCard(template).getVCard(map); if (ldapvCard == null) { // This person has no vcard at all, may not change it! Log.debug("LdapVCardProvider: User has no LDAP vcard, nothing they can change, rejecting."); return false; } // If the LDAP vcard has a non-empty PHOTO element set, then there is literally no way this will be accepted. Element ldapPhotoElem = ldapvCard.element("PHOTO"); if (ldapPhotoElem != null) { Element ldapBinvalElem = ldapPhotoElem.element("BINVAL"); if (ldapBinvalElem != null && !ldapBinvalElem.getTextTrim().matches("\\s*")) { // LDAP is providing a valid PHOTO element, byebye! Log.debug("LdapVCardProvider: LDAP has a PHOTO element set, no way to override, rejecting."); return false; } } // Retrieve database vcard, if it exists Element dbvCard = defaultProvider.loadVCard(username); if (dbvCard != null) { Element dbPhotoElem = dbvCard.element("PHOTO"); if (dbPhotoElem == null) { // DB has no photo, lets accept what we got. Log.debug("LdapVCardProvider: Database has no PHOTO element, accepting update."); return true; } else { Element newPhotoElem = newvCard.element("PHOTO"); // Note: NodeComparator never seems to consider these equal, even if they are? if (!dbPhotoElem.asXML().equals(newPhotoElem.asXML())) { Log.debug("LdapVCardProvider: DB photo element is:\n"+dbPhotoElem.asXML()); Log.debug("LdapVCardProvider: New photo element is:\n"+newPhotoElem.asXML()); // Photo element was changed. Ignore all other changes and accept this. Log.debug("LdapVCardProvider: PHOTO element changed, accepting update."); return true; } } } + else { + // No vcard exists in database + Log.debug("LdapVCardProvider: Database has no vCard stored, accepting update."); + return true; + } // Ok, either something bad changed or nothing changed. Either way, user either: // 1. should not have tried to change something 'readonly' // 2. shouldn't have bothered submitting no changes // So we'll consider this a bad return. Log.debug("LdapVCardProvider: PHOTO element didn't change, no reason to accept this, rejecting."); return false; } public boolean isReadOnly() { return !dbStorageEnabled; } public void propertySet(String property, Map params) { if ("ldap.override.avatar".equals(property)) { dbStorageEnabled = Boolean.parseBoolean((String)params.get("value")); } } public void propertyDeleted(String property, Map params) { if ("ldap.override.avatar".equals(property)) { dbStorageEnabled = false; } } public void xmlPropertySet(String property, Map params) { if ("ldap.vcard-mapping".equals(property)) { initTemplate(); // Reset cache of vCards VCardManager.getInstance().reset(); } } public void xmlPropertyDeleted(String property, Map params) { //Ignore } /** * Class to hold a <code>Document</code> representation of a vcard mapping * and unique attribute placeholders. Used by <code>VCard</code> to apply * a <code>Map</code> of ldap attributes to ldap values via * <code>MessageFormat</code> * * @author rkelly */ private static class VCardTemplate { private Document document; private String[] attributes; public VCardTemplate(Document document) { Set<String> set = new HashSet<String>(); this.document = document; treeWalk(this.document.getRootElement(), set); attributes = set.toArray(new String[set.size()]); } public String[] getAttributes() { return attributes; } public Document getDocument() { return document; } private void treeWalk(Element element, Set<String> set) { for (int i = 0, size = element.nodeCount(); i < size; i++) { Node node = element.node(i); if (node instanceof Element) { Element emement = (Element) node; StringTokenizer st = new StringTokenizer(emement.getTextTrim(), ", //{}"); while (st.hasMoreTokens()) { // Remove enclosing {} String string = st.nextToken().replaceAll("(\\{)([\\d\\D&&[^}]]+)(})", "$2"); Log.debug("VCardTemplate: found attribute " + string); set.add(string); } treeWalk(emement, set); } } } } /** * vCard class that converts vcard data using a template. */ private static class VCard { private VCardTemplate template; public VCard(VCardTemplate template) { this.template = template; } public Element getVCard(Map<String, String> map) { Document document = (Document) template.getDocument().clone(); Element element = document.getRootElement(); return treeWalk(element, map); } private Element treeWalk(Element element, Map<String, String> map) { for (int i = 0, size = element.nodeCount(); i < size; i++) { Node node = element.node(i); if (node instanceof Element) { Element emement = (Element) node; String elementText = emement.getTextTrim(); if (elementText != null && !"".equals(elementText)) { String format = emement.getStringValue(); StringTokenizer st = new StringTokenizer(elementText, ", //{}"); while (st.hasMoreTokens()) { // Remove enclosing {} String field = st.nextToken(); String attrib = field.replaceAll("(\\{)(" + field + ")(})", "$2"); String value = map.get(attrib); format = format.replaceFirst("(\\{)(" + field + ")(})", value); } emement.setText(format); } treeWalk(emement, map); } } return element; } } }
true
true
private Boolean isValidVCardChange(String username, Element newvCard) { if (newvCard == null) { // Well if there's nothing to change, of course it's valid. Log.debug("LdapVCardProvider: No new vcard provided (no changes), accepting."); return true; } // Un-escape username. username = JID.unescapeNode(username); Map<String, String> map = getLdapAttributes(username); // Retrieve LDAP created vcard for comparison Element ldapvCard = new VCard(template).getVCard(map); if (ldapvCard == null) { // This person has no vcard at all, may not change it! Log.debug("LdapVCardProvider: User has no LDAP vcard, nothing they can change, rejecting."); return false; } // If the LDAP vcard has a non-empty PHOTO element set, then there is literally no way this will be accepted. Element ldapPhotoElem = ldapvCard.element("PHOTO"); if (ldapPhotoElem != null) { Element ldapBinvalElem = ldapPhotoElem.element("BINVAL"); if (ldapBinvalElem != null && !ldapBinvalElem.getTextTrim().matches("\\s*")) { // LDAP is providing a valid PHOTO element, byebye! Log.debug("LdapVCardProvider: LDAP has a PHOTO element set, no way to override, rejecting."); return false; } } // Retrieve database vcard, if it exists Element dbvCard = defaultProvider.loadVCard(username); if (dbvCard != null) { Element dbPhotoElem = dbvCard.element("PHOTO"); if (dbPhotoElem == null) { // DB has no photo, lets accept what we got. Log.debug("LdapVCardProvider: Database has no PHOTO element, accepting update."); return true; } else { Element newPhotoElem = newvCard.element("PHOTO"); // Note: NodeComparator never seems to consider these equal, even if they are? if (!dbPhotoElem.asXML().equals(newPhotoElem.asXML())) { Log.debug("LdapVCardProvider: DB photo element is:\n"+dbPhotoElem.asXML()); Log.debug("LdapVCardProvider: New photo element is:\n"+newPhotoElem.asXML()); // Photo element was changed. Ignore all other changes and accept this. Log.debug("LdapVCardProvider: PHOTO element changed, accepting update."); return true; } } } // Ok, either something bad changed or nothing changed. Either way, user either: // 1. should not have tried to change something 'readonly' // 2. shouldn't have bothered submitting no changes // So we'll consider this a bad return. Log.debug("LdapVCardProvider: PHOTO element didn't change, no reason to accept this, rejecting."); return false; }
private Boolean isValidVCardChange(String username, Element newvCard) { if (newvCard == null) { // Well if there's nothing to change, of course it's valid. Log.debug("LdapVCardProvider: No new vcard provided (no changes), accepting."); return true; } // Un-escape username. username = JID.unescapeNode(username); Map<String, String> map = getLdapAttributes(username); // Retrieve LDAP created vcard for comparison Element ldapvCard = new VCard(template).getVCard(map); if (ldapvCard == null) { // This person has no vcard at all, may not change it! Log.debug("LdapVCardProvider: User has no LDAP vcard, nothing they can change, rejecting."); return false; } // If the LDAP vcard has a non-empty PHOTO element set, then there is literally no way this will be accepted. Element ldapPhotoElem = ldapvCard.element("PHOTO"); if (ldapPhotoElem != null) { Element ldapBinvalElem = ldapPhotoElem.element("BINVAL"); if (ldapBinvalElem != null && !ldapBinvalElem.getTextTrim().matches("\\s*")) { // LDAP is providing a valid PHOTO element, byebye! Log.debug("LdapVCardProvider: LDAP has a PHOTO element set, no way to override, rejecting."); return false; } } // Retrieve database vcard, if it exists Element dbvCard = defaultProvider.loadVCard(username); if (dbvCard != null) { Element dbPhotoElem = dbvCard.element("PHOTO"); if (dbPhotoElem == null) { // DB has no photo, lets accept what we got. Log.debug("LdapVCardProvider: Database has no PHOTO element, accepting update."); return true; } else { Element newPhotoElem = newvCard.element("PHOTO"); // Note: NodeComparator never seems to consider these equal, even if they are? if (!dbPhotoElem.asXML().equals(newPhotoElem.asXML())) { Log.debug("LdapVCardProvider: DB photo element is:\n"+dbPhotoElem.asXML()); Log.debug("LdapVCardProvider: New photo element is:\n"+newPhotoElem.asXML()); // Photo element was changed. Ignore all other changes and accept this. Log.debug("LdapVCardProvider: PHOTO element changed, accepting update."); return true; } } } else { // No vcard exists in database Log.debug("LdapVCardProvider: Database has no vCard stored, accepting update."); return true; } // Ok, either something bad changed or nothing changed. Either way, user either: // 1. should not have tried to change something 'readonly' // 2. shouldn't have bothered submitting no changes // So we'll consider this a bad return. Log.debug("LdapVCardProvider: PHOTO element didn't change, no reason to accept this, rejecting."); return false; }
diff --git a/src/test/java/org/atlasapi/feeds/radioplayer/RadioPlayerQueryCompilerTest.java b/src/test/java/org/atlasapi/feeds/radioplayer/RadioPlayerQueryCompilerTest.java index b8a2165b..645d1e00 100644 --- a/src/test/java/org/atlasapi/feeds/radioplayer/RadioPlayerQueryCompilerTest.java +++ b/src/test/java/org/atlasapi/feeds/radioplayer/RadioPlayerQueryCompilerTest.java @@ -1,44 +1,44 @@ package org.atlasapi.feeds.radioplayer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.Set; import java.util.regex.Matcher; import org.atlasapi.content.criteria.AtomicQuery; import org.atlasapi.content.criteria.ContentQuery; import org.atlasapi.feeds.radioplayer.compilers.RadioPlayerFeedCompilers; import org.atlasapi.feeds.radioplayer.compilers.RadioPlayerProgrammeInformationFeedCompiler; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.junit.Test; public class RadioPlayerQueryCompilerTest { RadioPlayerProgrammeInformationFeedCompiler compiler = RadioPlayerFeedCompilers.compilers.get(0); @Test public void testCompileQuery(){ - String filename = "20100906_e1_ce15_c221_0_PI.xml"; + String filename = "20100906_e1_ce15_c222_0_PI.xml"; Matcher matcher = compiler.getPattern().matcher(filename); assertTrue(matcher.matches()); assertEquals(2,matcher.groupCount()); DateTime day = DateTimeFormat.forPattern("yyyyMMdd").parseDateTime(matcher.group(1)); String stationId = matcher.group(2); RadioPlayerServiceIdentifier id = RadioPlayerIDMappings.all.get(stationId); ContentQuery query = compiler.queryFor(day, id.getBroadcastUri()); assertNotNull(query); Set<AtomicQuery> os = query.operands(); assertEquals(3,os.size()); } }
true
true
public void testCompileQuery(){ String filename = "20100906_e1_ce15_c221_0_PI.xml"; Matcher matcher = compiler.getPattern().matcher(filename); assertTrue(matcher.matches()); assertEquals(2,matcher.groupCount()); DateTime day = DateTimeFormat.forPattern("yyyyMMdd").parseDateTime(matcher.group(1)); String stationId = matcher.group(2); RadioPlayerServiceIdentifier id = RadioPlayerIDMappings.all.get(stationId); ContentQuery query = compiler.queryFor(day, id.getBroadcastUri()); assertNotNull(query); Set<AtomicQuery> os = query.operands(); assertEquals(3,os.size()); }
public void testCompileQuery(){ String filename = "20100906_e1_ce15_c222_0_PI.xml"; Matcher matcher = compiler.getPattern().matcher(filename); assertTrue(matcher.matches()); assertEquals(2,matcher.groupCount()); DateTime day = DateTimeFormat.forPattern("yyyyMMdd").parseDateTime(matcher.group(1)); String stationId = matcher.group(2); RadioPlayerServiceIdentifier id = RadioPlayerIDMappings.all.get(stationId); ContentQuery query = compiler.queryFor(day, id.getBroadcastUri()); assertNotNull(query); Set<AtomicQuery> os = query.operands(); assertEquals(3,os.size()); }
diff --git a/Compiler/MAlice/src/codeGeneration/Function.java b/Compiler/MAlice/src/codeGeneration/Function.java index 7a7a157..e2e435b 100644 --- a/Compiler/MAlice/src/codeGeneration/Function.java +++ b/Compiler/MAlice/src/codeGeneration/Function.java @@ -1,138 +1,138 @@ package codeGeneration; import org.antlr.runtime.tree.Tree; import semantics_checks.SemanticsUtils; import symbol_table.DATA_TYPES; import symbol_table.FunctionSTValue; import symbol_table.SymbolTable; public class Function { public static Tree writeCodeForFunctions(Tree node, SymbolTable table, LabelGenerator gen) { if (node.getText().contentEquals("looking")) { return writeCodeForProcedure(node, table, gen); } else if (node.getText().contentEquals("room")){ return writeCodeForFunction(node, table,gen); } return node; } private static Tree writeCodeForProcedure(Tree node, SymbolTable table,LabelGenerator gen ) { Tree current = node.getChild(0); FunctionSTValue fVal = (FunctionSTValue) table.lookup(node.getChild(0).getText()); fVal.setLocationReg(current.getText().contentEquals("hatta")? "@main" : "@" + current); current = SemanticsUtils.getNextChild(current); String params = getParamsForFunctions(current,table); writeFunctionHeader("i32", fVal.getLocationReg(), params); CodeGenerator.incrementIdentLevel(); //DO ALL STATEMENTS current = Statement.checkAllStatements(current, table, gen); //DO ALL STATEMENTS //current = writeNestedFunctions(table, current,gen); writeReturnStatement("i32", "0"); CodeGenerator.decrementIdentLevel(); CodeGenerator.addInstruction("}"); return current; } private static Tree writeCodeForFunction(Tree node, SymbolTable table,LabelGenerator gen) { Tree current = node.getChild(0); System.out.println(node.getChild(0).getText()); FunctionSTValue fVal = (FunctionSTValue) table.lookup(node.getChild(0).getText()); fVal.setLocationReg("@" + current); current = SemanticsUtils.getNextChild(current); - String params = getParamsForFunctions(current,table); + String params = getParamsForFunctions(current,fVal.getTable()); current = SemanticsUtils.getNextChild( SemanticsUtils.getNextChild(current)); writeFunctionHeader( Utils.getReturnTypeOfFunction(fVal.getType()) , fVal.getLocationReg() , params); CodeGenerator.incrementIdentLevel(); //DO ALL STATEMENTS - current = Statement.checkAllStatements(current, table, gen); + current = Statement.checkAllStatements(current, fVal.getTable(), gen); //DO ALL STATEMENTS //current = writeNestedFunctions(table, current,gen); CodeGenerator.decrementIdentLevel(); CodeGenerator.addInstruction("}"); return current; } private static Tree writeNestedFunctions(SymbolTable table, Tree current,LabelGenerator gen) { try { Tree temp = current; while (true) { temp = writeCodeForFunction(current , table,gen); if (temp == current) { break; } //current = StatementChecker.checkAllStatements(curr, table); //THIS HAS TO BE WRITE CODE FOR ALL STATEMENTS current = temp; //THIS HAS TO BE WRITE CODE FOR ALL STATEMENTS } } catch (NullPointerException e) { } return current; } private static String getParamsForFunctions(Tree child, SymbolTable table) { Tree current = child; String params = ""; while (current!=null) { DATA_TYPES type = getType(current.getText()) ; if (type == null) break; params += Utils.getReturnTypeOfFunction(type) + " " + "%" + current.getChild(0).getText() + ", "; current = SemanticsUtils.getNextChild(current); } return (params.length()!=0)? "(" + params.substring(0, params.length()-2) + ")" : "()"; } private static DATA_TYPES getType(String type) { if(type.contentEquals("number")) { return DATA_TYPES.NUMBER; } else if(type.contentEquals("letter")) { return DATA_TYPES.LETTER; } else if (type.contentEquals("sentence")) { return DATA_TYPES.SENTENCE; } return null; } private static void writeFunctionHeader(String ret_type, String name, String params) { CodeGenerator.addInstruction( "define " + ret_type + " " + name + " " + params + " " + "nounwind uwtable readnone {" ); } private static void writeReturnStatement(String ret_type, String val) { CodeGenerator.addInstruction("ret " + ret_type + " " + val); } }
false
true
private static Tree writeCodeForFunction(Tree node, SymbolTable table,LabelGenerator gen) { Tree current = node.getChild(0); System.out.println(node.getChild(0).getText()); FunctionSTValue fVal = (FunctionSTValue) table.lookup(node.getChild(0).getText()); fVal.setLocationReg("@" + current); current = SemanticsUtils.getNextChild(current); String params = getParamsForFunctions(current,table); current = SemanticsUtils.getNextChild( SemanticsUtils.getNextChild(current)); writeFunctionHeader( Utils.getReturnTypeOfFunction(fVal.getType()) , fVal.getLocationReg() , params); CodeGenerator.incrementIdentLevel(); //DO ALL STATEMENTS current = Statement.checkAllStatements(current, table, gen); //DO ALL STATEMENTS //current = writeNestedFunctions(table, current,gen); CodeGenerator.decrementIdentLevel(); CodeGenerator.addInstruction("}"); return current; }
private static Tree writeCodeForFunction(Tree node, SymbolTable table,LabelGenerator gen) { Tree current = node.getChild(0); System.out.println(node.getChild(0).getText()); FunctionSTValue fVal = (FunctionSTValue) table.lookup(node.getChild(0).getText()); fVal.setLocationReg("@" + current); current = SemanticsUtils.getNextChild(current); String params = getParamsForFunctions(current,fVal.getTable()); current = SemanticsUtils.getNextChild( SemanticsUtils.getNextChild(current)); writeFunctionHeader( Utils.getReturnTypeOfFunction(fVal.getType()) , fVal.getLocationReg() , params); CodeGenerator.incrementIdentLevel(); //DO ALL STATEMENTS current = Statement.checkAllStatements(current, fVal.getTable(), gen); //DO ALL STATEMENTS //current = writeNestedFunctions(table, current,gen); CodeGenerator.decrementIdentLevel(); CodeGenerator.addInstruction("}"); return current; }
diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtGL20.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtGL20.java index 306904e82..0cfb305bd 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtGL20.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtGL20.java @@ -1,1105 +1,1105 @@ /******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.backends.gwt; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.HasArrayBufferView; import java.nio.IntBuffer; import java.nio.ShortBuffer; import java.util.HashMap; import java.util.Map; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.utils.GdxRuntimeException; import com.google.gwt.core.client.GWT; import com.google.gwt.typedarrays.client.Float32Array; import com.google.gwt.typedarrays.client.Int16Array; import com.google.gwt.typedarrays.client.Int32Array; import com.google.gwt.typedarrays.client.Uint8Array; import com.google.gwt.webgl.client.WebGLActiveInfo; import com.google.gwt.webgl.client.WebGLBuffer; import com.google.gwt.webgl.client.WebGLFramebuffer; import com.google.gwt.webgl.client.WebGLProgram; import com.google.gwt.webgl.client.WebGLRenderbuffer; import com.google.gwt.webgl.client.WebGLRenderingContext; import com.google.gwt.webgl.client.WebGLShader; import com.google.gwt.webgl.client.WebGLTexture; import com.google.gwt.webgl.client.WebGLUniformLocation; public class GwtGL20 implements GL20 { final Map<Integer, WebGLProgram> programs = new HashMap<Integer, WebGLProgram>(); int nextProgramId = 1; final Map<Integer, WebGLShader> shaders = new HashMap<Integer, WebGLShader>(); int nextShaderId = 1; final Map<Integer, WebGLBuffer> buffers = new HashMap<Integer, WebGLBuffer>(); int nextBufferId = 1; final Map<Integer, WebGLFramebuffer> frameBuffers = new HashMap<Integer, WebGLFramebuffer>(); int nextFrameBufferId = 1; final Map<Integer, WebGLRenderbuffer> renderBuffers = new HashMap<Integer, WebGLRenderbuffer>(); int nextRenderBufferId = 1; final Map<Integer, WebGLTexture> textures = new HashMap<Integer, WebGLTexture>(); int nextTextureId = 1; final Map<Integer, Map<Integer, WebGLUniformLocation>> uniforms = new HashMap<Integer, Map<Integer, WebGLUniformLocation>>(); int nextUniformId = 1; int currProgram = 0; Float32Array floatBuffer = Float32Array.create(2000 * 20); Int16Array shortBuffer = Int16Array.create(2000 * 6); final WebGLRenderingContext gl; protected GwtGL20 (WebGLRenderingContext gl) { this.gl = gl; this.gl.pixelStorei(WebGLRenderingContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0); } private void ensureCapacity (FloatBuffer buffer) { if (buffer.remaining() > floatBuffer.getLength()) { floatBuffer = Float32Array.create(buffer.remaining()); } } private void ensureCapacity (ShortBuffer buffer) { if (buffer.remaining() > shortBuffer.getLength()) { shortBuffer = Int16Array.create(buffer.remaining()); } } public Float32Array copy (FloatBuffer buffer) { if (GWT.isProdMode()) { return ((Float32Array)((HasArrayBufferView)buffer).getTypedArray()).subarray(buffer.position(), buffer.remaining()); } else { ensureCapacity(buffer); float[] array = buffer.array(); for (int i = buffer.position(), j = 0; i < buffer.limit(); i++, j++) { floatBuffer.set(j, array[i]); } return floatBuffer.subarray(0, buffer.remaining()); } } public Int16Array copy (ShortBuffer buffer) { if (GWT.isProdMode()) { return ((Int16Array)((HasArrayBufferView)buffer).getTypedArray()).subarray(buffer.position(), buffer.remaining()); } else { ensureCapacity(buffer); short[] array = buffer.array(); for (int i = buffer.position(), j = 0; i < buffer.limit(); i++, j++) { shortBuffer.set(j, array[i]); } return shortBuffer.subarray(0, buffer.remaining()); } } private int allocateUniformLocationId (int program, WebGLUniformLocation location) { Map<Integer, WebGLUniformLocation> progUniforms = uniforms.get(program); if (progUniforms == null) { progUniforms = new HashMap<Integer, WebGLUniformLocation>(); uniforms.put(program, progUniforms); } // FIXME check if uniform already stored. int id = nextUniformId++; progUniforms.put(id, location); return id; } private WebGLUniformLocation getUniformLocation (int location) { return uniforms.get(currProgram).get(location); } private int allocateShaderId (WebGLShader shader) { int id = nextShaderId++; shaders.put(id, shader); return id; } private void deallocateShaderId (int id) { shaders.remove(id); } private int allocateProgramId (WebGLProgram program) { int id = nextProgramId++; programs.put(id, program); return id; } private void deallocateProgramId (int id) { uniforms.remove(id); programs.remove(id); } private int allocateBufferId (WebGLBuffer buffer) { int id = nextBufferId++; buffers.put(id, buffer); return id; } private void deallocateBufferId (int id) { buffers.remove(id); } private int allocateFrameBufferId (WebGLFramebuffer frameBuffer) { int id = nextBufferId++; frameBuffers.put(id, frameBuffer); return id; } private void deallocateFrameBufferId (int id) { frameBuffers.remove(id); } private int allocateRenderBufferId (WebGLRenderbuffer renderBuffer) { int id = nextRenderBufferId++; renderBuffers.put(id, renderBuffer); return id; } private void deallocateRenderBufferId (int id) { renderBuffers.remove(id); } private int allocateTextureId (WebGLTexture texture) { int id = nextTextureId++; textures.put(id, texture); return id; } private void deallocateTextureId (int id) { textures.remove(id); } @Override public void glActiveTexture (int texture) { gl.activeTexture(texture); } @Override public void glBindTexture (int target, int texture) { gl.bindTexture(target, textures.get(texture)); } @Override public void glBlendFunc (int sfactor, int dfactor) { gl.blendFunc(sfactor, dfactor); } @Override public void glClear (int mask) { gl.clear(mask); } @Override public void glClearColor (float red, float green, float blue, float alpha) { gl.clearColor(red, green, blue, alpha); } @Override public void glClearDepthf (float depth) { gl.clearDepth(depth); } @Override public void glClearStencil (int s) { gl.clearStencil(s); } @Override public void glColorMask (boolean red, boolean green, boolean blue, boolean alpha) { gl.colorMask(red, green, blue, alpha); } @Override public void glCompressedTexImage2D (int target, int level, int internalformat, int width, int height, int border, int imageSize, Buffer data) { throw new GdxRuntimeException("compressed textures not supported by GWT WebGL backend"); } @Override public void glCompressedTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format, int imageSize, Buffer data) { throw new GdxRuntimeException("compressed textures not supported by GWT WebGL backend"); } @Override public void glCopyTexImage2D (int target, int level, int internalformat, int x, int y, int width, int height, int border) { gl.copyTexImage2D(target, level, internalformat, x, y, width, height, border); } @Override public void glCopyTexSubImage2D (int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) { gl.copyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); } @Override public void glCullFace (int mode) { gl.cullFace(mode); } @Override public void glDeleteTextures (int n, IntBuffer textures) { for (int i = 0; i < n; i++) { int id = textures.get(); WebGLTexture texture = this.textures.get(id); deallocateTextureId(id); gl.deleteTexture(texture); } } @Override public void glDepthFunc (int func) { gl.depthFunc(func); } @Override public void glDepthMask (boolean flag) { gl.depthMask(flag); } @Override public void glDepthRangef (float zNear, float zFar) { gl.depthRange(zNear, zFar); } @Override public void glDisable (int cap) { gl.disable(cap); } @Override public void glDrawArrays (int mode, int first, int count) { gl.drawArrays(mode, first, count); } @Override public void glDrawElements (int mode, int count, int type, Buffer indices) { gl.drawElements(mode, count, type, indices.position()); // FIXME this is assuming WebGL supports client side buffers... } @Override public void glEnable (int cap) { gl.enable(cap); } @Override public void glFinish () { gl.finish(); } @Override public void glFlush () { gl.flush(); } @Override public void glFrontFace (int mode) { gl.frontFace(mode); } @Override public void glGenTextures (int n, IntBuffer textures) { WebGLTexture texture = gl.createTexture(); int id = allocateTextureId(texture); textures.put(id); } @Override public int glGetError () { return gl.getError(); } @Override public void glGetIntegerv (int pname, IntBuffer params) { // FIXME throw new GdxRuntimeException("glGetInteger not supported by GWT WebGL backend"); } @Override public String glGetString (int name) { // FIXME throw new GdxRuntimeException("not implemented"); } @Override public void glHint (int target, int mode) { gl.hint(target, mode); } @Override public void glLineWidth (float width) { gl.lineWidth(width); } @Override public void glPixelStorei (int pname, int param) { gl.pixelStorei(pname, param); } @Override public void glPolygonOffset (float factor, float units) { gl.polygonOffset(factor, units); } @Override public void glReadPixels (int x, int y, int width, int height, int format, int type, Buffer pixels) { // verify request - if ((format != WebGLRenderingContext.UNSIGNED_BYTE) || (type != WebGLRenderingContext.RGBA)) { + if ((format != WebGLRenderingContext.RGBA) || (type != WebGLRenderingContext.UNSIGNED_BYTE)) { throw new GdxRuntimeException("Only format UNSIGNED_BYTE for type RGBA is currently supported."); } if (!(pixels instanceof ByteBuffer)) { throw new GdxRuntimeException("Inputed pixels buffer needs to be of type ByteBuffer."); } // create new ArrayBufferView (4 bytes per pixel) int size = 4 * width * height; Uint8Array buffer = Uint8Array.create(size); // read bytes to ArrayBufferView gl.readPixels(x, y, width, height, format, type, buffer); // copy ArrayBufferView to our pixels array ByteBuffer pixelsByte = (ByteBuffer)pixels; for (int i = 0; i < size; i++) { pixelsByte.put((byte)(buffer.get(i) & 0x000000ff)); } } @Override public void glScissor (int x, int y, int width, int height) { gl.scissor(x, y, width, height); } @Override public void glStencilFunc (int func, int ref, int mask) { gl.stencilFunc(func, ref, mask); } @Override public void glStencilMask (int mask) { gl.stencilMask(mask); } @Override public void glStencilOp (int fail, int zfail, int zpass) { gl.stencilOp(fail, zfail, zpass); } @Override public void glTexImage2D (int target, int level, int internalformat, int width, int height, int border, int format, int type, Buffer pixels) { Pixmap pixmap = Pixmap.pixmaps.get(((IntBuffer)pixels).get(0)); gl.texImage2D(target, level, internalformat, format, type, pixmap.getCanvasElement()); } @Override public void glTexParameterf (int target, int pname, float param) { gl.texParameterf(target, pname, param); } @Override public void glTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, Buffer pixels) { Pixmap pixmap = Pixmap.pixmaps.get(((IntBuffer)pixels).get(0)); gl.texSubImage2D(target, level, xoffset, yoffset, width, height, pixmap.getCanvasElement()); } @Override public void glViewport (int x, int y, int width, int height) { gl.viewport(x, y, width, height); } @Override public void glAttachShader (int program, int shader) { WebGLProgram glProgram = programs.get(program); WebGLShader glShader = shaders.get(shader); gl.attachShader(glProgram, glShader); } @Override public void glBindAttribLocation (int program, int index, String name) { WebGLProgram glProgram = programs.get(program); gl.bindAttribLocation(glProgram, index, name); } @Override public void glBindBuffer (int target, int buffer) { gl.bindBuffer(target, buffers.get(buffer)); } @Override public void glBindFramebuffer (int target, int framebuffer) { gl.bindFramebuffer(target, frameBuffers.get(framebuffer)); } @Override public void glBindRenderbuffer (int target, int renderbuffer) { gl.bindRenderbuffer(target, renderBuffers.get(renderbuffer)); } @Override public void glBlendColor (float red, float green, float blue, float alpha) { gl.blendColor(red, green, blue, alpha); } @Override public void glBlendEquation (int mode) { gl.blendEquation(mode); } @Override public void glBlendEquationSeparate (int modeRGB, int modeAlpha) { gl.blendEquationSeparate(modeRGB, modeAlpha); } @Override public void glBlendFuncSeparate (int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { gl.blendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); } @Override public void glBufferData (int target, int size, Buffer data, int usage) { if (data instanceof FloatBuffer) { gl.bufferData(target, copy((FloatBuffer)data), usage); } else if (data instanceof ShortBuffer) { gl.bufferData(target, copy((ShortBuffer)data), usage); } else { throw new GdxRuntimeException("Can only cope with FloatBuffer and ShortBuffer at the moment"); } } @Override public void glBufferSubData (int target, int offset, int size, Buffer data) { if (data instanceof FloatBuffer) { gl.bufferSubData(target, offset, copy((FloatBuffer)data)); } else if (data instanceof ShortBuffer) { gl.bufferSubData(target, offset, copy((ShortBuffer)data)); } else { throw new GdxRuntimeException("Can only cope with FloatBuffer and ShortBuffer at the moment"); } } @Override public int glCheckFramebufferStatus (int target) { return gl.checkFramebufferStatus(target); } @Override public void glCompileShader (int shader) { WebGLShader glShader = shaders.get(shader); gl.compileShader(glShader); } @Override public int glCreateProgram () { WebGLProgram program = gl.createProgram(); return allocateProgramId(program); } @Override public int glCreateShader (int type) { WebGLShader shader = gl.createShader(type); return allocateShaderId(shader); } @Override public void glDeleteBuffers (int n, IntBuffer buffers) { for (int i = 0; i < n; i++) { int id = buffers.get(); WebGLBuffer buffer = this.buffers.get(id); deallocateBufferId(id); gl.deleteBuffer(buffer); } } @Override public void glDeleteFramebuffers (int n, IntBuffer framebuffers) { for (int i = 0; i < n; i++) { int id = framebuffers.get(); WebGLFramebuffer fb = this.frameBuffers.get(id); deallocateFrameBufferId(id); gl.deleteFramebuffer(fb); } } @Override public void glDeleteProgram (int program) { WebGLProgram prog = programs.get(program); deallocateProgramId(program); gl.deleteProgram(prog); } @Override public void glDeleteRenderbuffers (int n, IntBuffer renderbuffers) { for (int i = 0; i < n; i++) { int id = renderbuffers.get(); WebGLRenderbuffer rb = this.renderBuffers.get(id); deallocateRenderBufferId(id); gl.deleteRenderbuffer(rb); } } @Override public void glDeleteShader (int shader) { WebGLShader sh = shaders.get(shader); deallocateShaderId(shader); gl.deleteShader(sh); } @Override public void glDetachShader (int program, int shader) { gl.detachShader(programs.get(program), shaders.get(shader)); } @Override public void glDisableVertexAttribArray (int index) { gl.disableVertexAttribArray(index); } @Override public void glDrawElements (int mode, int count, int type, int indices) { gl.drawElements(mode, count, type, indices); } @Override public void glEnableVertexAttribArray (int index) { gl.enableVertexAttribArray(index); } @Override public void glFramebufferRenderbuffer (int target, int attachment, int renderbuffertarget, int renderbuffer) { gl.framebufferRenderbuffer(target, attachment, renderbuffertarget, renderBuffers.get(renderbuffer)); } @Override public void glFramebufferTexture2D (int target, int attachment, int textarget, int texture, int level) { gl.framebufferTexture2D(target, attachment, textarget, textures.get(texture), level); } @Override public void glGenBuffers (int n, IntBuffer buffers) { for (int i = 0; i < n; i++) { WebGLBuffer buffer = gl.createBuffer(); int id = allocateBufferId(buffer); buffers.put(id); } } @Override public void glGenerateMipmap (int target) { gl.generateMipmap(target); } @Override public void glGenFramebuffers (int n, IntBuffer framebuffers) { for (int i = 0; i < n; i++) { WebGLFramebuffer fb = gl.createFramebuffer(); int id = allocateFrameBufferId(fb); framebuffers.put(id); } } @Override public void glGenRenderbuffers (int n, IntBuffer renderbuffers) { for (int i = 0; i < n; i++) { WebGLRenderbuffer rb = gl.createRenderbuffer(); int id = allocateRenderBufferId(rb); renderbuffers.put(id); } } @Override public String glGetActiveAttrib (int program, int index, IntBuffer size, Buffer type) { WebGLActiveInfo activeAttrib = gl.getActiveAttrib(programs.get(program), index); size.put(activeAttrib.getSize()); ((IntBuffer)type).put(activeAttrib.getType()); return activeAttrib.getName(); } @Override public String glGetActiveUniform (int program, int index, IntBuffer size, Buffer type) { WebGLActiveInfo activeUniform = gl.getActiveUniform(programs.get(program), index); size.put(activeUniform.getSize()); ((IntBuffer)type).put(activeUniform.getType()); return activeUniform.getName(); } @Override public void glGetAttachedShaders (int program, int maxcount, Buffer count, IntBuffer shaders) { // FIXME throw new GdxRuntimeException("not implemented"); } @Override public int glGetAttribLocation (int program, String name) { WebGLProgram prog = programs.get(program); return gl.getAttribLocation(prog, name); } @Override public void glGetBooleanv (int pname, Buffer params) { throw new GdxRuntimeException("glGetBoolean not supported by GWT WebGL backend"); } @Override public void glGetBufferParameteriv (int target, int pname, IntBuffer params) { // FIXME throw new GdxRuntimeException("not implemented"); } @Override public void glGetFloatv (int pname, FloatBuffer params) { throw new GdxRuntimeException("glGetFloat not supported by GWT WebGL backend"); } @Override public void glGetFramebufferAttachmentParameteriv (int target, int attachment, int pname, IntBuffer params) { // FIXME throw new GdxRuntimeException("not implemented"); } @Override public void glGetProgramiv (int program, int pname, IntBuffer params) { if (pname == GL20.GL_DELETE_STATUS || pname == GL20.GL_LINK_STATUS || pname == GL20.GL_VALIDATE_STATUS) { boolean result = gl.getProgramParameterb(programs.get(program), pname); params.put(result ? GL20.GL_TRUE : GL20.GL_FALSE); } else { params.put(gl.getProgramParameteri(programs.get(program), pname)); } } @Override public String glGetProgramInfoLog (int program) { return gl.getProgramInfoLog(programs.get(program)); } @Override public void glGetRenderbufferParameteriv (int target, int pname, IntBuffer params) { // FIXME throw new GdxRuntimeException("not implemented"); } @Override public void glGetShaderiv (int shader, int pname, IntBuffer params) { if (pname == GL20.GL_COMPILE_STATUS || pname == GL20.GL_DELETE_STATUS) { boolean result = gl.getShaderParameterb(shaders.get(shader), pname); params.put(result ? GL20.GL_TRUE : GL20.GL_FALSE); } else { int result = gl.getShaderParameteri(shaders.get(shader), pname); params.put(result); } } @Override public String glGetShaderInfoLog (int shader) { return gl.getShaderInfoLog(shaders.get(shader)); } @Override public void glGetShaderPrecisionFormat (int shadertype, int precisiontype, IntBuffer range, IntBuffer precision) { throw new GdxRuntimeException("glGetShaderPrecisionFormat not supported by GWT WebGL backend"); } @Override public void glGetShaderSource (int shader, int bufsize, Buffer length, String source) { throw new GdxRuntimeException("glGetShaderSource not supported by GWT WebGL backend"); } @Override public void glGetTexParameterfv (int target, int pname, FloatBuffer params) { throw new GdxRuntimeException("glGetTexParameter not supported by GWT WebGL backend"); } @Override public void glGetTexParameteriv (int target, int pname, IntBuffer params) { throw new GdxRuntimeException("glGetTexParameter not supported by GWT WebGL backend"); } @Override public void glGetUniformfv (int program, int location, FloatBuffer params) { // FIXME throw new GdxRuntimeException("not implemented"); } @Override public void glGetUniformiv (int program, int location, IntBuffer params) { // FIXME throw new GdxRuntimeException("not implemented"); } @Override public int glGetUniformLocation (int program, String name) { WebGLUniformLocation location = gl.getUniformLocation(programs.get(program), name); return allocateUniformLocationId(program, location); } @Override public void glGetVertexAttribfv (int index, int pname, FloatBuffer params) { // FIXME throw new GdxRuntimeException("not implemented"); } @Override public void glGetVertexAttribiv (int index, int pname, IntBuffer params) { // FIXME throw new GdxRuntimeException("not implemented"); } @Override public void glGetVertexAttribPointerv (int index, int pname, Buffer pointer) { throw new GdxRuntimeException("glGetVertexAttribPointer not supported by GWT WebGL backend"); } @Override public boolean glIsBuffer (int buffer) { return gl.isBuffer(buffers.get(buffer)); } @Override public boolean glIsEnabled (int cap) { return gl.isEnabled(cap); } @Override public boolean glIsFramebuffer (int framebuffer) { return gl.isFramebuffer(frameBuffers.get(framebuffer)); } @Override public boolean glIsProgram (int program) { return gl.isProgram(programs.get(program)); } @Override public boolean glIsRenderbuffer (int renderbuffer) { return gl.isRenderbuffer(renderBuffers.get(renderbuffer)); } @Override public boolean glIsShader (int shader) { return gl.isShader(shaders.get(shader)); } @Override public boolean glIsTexture (int texture) { return gl.isTexture(textures.get(texture)); } @Override public void glLinkProgram (int program) { gl.linkProgram(programs.get(program)); } @Override public void glReleaseShaderCompiler () { throw new GdxRuntimeException("not implemented"); } @Override public void glRenderbufferStorage (int target, int internalformat, int width, int height) { gl.renderbufferStorage(target, internalformat, width, height); } @Override public void glSampleCoverage (float value, boolean invert) { gl.sampleCoverage(value, invert); } @Override public void glShaderBinary (int n, IntBuffer shaders, int binaryformat, Buffer binary, int length) { throw new GdxRuntimeException("glShaderBinary not supported by GWT WebGL backend"); } @Override public void glShaderSource (int shader, String source) { gl.shaderSource(shaders.get(shader), source); } @Override public void glStencilFuncSeparate (int face, int func, int ref, int mask) { gl.stencilFuncSeparate(face, func, ref, mask); } @Override public void glStencilMaskSeparate (int face, int mask) { gl.stencilMaskSeparate(face, mask); } @Override public void glStencilOpSeparate (int face, int fail, int zfail, int zpass) { gl.stencilOpSeparate(face, fail, zfail, zpass); } @Override public void glTexParameterfv (int target, int pname, FloatBuffer params) { gl.texParameterf(target, pname, params.get()); } @Override public void glTexParameteri (int target, int pname, int param) { gl.texParameterf(target, pname, param); } @Override public void glTexParameteriv (int target, int pname, IntBuffer params) { gl.texParameterf(target, pname, params.get()); } @Override public void glUniform1f (int location, float x) { WebGLUniformLocation loc = getUniformLocation(location); gl.uniform1f(loc, x); } @Override public void glUniform1fv (int location, int count, FloatBuffer v) { WebGLUniformLocation loc = getUniformLocation(location); if (GWT.isProdMode()) { gl.uniform1fv(loc, ((Float32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining())); } else { gl.uniform1fv(loc, v.array()); } } @Override public void glUniform1i (int location, int x) { WebGLUniformLocation loc = getUniformLocation(location); gl.uniform1i(loc, x); } @Override public void glUniform1iv (int location, int count, IntBuffer v) { WebGLUniformLocation loc = getUniformLocation(location); if (GWT.isProdMode()) { gl.uniform1iv(loc, ((Int32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining())); } else { gl.uniform1iv(loc, v.array()); } } @Override public void glUniform2f (int location, float x, float y) { WebGLUniformLocation loc = getUniformLocation(location); gl.uniform2f(loc, x, y); } @Override public void glUniform2fv (int location, int count, FloatBuffer v) { WebGLUniformLocation loc = getUniformLocation(location); if (GWT.isProdMode()) { gl.uniform2fv(loc, ((Float32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining())); ; } else { gl.uniform2fv(loc, v.array()); } } @Override public void glUniform2i (int location, int x, int y) { WebGLUniformLocation loc = getUniformLocation(location); gl.uniform2i(loc, x, y); } @Override public void glUniform2iv (int location, int count, IntBuffer v) { WebGLUniformLocation loc = getUniformLocation(location); if (GWT.isProdMode()) { gl.uniform2iv(loc, ((Int32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining())); } else { gl.uniform2iv(loc, v.array()); } } @Override public void glUniform3f (int location, float x, float y, float z) { WebGLUniformLocation loc = getUniformLocation(location); gl.uniform3f(loc, x, y, z); } @Override public void glUniform3fv (int location, int count, FloatBuffer v) { WebGLUniformLocation loc = getUniformLocation(location); if (GWT.isProdMode()) { gl.uniform3fv(loc, ((Float32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining())); } else { gl.uniform3fv(loc, v.array()); } } @Override public void glUniform3i (int location, int x, int y, int z) { WebGLUniformLocation loc = getUniformLocation(location); gl.uniform3i(loc, x, y, z); } @Override public void glUniform3iv (int location, int count, IntBuffer v) { WebGLUniformLocation loc = getUniformLocation(location); if (GWT.isProdMode()) { gl.uniform3iv(loc, ((Int32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining())); } else { gl.uniform3iv(loc, v.array()); } } @Override public void glUniform4f (int location, float x, float y, float z, float w) { WebGLUniformLocation loc = getUniformLocation(location); gl.uniform4f(loc, x, y, z, w); } @Override public void glUniform4fv (int location, int count, FloatBuffer v) { WebGLUniformLocation loc = getUniformLocation(location); if (GWT.isProdMode()) { gl.uniform4fv(loc, ((Float32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining())); } else { gl.uniform4fv(loc, v.array()); } } @Override public void glUniform4i (int location, int x, int y, int z, int w) { WebGLUniformLocation loc = getUniformLocation(location); gl.uniform4i(loc, x, y, z, w); } @Override public void glUniform4iv (int location, int count, IntBuffer v) { WebGLUniformLocation loc = getUniformLocation(location); if (GWT.isProdMode()) { gl.uniform4iv(loc, ((Int32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining())); } else { gl.uniform4iv(loc, v.array()); } } @Override public void glUniformMatrix2fv (int location, int count, boolean transpose, FloatBuffer value) { WebGLUniformLocation loc = getUniformLocation(location); if (GWT.isProdMode()) { gl.uniformMatrix2fv(loc, transpose, ((Float32Array)((HasArrayBufferView)value).getTypedArray()).subarray(value.position(), value.remaining())); } else { gl.uniformMatrix2fv(loc, transpose, value.array()); } } @Override public void glUniformMatrix3fv (int location, int count, boolean transpose, FloatBuffer value) { WebGLUniformLocation loc = getUniformLocation(location); if (GWT.isProdMode()) { gl.uniformMatrix3fv(loc, transpose, ((Float32Array)((HasArrayBufferView)value).getTypedArray()).subarray(value.position(), value.remaining())); } else { gl.uniformMatrix3fv(loc, transpose, value.array()); } } @Override public void glUniformMatrix4fv (int location, int count, boolean transpose, FloatBuffer value) { WebGLUniformLocation loc = getUniformLocation(location); if (GWT.isProdMode()) { gl.uniformMatrix4fv(loc, transpose, ((Float32Array)((HasArrayBufferView)value).getTypedArray()).subarray(value.position(), value.remaining())); } else { gl.uniformMatrix4fv(loc, transpose, value.array()); } } @Override public void glUseProgram (int program) { currProgram = program; gl.useProgram(programs.get(program)); } @Override public void glValidateProgram (int program) { gl.validateProgram(programs.get(program)); } @Override public void glVertexAttrib1f (int indx, float x) { gl.vertexAttrib1f(indx, x); } @Override public void glVertexAttrib1fv (int indx, FloatBuffer values) { if (GWT.isProdMode()) { gl.vertexAttrib1fv(indx, ((Float32Array)((HasArrayBufferView)values).getTypedArray()).subarray(values.position(), values.remaining())); } else { gl.vertexAttrib1fv(indx, values.array()); } } @Override public void glVertexAttrib2f (int indx, float x, float y) { gl.vertexAttrib2f(indx, x, y); } @Override public void glVertexAttrib2fv (int indx, FloatBuffer values) { if (GWT.isProdMode()) { gl.vertexAttrib2fv(indx, ((Float32Array)((HasArrayBufferView)values).getTypedArray()).subarray(values.position(), values.remaining())); } else { gl.vertexAttrib2fv(indx, values.array()); } } @Override public void glVertexAttrib3f (int indx, float x, float y, float z) { gl.vertexAttrib3f(indx, x, y, z); } @Override public void glVertexAttrib3fv (int indx, FloatBuffer values) { if (GWT.isProdMode()) { gl.vertexAttrib3fv(indx, ((Float32Array)((HasArrayBufferView)values).getTypedArray()).subarray(values.position(), values.remaining())); } else { gl.vertexAttrib3fv(indx, values.array()); } } @Override public void glVertexAttrib4f (int indx, float x, float y, float z, float w) { gl.vertexAttrib4f(indx, x, y, z, w); } @Override public void glVertexAttrib4fv (int indx, FloatBuffer values) { if (GWT.isProdMode()) { gl.vertexAttrib4fv(indx, ((Float32Array)((HasArrayBufferView)values).getTypedArray()).subarray(values.position(), values.remaining())); } else { gl.vertexAttrib4fv(indx, values.array()); } } @Override public void glVertexAttribPointer (int indx, int size, int type, boolean normalized, int stride, Buffer ptr) { throw new GdxRuntimeException("not implemented, vertex arrays aren't support in WebGL it seems"); } @Override public void glVertexAttribPointer (int indx, int size, int type, boolean normalized, int stride, int ptr) { gl.vertexAttribPointer(indx, size, type, normalized, stride, ptr); } }
true
true
public void glReadPixels (int x, int y, int width, int height, int format, int type, Buffer pixels) { // verify request if ((format != WebGLRenderingContext.UNSIGNED_BYTE) || (type != WebGLRenderingContext.RGBA)) { throw new GdxRuntimeException("Only format UNSIGNED_BYTE for type RGBA is currently supported."); } if (!(pixels instanceof ByteBuffer)) { throw new GdxRuntimeException("Inputed pixels buffer needs to be of type ByteBuffer."); } // create new ArrayBufferView (4 bytes per pixel) int size = 4 * width * height; Uint8Array buffer = Uint8Array.create(size); // read bytes to ArrayBufferView gl.readPixels(x, y, width, height, format, type, buffer); // copy ArrayBufferView to our pixels array ByteBuffer pixelsByte = (ByteBuffer)pixels; for (int i = 0; i < size; i++) { pixelsByte.put((byte)(buffer.get(i) & 0x000000ff)); } }
public void glReadPixels (int x, int y, int width, int height, int format, int type, Buffer pixels) { // verify request if ((format != WebGLRenderingContext.RGBA) || (type != WebGLRenderingContext.UNSIGNED_BYTE)) { throw new GdxRuntimeException("Only format UNSIGNED_BYTE for type RGBA is currently supported."); } if (!(pixels instanceof ByteBuffer)) { throw new GdxRuntimeException("Inputed pixels buffer needs to be of type ByteBuffer."); } // create new ArrayBufferView (4 bytes per pixel) int size = 4 * width * height; Uint8Array buffer = Uint8Array.create(size); // read bytes to ArrayBufferView gl.readPixels(x, y, width, height, format, type, buffer); // copy ArrayBufferView to our pixels array ByteBuffer pixelsByte = (ByteBuffer)pixels; for (int i = 0; i < size; i++) { pixelsByte.put((byte)(buffer.get(i) & 0x000000ff)); } }
diff --git a/bootstrap/src/main/java/org/soluvas/web/bootstrap/BootstrapPage.java b/bootstrap/src/main/java/org/soluvas/web/bootstrap/BootstrapPage.java index 67ba7911..abb4adcf 100644 --- a/bootstrap/src/main/java/org/soluvas/web/bootstrap/BootstrapPage.java +++ b/bootstrap/src/main/java/org/soluvas/web/bootstrap/BootstrapPage.java @@ -1,436 +1,437 @@ package org.soluvas.web.bootstrap; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.inject.Inject; import org.apache.wicket.AttributeModifier; import org.apache.wicket.Component; import org.apache.wicket.Page; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.html.IHeaderResponse; import org.apache.wicket.markup.html.TransparentWebMarkupContainer; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.markup.repeater.RepeatingView; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.request.Response; import org.apache.wicket.util.visit.IVisit; import org.apache.wicket.util.visit.IVisitor; import org.ops4j.pax.wicket.api.PaxWicketBean; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.soluvas.commons.AppManifest; import org.soluvas.commons.WebAddress; import org.soluvas.commons.inject.Filter; import org.soluvas.commons.inject.Supplied; import org.soluvas.commons.tenant.TenantRef; import org.soluvas.data.repository.CrudRepository; import org.soluvas.web.site.AmdJavaScriptSource; import org.soluvas.web.site.AsyncModel; import org.soluvas.web.site.CssLink; import org.soluvas.web.site.ExtensiblePage; import org.soluvas.web.site.JavaScriptLink; import org.soluvas.web.site.JavaScriptLinkImpl; import org.soluvas.web.site.JavaScriptSource; import org.soluvas.web.site.PageMetaSupplier; import org.soluvas.web.site.PageMetaSupplierFactory; import org.soluvas.web.site.PageRuleContext; import org.soluvas.web.site.Site; import org.soluvas.web.site.client.AmdDependency; import org.soluvas.web.site.client.JsSource; import org.soluvas.web.site.compose.ComposeUtils; import org.soluvas.web.site.compose.LiveContributor; import org.soluvas.web.site.osgi.WebTenantUtils; import org.soluvas.web.site.pagemeta.PageMeta; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.base.Strings; import com.google.common.base.Supplier; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.Ordering; /** * Base page for Twitter Bootstrap-powered Wicket pages. * @author ceefour */ @SuppressWarnings("serial") public class BootstrapPage extends ExtensiblePage { public static class MetaTag extends WebMarkupContainer { /** * @param id * @param model */ public MetaTag(String id, IModel<String> model) { super(id, model); add(new AttributeModifier("content", model)); } @Override protected void onConfigure() { super.onConfigure(); setVisible(!Strings.isNullOrEmpty(getDefaultModelObjectAsString())); } } /** * Usage: * * <pre>{@code * final Builder<String, String> dependencies = ImmutableMap.builder(); * new AmdDependencyVisitor(dependencies).component(BootstrapPage.this, null); * visitChildren(new AmdDependencyVisitor(dependencies)); * final Map<String, String> dependencyMap = dependencies.build(); * log.debug("Page {} has {} AMD dependencies: {}", getClass().getName(), dependencyMap.size(), * dependencyMap.keySet()); * }</pre> * * @author ceefour */ public static final class AmdDependencyVisitor implements IVisitor<Component, Void> { private final Builder<String, String> dependencies; public AmdDependencyVisitor(Builder<String, String> dependencies) { this.dependencies = dependencies; } @Override public void component(Component component, IVisit<Void> visit) { List<AmdDependency> amdDeps = component.getBehaviors(AmdDependency.class); for (AmdDependency dep : amdDeps) { dependencies.put(dep.getPath(), dep.getName()); } } } public static final class JsSourceVisitor implements IVisitor<Component, Void> { private final ImmutableList.Builder<String> jsSources; public JsSourceVisitor(ImmutableList.Builder<String> jsSources) { this.jsSources = jsSources; } @Override public void component(Component component, IVisit<Void> visit) { List<JsSource> jsSourceBehaviors = component.getBehaviors(JsSource.class); for (JsSource src : jsSourceBehaviors) { jsSources.add( src.getJsSource() ); } } } private static final Logger log = LoggerFactory.getLogger(BootstrapPage.class); @PaxWicketBean(name="jacksonMapperFactory") private Supplier<ObjectMapper> jacksonMapperFactory; /** * Should not use {@link Site} directly! */ // @PaxWicketBean(name="site") @Deprecated // private Site site; @PaxWicketBean(name="cssLinks") private List<CssLink> cssLinks; @PaxWicketBean(name="headJavaScripts") private List<JavaScriptLink> headJavaScripts; @PaxWicketBean(name="footerJavaScripts") private List<JavaScriptLink> footerJavaScripts; @PaxWicketBean(name="footerJavaScriptSources") private List<JavaScriptSource> footerJavaScriptSources; protected final RepeatingView sidebarBlocks; // @PaxWicketBean(name="pageRulesSupplier") // private Supplier<List<PageRule>> pageRulesSupplier; @Inject private PageMetaSupplierFactory<PageMetaSupplier> pageMetaSupplierFactory; @Inject @Supplied private WebAddress webAddress; @Inject @Supplied @Filter("(layer=application)") private AppManifest appManifest; @PaxWicketBean(name="contributors") private CrudRepository<LiveContributor, Integer> contributors; private final List<JavaScriptLink> pageJavaScriptLinks = new ArrayList<JavaScriptLink>(); protected Component feedbackPanel; protected TransparentWebMarkupContainer contentColumn; protected TransparentWebMarkupContainer sidebarColumn; private TenantRef tenant; protected final RepeatingView afterHeader; public JavaScriptLink addJsLink(String uri) { JavaScriptLinkImpl js = new JavaScriptLinkImpl(uri, 100); pageJavaScriptLinks.add(js); return js; } @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); final List<CssLink> filteredCsses = ImmutableList.copyOf(Collections2.filter(cssLinks, new Predicate<CssLink>() { @Override public boolean apply(@Nullable CssLink input) { return Strings.isNullOrEmpty(input.getTenantId()) || "*".equals(input.getTenantId()) || tenant.getTenantId().equals(input.getTenantId()); } })); log.debug("Page {} has {} CSS links (from {} total)", getClass().getName(), filteredCsses.size(), cssLinks.size()); final Ordering<CssLink> cssOrdering = Ordering.from(new Comparator<CssLink>() { @Override public int compare(CssLink o1, CssLink o2) { return o1.getWeight() - o2.getWeight(); }; }); final List<CssLink> sortedCsses = cssOrdering.immutableSortedCopy(filteredCsses); for (CssLink css : sortedCsses) { response.renderCSSReference(webAddress.getSkinUri() + css.getPath()); } log.debug("Page {} has {} head JavaScript links", getClass().getName(), headJavaScripts.size()); Ordering<JavaScriptLink> jsOrdering = Ordering.from(new Comparator<JavaScriptLink>() { @Override public int compare(JavaScriptLink o1, JavaScriptLink o2) { return o1.getWeight() - o2.getWeight(); }; }); List<JavaScriptLink> sortedJses = jsOrdering.immutableSortedCopy(headJavaScripts); for (JavaScriptLink js : sortedJses) { response.renderJavaScriptReference(js.getSrc()); } } protected PageMeta getPageMeta(@Nonnull final TenantRef tenant, String currentUri) { final PageRuleContext context = new PageRuleContext(tenant.getClientId(), tenant.getTenantId(), tenant.getTenantEnv(), this, currentUri, webAddress, appManifest); // final List<PageRule> pageRules = pageRulesSupplier.get(); // final PageMetaSupplier pageSupplier = new RulesPageMetaSupplier(pageRules, context); final PageMetaSupplier pageMetaSupplier = pageMetaSupplierFactory.create(context); final PageMeta pageMeta = pageMetaSupplier.get(); return pageMeta; } @Override protected void renderPlaceholderTag(ComponentTag tag, Response response) { super.renderPlaceholderTag(tag, response); } /** * Please override this. * @return */ protected String getTitle() { return null; } public BootstrapPage() { tenant = WebTenantUtils.getTenant(); final String currentUri = getRequest().getUrl().toString(); final Ordering<JavaScriptSource> sourceOrdering = Ordering.natural(); final Ordering<JavaScriptLink> linkOrdering = Ordering.natural(); - // do NOT use AsyncModel here because we need it to load last + // do NOT use AsyncModel here because we need it to load LAST // (i.e. after all scopes has been attached as page model using addModelForPageMeta) final IModel<PageMeta> pageMetaModel = new LoadableDetachableModel<PageMeta>() { @Override protected PageMeta load() { return getPageMeta(tenant, currentUri); } }; // HTML add(new TransparentWebMarkupContainer("html").add( new AttributeModifier("lang", new PropertyModel<String>(pageMetaModel, "languageCode")))); final BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext(); final ServiceReference<Site> siteRef = bundleContext.getServiceReference(Site.class); try { final Site site = bundleContext.getService(siteRef); // HEAD //add(new Label("pageTitle", "Welcome").setRenderBodyOnly(true)); - final IModel<String> titleModel = new AsyncModel<String>() { + // do NOT use AsyncModel here, because it depends on PageMeta model loading last + final IModel<String> titleModel = new LoadableDetachableModel<String>() { @Override protected String load() { return Optional.fromNullable(getTitle()) .or( Optional.fromNullable(pageMetaModel.getObject().getTitle()) ).orNull(); } }; final IModel<String> titleSuffixModel = new AsyncModel<String>() { @Override protected String load() { return " | " + appManifest.getTitle(); } }; add(new Label("pageTitle", titleModel).setRenderBodyOnly(true)); add(new Label("pageTitleSuffix", titleSuffixModel).setRenderBodyOnly(true)); final WebMarkupContainer faviconLink = new WebMarkupContainer("faviconLink"); faviconLink.add(new AttributeModifier("href", new PropertyModel<String>(pageMetaModel, "icon.faviconUri"))); add(faviconLink); add( new MetaTag("metaDescription", new PropertyModel<String>(pageMetaModel, "description")), new MetaTag("ogTitle", new PropertyModel<String>(pageMetaModel, "openGraph.title")), new MetaTag("ogType", new PropertyModel<String>(pageMetaModel, "openGraph.type")), new MetaTag("ogUrl", new PropertyModel<String>(pageMetaModel, "openGraph.url")), new MetaTag("ogImage", new PropertyModel<String>(pageMetaModel, "openGraph.image")) ); add(new WebMarkupContainer("bootstrapCss").add( new AttributeModifier("href", webAddress.getSkinUri() + "org.soluvas.web.bootstrap/css/bootstrap.css"))); add(new WebMarkupContainer("bootstrapResponsiveCss").add( new AttributeModifier("href", webAddress.getSkinUri() + "org.soluvas.web.bootstrap/css/bootstrap-responsive.css"))); add(new WebMarkupContainer("bootstrapPatchesCss").add( new AttributeModifier("href", webAddress.getSkinUri() + "org.soluvas.web.bootstrap/css/bootstrap-patches.css"))); add(new WebMarkupContainer("requireJs").add( new AttributeModifier("src", webAddress.getJsUri() + "org.soluvas.web.bootstrap/require-2.1.2.js"))); //Carousel add(afterHeader = new RepeatingView("afterHeader")); // NAVBAR final Navbar navbar = new Navbar("navbar"); add(navbar); // add(new Label("logoText", site.getLogoText()).setRenderBodyOnly(true)); // add(new Label("logoAlt", site.getLogoAlt()).setRenderBodyOnly(true)); navbar.add(new BookmarkablePageLink<Page>("homeLink", getApplication().getHomePage()) { { this.setBody(new Model<String>(site.getLogoText())); } @Override protected void onComponentTag(ComponentTag tag) { super.onComponentTag(tag); tag.getAttributes().put("title", site.getLogoAlt()); } }); add(new Header()); final String requireConfigPath = webAddress.getApiPath() + "org.soluvas.web.backbone/requireConfig.js"; add(new WebMarkupContainer("requireConfig").add(new AttributeModifier("src", requireConfigPath))); // SIDEBAR sidebarColumn = new TransparentWebMarkupContainer("sidebarColumn"); add(sidebarColumn); sidebarBlocks = new RepeatingView("sidebarBlocks"); sidebarColumn.add(sidebarBlocks); contentColumn = new TransparentWebMarkupContainer("contentColumn"); add(contentColumn); feedbackPanel = new FeedbackPanel("feedback").setOutputMarkupId(true); add(feedbackPanel); // FOOTER add(new Footer(site.getFooterHtml())); } finally { bundleContext.ungetService(siteRef); } // JAVASCRIPT final RepeatingView beforeFooterJs = new RepeatingView("beforeFooterJs"); add(beforeFooterJs); log.debug("Page {} has {} footer JavaScript links", getClass().getName(), footerJavaScripts.size()); final List<JavaScriptLink> sortedJsLinks = linkOrdering.immutableSortedCopy(footerJavaScripts); final RepeatingView footerJavaScriptLinks = new RepeatingView("footerJavaScriptLinks"); for (JavaScriptLink js : sortedJsLinks) { footerJavaScriptLinks.add(new WebMarkupContainer(footerJavaScriptLinks.newChildId()).add(new AttributeModifier("src", js.getSrc()))); } add(footerJavaScriptLinks); log.debug("Page {} has {} footer JavaScript sources", getClass().getName(), footerJavaScriptSources.size()); final List<JavaScriptSource> sortedJsSources = sourceOrdering.immutableSortedCopy(footerJavaScriptSources); final RepeatingView footerJavaScriptSources = new RepeatingView("footerJavaScriptSources"); for (JavaScriptSource js : sortedJsSources) { footerJavaScriptSources.add(new Label(footerJavaScriptSources.newChildId(), js.getScript()).setEscapeModelStrings(false)); } add(footerJavaScriptSources); log.debug("Page {} has {} page JavaScript links", getClass().getName(), pageJavaScriptLinks.size()); final List<JavaScriptLink> sortedPageJsLinks = linkOrdering.immutableSortedCopy(pageJavaScriptLinks); final RepeatingView pageJavaScriptLinksView = new RepeatingView("pageJavaScriptLinks"); for (JavaScriptLink js : sortedPageJsLinks) { pageJavaScriptLinksView.add(new WebMarkupContainer(pageJavaScriptLinksView.newChildId()).add(new AttributeModifier("src", js.getSrc()))); } add(pageJavaScriptLinksView); final IModel<String> pageJavaScriptSourcesModel = new LoadableDetachableModel<String>() { @Override protected String load() { final Builder<String, String> dependencies = ImmutableMap.builder(); final AmdDependencyVisitor amdDependencyVisitor = new AmdDependencyVisitor(dependencies); amdDependencyVisitor.component(BootstrapPage.this, null); visitChildren(amdDependencyVisitor); final Map<String, String> dependencyMap = dependencies.build(); log.debug("Page {} has {} AMD dependencies: {}", getClass().getName(), dependencyMap.size(), dependencyMap.keySet()); final ImmutableList.Builder<String> pageJsSourcesBuilder = ImmutableList.builder(); final JsSourceVisitor jsSourceVisitor = new JsSourceVisitor(pageJsSourcesBuilder); jsSourceVisitor.component(BootstrapPage.this, null); visitChildren(jsSourceVisitor); final List<String> pageJsSources = pageJsSourcesBuilder.build(); log.debug("Page {} has {} page JavaScript sources", getClass().getName(), pageJsSources.size()); final String merged = Joiner.on('\n').join(pageJsSources); JavaScriptSource js = new AmdJavaScriptSource(merged, dependencyMap); return js.getScript(); }; }; add(new Label("pageJavaScriptSources", pageJavaScriptSourcesModel).setEscapeModelStrings(false)); } public BootstrapPage(boolean sidebarVisible) { this(); if (!sidebarVisible) { sidebarColumn.setVisible(false); contentColumn.add(new AttributeModifier("class", "span12")); } } @Override protected void onInitialize() { super.onInitialize(); // compose other components ComposeUtils.compose(this, contributors.findAll()); } }
false
true
public BootstrapPage() { tenant = WebTenantUtils.getTenant(); final String currentUri = getRequest().getUrl().toString(); final Ordering<JavaScriptSource> sourceOrdering = Ordering.natural(); final Ordering<JavaScriptLink> linkOrdering = Ordering.natural(); // do NOT use AsyncModel here because we need it to load last // (i.e. after all scopes has been attached as page model using addModelForPageMeta) final IModel<PageMeta> pageMetaModel = new LoadableDetachableModel<PageMeta>() { @Override protected PageMeta load() { return getPageMeta(tenant, currentUri); } }; // HTML add(new TransparentWebMarkupContainer("html").add( new AttributeModifier("lang", new PropertyModel<String>(pageMetaModel, "languageCode")))); final BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext(); final ServiceReference<Site> siteRef = bundleContext.getServiceReference(Site.class); try { final Site site = bundleContext.getService(siteRef); // HEAD //add(new Label("pageTitle", "Welcome").setRenderBodyOnly(true)); final IModel<String> titleModel = new AsyncModel<String>() { @Override protected String load() { return Optional.fromNullable(getTitle()) .or( Optional.fromNullable(pageMetaModel.getObject().getTitle()) ).orNull(); } }; final IModel<String> titleSuffixModel = new AsyncModel<String>() { @Override protected String load() { return " | " + appManifest.getTitle(); } }; add(new Label("pageTitle", titleModel).setRenderBodyOnly(true)); add(new Label("pageTitleSuffix", titleSuffixModel).setRenderBodyOnly(true)); final WebMarkupContainer faviconLink = new WebMarkupContainer("faviconLink"); faviconLink.add(new AttributeModifier("href", new PropertyModel<String>(pageMetaModel, "icon.faviconUri"))); add(faviconLink); add( new MetaTag("metaDescription", new PropertyModel<String>(pageMetaModel, "description")), new MetaTag("ogTitle", new PropertyModel<String>(pageMetaModel, "openGraph.title")), new MetaTag("ogType", new PropertyModel<String>(pageMetaModel, "openGraph.type")), new MetaTag("ogUrl", new PropertyModel<String>(pageMetaModel, "openGraph.url")), new MetaTag("ogImage", new PropertyModel<String>(pageMetaModel, "openGraph.image")) ); add(new WebMarkupContainer("bootstrapCss").add( new AttributeModifier("href", webAddress.getSkinUri() + "org.soluvas.web.bootstrap/css/bootstrap.css"))); add(new WebMarkupContainer("bootstrapResponsiveCss").add( new AttributeModifier("href", webAddress.getSkinUri() + "org.soluvas.web.bootstrap/css/bootstrap-responsive.css"))); add(new WebMarkupContainer("bootstrapPatchesCss").add( new AttributeModifier("href", webAddress.getSkinUri() + "org.soluvas.web.bootstrap/css/bootstrap-patches.css"))); add(new WebMarkupContainer("requireJs").add( new AttributeModifier("src", webAddress.getJsUri() + "org.soluvas.web.bootstrap/require-2.1.2.js"))); //Carousel add(afterHeader = new RepeatingView("afterHeader")); // NAVBAR final Navbar navbar = new Navbar("navbar"); add(navbar); // add(new Label("logoText", site.getLogoText()).setRenderBodyOnly(true)); // add(new Label("logoAlt", site.getLogoAlt()).setRenderBodyOnly(true)); navbar.add(new BookmarkablePageLink<Page>("homeLink", getApplication().getHomePage()) { { this.setBody(new Model<String>(site.getLogoText())); } @Override protected void onComponentTag(ComponentTag tag) { super.onComponentTag(tag); tag.getAttributes().put("title", site.getLogoAlt()); } }); add(new Header()); final String requireConfigPath = webAddress.getApiPath() + "org.soluvas.web.backbone/requireConfig.js"; add(new WebMarkupContainer("requireConfig").add(new AttributeModifier("src", requireConfigPath))); // SIDEBAR sidebarColumn = new TransparentWebMarkupContainer("sidebarColumn"); add(sidebarColumn); sidebarBlocks = new RepeatingView("sidebarBlocks"); sidebarColumn.add(sidebarBlocks); contentColumn = new TransparentWebMarkupContainer("contentColumn"); add(contentColumn); feedbackPanel = new FeedbackPanel("feedback").setOutputMarkupId(true); add(feedbackPanel); // FOOTER add(new Footer(site.getFooterHtml())); } finally { bundleContext.ungetService(siteRef); } // JAVASCRIPT final RepeatingView beforeFooterJs = new RepeatingView("beforeFooterJs"); add(beforeFooterJs); log.debug("Page {} has {} footer JavaScript links", getClass().getName(), footerJavaScripts.size()); final List<JavaScriptLink> sortedJsLinks = linkOrdering.immutableSortedCopy(footerJavaScripts); final RepeatingView footerJavaScriptLinks = new RepeatingView("footerJavaScriptLinks"); for (JavaScriptLink js : sortedJsLinks) { footerJavaScriptLinks.add(new WebMarkupContainer(footerJavaScriptLinks.newChildId()).add(new AttributeModifier("src", js.getSrc()))); } add(footerJavaScriptLinks); log.debug("Page {} has {} footer JavaScript sources", getClass().getName(), footerJavaScriptSources.size()); final List<JavaScriptSource> sortedJsSources = sourceOrdering.immutableSortedCopy(footerJavaScriptSources); final RepeatingView footerJavaScriptSources = new RepeatingView("footerJavaScriptSources"); for (JavaScriptSource js : sortedJsSources) { footerJavaScriptSources.add(new Label(footerJavaScriptSources.newChildId(), js.getScript()).setEscapeModelStrings(false)); } add(footerJavaScriptSources); log.debug("Page {} has {} page JavaScript links", getClass().getName(), pageJavaScriptLinks.size()); final List<JavaScriptLink> sortedPageJsLinks = linkOrdering.immutableSortedCopy(pageJavaScriptLinks); final RepeatingView pageJavaScriptLinksView = new RepeatingView("pageJavaScriptLinks"); for (JavaScriptLink js : sortedPageJsLinks) { pageJavaScriptLinksView.add(new WebMarkupContainer(pageJavaScriptLinksView.newChildId()).add(new AttributeModifier("src", js.getSrc()))); } add(pageJavaScriptLinksView); final IModel<String> pageJavaScriptSourcesModel = new LoadableDetachableModel<String>() { @Override protected String load() { final Builder<String, String> dependencies = ImmutableMap.builder(); final AmdDependencyVisitor amdDependencyVisitor = new AmdDependencyVisitor(dependencies); amdDependencyVisitor.component(BootstrapPage.this, null); visitChildren(amdDependencyVisitor); final Map<String, String> dependencyMap = dependencies.build(); log.debug("Page {} has {} AMD dependencies: {}", getClass().getName(), dependencyMap.size(), dependencyMap.keySet()); final ImmutableList.Builder<String> pageJsSourcesBuilder = ImmutableList.builder(); final JsSourceVisitor jsSourceVisitor = new JsSourceVisitor(pageJsSourcesBuilder); jsSourceVisitor.component(BootstrapPage.this, null); visitChildren(jsSourceVisitor); final List<String> pageJsSources = pageJsSourcesBuilder.build(); log.debug("Page {} has {} page JavaScript sources", getClass().getName(), pageJsSources.size()); final String merged = Joiner.on('\n').join(pageJsSources); JavaScriptSource js = new AmdJavaScriptSource(merged, dependencyMap); return js.getScript(); }; }; add(new Label("pageJavaScriptSources", pageJavaScriptSourcesModel).setEscapeModelStrings(false)); }
public BootstrapPage() { tenant = WebTenantUtils.getTenant(); final String currentUri = getRequest().getUrl().toString(); final Ordering<JavaScriptSource> sourceOrdering = Ordering.natural(); final Ordering<JavaScriptLink> linkOrdering = Ordering.natural(); // do NOT use AsyncModel here because we need it to load LAST // (i.e. after all scopes has been attached as page model using addModelForPageMeta) final IModel<PageMeta> pageMetaModel = new LoadableDetachableModel<PageMeta>() { @Override protected PageMeta load() { return getPageMeta(tenant, currentUri); } }; // HTML add(new TransparentWebMarkupContainer("html").add( new AttributeModifier("lang", new PropertyModel<String>(pageMetaModel, "languageCode")))); final BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext(); final ServiceReference<Site> siteRef = bundleContext.getServiceReference(Site.class); try { final Site site = bundleContext.getService(siteRef); // HEAD //add(new Label("pageTitle", "Welcome").setRenderBodyOnly(true)); // do NOT use AsyncModel here, because it depends on PageMeta model loading last final IModel<String> titleModel = new LoadableDetachableModel<String>() { @Override protected String load() { return Optional.fromNullable(getTitle()) .or( Optional.fromNullable(pageMetaModel.getObject().getTitle()) ).orNull(); } }; final IModel<String> titleSuffixModel = new AsyncModel<String>() { @Override protected String load() { return " | " + appManifest.getTitle(); } }; add(new Label("pageTitle", titleModel).setRenderBodyOnly(true)); add(new Label("pageTitleSuffix", titleSuffixModel).setRenderBodyOnly(true)); final WebMarkupContainer faviconLink = new WebMarkupContainer("faviconLink"); faviconLink.add(new AttributeModifier("href", new PropertyModel<String>(pageMetaModel, "icon.faviconUri"))); add(faviconLink); add( new MetaTag("metaDescription", new PropertyModel<String>(pageMetaModel, "description")), new MetaTag("ogTitle", new PropertyModel<String>(pageMetaModel, "openGraph.title")), new MetaTag("ogType", new PropertyModel<String>(pageMetaModel, "openGraph.type")), new MetaTag("ogUrl", new PropertyModel<String>(pageMetaModel, "openGraph.url")), new MetaTag("ogImage", new PropertyModel<String>(pageMetaModel, "openGraph.image")) ); add(new WebMarkupContainer("bootstrapCss").add( new AttributeModifier("href", webAddress.getSkinUri() + "org.soluvas.web.bootstrap/css/bootstrap.css"))); add(new WebMarkupContainer("bootstrapResponsiveCss").add( new AttributeModifier("href", webAddress.getSkinUri() + "org.soluvas.web.bootstrap/css/bootstrap-responsive.css"))); add(new WebMarkupContainer("bootstrapPatchesCss").add( new AttributeModifier("href", webAddress.getSkinUri() + "org.soluvas.web.bootstrap/css/bootstrap-patches.css"))); add(new WebMarkupContainer("requireJs").add( new AttributeModifier("src", webAddress.getJsUri() + "org.soluvas.web.bootstrap/require-2.1.2.js"))); //Carousel add(afterHeader = new RepeatingView("afterHeader")); // NAVBAR final Navbar navbar = new Navbar("navbar"); add(navbar); // add(new Label("logoText", site.getLogoText()).setRenderBodyOnly(true)); // add(new Label("logoAlt", site.getLogoAlt()).setRenderBodyOnly(true)); navbar.add(new BookmarkablePageLink<Page>("homeLink", getApplication().getHomePage()) { { this.setBody(new Model<String>(site.getLogoText())); } @Override protected void onComponentTag(ComponentTag tag) { super.onComponentTag(tag); tag.getAttributes().put("title", site.getLogoAlt()); } }); add(new Header()); final String requireConfigPath = webAddress.getApiPath() + "org.soluvas.web.backbone/requireConfig.js"; add(new WebMarkupContainer("requireConfig").add(new AttributeModifier("src", requireConfigPath))); // SIDEBAR sidebarColumn = new TransparentWebMarkupContainer("sidebarColumn"); add(sidebarColumn); sidebarBlocks = new RepeatingView("sidebarBlocks"); sidebarColumn.add(sidebarBlocks); contentColumn = new TransparentWebMarkupContainer("contentColumn"); add(contentColumn); feedbackPanel = new FeedbackPanel("feedback").setOutputMarkupId(true); add(feedbackPanel); // FOOTER add(new Footer(site.getFooterHtml())); } finally { bundleContext.ungetService(siteRef); } // JAVASCRIPT final RepeatingView beforeFooterJs = new RepeatingView("beforeFooterJs"); add(beforeFooterJs); log.debug("Page {} has {} footer JavaScript links", getClass().getName(), footerJavaScripts.size()); final List<JavaScriptLink> sortedJsLinks = linkOrdering.immutableSortedCopy(footerJavaScripts); final RepeatingView footerJavaScriptLinks = new RepeatingView("footerJavaScriptLinks"); for (JavaScriptLink js : sortedJsLinks) { footerJavaScriptLinks.add(new WebMarkupContainer(footerJavaScriptLinks.newChildId()).add(new AttributeModifier("src", js.getSrc()))); } add(footerJavaScriptLinks); log.debug("Page {} has {} footer JavaScript sources", getClass().getName(), footerJavaScriptSources.size()); final List<JavaScriptSource> sortedJsSources = sourceOrdering.immutableSortedCopy(footerJavaScriptSources); final RepeatingView footerJavaScriptSources = new RepeatingView("footerJavaScriptSources"); for (JavaScriptSource js : sortedJsSources) { footerJavaScriptSources.add(new Label(footerJavaScriptSources.newChildId(), js.getScript()).setEscapeModelStrings(false)); } add(footerJavaScriptSources); log.debug("Page {} has {} page JavaScript links", getClass().getName(), pageJavaScriptLinks.size()); final List<JavaScriptLink> sortedPageJsLinks = linkOrdering.immutableSortedCopy(pageJavaScriptLinks); final RepeatingView pageJavaScriptLinksView = new RepeatingView("pageJavaScriptLinks"); for (JavaScriptLink js : sortedPageJsLinks) { pageJavaScriptLinksView.add(new WebMarkupContainer(pageJavaScriptLinksView.newChildId()).add(new AttributeModifier("src", js.getSrc()))); } add(pageJavaScriptLinksView); final IModel<String> pageJavaScriptSourcesModel = new LoadableDetachableModel<String>() { @Override protected String load() { final Builder<String, String> dependencies = ImmutableMap.builder(); final AmdDependencyVisitor amdDependencyVisitor = new AmdDependencyVisitor(dependencies); amdDependencyVisitor.component(BootstrapPage.this, null); visitChildren(amdDependencyVisitor); final Map<String, String> dependencyMap = dependencies.build(); log.debug("Page {} has {} AMD dependencies: {}", getClass().getName(), dependencyMap.size(), dependencyMap.keySet()); final ImmutableList.Builder<String> pageJsSourcesBuilder = ImmutableList.builder(); final JsSourceVisitor jsSourceVisitor = new JsSourceVisitor(pageJsSourcesBuilder); jsSourceVisitor.component(BootstrapPage.this, null); visitChildren(jsSourceVisitor); final List<String> pageJsSources = pageJsSourcesBuilder.build(); log.debug("Page {} has {} page JavaScript sources", getClass().getName(), pageJsSources.size()); final String merged = Joiner.on('\n').join(pageJsSources); JavaScriptSource js = new AmdJavaScriptSource(merged, dependencyMap); return js.getScript(); }; }; add(new Label("pageJavaScriptSources", pageJavaScriptSourcesModel).setEscapeModelStrings(false)); }
diff --git a/src/main/java/com/sun/kohsuke/hadoop/importer/App.java b/src/main/java/com/sun/kohsuke/hadoop/importer/App.java index 329d14e..91fb725 100644 --- a/src/main/java/com/sun/kohsuke/hadoop/importer/App.java +++ b/src/main/java/com/sun/kohsuke/hadoop/importer/App.java @@ -1,66 +1,66 @@ /* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.sun.kohsuke.hadoop.importer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.hdfs.DFSClient; import org.apache.hadoop.io.IOUtils; import java.io.File; import java.io.FileInputStream; /** * This tool keeps a directory mirrored in HDFS. * * Run this tool repeatedly on the same directory and updates will be sent to the HDFS. * TODO: if files are removed from the source, remove them from HDFS. */ public class App { public static void main(String[] args) throws Exception { if(args.length!=3) { System.out.println("Usage: java -jar importer.jar [HDFS URL] [local directory] [HDFS directory]"); } Configuration conf = new Configuration(); conf.set("fs.default.name", args[0]); DFSClient dfs = new DFSClient(conf); File in = new File(args[1]); String out = args[2]; for (File f : in.listFiles()) { if (f.isDirectory()) continue; String dest = out + '/' + f.getName(); FileStatus i = dfs.getFileInfo(dest); - if (i == null || i.getModificationTime() != f.lastModified()) { + if (i == null || i.getModificationTime() != f.lastModified() || i.getLen()!=f.length()) { System.out.println("Importing " + f); IOUtils.copyBytes(new FileInputStream(f), dfs.create(dest, true), conf); dfs.setTimes(dest, f.lastModified(), f.lastModified()); } else { System.out.println("Skipping " + f); } } } }
true
true
public static void main(String[] args) throws Exception { if(args.length!=3) { System.out.println("Usage: java -jar importer.jar [HDFS URL] [local directory] [HDFS directory]"); } Configuration conf = new Configuration(); conf.set("fs.default.name", args[0]); DFSClient dfs = new DFSClient(conf); File in = new File(args[1]); String out = args[2]; for (File f : in.listFiles()) { if (f.isDirectory()) continue; String dest = out + '/' + f.getName(); FileStatus i = dfs.getFileInfo(dest); if (i == null || i.getModificationTime() != f.lastModified()) { System.out.println("Importing " + f); IOUtils.copyBytes(new FileInputStream(f), dfs.create(dest, true), conf); dfs.setTimes(dest, f.lastModified(), f.lastModified()); } else { System.out.println("Skipping " + f); } } }
public static void main(String[] args) throws Exception { if(args.length!=3) { System.out.println("Usage: java -jar importer.jar [HDFS URL] [local directory] [HDFS directory]"); } Configuration conf = new Configuration(); conf.set("fs.default.name", args[0]); DFSClient dfs = new DFSClient(conf); File in = new File(args[1]); String out = args[2]; for (File f : in.listFiles()) { if (f.isDirectory()) continue; String dest = out + '/' + f.getName(); FileStatus i = dfs.getFileInfo(dest); if (i == null || i.getModificationTime() != f.lastModified() || i.getLen()!=f.length()) { System.out.println("Importing " + f); IOUtils.copyBytes(new FileInputStream(f), dfs.create(dest, true), conf); dfs.setTimes(dest, f.lastModified(), f.lastModified()); } else { System.out.println("Skipping " + f); } } }
diff --git a/cadpage/src/net/anei/cadpage/parsers/NY/NYNassauCountyCParser.java b/cadpage/src/net/anei/cadpage/parsers/NY/NYNassauCountyCParser.java index 4cfcfeb5c..843d7705e 100644 --- a/cadpage/src/net/anei/cadpage/parsers/NY/NYNassauCountyCParser.java +++ b/cadpage/src/net/anei/cadpage/parsers/NY/NYNassauCountyCParser.java @@ -1,65 +1,74 @@ package net.anei.cadpage.parsers.NY; import java.util.regex.Pattern; import net.anei.cadpage.SmsMsgInfo.Data; import net.anei.cadpage.parsers.FieldProgramParser; /* Nassau County, NY (version C) Contact: Besnik Gjonlekaj <[email protected]> Sender: [email protected] System: Fire Rescue Systems SIG 14- SIGNAL 8 - FOR AFA WESTBURY MIDDLE SCHOOL 455 ROCKLAND ST CS: LINDEN PLACE / SCHOOL ST TOA: 13:36 03/27 SIG 16- AFA THE SOURCE MALL 1504 OLD COUNTRY ROAD CS: MERCHANTS CONCOURSE / ZECKENDORF BOULEVARD TOA: 06:03 03/27/11 SIG 4- SIGNAL 9 CABRERA, TULIO 362 WINTHROP STREET CS: POST AVENUE / LINDEN AVENUE TOA: 11:33 03/26/11 SIG 3- AUTO ACCIDENT W/AIDED BOND STREET & OLD COUNTRY ROAD BOND STREET CS: OLD COUNTRY ROAD TOA: 11:49 03/25/11 SIG 1- STRUCTURE FIRE RITE AID 210 POST AVENUE CS: MAPLE AVENUE / MADISON AVENUE TOA: 10:30 03/24/11 SIG 3- AUTO ACCIDENT/ HURST TOOL BENIHANA RESAURANT 920 MERCHANTS CONCOURSE CS: TAYLOR AVENUE / PRIVADO ROAD TOA: 12:56 03/24/11 SIG 14- SIGNAL 8 - FOR AFA WESTBURY MIDDLE SCHOOL 455 ROCKLAND STREET CS: LINDEN PLACE / SCHOOL STREET TOA: 13:36 03/27/11 SIG 4- SIGNAL 9 MARK,GERTRUDE 701 THE PLAIN ROAD CS: LADENBURG DRIVE / VALENTINE ROAD TOA: 09:14 04/02/11 SIG 4- SIGNAL 9 CODE 96 OUIDIO CASTRO 50 WATERBURY LANE CS: BARD ROAD / PEPPERIDGE ROAD TOA: 13:23 04/02/11 */ public class NYNassauCountyCParser extends FieldProgramParser { private static final Pattern MARKER = Pattern.compile("^SIG \\d{1,2}- "); public NYNassauCountyCParser() { super("NASSAU COUNTY", "NY", "CALL! LOC:ADDR/SP! CS:X! TOA:SKIP"); } @Override protected boolean parseMsg(String body, Data data) { if (body.startsWith("***")) return false; if (!MARKER.matcher(body).find()) return false; body = body.replaceFirst(" ", " LOC: "); return super.parseMsg(body, data); } private class MyAddressField extends AddressField { @Override public void parse(String field, Data data) { - int pt = field.lastIndexOf(" "); - if (pt >= 0) { - data.strPlace = field.substring(pt+2).trim(); - field = field.substring(0,pt).trim(); + int pt1 = field.indexOf(" "); + if (pt1 >= 0) { + int pt2 = field.lastIndexOf(" "); + if (pt1 == pt2) { + if (field.startsWith("CODE ")) { + pt2 = field.length(); + } else { + pt1 = -2; + } + } + if (pt1 >= 0) data.strCall = append(data.strCall, " ", field.substring(0,pt1).trim()); + if (pt2 < field.length()) data.strPlace = field.substring(pt2+2).trim(); + field = field.substring(pt1+2,pt2).trim(); } super.parse(field, data); } } @Override public Field getField(String name) { if (name.equals("ADDR")) return new MyAddressField(); return super.getField(name); } }
true
true
public void parse(String field, Data data) { int pt = field.lastIndexOf(" "); if (pt >= 0) { data.strPlace = field.substring(pt+2).trim(); field = field.substring(0,pt).trim(); } super.parse(field, data); }
public void parse(String field, Data data) { int pt1 = field.indexOf(" "); if (pt1 >= 0) { int pt2 = field.lastIndexOf(" "); if (pt1 == pt2) { if (field.startsWith("CODE ")) { pt2 = field.length(); } else { pt1 = -2; } } if (pt1 >= 0) data.strCall = append(data.strCall, " ", field.substring(0,pt1).trim()); if (pt2 < field.length()) data.strPlace = field.substring(pt2+2).trim(); field = field.substring(pt1+2,pt2).trim(); } super.parse(field, data); }
diff --git a/src/com/undeadscythes/udsplugin/eventhandlers/PlayerInteractEntity.java b/src/com/undeadscythes/udsplugin/eventhandlers/PlayerInteractEntity.java index 82c0e52..56f675c 100644 --- a/src/com/undeadscythes/udsplugin/eventhandlers/PlayerInteractEntity.java +++ b/src/com/undeadscythes/udsplugin/eventhandlers/PlayerInteractEntity.java @@ -1,37 +1,39 @@ package com.undeadscythes.udsplugin.eventhandlers; import com.undeadscythes.udsplugin.*; import org.bukkit.entity.*; import org.bukkit.event.*; import org.bukkit.event.player.*; /** * When a player interacts with an entity. * @author UndeadScythes */ public class PlayerInteractEntity extends ListenerWrapper implements Listener { @EventHandler public final void onEvent(final PlayerInteractEntityEvent event) { final Entity entity = event.getRightClicked(); if(entity instanceof Tameable) { final Tameable pet = (Tameable)entity; if(pet.isTamed()) { final String ownerName = pet.getOwner().getName(); - if(ownerName.equals(event.getPlayer().getName()) && event.getPlayer().isSneaking()) { - UDSPlugin.getPlayers().get(event.getPlayer().getName()).selectPet(entity.getUniqueId()); - event.getPlayer().sendMessage(Color.MESSAGE + "Pet selected."); - event.setCancelled(true); + if(ownerName.equals(event.getPlayer().getName())) { + if(event.getPlayer().isSneaking()) { + UDSPlugin.getPlayers().get(event.getPlayer().getName()).selectPet(entity.getUniqueId()); + event.getPlayer().sendMessage(Color.MESSAGE + "Pet selected."); + event.setCancelled(true); + } } else { event.getPlayer().sendMessage(Color.MESSAGE + "This animal belongs to " + UDSPlugin.getPlayers().get(ownerName).getNick()); event.setCancelled(true); } } } else if(entity instanceof ItemFrame) { final SaveablePlayer player = UDSPlugin.getPlayers().get(event.getPlayer().getName()); if(!(player.canBuildHere(entity.getLocation()))) { event.setCancelled(true); player.sendMessage(Message.CANT_BUILD_HERE); } } } }
true
true
public final void onEvent(final PlayerInteractEntityEvent event) { final Entity entity = event.getRightClicked(); if(entity instanceof Tameable) { final Tameable pet = (Tameable)entity; if(pet.isTamed()) { final String ownerName = pet.getOwner().getName(); if(ownerName.equals(event.getPlayer().getName()) && event.getPlayer().isSneaking()) { UDSPlugin.getPlayers().get(event.getPlayer().getName()).selectPet(entity.getUniqueId()); event.getPlayer().sendMessage(Color.MESSAGE + "Pet selected."); event.setCancelled(true); } else { event.getPlayer().sendMessage(Color.MESSAGE + "This animal belongs to " + UDSPlugin.getPlayers().get(ownerName).getNick()); event.setCancelled(true); } } } else if(entity instanceof ItemFrame) { final SaveablePlayer player = UDSPlugin.getPlayers().get(event.getPlayer().getName()); if(!(player.canBuildHere(entity.getLocation()))) { event.setCancelled(true); player.sendMessage(Message.CANT_BUILD_HERE); } } }
public final void onEvent(final PlayerInteractEntityEvent event) { final Entity entity = event.getRightClicked(); if(entity instanceof Tameable) { final Tameable pet = (Tameable)entity; if(pet.isTamed()) { final String ownerName = pet.getOwner().getName(); if(ownerName.equals(event.getPlayer().getName())) { if(event.getPlayer().isSneaking()) { UDSPlugin.getPlayers().get(event.getPlayer().getName()).selectPet(entity.getUniqueId()); event.getPlayer().sendMessage(Color.MESSAGE + "Pet selected."); event.setCancelled(true); } } else { event.getPlayer().sendMessage(Color.MESSAGE + "This animal belongs to " + UDSPlugin.getPlayers().get(ownerName).getNick()); event.setCancelled(true); } } } else if(entity instanceof ItemFrame) { final SaveablePlayer player = UDSPlugin.getPlayers().get(event.getPlayer().getName()); if(!(player.canBuildHere(entity.getLocation()))) { event.setCancelled(true); player.sendMessage(Message.CANT_BUILD_HERE); } } }
diff --git a/org.scala-ide.sdt.debug.tests/src/scala/tools/eclipse/debug/spy/TcpipSpy.java b/org.scala-ide.sdt.debug.tests/src/scala/tools/eclipse/debug/spy/TcpipSpy.java index 40bed028b..482a5abfc 100644 --- a/org.scala-ide.sdt.debug.tests/src/scala/tools/eclipse/debug/spy/TcpipSpy.java +++ b/org.scala-ide.sdt.debug.tests/src/scala/tools/eclipse/debug/spy/TcpipSpy.java @@ -1,252 +1,265 @@ /******************************************************************************* * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package scala.tools.eclipse.debug.spy; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.HashMap; import java.util.Map; import com.ibm.icu.text.MessageFormat; /** * This class can be used to spy all JDWP packets. It should be configured 'in * between' the debugger application and the VM (or J9 debug proxy). Its * parameters are: 1) The port number to which the debugger application * connects; 2) The name of the host on which the VM or proxy waits for a JDWP * connection; 3) The port number on which the VM or proxy waits for a JDWP * connection; 4) The file where the trace is written to. * * Note that if this program is used for tracing JDWP activity of Leapfrog, the * 'debug remote program' option must be used, and the J9 proxy must first be * started up by hand on the port to which Leapfrog will connect. The J9 proxy * that is started up by Leapfrog is not used and will return immediately. */ public class TcpipSpy extends Thread { private static final byte[] handshakeBytes = "JDWP-Handshake".getBytes(); //$NON-NLS-1$ private boolean fVMtoDebugger; private DataInputStream fDataIn; private DataOutputStream fDataOut; private static VerbosePacketStream out = new VerbosePacketStream(System.out); private static Map<Integer, JdwpConversation> fPackets = new HashMap<Integer, JdwpConversation>(); private static int fFieldIDSize; private static int fMethodIDSize; private static int fObjectIDSize; private static int fReferenceTypeIDSize; private static int fFrameIDSize; private static boolean fHasSizes; public TcpipSpy(boolean VMtoDebugger, InputStream in, OutputStream out) { fVMtoDebugger = VMtoDebugger; fDataIn = new DataInputStream(new BufferedInputStream(in)); fDataOut = new DataOutputStream(new BufferedOutputStream(out)); fHasSizes = false; } public static void main(String[] args) { boolean listenMode = false; int inPort = 0; String serverHost = null; int outPort = 0; String outputFile = null; try { listenMode = args[0].equals("-l"); int argIndex = listenMode ? 1 : 0; inPort = Integer.parseInt(args[argIndex ++]); serverHost = args[argIndex++]; outPort = Integer.parseInt(args[argIndex++]); if (args.length >= argIndex) { outputFile = args[argIndex]; } } catch (Exception e) { out.println("usage: TcpipSpy [-l] <client port> <server host> <server port> [<output file>]"); //$NON-NLS-1$ System.exit(-1); } if (outputFile != null) { File file = new File(outputFile); out.println(MessageFormat .format("Writing output to {0}", new Object[] { file.getAbsolutePath() })); //$NON-NLS-1$ try { out = new VerbosePacketStream(new BufferedOutputStream( new FileOutputStream(file))); } catch (FileNotFoundException e) { out.println(MessageFormat .format("Could not open {0}. Using stdout instead", new Object[] { file.getAbsolutePath() })); //$NON-NLS-1$ } } out.println(); + ServerSocket serverSock = null; + Socket outSock = null; try { - ServerSocket serverSock = new ServerSocket(inPort); + serverSock = new ServerSocket(inPort); Socket inSock = serverSock.accept(); - Socket outSock = new Socket(InetAddress.getByName(serverHost), + outSock = new Socket(InetAddress.getByName(serverHost), outPort); Thread inThread = new TcpipSpy(listenMode, inSock.getInputStream(), outSock.getOutputStream()); Thread outThread = new TcpipSpy(!listenMode, outSock.getInputStream(), inSock.getOutputStream()); inThread.start(); outThread.start(); inThread.join(); outThread.join(); } catch (Exception e) { out.println(e); + } finally { + try { + if (serverSock != null) { + serverSock.close(); + } + } catch (IOException e) {} + try { + if (outSock != null) { + outSock.close(); + } + } catch (Exception e) {} } } @Override public void run() { try { // Skip handshake. int handshakeLength; handshakeLength = handshakeBytes.length; while (handshakeLength-- > 0) { int b = fDataIn.read(); fDataOut.write(b); } fDataOut.flush(); // Print all packages. while (true) { JdwpPacket p = JdwpPacket.read(fDataIn); // we need to store conversation only for command send by the // debugger, // as there is no answer from the debugger to VM commands. if (!(fVMtoDebugger && (p.getFlags() & JdwpPacket.FLAG_REPLY_PACKET) == 0)) { store(p); } out.print(p, fVMtoDebugger); out.flush(); p.write(fDataOut); fDataOut.flush(); } } catch (EOFException e) { } catch (SocketException e) { } catch (IOException e) { out.println(MessageFormat.format( "Caught exception: {0}", new Object[] { e.toString() })); //$NON-NLS-1$ e.printStackTrace(out); } finally { try { fDataIn.close(); fDataOut.close(); } catch (IOException e) { } out.flush(); } } public static JdwpCommandPacket getCommand(int id) { JdwpConversation conversation = fPackets .get(new Integer(id)); if (conversation != null) return conversation.getCommand(); return null; } protected static void store(JdwpPacket packet) { int id = packet.getId(); JdwpConversation conversation = fPackets .get(new Integer(id)); if (conversation == null) { conversation = new JdwpConversation(id); fPackets.put(new Integer(id), conversation); } if ((packet.getFlags() & JdwpPacket.FLAG_REPLY_PACKET) != 0) { conversation.setReply((JdwpReplyPacket) packet); } else { conversation.setCommand((JdwpCommandPacket) packet); } } public static int getCommand(JdwpPacket packet) throws UnableToParseDataException { JdwpCommandPacket command = null; if (packet instanceof JdwpCommandPacket) { command = (JdwpCommandPacket) packet; } else { command = getCommand(packet.getId()); if (command == null) { throw new UnableToParseDataException( "This packet is marked as reply, but there is no command with the same id.", null); //$NON-NLS-1$ } } return command.getCommand(); } public static boolean hasSizes() { return fHasSizes; } public static void setHasSizes(boolean value) { fHasSizes = value; } public static void setFieldIDSize(int fieldIDSize) { fFieldIDSize = fieldIDSize; } public static int getFieldIDSize() { return fFieldIDSize; } public static void setMethodIDSize(int methodIDSize) { fMethodIDSize = methodIDSize; } public static int getMethodIDSize() { return fMethodIDSize; } public static void setObjectIDSize(int objectIDSize) { fObjectIDSize = objectIDSize; } public static int getObjectIDSize() { return fObjectIDSize; } public static void setReferenceTypeIDSize(int referenceTypeIDSize) { fReferenceTypeIDSize = referenceTypeIDSize; } public static int getReferenceTypeIDSize() { return fReferenceTypeIDSize; } public static void setFrameIDSize(int frameIDSize) { fFrameIDSize = frameIDSize; } public static int getFrameIDSize() { return fFrameIDSize; } }
false
true
public static void main(String[] args) { boolean listenMode = false; int inPort = 0; String serverHost = null; int outPort = 0; String outputFile = null; try { listenMode = args[0].equals("-l"); int argIndex = listenMode ? 1 : 0; inPort = Integer.parseInt(args[argIndex ++]); serverHost = args[argIndex++]; outPort = Integer.parseInt(args[argIndex++]); if (args.length >= argIndex) { outputFile = args[argIndex]; } } catch (Exception e) { out.println("usage: TcpipSpy [-l] <client port> <server host> <server port> [<output file>]"); //$NON-NLS-1$ System.exit(-1); } if (outputFile != null) { File file = new File(outputFile); out.println(MessageFormat .format("Writing output to {0}", new Object[] { file.getAbsolutePath() })); //$NON-NLS-1$ try { out = new VerbosePacketStream(new BufferedOutputStream( new FileOutputStream(file))); } catch (FileNotFoundException e) { out.println(MessageFormat .format("Could not open {0}. Using stdout instead", new Object[] { file.getAbsolutePath() })); //$NON-NLS-1$ } } out.println(); try { ServerSocket serverSock = new ServerSocket(inPort); Socket inSock = serverSock.accept(); Socket outSock = new Socket(InetAddress.getByName(serverHost), outPort); Thread inThread = new TcpipSpy(listenMode, inSock.getInputStream(), outSock.getOutputStream()); Thread outThread = new TcpipSpy(!listenMode, outSock.getInputStream(), inSock.getOutputStream()); inThread.start(); outThread.start(); inThread.join(); outThread.join(); } catch (Exception e) { out.println(e); } }
public static void main(String[] args) { boolean listenMode = false; int inPort = 0; String serverHost = null; int outPort = 0; String outputFile = null; try { listenMode = args[0].equals("-l"); int argIndex = listenMode ? 1 : 0; inPort = Integer.parseInt(args[argIndex ++]); serverHost = args[argIndex++]; outPort = Integer.parseInt(args[argIndex++]); if (args.length >= argIndex) { outputFile = args[argIndex]; } } catch (Exception e) { out.println("usage: TcpipSpy [-l] <client port> <server host> <server port> [<output file>]"); //$NON-NLS-1$ System.exit(-1); } if (outputFile != null) { File file = new File(outputFile); out.println(MessageFormat .format("Writing output to {0}", new Object[] { file.getAbsolutePath() })); //$NON-NLS-1$ try { out = new VerbosePacketStream(new BufferedOutputStream( new FileOutputStream(file))); } catch (FileNotFoundException e) { out.println(MessageFormat .format("Could not open {0}. Using stdout instead", new Object[] { file.getAbsolutePath() })); //$NON-NLS-1$ } } out.println(); ServerSocket serverSock = null; Socket outSock = null; try { serverSock = new ServerSocket(inPort); Socket inSock = serverSock.accept(); outSock = new Socket(InetAddress.getByName(serverHost), outPort); Thread inThread = new TcpipSpy(listenMode, inSock.getInputStream(), outSock.getOutputStream()); Thread outThread = new TcpipSpy(!listenMode, outSock.getInputStream(), inSock.getOutputStream()); inThread.start(); outThread.start(); inThread.join(); outThread.join(); } catch (Exception e) { out.println(e); } finally { try { if (serverSock != null) { serverSock.close(); } } catch (IOException e) {} try { if (outSock != null) { outSock.close(); } } catch (Exception e) {} } }
diff --git a/tests/tests/app/src/android/app/cts/SystemFeaturesTest.java b/tests/tests/app/src/android/app/cts/SystemFeaturesTest.java index c9789192..ac3d03ac 100644 --- a/tests/tests/app/src/android/app/cts/SystemFeaturesTest.java +++ b/tests/tests/app/src/android/app/cts/SystemFeaturesTest.java @@ -1,304 +1,304 @@ /* * Copyright (C) 2010 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.app.cts; import android.app.ActivityManager; import android.app.Instrumentation; import android.app.WallpaperManager; import android.bluetooth.BluetoothAdapter; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.pm.ConfigurationInfo; import android.content.pm.FeatureInfo; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.hardware.Camera; import android.hardware.Sensor; import android.hardware.SensorManager; import android.hardware.Camera.Parameters; import android.location.LocationManager; import android.net.wifi.WifiManager; import android.telephony.TelephonyManager; import android.test.InstrumentationTestCase; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Test for checking that the {@link PackageManager} is reporting the correct features. */ public class SystemFeaturesTest extends InstrumentationTestCase { private Context mContext; private PackageManager mPackageManager; private HashSet<String> mAvailableFeatures; private ActivityManager mActivityManager; private LocationManager mLocationManager; private SensorManager mSensorManager; private TelephonyManager mTelephonyManager; private WifiManager mWifiManager; @Override protected void setUp() throws Exception { super.setUp(); Instrumentation instrumentation = getInstrumentation(); mContext = instrumentation.getContext(); mPackageManager = mContext.getPackageManager(); mAvailableFeatures = new HashSet<String>(); if (mPackageManager.getSystemAvailableFeatures() != null) { for (FeatureInfo feature : mPackageManager.getSystemAvailableFeatures()) { mAvailableFeatures.add(feature.name); } } mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE); mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); } /** * Check for features improperly prefixed with "android." that are not defined in * {@link PackageManager}. */ public void testFeatureNamespaces() throws IllegalArgumentException, IllegalAccessException { Set<String> officialFeatures = getFeatureConstantsNames("FEATURE_"); assertFalse(officialFeatures.isEmpty()); Set<String> notOfficialFeatures = new HashSet<String>(mAvailableFeatures); notOfficialFeatures.removeAll(officialFeatures); for (String featureName : notOfficialFeatures) { if (featureName != null) { assertFalse("Use a different namespace than 'android' for " + featureName, featureName.startsWith("android")); } } } public void testBluetoothFeature() { if (BluetoothAdapter.getDefaultAdapter() != null) { assertAvailable(PackageManager.FEATURE_BLUETOOTH); } else { assertNotAvailable(PackageManager.FEATURE_BLUETOOTH); } } public void testCameraFeatures() { Camera camera = null; try { // Try getting a camera. This is unlikely to fail but implentations without a camera // could return null or throw an exception. camera = Camera.open(); if (camera != null) { assertAvailable(PackageManager.FEATURE_CAMERA); Camera.Parameters params = camera.getParameters(); - if (!Parameters.FOCUS_MODE_FIXED.equals(params.getFocusMode())) { + if (params.getSupportedFocusModes().contains(Parameters.FOCUS_MODE_AUTO)) { assertAvailable(PackageManager.FEATURE_CAMERA_AUTOFOCUS); } else { assertNotAvailable(PackageManager.FEATURE_CAMERA_AUTOFOCUS); } if (params.getFlashMode() != null) { assertAvailable(PackageManager.FEATURE_CAMERA_FLASH); } else { assertNotAvailable(PackageManager.FEATURE_CAMERA_FLASH); } } else { assertNotAvailable(PackageManager.FEATURE_CAMERA); assertNotAvailable(PackageManager.FEATURE_CAMERA_AUTOFOCUS); assertNotAvailable(PackageManager.FEATURE_CAMERA_FLASH); } } catch (RuntimeException e) { assertNotAvailable(PackageManager.FEATURE_CAMERA); assertNotAvailable(PackageManager.FEATURE_CAMERA_AUTOFOCUS); assertNotAvailable(PackageManager.FEATURE_CAMERA_FLASH); } finally { if (camera != null) { camera.release(); } } } public void testLiveWallpaperFeature() { try { Intent intent = new Intent(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); assertAvailable(PackageManager.FEATURE_LIVE_WALLPAPER); } catch (ActivityNotFoundException e) { assertNotAvailable(PackageManager.FEATURE_LIVE_WALLPAPER); } } public void testLocationFeatures() { if (mLocationManager.getProvider(LocationManager.GPS_PROVIDER) != null) { assertAvailable(PackageManager.FEATURE_LOCATION); assertAvailable(PackageManager.FEATURE_LOCATION_GPS); } else { assertNotAvailable(PackageManager.FEATURE_LOCATION_GPS); } if (mLocationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) { assertAvailable(PackageManager.FEATURE_LOCATION); assertAvailable(PackageManager.FEATURE_LOCATION_NETWORK); } else { assertNotAvailable(PackageManager.FEATURE_LOCATION_NETWORK); } } /** * Check that the sensor features reported by the PackageManager correspond to the sensors * returned by {@link SensorManager#getSensorList(int)}. */ public void testSensorFeatures() throws Exception { Set<String> featuresLeft = getFeatureConstantsNames("FEATURE_SENSOR_"); assertFeatureForSensor(featuresLeft, PackageManager.FEATURE_SENSOR_ACCELEROMETER, Sensor.TYPE_ACCELEROMETER); assertFeatureForSensor(featuresLeft, PackageManager.FEATURE_SENSOR_COMPASS, Sensor.TYPE_MAGNETIC_FIELD); assertFeatureForSensor(featuresLeft, PackageManager.FEATURE_SENSOR_LIGHT, Sensor.TYPE_LIGHT); assertFeatureForSensor(featuresLeft, PackageManager.FEATURE_SENSOR_PROXIMITY, Sensor.TYPE_PROXIMITY); assertTrue("Assertions need to be added to this test for " + featuresLeft, featuresLeft.isEmpty()); } /** Get a list of feature constants in PackageManager matching a prefix. */ private static Set<String> getFeatureConstantsNames(String prefix) throws IllegalArgumentException, IllegalAccessException { Set<String> features = new HashSet<String>(); Field[] fields = PackageManager.class.getFields(); for (Field field : fields) { if (field.getName().startsWith(prefix)) { String feature = (String) field.get(null); features.add(feature); } } return features; } /** * Check that if the PackageManager declares a sensor feature that the device has at least * one sensor that matches that feature. Also check that if a PackageManager does not declare * a sensor that the device also does not have such a sensor. * * @param featuresLeft to check in order to make sure the test covers all sensor features * @param expectedFeature that the PackageManager may report * @param expectedSensorType that that {@link SensorManager#getSensorList(int)} may have */ private void assertFeatureForSensor(Set<String> featuresLeft, String expectedFeature, int expectedSensorType) { assertTrue("Features left " + featuresLeft + " to check did not include " + expectedFeature, featuresLeft.remove(expectedFeature)); boolean hasSensorFeature = mPackageManager.hasSystemFeature(expectedFeature); List<Sensor> sensors = mSensorManager.getSensorList(expectedSensorType); List<String> sensorNames = new ArrayList<String>(sensors.size()); for (Sensor sensor : sensors) { sensorNames.add(sensor.getName()); } boolean hasSensorType = !sensors.isEmpty(); String message = "PackageManager#hasSystemFeature(" + expectedFeature + ") returns " + hasSensorFeature + " but SensorManager#getSensorList(" + expectedSensorType + ") shows sensors " + sensorNames; assertEquals(message, hasSensorFeature, hasSensorType); } /** * Check that the {@link TelephonyManager#getPhoneType()} matches the reported features. */ public void testTelephonyFeatures() { int phoneType = mTelephonyManager.getPhoneType(); switch (phoneType) { case TelephonyManager.PHONE_TYPE_GSM: assertAvailable(PackageManager.FEATURE_TELEPHONY); assertAvailable(PackageManager.FEATURE_TELEPHONY_GSM); break; case TelephonyManager.PHONE_TYPE_CDMA: assertAvailable(PackageManager.FEATURE_TELEPHONY); assertAvailable(PackageManager.FEATURE_TELEPHONY_CDMA); break; case TelephonyManager.PHONE_TYPE_NONE: assertNotAvailable(PackageManager.FEATURE_TELEPHONY); assertNotAvailable(PackageManager.FEATURE_TELEPHONY_CDMA); assertNotAvailable(PackageManager.FEATURE_TELEPHONY_GSM); break; default: throw new IllegalArgumentException("Did you add a new phone type? " + phoneType); } } public void testTouchScreenFeatures() { ConfigurationInfo configInfo = mActivityManager.getDeviceConfigurationInfo(); if (configInfo.reqTouchScreen != Configuration.TOUCHSCREEN_NOTOUCH) { assertAvailable(PackageManager.FEATURE_TOUCHSCREEN); } else { assertNotAvailable(PackageManager.FEATURE_TOUCHSCREEN); } // TODO: Add tests for the other touchscreen features. } public void testWifiFeature() throws Exception { boolean enabled = mWifiManager.isWifiEnabled(); try { // WifiManager is hard-coded to return true, but in other implementations this could // return false for devices that don't have WiFi. if (mWifiManager.setWifiEnabled(true)) { assertAvailable(PackageManager.FEATURE_WIFI); } else { assertNotAvailable(PackageManager.FEATURE_WIFI); } } finally { if (!enabled) { mWifiManager.setWifiEnabled(false); } } } private void assertAvailable(String feature) { assertTrue("PackageManager#hasSystemFeature should return true for " + feature, mPackageManager.hasSystemFeature(feature)); assertTrue("PackageManager#getSystemAvailableFeatures should have " + feature, mAvailableFeatures.contains(feature)); } private void assertNotAvailable(String feature) { assertFalse("PackageManager#hasSystemFeature should NOT return true for " + feature, mPackageManager.hasSystemFeature(feature)); assertFalse("PackageManager#getSystemAvailableFeatures should NOT have " + feature, mAvailableFeatures.contains(feature)); } }
true
true
public void testCameraFeatures() { Camera camera = null; try { // Try getting a camera. This is unlikely to fail but implentations without a camera // could return null or throw an exception. camera = Camera.open(); if (camera != null) { assertAvailable(PackageManager.FEATURE_CAMERA); Camera.Parameters params = camera.getParameters(); if (!Parameters.FOCUS_MODE_FIXED.equals(params.getFocusMode())) { assertAvailable(PackageManager.FEATURE_CAMERA_AUTOFOCUS); } else { assertNotAvailable(PackageManager.FEATURE_CAMERA_AUTOFOCUS); } if (params.getFlashMode() != null) { assertAvailable(PackageManager.FEATURE_CAMERA_FLASH); } else { assertNotAvailable(PackageManager.FEATURE_CAMERA_FLASH); } } else { assertNotAvailable(PackageManager.FEATURE_CAMERA); assertNotAvailable(PackageManager.FEATURE_CAMERA_AUTOFOCUS); assertNotAvailable(PackageManager.FEATURE_CAMERA_FLASH); } } catch (RuntimeException e) { assertNotAvailable(PackageManager.FEATURE_CAMERA); assertNotAvailable(PackageManager.FEATURE_CAMERA_AUTOFOCUS); assertNotAvailable(PackageManager.FEATURE_CAMERA_FLASH); } finally { if (camera != null) { camera.release(); } } }
public void testCameraFeatures() { Camera camera = null; try { // Try getting a camera. This is unlikely to fail but implentations without a camera // could return null or throw an exception. camera = Camera.open(); if (camera != null) { assertAvailable(PackageManager.FEATURE_CAMERA); Camera.Parameters params = camera.getParameters(); if (params.getSupportedFocusModes().contains(Parameters.FOCUS_MODE_AUTO)) { assertAvailable(PackageManager.FEATURE_CAMERA_AUTOFOCUS); } else { assertNotAvailable(PackageManager.FEATURE_CAMERA_AUTOFOCUS); } if (params.getFlashMode() != null) { assertAvailable(PackageManager.FEATURE_CAMERA_FLASH); } else { assertNotAvailable(PackageManager.FEATURE_CAMERA_FLASH); } } else { assertNotAvailable(PackageManager.FEATURE_CAMERA); assertNotAvailable(PackageManager.FEATURE_CAMERA_AUTOFOCUS); assertNotAvailable(PackageManager.FEATURE_CAMERA_FLASH); } } catch (RuntimeException e) { assertNotAvailable(PackageManager.FEATURE_CAMERA); assertNotAvailable(PackageManager.FEATURE_CAMERA_AUTOFOCUS); assertNotAvailable(PackageManager.FEATURE_CAMERA_FLASH); } finally { if (camera != null) { camera.release(); } } }
diff --git a/wiki30-realtime-wysiwyg/wiki30-realtime-wysiwyg-plugin/src/main/java/org/xwiki/gwt/wysiwyg/client/plugin/rt/RealTimePlugin.java b/wiki30-realtime-wysiwyg/wiki30-realtime-wysiwyg-plugin/src/main/java/org/xwiki/gwt/wysiwyg/client/plugin/rt/RealTimePlugin.java index 6404afa..d3af956 100644 --- a/wiki30-realtime-wysiwyg/wiki30-realtime-wysiwyg-plugin/src/main/java/org/xwiki/gwt/wysiwyg/client/plugin/rt/RealTimePlugin.java +++ b/wiki30-realtime-wysiwyg/wiki30-realtime-wysiwyg-plugin/src/main/java/org/xwiki/gwt/wysiwyg/client/plugin/rt/RealTimePlugin.java @@ -1,541 +1,546 @@ /* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.gwt.wysiwyg.client.plugin.rt; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import org.xwiki.gwt.dom.client.DOMUtils; import org.xwiki.gwt.dom.client.Range; import org.xwiki.gwt.dom.client.Selection; import org.xwiki.gwt.user.client.Config; import org.xwiki.gwt.user.client.ui.rta.RichTextArea; import org.xwiki.gwt.user.client.ui.rta.cmd.Command; import org.xwiki.gwt.user.client.ui.rta.cmd.CommandListener; import org.xwiki.gwt.user.client.ui.rta.cmd.CommandManager; import org.xwiki.gwt.wysiwyg.client.Images; import org.xwiki.gwt.wysiwyg.client.Strings; import org.xwiki.gwt.wysiwyg.client.plugin.internal.AbstractStatefulPlugin; import org.xwiki.gwt.wysiwyg.client.plugin.internal.FocusWidgetUIExtension; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Node; import com.google.gwt.dom.client.Text; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.event.dom.client.KeyDownHandler; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwt.event.dom.client.KeyPressHandler; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.ui.FocusWidget; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.ToggleButton; import fr.loria.score.client.ClientJupiterAlg; import fr.loria.score.client.CommunicationService; import fr.loria.score.client.RtApi; import fr.loria.score.jupiter.tree.TreeDocument; import fr.loria.score.jupiter.tree.operation.TreeDeleteText; import fr.loria.score.jupiter.tree.operation.TreeInsertParagraph; import fr.loria.score.jupiter.tree.operation.TreeInsertText; import fr.loria.score.jupiter.tree.operation.TreeMergeParagraph; import fr.loria.score.jupiter.tree.operation.TreeNewParagraph; import fr.loria.score.jupiter.tree.operation.TreeOperation; import fr.loria.score.jupiter.tree.operation.TreeStyle; import sun.java2d.pipe.SpanClipRenderer; /** * Broadcasts DOM mutations generated inside the rich text area. * It overrides nearly all plugin-based features of WYSIWYG: line, text aso. * * @version $Id: 4e19fb82c1f5869f4850b80c3b5f5d3b3d319483 $ */ public class RealTimePlugin extends AbstractStatefulPlugin implements KeyDownHandler, KeyPressHandler, KeyUpHandler, CommandListener, ClickHandler { private static Logger log = Logger.getLogger(RealTimePlugin.class.getName()); private static final String BR = "br"; private static ClientJupiterAlg clientJupiter; /** * The object used to create tree operations. */ private TreeOperationFactory treeOperationFactory = new TreeOperationFactory(); /** * The list of command that shouldn't be broadcasted. */ private static final List<Command> IGNORED_COMMANDS = Arrays.asList(Command.UPDATE, Command.ENABLE, new Command( "submit")); /** * The association between tool bar buttons and the commands that are executed when these buttons are clicked. */ private final Map<ToggleButton, Command> buttons = new HashMap<ToggleButton, Command>(); /** * User interface extension for the editor tool bar. */ private final FocusWidgetUIExtension toolBarExtension = new FocusWidgetUIExtension("toolbar"); /** * {@inheritDoc} * * @see AbstractStatefulPlugin#init(RichTextArea, Config) */ public void init(RichTextArea textArea, Config config) { super.init(textArea, config); saveRegistration(textArea.addKeyDownHandler(this)); saveRegistration(textArea.addKeyPressHandler(this)); saveRegistration(textArea.addKeyUpHandler(this)); getTextArea().getCommandManager().addCommandListener(this); // register the styling buttons and their actions addFeature("bold", Command.BOLD, Images.INSTANCE.bold(), Strings.INSTANCE.bold()); addFeature("italic", Command.ITALIC, Images.INSTANCE.italic(), Strings.INSTANCE.italic()); addFeature("underline", Command.UNDERLINE, Images.INSTANCE.underline(), Strings.INSTANCE.underline()); addFeature("strikethrough", Command.STRIKE_THROUGH, Images.INSTANCE.strikeThrough(), Strings.INSTANCE.strikeThrough()); if (toolBarExtension.getFeatures().length > 0) { registerTextAreaHandlers(); getUIExtensionList().add(toolBarExtension); } // Jupiter algo initializing Node bodyNode = textArea.getDocument().getBody(); // insert a new paragraph on an empty text area final Element p = Document.get().createElement("p"); if (bodyNode.getChildCount() == 0) { bodyNode.insertFirst(p); } else if (bodyNode.getChildCount() == 1 && bodyNode.getFirstChild().getNodeName().equalsIgnoreCase(BR)) { bodyNode.insertBefore(p, bodyNode.getFirstChild()); } clientJupiter = new ClientJupiterAlg(new TreeDocument(Converter.fromNativeToCustom(Element.as(bodyNode)))); clientJupiter.setEditingSessionId(Integer.parseInt(config.getParameter(RtApi.DOCUMENT_ID))); clientJupiter.setCommunicationService(CommunicationService.ServiceHelper.getCommunicationService()); clientJupiter.setCallback(new TreeClientCallback(bodyNode)); clientJupiter.connect(); customizeActionListeners(); } /** * {@inheritDoc} * * @see AbstractStatefulPlugin#destroy() */ public void destroy() { getTextArea().getCommandManager().removeCommandListener(this); super.destroy(); } /** * {@inheritDoc} * * @see CommandListener#onBeforeCommand(CommandManager, Command, String) */ public boolean onBeforeCommand(CommandManager sender, Command command, String param) { if (getTextArea().isAttached() && getTextArea().isEnabled() && !IGNORED_COMMANDS.contains(command)) { Selection selection = getTextArea().getDocument().getSelection(); log.severe("It should execute just 1 time !"); if (selection.getRangeCount() > 0) { String styleKey = "unsupported"; String styleValue = "unsupported"; if (Command.BOLD.equals(command)) { styleKey = "font-weight"; styleValue = "bold"; } else if (Command.ITALIC.equals(command)) { styleKey = "font-style"; styleValue = "italic"; } else if (Command.UNDERLINE.equals(command)) { styleKey = "text-decoration"; styleValue = "underline"; } else if (Command.STRIKE_THROUGH.equals(command)) { styleKey = "text-decoration"; styleValue = "line-through"; } //Use this range to get all intermediary paths Range range = selection.getRangeAt(0); List<OperationTarget> targets = getIntermediaryTargets(range); log.info(targets.toString()); for (OperationTarget target : targets) { log.severe("Generate tree style op for :" + target.toString()); boolean addStyle = false; int[] path = treeOperationFactory.toIntArray(target.getStartContainer()); if (path.length == 2) { addStyle = true; } boolean splitLeft = true; int start = target.getStartOffset(); if (start == 0) { splitLeft = false; } boolean splitRight = true; int end = target.getEndOffset(); if (end == target.getDataLength()) { splitRight = false; } TreeOperation op = new TreeStyle(clientJupiter.getSiteId(), path, start, end, styleKey, styleValue, addStyle, splitLeft, splitRight); clientJupiter.generate(op); } // Block the command because it's already handled in DomStyle operation. return true; } } return false; } /** * {@inheritDoc} * * @see CommandListener#onCommand(CommandManager, Command, String) */ public void onCommand(CommandManager sender, final Command command, final String param) {} @Override public void onClick(ClickEvent event) { Command command = buttons.get(event.getSource()); // We have to test if the text area is attached because this method can be called after the event was consumed. if (command != null && getTextArea().isAttached() && ((FocusWidget) event.getSource()).isEnabled()) { getTextArea().setFocus(true); getTextArea().getCommandManager().execute(command); } } @Override public void update() { for (Map.Entry<ToggleButton, Command> entry : buttons.entrySet()) { if (entry.getKey().isEnabled()) { entry.getKey().setDown(getTextArea().getCommandManager().isExecuted(entry.getValue())); } } } //todo: broadcast only if the caret was inside the RTA, not outside.. @Override public void onKeyDown(KeyDownEvent event) { final int keyCode = event.getNativeKeyCode(); Selection selection = getTextArea().getDocument().getSelection(); if (selection.getRangeCount() > 0) { Range range = selection.getRangeAt(0); logRange(range); int pos = -1; Node startContainer = range.getStartContainer(); Node endContainer = range.getEndContainer(); List<Integer> path = treeOperationFactory.getLocator(range.getStartContainer()); //make case TreeOperation op = null; switch (keyCode) { case KeyCodes.KEY_BACKSPACE: { pos = range.getStartOffset(); log.info("Position is: " + pos); if (Node.TEXT_NODE == startContainer.getNodeType()) { Text textNode = Text.as(startContainer); if (pos == 0) { // perhaps a line merge log.info("1"); if (textNode.getParentElement().getPreviousSibling() != null) { // todo: test it 8Feb12.eroare log.info("1 - line merge"); //definitively a line merge op = new TreeMergeParagraph(clientJupiter.getSiteId(), path.get(0), 1, 1); op.setPath(treeOperationFactory.toIntArray(path)); } else { log.info("2 - nothing"); } } else { log.info("3 - delete"); pos = pos - 1; op = new TreeDeleteText(clientJupiter.getSiteId(), pos, treeOperationFactory.toIntArray(path)); } } else if (Node.ELEMENT_NODE == startContainer.getNodeType()) { if (pos == 0) { if (startContainer.getPreviousSibling() != null) { log.severe("Delete text on element, pos = 0, prev sibling not null"); // nothing for now } else { // prevent default, otherwise it would remove the paragraph element event.preventDefault(); } } } } break; case KeyCodes.KEY_DELETE: { if (Node.TEXT_NODE == startContainer.getNodeType()) { Text textNode = Text.as(startContainer); pos = range.getStartOffset(); if (textNode.getLength() == pos) { // perhaps a line merge Element sibling = textNode.getParentElement().getNextSiblingElement(); if ((sibling != null) && (!sibling.getClassName().toLowerCase().contains("firebug"))) { //line merge only if there is something to merge: the text node's parent has siblings path.set(0, path.get(0) + 1); op = new TreeMergeParagraph(clientJupiter.getSiteId(), path.get(0), 1, 1); op.setPath(treeOperationFactory.toIntArray(path)); } } else { op = new TreeDeleteText(clientJupiter.getSiteId(), pos, treeOperationFactory.toIntArray(path)); } } else if (Node.ELEMENT_NODE == startContainer.getNodeType()) { if (startContainer.getNextSibling() != null) { path.set(0, path.get(0) + 1); op = new TreeMergeParagraph(clientJupiter.getSiteId(), path.get(0), 1, 1); op.setPath(treeOperationFactory.toIntArray(path)); } } } break; case KeyCodes.KEY_ENTER: { path = treeOperationFactory.getLocator(range.getEndContainer()); pos = range.getEndOffset(); if (Node.TEXT_NODE == endContainer.getNodeType()) { Text textNode = Text.as(endContainer); boolean isNewParagraph = false; // Start of the line if (textNode.getPreviousSibling() == null && 0 == pos) { isNewParagraph = true; pos = path.get(0); } + // Go up until we reach the parent paragraph node, because we might have nested span tags + Node n = textNode; + while (!"p".equalsIgnoreCase(n.getParentNode().getNodeName())) { + n = n.getParentNode(); + } // End of line - if ((textNode.getNextSibling() == null || BR.equalsIgnoreCase(textNode.getNextSibling().getNodeName())) && textNode.getLength() == pos) { + if ((n.getNextSibling() == null || BR.equalsIgnoreCase(n.getNextSibling().getNodeName())) && textNode.getLength() == pos) { isNewParagraph = true; pos = path.get(0) + 1; } if (isNewParagraph) { op = new TreeNewParagraph(clientJupiter.getSiteId(), pos); op.setPath(treeOperationFactory.toIntArray(path)); } else { op = new TreeInsertParagraph(clientJupiter.getSiteId(), pos, treeOperationFactory.toIntArray(path)); } } else if (Node.ELEMENT_NODE == endContainer.getNodeType()) { Element element = Element.as(endContainer); // Start of the line if (element.getPreviousSibling() == null && 0 == pos) { op = new TreeNewParagraph(clientJupiter.getSiteId(), path.get(0)); op.setPath(treeOperationFactory.toIntArray(path)); } else { int brCount = element.getElementsByTagName(BR).getLength(); int childCount = element.getChildCount(); boolean isBeforeLastBrTag = ((pos == (childCount - brCount)) && (BR.equalsIgnoreCase(element.getLastChild().getNodeName()))); boolean isAfterLastTag = (pos == childCount); // End of the line if (isBeforeLastBrTag || isAfterLastTag) { pos = path.get(0) + 1; op = new TreeNewParagraph(clientJupiter.getSiteId(), pos); op.setPath(treeOperationFactory.toIntArray(path)); } else { // Somewhere in the middle of the line pos = range.getEndOffset(); op = new TreeInsertParagraph(clientJupiter.getSiteId(), pos, treeOperationFactory.toIntArray(path)); } } } } break; default: break; } if (op != null) { if (!(op instanceof TreeInsertText || op instanceof TreeDeleteText)) { // Prevent the default behavior because the DOM tree will be synchronized with the Tree model. event.preventDefault(); } clientJupiter.generate(op); } } } /** * {@inheritDoc} * * @see KeyPressHandler#onKeyPress(KeyPressEvent) */ public void onKeyPress(KeyPressEvent event) { log.info("onKeyPress: " + getTextArea().getHTML()); log.fine("onKeyPress: " + event.getCharCode() + ", native keyCode" + event.getNativeEvent().getKeyCode() + ", unicodeCharCode: " + event.getUnicodeCharCode()); boolean isAltControlOrMetaDown = event.isAltKeyDown() || event.isControlKeyDown() || event.isMetaKeyDown(); boolean isNoteworthyKeyPressed = event.getCharCode() != '\u0000'; if (getTextArea().isAttached() && getTextArea().isEnabled() && !isAltControlOrMetaDown && isNoteworthyKeyPressed) { Selection selection = getTextArea().getDocument().getSelection(); if (selection.getRangeCount() > 0) { Range range = selection.getRangeAt(0); logRange(range); char character = new String(new int[] {event.getUnicodeCharCode()}, 0, 1).charAt(0); clientJupiter.generate(treeOperationFactory.createTreeInsertText(clientJupiter.getSiteId(), range, character)); } } } @Override public void onKeyUp(KeyUpEvent event) { //for now nothing } /** * Customize the action listeners found in actionButtonsRT.js */ private static native void customizeActionListeners() /*-{ $wnd.onCancelHook = function() { @org.xwiki.gwt.wysiwyg.client.plugin.rt.RealTimePlugin::disconnect()(); }; $wnd.onSaveAndViewHook= function() { @org.xwiki.gwt.wysiwyg.client.plugin.rt.RealTimePlugin::disconnect()(); }; $wnd.onSaveAndContinueHook = function() { @org.xwiki.gwt.wysiwyg.client.plugin.rt.RealTimePlugin::disconnect()(); } }-*/; private static void disconnect() { clientJupiter.disconnect(); } private void logRange(Range r) { log.info("Start container: " + r.getStartContainer().getNodeName() + ", " + " locator: " + treeOperationFactory.getLocator(r.getStartContainer()) + " offset: " + r.getStartOffset() ); log.info("End container: " + r.getEndContainer().getNodeName() + ", " + " locator: " + treeOperationFactory.getLocator(r.getStartContainer()) + " offset: " + r.getEndOffset() ); } /** * Creates a tool bar feature and adds it to the tool bar. * * @param name the feature name * @param command the rich text area command that is executed by this feature * @param imageResource the image displayed on the tool bar * @param title the tool tip used on the tool bar button * @return the tool bar button that exposes this feature */ private ToggleButton addFeature(String name, Command command, ImageResource imageResource, String title) { ToggleButton button = null; if (getTextArea().getCommandManager().isSupported(command)) { button = new ToggleButton(new Image(imageResource)); saveRegistration(button.addClickHandler(this)); button.setTitle(title); toolBarExtension.addFeature(name, button); buttons.put(button, command); } return button; } /** * Converts a DOM range to an list of operation targets. * * @param range a DOM range * @return the corresponding list of operation targets */ private List<OperationTarget> getIntermediaryTargets(Range range) { // Iterate through all the text nodes within the given range and extract the operation target List<OperationTarget> operationTargets = new ArrayList<OperationTarget>(); List<Text> textNodes = getNonEmptyTextNodes(range); for (int i = 0; i < textNodes.size(); i++) { Text text = textNodes.get(i); int startIndex = 0; if (text == range.getStartContainer()) { startIndex = range.getStartOffset(); } int endIndex = text.getLength(); if (text == range.getEndContainer()) { endIndex = range.getEndOffset(); } operationTargets.add(new OperationTarget(treeOperationFactory.getLocator(text), startIndex, endIndex, text.getLength())); } return operationTargets; } /** * @param range a DOM range * @return the list of non empty text nodes that are completely or partially (at least one character) included in * the given range */ protected List<Text> getNonEmptyTextNodes(Range range) { Node leaf = DOMUtils.getInstance().getFirstLeaf(range); Node lastLeaf = DOMUtils.getInstance().getLastLeaf(range); List<Text> textNodes = new ArrayList<Text>(); // If the range starts at the end of a text node we have to ignore that node. if (isNonEmptyTextNode(leaf) && (leaf != range.getStartContainer() || range.getStartOffset() < leaf.getNodeValue().length())) { textNodes.add((Text) leaf); } while (leaf != lastLeaf) { leaf = DOMUtils.getInstance().getNextLeaf(leaf); if (isNonEmptyTextNode(leaf)) { textNodes.add((Text) leaf); } } // If the range ends at the start of a text node then we have to ignore that node. int lastIndex = textNodes.size() - 1; if (lastIndex >= 0 && range.getEndOffset() == 0 && textNodes.get(lastIndex) == range.getEndContainer()) { textNodes.remove(lastIndex); } return textNodes; } /** * @param node a DOM node * @return {@code true} if the given node is of type {@link Node#TEXT_NODE} and it's not empty, {@code false} * otherwise */ private boolean isNonEmptyTextNode(Node node) { return node.getNodeType() == Node.TEXT_NODE && node.getNodeValue().length() > 0; } }
false
true
public void onKeyDown(KeyDownEvent event) { final int keyCode = event.getNativeKeyCode(); Selection selection = getTextArea().getDocument().getSelection(); if (selection.getRangeCount() > 0) { Range range = selection.getRangeAt(0); logRange(range); int pos = -1; Node startContainer = range.getStartContainer(); Node endContainer = range.getEndContainer(); List<Integer> path = treeOperationFactory.getLocator(range.getStartContainer()); //make case TreeOperation op = null; switch (keyCode) { case KeyCodes.KEY_BACKSPACE: { pos = range.getStartOffset(); log.info("Position is: " + pos); if (Node.TEXT_NODE == startContainer.getNodeType()) { Text textNode = Text.as(startContainer); if (pos == 0) { // perhaps a line merge log.info("1"); if (textNode.getParentElement().getPreviousSibling() != null) { // todo: test it 8Feb12.eroare log.info("1 - line merge"); //definitively a line merge op = new TreeMergeParagraph(clientJupiter.getSiteId(), path.get(0), 1, 1); op.setPath(treeOperationFactory.toIntArray(path)); } else { log.info("2 - nothing"); } } else { log.info("3 - delete"); pos = pos - 1; op = new TreeDeleteText(clientJupiter.getSiteId(), pos, treeOperationFactory.toIntArray(path)); } } else if (Node.ELEMENT_NODE == startContainer.getNodeType()) { if (pos == 0) { if (startContainer.getPreviousSibling() != null) { log.severe("Delete text on element, pos = 0, prev sibling not null"); // nothing for now } else { // prevent default, otherwise it would remove the paragraph element event.preventDefault(); } } } } break; case KeyCodes.KEY_DELETE: { if (Node.TEXT_NODE == startContainer.getNodeType()) { Text textNode = Text.as(startContainer); pos = range.getStartOffset(); if (textNode.getLength() == pos) { // perhaps a line merge Element sibling = textNode.getParentElement().getNextSiblingElement(); if ((sibling != null) && (!sibling.getClassName().toLowerCase().contains("firebug"))) { //line merge only if there is something to merge: the text node's parent has siblings path.set(0, path.get(0) + 1); op = new TreeMergeParagraph(clientJupiter.getSiteId(), path.get(0), 1, 1); op.setPath(treeOperationFactory.toIntArray(path)); } } else { op = new TreeDeleteText(clientJupiter.getSiteId(), pos, treeOperationFactory.toIntArray(path)); } } else if (Node.ELEMENT_NODE == startContainer.getNodeType()) { if (startContainer.getNextSibling() != null) { path.set(0, path.get(0) + 1); op = new TreeMergeParagraph(clientJupiter.getSiteId(), path.get(0), 1, 1); op.setPath(treeOperationFactory.toIntArray(path)); } } } break; case KeyCodes.KEY_ENTER: { path = treeOperationFactory.getLocator(range.getEndContainer()); pos = range.getEndOffset(); if (Node.TEXT_NODE == endContainer.getNodeType()) { Text textNode = Text.as(endContainer); boolean isNewParagraph = false; // Start of the line if (textNode.getPreviousSibling() == null && 0 == pos) { isNewParagraph = true; pos = path.get(0); } // End of line if ((textNode.getNextSibling() == null || BR.equalsIgnoreCase(textNode.getNextSibling().getNodeName())) && textNode.getLength() == pos) { isNewParagraph = true; pos = path.get(0) + 1; } if (isNewParagraph) { op = new TreeNewParagraph(clientJupiter.getSiteId(), pos); op.setPath(treeOperationFactory.toIntArray(path)); } else { op = new TreeInsertParagraph(clientJupiter.getSiteId(), pos, treeOperationFactory.toIntArray(path)); } } else if (Node.ELEMENT_NODE == endContainer.getNodeType()) { Element element = Element.as(endContainer); // Start of the line if (element.getPreviousSibling() == null && 0 == pos) { op = new TreeNewParagraph(clientJupiter.getSiteId(), path.get(0)); op.setPath(treeOperationFactory.toIntArray(path)); } else { int brCount = element.getElementsByTagName(BR).getLength(); int childCount = element.getChildCount(); boolean isBeforeLastBrTag = ((pos == (childCount - brCount)) && (BR.equalsIgnoreCase(element.getLastChild().getNodeName()))); boolean isAfterLastTag = (pos == childCount); // End of the line if (isBeforeLastBrTag || isAfterLastTag) { pos = path.get(0) + 1; op = new TreeNewParagraph(clientJupiter.getSiteId(), pos); op.setPath(treeOperationFactory.toIntArray(path)); } else { // Somewhere in the middle of the line pos = range.getEndOffset(); op = new TreeInsertParagraph(clientJupiter.getSiteId(), pos, treeOperationFactory.toIntArray(path)); } } } } break; default: break; } if (op != null) { if (!(op instanceof TreeInsertText || op instanceof TreeDeleteText)) { // Prevent the default behavior because the DOM tree will be synchronized with the Tree model. event.preventDefault(); } clientJupiter.generate(op); } } }
public void onKeyDown(KeyDownEvent event) { final int keyCode = event.getNativeKeyCode(); Selection selection = getTextArea().getDocument().getSelection(); if (selection.getRangeCount() > 0) { Range range = selection.getRangeAt(0); logRange(range); int pos = -1; Node startContainer = range.getStartContainer(); Node endContainer = range.getEndContainer(); List<Integer> path = treeOperationFactory.getLocator(range.getStartContainer()); //make case TreeOperation op = null; switch (keyCode) { case KeyCodes.KEY_BACKSPACE: { pos = range.getStartOffset(); log.info("Position is: " + pos); if (Node.TEXT_NODE == startContainer.getNodeType()) { Text textNode = Text.as(startContainer); if (pos == 0) { // perhaps a line merge log.info("1"); if (textNode.getParentElement().getPreviousSibling() != null) { // todo: test it 8Feb12.eroare log.info("1 - line merge"); //definitively a line merge op = new TreeMergeParagraph(clientJupiter.getSiteId(), path.get(0), 1, 1); op.setPath(treeOperationFactory.toIntArray(path)); } else { log.info("2 - nothing"); } } else { log.info("3 - delete"); pos = pos - 1; op = new TreeDeleteText(clientJupiter.getSiteId(), pos, treeOperationFactory.toIntArray(path)); } } else if (Node.ELEMENT_NODE == startContainer.getNodeType()) { if (pos == 0) { if (startContainer.getPreviousSibling() != null) { log.severe("Delete text on element, pos = 0, prev sibling not null"); // nothing for now } else { // prevent default, otherwise it would remove the paragraph element event.preventDefault(); } } } } break; case KeyCodes.KEY_DELETE: { if (Node.TEXT_NODE == startContainer.getNodeType()) { Text textNode = Text.as(startContainer); pos = range.getStartOffset(); if (textNode.getLength() == pos) { // perhaps a line merge Element sibling = textNode.getParentElement().getNextSiblingElement(); if ((sibling != null) && (!sibling.getClassName().toLowerCase().contains("firebug"))) { //line merge only if there is something to merge: the text node's parent has siblings path.set(0, path.get(0) + 1); op = new TreeMergeParagraph(clientJupiter.getSiteId(), path.get(0), 1, 1); op.setPath(treeOperationFactory.toIntArray(path)); } } else { op = new TreeDeleteText(clientJupiter.getSiteId(), pos, treeOperationFactory.toIntArray(path)); } } else if (Node.ELEMENT_NODE == startContainer.getNodeType()) { if (startContainer.getNextSibling() != null) { path.set(0, path.get(0) + 1); op = new TreeMergeParagraph(clientJupiter.getSiteId(), path.get(0), 1, 1); op.setPath(treeOperationFactory.toIntArray(path)); } } } break; case KeyCodes.KEY_ENTER: { path = treeOperationFactory.getLocator(range.getEndContainer()); pos = range.getEndOffset(); if (Node.TEXT_NODE == endContainer.getNodeType()) { Text textNode = Text.as(endContainer); boolean isNewParagraph = false; // Start of the line if (textNode.getPreviousSibling() == null && 0 == pos) { isNewParagraph = true; pos = path.get(0); } // Go up until we reach the parent paragraph node, because we might have nested span tags Node n = textNode; while (!"p".equalsIgnoreCase(n.getParentNode().getNodeName())) { n = n.getParentNode(); } // End of line if ((n.getNextSibling() == null || BR.equalsIgnoreCase(n.getNextSibling().getNodeName())) && textNode.getLength() == pos) { isNewParagraph = true; pos = path.get(0) + 1; } if (isNewParagraph) { op = new TreeNewParagraph(clientJupiter.getSiteId(), pos); op.setPath(treeOperationFactory.toIntArray(path)); } else { op = new TreeInsertParagraph(clientJupiter.getSiteId(), pos, treeOperationFactory.toIntArray(path)); } } else if (Node.ELEMENT_NODE == endContainer.getNodeType()) { Element element = Element.as(endContainer); // Start of the line if (element.getPreviousSibling() == null && 0 == pos) { op = new TreeNewParagraph(clientJupiter.getSiteId(), path.get(0)); op.setPath(treeOperationFactory.toIntArray(path)); } else { int brCount = element.getElementsByTagName(BR).getLength(); int childCount = element.getChildCount(); boolean isBeforeLastBrTag = ((pos == (childCount - brCount)) && (BR.equalsIgnoreCase(element.getLastChild().getNodeName()))); boolean isAfterLastTag = (pos == childCount); // End of the line if (isBeforeLastBrTag || isAfterLastTag) { pos = path.get(0) + 1; op = new TreeNewParagraph(clientJupiter.getSiteId(), pos); op.setPath(treeOperationFactory.toIntArray(path)); } else { // Somewhere in the middle of the line pos = range.getEndOffset(); op = new TreeInsertParagraph(clientJupiter.getSiteId(), pos, treeOperationFactory.toIntArray(path)); } } } } break; default: break; } if (op != null) { if (!(op instanceof TreeInsertText || op instanceof TreeDeleteText)) { // Prevent the default behavior because the DOM tree will be synchronized with the Tree model. event.preventDefault(); } clientJupiter.generate(op); } } }
diff --git a/JunkHub/src/edu/unsw/triangle/web/ItemFormController.java b/JunkHub/src/edu/unsw/triangle/web/ItemFormController.java index 0c380e2..44aa11e 100644 --- a/JunkHub/src/edu/unsw/triangle/web/ItemFormController.java +++ b/JunkHub/src/edu/unsw/triangle/web/ItemFormController.java @@ -1,115 +1,115 @@ package edu.unsw.triangle.web; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import edu.unsw.triangle.controller.AbstractFormController; import edu.unsw.triangle.controller.ModelView; import edu.unsw.triangle.model.Bid; import edu.unsw.triangle.model.Item; import edu.unsw.triangle.model.Item.ItemStatus; import edu.unsw.triangle.service.BidService; import edu.unsw.triangle.service.ItemService; import edu.unsw.triangle.util.BidValidator; import edu.unsw.triangle.util.Errors; import edu.unsw.triangle.util.Messages; import edu.unsw.triangle.util.Validator; import edu.unsw.triangle.view.BidBinder; import edu.unsw.triangle.view.RequestBinder; public class ItemFormController extends AbstractFormController { private final Logger logger = Logger.getLogger(ItemFormController.class.getName()); @Override public String getFormView() { return "item.view"; } @Override protected Object createBackingObject(HttpServletRequest request) { // TODO Auto-generated method stub return null; } // TODO poor logic here @Override protected ModelView handleFormSubmit(Object command) { Bid bid = (Bid) command; Item item = bid.getItem(); if (item == null) { logger.severe("item id: " + bid.getItemId() + " is null"); Errors errors = new Errors().rejectValue("item.error", "item id: " + bid.getItemId() + " is null"); return handleFormError(bid, errors); } // Check item is active and not expired if (item.getStatus() != ItemStatus.ACTIVE || item.getTimeLeft() < 0) { // Item is not active or expired logger.severe("item id: " + bid.getItemId() + " is not active or expired"); Errors errors = new Errors().rejectValue("bid", "bid failed, item is no longer active"); return handleFormError(bid, errors); } // Check bid is greater than current bid plus increment if (bid.getBidFloat() < (item.getBid() + item.getIncrement())) { logger.severe("item id: bid: $" + bid.getBid() + " is less than current bid: " + item.getBid() + " and increment: " + item.getIncrement()); Errors errors = new Errors().rejectValue("bid", "bid is less than current bid plus increment"); return handleFormError(bid, errors); } // Update new bid try { // Notify bidder of success BidService.updateItemBidAndNotify(bid, item); } catch (Exception e) { logger.severe("updating item with new bid failed reason: " + e.getMessage()); e.printStackTrace(); - Errors errors = new Errors().rejectValue("bid", "bid faild to update in repository"); + Errors errors = new Errors().rejectValue("bid", "bid faild to update in repository reason:" + e.getMessage()); return handleFormError(bid, errors); } Messages messages = new Messages().add("bid.success", "your bid was successful"); ModelView modelView = new ModelView(getSuccessView()).redirect().addParameter("id", String.valueOf(item.getId())).addModel("messages", messages); return modelView; } @Override protected Validator getValidator() { return new BidValidator(); } @Override protected RequestBinder getBinder() { return new BidBinder(); } @Override protected String getSuccessView() { return "item"; } @Override protected ModelView handleFormError(Object command, Errors errors) { Bid bid = (Bid) command; ModelView modelView = new ModelView(getFormView()).forward().addModel("item", bid.getItem()). addModel("errors", errors).addParameter("id", String.valueOf(bid.getItemId())); return modelView; } }
true
true
protected ModelView handleFormSubmit(Object command) { Bid bid = (Bid) command; Item item = bid.getItem(); if (item == null) { logger.severe("item id: " + bid.getItemId() + " is null"); Errors errors = new Errors().rejectValue("item.error", "item id: " + bid.getItemId() + " is null"); return handleFormError(bid, errors); } // Check item is active and not expired if (item.getStatus() != ItemStatus.ACTIVE || item.getTimeLeft() < 0) { // Item is not active or expired logger.severe("item id: " + bid.getItemId() + " is not active or expired"); Errors errors = new Errors().rejectValue("bid", "bid failed, item is no longer active"); return handleFormError(bid, errors); } // Check bid is greater than current bid plus increment if (bid.getBidFloat() < (item.getBid() + item.getIncrement())) { logger.severe("item id: bid: $" + bid.getBid() + " is less than current bid: " + item.getBid() + " and increment: " + item.getIncrement()); Errors errors = new Errors().rejectValue("bid", "bid is less than current bid plus increment"); return handleFormError(bid, errors); } // Update new bid try { // Notify bidder of success BidService.updateItemBidAndNotify(bid, item); } catch (Exception e) { logger.severe("updating item with new bid failed reason: " + e.getMessage()); e.printStackTrace(); Errors errors = new Errors().rejectValue("bid", "bid faild to update in repository"); return handleFormError(bid, errors); } Messages messages = new Messages().add("bid.success", "your bid was successful"); ModelView modelView = new ModelView(getSuccessView()).redirect().addParameter("id", String.valueOf(item.getId())).addModel("messages", messages); return modelView; }
protected ModelView handleFormSubmit(Object command) { Bid bid = (Bid) command; Item item = bid.getItem(); if (item == null) { logger.severe("item id: " + bid.getItemId() + " is null"); Errors errors = new Errors().rejectValue("item.error", "item id: " + bid.getItemId() + " is null"); return handleFormError(bid, errors); } // Check item is active and not expired if (item.getStatus() != ItemStatus.ACTIVE || item.getTimeLeft() < 0) { // Item is not active or expired logger.severe("item id: " + bid.getItemId() + " is not active or expired"); Errors errors = new Errors().rejectValue("bid", "bid failed, item is no longer active"); return handleFormError(bid, errors); } // Check bid is greater than current bid plus increment if (bid.getBidFloat() < (item.getBid() + item.getIncrement())) { logger.severe("item id: bid: $" + bid.getBid() + " is less than current bid: " + item.getBid() + " and increment: " + item.getIncrement()); Errors errors = new Errors().rejectValue("bid", "bid is less than current bid plus increment"); return handleFormError(bid, errors); } // Update new bid try { // Notify bidder of success BidService.updateItemBidAndNotify(bid, item); } catch (Exception e) { logger.severe("updating item with new bid failed reason: " + e.getMessage()); e.printStackTrace(); Errors errors = new Errors().rejectValue("bid", "bid faild to update in repository reason:" + e.getMessage()); return handleFormError(bid, errors); } Messages messages = new Messages().add("bid.success", "your bid was successful"); ModelView modelView = new ModelView(getSuccessView()).redirect().addParameter("id", String.valueOf(item.getId())).addModel("messages", messages); return modelView; }
diff --git a/sobiohazardous/minestrappolation/extradecor/block/EDOreRegistry.java b/sobiohazardous/minestrappolation/extradecor/block/EDOreRegistry.java index 6f1ddafe..89712a86 100644 --- a/sobiohazardous/minestrappolation/extradecor/block/EDOreRegistry.java +++ b/sobiohazardous/minestrappolation/extradecor/block/EDOreRegistry.java @@ -1,37 +1,41 @@ package sobiohazardous.minestrappolation.extradecor.block; import sobiohazardous.minestrappolation.extradecor.lib.EDBlockManager; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.ShapedOreRecipe; import cpw.mods.fml.common.registry.GameRegistry; public class EDOreRegistry { public static void oreRegistration() { OreDictionary.registerOre("plankWood", new ItemStack(EDBlockManager.woodBoards, 1, 0)); OreDictionary.registerOre("plankWood", new ItemStack(EDBlockManager.woodBoards, 1, 1)); OreDictionary.registerOre("plankWood", new ItemStack(EDBlockManager.woodBoards, 1, 2)); OreDictionary.registerOre("plankWood", new ItemStack(EDBlockManager.woodBoards, 1, 3)); + OreDictionary.registerOre("plankWood", new ItemStack(EDBlockManager.woodPlanksMossy, 1, 0)); + OreDictionary.registerOre("plankWood", new ItemStack(EDBlockManager.woodPlanksMossy, 1, 1)); + OreDictionary.registerOre("plankWood", new ItemStack(EDBlockManager.woodPlanksMossy, 1, 2)); + OreDictionary.registerOre("plankWood", new ItemStack(EDBlockManager.woodPlanksMossy, 1, 3)); OreDictionary.registerOre("meatRaw", new ItemStack(Item.beefRaw)); OreDictionary.registerOre("meatRaw", new ItemStack(Item.porkRaw)); OreDictionary.registerOre("meatRaw", new ItemStack(Item.fishRaw)); OreDictionary.registerOre("meatRaw", new ItemStack(Item.chickenRaw)); OreDictionary.registerOre("meatRaw", new ItemStack(Item.rottenFlesh)); } public static void addOreRecipes() { GameRegistry.addRecipe(new ShapedOreRecipe(EDBlockManager.meatBlock, true, new Object[] { "MMM", "MMM", "MMM", Character.valueOf('M'), "meatRaw" })); GameRegistry.addRecipe(new ShapedOreRecipe(EDBlockManager.crate, true, new Object[] { "WWW","SSS","WWW", Character.valueOf('S'), Item.stick, Character.valueOf('W'), "plankWood" })); } }
true
true
public static void oreRegistration() { OreDictionary.registerOre("plankWood", new ItemStack(EDBlockManager.woodBoards, 1, 0)); OreDictionary.registerOre("plankWood", new ItemStack(EDBlockManager.woodBoards, 1, 1)); OreDictionary.registerOre("plankWood", new ItemStack(EDBlockManager.woodBoards, 1, 2)); OreDictionary.registerOre("plankWood", new ItemStack(EDBlockManager.woodBoards, 1, 3)); OreDictionary.registerOre("meatRaw", new ItemStack(Item.beefRaw)); OreDictionary.registerOre("meatRaw", new ItemStack(Item.porkRaw)); OreDictionary.registerOre("meatRaw", new ItemStack(Item.fishRaw)); OreDictionary.registerOre("meatRaw", new ItemStack(Item.chickenRaw)); OreDictionary.registerOre("meatRaw", new ItemStack(Item.rottenFlesh)); }
public static void oreRegistration() { OreDictionary.registerOre("plankWood", new ItemStack(EDBlockManager.woodBoards, 1, 0)); OreDictionary.registerOre("plankWood", new ItemStack(EDBlockManager.woodBoards, 1, 1)); OreDictionary.registerOre("plankWood", new ItemStack(EDBlockManager.woodBoards, 1, 2)); OreDictionary.registerOre("plankWood", new ItemStack(EDBlockManager.woodBoards, 1, 3)); OreDictionary.registerOre("plankWood", new ItemStack(EDBlockManager.woodPlanksMossy, 1, 0)); OreDictionary.registerOre("plankWood", new ItemStack(EDBlockManager.woodPlanksMossy, 1, 1)); OreDictionary.registerOre("plankWood", new ItemStack(EDBlockManager.woodPlanksMossy, 1, 2)); OreDictionary.registerOre("plankWood", new ItemStack(EDBlockManager.woodPlanksMossy, 1, 3)); OreDictionary.registerOre("meatRaw", new ItemStack(Item.beefRaw)); OreDictionary.registerOre("meatRaw", new ItemStack(Item.porkRaw)); OreDictionary.registerOre("meatRaw", new ItemStack(Item.fishRaw)); OreDictionary.registerOre("meatRaw", new ItemStack(Item.chickenRaw)); OreDictionary.registerOre("meatRaw", new ItemStack(Item.rottenFlesh)); }
diff --git a/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/bugzilla/ui/tasklist/BugzillaRefreshManager.java b/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/bugzilla/ui/tasklist/BugzillaRefreshManager.java index 7cf79ca47..0f9532f3e 100644 --- a/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/bugzilla/ui/tasklist/BugzillaRefreshManager.java +++ b/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/bugzilla/ui/tasklist/BugzillaRefreshManager.java @@ -1,75 +1,76 @@ /******************************************************************************* * Copyright (c) 2004 - 2005 University Of British Columbia and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylar.bugzilla.ui.tasklist; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.eclipse.core.runtime.jobs.Job; public class BugzillaRefreshManager { private List<BugzillaTask> toBeRefreshed; private Map<BugzillaTask, Job> currentlyRefreshing; private static final int MAX_REFRESH_JOBS = 5; public BugzillaRefreshManager (){ toBeRefreshed = new LinkedList<BugzillaTask>(); currentlyRefreshing = new HashMap<BugzillaTask, Job>(); } public void addTaskToBeRefreshed(BugzillaTask task){ if(!currentlyRefreshing.containsKey(task) && !toBeRefreshed.contains(task)){ toBeRefreshed.add(task); } updateRefreshState(); } public void removeTaskToBeRefreshed(BugzillaTask task){ toBeRefreshed.remove(task); if(currentlyRefreshing.get(task) != null){ currentlyRefreshing.get(task).cancel(); currentlyRefreshing.remove(task); } updateRefreshState(); } public void removeRefreshingTask(BugzillaTask task){ if(currentlyRefreshing.containsKey(task)){ currentlyRefreshing.remove(task); } updateRefreshState(); } private void updateRefreshState(){ if(currentlyRefreshing.size() < MAX_REFRESH_JOBS && toBeRefreshed.size() > 0){ BugzillaTask t = toBeRefreshed.remove(0); Job j = t.getRefreshJob(); currentlyRefreshing.put(t, j); j.schedule(); } } public void clearAllRefreshes() { toBeRefreshed.clear(); List<Job> l = new ArrayList<Job>(); l.addAll(currentlyRefreshing.values()); for(Job j : l){ - j.cancel(); + if(j != null) + j.cancel(); } currentlyRefreshing.clear(); } }
true
true
public void clearAllRefreshes() { toBeRefreshed.clear(); List<Job> l = new ArrayList<Job>(); l.addAll(currentlyRefreshing.values()); for(Job j : l){ j.cancel(); } currentlyRefreshing.clear(); }
public void clearAllRefreshes() { toBeRefreshed.clear(); List<Job> l = new ArrayList<Job>(); l.addAll(currentlyRefreshing.values()); for(Job j : l){ if(j != null) j.cancel(); } currentlyRefreshing.clear(); }