diff
stringlengths
164
2.11M
is_single_chunk
bool
2 classes
is_single_function
bool
2 classes
buggy_function
stringlengths
0
335k
fixed_function
stringlengths
23
335k
diff --git a/src/jcue/domain/CueList.java b/src/jcue/domain/CueList.java index b2d7797..4fb2797 100644 --- a/src/jcue/domain/CueList.java +++ b/src/jcue/domain/CueList.java @@ -1,307 +1,313 @@ package jcue.domain; import java.util.ArrayList; import java.util.EventListener; import javax.swing.ListModel; import javax.swing.event.EventListenerList; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; import javax.swing.table.AbstractTableModel; import jcue.domain.audiocue.AudioCue; import jcue.domain.eventcue.EventCue; import jcue.domain.fadecue.FadeCue; /** * Stores the cues created. Only on instance of CueList can * be created. Use getInstance() to retrieve it. * * @author Jaakko */ public class CueList extends AbstractTableModel implements ListModel { private static volatile CueList instance = null; protected EventListenerList listListenerList = new EventListenerList(); private ArrayList<AbstractCue> cues; private int counter; private DeviceManager dm; private CueList() { super(); this.cues = new ArrayList<AbstractCue>(); this.counter = 1; this.dm = DeviceManager.getInstance(); } /** * * @return instance of CueList */ public static CueList getInstance() { if (instance == null) { synchronized (CueList.class) { if (instance == null) { instance = new CueList(); } } } return instance; } /** * Create and add a new cue. * * @param cueType type of the new cue */ public void addCue(CueType cueType) { AbstractCue cue = null; if (cueType == CueType.AUDIO) { cue = new AudioCue("Q" + counter, "", this.dm.getAutoIncludeDevices()); } else if (cueType == CueType.EVENT) { cue = new EventCue("Q" + counter, ""); } else if (cueType == CueType.FADE) { cue = new FadeCue("Q" + counter, ""); } else if (cueType == CueType.NOTE) { } this.cues.add(cue); //Notify JList and JTable about new element fireIntervalAdded(cue, getSize() - 1, getSize()); super.fireTableRowsInserted(getSize() - 1, getSize()); //Increment the "id" counter this.counter++; } /** * Add existing cue to the list. * * @param cue cue to add */ public void addCue(AbstractCue cue) { this.cues.add(cue); //Notify JList and JTable about new element fireIntervalAdded(cue, getSize() - 1, getSize()); super.fireTableRowsInserted(getSize() - 1, getSize()); //Increment the "id" counter this.counter++; } public void deleteCue(AbstractCue cue) { if (this.cues.contains(cue)) { int index = getCueIndex(cue); this.fireIntervalRemoved(cue, index - 1, index); super.fireTableRowsDeleted(index - 1, index); this.cues.remove(cue); } } - public void moveCue(AbstractCue cue, int newIndex) { + public boolean moveCue(AbstractCue cue, int newIndex) { + if (cue == null) { + return false; + } + int size = cues.size(); int index = getCueIndex(cue); cues.remove(cue); if (newIndex < 0) { cues.add(0, cue); } else if (newIndex >= size) { cues.add(cue); } else { cues.add(newIndex, cue); } this.fireContentsChanged(cue, index, newIndex); this.fireTableDataChanged(); + + return true; } /** * Get cue by its index. * * @param index index starting from 0 * @return cue at index */ public AbstractCue getCue(int index) { return this.cues.get(index); } /** * * @return amount of cues in the list */ public int size() { return this.cues.size(); } /** * Returns the index of specific cue. * * @param cue cue which index to get * @return cue's index */ public int getCueIndex(AbstractCue cue) { return this.cues.lastIndexOf(cue); } /** * Returns list of all cues. * * @return list of all cues */ public ArrayList<AbstractCue> getCues() { return cues; } /** * Returns a list of all cues excluding the cue given. * * @param exclude cue to exclude from the result * @return resulting list */ public ArrayList<AbstractCue> getCues(AbstractCue exclude) { ArrayList<AbstractCue> result = new ArrayList<AbstractCue>(); for (AbstractCue ac : this.cues) { if (ac != exclude) { result.add(ac); } } return result; } /** * Returns a list of cues of given type. * * @param type type of cues * @return cues of given type */ public ArrayList<AbstractCue> getCues(CueType type) { ArrayList<AbstractCue> result = new ArrayList<AbstractCue>(); for (AbstractCue ac : this.cues) { if (ac.getType() == type) { result.add(ac); } } return result; } //<editor-fold defaultstate="collapsed" desc="Model stuff"> @Override public int getSize() { return this.cues.size(); } @Override public Object getElementAt(int i) { return this.cues.get(i); } @Override public void addListDataListener(ListDataListener ll) { listListenerList.add(ListDataListener.class, ll); } @Override public void removeListDataListener(ListDataListener ll) { listListenerList.remove(ListDataListener.class, ll); } public ListDataListener[] getListDataListeners() { return (ListDataListener[]) listListenerList.getListeners(ListDataListener.class); } public void fireContentsChanged(Object source, int index0, int index1) { Object[] listeners = listListenerList.getListenerList(); ListDataEvent e = null; for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ListDataListener.class) { if (e == null) { e = new ListDataEvent(source, ListDataEvent.CONTENTS_CHANGED, index0, index1); } ((ListDataListener) listeners[i + 1]).contentsChanged(e); } } } protected void fireIntervalAdded(Object source, int index0, int index1) { Object[] listeners = listListenerList.getListenerList(); ListDataEvent e = null; for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ListDataListener.class) { if (e == null) { e = new ListDataEvent(source, ListDataEvent.INTERVAL_ADDED, index0, index1); } ((ListDataListener) listeners[i + 1]).contentsChanged(e); } } } protected void fireIntervalRemoved(Object source, int index0, int index1) { Object[] listeners = listListenerList.getListenerList(); ListDataEvent e = null; for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ListDataListener.class) { if (e == null) { e = new ListDataEvent(source, ListDataEvent.INTERVAL_REMOVED, index0, index1); } ((ListDataListener) listeners[i + 1]).contentsChanged(e); } } } @Override public <T extends EventListener> T[] getListeners(Class<T> listenerType) { return listListenerList.getListeners(listenerType); } @Override public int getRowCount() { return this.cues.size(); } @Override public int getColumnCount() { return 5; } @Override public Object getValueAt(int i, int i1) { AbstractCue cue = this.cues.get(i); if (i1 == 0) { return cue.getName() + " " + cue.getDescription(); } else if (i1 == 1) { return cue.getType(); } else if (i1 == 2) { if (cue instanceof AudioCue) { AudioCue ac = (AudioCue) cue; return ac.getState(); } } else if (i1 == 3) { return cue.getStartMode(); } else if (i1 == 4) { if (cue instanceof AudioCue) { AudioCue ac = (AudioCue) cue; return ac.getRemainingTime(); } } return null; } //</editor-fold> } diff --git a/src/jcue/ui/event/EditorListener.java b/src/jcue/ui/event/EditorListener.java index 59a12db..f3fe1fd 100644 --- a/src/jcue/ui/event/EditorListener.java +++ b/src/jcue/ui/event/EditorListener.java @@ -1,84 +1,92 @@ package jcue.ui.event; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import jcue.domain.AbstractCue; import jcue.domain.CueList; import jcue.domain.CueType; import jcue.ui.EditorWindow; /** * * @author Jaakko */ public class EditorListener implements ActionListener, ListSelectionListener { private CueList cueList; private JList list; private JPanel panel; private EditorWindow window; public EditorListener(CueList cueList, EditorWindow window, JList list) { this.cueList = cueList; this.window = window; this.list = list; } @Override public void actionPerformed(ActionEvent ae) { String command = ae.getActionCommand(); System.out.println(command); if (command.equals("audio")) { this.cueList.addCue(CueType.AUDIO); this.list.setSelectedIndex(this.cueList.getSize() - 1); } else if (command.equals("event")) { this.cueList.addCue(CueType.EVENT); this.list.setSelectedIndex(this.cueList.getSize() - 1); } else if (command.equals("change")) { this.cueList.addCue(CueType.FADE); this.list.setSelectedIndex(this.cueList.getSize() - 1); } else if (command.equals("note")) { this.cueList.addCue(CueType.NOTE); this.list.setSelectedIndex(this.cueList.getSize() - 1); } else if (command.equals("deleteCue")) { this.cueList.deleteCue(window.getCurrentCue()); + + window.setCurrentCue(null); window.setUI(null); } else if (command.equals("moveUp")) { AbstractCue cue = window.getCurrentCue(); int index = cueList.getCueIndex(cue); - this.cueList.moveCue(cue, index - 1); - window.setSelectedIndex(index - 1); + boolean moveCue = this.cueList.moveCue(cue, index - 1); + + if (moveCue) { + window.setSelectedIndex(index - 1); + } } else if (command.equals("moveDown")) { AbstractCue cue = window.getCurrentCue(); int index = cueList.getCueIndex(cue); - this.cueList.moveCue(cue, index + 1); - window.setSelectedIndex(index + 1); + boolean moveCue = this.cueList.moveCue(cue, index + 1); + + if (moveCue) { + window.setSelectedIndex(index + 1); + } } } @Override public void valueChanged(ListSelectionEvent lse) { if (!lse.getValueIsAdjusting()) { Object selection = list.getSelectedValue(); if (selection instanceof AbstractCue) { AbstractCue cue = (AbstractCue) list.getSelectedValue(); this.window.setUI(cue); this.window.setCurrentCue(cue); } } } }
false
false
null
null
diff --git a/MythicDrops/src/main/java/net/nunnerycode/bukkit/mythicdrops/spawning/ItemSpawningListener.java b/MythicDrops/src/main/java/net/nunnerycode/bukkit/mythicdrops/spawning/ItemSpawningListener.java index 1ab85617..3059331f 100644 --- a/MythicDrops/src/main/java/net/nunnerycode/bukkit/mythicdrops/spawning/ItemSpawningListener.java +++ b/MythicDrops/src/main/java/net/nunnerycode/bukkit/mythicdrops/spawning/ItemSpawningListener.java @@ -1,490 +1,491 @@ package net.nunnerycode.bukkit.mythicdrops.spawning; import com.google.common.base.Joiner; import mkremins.fanciful.FancyMessage; import net.nunnerycode.bukkit.libraries.ivory.utils.JSONUtils; import net.nunnerycode.bukkit.mythicdrops.MythicDropsPlugin; import net.nunnerycode.bukkit.mythicdrops.api.MythicDrops; import net.nunnerycode.bukkit.mythicdrops.api.items.CustomItem; import net.nunnerycode.bukkit.mythicdrops.api.items.ItemGenerationReason; import net.nunnerycode.bukkit.mythicdrops.api.names.NameType; import net.nunnerycode.bukkit.mythicdrops.api.tiers.Tier; import net.nunnerycode.bukkit.mythicdrops.events.EntityDyingEvent; import net.nunnerycode.bukkit.mythicdrops.items.CustomItemMap; import net.nunnerycode.bukkit.mythicdrops.items.MythicDropBuilder; import net.nunnerycode.bukkit.mythicdrops.names.NameMap; import net.nunnerycode.bukkit.mythicdrops.socketting.SocketGem; import net.nunnerycode.bukkit.mythicdrops.socketting.SocketItem; import net.nunnerycode.bukkit.mythicdrops.tiers.TierMap; import net.nunnerycode.bukkit.mythicdrops.utils.CustomItemUtil; import net.nunnerycode.bukkit.mythicdrops.utils.EntityUtil; import net.nunnerycode.bukkit.mythicdrops.utils.ItemStackUtil; import net.nunnerycode.bukkit.mythicdrops.utils.SocketGemUtil; import net.nunnerycode.bukkit.mythicdrops.utils.TierUtil; import org.apache.commons.lang.math.RandomUtils; import org.apache.commons.lang3.text.WordUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Monster; import org.bukkit.entity.Player; import org.bukkit.entity.Skeleton; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public final class ItemSpawningListener implements Listener { private MythicDrops mythicDrops; public ItemSpawningListener(MythicDropsPlugin mythicDrops) { this.mythicDrops = mythicDrops; } public MythicDrops getMythicDrops() { return mythicDrops; } @EventHandler(priority = EventPriority.LOWEST) public void onCreatureSpawnEventLowest(CreatureSpawnEvent event) { - if (event.getEntity() instanceof Player) { + if (!(event.getEntity() instanceof Monster) || event.isCancelled()) { return; } if (mythicDrops.getCreatureSpawningSettings().isBlankMobSpawnEnabled()) { if (event.getEntity() instanceof Skeleton) { event.getEntity().getEquipment().clear(); if (mythicDrops.getCreatureSpawningSettings().isBlankMobSpawnSkeletonsSpawnWithBows()) { event.getEntity().getEquipment().setItemInHand(new ItemStack(Material.BOW, 1)); } } else { event.getEntity().getEquipment().clear(); } } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER && mythicDrops.getCreatureSpawningSettings().isPreventSpawner()) { event.getEntity().setCanPickupItems(mythicDrops.getCreatureSpawningSettings().isCanMobsPickUpEquipment()); return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER_EGG && mythicDrops.getCreatureSpawningSettings().isPreventSpawner()) { event.getEntity().setCanPickupItems(mythicDrops.getCreatureSpawningSettings().isCanMobsPickUpEquipment()); return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM && - mythicDrops.getCreatureSpawningSettings().isPreventSpawner()) { + mythicDrops.getCreatureSpawningSettings().isPreventCustom()) { event.getEntity().setCanPickupItems(mythicDrops.getCreatureSpawningSettings().isCanMobsPickUpEquipment()); return; } if (event.getEntity().getLocation().getY() > mythicDrops.getCreatureSpawningSettings().getSpawnHeightLimit(event.getEntity ().getWorld().getName())) { event.getEntity().setCanPickupItems(mythicDrops.getCreatureSpawningSettings().isCanMobsPickUpEquipment()); return; } event.getEntity().setCanPickupItems(mythicDrops.getCreatureSpawningSettings().isCanMobsPickUpEquipment()); } - @EventHandler(priority = EventPriority.HIGHEST) + @EventHandler(priority = EventPriority.LOW) public void onCreatureSpawnEvent(CreatureSpawnEvent event) { - if (event.getEntity() instanceof Player || event.isCancelled()) { + if (!(event.getEntity() instanceof Monster) || event.isCancelled()) { return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER && mythicDrops.getCreatureSpawningSettings().isPreventSpawner()) { return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER_EGG && mythicDrops.getCreatureSpawningSettings().isPreventSpawner()) { return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM && mythicDrops.getCreatureSpawningSettings().isPreventSpawner()) { return; } if (mythicDrops.getCreatureSpawningSettings().getSpawnHeightLimit(event.getEntity().getWorld().getName()) <= event .getEntity().getLocation().getY()) { return; } if (!mythicDrops.getCreatureSpawningSettings().isGiveMobsEquipment()) { return; } double chance = mythicDrops.getCreatureSpawningSettings().getGlobalSpawnChance() * mythicDrops.getCreatureSpawningSettings() .getEntityTypeChanceToSpawn(event.getEntityType()); if (mythicDrops.getCreatureSpawningSettings().isOnlyCustomItemsSpawn()) { if (mythicDrops.getCreatureSpawningSettings().isCustomItemsSpawn() && RandomUtils.nextDouble() < mythicDrops .getCreatureSpawningSettings().getCustomItemSpawnChance() && !CustomItemMap.getInstance().isEmpty()) { for (int i = 0; i < 5; i++) { if (RandomUtils.nextDouble() < chance) { EntityUtil.equipEntity(event.getEntity(), CustomItemMap.getInstance().getRandomWithChance() .toItemStack()); chance *= 0.5; continue; } break; } } return; } if (mythicDrops.getCreatureSpawningSettings().isGiveMobsNames()) { String generalName = NameMap.getInstance().getRandom(NameType.MOB_NAME, ""); String specificName = NameMap.getInstance().getRandom(NameType.MOB_NAME, "." + event.getEntityType().name ()); event.getEntity().setCustomName(specificName != null ? specificName : generalName); } if (mythicDrops.getCreatureSpawningSettings().getEntityTypeChanceToSpawn(event.getEntityType()) <= 0 && mythicDrops.getCreatureSpawningSettings().getEntityTypeTiers(event.getEntityType()).isEmpty()) { return; } for (int i = 0; i < 5; i++) { if (RandomUtils.nextDouble() < chance) { Tier tier = getTier("*", event.getEntity()); if (tier == null) { continue; } try { ItemStack itemStack = new MythicDropBuilder().inWorld(event.getEntity() .getWorld()).useDurability(true).withTier(tier).withItemGenerationReason (ItemGenerationReason.MONSTER_SPAWN).build(); EntityUtil.equipEntity(event.getEntity(), itemStack); } catch (Exception e) { continue; } chance *= 0.5; continue; } break; } if (mythicDrops.getCreatureSpawningSettings().isCustomItemsSpawn() && RandomUtils.nextDouble() < mythicDrops .getCreatureSpawningSettings().getCustomItemSpawnChance() && !CustomItemMap.getInstance().isEmpty()) { for (int i = 0; i < 5; i++) { if (RandomUtils.nextDouble() < chance) { EntityUtil.equipEntity(event.getEntity(), CustomItemMap.getInstance().getRandomWithChance() .toItemStack()); chance *= 0.5; continue; } break; } } } private Tier getTier(String tierName, LivingEntity livingEntity) { Tier tier; if (tierName.equals("*")) { tier = TierUtil.randomTierWithChance(mythicDrops.getCreatureSpawningSettings().getEntityTypeTiers (livingEntity.getType())); if (tier == null) { tier = TierUtil.randomTierWithChance(mythicDrops.getCreatureSpawningSettings().getEntityTypeTiers (livingEntity.getType())); } } else { tier = TierMap.getInstance().get(tierName.toLowerCase()); if (tier == null) { tier = TierMap.getInstance().get(tierName); } } return tier; } @EventHandler public void onEntityDeath(EntityDeathEvent event) { if (event.getEntity() instanceof Player || event.getEntity().getLastDamageCause() == null || event.getEntity() .getLastDamageCause().isCancelled()) { return; } EntityDamageEvent.DamageCause damageCause = event.getEntity().getLastDamageCause().getCause(); if (damageCause == EntityDamageEvent.DamageCause.CONTACT || damageCause == EntityDamageEvent.DamageCause .SUFFOCATION || damageCause == EntityDamageEvent.DamageCause.FALL || damageCause == EntityDamageEvent .DamageCause.FIRE_TICK || damageCause == EntityDamageEvent.DamageCause.MELTING || damageCause == EntityDamageEvent.DamageCause.LAVA || damageCause == EntityDamageEvent.DamageCause.DROWNING || damageCause == EntityDamageEvent.DamageCause.BLOCK_EXPLOSION || damageCause == EntityDamageEvent .DamageCause.BLOCK_EXPLOSION || damageCause == EntityDamageEvent.DamageCause.VOID || damageCause == EntityDamageEvent.DamageCause.LIGHTNING || damageCause == EntityDamageEvent.DamageCause.SUICIDE || damageCause == EntityDamageEvent.DamageCause.STARVATION || damageCause == EntityDamageEvent .DamageCause.WITHER || damageCause == EntityDamageEvent.DamageCause.FALLING_BLOCK || damageCause == EntityDamageEvent.DamageCause.CUSTOM) { return; } if (mythicDrops.getCreatureSpawningSettings().isGiveMobsEquipment()) { handleEntityDyingWithGive(event); } else { handleEntityDyingWithoutGive(event); } } private void handleEntityDyingWithGive(EntityDeathEvent event) { List<ItemStack> newDrops = new ArrayList<>(); ItemStack[] array = new ItemStack[5]; System.arraycopy(event.getEntity().getEquipment().getArmorContents(), 0, array, 0, 4); array[4] = event.getEntity().getEquipment().getItemInHand(); event.getEntity().getEquipment().setBootsDropChance(0.0F); event.getEntity().getEquipment().setLeggingsDropChance(0.0F); event.getEntity().getEquipment().setChestplateDropChance(0.0F); event.getEntity().getEquipment().setHelmetDropChance(0.0F); event.getEntity().getEquipment().setItemInHandDropChance(0.0F); for (ItemStack is : array) { if (is == null || is.getType() == Material.AIR) { continue; } if (!is.hasItemMeta()) { continue; } CustomItem ci; try { ci = CustomItemUtil.getCustomItemFromItemStack(is); } catch (NullPointerException e) { ci = null; } if (ci != null) { if (RandomUtils.nextDouble() < ci.getChanceToDropOnDeath()) { newDrops.add(ci.toItemStack()); continue; } } Tier tier = TierUtil.getTierFromItemStack(is, mythicDrops.getCreatureSpawningSettings().getEntityTypeTiers(event.getEntityType())); if (tier == null) { continue; } String displayName = WordUtils.capitalizeFully(Joiner.on(" ").join(is.getType().name().split("_"))); List<String> lore = new ArrayList<>(); Map<Enchantment, Integer> enchantments = new LinkedHashMap<>(); if (is.hasItemMeta()) { if (is.getItemMeta().hasDisplayName()) { displayName = is.getItemMeta().getDisplayName(); } if (is.getItemMeta().hasLore()) { lore = is.getItemMeta().getLore(); } if (is.getItemMeta().hasEnchants()) { enchantments = is.getItemMeta().getEnchants(); } } if (tier.isBroadcastOnFind() && event.getEntity().getKiller() != null) { String locale = mythicDrops.getConfigSettings().getFormattedLanguageString("command" + ".found-item-broadcast", new String[][]{{"%receiver%", event.getEntity().getKiller() .getName()}}); String[] messages = locale.split("%item%"); if (Bukkit.getServer().getClass().getPackage().getName().equals("org.bukkit.craftbukkit" + ".v1_7_R1")) { FancyMessage fancyMessage = new FancyMessage(""); for (int i1 = 0; i1 < messages.length; i1++) { String key = messages[i1]; if (i1 < messages.length - 1) { fancyMessage.then(key).then(displayName).itemTooltip(JSONUtils.toJSON(is.getData() .getItemTypeId(), is.getData().getData(), displayName, lore, enchantments)); } else { fancyMessage.then(key); } } for (Player player : event.getEntity().getWorld().getPlayers()) { fancyMessage.send(player); } } else { for (Player player : event.getEntity().getWorld().getPlayers()) { player.sendMessage(locale.replace("%item%", displayName)); } } } if (RandomUtils.nextDouble() < getTierDropChance(tier, event.getEntity().getWorld().getName())) { ItemStack newItemStack = is.getData().toItemStack(is.getAmount()); newItemStack.setItemMeta(is.getItemMeta().clone()); newItemStack.setDurability(ItemStackUtil.getDurabilityForMaterial(is.getType(), tier.getMinimumDurabilityPercentage(), tier.getMaximumDurabilityPercentage())); newDrops.add(newItemStack); } } EntityDyingEvent ede = new EntityDyingEvent(event.getEntity(), array, newDrops); Bukkit.getPluginManager().callEvent(ede); Location location = event.getEntity().getLocation(); for (ItemStack itemstack : ede.getEquipmentDrops()) { if (itemstack.getData().getItemTypeId() == 0) { continue; } location.getWorld().dropItemNaturally(location, itemstack); } } private double getTierDropChance(Tier t, String worldName) { if (t.getWorldDropChanceMap().containsKey(worldName)) { return t.getWorldDropChanceMap().get(worldName); } if (t.getWorldDropChanceMap().containsKey("default")) { return t.getWorldDropChanceMap().get("default"); } return 1.0; } private void handleEntityDyingWithoutGive(EntityDeathEvent event) { List<ItemStack> newDrops = new ArrayList<>(); ItemStack[] array = new ItemStack[5]; System.arraycopy(event.getEntity().getEquipment().getArmorContents(), 0, array, 0, 4); array[4] = event.getEntity().getEquipment().getItemInHand(); double chance = mythicDrops.getCreatureSpawningSettings().getGlobalSpawnChance() * mythicDrops.getCreatureSpawningSettings() .getEntityTypeChanceToSpawn(event.getEntityType()); if (mythicDrops.getCreatureSpawningSettings().isOnlyCustomItemsSpawn()) { if (mythicDrops.getCreatureSpawningSettings().isCustomItemsSpawn() && RandomUtils.nextDouble() < mythicDrops .getCreatureSpawningSettings().getCustomItemSpawnChance() && !CustomItemMap.getInstance().isEmpty()) { for (int i = 0; i < 5; i++) { if (RandomUtils.nextDouble() < chance) { newDrops.add(CustomItemMap.getInstance().getRandomWithChance().toItemStack()); chance *= 0.5; continue; } break; } } return; } if (mythicDrops.getCreatureSpawningSettings().getEntityTypeChanceToSpawn(event.getEntityType()) <= 0 && mythicDrops.getCreatureSpawningSettings().getEntityTypeTiers(event.getEntityType()).isEmpty()) { return; } for (int i = 0; i < 5; i++) { if (RandomUtils.nextDouble() < chance) { Tier tier = getTier("*", event.getEntity()); if (tier == null) { continue; } try { ItemStack itemStack = new MythicDropBuilder().inWorld(event.getEntity().getWorld()).useDurability(true). withTier(tier).withItemGenerationReason(ItemGenerationReason.MONSTER_SPAWN).build(); newDrops.add(itemStack); String displayName = WordUtils.capitalizeFully(Joiner.on(" ").join(itemStack.getType().name().split("_"))); List<String> lore = new ArrayList<>(); Map<Enchantment, Integer> enchantments = new LinkedHashMap<>(); if (itemStack.hasItemMeta()) { if (itemStack.getItemMeta().hasDisplayName()) { displayName = itemStack.getItemMeta().getDisplayName(); } if (itemStack.getItemMeta().hasLore()) { lore = itemStack.getItemMeta().getLore(); } if (itemStack.getItemMeta().hasEnchants()) { enchantments = itemStack.getItemMeta().getEnchants(); } } if (tier.isBroadcastOnFind() && event.getEntity().getKiller() != null) { String locale = mythicDrops.getConfigSettings().getFormattedLanguageString("command" + ".found-item-broadcast", new String[][]{{"%receiver%", event.getEntity().getKiller() .getName()}}); String[] messages = locale.split("%item%"); if (Bukkit.getServer().getClass().getPackage().getName().equals("org.bukkit.craftbukkit" + ".v1_7_R1")) { FancyMessage fancyMessage = new FancyMessage(""); for (int i1 = 0; i1 < messages.length; i1++) { String key = messages[i1]; if (i1 < messages.length - 1) { fancyMessage.then(key).then(displayName).itemTooltip(JSONUtils.toJSON(itemStack.getData() .getItemTypeId(), itemStack.getData().getData(), displayName, lore, enchantments)); } else { fancyMessage.then(key); } } for (Player player : event.getEntity().getWorld().getPlayers()) { fancyMessage.send(player); } } else { for (Player player : event.getEntity().getWorld().getPlayers()) { player.sendMessage(locale.replace("%item%", displayName)); } } } } catch (Exception e) { continue; } chance *= 0.5; continue; } break; } if (mythicDrops.getCreatureSpawningSettings().isCustomItemsSpawn() && RandomUtils.nextDouble() < mythicDrops .getCreatureSpawningSettings().getCustomItemSpawnChance() && !CustomItemMap.getInstance().isEmpty()) { for (int i = 0; i < 5; i++) { if (RandomUtils.nextDouble() < chance) { newDrops.add(CustomItemMap.getInstance().getRandomWithChance().toItemStack()); chance *= 0.5; continue; } break; } } EntityDyingEvent ede = new EntityDyingEvent(event.getEntity(), array, newDrops); Bukkit.getPluginManager().callEvent(ede); Location location = event.getEntity().getLocation(); for (ItemStack itemstack : ede.getEquipmentDrops()) { if (itemstack.getData().getItemTypeId() == 0) { continue; } location.getWorld().dropItemNaturally(location, itemstack); } } @EventHandler public void onEntityDyingEvent(EntityDyingEvent event) { String replaceString = mythicDrops.getSockettingSettings().getSocketGemName().replace('&', '\u00A7').replace("\u00A7\u00A7", "&").replaceAll("%(?s)(.*?)%", "").replaceAll("\\s+", " "); String[] splitString = ChatColor.stripColor(replaceString).split(" "); for (ItemStack is : event.getEquipment()) { if (is.getType() == Material.AIR) { continue; } if (!is.hasItemMeta()) { continue; } ItemMeta im = is.getItemMeta(); if (!im.hasDisplayName()) { continue; } String displayName = im.getDisplayName(); String colorlessName = ChatColor.stripColor(displayName); for (String s : splitString) { if (colorlessName.contains(s)) { colorlessName = colorlessName.replace(s, ""); } } colorlessName = colorlessName.replaceAll("\\s+", " ").trim(); SocketGem socketGem = SocketGemUtil.getSocketGemFromName(colorlessName); if (socketGem == null) { continue; } if (is.isSimilar(new SocketItem(is.getData(), socketGem))) { event.getEquipmentDrops().add(new SocketItem(is.getData(), socketGem)); } } } }
false
false
null
null
diff --git a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Folder.java b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Folder.java index 8784402a8..5d9328e4e 100644 --- a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Folder.java +++ b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Folder.java @@ -1,122 +1,122 @@ package org.eclipse.core.internal.resources; /* * Licensed Materials - Property of IBM, * WebSphere Studio Workbench * (c) Copyright IBM Corp 2000 */ import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.core.internal.utils.Policy; public class Folder extends Container implements IFolder { protected Folder(IPath path, Workspace container) { super(path, container); } /** * Changes this folder to be a file in the resource tree and returns * the newly created file. All related * properties are deleted. It is assumed that on disk the resource is * already a file so no action is taken to delete the disk contents. * <p> * <b>This method is for the exclusive use of the local resource manager</b> * * @see FileSystemResourceManager#reportChanges */ public IFile changeToFile() throws CoreException { getPropertyManager().deleteProperties(this); workspace.deleteResource(this); IFile result = workspace.getRoot().getFile(path); workspace.createResource(result, false); return result; } /** * @see IFolder */ public void create(boolean force, boolean local, IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { monitor.beginTask(Policy.bind("creating", new String[] { getFullPath().toString()}), Policy.totalWork); checkValidPath(path, FOLDER); try { workspace.prepareOperation(); ResourceInfo info = getResourceInfo(false, false); int flags = getFlags(info); checkDoesNotExist(flags, false); workspace.beginOperation(true); refreshLocal(DEPTH_ZERO, null); Container parent = (Container) getParent(); info = parent.getResourceInfo(false, false); flags = getFlags(info); parent.checkAccessible(flags); info = getResourceInfo(false, false); flags = getFlags(info); if (force) { if (exists(flags, false)) return; } else { checkDoesNotExist(flags, false); } - internalCreate(force, local, Policy.subMonitorFor(monitor, Policy.totalWork)); + internalCreate(force, local, Policy.subMonitorFor(monitor, Policy.opWork)); } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; } finally { workspace.endOperation(true, Policy.subMonitorFor(monitor, Policy.buildWork)); } } finally { monitor.done(); } } /** * Ensures that this folder exists in the workspace. This is similar in * concept to mkdirs but it does not work on projects. * If this folder is created, it will be marked as being local. */ public void ensureExists(IProgressMonitor monitor) throws CoreException { ResourceInfo info = getResourceInfo(false, false); int flags = getFlags(info); if (exists(flags, true)) return; if (exists(flags, false)) { String message = Policy.bind("folderOverFile", new String[] { getFullPath().toString()}); throw new ResourceException(IResourceStatus.RESOURCE_WRONG_TYPE, getFullPath(), message, null); } Container parent = (Container) getParent(); if (parent.getType() == PROJECT) { info = parent.getResourceInfo(false, false); parent.checkExists(getFlags(info), true); } else ((Folder) parent).ensureExists(monitor); internalCreate(true, true, monitor); } /** * @see IResource#getType */ public int getType() { return FOLDER; } public void internalCreate(boolean force, boolean local, IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { monitor.beginTask("Creating file.", Policy.totalWork); workspace.createResource(this, false); if (local) { try { getLocalManager().write(this, force, Policy.subMonitorFor(monitor, Policy.totalWork * 75 / 100)); } catch (CoreException e) { // a problem happened creating the folder on disk, so delete from the workspace workspace.deleteResource(this); throw e; // rethrow } } setLocal(local, DEPTH_ZERO, Policy.subMonitorFor(monitor, Policy.totalWork * 25 / 100)); if (!local) getResourceInfo(true, true).setModificationStamp(IResource.NULL_STAMP); } finally { monitor.done(); } } }
true
true
public void create(boolean force, boolean local, IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { monitor.beginTask(Policy.bind("creating", new String[] { getFullPath().toString()}), Policy.totalWork); checkValidPath(path, FOLDER); try { workspace.prepareOperation(); ResourceInfo info = getResourceInfo(false, false); int flags = getFlags(info); checkDoesNotExist(flags, false); workspace.beginOperation(true); refreshLocal(DEPTH_ZERO, null); Container parent = (Container) getParent(); info = parent.getResourceInfo(false, false); flags = getFlags(info); parent.checkAccessible(flags); info = getResourceInfo(false, false); flags = getFlags(info); if (force) { if (exists(flags, false)) return; } else { checkDoesNotExist(flags, false); } internalCreate(force, local, Policy.subMonitorFor(monitor, Policy.totalWork)); } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; } finally { workspace.endOperation(true, Policy.subMonitorFor(monitor, Policy.buildWork)); } } finally { monitor.done(); } }
public void create(boolean force, boolean local, IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { monitor.beginTask(Policy.bind("creating", new String[] { getFullPath().toString()}), Policy.totalWork); checkValidPath(path, FOLDER); try { workspace.prepareOperation(); ResourceInfo info = getResourceInfo(false, false); int flags = getFlags(info); checkDoesNotExist(flags, false); workspace.beginOperation(true); refreshLocal(DEPTH_ZERO, null); Container parent = (Container) getParent(); info = parent.getResourceInfo(false, false); flags = getFlags(info); parent.checkAccessible(flags); info = getResourceInfo(false, false); flags = getFlags(info); if (force) { if (exists(flags, false)) return; } else { checkDoesNotExist(flags, false); } internalCreate(force, local, Policy.subMonitorFor(monitor, Policy.opWork)); } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; } finally { workspace.endOperation(true, Policy.subMonitorFor(monitor, Policy.buildWork)); } } finally { monitor.done(); } }
diff --git a/org.spearce.jgit/src/org/spearce/jgit/lib/RefDatabase.java b/org.spearce.jgit/src/org/spearce/jgit/lib/RefDatabase.java index ba4b654c..72777af3 100644 --- a/org.spearce.jgit/src/org/spearce/jgit/lib/RefDatabase.java +++ b/org.spearce.jgit/src/org/spearce/jgit/lib/RefDatabase.java @@ -1,513 +1,516 @@ /* * Copyright (C) 2007, Robin Rosenberg <robin.rosenberg@dewire.com> * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org> * * 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 Git Development Community 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 COPYRIGHT HOLDERS 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 COPYRIGHT OWNER OR * 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 org.spearce.jgit.lib; import static org.spearce.jgit.lib.Constants.R_TAGS; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import org.spearce.jgit.errors.ObjectWritingException; import org.spearce.jgit.lib.Ref.Storage; import org.spearce.jgit.util.FS; import org.spearce.jgit.util.NB; import org.spearce.jgit.util.RawParseUtils; class RefDatabase { private static final String REFS_SLASH = "refs/"; private static final String[] refSearchPaths = { "", REFS_SLASH, R_TAGS, Constants.R_HEADS, Constants.R_REMOTES }; private final Repository db; private final File gitDir; private final File refsDir; private Map<String, Ref> looseRefs; private Map<String, Long> looseRefsMTime; private Map<String, String> looseSymRefs; private final File packedRefsFile; private Map<String, Ref> packedRefs; private long packedRefsLastModified; private long packedRefsLength; int lastRefModification; int lastNotifiedRefModification; private int refModificationCounter; RefDatabase(final Repository r) { db = r; gitDir = db.getDirectory(); refsDir = FS.resolve(gitDir, "refs"); packedRefsFile = FS.resolve(gitDir, Constants.PACKED_REFS); clearCache(); } synchronized void clearCache() { looseRefs = new HashMap<String, Ref>(); looseRefsMTime = new HashMap<String, Long>(); packedRefs = new HashMap<String, Ref>(); looseSymRefs = new HashMap<String, String>(); packedRefsLastModified = 0; packedRefsLength = 0; } Repository getRepository() { return db; } void create() { refsDir.mkdir(); new File(refsDir, "heads").mkdir(); new File(refsDir, "tags").mkdir(); } ObjectId idOf(final String name) throws IOException { refreshPackedRefs(); final Ref r = readRefBasic(name, 0); return r != null ? r.getObjectId() : null; } /** * Create a command to update, create or delete a ref in this repository. * * @param name * name of the ref the caller wants to modify. * @return an update command. The caller must finish populating this command * and then invoke one of the update methods to actually make a * change. * @throws IOException * a symbolic ref was passed in and could not be resolved back * to the base ref, as the symbolic ref could not be read. */ RefUpdate newUpdate(final String name) throws IOException { refreshPackedRefs(); Ref r = readRefBasic(name, 0); if (r == null) r = new Ref(Ref.Storage.NEW, name, null); return new RefUpdate(this, r, fileForRef(r.getName())); } void stored(final String origName, final String name, final ObjectId id, final long time) { synchronized (this) { looseRefs.put(name, new Ref(Ref.Storage.LOOSE, name, name, id)); looseRefsMTime.put(name, time); setModified(); } db.fireRefsMaybeChanged(); } /** * An set of update operations for renaming a ref * * @param fromRef Old ref name * @param toRef New ref name * @return a RefUpdate operation to rename a ref * @throws IOException */ RefRename newRename(String fromRef, String toRef) throws IOException { refreshPackedRefs(); Ref f = readRefBasic(fromRef, 0); Ref t = new Ref(Ref.Storage.NEW, toRef, null); RefUpdate refUpdateFrom = new RefUpdate(this, f, fileForRef(f.getName())); RefUpdate refUpdateTo = new RefUpdate(this, t, fileForRef(t.getName())); return new RefRename(refUpdateTo, refUpdateFrom); } /** * Writes a symref (e.g. HEAD) to disk * * @param name * symref name * @param target * pointed to ref * @throws IOException */ void link(final String name, final String target) throws IOException { final byte[] content = Constants.encode("ref: " + target + "\n"); lockAndWriteFile(fileForRef(name), content); synchronized (this) { looseSymRefs.remove(name); setModified(); } db.fireRefsMaybeChanged(); } void uncacheSymRef(String name) { synchronized(this) { looseSymRefs.remove(name); setModified(); } } void uncacheRef(String name) { looseRefs.remove(name); looseRefsMTime.remove(name); packedRefs.remove(name); } private void setModified() { lastRefModification = refModificationCounter++; } Ref readRef(final String partialName) throws IOException { refreshPackedRefs(); for (int k = 0; k < refSearchPaths.length; k++) { final Ref r = readRefBasic(refSearchPaths[k] + partialName, 0); if (r != null && r.getObjectId() != null) return r; } return null; } /** * @return all known refs (heads, tags, remotes). */ Map<String, Ref> getAllRefs() { return readRefs(); } /** * @return all tags; key is short tag name ("v1.0") and value of the entry * contains the ref with the full tag name ("refs/tags/v1.0"). */ Map<String, Ref> getTags() { final Map<String, Ref> tags = new HashMap<String, Ref>(); for (final Ref r : readRefs().values()) { if (r.getName().startsWith(R_TAGS)) tags.put(r.getName().substring(R_TAGS.length()), r); } return tags; } private Map<String, Ref> readRefs() { final HashMap<String, Ref> avail = new HashMap<String, Ref>(); readPackedRefs(avail); readLooseRefs(avail, REFS_SLASH, refsDir); try { final Ref r = readRefBasic(Constants.HEAD, 0); if (r != null && r.getObjectId() != null) avail.put(Constants.HEAD, r); } catch (IOException e) { // ignore here } db.fireRefsMaybeChanged(); return avail; } private synchronized void readPackedRefs(final Map<String, Ref> avail) { refreshPackedRefs(); avail.putAll(packedRefs); } private void readLooseRefs(final Map<String, Ref> avail, final String prefix, final File dir) { final File[] entries = dir.listFiles(); if (entries == null) return; for (final File ent : entries) { final String entName = ent.getName(); if (".".equals(entName) || "..".equals(entName)) continue; if (ent.isDirectory()) { readLooseRefs(avail, prefix + entName + "/", ent); } else { try { final Ref ref = readRefBasic(prefix + entName, 0); if (ref != null) avail.put(ref.getOrigName(), ref); } catch (IOException e) { continue; } } } } Ref peel(final Ref ref) { if (ref.isPeeled()) return ref; ObjectId peeled = null; try { Object target = db.mapObject(ref.getObjectId(), ref.getName()); while (target instanceof Tag) { final Tag tag = (Tag)target; peeled = tag.getObjId(); if (Constants.TYPE_TAG.equals(tag.getType())) target = db.mapObject(tag.getObjId(), ref.getName()); else break; } } catch (IOException e) { // Ignore a read error.  Callers will also get the same error // if they try to use the result of getPeeledObjectId. } return new Ref(ref.getStorage(), ref.getName(), ref.getObjectId(), peeled, true); } private File fileForRef(final String name) { if (name.startsWith(REFS_SLASH)) return new File(refsDir, name.substring(REFS_SLASH.length())); return new File(gitDir, name); } private Ref readRefBasic(final String name, final int depth) throws IOException { return readRefBasic(name, name, depth); } private synchronized Ref readRefBasic(final String origName, final String name, final int depth) throws IOException { // Prefer loose ref to packed ref as the loose // file can be more up-to-date than a packed one. // Ref ref = looseRefs.get(origName); final File loose = fileForRef(name); final long mtime = loose.lastModified(); if (ref != null) { Long cachedlastModified = looseRefsMTime.get(name); if (cachedlastModified != null && cachedlastModified == mtime) { if (packedRefs.containsKey(origName)) return new Ref(Storage.LOOSE_PACKED, origName, ref .getObjectId(), ref.getPeeledObjectId(), ref .isPeeled()); else return ref; } looseRefs.remove(origName); looseRefsMTime.remove(origName); } if (mtime == 0) { // If last modified is 0 the file does not exist. // Try packed cache. // ref = packedRefs.get(name); if (ref != null) if (!ref.getOrigName().equals(origName)) ref = new Ref(Storage.LOOSE_PACKED, origName, name, ref.getObjectId()); return ref; } String line = null; try { Long cachedlastModified = looseRefsMTime.get(name); if (cachedlastModified != null && cachedlastModified == mtime) { line = looseSymRefs.get(name); } if (line == null) { line = readLine(loose); looseRefsMTime.put(name, mtime); looseSymRefs.put(name, line); } } catch (FileNotFoundException notLoose) { return packedRefs.get(name); } if (line == null || line.length() == 0) { looseRefs.remove(origName); looseRefsMTime.remove(origName); return new Ref(Ref.Storage.LOOSE, origName, name, null); } if (line.startsWith("ref: ")) { if (depth >= 5) { throw new IOException("Exceeded maximum ref depth of " + depth + " at " + name + ". Circular reference?"); } final String target = line.substring("ref: ".length()); Ref r = readRefBasic(target, target, depth + 1); Long cachedMtime = looseRefsMTime.get(name); if (cachedMtime != null && cachedMtime != mtime) setModified(); looseRefsMTime.put(name, mtime); if (r == null) return new Ref(Ref.Storage.LOOSE, origName, target, null); if (!origName.equals(r.getName())) r = new Ref(Ref.Storage.LOOSE_PACKED, origName, r.getName(), r.getObjectId(), r.getPeeledObjectId(), true); return r; } setModified(); final ObjectId id; try { id = ObjectId.fromString(line); } catch (IllegalArgumentException notRef) { throw new IOException("Not a ref: " + name + ": " + line); } Storage storage; if (packedRefs.containsKey(name)) storage = Ref.Storage.LOOSE_PACKED; else storage = Ref.Storage.LOOSE; ref = new Ref(storage, name, id); looseRefs.put(name, ref); looseRefsMTime.put(name, mtime); if (!origName.equals(name)) { ref = new Ref(Ref.Storage.LOOSE, origName, name, id); looseRefs.put(origName, ref); } return ref; } private synchronized void refreshPackedRefs() { final long currTime = packedRefsFile.lastModified(); final long currLen = currTime == 0 ? 0 : packedRefsFile.length(); if (currTime == packedRefsLastModified && currLen == packedRefsLength) return; if (currTime == 0) { packedRefsLastModified = 0; packedRefsLength = 0; packedRefs = new HashMap<String, Ref>(); return; } final Map<String, Ref> newPackedRefs = new HashMap<String, Ref>(); try { final BufferedReader b = openReader(packedRefsFile); try { String p; Ref last = null; while ((p = b.readLine()) != null) { if (p.charAt(0) == '#') continue; if (p.charAt(0) == '^') { if (last == null) throw new IOException("Peeled line before ref."); final ObjectId id = ObjectId.fromString(p.substring(1)); last = new Ref(Ref.Storage.PACKED, last.getName(), last .getName(), last.getObjectId(), id, true); newPackedRefs.put(last.getName(), last); continue; } final int sp = p.indexOf(' '); final ObjectId id = ObjectId.fromString(p.substring(0, sp)); final String name = copy(p, sp + 1, p.length()); last = new Ref(Ref.Storage.PACKED, name, name, id); newPackedRefs.put(last.getName(), last); } } finally { b.close(); } packedRefsLastModified = currTime; packedRefsLength = currLen; packedRefs = newPackedRefs; setModified(); } catch (FileNotFoundException noPackedRefs) { // Ignore it and leave the new map empty. // packedRefsLastModified = 0; packedRefsLength = 0; packedRefs = newPackedRefs; } catch (IOException e) { throw new RuntimeException("Cannot read packed refs", e); } } private static String copy(final String src, final int off, final int end) { return new StringBuilder(end - off).append(src, off, end).toString(); } private void lockAndWriteFile(File file, byte[] content) throws IOException { String name = file.getName(); final LockFile lck = new LockFile(file); if (!lck.lock()) throw new ObjectWritingException("Unable to lock " + name); try { lck.write(content); } catch (IOException ioe) { throw new ObjectWritingException("Unable to write " + name, ioe); } if (!lck.commit()) throw new ObjectWritingException("Unable to write " + name); } synchronized void removePackedRef(String name) throws IOException { packedRefs.remove(name); writePackedRefs(); } private void writePackedRefs() throws IOException { new RefWriter(packedRefs.values()) { @Override protected void writeFile(String name, byte[] content) throws IOException { lockAndWriteFile(new File(db.getDirectory(), name), content); } }.writePackedRefs(); } private static String readLine(final File file) throws FileNotFoundException, IOException { final byte[] buf = NB.readFully(file, 4096); int n = buf.length; if (n == 0) return null; - if (buf[n - 1] == '\n') + + // remove trailing whitespaces + while (n > 0 && Character.isWhitespace(buf[n - 1])) n--; + return RawParseUtils.decode(buf, 0, n); } private static BufferedReader openReader(final File fileLocation) throws FileNotFoundException { return new BufferedReader(new InputStreamReader(new FileInputStream( fileLocation), Constants.CHARSET)); } }
false
false
null
null
diff --git a/src/com/ankitguglani/samples/SamplesListActivity.java b/src/com/ankitguglani/samples/SamplesListActivity.java index 82bd58d..4dd301e 100644 --- a/src/com/ankitguglani/samples/SamplesListActivity.java +++ b/src/com/ankitguglani/samples/SamplesListActivity.java @@ -1,125 +1,108 @@ package com.ankitguglani.samples; import java.util.ArrayList; import java.util.List; import android.app.ListActivity; -import android.content.ComponentName; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; public class SamplesListActivity extends ListActivity { private static final String TAG = "com.ankitguglani.samples.SamplesListActivity"; private static final Class<SamplesListActivity> SELF = com.ankitguglani.samples.SamplesListActivity.class; int samplesCount = 0; List<AppListItem> AppList = new ArrayList<AppListItem>(); // String display[] = {"Splash Screen","Notes App","Photo App"}; // String classes[] = {"com.ankitguglani.samples.SplashActivity", // "com.ankitguglani.samples.notes.NotesListActivity", // "com.ankitguglani.samples.camera.PictureActivity"}; AppListItem splash = new AppListItem(++samplesCount,"Splash Screen","com.ankitguglani.samples.SplashActivity", 0, true); AppListItem notes = new AppListItem(++samplesCount,"Notes App","com.ankitguglani.samples.notes.NotesListActivity", R.drawable.notes, true); AppListItem photos = new AppListItem(++samplesCount,"Photo App","com.ankitguglani.samples.camera.PictureActivity", R.drawable.camera, true); AppListItem notification = new AppListItem(++samplesCount, "Notification.", "com.ankitguglani.samples.notification.NotificationBarActivity", 0, true); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setListAdapter(new ArrayAdapter<String>(SamplesListActivity.this, android.R.layout.simple_list_item_1, display)); setContentView(R.layout.application_list); AppList.add(splash); AppList.add(notes); AppList.add(photos); AppList.add(notification); // Check for additionally installed applications. - -// final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); -// mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); -// final List<ResolveInfo> pkgAppsList = this.getPackageManager().queryIntentActivities( mainIntent, 0); -// Log.d(tag,pkgAppsList.toString()); - final PackageManager pm = getPackageManager(); - //get a list of installed apps. List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA); for (ApplicationInfo packageInfo : packages) { -// Log.d(TAG, "Installed package :" + packageInfo.packageName); -// Log.d(TAG, "Launch Activity :" + pm.getLaunchIntentForPackage(packageInfo.packageName)); if(packageInfo.packageName.contains("com.codewithchris")) { AppList.add(new AppListItem(++samplesCount, "Code with Chris", "com.ankitguglani.samples.codewithchris", 0, false)); } } setListAdapter(new ApplicationListAdapter()); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); try { -// Class sampleAppClass = Class.forName(classes[position]); - if(AppList.get(position).isInternal()) { Class sampleAppClass = Class.forName(AppList.get(position).getClassName().toString()); Intent sampleAppIntent = new Intent(SamplesListActivity.this, sampleAppClass); startActivity(sampleAppIntent); } else { -// Intent externalSampleIntent = new Intent("com.codewithchris"); -// externalSampleIntent.setComponent(new ComponentName("com.codewithchris","com.codewithchris.SplashActivity")); -// startActivity(externalSampleIntent); Intent externalSampleIntent = new Intent(); externalSampleIntent.setAction(AppList.get(position).getClassName().toString()); startActivity(externalSampleIntent); } } catch (ClassNotFoundException e) { Log.e(TAG, "Class not found exception: " + e); } } public class ApplicationListAdapter extends ArrayAdapter<AppListItem> { ApplicationListAdapter() { super(SamplesListActivity.this, R.layout.application_list_row, R.id.appTitle, AppList); } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = getLayoutInflater(); View row = inflater.inflate(R.layout.application_list_row, parent, false); TextView label = (TextView)row.findViewById(R.id.appTitle); label.setText(AppList.get(position).getDisplayName()); ImageView icon = (ImageView)row.findViewById(R.id.appIconImageView); icon.setImageResource(AppList.get(position).getImageResourceId()); return row; } } - - }
false
false
null
null
diff --git a/org.maven.ide.eclipse.tests/src/org/maven/ide/eclipse/tests/BuildPathManagerTest.java b/org.maven.ide.eclipse.tests/src/org/maven/ide/eclipse/tests/BuildPathManagerTest.java index d1d04bab..74e0a026 100644 --- a/org.maven.ide.eclipse.tests/src/org/maven/ide/eclipse/tests/BuildPathManagerTest.java +++ b/org.maven.ide.eclipse.tests/src/org/maven/ide/eclipse/tests/BuildPathManagerTest.java @@ -1,995 +1,995 @@ /******************************************************************************* * Copyright (c) 2008 Sonatype, Inc. * 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 *******************************************************************************/ package org.maven.ide.eclipse.tests; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Properties; import org.apache.maven.archetype.catalog.Archetype; import org.apache.maven.model.Dependency; import org.apache.maven.model.Model; import org.eclipse.core.resources.ICommand; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.core.IAccessRule; import org.eclipse.jdt.core.IClasspathAttribute; import org.eclipse.jdt.core.IClasspathContainer; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.launching.JavaRuntime; import org.maven.ide.eclipse.MavenPlugin; import org.maven.ide.eclipse.core.IMavenConstants; import org.maven.ide.eclipse.index.IndexInfo; import org.maven.ide.eclipse.index.IndexManager; import org.maven.ide.eclipse.jdt.BuildPathManager; import org.maven.ide.eclipse.jdt.MavenJdtPlugin; import org.maven.ide.eclipse.project.IProjectConfigurationManager; import org.maven.ide.eclipse.project.MavenUpdateRequest; import org.maven.ide.eclipse.project.ProjectImportConfiguration; import org.maven.ide.eclipse.project.ResolverConfiguration; /** * @author Eugene Kuleshov */ public class BuildPathManagerTest extends AsbtractMavenProjectTestCase { public void testEnableMavenNature() throws Exception { deleteProject("MNGECLIPSE-248parent"); deleteProject("MNGECLIPSE-248child"); final IProject project1 = createProject("MNGECLIPSE-248parent", "projects/MNGECLIPSE-248parent/pom.xml"); final IProject project2 = createProject("MNGECLIPSE-248child", "projects/MNGECLIPSE-248child/pom.xml"); NullProgressMonitor monitor = new NullProgressMonitor(); IProjectConfigurationManager configurationManager = MavenPlugin.getDefault().getProjectConfigurationManager(); ResolverConfiguration configuration = new ResolverConfiguration(); configurationManager.enableMavenNature(project1, configuration, monitor); // buildpathManager.updateSourceFolders(project1, monitor); configurationManager.enableMavenNature(project2, configuration, monitor); // buildpathManager.updateSourceFolders(project2, monitor); // waitForJob("Initializing " + project1.getProject().getName()); // waitForJob("Initializing " + project2.getProject().getName()); try { project1.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor()); project2.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor()); } catch(Exception ex) { throw ex; } waitForJobsToComplete(); IMarker[] markers1 = project1.findMarkers(null, true, IResource.DEPTH_INFINITE); assertTrue("Unexpected markers " + Arrays.asList(markers1), markers1.length == 0); IClasspathEntry[] project1entries = getMavenContainerEntries(project1); assertEquals(1, project1entries.length); assertEquals(IClasspathEntry.CPE_LIBRARY, project1entries[0].getEntryKind()); assertEquals("junit-4.1.jar", project1entries[0].getPath().lastSegment()); IClasspathEntry[] project2entries = getMavenContainerEntries(project2); assertEquals(2, project2entries.length); assertEquals(IClasspathEntry.CPE_PROJECT, project2entries[0].getEntryKind()); assertEquals("MNGECLIPSE-248parent", project2entries[0].getPath().segment(0)); assertEquals(IClasspathEntry.CPE_LIBRARY, project2entries[1].getEntryKind()); assertEquals("junit-4.1.jar", project2entries[1].getPath().lastSegment()); configurationManager.updateProjectConfiguration(project2, configuration, "", monitor); waitForJobsToComplete(); assertMarkers(project2, 0); } public void testDisableMavenNature() throws Exception { deleteProject("disablemaven-p001"); IProject p = createExisting("disablemaven-p001", "projects/disablemaven/p001"); waitForJobsToComplete(); assertTrue(p.hasNature(IMavenConstants.NATURE_ID)); assertTrue(p.hasNature(JavaCore.NATURE_ID)); assertNotNull(BuildPathManager.getMaven2ClasspathContainer(JavaCore.create(p))); IProjectConfigurationManager configurationManager = MavenPlugin.getDefault().getProjectConfigurationManager(); configurationManager.disableMavenNature(p, monitor); waitForJobsToComplete(); assertFalse(p.hasNature(IMavenConstants.NATURE_ID)); assertFalse(hasBuilder(p, IMavenConstants.BUILDER_ID)); assertTrue(p.hasNature(JavaCore.NATURE_ID)); assertNull(BuildPathManager.getMaven2ClasspathContainer(JavaCore.create(p))); } private boolean hasBuilder(IProject p, String builderId) throws CoreException { for (ICommand command : p.getDescription().getBuildSpec()) { if (builderId.equals(command.getBuilderName())) { return true; } } return false; } public void testEnableMavenNatureWithNoWorkspace() throws Exception { deleteProject("MNGECLIPSE-248parent"); deleteProject("MNGECLIPSE-248child"); final IProject project1 = createProject("MNGECLIPSE-248parent", "projects/MNGECLIPSE-248parent/pom.xml"); final IProject project2 = createProject("MNGECLIPSE-248child", "projects/MNGECLIPSE-248child/pom.xml"); NullProgressMonitor monitor = new NullProgressMonitor(); IProjectConfigurationManager importManager = MavenPlugin.getDefault().getProjectConfigurationManager(); ResolverConfiguration configuration = new ResolverConfiguration(); configuration.setIncludeModules(false); configuration.setResolveWorkspaceProjects(false); configuration.setActiveProfiles(""); importManager.enableMavenNature(project1, configuration, monitor); importManager.enableMavenNature(project2, configuration, monitor); // buildpathManager.updateSourceFolders(project1, monitor); // buildpathManager.updateSourceFolders(project2, monitor); // waitForJob("Initializing " + project1.getProject().getName()); // waitForJob("Initializing " + project2.getProject().getName()); waitForJobsToComplete(); IClasspathEntry[] project1entries = getMavenContainerEntries(project1); assertEquals(Arrays.asList(project1entries).toString(), 1, project1entries.length); assertEquals(IClasspathEntry.CPE_LIBRARY, project1entries[0].getEntryKind()); assertEquals("junit-4.1.jar", project1entries[0].getPath().lastSegment()); IClasspathEntry[] project2entries = getMavenContainerEntries(project2); assertEquals(Arrays.asList(project2entries).toString(), 1, project2entries.length); assertEquals(IClasspathEntry.CPE_LIBRARY, project2entries[0].getEntryKind()); assertEquals("MNGECLIPSE-248parent-1.0.0.jar", project2entries[0].getPath().lastSegment()); } public void testProjectImportWithProfile1() throws Exception { deleteProject("MNGECLIPSE-353"); ResolverConfiguration configuration = new ResolverConfiguration(); configuration.setIncludeModules(false); configuration.setResolveWorkspaceProjects(true); configuration.setActiveProfiles("jaxb1"); IProject project = importProject("projects/MNGECLIPSE-353/pom.xml", configuration); waitForJobsToComplete(); IJavaProject javaProject = JavaCore.create(project); IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject) .getClasspathEntries(); assertEquals("" + Arrays.asList(classpathEntries), 2, classpathEntries.length); assertEquals("junit-3.8.1.jar", classpathEntries[0].getPath().lastSegment()); assertEquals("jaxb-api-1.5.jar", classpathEntries[1].getPath().lastSegment()); assertMarkers(project, 0); } public void testProjectImportWithProfile2() throws Exception { deleteProject("MNGECLIPSE-353"); ResolverConfiguration configuration = new ResolverConfiguration(); configuration.setIncludeModules(false); configuration.setResolveWorkspaceProjects(true); configuration.setActiveProfiles("jaxb20"); IProject project = importProject("projects/MNGECLIPSE-353/pom.xml", configuration); waitForJobsToComplete(); IJavaProject javaProject = JavaCore.create(project); IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject) .getClasspathEntries(); assertEquals("" + Arrays.asList(classpathEntries), 4, classpathEntries.length); assertEquals("junit-3.8.1.jar", classpathEntries[0].getPath().lastSegment()); assertEquals("jaxb-api-2.0.jar", classpathEntries[1].getPath().lastSegment()); assertEquals("jsr173_api-1.0.jar", classpathEntries[2].getPath().lastSegment()); assertEquals("activation-1.1.jar", classpathEntries[3].getPath().lastSegment()); assertMarkers(project, 0); } public void testProjectImport001_useMavenOutputFolders() throws Exception { deleteProject("projectimport-p001"); ResolverConfiguration configuration = new ResolverConfiguration(); IProject project = importProject("projectimport-p001", "projects/projectimport/p001", configuration); waitForJobsToComplete(); IJavaProject javaProject = JavaCore.create(project); assertEquals(new Path("/projectimport-p001/target/classes"), javaProject.getOutputLocation()); IClasspathEntry[] cp = javaProject.getRawClasspath(); assertEquals(4, cp.length); assertEquals(new Path("/projectimport-p001/src/main/java"), cp[0].getPath()); assertEquals(new Path("/projectimport-p001/target/classes"), cp[0].getOutputLocation()); assertEquals(new Path("/projectimport-p001/src/test/java"), cp[1].getPath()); assertEquals(new Path("/projectimport-p001/target/test-classes"), cp[1].getOutputLocation()); } public void testProjectImport002_useMavenOutputFolders() throws Exception { deleteProject("projectimport-p002"); ResolverConfiguration configuration = new ResolverConfiguration(); configuration.setIncludeModules(true); IProject project = importProject("projectimport-p002", "projects/projectimport/p002", configuration); waitForJobsToComplete(); IJavaProject javaProject = JavaCore.create(project); assertEquals(new Path("/projectimport-p002/target/classes"), javaProject.getOutputLocation()); IClasspathEntry[] cp = javaProject.getRawClasspath(); assertEquals(3, cp.length); assertEquals(new Path("/projectimport-p002/p002-m1/src/main/java"), cp[0].getPath()); assertEquals(new Path("/projectimport-p002/p002-m1/target/classes"), cp[0].getOutputLocation()); } public void testEmbedderException() throws Exception { deleteProject("MNGECLIPSE-157parent"); IProject project = importProject("projects/MNGECLIPSE-157parent/pom.xml", new ResolverConfiguration()); importProject("projects/MNGECLIPSE-157child/pom.xml", new ResolverConfiguration()); waitForJobsToComplete(); project.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor()); IMarker[] markers = project.findMarkers(null, true, IResource.DEPTH_INFINITE); assertEquals(toString(markers), 1, markers.length); assertEquals(toString(markers), "pom.xml", markers[0].getResource().getFullPath().lastSegment()); } public void testClasspathOrderWorkspace001() throws Exception { deleteProject("p1"); deleteProject("p2"); ResolverConfiguration configuration = new ResolverConfiguration(); configuration.setIncludeModules(false); configuration.setResolveWorkspaceProjects(true); configuration.setActiveProfiles(""); IProject project1 = importProject("projects/dependencyorder/p1/pom.xml", configuration); IProject project2 = importProject("projects/dependencyorder/p2/pom.xml", configuration); project1.build(IncrementalProjectBuilder.FULL_BUILD, null); project2.build(IncrementalProjectBuilder.FULL_BUILD, null); waitForJobsToComplete(); // MavenPlugin.getDefault().getBuildpathManager().updateClasspathContainer(p1, new NullProgressMonitor()); IJavaProject javaProject = JavaCore.create(project1); IClasspathContainer maven2ClasspathContainer = BuildPathManager.getMaven2ClasspathContainer(javaProject); IClasspathEntry[] cp = maven2ClasspathContainer.getClasspathEntries(); // order according to mvn -X assertEquals(3, cp.length); assertEquals(new Path("/p2"), cp[0].getPath()); assertEquals("junit-4.0.jar", cp[1].getPath().lastSegment()); assertEquals("easymock-1.0.jar", cp[2].getPath().lastSegment()); } public void testClasspathOrderWorkspace003() throws Exception { deleteProject("p3"); ResolverConfiguration configuration = new ResolverConfiguration(); configuration.setIncludeModules(false); configuration.setResolveWorkspaceProjects(true); configuration.setActiveProfiles(""); IProject p3 = importProject("projects/dependencyorder/p3/pom.xml", configuration); p3.build(IncrementalProjectBuilder.FULL_BUILD, null); waitForJobsToComplete(); IJavaProject javaProject = JavaCore.create(p3); IClasspathContainer maven2ClasspathContainer = BuildPathManager.getMaven2ClasspathContainer(javaProject); IClasspathEntry[] cp = maven2ClasspathContainer.getClasspathEntries(); // order according to mvn -X. note that maven 2.0.7 and 2.1-SNAPSHOT produce different order assertEquals(6, cp.length); assertEquals("junit-3.8.1.jar", cp[0].getPath().lastSegment()); assertEquals("commons-digester-1.6.jar", cp[1].getPath().lastSegment()); assertEquals("commons-beanutils-1.6.jar", cp[2].getPath().lastSegment()); assertEquals("commons-logging-1.0.jar", cp[3].getPath().lastSegment()); assertEquals("commons-collections-2.1.jar", cp[4].getPath().lastSegment()); assertEquals("xml-apis-1.0.b2.jar", cp[5].getPath().lastSegment()); } public void testDownloadSources_001_basic() throws Exception { new File(repo, "downloadsources/downloadsources-t001/0.0.1/downloadsources-t001-0.0.1-sources.jar").delete(); new File(repo, "downloadsources/downloadsources-t002/0.0.1/downloadsources-t002-0.0.1-sources.jar").delete(); IProject project = createExisting("downloadsources-p001", "projects/downloadsources/p001"); waitForJobsToComplete(); IJavaProject javaProject = JavaCore.create(project); IClasspathContainer container = BuildPathManager.getMaven2ClasspathContainer(javaProject); // sanity check IClasspathEntry[] cp = container.getClasspathEntries(); assertEquals(2, cp.length); assertNull(cp[0].getSourceAttachmentPath()); assertNull(cp[1].getSourceAttachmentPath()); // test project getBuildPathManager().downloadSources(project, null); waitForJobsToComplete(); container = BuildPathManager.getMaven2ClasspathContainer(javaProject); cp = container.getClasspathEntries(); assertEquals(2, cp.length); assertEquals("downloadsources-t001-0.0.1-sources.jar", cp[0].getSourceAttachmentPath().lastSegment()); assertEquals("downloadsources-t002-0.0.1-sources.jar", cp[1].getSourceAttachmentPath().lastSegment()); { // cleanup new File(repo, "downloadsources/downloadsources-t001/0.0.1/downloadsources-t001-0.0.1-sources.jar").delete(); new File(repo, "downloadsources/downloadsources-t002/0.0.1/downloadsources-t002-0.0.1-sources.jar").delete(); MavenPlugin.getDefault().getMavenProjectManager().refresh( new MavenUpdateRequest(new IProject[] {project}, false /*offline*/, false)); waitForJobsToComplete(); } // test one entry getBuildPathManager().downloadSources(project, cp[0].getPath()); waitForJobsToComplete(); container = BuildPathManager.getMaven2ClasspathContainer(javaProject); cp = container.getClasspathEntries(); assertEquals(2, cp.length); assertEquals("downloadsources-t001-0.0.1-sources.jar", cp[0].getSourceAttachmentPath().lastSegment()); assertNull(cp[1].getSourceAttachmentPath()); { // cleanup new File(repo, "downloadsources/downloadsources-t001/0.0.1/downloadsources-t001-0.0.1-sources.jar").delete(); new File(repo, "downloadsources/downloadsources-t002/0.0.1/downloadsources-t002-0.0.1-sources.jar").delete(); MavenPlugin.getDefault().getMavenProjectManager().refresh( new MavenUpdateRequest(new IProject[] {project}, false /*offline*/, false)); waitForJobsToComplete(); } // test two entries getBuildPathManager().downloadSources(project, cp[0].getPath()); getBuildPathManager().downloadSources(project, cp[1].getPath()); waitForJobsToComplete(); container = BuildPathManager.getMaven2ClasspathContainer(javaProject); cp = container.getClasspathEntries(); assertEquals(2, cp.length); assertEquals("downloadsources-t001-0.0.1-sources.jar", cp[0].getSourceAttachmentPath().lastSegment()); assertEquals("downloadsources-t002-0.0.1-sources.jar", cp[1].getSourceAttachmentPath().lastSegment()); } public void testDownloadSources_001_sourceAttachment() throws Exception { new File(repo, "downloadsources/downloadsources-t001/0.0.1/downloadsources-t001-0.0.1-sources.jar").delete(); new File(repo, "downloadsources/downloadsources-t002/0.0.1/downloadsources-t002-0.0.1-sources.jar").delete(); IProject project = createExisting("downloadsources-p001", "projects/downloadsources/p001"); waitForJobsToComplete(); IJavaProject javaProject = JavaCore.create(project); final IClasspathContainer container = BuildPathManager.getMaven2ClasspathContainer(javaProject); IPath entryPath = container.getClasspathEntries()[0].getPath(); IPath srcPath = new Path("/a"); IPath srcRoot = new Path("/b"); String javaDocUrl = "c"; IClasspathAttribute attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME, javaDocUrl); final IClasspathEntry entry = JavaCore.newLibraryEntry(entryPath, // srcPath, srcRoot, new IAccessRule[0], // new IClasspathAttribute[] {attribute}, // false /*not exported*/); BuildPathManager buildpathManager = getBuildPathManager(); IClasspathContainer containerSuggestion = new IClasspathContainer() { public IClasspathEntry[] getClasspathEntries() { return new IClasspathEntry[] {entry}; } public String getDescription() { return container.getDescription(); } public int getKind() { return container.getKind(); } public IPath getPath() { return container.getPath(); } }; buildpathManager.updateClasspathContainer(javaProject, containerSuggestion, monitor); waitForJobsToComplete(); // check custom source/javadoc IClasspathContainer container2 = BuildPathManager.getMaven2ClasspathContainer(javaProject); IClasspathEntry entry2 = container2.getClasspathEntries()[0]; assertEquals(entryPath, entry2.getPath()); assertEquals(srcPath, entry2.getSourceAttachmentPath()); assertEquals(srcRoot, entry2.getSourceAttachmentRootPath()); assertEquals(javaDocUrl, buildpathManager.getJavadocLocation(entry2)); File file = buildpathManager.getSourceAttachmentPropertiesFile(project); assertEquals(true, file.canRead()); // check project delete project.delete(true, monitor); waitForJobsToComplete(); assertEquals(false, file.canRead()); } public void testDownloadSources_002_javadoconly() throws Exception { new File(repo, "downloadsources/downloadsources-t003/0.0.1/downloadsources-t003-0.0.1-javadoc.jar").delete(); IProject project = createExisting("downloadsources-p002", "projects/downloadsources/p002"); waitForJobsToComplete(); // sanity check IJavaProject javaProject = JavaCore.create(project); IClasspathContainer container = BuildPathManager.getMaven2ClasspathContainer(javaProject); IClasspathEntry[] cp = container.getClasspathEntries(); assertEquals(1, cp.length); assertNull(cp[0].getSourceAttachmentPath()); getBuildPathManager().downloadJavaDoc(project, null); waitForJobsToComplete(); container = BuildPathManager.getMaven2ClasspathContainer(javaProject); cp = container.getClasspathEntries(); assertEquals(1, cp.length); assertNull(cp[0].getSourceAttachmentPath()); // sanity check assertEquals("" + cp[0], 1, getAttributeCount(cp[0], IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME)); getBuildPathManager().downloadJavaDoc(project, null); waitForJobsToComplete(); container = BuildPathManager.getMaven2ClasspathContainer(javaProject); cp = container.getClasspathEntries(); assertEquals(1, cp.length); assertNull(cp[0].getSourceAttachmentPath()); // sanity check assertEquals("" + cp[0], 1, getAttributeCount(cp[0], IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME)); } - public void testDownloadSources_003_customRenoteRepository() throws Exception { + public void testDownloadSources_003_customRemoteRepository() throws Exception { File file = new File(repo, "downloadsources/downloadsources-t004/0.0.1/downloadsources-t004-0.0.1-sources.jar"); assertTrue(!file.exists() || file.delete()); IProject project = createExisting("downloadsources-p003", "projects/downloadsources/p003"); waitForJobsToComplete(); // sanity check IJavaProject javaProject = JavaCore.create(project); IClasspathContainer container = BuildPathManager.getMaven2ClasspathContainer(javaProject); IClasspathEntry[] cp = container.getClasspathEntries(); assertEquals(1, cp.length); assertNull(cp[0].getSourceAttachmentPath()); getBuildPathManager().downloadSources(project, cp[0].getPath()); waitForJobsToComplete(); javaProject = JavaCore.create(project); container = BuildPathManager.getMaven2ClasspathContainer(javaProject); cp = container.getClasspathEntries(); assertEquals(1, cp.length); assertEquals("downloadsources-t004-0.0.1-sources.jar", cp[0].getSourceAttachmentPath().lastSegment()); } private static int getAttributeCount(IClasspathEntry entry, String name) { IClasspathAttribute[] attrs = entry.getExtraAttributes(); int count = 0; for(int i = 0; i < attrs.length; i++ ) { if(name.equals(attrs[i].getName())) { count++ ; } } return count; } public void testDownloadSources_004_testsClassifier() throws Exception { File file = new File(repo, "downloadsources/downloadsources-t005/0.0.1/downloadsources-t005-0.0.1-test-sources.jar"); assertTrue(!file.exists() || file.delete()); IProject project = createExisting("downloadsources-p004", "projects/downloadsources/p004"); waitForJobsToComplete(); IJavaProject javaProject = JavaCore.create(project); IClasspathContainer container = BuildPathManager.getMaven2ClasspathContainer(javaProject); IClasspathEntry[] cp = container.getClasspathEntries(); // sanity check assertEquals("downloadsources-t005-0.0.1-tests.jar", cp[1].getPath().lastSegment()); getBuildPathManager().downloadSources(project, cp[1].getPath()); waitForJobsToComplete(); container = BuildPathManager.getMaven2ClasspathContainer(javaProject); cp = container.getClasspathEntries(); assertEquals(2, cp.length); assertEquals("downloadsources-t005-0.0.1-test-sources.jar", cp[1].getSourceAttachmentPath().lastSegment()); } public void testDownloadSources_004_classifier() throws Exception { File file = new File(repo, "downloadsources/downloadsources-t006/0.0.1/downloadsources-t006-0.0.1-sources.jar"); assertTrue(!file.exists() || file.delete()); IProject project = createExisting("downloadsources-p005", "projects/downloadsources/p005"); waitForJobsToComplete(); IJavaProject javaProject = JavaCore.create(project); IClasspathContainer container = BuildPathManager.getMaven2ClasspathContainer(javaProject); IClasspathEntry[] cp = container.getClasspathEntries(); // sanity check assertEquals("downloadsources-t006-0.0.1-jdk14.jar", cp[0].getPath().lastSegment()); getBuildPathManager().downloadSources(project, cp[0].getPath()); waitForJobsToComplete(); container = BuildPathManager.getMaven2ClasspathContainer(javaProject); cp = container.getClasspathEntries(); assertEquals(1, cp.length); assertNotNull(cp[0].getSourceAttachmentPath()); assertEquals(cp[0].getSourceAttachmentPath().toString(), "downloadsources-t006-0.0.1-sources.jar", cp[0].getSourceAttachmentPath().lastSegment()); } public void testDownloadSources_006_nonMavenProject() throws Exception { IndexManager indexManager = MavenPlugin.getDefault().getIndexManager(); IndexInfo indexInfo = new IndexInfo("remoterepo-local", new File("remoterepo"), null, IndexInfo.Type.LOCAL, false); indexManager.addIndex(indexInfo, false); indexManager.reindex(indexInfo.getIndexName(), monitor); indexManager.addIndex(new IndexInfo("remoterepo", null, "file:remoterepo", IndexInfo.Type.REMOTE, false), false); IProject project = createExisting("downloadsources-p006", "projects/downloadsources/p006"); File log4jJar = new File("remoterepo/log4j/log4j/1.2.13/log4j-1.2.13.jar"); Path log4jPath = new Path(log4jJar.getAbsolutePath()); File junitJar = new File("remoterepo/junit/junit/3.8.1/junit-3.8.1.jar"); Path junitPath = new Path(junitJar.getAbsolutePath()); IJavaProject javaProject = JavaCore.create(project); IClasspathEntry[] origCp = javaProject.getRawClasspath(); IClasspathEntry[] cp = new IClasspathEntry[origCp.length + 2]; System.arraycopy(origCp, 0, cp, 0, origCp.length); cp[cp.length - 2] = JavaCore.newLibraryEntry(log4jPath, null, null, true); cp[cp.length - 1] = JavaCore.newLibraryEntry(junitPath, null, null, false); javaProject.setRawClasspath(cp, monitor); getBuildPathManager().downloadSources(project, log4jPath); waitForJobsToComplete(); cp = javaProject.getRawClasspath(); assertEquals(log4jPath, cp[cp.length - 2].getPath()); assertEquals("log4j-1.2.13-sources.jar", cp[cp.length - 2].getSourceAttachmentPath().lastSegment()); assertEquals(true, cp[cp.length - 2].isExported()); getBuildPathManager().downloadSources(project, junitPath); waitForJobsToComplete(); assertEquals(junitPath, cp[cp.length - 1].getPath()); assertEquals("junit-3.8.1-sources.jar", cp[cp.length - 1].getSourceAttachmentPath().lastSegment()); assertEquals(false, cp[cp.length - 1].isExported()); } private BuildPathManager getBuildPathManager() { return MavenJdtPlugin.getDefault().getBuildpathManager(); } public void testClassifiers() throws Exception { IProject p1 = createExisting("classifiers-p1", "projects/classifiers/classifiers-p1"); waitForJobsToComplete(); IJavaProject javaProject = JavaCore.create(p1); IClasspathContainer container = BuildPathManager.getMaven2ClasspathContainer(javaProject); IClasspathEntry[] cp = container.getClasspathEntries(); assertEquals(2, cp.length); assertEquals("classifiers-p2-0.0.1.jar", cp[0].getPath().lastSegment()); assertEquals("classifiers-p2-0.0.1-tests.jar", cp[1].getPath().lastSegment()); createExisting("classifiers-p2", "projects/classifiers/classifiers-p2"); waitForJobsToComplete(); container = BuildPathManager.getMaven2ClasspathContainer(javaProject); cp = container.getClasspathEntries(); assertEquals(1, cp.length); assertEquals("classifiers-p2", cp[0].getPath().lastSegment()); } public void testCreateSimpleProject() throws CoreException { final MavenPlugin plugin = MavenPlugin.getDefault(); final boolean modules = true; IProject project = createSimpleProject("simple-project", null, modules); ResolverConfiguration configuration = plugin.getMavenProjectManager().getResolverConfiguration(project); assertEquals(modules, configuration.shouldIncludeModules()); IJavaProject javaProject = JavaCore.create(project); IClasspathEntry[] rawClasspath = javaProject.getRawClasspath(); assertEquals(Arrays.toString(rawClasspath), 6, rawClasspath.length); assertEquals("/simple-project/src/main/java", rawClasspath[0].getPath().toString()); assertEquals("/simple-project/src/main/resources", rawClasspath[1].getPath().toString()); assertEquals("/simple-project/src/test/java", rawClasspath[2].getPath().toString()); assertEquals("/simple-project/src/test/resources", rawClasspath[3].getPath().toString()); assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[4].getPath().toString()); assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[5].getPath().toString()); IClasspathEntry[] entries = getMavenContainerEntries(project); assertEquals(Arrays.toString(entries), 1, entries.length); assertEquals(IClasspathEntry.CPE_LIBRARY, entries[0].getEntryKind()); assertEquals("junit-3.8.1.jar", entries[0].getPath().lastSegment()); assertTrue(project.getFile("pom.xml").exists()); assertTrue(project.getFolder("src/main/java").exists()); assertTrue(project.getFolder("src/test/java").exists()); assertTrue(project.getFolder("src/main/resources").exists()); assertTrue(project.getFolder("src/test/resources").exists()); } public void test005_dependencyAvailableFromLocalRepoAndWorkspace() throws Exception { IProject p1 = createExisting("t005-p1", "resources/t005/t005-p1"); IProject p2 = createExisting("t005-p2", "resources/t005/t005-p2"); waitForJobsToComplete(); IClasspathEntry[] cp = getMavenContainerEntries(p1); assertEquals(1, cp.length); assertEquals(p2.getFullPath(), cp[0].getPath()); p2.close(monitor); waitForJobsToComplete(); cp = getMavenContainerEntries(p1); assertEquals(1, cp.length); assertEquals("t005-p2-0.0.1.jar", cp[0].getPath().lastSegment()); p2.open(monitor); waitForJobsToComplete(); cp = getMavenContainerEntries(p1); assertEquals(1, cp.length); assertEquals(p2.getFullPath(), cp[0].getPath()); } public void testProjectNameTemplate() throws Exception { deleteProject("p003"); deleteProject("projectimport.p003-2.0"); ResolverConfiguration configuration = new ResolverConfiguration(); ProjectImportConfiguration projectImportConfiguration = new ProjectImportConfiguration(configuration); importProject("p003version1", "projects/projectimport/p003version1", projectImportConfiguration); projectImportConfiguration.setProjectNameTemplate("[groupId].[artifactId]-[version]"); importProject("p003version2", "projects/projectimport/p003version2", projectImportConfiguration); waitForJobsToComplete(); assertTrue(workspace.getRoot().getProject("p003").exists()); assertTrue(workspace.getRoot().getProject("projectimport.p003-2.0").exists()); } public void testCompilerSettingsJsr14() throws Exception { deleteProject("compilerSettingsJsr14"); ResolverConfiguration configuration = new ResolverConfiguration(); ProjectImportConfiguration projectImportConfiguration = new ProjectImportConfiguration(configuration); importProject("compilerSettingsJsr14", "projects/compilerSettingsJsr14", projectImportConfiguration); waitForJobsToComplete(); IProject project = workspace.getRoot().getProject("compilerSettingsJsr14"); assertTrue(project.exists()); assertMarkers(project, 0); IJavaProject javaProject = JavaCore.create(project); assertEquals("1.5", javaProject.getOption(JavaCore.COMPILER_SOURCE, true)); assertEquals("1.5", javaProject.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true)); IClasspathEntry jreEntry = getJreContainer(javaProject.getRawClasspath()); assertEquals("J2SE-1.5", JavaRuntime.getExecutionEnvironmentId(jreEntry.getPath())); } public void testCompilerSettings14() throws Exception { deleteProject("compilerSettings14"); ResolverConfiguration configuration = new ResolverConfiguration(); ProjectImportConfiguration projectImportConfiguration = new ProjectImportConfiguration(configuration); importProject("compilerSettings14", "projects/compilerSettings14", projectImportConfiguration); waitForJobsToComplete(); IProject project = workspace.getRoot().getProject("compilerSettings14"); assertTrue(project.exists()); // Build path specifies execution environment J2SE-1.4. // There are no JREs in the workspace strictly compatible with this environment. assertMarkers(project, 0); IJavaProject javaProject = JavaCore.create(project); assertEquals("1.4", javaProject.getOption(JavaCore.COMPILER_SOURCE, true)); assertEquals("1.4", javaProject.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true)); IClasspathEntry jreEntry = getJreContainer(javaProject.getRawClasspath()); assertEquals("J2SE-1.4", JavaRuntime.getExecutionEnvironmentId(jreEntry.getPath())); } private IClasspathEntry getJreContainer(IClasspathEntry[] entries) { for(IClasspathEntry entry : entries) { if(JavaRuntime.newDefaultJREContainerPath().isPrefixOf(entry.getPath())) { return entry; } } return null; } public void testMavenBuilderOrder() throws Exception { IProject project = createExisting("builderOrder", "projects/builderOrder"); IProjectDescription description = project.getDescription(); ICommand[] buildSpec = description.getBuildSpec(); ICommand javaBuilder = buildSpec[0]; ICommand mavenBuilder = buildSpec[1]; verifyNaturesAndBuilders(project); ResolverConfiguration configuration = new ResolverConfiguration(); String goalToExecute = ""; IProjectConfigurationManager configurationManager = plugin.getProjectConfigurationManager(); configurationManager.updateProjectConfiguration(project, configuration, goalToExecute, monitor); verifyNaturesAndBuilders(project); description.setNatureIds(new String[] {JavaCore.NATURE_ID}); description.setBuildSpec(new ICommand[] {javaBuilder}); project.setDescription(description, monitor); // can't update configuration of non-maven project configurationManager.enableMavenNature(project, configuration, monitor); verifyNaturesAndBuilders(project); description.setNatureIds(new String[] {}); description.setBuildSpec(new ICommand[] {mavenBuilder, javaBuilder}); project.setDescription(description, monitor); // can't update configuration of non-maven project configurationManager.enableMavenNature(project, configuration, monitor); verifyNaturesAndBuilders(project); description.setNatureIds(new String[] {IMavenConstants.NATURE_ID, JavaCore.NATURE_ID}); description.setBuildSpec(new ICommand[] {mavenBuilder, javaBuilder}); project.setDescription(description, monitor); // can't update configuration of non-maven project configurationManager.enableMavenNature(project, configuration, monitor); verifyNaturesAndBuilders(project); } // MNGECLIPSE-1133 public void testUpdateProjectConfigurationWithWorkspace() throws Exception { deleteProject("MNGECLIPSE-1133parent"); deleteProject("MNGECLIPSE-1133child"); final IProject project1 = createProject("MNGECLIPSE-1133parent", "projects/MNGECLIPSE-1133/parent/pom.xml"); final IProject project2 = createProject("MNGECLIPSE-1133child", "projects/MNGECLIPSE-1133/child/pom.xml"); NullProgressMonitor monitor = new NullProgressMonitor(); IProjectConfigurationManager configurationManager = MavenPlugin.getDefault().getProjectConfigurationManager(); ResolverConfiguration configuration = new ResolverConfiguration(); configurationManager.enableMavenNature(project1, configuration, monitor); // buildpathManager.updateSourceFolders(project1, monitor); configurationManager.enableMavenNature(project2, configuration, monitor); // buildpathManager.updateSourceFolders(project2, monitor); // waitForJob("Initializing " + project1.getProject().getName()); // waitForJob("Initializing " + project2.getProject().getName()); try { project1.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor()); project2.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor()); } catch(Exception ex) { throw ex; } waitForJobsToComplete(); assertMarkers(project2, 0); // update configuration configurationManager.updateProjectConfiguration(project2, configuration, "", monitor); waitForJobsToComplete(); assertMarkers(project2, 0); } private void verifyNaturesAndBuilders(IProject project) throws CoreException { assertTrue(project.hasNature(JavaCore.NATURE_ID)); assertTrue(project.hasNature(IMavenConstants.NATURE_ID)); IProjectDescription description = project.getDescription(); { ICommand[] buildSpec = description.getBuildSpec(); assertEquals(2, buildSpec.length); assertEquals(JavaCore.BUILDER_ID, buildSpec[0].getBuilderName()); assertEquals(IMavenConstants.BUILDER_ID, buildSpec[1].getBuilderName()); } } private IProject createSimpleProject(final String projectName, final IPath location, final boolean modules) throws CoreException { final IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); workspace.run(new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { Model model = new Model(); model.setGroupId(projectName); model.setArtifactId(projectName); model.setVersion("0.0.1-SNAPSHOT"); model.setModelVersion("4.0.0"); Dependency dependency = new Dependency(); dependency.setGroupId("junit"); dependency.setArtifactId("junit"); dependency.setVersion("3.8.1"); model.addDependency(dependency); String[] directories = {"src/main/java", "src/test/java", "src/main/resources", "src/test/resources"}; ProjectImportConfiguration config = new ProjectImportConfiguration(); config.getResolverConfiguration().setIncludeModules(modules); plugin.getProjectConfigurationManager().createSimpleProject(project, location, model, directories, config, monitor); } }, plugin.getProjectConfigurationManager().getRule(), IWorkspace.AVOID_UPDATE, monitor); return project; } public void testSimpleProjectInExternalLocation() throws CoreException, IOException { final MavenPlugin plugin = MavenPlugin.getDefault(); final boolean modules = true; File tmp = File.createTempFile("m2eclipse", "test"); tmp.delete(); //deleting a tmp file so we can use the name for a folder final String projectName1 = "external-simple-project-1"; IProject project1 = createSimpleProject(projectName1, new Path(tmp.getAbsolutePath()).append(projectName1), modules); ResolverConfiguration configuration = plugin.getMavenProjectManager().getResolverConfiguration(project1); assertEquals(modules, configuration.shouldIncludeModules()); final String projectName2 = "external-simple-project-2"; File existingFolder = new File(tmp, projectName2); existingFolder.mkdirs(); new File(existingFolder, IMavenConstants.POM_FILE_NAME).createNewFile(); try { createSimpleProject(projectName2, new Path(tmp.getAbsolutePath()).append(projectName2), modules); fail("Project creation should fail if the POM exists in the target folder"); } catch(CoreException e) { final String msg = IMavenConstants.POM_FILE_NAME + " already exists"; assertTrue("Project creation should throw a \"" + msg + "\" exception if the POM exists in the target folder", e .getMessage().indexOf(msg) > 0); } tmp.delete(); } //FIXME FB 30/10/2008 : Archetype tests are disabled while MNGECLIPSE-948 is not fixed public void XXXtestArchetypeProject() throws CoreException { MavenPlugin plugin = MavenPlugin.getDefault(); boolean modules = true; Archetype quickStart = findQuickStartArchetype(); IProject project = createArchetypeProject("archetype-project", null, quickStart, modules); ResolverConfiguration configuration = plugin.getMavenProjectManager().getResolverConfiguration(project); assertEquals(modules, configuration.shouldIncludeModules()); } public void XXXtestArchetypeProjectInExternalLocation() throws CoreException, IOException { final MavenPlugin plugin = MavenPlugin.getDefault(); final boolean modules = true; Archetype quickStart = findQuickStartArchetype(); File tmp = File.createTempFile("m2eclipse", "test"); tmp.delete(); //deleting a tmp file so we can use the name for a folder final String projectName1 = "external-archetype-project-1"; IProject project1 = createArchetypeProject(projectName1, new Path(tmp.getAbsolutePath()).append(projectName1), quickStart, modules); ResolverConfiguration configuration = plugin.getMavenProjectManager().getResolverConfiguration(project1); assertEquals(modules, configuration.shouldIncludeModules()); final String projectName2 = "external-archetype-project-2"; File existingFolder = new File(tmp, projectName2); existingFolder.mkdirs(); new File(existingFolder, IMavenConstants.POM_FILE_NAME).createNewFile(); try { createArchetypeProject(projectName2, new Path(tmp.getAbsolutePath()).append(projectName2), quickStart, modules); fail("Project creation should fail if the POM exists in the target folder"); } catch(CoreException e) { // this is supposed to happen } tmp.delete(); } private Archetype findQuickStartArchetype() throws CoreException { final MavenPlugin plugin = MavenPlugin.getDefault(); @SuppressWarnings("unchecked") List<Archetype> archetypes = plugin.getArchetypeManager().getArchetypeCatalogFactory("internal") .getArchetypeCatalog().getArchetypes(); for(Archetype archetype : archetypes) { if("org.apache.maven.archetypes".equals(archetype.getGroupId()) && "maven-archetype-quickstart".equals(archetype.getArtifactId()) && "1.0".equals(archetype.getVersion())) { return archetype; } } fail("maven-archetype-quickstart archetype not found in the internal catalog"); return null; } private IProject createArchetypeProject(final String projectName, final IPath location, final Archetype archetype, final boolean modules) throws CoreException { final IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); workspace.run(new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { ResolverConfiguration resolverConfiguration = new ResolverConfiguration(); resolverConfiguration.setIncludeModules(modules); ProjectImportConfiguration pic = new ProjectImportConfiguration(resolverConfiguration); plugin.getProjectConfigurationManager().createArchetypeProject(project, location, archetype, // projectName, projectName, "0.0.1-SNAPSHOT", "jar", new Properties(), pic, monitor); } }, plugin.getProjectConfigurationManager().getRule(), IWorkspace.AVOID_UPDATE, monitor); return project; } //Local repo set by the BuildManager is based on a cached version of MavenEmbedder, not the one configured in setup. public void XXXtestMNGECLIPSE_1047_localRepoPath() { IPath m2_repo = JavaCore.getClasspathVariable(BuildPathManager.M2_REPO); assertEquals(repo.toString(), m2_repo.toOSString()); } }
true
false
null
null
diff --git a/src/test/java/com/onarandombox/MultiverseCore/test/TestWorldStuff.java b/src/test/java/com/onarandombox/MultiverseCore/test/TestWorldStuff.java index 9508bc1..707776c 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/test/TestWorldStuff.java +++ b/src/test/java/com/onarandombox/MultiverseCore/test/TestWorldStuff.java @@ -1,220 +1,220 @@ /****************************************************************************** * Multiverse 2 Copyright (c) the Multiverse Team 2011. * * Multiverse 2 is licensed under the BSD License. * * For more information please check the README.md file included * * with this project. * ******************************************************************************/ package com.onarandombox.MultiverseCore.test; import com.onarandombox.MultiverseCore.MultiverseCore; import com.onarandombox.MultiverseCore.api.MultiverseWorld; import com.onarandombox.MultiverseCore.exceptions.PropertyDoesNotExistException; import com.onarandombox.MultiverseCore.test.utils.TestInstanceCreator; import com.onarandombox.MultiverseCore.test.utils.WorldCreatorMatcher; import com.onarandombox.MultiverseCore.utils.WorldManager; import org.bukkit.*; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.permissions.Permission; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Matchers; import org.mockito.internal.verification.VerificationModeFactory; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.File; import static junit.framework.Assert.*; import static org.mockito.Mockito.*; @RunWith(PowerMockRunner.class) @PrepareForTest({ PluginManager.class, MultiverseCore.class, Permission.class, Bukkit.class, WorldManager.class }) public class TestWorldStuff { private TestInstanceCreator creator; private Server mockServer; private CommandSender mockCommandSender; @Before public void setUp() throws Exception { creator = new TestInstanceCreator(); assertTrue(creator.setUp()); mockServer = creator.getServer(); mockCommandSender = creator.getCommandSender(); } @After public void tearDown() throws Exception { creator.tearDown(); } @Test public void testWorldImportWithNoFolder() { // Make sure the world directory do NOT exist // (it was created by the TestInstanceCreator) File worldFile = new File(TestInstanceCreator.serverDirectory, "world"); assertTrue(worldFile.exists()); assertTrue(worldFile.delete()); // Start actual testing. // Pull a core instance from the server. Plugin plugin = mockServer.getPluginManager().getPlugin("Multiverse-Core"); // Make sure Core is not null assertNotNull(plugin); // Make sure Core is enabled assertTrue(plugin.isEnabled()); // Initialize a fake command Command mockCommand = mock(Command.class); when(mockCommand.getName()).thenReturn("mv"); String[] normalArgs = new String[]{ "import", "world", "normal" }; // Ensure we have a fresh copy of MV, 0 worlds. assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size()); // Import the first world. The world folder does not exist. plugin.onCommand(mockCommandSender, mockCommand, "", normalArgs); verify(mockCommandSender).sendMessage(ChatColor.RED + "FAILED."); verify(mockCommandSender).sendMessage("That world folder does not exist. These look like worlds to me:"); // We should still have no worlds. assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size()); } @Test public void testWorldImport() { // Pull a core instance from the server. Plugin plugin = mockServer.getPluginManager().getPlugin("Multiverse-Core"); // Make sure Core is not null assertNotNull(plugin); // Make sure Core is enabled assertTrue(plugin.isEnabled()); // Initialize a fake command Command mockCommand = mock(Command.class); when(mockCommand.getName()).thenReturn("mv"); // Ensure that there are no worlds imported. This is a fresh setup. assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size()); // Import the first world. String[] normalArgs = new String[]{ "import", "world", "normal" }; plugin.onCommand(mockCommandSender, mockCommand, "", normalArgs); // We should now have one world imported! assertEquals(1, creator.getCore().getMVWorldManager().getMVWorlds().size()); // Import the second world. String[] netherArgs = new String[]{ "import", "world_nether", "nether" }; plugin.onCommand(mockCommandSender, mockCommand, "", netherArgs); // We should now have 2 worlds imported! assertEquals(2, creator.getCore().getMVWorldManager().getMVWorlds().size()); // Import the third world. String[] skyArgs = new String[]{ "import", "world_the_end", "end" }; plugin.onCommand(mockCommandSender, mockCommand, "", skyArgs); // We should now have 2 worlds imported! assertEquals(3, creator.getCore().getMVWorldManager().getMVWorlds().size()); // Verify that the commandSender has been called 3 times. verify(mockCommandSender).sendMessage("Starting import of world 'world'..."); verify(mockCommandSender).sendMessage("Starting import of world 'world_nether'..."); verify(mockCommandSender).sendMessage("Starting import of world 'world_the_end'..."); verify(mockCommandSender, VerificationModeFactory.times(3)).sendMessage(ChatColor.GREEN + "Complete!"); } @Test public void testWorldCreation() { // Pull a core instance from the server. Plugin plugin = mockServer.getPluginManager().getPlugin("Multiverse-Core"); // Make sure Core is not null assertNotNull(plugin); // Make sure Core is enabled assertTrue(plugin.isEnabled()); // Initialize a fake command Command mockCommand = mock(Command.class); when(mockCommand.getName()).thenReturn("mv"); // Ensure that there are no worlds imported. This is a fresh setup. assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size()); // Create the world String[] normalArgs = new String[]{ "create", "newworld", "normal" }; plugin.onCommand(mockCommandSender, mockCommand, "", normalArgs); // We should now have one world! assertEquals(1, creator.getCore().getMVWorldManager().getMVWorlds().size()); // Verify verify(mockCommandSender).sendMessage("Starting creation of world 'newworld'..."); verify(mockCommandSender).sendMessage("Complete!"); WorldCreatorMatcher matcher = new WorldCreatorMatcher(new WorldCreator("newworld")); verify(mockServer).createWorld(Matchers.argThat(matcher)); } @Test public void testModifyGameMode() { // Pull a core instance from the server. Plugin plugin = mockServer.getPluginManager().getPlugin("Multiverse-Core"); Command mockCommand = mock(Command.class); when(mockCommand.getName()).thenReturn("mv"); // Ensure that there are no worlds imported. This is a fresh setup. assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size()); this.createInitialWorlds(plugin, mockCommand); // Ensure that the default worlds have been created. assertEquals(3, creator.getCore().getMVWorldManager().getMVWorlds().size()); MultiverseWorld mainWorld = creator.getCore().getMVWorldManager().getMVWorld("world"); // Ensure that the default mode was normal. assertEquals(GameMode.SURVIVAL, mainWorld.getGameMode()); // Set the mode to creative in world. plugin.onCommand(mockCommandSender, mockCommand, "", new String[]{ "modify", "set", "mode", "creative", "world" }); verify(mockCommandSender).sendMessage(ChatColor.GREEN + "Success!" + ChatColor.WHITE + " Property " + ChatColor.AQUA + "mode" + ChatColor.WHITE + " was set to " + ChatColor.GREEN + "creative"); // Ensure the world is now a creative world assertEquals(GameMode.CREATIVE, mainWorld.getGameMode()); // More tests, with alternate syntax. plugin.onCommand(mockCommandSender, mockCommand, "", new String[]{ "modify", "set", "gamemode", "0", "world" }); verify(mockCommandSender).sendMessage(ChatColor.GREEN + "Success!" + ChatColor.WHITE + " Property " + ChatColor.AQUA + "gamemode" + ChatColor.WHITE + " was set to " + ChatColor.GREEN + "0"); assertEquals(GameMode.SURVIVAL, mainWorld.getGameMode()); // Now fail one. plugin.onCommand(mockCommandSender, mockCommand, "", new String[]{ "modify", "set", "mode", "fish", "world" }); try { verify(mockCommandSender).sendMessage(mainWorld.getProperty("mode", Object.class).getHelp()); } catch (PropertyDoesNotExistException e) { fail("Mode property did not exist."); } plugin.onCommand(mockCommandSender, mockCommand, "", new String[]{ "modify", "set", "blah", "fish", "world" }); verify(mockCommandSender).sendMessage(ChatColor.RED + "Sorry, You can't set: '"+ChatColor.GRAY+ "blah" + ChatColor.RED + "'"); } private void createInitialWorlds(Plugin plugin, Command command) { plugin.onCommand(mockCommandSender, command, "", new String[]{ "import", "world", "normal" }); plugin.onCommand(mockCommandSender, command, "", new String[]{ "import", "world_nether", "nether" }); plugin.onCommand(mockCommandSender, command, "", new String[]{ "import", "world_the_end", "end" }); verify(mockCommandSender).sendMessage("Starting import of world 'world'..."); verify(mockCommandSender).sendMessage("Starting import of world 'world_nether'..."); verify(mockCommandSender).sendMessage("Starting import of world 'world_the_end'..."); - verify(mockCommandSender, times(3)).sendMessage("Complete!"); + verify(mockCommandSender, times(3)).sendMessage(ChatColor.GREEN + "Complete!"); } }
true
false
null
null
diff --git a/SeriesGuide/src/com/battlelancer/seriesguide/util/DBUtils.java b/SeriesGuide/src/com/battlelancer/seriesguide/util/DBUtils.java index 734b83444..8d72c5fa2 100644 --- a/SeriesGuide/src/com/battlelancer/seriesguide/util/DBUtils.java +++ b/SeriesGuide/src/com/battlelancer/seriesguide/util/DBUtils.java @@ -1,776 +1,775 @@ /* * Copyright 2011 Uwe Trottmann * * 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.battlelancer.seriesguide.util; import android.app.ProgressDialog; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.OperationApplicationException; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.RemoteException; import android.preference.PreferenceManager; import android.text.format.DateUtils; import com.battlelancer.seriesguide.SeriesGuideApplication; import com.battlelancer.seriesguide.dataliberation.JsonExportTask.ShowStatusExport; import com.battlelancer.seriesguide.dataliberation.model.Show; import com.battlelancer.seriesguide.items.Series; import com.battlelancer.seriesguide.provider.SeriesContract.EpisodeSearch; import com.battlelancer.seriesguide.provider.SeriesContract.Episodes; import com.battlelancer.seriesguide.provider.SeriesContract.Seasons; import com.battlelancer.seriesguide.provider.SeriesContract.Shows; import com.battlelancer.seriesguide.settings.ActivitySettings; import com.battlelancer.seriesguide.ui.SeriesGuidePreferences; import com.battlelancer.seriesguide.ui.UpcomingFragment.ActivityType; import com.battlelancer.seriesguide.ui.UpcomingFragment.UpcomingQuery; import com.battlelancer.thetvdbapi.TheTVDB.ShowStatus; import com.uwetrottmann.androidutils.Lists; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; public class DBUtils { static final String TAG = "SeriesDatabase"; /** * Use 9223372036854775807 (Long.MAX_VALUE) for unknown airtime/no next * episode so they will get sorted last. */ public static final String UNKNOWN_NEXT_AIR_DATE = "9223372036854775807"; interface UnwatchedQuery { static final String[] PROJECTION = new String[] { Episodes._ID }; static final String NOAIRDATE_SELECTION = Episodes.WATCHED + "=? AND " + Episodes.FIRSTAIREDMS + "=?"; static final String FUTURE_SELECTION = Episodes.WATCHED + "=? AND " + Episodes.FIRSTAIREDMS + ">?"; static final String AIRED_SELECTION = Episodes.WATCHED + "=? AND " + Episodes.FIRSTAIREDMS + " !=? AND " + Episodes.FIRSTAIREDMS + "<=?"; } /** * Looks up the episodes of a given season and stores the count of already * aired, but not watched ones in the seasons watchcount. * * @param context * @param seasonid * @param prefs */ public static void updateUnwatchedCount(Context context, String seasonid, SharedPreferences prefs) { final ContentResolver resolver = context.getContentResolver(); final String fakenow = String.valueOf(Utils.getFakeCurrentTime(prefs)); final Uri episodesOfSeasonUri = Episodes.buildEpisodesOfSeasonUri(seasonid); // all a seasons episodes final Cursor total = resolver.query(episodesOfSeasonUri, new String[] { Episodes._ID }, null, null, null); final int totalcount = total.getCount(); total.close(); // unwatched, aired episodes final Cursor unwatched = resolver.query(episodesOfSeasonUri, UnwatchedQuery.PROJECTION, UnwatchedQuery.AIRED_SELECTION, new String[] { "0", "-1", fakenow }, null); final int count = unwatched.getCount(); unwatched.close(); // unwatched, aired in the future episodes final Cursor unaired = resolver.query(episodesOfSeasonUri, UnwatchedQuery.PROJECTION, UnwatchedQuery.FUTURE_SELECTION, new String[] { "0", fakenow }, null); final int unaired_count = unaired.getCount(); unaired.close(); // unwatched, no airdate final Cursor noairdate = resolver.query(episodesOfSeasonUri, UnwatchedQuery.PROJECTION, UnwatchedQuery.NOAIRDATE_SELECTION, new String[] { "0", "-1" }, null); final int noairdate_count = noairdate.getCount(); noairdate.close(); final ContentValues update = new ContentValues(); update.put(Seasons.WATCHCOUNT, count); update.put(Seasons.UNAIREDCOUNT, unaired_count); update.put(Seasons.NOAIRDATECOUNT, noairdate_count); update.put(Seasons.TOTALCOUNT, totalcount); resolver.update(Seasons.buildSeasonUri(seasonid), update, null, null); } /** * Returns how many episodes of a show are left to watch (only aired and not * watched, exclusive episodes with no air date and without specials). */ public static int getUnwatchedEpisodesOfShow(Context context, String showId, SharedPreferences prefs) { if (context == null) { return -1; } final ContentResolver resolver = context.getContentResolver(); final String fakenow = String.valueOf(Utils.getFakeCurrentTime(prefs)); final Uri episodesOfShowUri = Episodes.buildEpisodesOfShowUri(showId); // unwatched, aired episodes final Cursor unwatched = resolver.query(episodesOfShowUri, UnwatchedQuery.PROJECTION, UnwatchedQuery.AIRED_SELECTION + Episodes.SELECTION_NOSPECIALS, new String[] { "0", "-1", fakenow }, null); if (unwatched == null) { return -1; } final int count = unwatched.getCount(); unwatched.close(); return count; } /** * Returns how many episodes of a show are left to collect. */ public static int getUncollectedEpisodesOfShow(Context context, String showId) { if (context == null) { return -1; } final ContentResolver resolver = context.getContentResolver(); final Uri episodesOfShowUri = Episodes.buildEpisodesOfShowUri(showId); // unwatched, aired episodes final Cursor uncollected = resolver.query(episodesOfShowUri, new String[] { Episodes._ID, Episodes.COLLECTED }, Episodes.COLLECTED + "=0", null, null); if (uncollected == null) { return -1; } final int count = uncollected.getCount(); uncollected.close(); return count; } /** * Calls {@code getUpcomingEpisodes(false, context)}. * * @param context * @return */ public static Cursor getUpcomingEpisodes(Context context) { return getUpcomingEpisodes(false, context); } /** * Returns all episodes that air today or later. Using Pacific Time to * determine today. Excludes shows that are hidden. * * @return Cursor using the projection of {@link UpcomingQuery}. */ public static Cursor getUpcomingEpisodes(boolean isOnlyUnwatched, Context context) { String[][] args = buildActivityQuery(context, ActivityType.UPCOMING, isOnlyUnwatched, -1); return context.getContentResolver().query(Episodes.CONTENT_URI_WITHSHOW, UpcomingQuery.PROJECTION, args[0][0], args[1], args[2][0]); } /** * Return all episodes that aired the day before and earlier. Using Pacific * Time to determine today. Excludes shows that are hidden. * * @return Cursor using the projection of {@link UpcomingQuery}. */ public static Cursor getRecentEpisodes(boolean isOnlyUnwatched, Context context) { String[][] args = buildActivityQuery(context, ActivityType.RECENT, isOnlyUnwatched, -1); return context.getContentResolver().query(Episodes.CONTENT_URI_WITHSHOW, UpcomingQuery.PROJECTION, args[0][0], args[1], args[2][0]); } /** * Returns an array of size 3. The built query is stored in {@code [0][0]}, * the built selection args in {@code [1]} and the sort order in * {@code [2][0]}. * * @param type A {@link ActivityType}, defaults to UPCOMING. * @param numberOfDaysToInclude Limits the time range of returned episodes * to a number of days from today. If lower then 1 defaults to * infinity. */ public static String[][] buildActivityQuery(Context context, String type, int numberOfDaysToInclude) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean isNoWatched = prefs.getBoolean(SeriesGuidePreferences.KEY_NOWATCHED, false); return buildActivityQuery(context, type, isNoWatched, numberOfDaysToInclude); } private static String[][] buildActivityQuery(Context context, String type, boolean isOnlyUnwatched, int numberOfDaysToInclude) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); long fakeNow = Utils.getFakeCurrentTime(prefs); // go an hour back in time, so episodes move to recent one hour late long recentThreshold = fakeNow - DateUtils.HOUR_IN_MILLIS; String query; String[] selectionArgs; String sortOrder; long timeThreshold; if (ActivityType.RECENT.equals(type)) { query = UpcomingQuery.QUERY_RECENT; sortOrder = UpcomingQuery.SORTING_RECENT; if (numberOfDaysToInclude < 1) { // at least has an air date timeThreshold = 0; } else { // last x days timeThreshold = System.currentTimeMillis() - DateUtils.DAY_IN_MILLIS * numberOfDaysToInclude; } } else { query = UpcomingQuery.QUERY_UPCOMING; sortOrder = UpcomingQuery.SORTING_UPCOMING; if (numberOfDaysToInclude < 1) { // to infinity! timeThreshold = Long.MAX_VALUE; } else { timeThreshold = System.currentTimeMillis() + DateUtils.DAY_IN_MILLIS * numberOfDaysToInclude; } } selectionArgs = new String[] { String.valueOf(recentThreshold), String.valueOf(timeThreshold) }; // append only favorites selection if necessary boolean isOnlyFavorites = ActivitySettings.isOnlyFavorites(context); if (isOnlyFavorites) { query += Shows.SELECTION_FAVORITES; } // append no specials selection if necessary boolean isNoSpecials = ActivitySettings.isHidingSpecials(context); if (isNoSpecials) { query += Episodes.SELECTION_NOSPECIALS; } // append unwatched selection if necessary if (isOnlyUnwatched) { query += Episodes.SELECTION_NOWATCHED; } // build result array String[][] results = new String[3][]; results[0] = new String[] { query }; results[1] = selectionArgs; results[2] = new String[] { sortOrder }; return results; } /** * Marks the next episode (if there is one) of the given show as watched. * Submits it to trakt if possible. * * @param showId */ public static void markNextEpisode(Context context, int showId, int episodeId) { if (episodeId > 0) { Cursor episode = context.getContentResolver().query( Episodes.buildEpisodeUri(String.valueOf(episodeId)), new String[] { Episodes.SEASON, Episodes.NUMBER }, null, null, null); if (episode != null) { if (episode.moveToFirst()) { new FlagTask(context, showId) .episodeWatched(episodeId, episode.getInt(0), episode.getInt(1), true) .execute(); } episode.close(); } } } private static final String[] SHOW_PROJECTION = new String[] { Shows._ID, Shows.ACTORS, Shows.AIRSDAYOFWEEK, Shows.AIRSTIME, Shows.CONTENTRATING, Shows.FIRSTAIRED, Shows.GENRES, Shows.NETWORK, Shows.OVERVIEW, Shows.POSTER, Shows.RATING, Shows.RUNTIME, Shows.TITLE, Shows.STATUS, Shows.IMDBID, Shows.NEXTEPISODE, Shows.LASTEDIT }; /** * Returns a {@link Series} object. Might return {@code null} if there is no * show with that TVDb id. */ public static Series getShow(Context context, int showTvdbId) { Cursor details = context.getContentResolver().query(Shows.buildShowUri(showTvdbId), SHOW_PROJECTION, null, null, null); + Series show = null; if (details != null) { if (details.moveToFirst()) { - Series show = new Series(); + show = new Series(); show.setId(details.getString(0)); show.setActors(details.getString(1)); show.setAirsDayOfWeek(details.getString(2)); show.setAirsTime(details.getLong(3)); show.setContentRating(details.getString(4)); show.setFirstAired(details.getString(5)); show.setGenres(details.getString(6)); show.setNetwork(details.getString(7)); show.setOverview(details.getString(8)); show.setPoster(details.getString(9)); show.setRating(details.getString(10)); show.setRuntime(details.getString(11)); show.setTitle(details.getString(12)); show.setStatus(details.getInt(13)); show.setImdbId(details.getString(14)); show.setNextEpisode(details.getLong(15)); show.setLastEdit(details.getLong(16)); - - return show; } details.close(); } - return null; + return show; } public static boolean isShowExists(String showId, Context context) { Cursor testsearch = context.getContentResolver().query(Shows.buildShowUri(showId), new String[] { Shows._ID }, null, null, null); boolean isShowExists = testsearch.getCount() != 0 ? true : false; testsearch.close(); return isShowExists; } /** * Builds a {@link ContentProviderOperation} for inserting or updating a * show (depending on {@code isNew}. * * @param show * @param context * @param isNew * @return */ public static ContentProviderOperation buildShowOp(Show show, Context context, boolean isNew) { ContentValues values = new ContentValues(); values = putCommonShowValues(show, values); if (isNew) { values.put(Shows._ID, show.tvdbId); return ContentProviderOperation.newInsert(Shows.CONTENT_URI).withValues(values).build(); } else { return ContentProviderOperation .newUpdate(Shows.buildShowUri(String.valueOf(show.tvdbId))) .withValues(values).build(); } } /** * Transforms a {@link Show} objects attributes into {@link ContentValues} * using the correct {@link Shows} columns. */ private static ContentValues putCommonShowValues(Show show, ContentValues values) { values.put(Shows.TITLE, show.title); values.put(Shows.OVERVIEW, show.overview); values.put(Shows.ACTORS, show.actors); values.put(Shows.AIRSDAYOFWEEK, show.airday); values.put(Shows.AIRSTIME, show.airtime); values.put(Shows.FIRSTAIRED, show.firstAired); values.put(Shows.GENRES, show.genres); values.put(Shows.NETWORK, show.network); values.put(Shows.RATING, show.rating); values.put(Shows.RUNTIME, show.runtime); values.put(Shows.CONTENTRATING, show.contentRating); values.put(Shows.POSTER, show.poster); values.put(Shows.IMDBID, show.imdbId); values.put(Shows.LASTEDIT, show.lastEdited); values.put(Shows.LASTUPDATED, System.currentTimeMillis()); int status; if (ShowStatusExport.CONTINUING.equals(show.status)) { status = ShowStatus.CONTINUING; } else if (ShowStatusExport.ENDED.equals(show.status)) { status = ShowStatus.ENDED; } else { status = ShowStatus.UNKNOWN; } values.put(Shows.STATUS, status); return values; } /** * Delete a show and manually delete its seasons and episodes. Also cleans * up the poster and images. * * @param context * @param showId * @param progress */ public static void deleteShow(Context context, String showId, ProgressDialog progress) { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); final ImageProvider imageProvider = ImageProvider.getInstance(context); // get poster path of show final Cursor poster = context.getContentResolver().query(Shows.buildShowUri(showId), new String[] { Shows.POSTER }, null, null, null); String posterPath = null; if (poster != null) { if (poster.moveToFirst()) { posterPath = poster.getString(0); } poster.close(); } batch.add(ContentProviderOperation.newDelete(Shows.buildShowUri(showId)).build()); // remove show entry already so we can hide the progress dialog try { context.getContentResolver() .applyBatch(SeriesGuideApplication.CONTENT_AUTHORITY, batch); } catch (RemoteException e) { // Failed binder transactions aren't recoverable throw new RuntimeException("Problem applying batch operation", e); } catch (OperationApplicationException e) { // Failures like constraint violation aren't recoverable throw new RuntimeException("Problem applying batch operation", e); } batch.clear(); // delete show poster if (posterPath != null) { imageProvider.removeImage(posterPath); } // delete episode images final Cursor episodes = context.getContentResolver().query( Episodes.buildEpisodesOfShowUri(showId), new String[] { Episodes._ID, Episodes.IMAGE }, null, null, null); if (episodes != null) { final String[] episodeIDs = new String[episodes.getCount()]; int counter = 0; episodes.moveToFirst(); while (!episodes.isAfterLast()) { episodeIDs[counter++] = episodes.getString(0); imageProvider.removeImage(episodes.getString(1)); episodes.moveToNext(); } episodes.close(); // delete search database entries for (String episodeID : episodeIDs) { batch.add(ContentProviderOperation.newDelete( EpisodeSearch.buildDocIdUri(String.valueOf(episodeID))).build()); } } batch.add(ContentProviderOperation.newDelete(Seasons.buildSeasonsOfShowUri(showId)).build()); batch.add(ContentProviderOperation.newDelete(Episodes.buildEpisodesOfShowUri(showId)) .build()); try { context.getContentResolver() .applyBatch(SeriesGuideApplication.CONTENT_AUTHORITY, batch); } catch (RemoteException e) { // Failed binder transactions aren't recoverable throw new RuntimeException("Problem applying batch operation", e); } catch (OperationApplicationException e) { // Failures like constraint violation aren't recoverable throw new RuntimeException("Problem applying batch operation", e); } // hide progress dialog now if (progress.isShowing()) { progress.dismiss(); } } /** * Returns the episode IDs and their last edit time for a given show as a * efficiently searchable HashMap. * * @return HashMap containing the shows existing episodes */ public static HashMap<Long, Long> getEpisodeMapForShow(Context context, int showTvdbId) { Cursor eptest = context.getContentResolver().query( Episodes.buildEpisodesOfShowUri(showTvdbId), new String[] { Episodes._ID, Episodes.LAST_EDITED }, null, null, null); HashMap<Long, Long> episodeMap = new HashMap<Long, Long>(); if (eptest != null) { while (eptest.moveToNext()) { episodeMap.put(eptest.getLong(0), eptest.getLong(1)); } eptest.close(); } return episodeMap; } /** * Returns the season IDs for a given show as a efficiently searchable * HashMap. * * @return HashMap containing the shows existing seasons */ public static HashSet<Long> getSeasonIDsForShow(Context context, int showTvdbId) { Cursor setest = context.getContentResolver().query( Seasons.buildSeasonsOfShowUri(showTvdbId), new String[] { Seasons._ID }, null, null, null); HashSet<Long> seasonIDs = new HashSet<Long>(); if (setest != null) { while (setest.moveToNext()) { seasonIDs.add(setest.getLong(0)); } setest.close(); } return seasonIDs; } /** * Creates an update {@link ContentProviderOperation} for the given episode * values. */ public static ContentProviderOperation buildEpisodeUpdateOp(ContentValues values) { final String episodeId = values.getAsString(Episodes._ID); ContentProviderOperation op = ContentProviderOperation .newUpdate(Episodes.buildEpisodeUri(episodeId)) .withValues(values).build(); return op; } /** * Creates a {@link ContentProviderOperation} for insert if isNew, or update * instead for with the given season values. * * @param values * @param isNew * @return */ public static ContentProviderOperation buildSeasonOp(ContentValues values, boolean isNew) { ContentProviderOperation op; final String seasonId = values.getAsString(Seasons.REF_SEASON_ID); final ContentValues seasonValues = new ContentValues(); seasonValues.put(Seasons.COMBINED, values.getAsString(Episodes.SEASON)); if (isNew) { seasonValues.put(Seasons._ID, seasonId); seasonValues.put(Shows.REF_SHOW_ID, values.getAsString(Shows.REF_SHOW_ID)); op = ContentProviderOperation.newInsert(Seasons.CONTENT_URI).withValues(seasonValues) .build(); } else { op = ContentProviderOperation.newUpdate(Seasons.buildSeasonUri(seasonId)) .withValues(seasonValues).build(); } return op; } /** * Convenience method for calling {@code updateLatestEpisode} once. If it is * going to be called multiple times, use the version which passes more * data. * * @param context * @param showId */ public static long updateLatestEpisode(Context context, String showId) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); final boolean isOnlyFutureEpisodes = prefs.getBoolean( SeriesGuidePreferences.KEY_ONLY_FUTURE_EPISODES, false); final boolean isNoSpecials = ActivitySettings.isHidingSpecials(context); return updateLatestEpisode(context, showId, isOnlyFutureEpisodes, isNoSpecials, prefs); } /** * Update the latest episode fields of the show where {@link Shows._ID} * equals the given {@code id}. * * @return The id of the calculated next episode. */ public static long updateLatestEpisode(Context context, String showId, boolean isOnlyFutureEpisodes, boolean isNoSpecials, SharedPreferences prefs) { final Uri episodesWithShow = Episodes.buildEpisodesOfShowUri(showId); final StringBuilder selectQuery = new StringBuilder(); // STEP 1: get last watched episode final Cursor show = context.getContentResolver().query(Shows.buildShowUri(showId), new String[] { Shows._ID, Shows.LASTWATCHEDID }, null, null, null); if (show == null || !show.moveToFirst()) { if (show != null) { show.close(); } return 0; } final String lastEpisodeId = show.getString(1); show.close(); final Cursor lastEpisode = context.getContentResolver().query( Episodes.buildEpisodeUri(lastEpisodeId), NextEpisodeQuery.PROJECTION_WATCHED, null, null, null); final String season; final String number; final String airtime; if (lastEpisode != null && lastEpisode.moveToFirst()) { season = lastEpisode.getString(NextEpisodeQuery.SEASON); number = lastEpisode.getString(NextEpisodeQuery.NUMBER); airtime = lastEpisode.getString(NextEpisodeQuery.FIRSTAIREDMS); } else { // no watched episodes, include all starting with // special 0 season = "-1"; number = "-1"; airtime = String.valueOf(Long.MIN_VALUE); } if (lastEpisode != null) { lastEpisode.close(); } // STEP 2: get episode airing closest afterwards or at the same time, // but with a higher number final String[] selectionArgs; selectQuery.delete(0, selectQuery.length()); selectQuery.append(NextEpisodeQuery.SELECT_NEXT); if (isNoSpecials) { // do not take specials into account selectQuery.append(Episodes.SELECTION_NOSPECIALS); } if (isOnlyFutureEpisodes) { // restrict to episodes with future air date selectQuery.append(NextEpisodeQuery.SELECT_ONLYFUTURE); final String now = String.valueOf(Utils.getFakeCurrentTime(prefs)); selectionArgs = new String[] { airtime, number, season, airtime, now }; } else { // restrict to episodes with any valid air date selectQuery.append(NextEpisodeQuery.SELECT_WITHAIRDATE); selectionArgs = new String[] { airtime, number, season, airtime }; } final Cursor next = context.getContentResolver().query(episodesWithShow, NextEpisodeQuery.PROJECTION_NEXT, selectQuery.toString(), selectionArgs, NextEpisodeQuery.SORTING_NEXT); // STEP 3: build and execute database update for show final long episodeId; final ContentValues update = new ContentValues(); if (next != null && next.moveToFirst()) { // next episode text, e.g. '0x12 Episode Name' final String nextEpisodeString = Utils.getNextEpisodeString(prefs, next.getInt(NextEpisodeQuery.SEASON), next.getInt(NextEpisodeQuery.NUMBER), next.getString(NextEpisodeQuery.TITLE)); // next air date text, e.g. 'Apr 2 (Mon)' final long airTime = next.getLong(NextEpisodeQuery.FIRSTAIREDMS); final String[] dayAndTimes = Utils.formatToTimeAndDay(airTime, context); final String nextAirdateString = dayAndTimes[2] + " (" + dayAndTimes[1] + ")"; episodeId = next.getLong(NextEpisodeQuery._ID); update.put(Shows.NEXTEPISODE, episodeId); update.put(Shows.NEXTAIRDATEMS, airTime); update.put(Shows.NEXTTEXT, nextEpisodeString); update.put(Shows.NEXTAIRDATETEXT, nextAirdateString); } else { episodeId = 0; update.put(Shows.NEXTEPISODE, ""); update.put(Shows.NEXTAIRDATEMS, UNKNOWN_NEXT_AIR_DATE); update.put(Shows.NEXTTEXT, ""); update.put(Shows.NEXTAIRDATETEXT, ""); } if (next != null) { next.close(); } // update the show with the new next episode values context.getContentResolver().update(Shows.buildShowUri(showId), update, null, null); return episodeId; } private interface NextEpisodeQuery { /** * Unwatched, airing later or has a different number or season if airing * the same time. */ String SELECT_NEXT = Episodes.WATCHED + "=0 AND (" + "(" + Episodes.FIRSTAIREDMS + "=? AND " + "(" + Episodes.NUMBER + "!=? OR " + Episodes.SEASON + "!=?)) " + "OR " + Episodes.FIRSTAIREDMS + ">?)"; String SELECT_WITHAIRDATE = " AND " + Episodes.FIRSTAIREDMS + "!=-1"; String SELECT_ONLYFUTURE = " AND " + Episodes.FIRSTAIREDMS + ">=?"; String[] PROJECTION_WATCHED = new String[] { Episodes._ID, Episodes.SEASON, Episodes.NUMBER, Episodes.FIRSTAIREDMS }; String[] PROJECTION_NEXT = new String[] { Episodes._ID, Episodes.SEASON, Episodes.NUMBER, Episodes.FIRSTAIREDMS, Episodes.TITLE }; /** * Air time, then lowest season, or if identical lowest episode number. */ String SORTING_NEXT = Episodes.FIRSTAIREDMS + " ASC," + Episodes.SEASON + " ASC," + Episodes.NUMBER + " ASC"; int _ID = 0; int SEASON = 1; int NUMBER = 2; int FIRSTAIREDMS = 3; int TITLE = 4; } }
false
false
null
null
diff --git a/src/main/java/org/thymeleaf/standard/inliner/AbstractStandardScriptingTextInliner.java b/src/main/java/org/thymeleaf/standard/inliner/AbstractStandardScriptingTextInliner.java index 779e6c44..61170457 100755 --- a/src/main/java/org/thymeleaf/standard/inliner/AbstractStandardScriptingTextInliner.java +++ b/src/main/java/org/thymeleaf/standard/inliner/AbstractStandardScriptingTextInliner.java @@ -1,309 +1,311 @@ /* * ============================================================================= * * Copyright (c) 2011-2012, The THYMELEAF team (http://www.thymeleaf.org) * * 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.thymeleaf.standard.inliner; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.thymeleaf.Arguments; import org.thymeleaf.TemplateEngine; import org.thymeleaf.dom.AbstractTextNode; import org.thymeleaf.exceptions.TemplateProcessingException; import org.thymeleaf.standard.expression.StandardExpressionProcessor; /** * * @author Daniel Fern&aacute;ndez * * @since 1.1.2 * */ public abstract class AbstractStandardScriptingTextInliner implements IStandardTextInliner { private final Logger logger = LoggerFactory.getLogger(this.getClass()); public static final String SCRIPT_ADD_INLINE_EVAL = "/\\*\\[\\+(.*?)\\+\\]\\*\\/"; public static final Pattern SCRIPT_ADD_INLINE_EVAL_PATTERN = Pattern.compile(SCRIPT_ADD_INLINE_EVAL, Pattern.DOTALL); public static final String SCRIPT_REMOVE_INLINE_EVAL = "\\/\\*\\[\\-(.*?)\\-\\]\\*\\/"; public static final Pattern SCRIPT_REMOVE_INLINE_EVAL_PATTERN = Pattern.compile(SCRIPT_REMOVE_INLINE_EVAL, Pattern.DOTALL); public static final String SCRIPT_VARIABLE_EXPRESSION_INLINE_EVAL = "\\/\\*(\\[\\[(.*?)\\]\\])\\*\\/([^\n]*?)\n"; public static final Pattern SCRIPT_VARIABLE_EXPRESSION_INLINE_EVAL_PATTERN = Pattern.compile(SCRIPT_VARIABLE_EXPRESSION_INLINE_EVAL, Pattern.DOTALL); public static final String SCRIPT_INLINE_EVAL = "\\[\\[(.*?)\\]\\]"; public static final Pattern SCRIPT_INLINE_EVAL_PATTERN = Pattern.compile(SCRIPT_INLINE_EVAL, Pattern.DOTALL); public static final String SCRIPT_INLINE_PREFIX = "[["; public static final String SCRIPT_INLINE_SUFFIX = "]]"; protected AbstractStandardScriptingTextInliner() { super(); } public final void inline(final Arguments arguments, final AbstractTextNode text) { final String content = text.getContent(); final String javascriptContent = processScriptingInline(content, arguments); text.setContent(javascriptContent); } private String processScriptingInline( final String input, final Arguments arguments) { return processScriptingVariableInline( processScriptingVariableExpressionInline( processScriptingAddInline( processScriptingRemoveInline( input) ) ), arguments); } private String processScriptingAddInline(final String input) { final Matcher matcher = SCRIPT_ADD_INLINE_EVAL_PATTERN.matcher(input); if (matcher.find()) { final StringBuilder strBuilder = new StringBuilder(); int curr = 0; do { strBuilder.append(input.substring(curr,matcher.start(0))); final String match = matcher.group(1); if (this.logger.isTraceEnabled()) { this.logger.trace("[THYMELEAF][{}] Adding inlined javascript text \"{}\"", TemplateEngine.threadIndex(), match); } strBuilder.append(match); curr = matcher.end(0); } while (matcher.find()); strBuilder.append(input.substring(curr)); return strBuilder.toString(); } return input; } private String processScriptingRemoveInline(final String input) { final Matcher matcher = SCRIPT_REMOVE_INLINE_EVAL_PATTERN.matcher(input); if (matcher.find()) { final StringBuilder strBuilder = new StringBuilder(); int curr = 0; do { strBuilder.append(input.substring(curr,matcher.start(0))); final String match = matcher.group(1); if (this.logger.isTraceEnabled()) { this.logger.trace("[THYMELEAF][{}] Removing inlined javascript text \"{}\"", TemplateEngine.threadIndex(), match); } curr = matcher.end(0); } while (matcher.find()); strBuilder.append(input.substring(curr)); return strBuilder.toString(); } return input; } private String processScriptingVariableExpressionInline(final String input) { final Matcher matcher = SCRIPT_VARIABLE_EXPRESSION_INLINE_EVAL_PATTERN.matcher(input); if (matcher.find()) { final StringBuilder strBuilder = new StringBuilder(); int curr = 0; do { strBuilder.append(input.substring(curr,matcher.start(0))); strBuilder.append(matcher.group(1)); strBuilder.append(computeLineEndForInline(matcher.group(3))); strBuilder.append('\n'); curr = matcher.end(0); } while (matcher.find()); strBuilder.append(input.substring(curr)); return strBuilder.toString(); } return input; } private static String computeLineEndForInline(final String lineRemainder) { if (lineRemainder == null) { return ""; } - boolean inLiteral = false; + char literalDelimiter = 0; int arrayLevel = 0; int objectLevel = 0; final int len = lineRemainder.length(); for (int i = 0; i < len; i++) { final char c = lineRemainder.charAt(i); - if (c == '\'') { - if (!inLiteral || i == 0 || lineRemainder.charAt(i - 1) != '\\') { - inLiteral = !inLiteral; + if (c == '\'' || c == '"') { + if (literalDelimiter == 0 || i == 0) { + literalDelimiter = c; + } else if (c == literalDelimiter && lineRemainder.charAt(i - 1) != '\\') { + literalDelimiter = 0; } - } else if (c == '{' && !inLiteral) { + } else if (c == '{' && literalDelimiter == 0) { objectLevel++; - } else if (c == '}' && !inLiteral) { + } else if (c == '}' && literalDelimiter == 0) { objectLevel--; - } else if (c == '[' && !inLiteral) { + } else if (c == '[' && literalDelimiter == 0) { arrayLevel++; - } else if (c == ']' && !inLiteral) { + } else if (c == ']' && literalDelimiter == 0) { arrayLevel--; } - if (!inLiteral && arrayLevel == 0 && objectLevel == 0) { + if (literalDelimiter == 0 && arrayLevel == 0 && objectLevel == 0) { if (c == ';' || c == ',') { return lineRemainder.substring(i); } if (c == '/' && ((i+1) < len)) { final char c1 = lineRemainder.charAt(i+1); if (c1 == '/' || c1 == '*') { return lineRemainder.substring(i); } } } } return ""; } private String processScriptingVariableInline(final String input, final Arguments arguments) { final Matcher matcher = SCRIPT_INLINE_EVAL_PATTERN.matcher(input); if (matcher.find()) { final StringBuilder strBuilder = new StringBuilder(); int curr = 0; do { strBuilder.append(input.substring(curr,matcher.start(0))); final String match = matcher.group(1); if (this.logger.isTraceEnabled()) { this.logger.trace("[THYMELEAF][{}] Applying javascript variable inline evaluation on \"{}\"", TemplateEngine.threadIndex(), match); } try { final Object result = StandardExpressionProcessor.processExpression(arguments, match); strBuilder.append(formatEvaluationResult(result)); } catch (final TemplateProcessingException ignored) { // If it is not a standard expression, just output it as original strBuilder.append(SCRIPT_INLINE_PREFIX).append(match).append(SCRIPT_INLINE_SUFFIX); } curr = matcher.end(0); } while (matcher.find()); strBuilder.append(input.substring(curr)); return strBuilder.toString(); } return input; } protected abstract String formatEvaluationResult(final Object result); }
false
false
null
null
diff --git a/src/org/mozilla/javascript/MemberBox.java b/src/org/mozilla/javascript/MemberBox.java index 32841978..4c6f997c 100644 --- a/src/org/mozilla/javascript/MemberBox.java +++ b/src/org/mozilla/javascript/MemberBox.java @@ -1,351 +1,345 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * The contents of this file are subject to the Netscape Public * License Version 1.1 (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.mozilla.org/NPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is Netscape * Communications Corporation. Portions created by Netscape are * Copyright (C) 1997-1999 Netscape Communications Corporation. All * Rights Reserved. * * Contributor(s): * Igor Bukanov * Felix Meschberger * * Alternatively, the contents of this file may be used under the * terms of the GNU Public License (the "GPL"), in which case the * provisions of the GPL are applicable instead of those above. * If you wish to allow use of your version of this file only * under the terms of the GPL and not to allow others to use your * version of this file under the NPL, indicate your decision by * deleting the provisions above and replace them with the notice * and other provisions required by the GPL. If you do not delete * the provisions above, a recipient may use your version of this * file under either the NPL or the GPL. */ package org.mozilla.javascript; import java.lang.reflect.*; import java.io.*; /** * Wrappper class for Method and Constructor instances to cache * getParameterTypes() results, recover from IllegalAccessException * in some cases and provide serialization support. * * @author Igor Bukanov */ final class MemberBox implements Serializable { MemberBox(Method method) { init(method); } MemberBox(Constructor constructor) { init(constructor); } private void init(Method method) { this.memberObject = method; this.argTypes = method.getParameterTypes(); } private void init(Constructor constructor) { this.memberObject = constructor; this.argTypes = constructor.getParameterTypes(); } Method method() { return (Method)memberObject; } Constructor ctor() { return (Constructor)memberObject; } boolean isMethod() { return memberObject instanceof Method; } boolean isCtor() { return memberObject instanceof Constructor; } boolean isStatic() { return Modifier.isStatic(memberObject.getModifiers()); } String getName() { return memberObject.getName(); } Class getDeclaringClass() { return memberObject.getDeclaringClass(); } String toJavaDeclaration() { StringBuffer sb = new StringBuffer(); if (isMethod()) { Method method = method(); sb.append(method.getReturnType()); sb.append(' '); sb.append(method.getName()); } else { Constructor ctor = ctor(); String name = ctor.getDeclaringClass().getName(); int lastDot = name.lastIndexOf('.'); if (lastDot >= 0) { name = name.substring(lastDot + 1); } sb.append(name); } sb.append(JavaMembers.liveConnectSignature(argTypes)); return sb.toString(); } public String toString() { return memberObject.toString(); } Object invoke(Object target, Object[] args) { Method method = method(); try { try { return method.invoke(target, args); } catch (IllegalAccessException ex) { Method accessible = searchAccessibleMethod(method, argTypes); if (accessible != null) { memberObject = accessible; method = accessible; } else { if (!VMBridge.instance.tryToMakeAccessible(method)) { throw Context.throwAsScriptRuntimeEx(ex); } } // Retry after recovery return method.invoke(target, args); } - } catch (IllegalAccessException ex) { - throw Context.throwAsScriptRuntimeEx(ex); - } catch (InvocationTargetException ex) { + } catch (Exception ex) { throw Context.throwAsScriptRuntimeEx(ex); } } Object newInstance(Object[] args) { Constructor ctor = ctor(); try { try { return ctor.newInstance(args); } catch (IllegalAccessException ex) { if (!VMBridge.instance.tryToMakeAccessible(ctor)) { throw Context.throwAsScriptRuntimeEx(ex); } } return ctor.newInstance(args); - } catch (IllegalAccessException ex) { - throw Context.throwAsScriptRuntimeEx(ex); - } catch (InvocationTargetException ex) { - throw Context.throwAsScriptRuntimeEx(ex); - } catch (InstantiationException ex) { + } catch (Exception ex) { throw Context.throwAsScriptRuntimeEx(ex); } } private static Method searchAccessibleMethod(Method method, Class[] params) { int modifiers = method.getModifiers(); if (Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers)) { Class c = method.getDeclaringClass(); if (!Modifier.isPublic(c.getModifiers())) { String name = method.getName(); Class[] intfs = c.getInterfaces(); for (int i = 0, N = intfs.length; i != N; ++i) { Class intf = intfs[i]; if (Modifier.isPublic(intf.getModifiers())) { try { return intf.getMethod(name, params); } catch (NoSuchMethodException ex) { } catch (SecurityException ex) { } } } for (;;) { c = c.getSuperclass(); if (c == null) { break; } if (Modifier.isPublic(c.getModifiers())) { try { Method m = c.getMethod(name, params); int mModifiers = m.getModifiers(); if (Modifier.isPublic(mModifiers) && !Modifier.isStatic(mModifiers)) { return m; } } catch (NoSuchMethodException ex) { } catch (SecurityException ex) { } } } } } return null; } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); Member member = readMember(in); if (member instanceof Method) { init((Method)member); } else { init((Constructor)member); } } private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); writeMember(out, memberObject); } /** * Writes a Constructor or Method object. * * Methods and Constructors are not serializable, so we must serialize * information about the class, the name, and the parameters and * recreate upon deserialization. */ private static void writeMember(ObjectOutputStream out, Member member) throws IOException { if (member == null) { out.writeBoolean(false); return; } out.writeBoolean(true); if (!(member instanceof Method || member instanceof Constructor)) throw new IllegalArgumentException("not Method or Constructor"); out.writeBoolean(member instanceof Method); out.writeObject(member.getName()); out.writeObject(member.getDeclaringClass()); if (member instanceof Method) { writeParameters(out, ((Method) member).getParameterTypes()); } else { writeParameters(out, ((Constructor) member).getParameterTypes()); } } /** * Reads a Method or a Constructor from the stream. */ private static Member readMember(ObjectInputStream in) throws IOException, ClassNotFoundException { if (!in.readBoolean()) return null; boolean isMethod = in.readBoolean(); String name = (String) in.readObject(); Class declaring = (Class) in.readObject(); Class[] parms = readParameters(in); try { if (isMethod) { return declaring.getMethod(name, parms); } else { return declaring.getConstructor(parms); } } catch (NoSuchMethodException e) { throw new IOException("Cannot find member: " + e); } } private static final Class[] primitives = { Boolean.TYPE, Byte.TYPE, Character.TYPE, Double.TYPE, Float.TYPE, Integer.TYPE, Long.TYPE, Short.TYPE, Void.TYPE }; /** * Writes an array of parameter types to the stream. * * Requires special handling because primitive types cannot be * found upon deserialization by the default Java implementation. */ private static void writeParameters(ObjectOutputStream out, Class[] parms) throws IOException { out.writeShort(parms.length); outer: for (int i=0; i < parms.length; i++) { Class parm = parms[i]; out.writeBoolean(parm.isPrimitive()); if (!parm.isPrimitive()) { out.writeObject(parm); continue; } for (int j=0; j < primitives.length; j++) { if (parm.equals(primitives[j])) { out.writeByte(j); continue outer; } } throw new IllegalArgumentException("Primitive " + parm + " not found"); } } /** * Reads an array of parameter types from the stream. */ private static Class[] readParameters(ObjectInputStream in) throws IOException, ClassNotFoundException { Class[] result = new Class[in.readShort()]; for (int i=0; i < result.length; i++) { if (!in.readBoolean()) { result[i] = (Class) in.readObject(); continue; } result[i] = primitives[in.readByte()]; } return result; } private transient Member memberObject; transient Class[] argTypes; }
false
false
null
null
diff --git a/sonar-surefire-plugin/src/test/java/org/sonar/plugins/surefire/SurefireJavaParserTest.java b/sonar-surefire-plugin/src/test/java/org/sonar/plugins/surefire/SurefireJavaParserTest.java index a470c0ab6..805f49da2 100644 --- a/sonar-surefire-plugin/src/test/java/org/sonar/plugins/surefire/SurefireJavaParserTest.java +++ b/sonar-surefire-plugin/src/test/java/org/sonar/plugins/surefire/SurefireJavaParserTest.java @@ -1,88 +1,90 @@ /* * Sonar Java * Copyright (C) 2012 SonarSource * dev@sonar.codehaus.org * * This program 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.surefire; import org.junit.Before; import org.junit.Test; import org.sonar.api.batch.SensorContext; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.resources.Project; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.Resource; import org.sonar.api.resources.Scopes; import org.sonar.api.test.IsMeasure; import org.sonar.api.test.IsResource; import org.sonar.api.tests.ProjectTests; import java.net.URISyntaxException; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyDouble; import static org.mockito.Matchers.argThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class SurefireJavaParserTest { private ProjectTests projectTests; private SurefireJavaParser parser; @Before public void before() { projectTests = mock(ProjectTests.class); parser = new SurefireJavaParser(projectTests); } @Test - public void shouldAggregateReports() throws URISyntaxException { + public void should_aggregate_reports() throws URISyntaxException { SensorContext context = mockContext(); parser.collect(new Project("foo"), context, getDir("multipleReports")); // Only 6 tests measures should be stored, no more: the TESTS-AllTests.xml must not be read as there's 1 file result per unit test // (SONAR-2841). verify(context, times(6)).saveMeasure(argThat(new IsResource(Scopes.FILE, Qualifiers.UNIT_TEST_FILE)), eq(CoreMetrics.TESTS), anyDouble()); verify(context, times(6)).saveMeasure(argThat(new IsResource(Scopes.FILE, Qualifiers.UNIT_TEST_FILE)), eq(CoreMetrics.TEST_ERRORS), anyDouble()); verify(context, times(6)).saveMeasure(argThat(new IsResource(Scopes.FILE, Qualifiers.UNIT_TEST_FILE)), argThat(new IsMeasure(CoreMetrics.TEST_DATA))); } @Test - public void shouldRegisterTests() throws URISyntaxException { + public void should_register_tests() throws URISyntaxException { SensorContext context = mockContext(); parser.collect(new Project("foo"), context, getDir("multipleReports")); - verify(projectTests).addTest("ch.hortis.sonar.mvn.mc.MetricsCollectorRegistryTest", new org.sonar.api.tests.Test("testGetUnKnownCollector")); - verify(projectTests).addTest("ch.hortis.sonar.mvn.mc.MetricsCollectorRegistryTest", new org.sonar.api.tests.Test("testGetJDependsCollector")); + verify(projectTests).addTest("ch.hortis.sonar.mvn.mc.MetricsCollectorRegistryTest", + new org.sonar.api.tests.Test("testGetUnKnownCollector").setStatus("ok").setDurationMilliseconds(35)); + verify(projectTests).addTest("ch.hortis.sonar.mvn.mc.MetricsCollectorRegistryTest", + new org.sonar.api.tests.Test("testGetJDependsCollector").setStatus("ok").setDurationMilliseconds(35)); } private java.io.File getDir(String dirname) throws URISyntaxException { return new java.io.File(getClass().getResource("/org/sonar/plugins/surefire/api/AbstractSurefireParserTest/" + dirname).toURI()); } private SensorContext mockContext() { SensorContext context = mock(SensorContext.class); when(context.isIndexed(any(Resource.class), eq(false))).thenReturn(true); return context; } }
false
false
null
null
diff --git a/framework/src/org/apache/cordova/DroidGap.java b/framework/src/org/apache/cordova/DroidGap.java index a9efc93e..bb895e25 100755 --- a/framework/src/org/apache/cordova/DroidGap.java +++ b/framework/src/org/apache/cordova/DroidGap.java @@ -1,1156 +1,1156 @@ /* 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.cordova; import java.util.HashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.cordova.api.CordovaInterface; import org.apache.cordova.api.CordovaPlugin; import org.apache.cordova.api.LOG; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.graphics.Color; import android.media.AudioManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.Display; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.ImageView; import android.webkit.ValueCallback; import android.webkit.WebViewClient; import android.widget.LinearLayout; /** * This class is the main Android activity that represents the Cordova * application. It should be extended by the user to load the specific * html file that contains the application. * * As an example: * * package org.apache.cordova.examples; * import android.app.Activity; * import android.os.Bundle; * import org.apache.cordova.*; * * public class Examples extends DroidGap { * @Override * public void onCreate(Bundle savedInstanceState) { * super.onCreate(savedInstanceState); * * // Set properties for activity * super.setStringProperty("loadingDialog", "Title,Message"); // show loading dialog * super.setStringProperty("errorUrl", "file:///android_asset/www/error.html"); // if error loading file in super.loadUrl(). * * // Initialize activity * super.init(); * * // Clear cache if you want * super.appView.clearCache(true); * * // Load your application * super.setIntegerProperty("splashscreen", R.drawable.splash); // load splash.jpg image from the resource drawable directory * super.loadUrl("file:///android_asset/www/index.html", 3000); // show splash screen 3 sec before loading app * } * } * * Properties: The application can be configured using the following properties: * * // Display a native loading dialog when loading app. Format for value = "Title,Message". * // (String - default=null) * super.setStringProperty("loadingDialog", "Wait,Loading Demo..."); * * // Display a native loading dialog when loading sub-pages. Format for value = "Title,Message". * // (String - default=null) * super.setStringProperty("loadingPageDialog", "Loading page..."); * * // Load a splash screen image from the resource drawable directory. * // (Integer - default=0) * super.setIntegerProperty("splashscreen", R.drawable.splash); * * // Set the background color. * // (Integer - default=0 or BLACK) * super.setIntegerProperty("backgroundColor", Color.WHITE); * * // Time in msec to wait before triggering a timeout error when loading * // with super.loadUrl(). (Integer - default=20000) * super.setIntegerProperty("loadUrlTimeoutValue", 60000); * * // URL to load if there's an error loading specified URL with loadUrl(). * // Should be a local URL starting with file://. (String - default=null) * super.setStringProperty("errorUrl", "file:///android_asset/www/error.html"); * * // Enable app to keep running in background. (Boolean - default=true) * super.setBooleanProperty("keepRunning", false); * * Cordova.xml configuration: * Cordova uses a configuration file at res/xml/cordova.xml to specify the following settings. * * Approved list of URLs that can be loaded into DroidGap * <access origin="http://server regexp" subdomains="true" /> * Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR) * <log level="DEBUG" /> * * Cordova plugins: * Cordova uses a file at res/xml/plugins.xml to list all plugins that are installed. * Before using a new plugin, a new element must be added to the file. * name attribute is the service name passed to Cordova.exec() in JavaScript * value attribute is the Java class name to call. * * <plugins> * <plugin name="App" value="org.apache.cordova.App"/> * ... * </plugins> */ public class DroidGap extends Activity implements CordovaInterface { public static String TAG = "DroidGap"; // The webview for our app protected CordovaWebView appView; protected CordovaWebViewClient webViewClient; protected LinearLayout root; protected boolean cancelLoadUrl = false; protected ProgressDialog spinnerDialog = null; private final ExecutorService threadPool = Executors.newCachedThreadPool(); // The initial URL for our app // ie http://server/path/index.html#abc?query //private String url = null; private static int ACTIVITY_STARTING = 0; private static int ACTIVITY_RUNNING = 1; private static int ACTIVITY_EXITING = 2; private int activityState = 0; // 0=starting, 1=running (after 1st resume), 2=shutting down // Plugin to call when activity result is received protected CordovaPlugin activityResultCallback = null; protected boolean activityResultKeepRunning; // Default background color for activity // (this is not the color for the webview, which is set in HTML) private int backgroundColor = Color.BLACK; /* * The variables below are used to cache some of the activity properties. */ // Draw a splash screen using an image located in the drawable resource directory. // This is not the same as calling super.loadSplashscreen(url) protected int splashscreen = 0; protected int splashscreenTime = 3000; // LoadUrl timeout value in msec (default of 20 sec) protected int loadUrlTimeoutValue = 20000; // Keep app running when pause is received. (default = true) // If true, then the JavaScript and native code continue to run in the background // when another application (activity) is started. protected boolean keepRunning = true; private int lastRequestCode; private Object responseCode; private Intent lastIntent; private Object lastResponseCode; private String initCallbackClass; private Object LOG_TAG; /** * Sets the authentication token. * * @param authenticationToken * @param host * @param realm */ public void setAuthenticationToken(AuthenticationToken authenticationToken, String host, String realm) { if (this.appView != null && this.appView.viewClient != null) { this.appView.viewClient.setAuthenticationToken(authenticationToken, host, realm); } } /** * Removes the authentication token. * * @param host * @param realm * * @return the authentication token or null if did not exist */ public AuthenticationToken removeAuthenticationToken(String host, String realm) { if (this.appView != null && this.appView.viewClient != null) { return this.appView.viewClient.removeAuthenticationToken(host, realm); } return null; } /** * Gets the authentication token. * * In order it tries: * 1- host + realm * 2- host * 3- realm * 4- no host, no realm * * @param host * @param realm * * @return the authentication token */ public AuthenticationToken getAuthenticationToken(String host, String realm) { if (this.appView != null && this.appView.viewClient != null) { return this.appView.viewClient.getAuthenticationToken(host, realm); } return null; } /** * Clear all authentication tokens. */ public void clearAuthenticationTokens() { if (this.appView != null && this.appView.viewClient != null) { this.appView.viewClient.clearAuthenticationTokens(); } } /** * Called when the activity is first created. * * @param savedInstanceState */ @SuppressWarnings("deprecation") @Override public void onCreate(Bundle savedInstanceState) { Config.init(this); LOG.d(TAG, "DroidGap.onCreate()"); super.onCreate(savedInstanceState); if(savedInstanceState != null) { initCallbackClass = savedInstanceState.getString("callbackClass"); } if(!this.getBooleanProperty("showTitle", false)) { getWindow().requestFeature(Window.FEATURE_NO_TITLE); } if(this.getBooleanProperty("setFullscreen", false)) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); } // This builds the view. We could probably get away with NOT having a LinearLayout, but I like having a bucket! Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight(); root = new LinearLayoutSoftKeyboardDetect(this, width, height); root.setOrientation(LinearLayout.VERTICAL); root.setBackgroundColor(this.backgroundColor); root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0F)); // Setup the hardware volume controls to handle volume control setVolumeControlStream(AudioManager.STREAM_MUSIC); } /** * Get the Android activity. * * @return */ public Activity getActivity() { return this; } /** * Create and initialize web container with default web view objects. */ public void init() { CordovaWebView webView = new CordovaWebView(DroidGap.this); CordovaWebViewClient webViewClient; if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { webViewClient = new CordovaWebViewClient(this, webView); } else { webViewClient = new IceCreamCordovaWebViewClient(this, webView); } this.init(webView, webViewClient, new CordovaChromeClient(this, webView)); } /** * Initialize web container with web view objects. * * @param webView * @param webViewClient * @param webChromeClient */ @SuppressLint("NewApi") public void init(CordovaWebView webView, CordovaWebViewClient webViewClient, CordovaChromeClient webChromeClient) { LOG.d(TAG, "DroidGap.init()"); // Set up web container this.appView = webView; this.appView.setId(100); this.appView.setWebViewClient(webViewClient); this.appView.setWebChromeClient(webChromeClient); webViewClient.setWebView(this.appView); webChromeClient.setWebView(this.appView); this.appView.setLayoutParams(new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0F)); if (this.getBooleanProperty("disallowOverscroll", false)) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) { this.appView.setOverScrollMode(CordovaWebView.OVER_SCROLL_NEVER); } } // Add web view but make it invisible while loading URL this.appView.setVisibility(View.INVISIBLE); this.root.addView(this.appView); setContentView(this.root); // Clear cancel flag this.cancelLoadUrl = false; } /** * Load the url into the webview. * * @param url */ public void loadUrl(String url) { // Init web view if not already done if (this.appView == null) { this.init(); } // Set backgroundColor this.backgroundColor = this.getIntegerProperty("backgroundColor", Color.BLACK); this.root.setBackgroundColor(this.backgroundColor); // If keepRunning this.keepRunning = this.getBooleanProperty("keepRunning", true); // Then load the spinner this.loadSpinner(); this.appView.loadUrl(url); } /* * Load the spinner */ void loadSpinner() { // If loadingDialog property, then show the App loading dialog for first page of app String loading = null; if ((this.appView == null) || !this.appView.canGoBack()) { loading = this.getStringProperty("loadingDialog", null); } else { loading = this.getStringProperty("loadingPageDialog", null); } if (loading != null) { String title = ""; String message = "Loading Application..."; if (loading.length() > 0) { int comma = loading.indexOf(','); if (comma > 0) { title = loading.substring(0, comma); message = loading.substring(comma + 1); } else { title = ""; message = loading; } } this.spinnerStart(title, message); } } /** * Load the url into the webview after waiting for period of time. * This is used to display the splashscreen for certain amount of time. * * @param url * @param time The number of ms to wait before loading webview */ public void loadUrl(final String url, int time) { // Init web view if not already done if (this.appView == null) { this.init(); } this.splashscreenTime = time; this.splashscreen = this.getIntegerProperty("splashscreen", 0); this.showSplashScreen(this.splashscreenTime); this.appView.loadUrl(url, time); } /** * Cancel loadUrl before it has been loaded. */ // TODO NO-OP @Deprecated public void cancelLoadUrl() { this.cancelLoadUrl = true; } /** * Clear the resource cache. */ public void clearCache() { if (this.appView == null) { this.init(); } this.appView.clearCache(true); } /** * Clear web history in this web view. */ public void clearHistory() { this.appView.clearHistory(); } /** * Go to previous page in history. (We manage our own history) * * @return true if we went back, false if we are already at top */ public boolean backHistory() { if (this.appView != null) { return appView.backHistory(); } return false; } @Override /** * Called by the system when the device configuration changes while your activity is running. * * @param Configuration newConfig */ public void onConfigurationChanged(Configuration newConfig) { //don't reload the current page when the orientation is changed super.onConfigurationChanged(newConfig); } /** * Get boolean property for activity. * * @param name * @param defaultValue * @return */ public boolean getBooleanProperty(String name, boolean defaultValue) { Bundle bundle = this.getIntent().getExtras(); if (bundle == null) { return defaultValue; } Boolean p; try { p = (Boolean) bundle.get(name); } catch (ClassCastException e) { String s = bundle.get(name).toString(); if ("true".equals(s)) { p = true; } else { p = false; } } if (p == null) { return defaultValue; } return p.booleanValue(); } /** * Get int property for activity. * * @param name * @param defaultValue * @return */ public int getIntegerProperty(String name, int defaultValue) { Bundle bundle = this.getIntent().getExtras(); if (bundle == null) { return defaultValue; } Integer p; try { p = (Integer) bundle.get(name); } catch (ClassCastException e) { p = Integer.parseInt(bundle.get(name).toString()); } if (p == null) { return defaultValue; } return p.intValue(); } /** * Get string property for activity. * * @param name * @param defaultValue * @return */ public String getStringProperty(String name, String defaultValue) { Bundle bundle = this.getIntent().getExtras(); if (bundle == null) { return defaultValue; } String p = bundle.getString(name); if (p == null) { return defaultValue; } return p; } /** * Get double property for activity. * * @param name * @param defaultValue * @return */ public double getDoubleProperty(String name, double defaultValue) { Bundle bundle = this.getIntent().getExtras(); if (bundle == null) { return defaultValue; } Double p; try { p = (Double) bundle.get(name); } catch (ClassCastException e) { p = Double.parseDouble(bundle.get(name).toString()); } if (p == null) { return defaultValue; } return p.doubleValue(); } /** * Set boolean property on activity. * * @param name * @param value */ public void setBooleanProperty(String name, boolean value) { Log.d(TAG, "Setting boolean properties in DroidGap will be deprecated in 3.0 on July 2013, please use config.xml"); this.getIntent().putExtra(name, value); } /** * Set int property on activity. * * @param name * @param value */ public void setIntegerProperty(String name, int value) { Log.d(TAG, "Setting integer properties in DroidGap will be deprecated in 3.1 on August 2013, please use config.xml"); this.getIntent().putExtra(name, value); } /** * Set string property on activity. * * @param name * @param value */ public void setStringProperty(String name, String value) { Log.d(TAG, "Setting string properties in DroidGap will be deprecated in 3.0 on July 2013, please use config.xml"); this.getIntent().putExtra(name, value); } /** * Set double property on activity. * * @param name * @param value */ public void setDoubleProperty(String name, double value) { Log.d(TAG, "Setting double properties in DroidGap will be deprecated in 3.0 on July 2013, please use config.xml"); this.getIntent().putExtra(name, value); } @Override /** * Called when the system is about to start resuming a previous activity. */ protected void onPause() { super.onPause(); LOG.d(TAG, "Paused the application!"); // Don't process pause if shutting down, since onDestroy() will be called if (this.activityState == ACTIVITY_EXITING) { return; } if (this.appView == null) { return; } else { this.appView.handlePause(this.keepRunning); } // hide the splash screen to avoid leaking a window this.removeSplashScreen(); } @Override /** * Called when the activity receives a new intent **/ protected void onNewIntent(Intent intent) { super.onNewIntent(intent); //Forward to plugins if (this.appView != null) this.appView.onNewIntent(intent); } @Override /** * Called when the activity will start interacting with the user. */ protected void onResume() { super.onResume(); LOG.d(TAG, "Resuming the App"); if (this.activityState == ACTIVITY_STARTING) { this.activityState = ACTIVITY_RUNNING; return; } if (this.appView == null) { return; } this.appView.handleResume(this.keepRunning, this.activityResultKeepRunning); // If app doesn't want to run in background if (!this.keepRunning || this.activityResultKeepRunning) { // Restore multitasking state if (this.activityResultKeepRunning) { this.keepRunning = this.activityResultKeepRunning; this.activityResultKeepRunning = false; } } } @Override /** * The final call you receive before your activity is destroyed. */ public void onDestroy() { LOG.d(TAG, "onDestroy()"); super.onDestroy(); // hide the splash screen to avoid leaking a window this.removeSplashScreen(); if (this.appView != null) { appView.handleDestroy(); } else { - this.endActivity(); + this.activityState = ACTIVITY_EXITING; } } /** * Send a message to all plugins. * * @param id The message id * @param data The message data */ public void postMessage(String id, Object data) { if (this.appView != null) { this.appView.postMessage(id, data); } } /** * @deprecated * Add services to res/xml/plugins.xml instead. * * Add a class that implements a service. * * @param serviceType * @param className */ public void addService(String serviceType, String className) { if (this.appView != null && this.appView.pluginManager != null) { this.appView.pluginManager.addService(serviceType, className); } } /** * Send JavaScript statement back to JavaScript. * (This is a convenience method) * * @param message */ public void sendJavascript(String statement) { if (this.appView != null) { this.appView.jsMessageQueue.addJavaScript(statement); } } /** * Show the spinner. Must be called from the UI thread. * * @param title Title of the dialog * @param message The message of the dialog */ public void spinnerStart(final String title, final String message) { if (this.spinnerDialog != null) { this.spinnerDialog.dismiss(); this.spinnerDialog = null; } final DroidGap me = this; this.spinnerDialog = ProgressDialog.show(DroidGap.this, title, message, true, true, new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { me.spinnerDialog = null; } }); } /** * Stop spinner - Must be called from UI thread */ public void spinnerStop() { if (this.spinnerDialog != null && this.spinnerDialog.isShowing()) { this.spinnerDialog.dismiss(); this.spinnerDialog = null; } } /** * End this activity by calling finish for activity */ public void endActivity() { this.activityState = ACTIVITY_EXITING; super.finish(); } /** * Launch an activity for which you would like a result when it finished. When this activity exits, * your onActivityResult() method will be called. * * @param command The command object * @param intent The intent to start * @param requestCode The request code that is passed to callback to identify the activity */ public void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode) { this.activityResultCallback = command; this.activityResultKeepRunning = this.keepRunning; // If multitasking turned on, then disable it for activities that return results if (command != null) { this.keepRunning = false; } // Start activity super.startActivityForResult(intent, requestCode); } @Override /** * Called when an activity you launched exits, giving you the requestCode you started it with, * the resultCode it returned, and any additional data from it. * * @param requestCode The request code originally supplied to startActivityForResult(), * allowing you to identify who this result came from. * @param resultCode The integer result code returned by the child activity through its setResult(). * @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). */ protected void onActivityResult(int requestCode, int resultCode, Intent intent) { LOG.d(TAG, "Incoming Result"); super.onActivityResult(requestCode, resultCode, intent); Log.d(TAG, "Request code = " + requestCode); ValueCallback<Uri> mUploadMessage = this.appView.getWebChromeClient().getValueCallback(); if (requestCode == CordovaChromeClient.FILECHOOSER_RESULTCODE) { Log.d(TAG, "did we get here?"); if (null == mUploadMessage) return; Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData(); Log.d(TAG, "result = " + result); // Uri filepath = Uri.parse("file://" + FileUtils.getRealPathFromURI(result, this)); // Log.d(TAG, "result = " + filepath); mUploadMessage.onReceiveValue(result); mUploadMessage = null; } CordovaPlugin callback = this.activityResultCallback; if(callback == null) { if(initCallbackClass != null) { this.activityResultCallback = appView.pluginManager.getPlugin(initCallbackClass); callback = activityResultCallback; LOG.d(TAG, "We have a callback to send this result to"); callback.onActivityResult(requestCode, resultCode, intent); } } else { LOG.d(TAG, "We have a callback to send this result to"); callback.onActivityResult(requestCode, resultCode, intent); } } public void setActivityResultCallback(CordovaPlugin plugin) { this.activityResultCallback = plugin; } /** * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable). * The errorCode parameter corresponds to one of the ERROR_* constants. * * @param errorCode The error code corresponding to an ERROR_* value. * @param description A String describing the error. * @param failingUrl The url that failed to load. */ public void onReceivedError(final int errorCode, final String description, final String failingUrl) { final DroidGap me = this; // If errorUrl specified, then load it final String errorUrl = me.getStringProperty("errorUrl", null); if ((errorUrl != null) && (errorUrl.startsWith("file://") || Config.isUrlWhiteListed(errorUrl)) && (!failingUrl.equals(errorUrl))) { // Load URL on UI thread me.runOnUiThread(new Runnable() { public void run() { // Stop "app loading" spinner if showing me.spinnerStop(); me.appView.showWebPage(errorUrl, false, true, null); } }); } // If not, then display error dialog else { final boolean exit = !(errorCode == WebViewClient.ERROR_HOST_LOOKUP); me.runOnUiThread(new Runnable() { public void run() { if (exit) { me.appView.setVisibility(View.GONE); me.displayError("Application Error", description + " (" + failingUrl + ")", "OK", exit); } } }); } } /** * Display an error dialog and optionally exit application. * * @param title * @param message * @param button * @param exit */ public void displayError(final String title, final String message, final String button, final boolean exit) { final DroidGap me = this; me.runOnUiThread(new Runnable() { public void run() { try { AlertDialog.Builder dlg = new AlertDialog.Builder(me); dlg.setMessage(message); dlg.setTitle(title); dlg.setCancelable(false); dlg.setPositiveButton(button, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (exit) { me.endActivity(); } } }); dlg.create(); dlg.show(); } catch (Exception e) { finish(); } } }); } /** * Determine if URL is in approved list of URLs to load. * * @param url * @return */ public boolean isUrlWhiteListed(String url) { return Config.isUrlWhiteListed(url); } /* * Hook in DroidGap for menu plugins * */ @Override public boolean onCreateOptionsMenu(Menu menu) { this.postMessage("onCreateOptionsMenu", menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { this.postMessage("onPrepareOptionsMenu", menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { this.postMessage("onOptionsItemSelected", item); return true; } /** * Get Activity context. * * @return */ public Context getContext() { LOG.d(TAG, "This will be deprecated December 2012"); return this; } /** * Load the specified URL in the Cordova webview or a new browser instance. * * NOTE: If openExternal is false, only URLs listed in whitelist can be loaded. * * @param url The url to load. * @param openExternal Load url in browser instead of Cordova webview. * @param clearHistory Clear the history stack, so new page becomes top of history * @param params DroidGap parameters for new app */ public void showWebPage(String url, boolean openExternal, boolean clearHistory, HashMap<String, Object> params) { if (this.appView != null) { appView.showWebPage(url, openExternal, clearHistory, params); } } protected Dialog splashDialog; /** * Removes the Dialog that displays the splash screen */ public void removeSplashScreen() { if (splashDialog != null && splashDialog.isShowing()) { splashDialog.dismiss(); splashDialog = null; } } /** * Shows the splash screen over the full Activity */ @SuppressWarnings("deprecation") protected void showSplashScreen(final int time) { final DroidGap that = this; Runnable runnable = new Runnable() { public void run() { // Get reference to display Display display = getWindowManager().getDefaultDisplay(); // Create the layout for the dialog LinearLayout root = new LinearLayout(that.getActivity()); root.setMinimumHeight(display.getHeight()); root.setMinimumWidth(display.getWidth()); root.setOrientation(LinearLayout.VERTICAL); root.setBackgroundColor(that.getIntegerProperty("backgroundColor", Color.BLACK)); root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, 0.0F)); // We want the splashscreen to keep its ratio, // for this we need to use an ImageView and not simply the background of the LinearLayout ImageView splashscreenView = new ImageView(that.getActivity()); splashscreenView.setImageResource(that.splashscreen); splashscreenView.setScaleType(ImageView.ScaleType.CENTER_CROP); // similar to the background-size:cover CSS property splashscreenView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); root.addView(splashscreenView); // Create and show the dialog splashDialog = new Dialog(that, android.R.style.Theme_Translucent_NoTitleBar); // check to see if the splash screen should be full screen if ((getWindow().getAttributes().flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) == WindowManager.LayoutParams.FLAG_FULLSCREEN) { splashDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } splashDialog.setContentView(root); splashDialog.setCancelable(false); splashDialog.show(); // Set Runnable to remove splash screen just in case final Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { removeSplashScreen(); } }, time); } }; this.runOnUiThread(runnable); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { //Get whatever has focus! View childView = appView.getFocusedChild(); if ((appView.isCustomViewShowing() || childView != null ) && (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU)) { return appView.onKeyUp(keyCode, event); } else { return super.onKeyUp(keyCode, event); } } /* * Android 2.x needs to be able to check where the cursor is. Android 4.x does not * * (non-Javadoc) * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent) */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { //Get whatever has focus! View childView = appView.getFocusedChild(); //Determine if the focus is on the current view or not if (childView != null && (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU)) { return appView.onKeyDown(keyCode, event); } else return super.onKeyDown(keyCode, event); } /** * Called when a message is sent to plugin. * * @param id The message id * @param data The message data * @return Object or null */ public Object onMessage(String id, Object data) { LOG.d(TAG, "onMessage(" + id + "," + data + ")"); if ("splashscreen".equals(id)) { if ("hide".equals(data.toString())) { this.removeSplashScreen(); } else { // If the splash dialog is showing don't try to show it again if (this.splashDialog == null || !this.splashDialog.isShowing()) { this.splashscreen = this.getIntegerProperty("splashscreen", 0); this.showSplashScreen(this.splashscreenTime); } } } else if ("spinner".equals(id)) { if ("stop".equals(data.toString())) { this.spinnerStop(); this.appView.setVisibility(View.VISIBLE); } } else if ("onReceivedError".equals(id)) { JSONObject d = (JSONObject) data; try { this.onReceivedError(d.getInt("errorCode"), d.getString("description"), d.getString("url")); } catch (JSONException e) { e.printStackTrace(); } } else if ("exit".equals(id)) { this.endActivity(); } return null; } public ExecutorService getThreadPool() { return threadPool; } protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if(this.activityResultCallback != null) { String cClass = this.activityResultCallback.getClass().getName(); outState.putString("callbackClass", cClass); } } }
true
false
null
null
diff --git a/src/core/CalendarProgram.java b/src/core/CalendarProgram.java index 83a6187..5225cc4 100644 --- a/src/core/CalendarProgram.java +++ b/src/core/CalendarProgram.java @@ -1,290 +1,291 @@ package core; import gui.CalendarPanel; import gui.EditAppointmentPanel; import gui.LoginPanel; import gui.MenuPanel; import java.awt.BorderLayout; import java.awt.Color; import java.awt.EventQueue; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import core.alarm.AlarmHandler; import core.alarm.AlarmListener; import db.Action; import db.Appointment; import db.Callback; import db.Notification; import db.Status; import db.User; public class CalendarProgram extends JFrame implements AlarmListener { //gui private JPanel contentPane; private EditAppointmentPanel eap; private LoginPanel loginPanel; private MenuPanel menuPanel; private CalendarPanel calendarPanel; //model private HashMap<User, ArrayList<Appointment>> appointments; private User currentUser; private ArrayList<User> cachedUsers; //tools private Thread alarmHandlerThread; private ClientFactory cf; //Alarm private AlarmHandler alarmHandler; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { CalendarProgram frame = new CalendarProgram(); frame.setSize(1200, 600); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public CalendarProgram() { System.out.println("creating main program"); appointments = new HashMap<User, ArrayList<Appointment>>(); //tool for talking with server cf = new ClientFactory(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//TODO: possibly overide this method to also close threads setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(new BorderLayout(0, 0)); loginPanel = new LoginPanel(this); contentPane.add(loginPanel, BorderLayout.CENTER); System.out.println(cachedUsers); } public void displayLogin() { menuPanel.setVisible(false); calendarPanel.setVisible(false); loginPanel = new LoginPanel(this); contentPane.add(loginPanel, BorderLayout.CENTER); } public void displayMainProgram(JPanel panel){ panel.setVisible(false); menuPanel.setVisible(true); calendarPanel.setVisible(true); } public boolean logIn(String userName, String password) { System.out.println("trying to log in"); - loginPanel.correctInput.setVisible(true); if (userName.length() > 0 && password.length() > 0 ) { User temp = cf.sendAction(new User(0 ,userName ,null, password), Action.LOGIN); System.out.println("got return value " + temp + " with status " + temp.getAction()); if (temp.getAction().equals(Action.SUCCESS)) { + loginPanel.correctInput.setVisible(true); System.out.println("*** Got valid login ***"); currentUser = temp; return true; - } + } } + loginPanel.wrongInput.setVisible(true); return false; } //called when user logs inn // added some appointments and notifications for testing. Unpossible to do in main... public void CreateMainProgram() { menuPanel = new MenuPanel(this); contentPane.add(menuPanel, BorderLayout.WEST); calendarPanel = new CalendarPanel(this); calendarPanel.setBackground(Color.RED); contentPane.add(calendarPanel, BorderLayout.CENTER); //Initialize values appointments = cf.sendAction(currentUser, Action.GET_ALL_USERS_ALL_APPOINTMENTS); cachedUsers = cf.sendAction(currentUser, Action.GET_ALL_USERS); calendarPanel.setUserAndAppointments(appointments.get(currentUser)); // TODO: kikk p� denne //loadAppointments(); alarmSetup(); //fetching notifications, after easch call it wait 5 mins new Thread(new Runnable() { public void run() { while(true){ long wait = 300000;//millisec = 5 min ArrayList<Notification> notifications = fetchNotifications(); System.out.println("Notifications: "+notifications); for (Notification notification : notifications) { menuPanel.addNotification(notification); } try { System.out.println("notification thread will sleep for "+wait+" millies"); Thread.sleep(wait); } catch (InterruptedException e) { System.out.println("notification thread interupted"); } System.out.println("notification thread woke up"); } } }).start();//starts the thread } // use this method to add notifications to the notificationsList //TODO make this method send notifications when it should private void addNotification(Notification notification) { menuPanel.addNotification(notification); } //this should be called every 5 minuts to fetch notifications public ArrayList<Notification> fetchNotifications(){ return cf.sendAction(currentUser, Action.GET_NOTIFICATION); } public void sendNotification(Notification notification){ Notification callback = cf.sendAction(notification, Action.NOTIFICATION); System.out.println(callback.getNotificationType()); } //get appointments and starts to check them in a new thread, signing up for notifications from alarmHandler. private void alarmSetup() { alarmHandler = new AlarmHandler(appointments.get(currentUser)); alarmHandler.addAlarmEventListener(this); alarmHandlerThread = new Thread(alarmHandler); alarmHandlerThread.start(); } public void logout(){ cf.sendAction(currentUser, Action.DISCONNECT); } public HashMap<User, Status> getAllAppointmentUsers(Appointment app) { System.out.println("getting participants with statuses for " + app.getId()); HashMap<User, Status> callback = cf.sendAction(app, Action.GET_ALL_APPOINTMENT_USERS); if (callback != null) { return callback; } else { System.out.println("could not return statuses"); return new HashMap<User, Status>(); } } public void addAppointment(Appointment app){ System.out.println("we have these participants!"); System.out.println(app.getParticipants()); Appointment callback = cf.sendAction(app, Action.INSERT); if (callback.getAction().equals(Action.SUCCESS)) { calendarPanel.addAppointmentToModel(callback); appointments.get(currentUser).add(callback); if(callback.hasAlarm()){ alarmHandler.addAppointment(callback); alarmHandlerThread.interrupt(); System.out.println("Thread: "+alarmHandlerThread.interrupted()); } System.out.println("our superlist now contains the following"+appointments.size()+"elements: " + appointments); } else { System.out.println("Warning: Returned with status code " + callback.getAction()); } } public void deleteAppointment(Appointment appointment) { Callback c = cf.sendAction(appointment, Action.DELETE); if (c.getAction().equals(Action.SUCCESS)){ System.out.println("det gikk bra"); calendarPanel.removeAppointment(appointment); appointments.get(currentUser).remove(appointment); calendarPanel.updateCalendar(); } else { System.out.println("Warning: Returned with status code " + c.getAction()); } } public void updateAppointment(Appointment appointment){ System.out.println("we have these participants!"); System.out.println(appointment.getParticipants()); // TODO: make edit appointment return the edited version Appointment callback = cf.sendAction(appointment, Action.UPDATE); if (callback.getAction().equals(Action.SUCCESS)) { appointments.get(currentUser).remove(appointment); appointments.get(currentUser).add(callback); calendarPanel.removeAppointment(appointment); calendarPanel.addAppointmentToModel(callback); //calendarPanel.removeAppointment(appointment); //calendarPanel.addAppointmentToModel(appointment); } else { System.out.println("Warning: Returned with status code " + callback.getAction()); } } public void createEditAppointmentPanel(Appointment appointment){ menuPanel.setVisible(false); calendarPanel.setVisible(false); if (appointment == null) { eap = new EditAppointmentPanel(this,new Appointment(currentUser), true); } else { eap = new EditAppointmentPanel(this,appointment, false); } contentPane.add(eap, BorderLayout.CENTER); eap.setBackground(Color.LIGHT_GRAY); } @Override public void alarmEvent(Appointment appointment) { String timeToAlarm = ""+new Date(appointment.getStart().getTimeInMillis()-appointment.getAlarm().getAlarmTime().getTimeInMillis()); JOptionPane.showMessageDialog(this, "You have appointment: "+appointment.getTitle()+" in: "+timeToAlarm,"Appointment alarm",JOptionPane.INFORMATION_MESSAGE); } public void setFocusInCalendar(Notification note) { calendarPanel.setFocusToAppointment(note.getAppointment()); } public void setEditButtonEnabled() { menuPanel.setEditButtonEnabled(); } public void setEditButtonDisabled() { menuPanel.setEditButtonDisabled(); } public Appointment getSelectedAppointment() { return calendarPanel.getSelectedEvent().getModel(); } public User getUser(){ return currentUser; } public ArrayList<User> getUsers() { return cf.sendAction(new User(), Action.GET_ALL_USERS); } //method for getting all appointments from user public ArrayList<Appointment> getApointmentsFromUser(User user){ return appointments.get(user.getId()); } public ArrayList<User> getCachedUsers() { return this.cachedUsers; } }
false
false
null
null
diff --git a/src/java/com/sapienter/jbilling/server/pricing/db/PriceModelDTO.java b/src/java/com/sapienter/jbilling/server/pricing/db/PriceModelDTO.java index 79e47a87..a04777bf 100644 --- a/src/java/com/sapienter/jbilling/server/pricing/db/PriceModelDTO.java +++ b/src/java/com/sapienter/jbilling/server/pricing/db/PriceModelDTO.java @@ -1,302 +1,304 @@ /* * JBILLING CONFIDENTIAL * _____________________ * * [2003] - [2012] Enterprise jBilling Software Ltd. * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Enterprise jBilling Software. * The intellectual and technical concepts contained * herein are proprietary to Enterprise jBilling Software * and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden. */ package com.sapienter.jbilling.server.pricing.db; import com.sapienter.jbilling.server.item.CurrencyBL; import com.sapienter.jbilling.server.item.PricingField; import com.sapienter.jbilling.server.item.tasks.PricingResult; import com.sapienter.jbilling.server.order.Usage; import com.sapienter.jbilling.server.order.db.OrderDTO; import com.sapienter.jbilling.server.pricing.PriceModelWS; import com.sapienter.jbilling.server.pricing.strategy.PricingStrategy; import com.sapienter.jbilling.server.user.UserBL; import com.sapienter.jbilling.server.util.db.CurrencyDTO; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.CollectionOfElements; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.MapKey; import org.hibernate.annotations.Sort; import org.hibernate.annotations.SortType; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Transient; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; /** * @author Brian Cowdery * @since 30-07-2010 */ @Entity @Table(name = "price_model") @TableGenerator( name = "price_model_GEN", table = "jbilling_seqs", pkColumnName = "name", valueColumnName = "next_id", pkColumnValue = "price_model", allocationSize = 100 ) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class PriceModelDTO implements Serializable { public static final String ATTRIBUTE_WILDCARD = "*"; private Integer id; private PriceModelStrategy type; private SortedMap<String, String> attributes = new TreeMap<String, String>(); private BigDecimal rate; private CurrencyDTO currency; // price model chaining private PriceModelDTO next; public PriceModelDTO() { } public PriceModelDTO(PriceModelStrategy type, BigDecimal rate, CurrencyDTO currency) { this.type = type; this.rate = rate; this.currency = currency; } public PriceModelDTO(PriceModelWS ws, CurrencyDTO currency) { setId(ws.getId()); setType(PriceModelStrategy.valueOf(ws.getType())); setAttributes(new TreeMap<String, String>(ws.getAttributes())); setRate(ws.getRateAsDecimal()); setCurrency(currency); } /** * Copy constructor. * * @param model model to copy */ public PriceModelDTO(PriceModelDTO model) { this.id = model.getId(); this.type = model.getType(); this.attributes = new TreeMap<String, String>(model.getAttributes()); this.rate = model.getRate(); this.currency = model.getCurrency(); if (model.getNext() != null) { this.next = new PriceModelDTO(model.getNext()); } } @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "price_model_GEN") @Column(name = "id", unique = true, nullable = false) public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Enumerated(EnumType.STRING) @Column(name = "strategy_type", nullable = false, length = 25) public PriceModelStrategy getType() { return type; } public void setType(PriceModelStrategy type) { this.type = type; } @Transient public PricingStrategy getStrategy() { return getType() != null ? getType().getStrategy() : null; } @CollectionOfElements(fetch = FetchType.EAGER) @JoinTable(name = "price_model_attribute", joinColumns = @JoinColumn(name = "price_model_id")) @MapKey(columns = @Column(name = "attribute_name", nullable = true, length = 255)) @Column(name = "attribute_value", nullable = true, length = 255) @Sort(type = SortType.NATURAL) @Fetch(FetchMode.SELECT) public SortedMap<String, String> getAttributes() { return attributes; } public void setAttributes(SortedMap<String, String> attributes) { this.attributes = attributes; setAttributeWildcards(); } /** * Sets the given attribute. If the attribute is null, it will be persisted as a wildcard "*". * * @param name attribute name * @param value attribute value */ public void addAttribute(String name, String value) { this.attributes.put(name, (value != null ? value : ATTRIBUTE_WILDCARD)); } /** * Replaces null values in the attribute list with a wildcard character. Null values cannot be * persisted using the @CollectionOfElements, and make for uglier 'optional' attribute queries. */ public void setAttributeWildcards() { if (getAttributes() != null && !getAttributes().isEmpty()) { for (Map.Entry<String, String> entry : getAttributes().entrySet()) if (entry.getValue() == null) entry.setValue(ATTRIBUTE_WILDCARD); } } /** * Returns the pricing rate. If the strategy type defines an overriding rate, the * strategy rate will be returned. * * @return pricing rate. */ @Column(name = "rate", nullable = true, precision = 10, scale = 22) public BigDecimal getRate() { return rate; } public void setRate(BigDecimal rate) { this.rate = rate; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "currency_id", nullable = true) public CurrencyDTO getCurrency() { return currency; } public void setCurrency(CurrencyDTO currency) { this.currency = currency; } @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "next_model_id", nullable = true) public PriceModelDTO getNext() { return next; } public void setNext(PriceModelDTO next) { this.next = next; } /** * Applies this pricing to the given PricingResult. * * This method will automatically convert the calculated price to the currency of the given * PricingResult if the set currencies differ. * * @see com.sapienter.jbilling.server.pricing.strategy.PricingStrategy *@param pricingOrder target order for this pricing request (may be null) * @param quantity quantity of item being priced * @param result pricing result to apply pricing to * @param usage total item usage for this billing period * @param singlePurchase true if pricing a single purchase/addition to an order, false if pricing a quantity that already exists on the pricingOrder. * @param pricingDate pricing date */ @Transient public void applyTo(OrderDTO pricingOrder, BigDecimal quantity, PricingResult result, List<PricingField> fields, Usage usage, boolean singlePurchase, Date pricingDate) { // each model in the chain for (PriceModelDTO next = this; next != null; next = next.getNext()) { // apply pricing next.getType().getStrategy().applyTo(pricingOrder, result, fields, next, quantity, usage, singlePurchase); // convert currency if necessary if (result.getUserId() != null && result.getCurrencyId() != null && result.getPrice() != null && next.getCurrency() != null && next.getCurrency().getId() != result.getCurrencyId()) { Integer entityId = new UserBL().getEntityId(result.getUserId()); if(pricingDate == null) { pricingDate = new Date(); } final BigDecimal converted = new CurrencyBL().convert(next.getCurrency().getId(), result.getCurrencyId(), result.getPrice(), pricingDate, entityId); result.setPrice(converted); - } else { - result.setPrice(BigDecimal.ZERO); } } + + if (result.getPrice() == null) { + result.setPrice(BigDecimal.ZERO); + } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PriceModelDTO that = (PriceModelDTO) o; if (attributes != null ? !attributes.equals(that.attributes) : that.attributes != null) return false; if (currency != null ? !currency.equals(that.currency) : that.currency != null) return false; if (id != null ? !id.equals(that.id) : that.id != null) return false; if (rate != null ? !rate.equals(that.rate) : that.rate != null) return false; if (type != that.type) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (attributes != null ? attributes.hashCode() : 0); result = 31 * result + (rate != null ? rate.hashCode() : 0); result = 31 * result + (currency != null ? currency.hashCode() : 0); return result; } @Override public String toString() { return "PriceModelDTO{" + "id=" + id + ", type=" + type + ", attributes=" + attributes + ", rate=" + rate + ", currencyId=" + (currency != null ? currency.getId() : null) + ", next=" + next + '}'; } }
false
false
null
null
diff --git a/src/main/java/net/aepik/casl/core/ldap/Schema.java b/src/main/java/net/aepik/casl/core/ldap/Schema.java index 0d0c963..d359a37 100755 --- a/src/main/java/net/aepik/casl/core/ldap/Schema.java +++ b/src/main/java/net/aepik/casl/core/ldap/Schema.java @@ -1,642 +1,650 @@ /* * Copyright (C) 2006-2010 Thomas Chemineau * * 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 net.aepik.casl.core.ldap; import net.aepik.casl.core.History; import java.io.File; import java.net.URL; import java.net.URLDecoder; import java.util.Arrays; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.Observable; import java.util.Properties; import java.util.Vector; import java.util.jar.*; /** * Cet objet est un schéma LDAP au sens large. Il doit contenir des définitions * de type objectClass ou AttributeType, par l'intermédiaire de l'objet Java * SchemaObject. */ public class Schema extends Observable { /** * L'ensemble des objets du schema */ private Hashtable<String,SchemaObject> objets; /** * Schema properties */ private Properties proprietes; /** * La syntaxe du schema */ private SchemaSyntax syntax; /** * Indique si la syntaxe a changée */ private boolean isSyntaxChanged; /** * L'historique d'ordre des objets */ private History objectsOrder; /** * A random object identifier prefix */ private String objectIdentifierPrefix; /** * A random object identifier suffix */ private String objectIdentifierSuffix; /** * Construit un schema vide. */ public Schema ( SchemaSyntax s ) { objets = new Hashtable<String,SchemaObject>(); proprietes = new Properties(); syntax = s; isSyntaxChanged = false; objectsOrder = new History(); objectIdentifierPrefix = null; objectIdentifierSuffix = null; } /** * Construit un schema en le remplissant * d'objets SchemaObject. * @param objets Des objets du schema. */ public Schema ( SchemaSyntax s, Vector<SchemaObject> objs ) { objets = new Hashtable<String,SchemaObject>() ; proprietes = new Properties(); syntax = s ; isSyntaxChanged = false ; addObjects( objs ); objectIdentifierPrefix = null; objectIdentifierSuffix = null; } /** * Ajoute un objet au schema. * @param o Un objet du schema. * @return True si l'objet n'existe pas déjà , false sinon. */ public boolean addObject ( SchemaObject o ) { try { + if (o == null || o.getId() == null) + { + return false; + } if (!contains(o.getId())) { objets.put(o.getId(), o); objectsOrder.insertElementInLastPosition(o); notifyUpdates(); return true; } } catch (Exception e) { e.printStackTrace(); } return false; } /** * Ajoute un ensemble d'objets au schema. * @param v Un ensemble d'objets du schema. * @return True si l'opération a réussi, false sinon. * Si l'opération n'a pas réussi, aucun objet n'aura été ajouté. */ public boolean addObjects ( SchemaObject[] v ) { boolean ok = true; for (int i = 0; i < v.length && ok; i++) { ok = addObject(v[i]); } if (ok) { notifyUpdates(); return true; } // // Si l'opération n'a pas réussi, c'est à dire qu'un objet, figurant // dans l'ensemble des objets que l'on tente d'insérer, possède un id // qui existe déjà dans le schema courant, alors on effectue // l'opération inverse: on supprime tout objet inséré durant // l'opération précédente. // for (SchemaObject o : v) { delObject(o.getId()); } return false; } /** * Ajoute un ensemble d'objets au schema. * @param v Un ensemble d'objets du schema. * @return True si l'opération a réussi, false sinon. * Si l'opération n'a pas réussi, aucun objet n'aura été ajouté. */ public boolean addObjects ( Vector<SchemaObject> v ) { SchemaObject[] o = new SchemaObject[v.size()]; Iterator<SchemaObject> it = v.iterator(); int position = 0; while (it.hasNext()) { o[position] = it.next(); position++; } return addObjects(o); } /** * Indique si l'objet identifié par id existe dans le schema. * @param id Une chaine de caractères représentant l'id d'un objet du schéma. * @return True si l'objet d'identifiant id existe dans le schema, false sinon. */ public boolean contains ( String id ) { try { + if (id == null || objets == null) + { + return false; + } if (objets.containsKey(id)) { return true; } } catch (Exception e) { e.printStackTrace(); } return false; } /** * Retourne le nombre d'objets que contient le schéma. * @return int Le nombre d'objets du schéma. */ public int countObjects () { return objets.size(); } /** * Créer un schéma et charge les objets lu à partir d'un fichier dans ce * nouveau schéma. * @param SchemaSyntax syntax * @param String filename * @param boolean load * @return SchemaFile Un objet SchemaFile contenant les objets. */ public static SchemaFile createAndLoad ( SchemaSyntax syntax, String filename, boolean load ) { SchemaFileReader sReader = syntax.createSchemaReader(); SchemaFile sFile = new SchemaFile(filename,sReader, null); if (load) { sFile.read(); } return sFile; } /** * Supprime un objet du schema. * @param id Une chaine de caractères représentant l'id d'un objet du schema. * @return True si l'objet d'identifiant id existe dans le schema, false sinon. */ public boolean delObject ( String id ) { if (contains(id)) { SchemaObject o = objets.remove(id); objectsOrder.removeElement(o); notifyUpdates(); return true; } return false; } /** * Generate a random object identifier. * @return String A random object identifier string. */ public String generateRandomObjectIdentifier () { if (this.objectIdentifierPrefix == null) { objectIdentifierPrefix = new String("0.1.2.3.4.5.6"); } if (this.objectIdentifierSuffix == null) { objectIdentifierSuffix = new String("0"); } int suffix = (new Integer(objectIdentifierSuffix)).intValue(); objectIdentifierSuffix = String.valueOf(++suffix); String roid = new String(objectIdentifierPrefix + "." + objectIdentifierSuffix); return roid; } /** * Retourne l'historique d'ajout du schéma. * @return History Un historique en fonction des données actuelles du schéma. */ public History getHistory () { return objectsOrder; } /** * Accède à un objet du schema. * @param id Une chaine de caractères représentant l'id d'un objet du schema. * @return SchemaObject Un objet du schema. */ public SchemaObject getObject ( String id ) { if (contains(id)) { return objets.get(id); } return null; } /** * Retourne un objet du schéma dont le nom est name. * @param name Le nom d'un objet, et non son id. * @return SchemaObject Un objet du schéma. */ public SchemaObject getObjectByName ( String name ) { SchemaObject result = null ; Enumeration<SchemaObject> it = objets.elements(); while (result == null && it.hasMoreElements()) { SchemaObject o = it.nextElement(); if (o.getName() == null) { continue; } if (o.getName().toLowerCase().equals(name.toLowerCase())) { result = o; } } return result; } /** * Retourne l'ensemble des objets du schema. * @return SchemaObject[] L'ensemble des objets du schema. */ public SchemaObject[] getObjects () { SchemaObject[] result = new SchemaObject[objets.size()]; int position = 0; for (Enumeration<SchemaObject> e=objets.elements(); e.hasMoreElements();) { result[position] = e.nextElement(); position++; } return result; } /** * Retourne l'ensemble des objets du schema d'un certain type. * @param type Le type des objets à selectionner. * @return SchemaObject[] L'ensemble des objets du schema. */ public SchemaObject[] getObjects ( String type ) { Vector<SchemaObject> v = new Vector<SchemaObject>(); for (Enumeration<SchemaObject> e=objets.elements(); e.hasMoreElements();) { SchemaObject o = e.nextElement(); if (type.equals(o.getType())) { v.add(o); } } SchemaObject[] result = new SchemaObject[v.size()]; int position = 0; for (Enumeration<SchemaObject> e=v.elements(); e.hasMoreElements();) { result[position] = e.nextElement(); position++; } return result; } /** * Retourne l'ensemble des objets du schema dans l'ordre dans lequel * ils ont été ajouté au schéma. * @return SchemaObject[] L'ensemble des objets du schema. */ public SchemaObject[] getObjectsInOrder () { Vector<SchemaObject> result = new Vector<SchemaObject>(); for (SchemaObject o : this.getObjectsInOrder(this.getSyntax().getObjectIdentifierType())) { result.add(o); } for (SchemaObject o : this.getObjectsInOrder(this.getSyntax().getAttributeType())) { result.add(o); } for (SchemaObject o : this.getObjectsInOrder(this.getSyntax().getObjectClassType())) { result.add(o); } return result.toArray(new SchemaObject[10]); } /** * Retourne l'ensemble des objets du schema d'un certain type, dans l'ordre * dans lequel ils ont été ajouté au schéma. * @param type Le type des objets à selectionner. * @return SchemaObject[] L'ensemble des objets du schema. */ public SchemaObject[] getObjectsInOrder ( String type ) { Vector<SchemaObject> v = new Vector<SchemaObject>(); for (Enumeration<Object> e=objectsOrder.elements(); e.hasMoreElements();) { SchemaObject o = (SchemaObject) e.nextElement(); if (type.equals(o.getType())) { v.add(o); } } SchemaObject[] result = new SchemaObject[v.size()]; int position = 0; for (Enumeration<SchemaObject> e=v.elements(); e.hasMoreElements();) { result[position] = e.nextElement(); position++; } return result; } /** * Returns objects identifiers. * @return Properties All objects identifiers. */ public Properties getObjectsIdentifiers () { Properties objectsIdentifiers = new Properties(); SchemaObject[] oids = this.getObjectsInOrder(this.getSyntax().getObjectIdentifierType()); for (SchemaObject object : oids) { String[] keys = object.getKeys(); SchemaValue value = object.getValue(keys[0]); objectsIdentifiers.setProperty(keys[0], value.toString()); } return objectsIdentifiers; } /** * Get objects sorted. * @return SchemaObject[] All schema objects sorted. */ public SchemaObject[] getObjectsSorted () { SchemaObject[] objects = new SchemaObject[objets.size()]; int position = 0; for (Enumeration<SchemaObject> e = objets.elements(); e.hasMoreElements(); position++) { objects[position] = e.nextElement(); } return objects; } /** * Retourne les propriétés du schéma. * @return Properties L'ensemble des propriétés du schéma. */ public Properties getProperties () { return proprietes; } /** * Retourne la syntaxe utilisée par le schema. * @return SchemaSyntax Une syntaxe spécifique. */ public SchemaSyntax getSyntax () { return syntax; } /** * Retourne le nom du paquetage contenant toutes les syntaxes. * @return String Un nom de paquetage. */ public static String getSyntaxPackageName () { Schema s = new Schema(null); return s.getClass().getPackage().getName() + ".syntax"; } /** * Retourne l'ensemble des syntaxes connues, qui sont * contenues dans le package 'ldap.syntax'. * @return String[] L'ensemble des noms de classes de syntaxes. */ public static String[] getSyntaxes () { String[] result = null; try { String packageName = getSyntaxPackageName(); URL url = Schema.class.getResource("/" + packageName.replace('.', '/')); if (url == null) { return null; } if (url.getProtocol().equals("jar")) { Vector<String> vectTmp = new Vector<String>(); int index = url.getPath().indexOf('!'); String path = URLDecoder.decode(url.getPath().substring(index+1), "UTF-8"); JarFile jarFile = new JarFile(URLDecoder.decode(url.getPath().substring(5, index), "UTF-8")); if (path.charAt(0) == '/') { path = path.substring(1); } Enumeration<JarEntry> jarFiles = jarFile.entries(); while (jarFiles.hasMoreElements()) { JarEntry tmp = jarFiles.nextElement(); // // Pour chaque fichier dans le jar, on regarde si c'est un // fichier de classe Java. // if (!tmp.isDirectory() && tmp.getName().substring(tmp.getName().length() - 6).equals(".class") && tmp.getName().startsWith(path)) { int i = tmp.getName().lastIndexOf('/'); vectTmp.add(tmp.getName().substring(i+1, tmp.getName().length() - 6)); } } jarFile.close(); result = new String[vectTmp.size()]; for (int i = 0; i < vectTmp.size(); i++) { result[i] = vectTmp.elementAt(i); } } else if (url.getProtocol().equals("file")) { // // On créé le fichier associé pour parcourir son contenu. // En l'occurence, c'est un dossier. // File[] files = (new File(url.toURI())).listFiles(); // // On liste tous les fichiers qui sont dedans. // On les stocke dans un vecteur ... // Vector<File> vectTmp = new Vector<File>(); for (File f : files) { if (!f.isDirectory()) { vectTmp.add(f); } } // // ... pour ensuite les mettres dans le tableau de resultat. // result = new String[vectTmp.size()]; for (int i = 0; i < vectTmp.size(); i++) { String name = vectTmp.elementAt(i).getName(); int a = name.indexOf('.'); name = name.substring(0, a); result[i] = name; } } } catch (Exception e) { e.printStackTrace(); } if (result != null) { Arrays.sort(result); } return result; } /** * Teste si la syntaxe à changer depuis la dernière fois qu'on a appelé * cette méthode. * @return boolean */ public boolean isSyntaxChangedSinceLastTime () { if (isSyntaxChanged) { isSyntaxChanged = false; return true; } return false; } /** * Permet de notifier que les données ont changées. * Tous les objets observant le schema verront la notification. */ public void notifyUpdates () { this.notifyUpdates(false); } /** * Permet de notifier que les données ont changées. * Tous les objets observant le schema verront la notification. * @param boolean force Indicates wheter or not to force the update. */ public void notifyUpdates ( boolean force ) { setChanged(); notifyObservers(Boolean.valueOf(force)); } /** * Modify objects identifiers of this schema. * @param newOIDs New objects identifiers. */ public void setObjectsIdentifiers ( Properties newOIDs ) { SchemaObject[] oids = this.getObjectsInOrder(this.getSyntax().getObjectIdentifierType()); for (SchemaObject object : oids) { this.delObject(object.getId()); } for (Enumeration keys = newOIDs.propertyNames(); keys.hasMoreElements();) { String id = (String) keys.nextElement(); SchemaValue v = this.getSyntax().createSchemaValue( this.getSyntax().getObjectIdentifierType(), id, newOIDs.getProperty(id) ); SchemaObject o = this.getSyntax().createSchemaObject( this.getSyntax().getObjectIdentifierType(), v.toString() ); o.addValue(id,v); this.addObject(o); } } /** * Modifies les propriétés du schéma. * @param newProp Le nouvel objet Properties. */ public void setProperties ( Properties newProp ) { this.proprietes = newProp; } /** * Modifie la syntaxe du schéma. * @param newSyntax Une syntaxe spécifique. */ public void setSyntax ( SchemaSyntax newSyntax ) { isSyntaxChanged = true; syntax = newSyntax; } }
false
false
null
null
diff --git a/sikuli-ide/src/main/java/edu/mit/csail/uid/CaptureButton.java b/sikuli-ide/src/main/java/edu/mit/csail/uid/CaptureButton.java index 9ea35de6..78802536 100644 --- a/sikuli-ide/src/main/java/edu/mit/csail/uid/CaptureButton.java +++ b/sikuli-ide/src/main/java/edu/mit/csail/uid/CaptureButton.java @@ -1,179 +1,184 @@ package edu.mit.csail.uid; import java.awt.*; import java.awt.event.*; import java.net.*; import javax.swing.*; import javax.swing.text.*; class CaptureButton extends JButton implements ActionListener, Cloneable, Observer{ protected Element _line; protected SikuliPane _codePane; protected boolean _isCapturing; /* public String toString(){ return " \"CAPTURE-BUTTON\" "; } */ public CaptureButton(){ super(); URL imageURL = SikuliIDE.class.getResource("/icons/capture.png"); setIcon(new ImageIcon(imageURL)); UserPreferences pref = UserPreferences.getInstance(); String strHotkey = Utils.convertKeyToText( pref.getCaptureHotkey(), pref.getCaptureHotkeyModifiers() ); setToolTipText(SikuliIDE._I("btnCaptureHint", strHotkey)); setBorderPainted(false); setMaximumSize(new Dimension(26,26)); addActionListener(this); _line = null; } public CaptureButton(SikuliPane codePane, Element elmLine){ this(); _line = elmLine; _codePane = codePane; setBorderPainted(true); setCursor(new Cursor (Cursor.HAND_CURSOR)); } public boolean hasNext(){ return false; } public CaptureButton getNextDiffButton(){ return null; } public void setParentPane(SikuliPane parent){ _codePane = parent; } public void setDiffMode(boolean flag){} public void setSrcElement(Element elmLine){ _line = elmLine; } public Element getSrcElement(){ return _line; } protected void insertAtCursor(SikuliPane pane, String imgFilename){ ImageButton icon = new ImageButton(pane, imgFilename); pane.insertComponent(icon); pane.requestFocus(); } public void captureCompleted(String imgFullPath){ _isCapturing = false; if(imgFullPath == null) return; Debug.log("captureCompleted: " + imgFullPath); Element src = getSrcElement(); if( src == null ){ if(_codePane == null) insertAtCursor(SikuliIDE.getInstance().getCurrentCodePane(), imgFullPath); else insertAtCursor(_codePane, imgFullPath); return; } int start = src.getStartOffset(); int end = src.getEndOffset(); int old_sel_start = _codePane.getSelectionStart(), old_sel_end = _codePane.getSelectionEnd(); try{ StyledDocument doc = (StyledDocument)src.getDocument(); String text = doc.getText(start, end-start); Debug.log(text); for(int i=start;i<end;i++){ Element elm = doc.getCharacterElement(i); if(elm.getName().equals(StyleConstants.ComponentElementName)){ AttributeSet attr=elm.getAttributes(); Component com=StyleConstants.getComponent(attr); if( com instanceof CaptureButton ){ Debug.log(5, "button is at " + i); int oldCaretPos = _codePane.getCaretPosition(); _codePane.select(i, i+1); ImageButton icon = new ImageButton(_codePane, imgFullPath); _codePane.insertComponent(icon); _codePane.setCaretPosition(oldCaretPos); break; } } } } catch(BadLocationException ble){ ble.printStackTrace(); } _codePane.select(old_sel_start, old_sel_end); _codePane.requestFocus(); } private String getFilenameFromUser(String hint){ return (String)JOptionPane.showInputDialog( _codePane, - "Enter the screen shot's file name:", - "Name The Screen Shot", + I18N._I("msgEnterScreenshotFilename"), + I18N._I("dlgEnterScreenshotFilename"), JOptionPane.PLAIN_MESSAGE, null, null, hint); } public void update(Subject s){ if(s instanceof CapturePrompt){ CapturePrompt cp = (CapturePrompt)s; ScreenImage simg = cp.getSelection(); if(simg==null){ captureCompleted(null); return; } cp.close(); SikuliIDE ide = SikuliIDE.getInstance(); SikuliPane pane = ide.getCurrentCodePane(); int naming = UserPreferences.getInstance().getAutoNamingMethod(); String filename; if(naming == UserPreferences.AUTO_NAMING_TIMESTAMP) filename = Utils.getTimestamp(); else if(naming == UserPreferences.AUTO_NAMING_OCR) filename = NamingPane.getFilenameFromImage(simg.getImage()); else{ String hint = NamingPane.getFilenameFromImage(simg.getImage()); filename = getFilenameFromUser(hint); + if(filename == null){ + captureCompleted(null); + return; + } + } String fullpath = Utils.saveImage(simg.getImage(), filename, pane.getSrcBundle()); if(fullpath != null){ //String fullpath = pane.getFileInBundle(filename).getAbsolutePath(); captureCompleted(Utils.slashify(fullpath,false)); } } } public void captureWithAutoDelay(){ UserPreferences pref = UserPreferences.getInstance(); int delay = (int)(pref.getCaptureDelay() * 1000.0) +1; capture(delay); } public void capture(final int delay){ if(_isCapturing) return; _isCapturing = true; Thread t = new Thread("capture"){ public void run(){ SikuliIDE ide = SikuliIDE.getInstance(); if(delay!=0) ide.setVisible(false); try{ Thread.sleep(delay); } catch(Exception e){} (new CapturePrompt(null, CaptureButton.this)).prompt(); if(delay!=0) ide.setVisible(true); } }; t.start(); } public void actionPerformed(ActionEvent e) { Debug.log("capture!"); captureWithAutoDelay(); } }
false
false
null
null
diff --git a/java/osgi/database/src/main/java/com/tintin/devcloud/database/manager/DatabaseManager.java b/java/osgi/database/src/main/java/com/tintin/devcloud/database/manager/DatabaseManager.java index a44f4af..1edfe6b 100644 --- a/java/osgi/database/src/main/java/com/tintin/devcloud/database/manager/DatabaseManager.java +++ b/java/osgi/database/src/main/java/com/tintin/devcloud/database/manager/DatabaseManager.java @@ -1,26 +1,26 @@ package com.tintin.devcloud.database.manager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import com.tintin.devcloud.database.Activator; import com.tintin.devcloud.database.interfaces.IDatabaseManager; public class DatabaseManager implements IDatabaseManager { private Activator activator = null; private EntityManagerFactory modelEMF = null; public DatabaseManager(Activator activator) { this.activator = activator; - modelEMF = Persistence.createEntityManagerFactory("datamodel"); + modelEMF = Persistence.createEntityManagerFactory("model"); } @Override public EntityManagerFactory getModelEMF() { return modelEMF; } }
true
true
public DatabaseManager(Activator activator) { this.activator = activator; modelEMF = Persistence.createEntityManagerFactory("datamodel"); }
public DatabaseManager(Activator activator) { this.activator = activator; modelEMF = Persistence.createEntityManagerFactory("model"); }
diff --git a/Essentials/src/com/earth2me/essentials/User.java b/Essentials/src/com/earth2me/essentials/User.java index 3e54c094..2c6e998b 100644 --- a/Essentials/src/com/earth2me/essentials/User.java +++ b/Essentials/src/com/earth2me/essentials/User.java @@ -1,320 +1,320 @@ package com.earth2me.essentials; import com.earth2me.essentials.commands.IEssentialsCommand; import com.earth2me.essentials.register.payment.Method; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class User extends UserData implements Comparable<User>, IReplyTo, IUser { private static final Logger logger = Logger.getLogger("Minecraft"); private boolean justPortaled = false; private CommandSender replyTo = null; private User teleportRequester; private boolean teleportRequestHere; private final Teleport teleport; private long lastActivity; User(Player base, IEssentials ess) { super(base, ess); teleport = new Teleport(this, ess); } User update(Player base) { setBase(base); return this; } public boolean isAuthorized(IEssentialsCommand cmd) { return isAuthorized(cmd, "essentials."); } public boolean isAuthorized(IEssentialsCommand cmd, String permissionPrefix) { return isAuthorized(permissionPrefix + (cmd.getName().equals("r") ? "msg" : cmd.getName())); } public boolean isAuthorized(String node) { if (isOp()) { return true; } if (isJailed()) { return false; } return ess.getPermissionsHandler().hasPermission(this, node); } public void healCooldown() throws Exception { Calendar now = new GregorianCalendar(); if (getLastHealTimestamp() > 0) { double cooldown = ess.getSettings().getHealCooldown(); Calendar cooldownTime = new GregorianCalendar(); cooldownTime.setTimeInMillis(getLastHealTimestamp()); cooldownTime.add(Calendar.SECOND, (int)cooldown); cooldownTime.add(Calendar.MILLISECOND, (int)((cooldown * 1000.0) % 1000.0)); if (cooldownTime.after(now) && !isAuthorized("essentials.heal.cooldown.bypass")) { throw new Exception(Util.format("timeBeforeHeal", Util.formatDateDiff(cooldownTime.getTimeInMillis()))); } } setLastHealTimestamp(now.getTimeInMillis()); } public void giveMoney(double value) { giveMoney(value, null); } public void giveMoney(double value, CommandSender initiator) { if (value == 0) { return; } setMoney(getMoney() + value); sendMessage(Util.format("addedToAccount", Util.formatCurrency(value))); if (initiator != null) { - initiator.sendMessage((Util.format("addedToAccount", Util.formatCurrency(value)))); + initiator.sendMessage((Util.format("addedToOthersAccount", Util.formatCurrency(value), this.getDisplayName()))); } } public void payUser(User reciever, double value) throws Exception { if (value == 0) { return; } if (!canAfford(value)) { throw new Exception(Util.i18n("notEnoughMoney")); } else { setMoney(getMoney() - value); reciever.setMoney(reciever.getMoney() + value); sendMessage(Util.format("moneySentTo", Util.formatCurrency(value), reciever.getDisplayName())); reciever.sendMessage(Util.format("moneyRecievedFrom", Util.formatCurrency(value), getDisplayName())); } } public void takeMoney(double value) { takeMoney(value, null); } public void takeMoney(double value, CommandSender initiator) { if (value == 0) { return; } setMoney(getMoney() - value); sendMessage(Util.format("takenFromAccount", Util.formatCurrency(value))); if (initiator != null) { - initiator.sendMessage((Util.format("takenFromAccount", Util.formatCurrency(value)))); + initiator.sendMessage((Util.format("takenFromOthersAccount", Util.formatCurrency(value), this.getDisplayName()))); } } public boolean canAfford(double cost) { double mon = getMoney(); return mon >= cost || isAuthorized("essentials.eco.loan"); } public void dispose() { this.base = new OfflinePlayer(getName()); } public boolean getJustPortaled() { return justPortaled; } public void setJustPortaled(boolean value) { justPortaled = value; } public void setReplyTo(CommandSender user) { replyTo = user; } public CommandSender getReplyTo() { return replyTo; } public int compareTo(User t) { return ChatColor.stripColor(this.getDisplayName()).compareToIgnoreCase(ChatColor.stripColor(t.getDisplayName())); } @Override public boolean equals(Object o) { if (!(o instanceof User)) { return false; } return ChatColor.stripColor(this.getDisplayName()).equalsIgnoreCase(ChatColor.stripColor(((User)o).getDisplayName())); } @Override public int hashCode() { return ChatColor.stripColor(this.getDisplayName()).hashCode(); } public Boolean canSpawnItem(int itemId) { return !ess.getSettings().itemSpawnBlacklist().contains(itemId); } public void setHome() { setHome(getLocation(), true); } public void setHome(boolean defaultHome) { setHome(getLocation(), defaultHome); } public void setLastLocation() { setLastLocation(getLocation()); } public void requestTeleport(User player, boolean here) { teleportRequester = player; teleportRequestHere = here; } public User getTeleportRequest() { return teleportRequester; } public boolean isTeleportRequestHere() { return teleportRequestHere; } public String getNick() { String nickname = getNickname(); if (ess.getSettings().isCommandDisabled("nick") || nickname == null || nickname.isEmpty() || nickname.equals(getName())) { nickname = getName(); } else { nickname = ess.getSettings().getNicknamePrefix() + nickname; } if (isOp()) { try { nickname = ess.getSettings().getOperatorColor().toString() + nickname + "§f"; } catch (Exception e) { } } return nickname; } public Teleport getTeleport() { return teleport; } public long getLastActivity() { return lastActivity; } public void setLastActivity(long timestamp) { lastActivity = timestamp; } @Override public double getMoney() { if (ess.isRegisterFallbackEnabled() && ess.getPaymentMethod().hasMethod()) { try { Method method = ess.getPaymentMethod().getMethod(); if (!method.hasAccount(this.getName())) { throw new Exception(); } Method.MethodAccount account = ess.getPaymentMethod().getMethod().getAccount(this.getName()); return account.balance(); } catch (Throwable ex) { } } return super.getMoney(); } @Override public void setMoney(double value) { if (ess.isRegisterFallbackEnabled() && ess.getPaymentMethod().hasMethod()) { try { Method method = ess.getPaymentMethod().getMethod(); if (!method.hasAccount(this.getName())) { throw new Exception(); } Method.MethodAccount account = ess.getPaymentMethod().getMethod().getAccount(this.getName()); account.set(value); } catch (Throwable ex) { } } super.setMoney(value); } @Override public void setAfk(boolean set) { this.setSleepingIgnored(set); super.setAfk(set); } @Override public boolean toggleAfk() { boolean now = super.toggleAfk(); this.setSleepingIgnored(now); return now; } }
false
false
null
null
diff --git a/src/flow/netbeans/markdown/options/MarkdownPanel.java b/src/flow/netbeans/markdown/options/MarkdownPanel.java index c4f3039..f22f01c 100644 --- a/src/flow/netbeans/markdown/options/MarkdownPanel.java +++ b/src/flow/netbeans/markdown/options/MarkdownPanel.java @@ -1,274 +1,275 @@ package flow.netbeans.markdown.options; import org.openide.util.NbPreferences; public final class MarkdownPanel extends javax.swing.JPanel { private final MarkdownOptionsPanelController controller; MarkdownPanel(MarkdownOptionsPanelController controller) { this.controller = controller; initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jCheckBox1 = new javax.swing.JCheckBox(); TABS = new javax.swing.JTabbedPane(); EXTENSIONS_PANEL = new javax.swing.JPanel(); EXTENSIONS_PANEL_HEADER = new javax.swing.JLabel(); SMARTS = new javax.swing.JCheckBox(); QUOTES = new javax.swing.JCheckBox(); ABBREVIATIONS = new javax.swing.JCheckBox(); HARDWRAPS = new javax.swing.JCheckBox(); AUTOLINKS = new javax.swing.JCheckBox(); TABLES = new javax.swing.JCheckBox(); DEFINITION_LISTS = new javax.swing.JCheckBox(); FENCED_CODE_BLOCKS = new javax.swing.JCheckBox(); HTML_BLOCK_SUPPRESSION = new javax.swing.JCheckBox(); INLINE_HTML_SUPPRESSION = new javax.swing.JCheckBox(); WIKILINKS = new javax.swing.JCheckBox(); HTML_EXPORT_PANEL = new javax.swing.JPanel(); HTML_PANEL_HEADER = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); HTML_TEMPLATE = new javax.swing.JTextArea(); org.openide.awt.Mnemonics.setLocalizedText(jCheckBox1, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.jCheckBox1.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(EXTENSIONS_PANEL_HEADER, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.EXTENSIONS_PANEL_HEADER.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(SMARTS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.SMARTS.text")); // NOI18N SMARTS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.SMARTS.toolTipText")); // NOI18N SMARTS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SMARTSActionPerformed(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(QUOTES, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.QUOTES.text")); // NOI18N QUOTES.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.QUOTES.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(ABBREVIATIONS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.ABBREVIATIONS.text")); // NOI18N ABBREVIATIONS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.ABBREVIATIONS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(HARDWRAPS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HARDWRAPS.text")); // NOI18N HARDWRAPS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HARDWRAPS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(AUTOLINKS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.AUTOLINKS.text")); // NOI18N AUTOLINKS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.AUTOLINKS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(TABLES, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.TABLES.text")); // NOI18N TABLES.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.TABLES.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(DEFINITION_LISTS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.DEFINITION_LISTS.text")); // NOI18N DEFINITION_LISTS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.DEFINITION_LISTS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(FENCED_CODE_BLOCKS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.FENCED_CODE_BLOCKS.text")); // NOI18N FENCED_CODE_BLOCKS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.FENCED_CODE_BLOCKS.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(HTML_BLOCK_SUPPRESSION, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HTML_BLOCK_SUPPRESSION.text")); // NOI18N HTML_BLOCK_SUPPRESSION.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HTML_BLOCK_SUPPRESSION.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(INLINE_HTML_SUPPRESSION, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.INLINE_HTML_SUPPRESSION.text")); // NOI18N INLINE_HTML_SUPPRESSION.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.INLINE_HTML_SUPPRESSION.toolTipText")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(WIKILINKS, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.WIKILINKS.text")); // NOI18N WIKILINKS.setToolTipText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.WIKILINKS.toolTipText")); // NOI18N javax.swing.GroupLayout EXTENSIONS_PANELLayout = new javax.swing.GroupLayout(EXTENSIONS_PANEL); EXTENSIONS_PANEL.setLayout(EXTENSIONS_PANELLayout); EXTENSIONS_PANELLayout.setHorizontalGroup( EXTENSIONS_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(EXTENSIONS_PANELLayout.createSequentialGroup() .addContainerGap() .addGroup(EXTENSIONS_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(EXTENSIONS_PANEL_HEADER, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(EXTENSIONS_PANELLayout.createSequentialGroup() .addGroup(EXTENSIONS_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(INLINE_HTML_SUPPRESSION) .addComponent(SMARTS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(QUOTES, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(ABBREVIATIONS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(HARDWRAPS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(AUTOLINKS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(TABLES, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(DEFINITION_LISTS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(FENCED_CODE_BLOCKS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(HTML_BLOCK_SUPPRESSION, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(WIKILINKS, javax.swing.GroupLayout.PREFERRED_SIZE, 412, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 118, Short.MAX_VALUE)))) ); EXTENSIONS_PANELLayout.setVerticalGroup( EXTENSIONS_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, EXTENSIONS_PANELLayout.createSequentialGroup() .addContainerGap() .addComponent(EXTENSIONS_PANEL_HEADER) .addGap(17, 17, 17) .addComponent(SMARTS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(QUOTES) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(ABBREVIATIONS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(HARDWRAPS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(AUTOLINKS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(TABLES) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(DEFINITION_LISTS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(FENCED_CODE_BLOCKS) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(HTML_BLOCK_SUPPRESSION) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(INLINE_HTML_SUPPRESSION) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(WIKILINKS) .addContainerGap(61, Short.MAX_VALUE)) ); TABS.addTab(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.EXTENSIONS_PANEL.TabConstraints.tabTitle"), EXTENSIONS_PANEL); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(HTML_PANEL_HEADER, org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HTML_PANEL_HEADER.text")); // NOI18N HTML_TEMPLATE.setColumns(20); HTML_TEMPLATE.setRows(5); HTML_TEMPLATE.setText(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HTML_TEMPLATE.text")); // NOI18N jScrollPane1.setViewportView(HTML_TEMPLATE); javax.swing.GroupLayout HTML_EXPORT_PANELLayout = new javax.swing.GroupLayout(HTML_EXPORT_PANEL); HTML_EXPORT_PANEL.setLayout(HTML_EXPORT_PANELLayout); HTML_EXPORT_PANELLayout.setHorizontalGroup( HTML_EXPORT_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(HTML_EXPORT_PANELLayout.createSequentialGroup() .addContainerGap() .addGroup(HTML_EXPORT_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(HTML_PANEL_HEADER, javax.swing.GroupLayout.DEFAULT_SIZE, 575, Short.MAX_VALUE) .addGroup(HTML_EXPORT_PANELLayout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 522, Short.MAX_VALUE) .addGap(8, 8, 8)))) ); HTML_EXPORT_PANELLayout.setVerticalGroup( HTML_EXPORT_PANELLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(HTML_EXPORT_PANELLayout.createSequentialGroup() .addContainerGap() .addComponent(HTML_PANEL_HEADER) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 347, Short.MAX_VALUE) .addContainerGap()) ); TABS.addTab(org.openide.util.NbBundle.getMessage(MarkdownPanel.class, "MarkdownPanel.HTML_EXPORT_PANEL.TabConstraints.tabTitle"), HTML_EXPORT_PANEL); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(TABS) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(1, 1, 1) .addComponent(TABS)) ); }// </editor-fold>//GEN-END:initComponents private void SMARTSActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SMARTSActionPerformed // TODO add your handling code here: }//GEN-LAST:event_SMARTSActionPerformed void load() { // TODO read settings and initialize GUI // Example: // someCheckBox.setSelected(Preferences.userNodeForPackage(MarkdownPanel.class).getBoolean("someFlag", false)); // or for org.openide.util with API spec. version >= 7.4: // someCheckBox.setSelected(NbPreferences.forModule(MarkdownPanel.class).getBoolean("someFlag", false)); // or: // someTextField.setText(SomeSystemOption.getDefault().getSomeStringProperty()); ABBREVIATIONS.setSelected(NbPreferences.forModule(MarkdownPanel.class).getBoolean("ABBREVIATIONS", false)); AUTOLINKS.setSelected(NbPreferences.forModule(MarkdownPanel.class).getBoolean("AUTOLINKS", false)); DEFINITION_LISTS.setSelected(NbPreferences.forModule(MarkdownPanel.class).getBoolean("DEFINITION_LISTS", false)); FENCED_CODE_BLOCKS.setSelected(NbPreferences.forModule(MarkdownPanel.class).getBoolean("FENCED_CODE_BLOCKS", false)); HARDWRAPS.setSelected(NbPreferences.forModule(MarkdownPanel.class).getBoolean("HARDWRAPS", false)); HTML_BLOCK_SUPPRESSION.setSelected(NbPreferences.forModule(MarkdownPanel.class).getBoolean("HTML_BLOCK_SUPPRESSION", false)); INLINE_HTML_SUPPRESSION.setSelected(NbPreferences.forModule(MarkdownPanel.class).getBoolean("INLINE_HTML_SUPPRESSION", false)); QUOTES.setSelected(NbPreferences.forModule(MarkdownPanel.class).getBoolean("QUOTES", false)); SMARTS.setSelected(NbPreferences.forModule(MarkdownPanel.class).getBoolean("SMARTS", false)); TABLES.setSelected(NbPreferences.forModule(MarkdownPanel.class).getBoolean("TABLES", false)); WIKILINKS.setSelected(NbPreferences.forModule(MarkdownPanel.class).getBoolean("WIKILINKS", false)); HTML_TEMPLATE.setText(NbPreferences.forModule(MarkdownPanel.class).get("HTML_TEMPLATE", getDefaultHtmlTemplate())); } void store() { // TODO store modified settings // Example: // Preferences.userNodeForPackage(MarkdownPanel.class).putBoolean("someFlag", someCheckBox.isSelected()); // or for org.openide.util with API spec. version >= 7.4: // NbPreferences.forModule(MarkdownPanel.class).putBoolean("someFlag", someCheckBox.isSelected()); // or: // SomeSystemOption.getDefault().setSomeStringProperty(someTextField.getText()); NbPreferences.forModule(MarkdownPanel.class).putBoolean("ABBREVIATIONS", ABBREVIATIONS.isSelected()); NbPreferences.forModule(MarkdownPanel.class).putBoolean("AUTOLINKS", AUTOLINKS.isSelected()); NbPreferences.forModule(MarkdownPanel.class).putBoolean("DEFINITION_LISTS", DEFINITION_LISTS.isSelected()); NbPreferences.forModule(MarkdownPanel.class).putBoolean("FENCED_CODE_BLOCKS", FENCED_CODE_BLOCKS.isSelected()); NbPreferences.forModule(MarkdownPanel.class).putBoolean("HARDWRAPS", HARDWRAPS.isSelected()); NbPreferences.forModule(MarkdownPanel.class).putBoolean("HTML_BLOCK_SUPPRESSION", HTML_BLOCK_SUPPRESSION.isSelected()); NbPreferences.forModule(MarkdownPanel.class).putBoolean("INLINE_HTML_SUPPRESSION", INLINE_HTML_SUPPRESSION.isSelected()); NbPreferences.forModule(MarkdownPanel.class).putBoolean("QUOTES", QUOTES.isSelected()); NbPreferences.forModule(MarkdownPanel.class).putBoolean("SMARTS", SMARTS.isSelected()); NbPreferences.forModule(MarkdownPanel.class).putBoolean("TABLES", TABLES.isSelected()); NbPreferences.forModule(MarkdownPanel.class).putBoolean("WIKILINKS", WIKILINKS.isSelected()); NbPreferences.forModule(MarkdownPanel.class).put("HTML_TEMPLATE", HTML_TEMPLATE.getText()); } public static String getDefaultHtmlTemplate() { - return "<html>\n" + return "<!DOCTYPE html>" + + "<html>\n" + "<head>\n" + "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n" + "<title>{%TITLE%}</title>\n" + "<style type=\"text/css\">/*...*/</style>\n" + "</head>\n" + "<body>\n" + "{%CONTENT%}\n" + "</body\n>" + "</html>"; } boolean valid() { return true; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JCheckBox ABBREVIATIONS; private javax.swing.JCheckBox AUTOLINKS; private javax.swing.JCheckBox DEFINITION_LISTS; private javax.swing.JPanel EXTENSIONS_PANEL; private javax.swing.JLabel EXTENSIONS_PANEL_HEADER; private javax.swing.JCheckBox FENCED_CODE_BLOCKS; private javax.swing.JCheckBox HARDWRAPS; private javax.swing.JCheckBox HTML_BLOCK_SUPPRESSION; private javax.swing.JPanel HTML_EXPORT_PANEL; private javax.swing.JLabel HTML_PANEL_HEADER; private javax.swing.JTextArea HTML_TEMPLATE; private javax.swing.JCheckBox INLINE_HTML_SUPPRESSION; private javax.swing.JCheckBox QUOTES; private javax.swing.JCheckBox SMARTS; private javax.swing.JCheckBox TABLES; private javax.swing.JTabbedPane TABS; private javax.swing.JCheckBox WIKILINKS; private javax.swing.JCheckBox jCheckBox1; private javax.swing.JScrollPane jScrollPane1; // End of variables declaration//GEN-END:variables }
true
false
null
null
diff --git a/src/com/example/simplevrcontroller/gamepad/Gamepad.java b/src/com/example/simplevrcontroller/gamepad/Gamepad.java index 914c3a2..b64c4ba 100644 --- a/src/com/example/simplevrcontroller/gamepad/Gamepad.java +++ b/src/com/example/simplevrcontroller/gamepad/Gamepad.java @@ -1,1155 +1,1149 @@ package com.example.simplevrcontroller.gamepad; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.Color; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; -import android.media.Ringtone; -import android.media.RingtoneManager; -import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; -import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Spinner; -import android.widget.TableLayout; import android.widget.TextView; import android.widget.Toast; import com.example.simplevrcontroller.MainActivity; import com.example.simplevrcontroller.R; import com.example.simplevrcontroller.cave.Cave; import com.example.simplevrcontroller.cave.CaveManager; // public class Gamepad extends Activity implements OnTouchListener, SensorEventListener{ // Sockets private InetAddress serverAddr; private DatagramSocket socket; private boolean socketOpen = false; private Cave cave; private int _port = 8888; private String _nodeName = null; private String _axis = null; private Map<String, Boolean> nodeOn = new HashMap<String, Boolean>();; // Type for queueing in CalVR static final int COMMAND = 7; static final int NAVI = 8; static final int NODE = 9; // What data type is being sent to socket // Movement type static final int ROT = 10; static final int TRANS = 11; static final int ZTRANS = 12; static final int VELOCITY = 13; static final int MOVE_NODE = 14; // Mode static final int FLY = 20; static final int DRIVE = 21; static final int ROTATE = 22; static final int NEW_FLY = 23; //Command static final int CONNECT = 30; static final int FLIP = 32; static final int FETCH = 34; static final int SELECTNODE = 35; static final int HIDE = 31; static final int SHOW = 33; // Booleans for checks boolean invert_pitch = false; boolean invert_roll = false; boolean toggle_pitch = false; boolean toggle_roll = false; boolean onNavigation = false; boolean onIp = false; boolean motionOn = true; boolean onNode = false; boolean onNodeMove = false; boolean onNodeType = false; // For Touch data Double[] coords = {0d, 0d}; //Only x and y Double[] z_coord = {0d}; //Handles z coord double x = 0.0; double y = 0.0; boolean move = false; boolean zoom = false; double magnitude = 1d; double new_mag = 1d; View touchControll, speed; // For Sensor Values private SensorManager sense = null; float[] accelData = new float[3]; float[] magnetData = new float[3]; float[] rotationMatrix = new float[16]; Double[] resultingAngles = {0.0, 0.0, 0.0}; Double[] previousAngles = {0d, 0d, 0d}; Double[] recalibration = {0.0, 0.0, 0.0}; Double[] prepare = {0.0, 0.0, 0.0}; double MIN_DIFF = 0.05d; float[] gravity = {0f, 0f, 0f}; - Double orient = 0d; // Velocity Double[] velocity = {0d}; long timeStart; TextView velText; // For Node Movement double height_adjust = 0d; double mag = 1d; double x_node = 0d; double y_node = 0d; Double[] adjustment = {0d, 0d, 0d}; // Data inputs // Main Navigation Screen TextView sensorText; TextView ipText; TextView accelText; SharedPreferences textValues; SharedPreferences.Editor text_editor; int height; int width; float xdpi; float ydpi; // Ip Screen // Main Node Screen -- Find Nodes Spinner nodeOptions; SharedPreferences nodesFound; ArrayAdapter<CharSequence> nodeAdapter; Map<String, String> nodeCollection; SharedPreferences.Editor node_editor; // For SharedPreferences public static final String PREF_IP = "IpPrefs"; public static final String PREF_DATA = "DataPref"; public static final String PREF_NODES = "NodesPref"; final String IPVALUE = "IPVALUE"; final String MODEVALUE = "MODEVALUE"; final String VELVALUE = "VELVALUE"; // For Log static String LOG_TAG = "Gamepad"; /* * Called on program create * Establishes Landscape Orientation * Calculates screen dimensions for later use * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); sense = (SensorManager)getSystemService(SENSOR_SERVICE); cave = CaveManager.getCaveManager().getCave(getIntent().getExtras().getString("CAVE")); getWindow().setBackgroundDrawableResource(R.drawable.techback); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); setContentView(R.layout.main); this.getActionBar().setHomeButtonEnabled(true); textValues = getSharedPreferences(PREF_DATA, 0); text_editor = textValues.edit(); motionOn = true; // Calculates screen dimensions DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); int statusHeight; switch(metrics.densityDpi){ case DisplayMetrics.DENSITY_HIGH: statusHeight = 38; // HIGH DPI STATUS HEIGHT break; case DisplayMetrics.DENSITY_LOW: statusHeight = 19; // LOW DPI STATUS HEIGHT break; case DisplayMetrics.DENSITY_MEDIUM: default: statusHeight = 25; // MEDIUM DPI STATUS HEIGHT break; } ydpi = metrics.ydpi - statusHeight; height = (int) ((ydpi * getResources().getDisplayMetrics().density + 0.5f)/3f); xdpi = metrics.xdpi * getResources().getDisplayMetrics().density + 0.5f; width = (int) (xdpi/3f); AsyncTask.execute(new Runnable(){ @Override public void run() { openSocket(); } }); try { Thread.sleep(500); int failed = 0; while(!socketOpen){ failed++; if(failed < 5){ Toast.makeText(this, "Failed to connect, trying again...", Toast.LENGTH_SHORT).show(); Thread.sleep(500); } else { Toast.makeText(this, "Could not connect to host!", Toast.LENGTH_LONG).show(); return; } } } catch(InterruptedException e){ e.printStackTrace(); } onMainStart(); } /* * Removes sensor listeners and clears text fields in SharedPreferences * @see android.app.Activity#onPause() */ @Override protected void onPause(){ super.onPause(); sense.unregisterListener(this); closeSocket(); text_editor.clear(); text_editor.commit(); } /* * Registers listener for acceleration and magnetic_field data * @see android.app.Activity#onResume() */ @Override protected void onResume(){ super.onResume(); sense.registerListener(this, sense.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST); sense.registerListener(this, sense.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_FASTEST); sense.registerListener(this, sense.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_FASTEST); onMainStart(); } /* * From here you either select Navigation or Node */ protected void onMainStart(){ Button navigation = (Button) findViewById(R.id.navigationButton); Button nodeControl= (Button) findViewById(R.id.nodeButton); navigation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onNode = false; setContentView(R.layout.main_navigation); onNavigationStart(); onNavigation = true; invalidateOptionsMenu(); } }); nodeControl.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onNavigation = false; setContentView(R.layout.find_node); onNodeMainStart(); node_editor.clear(); node_editor.commit(); nodeAdapter.clear(); onNode = true; invalidateOptionsMenu(); } }); } /* * Sets up main navigation screen: * Faster button -- increases velocity on touch * Slower button -- decreases velocity on touch * Stop button -- pauses all rotation movement and resets velocity to 0. * Also recalibrates orientation such that current orientation is the standard orientation. */ protected void onNavigationStart(){ try{ Log.d("Navigation", "Initialization"); LinearLayout layout = (LinearLayout) findViewById(R.id.navigationLayout); layout.setOnTouchListener((OnTouchListener) this); layout.setKeepScreenOn(true); sensorText = (TextView) findViewById(R.id.sensorText); ipText = (TextView) findViewById(R.id.ipText); accelText = (TextView) findViewById(R.id.accelData); velText = (TextView) findViewById(R.id.velocity); touchControll = findViewById(R.id.touchControl); speed = findViewById(R.id.speed); speed.setBackgroundColor(Color.GRAY); speed.setAlpha(.7f); velText.setWidth(width); ipText.setWidth(width); sensorText.setWidth(width); accelText.setWidth(width); Log.d("Navigation", "" + socket.isConnected()); ipText.setText(socket.getInetAddress() .getHostAddress()); sensorText.setText(textValues.getString(MODEVALUE, "Mode: Select Mode")); velText.setText(textValues.getString(VELVALUE, "Velocity: 0")); touchControll.setOnTouchListener(this); speed.setOnTouchListener(new OnTouchListener(){ private float old; @Override public boolean onTouch(View v, MotionEvent event) { Log.d("Touch", "" + event.getAction() + " " + MotionEvent.ACTION_MOVE); float dy = 0; if(event.getAction() == MotionEvent.ACTION_UP){ dy = 0; speed.setBackgroundColor(Color.GRAY); speed.setAlpha(.7f); } else if(event.getAction() == MotionEvent.ACTION_DOWN) old = event.getY(); else if(event.getAction() == MotionEvent.ACTION_MOVE) dy = old - event.getY(); velocity[0] = roundDecimal(dy); if(dy != 0) speed.setAlpha((Math.abs(dy)/ (speed.getHeight() / 2))); if(dy > 0) speed.setBackgroundColor(Color.GREEN); else if(dy < 0) speed.setBackgroundColor(Color.RED); sendSocketDoubles(VELOCITY, velocity, 1, NAVI); velText.setText("Velocity: " + velocity[0]); return true; } }); } catch(Exception e){ Log.e(LOG_TAG, "Exception in NavigationStart: " + e.getMessage()); e.printStackTrace(); } } /* * Main Node loaded * find -- sends a request to find all AndroidTransform nodes. Calls getNodes() to return them. * selectNode -- whichever node is selected in the nodeOptions spinner becomes the selected node to act upon * hideNodes -- hides the selected node */ @SuppressWarnings("unchecked") protected void onNodeMainStart(){ try{ nodesFound = getSharedPreferences(PREF_NODES, 0); node_editor = nodesFound.edit(); nodeOptions = (Spinner) findViewById(R.id.nodeOptions); Button find = (Button) findViewById(R.id.findNodesButton); Button selectNode = (Button) findViewById(R.id.selectNodeButton); final CheckBox hideNodes = (CheckBox) findViewById(R.id.hideNodeBox); hideNodes.setClickable(false); // Allows spinner to dynamically update ip addresses. CharSequence[] nodeArray = getResources().getTextArray(R.array.nodes_array); List<CharSequence> nodeNames = new ArrayList<CharSequence>(Arrays.asList(nodeArray)); nodeAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, nodeNames); nodeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); nodeOptions.setAdapter(nodeAdapter); nodeOptions.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { _nodeName = parent.getItemAtPosition(pos).toString(); } public void onNothingSelected(AdapterView<?> parent) { // Do nothing. } }); find.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { node_editor.clear(); node_editor.commit(); nodeAdapter.clear(); nodeOptions.setAdapter(nodeAdapter); if(!nodeOn.isEmpty()) nodeOn.clear(); hideNodes.setClickable(false); getNodes(); } }); selectNode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(_nodeName != null){ sendSocketString(SELECTNODE, _nodeName); if(socketOpen) Toast.makeText(Gamepad.this, "Selecting " + _nodeName, Toast.LENGTH_SHORT).show(); hideNodes.setClickable(true); Boolean on = nodeOn.get(_nodeName); if(on){ hideNodes.setChecked(false); } else{ hideNodes.setChecked(true); } } else{ Toast.makeText(Gamepad.this, "No node selected", Toast.LENGTH_SHORT).show(); } } }); nodeCollection = (Map<String, String>) nodesFound.getAll(); if(!nodeCollection.isEmpty()){ Iterator<String> over = nodeCollection.values().iterator(); while(over.hasNext()){ String temp = over.next(); nodeAdapter.add(temp); } } hideNodes.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(_nodeName != null){ if(hideNodes.isChecked()){ sendSocketCommand(HIDE, "HideNode"); Toast.makeText(Gamepad.this, "Hiding " + _nodeName, Toast.LENGTH_SHORT).show(); nodeOn.remove(_nodeName); nodeOn.put(_nodeName, false); } else{ sendSocketCommand(SHOW, "ShowNode"); Toast.makeText(Gamepad.this, "Showing " + _nodeName, Toast.LENGTH_SHORT).show(); nodeOn.remove(_nodeName); nodeOn.put(_nodeName, true); } } else{ Toast.makeText(Gamepad.this, "No node selected", Toast.LENGTH_SHORT).show(); if(hideNodes.isChecked()){ hideNodes.setChecked(false); } else{ hideNodes.setChecked(true); } } } }); } catch(Exception e){ Log.w(LOG_TAG, "Exception in IP Loader: " + e.getMessage()); onIp = false; } } /* * Moves the actual node * selectAxisButton -- picks an axis to work on X, Y, Z Trans, X, Y, Z Rotation * When you move, the x-axis is the magnitude (increases to the right) and the y-axis is the axis you're moving on. */ protected void onNodeMove(){ LinearLayout layout = (LinearLayout) findViewById(R.id.moveNodeLayout); // main layout Button selectAxisButton = (Button) findViewById(R.id.selectAxisButton); selectAxisButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String[] axisOptions = {"X Trans", "Y Trans", "Z Trans", "X Rot", "Y Rot", "Z Rot"}; AlertDialog.Builder builder = new AlertDialog.Builder(Gamepad.this); builder.setItems(axisOptions, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { _axis = String.valueOf(which); Toast.makeText(Gamepad.this, axisOptions[which] + " selected.", Toast.LENGTH_SHORT).show(); } }); builder.show(); } }); layout.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event) { switch(event.getAction() & MotionEvent.ACTION_MASK){ case MotionEvent.ACTION_DOWN: height_adjust = event.getY(); break; case MotionEvent.ACTION_MOVE: mag = (event.getX())/xdpi; adjustment[0] = roundDecimal(event.getY() - height_adjust); adjustment[1] = roundDecimal(mag); height_adjust = event.getY(); sendSocketDoubles(MOVE_NODE, adjustment, 2, NODE); break; } return true; } }); layout.setKeepScreenOn(true); } /* * Gets node names from CalVR (after find is selected in onNodeMainStart()) */ public boolean getNodes(){ if (!socketOpen) { if (onNode) Toast.makeText(Gamepad.this, "Not connected...", Toast.LENGTH_SHORT).show(); return false; } try{ sendSocketCommand(FETCH, "Fetch Nodes"); // First -- receive how many // Second -- receive all strings byte[] data = new byte[1024]; DatagramPacket get = new DatagramPacket(data, 1024); receiveSocket(get); int num = byteToInt(data); for(int i = 0; i< num; i++){ byte[] dataSize = new byte[Integer.SIZE]; DatagramPacket getSize = new DatagramPacket(dataSize, Integer.SIZE); receiveSocket(getSize); byte[] dataName = new byte[byteToInt(dataSize)]; DatagramPacket getName = new DatagramPacket(dataName, byteToInt(dataSize)); receiveSocket(getName); String temp = new String(dataName); node_editor.putString(temp, temp); nodeAdapter.add(temp); nodeOn.put(temp, true); } node_editor.commit(); } catch (Exception ie){ Toast.makeText(Gamepad.this, "Exception in getting Nodes! " + ie.getMessage(), Toast.LENGTH_SHORT).show(); Log.w(LOG_TAG, "Exception getNodes: " + ie.getMessage()); ie.printStackTrace(); } return true; } public void receiveSocket(DatagramPacket pack) throws InterruptedException, ExecutionException, IOException{ IOException e = new AsyncTask<DatagramPacket, Void, IOException>(){ @Override protected IOException doInBackground(DatagramPacket... params) { for(DatagramPacket pack : params) try { socket.receive(pack); } catch (IOException e) { return e; } return null; } }.execute(pack).get(); if(e != null) throw e; } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu){ MenuInflater inflater = getMenuInflater(); menu.clear(); if(onNavigation) { inflater.inflate(R.menu.navi_menu, menu); } else if(onNode) { inflater.inflate(R.menu.node_menu, menu); } else{ inflater.inflate(R.menu.main_menu, menu); } return true; } /* * Handles when menu and submenu options are selected: * subFly -- enters fly mode -- NAVI * subNewFly -- enters new fly mode -- NAVI * subDrive -- enters Drive mode -- NAVI * subMove -- enters Rotate world mode -- NAVI * address -- toggles on/off ip selection screen -- NAVI/NODE * invertPitch -- inverts pitch -- NAVI * invertRoll -- inverts roll -- NAVI * togglePitch -- toggles pitch -- NAVI * toggleRoll -- toggles roll -- NAVI * moveNodesMenu -- goes to move node menu screen -- NODE * findNodesMenu -- goes to find node menu screen -- NODE * returnMain -- returns to Main screen -- NAVI/NODE * This is where you pick either Navigation page or Node page * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { // NAVIGATION //MOVEMENT TYPE case android.R.id.home: // app icon in action bar clicked; go home Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); return true; case R.id.subFly: sendSocketCommand(FLY, "Fly"); break; case R.id.subNewFly: sendSocketCommand(NEW_FLY, "New Fly"); break; case R.id.subDrive: sendSocketCommand(DRIVE, "Drive"); break; case R.id.subMove: sendSocketCommand(ROTATE, "Rotate World"); break; // OPTIONS FOR PITCH/ROLL case R.id.invertPitch: if(invert_pitch){ invert_pitch = false; Toast.makeText(Gamepad.this, "Reverting Pitch", Toast.LENGTH_SHORT).show(); } else{ invert_pitch = true; Toast.makeText(Gamepad.this, "Inverting Pitch", Toast.LENGTH_SHORT).show(); } break; case R.id.invertRoll: if(invert_roll){ invert_roll = false; Toast.makeText(Gamepad.this, "Reverting Roll", Toast.LENGTH_SHORT).show(); } else{ invert_roll = true; Toast.makeText(Gamepad.this, "Inverting Roll", Toast.LENGTH_SHORT).show(); } break; case R.id.togglePitch: if(toggle_pitch){ toggle_pitch = false; Toast.makeText(Gamepad.this, "Pitch On", Toast.LENGTH_SHORT).show(); } else{ toggle_pitch = true; Toast.makeText(Gamepad.this, "Pitch Off", Toast.LENGTH_SHORT).show(); } break; case R.id.toggleRoll: if(toggle_roll){ toggle_roll = false; Toast.makeText(Gamepad.this, "Roll On", Toast.LENGTH_SHORT).show(); } else{ toggle_roll = true; Toast.makeText(Gamepad.this, "Roll Off", Toast.LENGTH_SHORT).show(); } break; // NODE CONTROL // MOVE NODE case R.id.moveNodesMenu: if (!onNodeMove){ setContentView(R.layout.move_node); onNodeMove = true; onNodeMove(); } else{ onNodeMove = false; setContentView(R.layout.find_node); onNodeMainStart(); } break; // FIND NODES (MAIN PAGE) case R.id.findNodesMenu: onNodeMove = false; setContentView(R.layout.find_node); onNodeMainStart(); break; // RETURNS TO MAIN SCREEN case R.id.returnMain: setContentView(R.layout.main); onMainStart(); onIp = false; onNavigation = false; onNode = false; onNodeMove = false; break; } return true; } /* * Sets up socket using _ip given by spinner (MyOnItemSelectedListener and ipValues) */ public void openSocket(){ Log.d("SocketOpen", "Connecting..."); if (socketOpen) return; try{ serverAddr = InetAddress.getByName(cave.getAddress()); socket = new DatagramSocket(); socket.connect(serverAddr, _port); socketOpen = true; socket.setSoTimeout(1000); Log.d("SocketOpen", "Socket Opened!"); return; } catch (IOException ie){ Log.w(LOG_TAG, "IOException Opening: " + ie.getMessage()); Toast.makeText(Gamepad.this, "IOException Opening!: " + ie.getMessage() , Toast.LENGTH_SHORT).show(); } catch (Exception e){ Log.w(LOG_TAG, "Exception: " + e.getMessage()); e.printStackTrace(); } Log.d("SocketOpen", "Failed to open!"); } // Says socket is closed. public void closeSocket(){ socketOpen = false; } /** * Sends menu command to socket. * Receives confirmation messages and then updates layout accordingly (updateLayout(int, int)) */ public void sendSocketCommand(int tag, String textStr){ if (!socketOpen) { if (onNode) Toast.makeText(Gamepad.this, "Not connected...", Toast.LENGTH_SHORT).show(); return; } try{ byte[] bytes = (String.valueOf(COMMAND) + String.valueOf(tag) + " ").getBytes(); sendPacket(new DatagramPacket(bytes, bytes.length, serverAddr, _port)); // Gets tag back confirming message sent byte[] data = new byte[Integer.SIZE]; DatagramPacket get = new DatagramPacket(data, Integer.SIZE); receiveSocket(get); int value = byteToInt(data); updateLayout(value); } catch (Exception ie){ if (tag == CONNECT) Toast.makeText(Gamepad.this, "Cannot Connect. Please reconnect to proper IP.", Toast.LENGTH_SHORT).show(); else{ Toast.makeText(Gamepad.this, "Exception in Sending! " + ie.getMessage(), Toast.LENGTH_SHORT).show(); Log.w(LOG_TAG, "Exception Sending: " + ie.getMessage()); } } } /** * Sends a double[] as a byte[] to server * Used to send touch and rotation data * * Double[tag, size of value, value, size of value 2, value 2, ...] */ public void sendSocketDoubles(int tag, Double[] value, int arrayLength, int type){ if (!socketOpen) { if (onNode) Toast.makeText(Gamepad.this, "Not connected...", Toast.LENGTH_SHORT).show(); return; } String send = String.valueOf(type) + String.valueOf(tag); for(int i = 0; i< arrayLength; i++){ send += (" " + String.valueOf(value[i])); } send += " "; if(tag == MOVE_NODE){ send += _axis + " "; } byte[] bytes = send.getBytes(); sendPacket(new DatagramPacket(bytes, bytes.length, serverAddr, _port)); } /* * Sends a double[] as a byte[] to server * Used to send touch and rotation data * * Double[tag, size of value, value, size of value 2, value 2, ...] */ public void sendSocketString(int tag, String str){ if (!socketOpen) { if (onNode) Toast.makeText(Gamepad.this, "Not connected...", Toast.LENGTH_SHORT).show(); return; } String send = String.valueOf(NODE) + String.valueOf(tag) + " " + str + " "; byte[] bytes = new byte[send.getBytes().length]; bytes = send.getBytes(); sendPacket(new DatagramPacket(bytes, bytes.length, serverAddr, _port)); } protected void sendPacket(final DatagramPacket p){ AsyncTask.execute(new Runnable(){ @Override public void run() { try { socket.send(p); } catch (IOException e) { Toast.makeText(Gamepad.this, "IOException in Sending! " + e.getMessage(), Toast.LENGTH_SHORT).show(); Log.w(LOG_TAG, "IOException Sending: " + e.getMessage()); e.printStackTrace(); } } }); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // Not used... } /** * Processes sensor changes * Accelerometer -- passes through low-pass filter to reduce error * Magnetic Field * Uses data to calculate orientation (rotationMatrix) * Compares new orientation data with previous data to check threshold (MIN_DIFF) * Also checks to see if data has been toggle/inverted and performs appropriately * Finally, sends data to sendSocketDouble to pass to server * * @see android.hardware.SensorEventListener#onSensorChanged(android.hardware.SensorEvent) */ @Override public void onSensorChanged(SensorEvent s) { if(!onNavigation) return; if(!motionOn) return; final float alpha = .5f; System.arraycopy(resultingAngles, 0, previousAngles, 0, 3); synchronized(this){ int type = s.sensor.getType(); if (type == Sensor.TYPE_ACCELEROMETER){ // Low-pass filter accelData[0] = gravity[0] + alpha*(s.values[0] - gravity[0]); accelData[1] = gravity[1] + alpha*(s.values[1] - gravity[1]); accelData[2] = gravity[2] + alpha*(s.values[2] - gravity[2]); gravity[0] = accelData[0]; gravity[1] = accelData[1]; gravity[2] = accelData[2]; } if(type == Sensor.TYPE_MAGNETIC_FIELD){ magnetData = s.values.clone(); } - if(type == Sensor.TYPE_ORIENTATION){ - orient = (double) s.values[0]; - } } // Gets a rotation matrix to calculate angles SensorManager.getRotationMatrix(rotationMatrix, null, accelData, magnetData); float[] anglesInRadians = new float[3]; // Uses orientation to get angles SensorManager.getOrientation(rotationMatrix, anglesInRadians); //TODO: Temporary fix for inversion float tmp = -anglesInRadians[1]; anglesInRadians[1] = -anglesInRadians[2]; anglesInRadians[2] = tmp; // Checks if angles have changed enough boolean run = false; // Gets difference between result and previous angles for limiting buffer for (int i = 1; i < 3; i++){ resultingAngles[i] = roundDecimal((double)anglesInRadians[i]); prepare[i] = resultingAngles[i]; resultingAngles[i] = roundDecimal(resultingAngles[i] - recalibration[i]); if(i == 1){ if(invert_roll) resultingAngles[i] *= -1; if(toggle_roll) resultingAngles[i] *= 0; } else if(i == 2){ if(invert_pitch) resultingAngles[i] *= -1; if(toggle_pitch) resultingAngles[i] *= 0; } if(Math.abs(resultingAngles[i] - previousAngles[i]) < MIN_DIFF ){ resultingAngles[i] = 0.0; } else{ run = true; } } + //anglesInRadians is +/-PI while orient is 0-2PI so this fixes that + if(anglesInRadians[0] < 0) + anglesInRadians[0] = (float) (2*Math.PI + anglesInRadians[0]); // Gets the orientation angle (Y-axis rotation) and compares it to the previous one - resultingAngles[0] = roundDecimal(orient * Math.PI/ 180); + resultingAngles[0] = roundDecimal(anglesInRadians[0]); if (Math.abs(resultingAngles[0] - previousAngles[0])< MIN_DIFF){ resultingAngles[0] = previousAngles[0]; } else{ run = true; } if (run){ accelText.setText("Accel: " + resultingAngles[0] + ", " + resultingAngles[1] + ", " + resultingAngles[2]); sendSocketDoubles(ROT, resultingAngles, 3, NAVI); } } /** * Processes touch data: * down -- starts move procedure * pointer down (for 2+ fingers) -- starts zoom procedure * pointer up * up * move -- if move procedure, calculates distance moved * -- if zoom, calculates distance zoomed * @see android.view.View.OnTouchListener#onTouch(android.view.View, android.view.MotionEvent) */ @Override public boolean onTouch(View v, MotionEvent e){ if (!onNavigation) return false; if (!motionOn) return false; switch(e.getAction() & MotionEvent.ACTION_MASK){ case MotionEvent.ACTION_DOWN: x = e.getX(); y = e.getY(); move = true; break; case MotionEvent.ACTION_POINTER_DOWN: // If magnitude too small (fingers resting) won't run if ((magnitude = distance(e)) > 10f){ zoom = true; move = false; } break; case MotionEvent.ACTION_POINTER_UP: double value = distance(e); if (Math.abs(value - magnitude) <= 15f){ sendSocketCommand(FLIP, "Flip"); } zoom = false; break; case MotionEvent.ACTION_UP: move = false; break; case MotionEvent.ACTION_MOVE: if (move){ coords[0] = roundDecimal(e.getX() - x); coords[1] = roundDecimal(e.getY() - y); x = e.getX(); y = e.getY(); sendSocketDoubles(TRANS, coords, 2, NAVI); break; } if (zoom){ new_mag = distance(e); // If new_mag too small, prevents zoom. if(new_mag > 10f && (Math.abs(new_mag - magnitude) > 15f)){ // Calculates the distance moved by one finger (assumes a pinching movement is used) // If z < 0, then the object moves farther away z_coord[0] = roundDecimal((new_mag- magnitude)/2); sendSocketDoubles(ZTRANS, z_coord, 1, NAVI); break; } } } return true; } /* * Updates layout according to tag * Tags are listed at top of page * TYPE is tens digit, TAG is ones digit */ public void updateLayout(int tag){ switch(tag){ case FLY: sensorText.setText("Mode: Fly"); text_editor.putString(MODEVALUE, "Mode: Fly"); text_editor.commit(); break; case DRIVE: sensorText.setText("Mode: Drive"); text_editor.putString(MODEVALUE, "Mode: Drive"); text_editor.commit(); break; case ROTATE: sensorText.setText("Mode: Rotate World"); text_editor.putString(MODEVALUE, "Mode: Rotate World"); text_editor.commit(); break; case NEW_FLY: sensorText.setText("Mode: New Fly"); text_editor.putString(MODEVALUE, "Mode: New Fly"); text_editor.commit(); break; case CONNECT: Toast.makeText(Gamepad.this, "Connected!!", Toast.LENGTH_SHORT).show(); onIp = false; text_editor.putString(IPVALUE, "ip: " + cave.getAddress()); text_editor.commit(); if(onNavigation){ setContentView(R.layout.main_navigation); ipText.setText("ip: " + cave.getAddress()); onNavigationStart(); } else if (onNode){ setContentView(R.layout.find_node); nodeAdapter.clear(); node_editor.clear(); node_editor.commit(); onNodeMainStart(); } break; case FLIP: Toast.makeText(Gamepad.this, "Rotation Command received", Toast.LENGTH_SHORT).show(); break; } } /* * Calculates distance between two fingers (for zoom) */ private double distance(MotionEvent e) { double x = e.getX(0) - e.getX(1); double y = e.getY(0) - e.getY(1); return Math.sqrt(x*x + y*y); } /* * Converts int to byte[] */ public final byte[] intToByte(int value) { return new byte[] { (byte)value, (byte)(value >>> 8), (byte)(value >>> 16), (byte)(value >>> 24),}; } /* * Converts byte[] to int */ public static int byteToInt( byte[] bytes ) { int result = 0; for (int i=0; i<4; i++) { //result = (result << 8) + (bytes[i] & 0xff); result += (bytes[i] & 0xff) << (8 * i); } return result; } /* * Rounds decimal to 4 places. */ double roundDecimal(double d) { DecimalFormat dForm = new DecimalFormat("#.####"); return Double.valueOf(dForm.format(d)); } void recalibrate(){ System.arraycopy(prepare, 0, recalibration, 0, 3); } }
false
false
null
null
diff --git a/src/com/android/exchange/EasSyncService.java b/src/com/android/exchange/EasSyncService.java index 642ea29..43ebb2d 100644 --- a/src/com/android/exchange/EasSyncService.java +++ b/src/com/android/exchange/EasSyncService.java @@ -1,2070 +1,2073 @@ /* * Copyright (C) 2008-2009 Marc Blank * Licensed to 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.exchange; import com.android.email.SecurityPolicy; import com.android.email.Utility; import com.android.email.SecurityPolicy.PolicySet; import com.android.email.mail.Address; import com.android.email.mail.AuthenticationFailedException; import com.android.email.mail.MeetingInfo; import com.android.email.mail.MessagingException; import com.android.email.mail.PackedString; import com.android.email.provider.EmailContent.Account; import com.android.email.provider.EmailContent.AccountColumns; import com.android.email.provider.EmailContent.Attachment; import com.android.email.provider.EmailContent.AttachmentColumns; import com.android.email.provider.EmailContent.HostAuth; import com.android.email.provider.EmailContent.Mailbox; import com.android.email.provider.EmailContent.MailboxColumns; import com.android.email.provider.EmailContent.Message; import com.android.email.service.EmailServiceConstants; import com.android.email.service.EmailServiceProxy; import com.android.email.service.EmailServiceStatus; import com.android.exchange.adapter.AbstractSyncAdapter; import com.android.exchange.adapter.AccountSyncAdapter; import com.android.exchange.adapter.CalendarSyncAdapter; import com.android.exchange.adapter.ContactsSyncAdapter; import com.android.exchange.adapter.EmailSyncAdapter; import com.android.exchange.adapter.FolderSyncParser; import com.android.exchange.adapter.GalParser; import com.android.exchange.adapter.MeetingResponseParser; import com.android.exchange.adapter.PingParser; import com.android.exchange.adapter.ProvisionParser; import com.android.exchange.adapter.Serializer; import com.android.exchange.adapter.Tags; import com.android.exchange.adapter.Parser.EasParserException; import com.android.exchange.provider.GalResult; import com.android.exchange.utility.CalendarUtilities; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpOptions; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import org.xmlpull.v1.XmlSerializer; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Entity; import android.database.Cursor; import android.os.Bundle; import android.os.RemoteException; import android.os.SystemClock; import android.provider.Calendar.Attendees; import android.provider.Calendar.Events; import android.text.TextUtils; import android.util.Base64; import android.util.Log; import android.util.Xml; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URLEncoder; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.HashMap; public class EasSyncService extends AbstractSyncService { // STOPSHIP - DO NOT RELEASE AS 'TRUE' public static final boolean DEBUG_GAL_SERVICE = true; private static final String EMAIL_WINDOW_SIZE = "5"; public static final String PIM_WINDOW_SIZE = "5"; private static final String WHERE_ACCOUNT_KEY_AND_SERVER_ID = MailboxColumns.ACCOUNT_KEY + "=? and " + MailboxColumns.SERVER_ID + "=?"; private static final String WHERE_ACCOUNT_AND_SYNC_INTERVAL_PING = MailboxColumns.ACCOUNT_KEY + "=? and " + MailboxColumns.SYNC_INTERVAL + '=' + Mailbox.CHECK_INTERVAL_PING; private static final String AND_FREQUENCY_PING_PUSH_AND_NOT_ACCOUNT_MAILBOX = " AND " + MailboxColumns.SYNC_INTERVAL + " IN (" + Mailbox.CHECK_INTERVAL_PING + ',' + Mailbox.CHECK_INTERVAL_PUSH + ") AND " + MailboxColumns.TYPE + "!=\"" + Mailbox.TYPE_EAS_ACCOUNT_MAILBOX + '\"'; private static final String WHERE_PUSH_HOLD_NOT_ACCOUNT_MAILBOX = MailboxColumns.ACCOUNT_KEY + "=? and " + MailboxColumns.SYNC_INTERVAL + '=' + Mailbox.CHECK_INTERVAL_PUSH_HOLD; static private final int CHUNK_SIZE = 16*1024; static private final String PING_COMMAND = "Ping"; // Command timeout is the the time allowed for reading data from an open connection before an // IOException is thrown. After a small added allowance, our watchdog alarm goes off (allowing // us to detect a silently dropped connection). The allowance is defined below. static private final int COMMAND_TIMEOUT = 20*SECONDS; // Connection timeout is the time given to connect to the server before reporting an IOException static private final int CONNECTION_TIMEOUT = 20*SECONDS; // The extra time allowed beyond the COMMAND_TIMEOUT before which our watchdog alarm triggers static private final int WATCHDOG_TIMEOUT_ALLOWANCE = 10*SECONDS; static private final String AUTO_DISCOVER_SCHEMA_PREFIX = "http://schemas.microsoft.com/exchange/autodiscover/mobilesync/"; static private final String AUTO_DISCOVER_PAGE = "/autodiscover/autodiscover.xml"; static private final int AUTO_DISCOVER_REDIRECT_CODE = 451; static public final String EAS_12_POLICY_TYPE = "MS-EAS-Provisioning-WBXML"; static public final String EAS_2_POLICY_TYPE = "MS-WAP-Provisioning-XML"; /** * We start with an 8 minute timeout, and increase/decrease by 3 minutes at a time. There's * no point having a timeout shorter than 5 minutes, I think; at that point, we can just let * the ping exception out. The maximum I use is 17 minutes, which is really an empirical * choice; too long and we risk silent connection loss and loss of push for that period. Too * short and we lose efficiency/battery life. * * If we ever have to drop the ping timeout, we'll never increase it again. There's no point * going into hysteresis; the NAT timeout isn't going to change without a change in connection, * which will cause the sync service to be restarted at the starting heartbeat and going through * the process again. */ static private final int PING_MINUTES = 60; // in seconds static private final int PING_FUDGE_LOW = 10; static private final int PING_STARTING_HEARTBEAT = (8*PING_MINUTES)-PING_FUDGE_LOW; static private final int PING_MIN_HEARTBEAT = (5*PING_MINUTES)-PING_FUDGE_LOW; static private final int PING_MAX_HEARTBEAT = (17*PING_MINUTES)-PING_FUDGE_LOW; static private final int PING_HEARTBEAT_INCREMENT = 3*PING_MINUTES; static private final int PING_FORCE_HEARTBEAT = 2*PING_MINUTES; static private final int PROTOCOL_PING_STATUS_COMPLETED = 1; // Fallbacks (in minutes) for ping loop failures static private final int MAX_PING_FAILURES = 1; static private final int PING_FALLBACK_INBOX = 5; static private final int PING_FALLBACK_PIM = 25; // MSFT's custom HTTP result code indicating the need to provision static private final int HTTP_NEED_PROVISIONING = 449; // Reasonable default public String mProtocolVersion = Eas.DEFAULT_PROTOCOL_VERSION; public Double mProtocolVersionDouble; protected String mDeviceId = null; private String mDeviceType = "Android"; private String mAuthString = null; private String mCmdString = null; public String mHostAddress; public String mUserName; public String mPassword; private boolean mSsl = true; private boolean mTrustSsl = false; public ContentResolver mContentResolver; private String[] mBindArguments = new String[2]; private ArrayList<String> mPingChangeList; private HttpPost mPendingPost = null; // The ping time (in seconds) private int mPingHeartbeat = PING_STARTING_HEARTBEAT; // The longest successful ping heartbeat private int mPingHighWaterMark = 0; // Whether we've ever lowered the heartbeat private boolean mPingHeartbeatDropped = false; // Whether a POST was aborted due to alarm (watchdog alarm) private boolean mPostAborted = false; // Whether a POST was aborted due to reset private boolean mPostReset = false; // Whether or not the sync service is valid (usable) public boolean mIsValid = true; public EasSyncService(Context _context, Mailbox _mailbox) { super(_context, _mailbox); mContentResolver = _context.getContentResolver(); if (mAccount == null) { mIsValid = false; return; } HostAuth ha = HostAuth.restoreHostAuthWithId(_context, mAccount.mHostAuthKeyRecv); if (ha == null) { mIsValid = false; return; } mSsl = (ha.mFlags & HostAuth.FLAG_SSL) != 0; mTrustSsl = (ha.mFlags & HostAuth.FLAG_TRUST_ALL_CERTIFICATES) != 0; } private EasSyncService(String prefix) { super(prefix); } public EasSyncService() { this("EAS Validation"); } @Override public void alarm() { synchronized(getSynchronizer()) { if (mPendingPost != null) { URI uri = mPendingPost.getURI(); if (uri != null) { String query = uri.getQuery(); if (query == null) { query = "POST"; } userLog("Alert, aborting " + query); } else { userLog("Alert, no URI?"); } mPostAborted = true; mPendingPost.abort(); } else { userLog("Alert, no pending POST"); } } } @Override public void reset() { synchronized(getSynchronizer()) { if (mPendingPost != null) { URI uri = mPendingPost.getURI(); if (uri != null) { String query = uri.getQuery(); if (query.startsWith("Cmd=Ping")) { userLog("Reset, aborting Ping"); mPostReset = true; mPendingPost.abort(); } } } } } @Override public void stop() { mStop = true; synchronized(getSynchronizer()) { if (mPendingPost != null) { mPendingPost.abort(); } } } /** * Determine whether an HTTP code represents an authentication error * @param code the HTTP code returned by the server * @return whether or not the code represents an authentication error */ protected boolean isAuthError(int code) { return (code == HttpStatus.SC_UNAUTHORIZED) || (code == HttpStatus.SC_FORBIDDEN); } /** * Determine whether an HTTP code represents a provisioning error * @param code the HTTP code returned by the server * @return whether or not the code represents an provisioning error */ protected boolean isProvisionError(int code) { return (code == HTTP_NEED_PROVISIONING) || (code == HttpStatus.SC_FORBIDDEN); } private void setupProtocolVersion(EasSyncService service, Header versionHeader) throws MessagingException { // The string is a comma separated list of EAS versions in ascending order // e.g. 1.0,2.0,2.5,12.0,12.1 String supportedVersions = versionHeader.getValue(); userLog("Server supports versions: ", supportedVersions); String[] supportedVersionsArray = supportedVersions.split(","); String ourVersion = null; // Find the most recent version we support for (String version: supportedVersionsArray) { if (version.equals(Eas.SUPPORTED_PROTOCOL_EX2003) || version.equals(Eas.SUPPORTED_PROTOCOL_EX2007)) { ourVersion = version; } } // If we don't support any of the servers supported versions, throw an exception here // This will cause validation to fail if (ourVersion == null) { Log.w(TAG, "No supported EAS versions: " + supportedVersions); throw new MessagingException(MessagingException.PROTOCOL_VERSION_UNSUPPORTED); } else { service.mProtocolVersion = ourVersion; service.mProtocolVersionDouble = Double.parseDouble(ourVersion); if (service.mAccount != null) { service.mAccount.mProtocolVersion = ourVersion; } } } @Override public void validateAccount(String hostAddress, String userName, String password, int port, boolean ssl, boolean trustCertificates, Context context) throws MessagingException { try { userLog("Testing EAS: ", hostAddress, ", ", userName, ", ssl = ", ssl ? "1" : "0"); EasSyncService svc = new EasSyncService("%TestAccount%"); svc.mContext = context; svc.mHostAddress = hostAddress; svc.mUserName = userName; svc.mPassword = password; svc.mSsl = ssl; svc.mTrustSsl = trustCertificates; // We mustn't use the "real" device id or we'll screw up current accounts // Any string will do, but we'll go for "validate" svc.mDeviceId = "validate"; HttpResponse resp = svc.sendHttpClientOptions(); int code = resp.getStatusLine().getStatusCode(); userLog("Validation (OPTIONS) response: " + code); if (code == HttpStatus.SC_OK) { // No exception means successful validation Header commands = resp.getFirstHeader("MS-ASProtocolCommands"); Header versions = resp.getFirstHeader("ms-asprotocolversions"); if (commands == null || versions == null) { userLog("OPTIONS response without commands or versions; reporting I/O error"); throw new MessagingException(MessagingException.IOERROR); } // Make sure we've got the right protocol version set up setupProtocolVersion(svc, versions); // Run second test here for provisioning failures... Serializer s = new Serializer(); userLog("Try folder sync"); s.start(Tags.FOLDER_FOLDER_SYNC).start(Tags.FOLDER_SYNC_KEY).text("0") .end().end().done(); resp = svc.sendHttpClientPost("FolderSync", s.toByteArray()); code = resp.getStatusLine().getStatusCode(); // We'll get one of the following responses if policies are required by the server if (code == HttpStatus.SC_FORBIDDEN || code == HTTP_NEED_PROVISIONING) { // Get the policies and see if we are able to support them if (svc.canProvision() != null) { // If so, send the advisory Exception (the account may be created later) throw new MessagingException(MessagingException.SECURITY_POLICIES_REQUIRED); } else // If not, send the unsupported Exception (the account won't be created) throw new MessagingException( MessagingException.SECURITY_POLICIES_UNSUPPORTED); } else if (code == HttpStatus.SC_NOT_FOUND) { // We get a 404 from OWA addresses (which are NOT EAS addresses) throw new MessagingException(MessagingException.PROTOCOL_VERSION_UNSUPPORTED); } else if (code != HttpStatus.SC_OK) { // Fail generically with anything other than success userLog("Unexpected response for FolderSync: ", code); throw new MessagingException(MessagingException.UNSPECIFIED_EXCEPTION); } userLog("Validation successful"); return; } if (isAuthError(code)) { userLog("Authentication failed"); throw new AuthenticationFailedException("Validation failed"); } else { // TODO Need to catch other kinds of errors (e.g. policy) For now, report the code. userLog("Validation failed, reporting I/O error: ", code); throw new MessagingException(MessagingException.IOERROR); } } catch (IOException e) { Throwable cause = e.getCause(); if (cause != null && cause instanceof CertificateException) { userLog("CertificateException caught: ", e.getMessage()); throw new MessagingException(MessagingException.GENERAL_SECURITY); } userLog("IOException caught: ", e.getMessage()); throw new MessagingException(MessagingException.IOERROR); } } /** * Gets the redirect location from the HTTP headers and uses that to modify the HttpPost so that * it can be reused * * @param resp the HttpResponse that indicates a redirect (451) * @param post the HttpPost that was originally sent to the server * @return the HttpPost, updated with the redirect location */ private HttpPost getRedirect(HttpResponse resp, HttpPost post) { Header locHeader = resp.getFirstHeader("X-MS-Location"); if (locHeader != null) { String loc = locHeader.getValue(); // If we've gotten one and it shows signs of looking like an address, we try // sending our request there if (loc != null && loc.startsWith("http")) { post.setURI(URI.create(loc)); return post; } } return null; } /** * Send the POST command to the autodiscover server, handling a redirect, if necessary, and * return the HttpResponse * * @param client the HttpClient to be used for the request * @param post the HttpPost we're going to send * @return an HttpResponse from the original or redirect server * @throws IOException on any IOException within the HttpClient code * @throws MessagingException */ private HttpResponse postAutodiscover(HttpClient client, HttpPost post) throws IOException, MessagingException { userLog("Posting autodiscover to: " + post.getURI()); HttpResponse resp = executePostWithTimeout(client, post, COMMAND_TIMEOUT); int code = resp.getStatusLine().getStatusCode(); // On a redirect, try the new location if (code == AUTO_DISCOVER_REDIRECT_CODE) { post = getRedirect(resp, post); if (post != null) { userLog("Posting autodiscover to redirect: " + post.getURI()); return executePostWithTimeout(client, post, COMMAND_TIMEOUT); } } else if (code == HttpStatus.SC_UNAUTHORIZED) { // 401 (Unauthorized) is for true auth errors when used in Autodiscover // 403 (and others) we'll just punt on throw new MessagingException(MessagingException.AUTHENTICATION_FAILED); } else if (code != HttpStatus.SC_OK) { // We'll try the next address if this doesn't work userLog("Code: " + code + ", throwing IOException"); throw new IOException(); } return resp; } /** * Use the Exchange 2007 AutoDiscover feature to try to retrieve server information using * only an email address and the password * * @param userName the user's email address * @param password the user's password * @return a HostAuth ready to be saved in an Account or null (failure) */ public Bundle tryAutodiscover(String userName, String password) throws RemoteException { XmlSerializer s = Xml.newSerializer(); ByteArrayOutputStream os = new ByteArrayOutputStream(1024); HostAuth hostAuth = new HostAuth(); Bundle bundle = new Bundle(); bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, MessagingException.NO_ERROR); try { // Build the XML document that's sent to the autodiscover server(s) s.setOutput(os, "UTF-8"); s.startDocument("UTF-8", false); s.startTag(null, "Autodiscover"); s.attribute(null, "xmlns", AUTO_DISCOVER_SCHEMA_PREFIX + "requestschema/2006"); s.startTag(null, "Request"); s.startTag(null, "EMailAddress").text(userName).endTag(null, "EMailAddress"); s.startTag(null, "AcceptableResponseSchema"); s.text(AUTO_DISCOVER_SCHEMA_PREFIX + "responseschema/2006"); s.endTag(null, "AcceptableResponseSchema"); s.endTag(null, "Request"); s.endTag(null, "Autodiscover"); s.endDocument(); String req = os.toString(); // Initialize the user name and password mUserName = userName; mPassword = password; // Make sure the authentication string is created (mAuthString) makeUriString("foo", null); // Split out the domain name int amp = userName.indexOf('@'); // The UI ensures that userName is a valid email address if (amp < 0) { throw new RemoteException(); } String domain = userName.substring(amp + 1); // There are up to four attempts here; the two URLs that we're supposed to try per the // specification, and up to one redirect for each (handled in postAutodiscover) // Try the domain first and see if we can get a response HttpPost post = new HttpPost("https://" + domain + AUTO_DISCOVER_PAGE); setHeaders(post, false); post.setHeader("Content-Type", "text/xml"); post.setEntity(new StringEntity(req)); HttpClient client = getHttpClient(COMMAND_TIMEOUT); HttpResponse resp; try { resp = postAutodiscover(client, post); } catch (IOException e1) { userLog("IOException in autodiscover; trying alternate address"); // We catch the IOException here because we have an alternate address to try post.setURI(URI.create("https://autodiscover." + domain + AUTO_DISCOVER_PAGE)); // If we fail here, we're out of options, so we let the outer try catch the // IOException and return null resp = postAutodiscover(client, post); } // Get the "final" code; if it's not 200, just return null int code = resp.getStatusLine().getStatusCode(); userLog("Code: " + code); if (code != HttpStatus.SC_OK) return null; // At this point, we have a 200 response (SC_OK) HttpEntity e = resp.getEntity(); InputStream is = e.getContent(); try { // The response to Autodiscover is regular XML (not WBXML) // If we ever get an error in this process, we'll just punt and return null XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser parser = factory.newPullParser(); parser.setInput(is, "UTF-8"); int type = parser.getEventType(); if (type == XmlPullParser.START_DOCUMENT) { type = parser.next(); if (type == XmlPullParser.START_TAG) { String name = parser.getName(); if (name.equals("Autodiscover")) { hostAuth = new HostAuth(); parseAutodiscover(parser, hostAuth); // On success, we'll have a server address and login if (hostAuth.mAddress != null && hostAuth.mLogin != null) { // Fill in the rest of the HostAuth hostAuth.mPassword = password; hostAuth.mPort = 443; hostAuth.mProtocol = "eas"; hostAuth.mFlags = HostAuth.FLAG_SSL | HostAuth.FLAG_AUTHENTICATE; bundle.putParcelable( EmailServiceProxy.AUTO_DISCOVER_BUNDLE_HOST_AUTH, hostAuth); } else { bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, MessagingException.UNSPECIFIED_EXCEPTION); } } } } } catch (XmlPullParserException e1) { // This would indicate an I/O error of some sort // We will simply return null and user can configure manually } // There's no reason at all for exceptions to be thrown, and it's ok if so. // We just won't do auto-discover; user can configure manually } catch (IllegalArgumentException e) { bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, MessagingException.UNSPECIFIED_EXCEPTION); } catch (IllegalStateException e) { bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, MessagingException.UNSPECIFIED_EXCEPTION); } catch (IOException e) { userLog("IOException in Autodiscover", e); bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, MessagingException.IOERROR); } catch (MessagingException e) { bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, MessagingException.AUTHENTICATION_FAILED); } return bundle; } void parseServer(XmlPullParser parser, HostAuth hostAuth) throws XmlPullParserException, IOException { boolean mobileSync = false; while (true) { int type = parser.next(); if (type == XmlPullParser.END_TAG && parser.getName().equals("Server")) { break; } else if (type == XmlPullParser.START_TAG) { String name = parser.getName(); if (name.equals("Type")) { if (parser.nextText().equals("MobileSync")) { mobileSync = true; } } else if (mobileSync && name.equals("Url")) { String url = parser.nextText().toLowerCase(); // This will look like https://<server address>/Microsoft-Server-ActiveSync // We need to extract the <server address> if (url.startsWith("https://") && url.endsWith("/microsoft-server-activesync")) { int lastSlash = url.lastIndexOf('/'); hostAuth.mAddress = url.substring(8, lastSlash); userLog("Autodiscover, server: " + hostAuth.mAddress); } } } } } void parseSettings(XmlPullParser parser, HostAuth hostAuth) throws XmlPullParserException, IOException { while (true) { int type = parser.next(); if (type == XmlPullParser.END_TAG && parser.getName().equals("Settings")) { break; } else if (type == XmlPullParser.START_TAG) { String name = parser.getName(); if (name.equals("Server")) { parseServer(parser, hostAuth); } } } } void parseAction(XmlPullParser parser, HostAuth hostAuth) throws XmlPullParserException, IOException { while (true) { int type = parser.next(); if (type == XmlPullParser.END_TAG && parser.getName().equals("Action")) { break; } else if (type == XmlPullParser.START_TAG) { String name = parser.getName(); if (name.equals("Error")) { // Should parse the error } else if (name.equals("Redirect")) { Log.d(TAG, "Redirect: " + parser.nextText()); } else if (name.equals("Settings")) { parseSettings(parser, hostAuth); } } } } void parseUser(XmlPullParser parser, HostAuth hostAuth) throws XmlPullParserException, IOException { while (true) { int type = parser.next(); if (type == XmlPullParser.END_TAG && parser.getName().equals("User")) { break; } else if (type == XmlPullParser.START_TAG) { String name = parser.getName(); if (name.equals("EMailAddress")) { String addr = parser.nextText(); hostAuth.mLogin = addr; userLog("Autodiscover, login: " + addr); } else if (name.equals("DisplayName")) { String dn = parser.nextText(); userLog("Autodiscover, user: " + dn); } } } } void parseResponse(XmlPullParser parser, HostAuth hostAuth) throws XmlPullParserException, IOException { while (true) { int type = parser.next(); if (type == XmlPullParser.END_TAG && parser.getName().equals("Response")) { break; } else if (type == XmlPullParser.START_TAG) { String name = parser.getName(); if (name.equals("User")) { parseUser(parser, hostAuth); } else if (name.equals("Action")) { parseAction(parser, hostAuth); } } } } void parseAutodiscover(XmlPullParser parser, HostAuth hostAuth) throws XmlPullParserException, IOException { while (true) { int type = parser.nextTag(); if (type == XmlPullParser.END_TAG && parser.getName().equals("Autodiscover")) { break; } else if (type == XmlPullParser.START_TAG && parser.getName().equals("Response")) { parseResponse(parser, hostAuth); } } } /** * Contact the GAL and obtain a list of matching accounts * @param context caller's context * @param accountId the account Id to search * @param filter the characters entered so far * @return a result record * * TODO: shorter timeout for interactive lookup * TODO: make watchdog actually work (it doesn't understand our service w/Mailbox == 0) * TODO: figure out why sendHttpClientPost() hangs - possibly pool exhaustion */ static public GalResult searchGal(Context context, long accountId, String filter) { Account acct = SyncManager.getAccountById(accountId); if (acct != null) { HostAuth ha = HostAuth.restoreHostAuthWithId(context, acct.mHostAuthKeyRecv); EasSyncService svc = new EasSyncService("%GalLookupk%"); try { svc.mContext = context; svc.mHostAddress = ha.mAddress; svc.mUserName = ha.mLogin; svc.mPassword = ha.mPassword; svc.mSsl = (ha.mFlags & HostAuth.FLAG_SSL) != 0; svc.mTrustSsl = (ha.mFlags & HostAuth.FLAG_TRUST_ALL_CERTIFICATES) != 0; svc.mDeviceId = SyncManager.getDeviceId(); svc.mAccount = acct; Serializer s = new Serializer(); s.start(Tags.SEARCH_SEARCH).start(Tags.SEARCH_STORE); s.data(Tags.SEARCH_NAME, "GAL").data(Tags.SEARCH_QUERY, filter); s.start(Tags.SEARCH_OPTIONS); s.data(Tags.SEARCH_RANGE, "0-19"); // Return 0..20 results s.end().end().end().done(); if (DEBUG_GAL_SERVICE) svc.userLog("GAL lookup starting for " + ha.mAddress); HttpResponse resp = svc.sendHttpClientPost("Search", s.toByteArray()); int code = resp.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { InputStream is = resp.getEntity().getContent(); GalParser gp = new GalParser(is, svc); if (gp.parse()) { if (DEBUG_GAL_SERVICE) svc.userLog("GAL lookup OK for " + ha.mAddress); return gp.getGalResult(); } else { if (DEBUG_GAL_SERVICE) svc.userLog("GAL lookup returned no matches"); } } else { svc.userLog("GAL lookup returned " + code); } } catch (IOException e) { // GAL is non-critical; we'll just go on svc.userLog("GAL lookup exception " + e); } } return null; } private void doStatusCallback(long messageId, long attachmentId, int status) { try { SyncManager.callback().loadAttachmentStatus(messageId, attachmentId, status, 0); } catch (RemoteException e) { // No danger if the client is no longer around } } private void doProgressCallback(long messageId, long attachmentId, int progress) { try { SyncManager.callback().loadAttachmentStatus(messageId, attachmentId, EmailServiceStatus.IN_PROGRESS, progress); } catch (RemoteException e) { // No danger if the client is no longer around } } public File createUniqueFileInternal(String dir, String filename) { File directory; if (dir == null) { directory = mContext.getFilesDir(); } else { directory = new File(dir); } if (!directory.exists()) { directory.mkdirs(); } File file = new File(directory, filename); if (!file.exists()) { return file; } // Get the extension of the file, if any. int index = filename.lastIndexOf('.'); String name = filename; String extension = ""; if (index != -1) { name = filename.substring(0, index); extension = filename.substring(index); } for (int i = 2; i < Integer.MAX_VALUE; i++) { file = new File(directory, name + '-' + i + extension); if (!file.exists()) { return file; } } return null; } /** * Loads an attachment, based on the PartRequest passed in. The PartRequest is basically our * wrapper for Attachment * @param req the part (attachment) to be retrieved * @throws IOException */ protected void getAttachment(PartRequest req) throws IOException { Attachment att = req.mAttachment; Message msg = Message.restoreMessageWithId(mContext, att.mMessageKey); doProgressCallback(msg.mId, att.mId, 0); String cmd = "GetAttachment&AttachmentName=" + att.mLocation; HttpResponse res = sendHttpClientPost(cmd, null, COMMAND_TIMEOUT); int status = res.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { HttpEntity e = res.getEntity(); int len = (int)e.getContentLength(); InputStream is = res.getEntity().getContent(); File f = (req.mDestination != null) ? new File(req.mDestination) : createUniqueFileInternal(req.mDestination, att.mFileName); if (f != null) { // Ensure that the target directory exists File destDir = f.getParentFile(); if (!destDir.exists()) { destDir.mkdirs(); } FileOutputStream os = new FileOutputStream(f); // len > 0 means that Content-Length was set in the headers // len < 0 means "chunked" transfer-encoding if (len != 0) { try { mPendingRequest = req; byte[] bytes = new byte[CHUNK_SIZE]; int length = len; // Loop terminates 1) when EOF is reached or 2) if an IOException occurs // One of these is guaranteed to occur int totalRead = 0; userLog("Attachment content-length: ", len); while (true) { int read = is.read(bytes, 0, CHUNK_SIZE); // read < 0 means that EOF was reached if (read < 0) { userLog("Attachment load reached EOF, totalRead: ", totalRead); break; } // Keep track of how much we've read for progress callback totalRead += read; // Write these bytes out os.write(bytes, 0, read); // We can't report percentages if this is chunked; by definition, the // length of incoming data is unknown if (length > 0) { // Belt and suspenders check to prevent runaway reading if (totalRead > length) { errorLog("totalRead is greater than attachment length?"); break; } int pct = (totalRead * 100) / length; doProgressCallback(msg.mId, att.mId, pct); } } } finally { mPendingRequest = null; } } os.flush(); os.close(); // EmailProvider will throw an exception if we try to update an unsaved attachment if (att.isSaved()) { String contentUriString = (req.mContentUriString != null) ? req.mContentUriString : "file://" + f.getAbsolutePath(); ContentValues cv = new ContentValues(); cv.put(AttachmentColumns.CONTENT_URI, contentUriString); att.update(mContext, cv); doStatusCallback(msg.mId, att.mId, EmailServiceStatus.SUCCESS); } } } else { doStatusCallback(msg.mId, att.mId, EmailServiceStatus.MESSAGE_NOT_FOUND); } } /** * Send an email responding to a Message that has been marked as a meeting request. The message * will consist a little bit of event information and an iCalendar attachment * @param msg the meeting request email */ private void sendMeetingResponseMail(Message msg, int response) { // Get the meeting information; we'd better have some... PackedString meetingInfo = new PackedString(msg.mMeetingInfo); if (meetingInfo == null) return; // This will come as "First Last" <box@server.blah>, so we use Address to // parse it into parts; we only need the email address part for the ics file Address[] addrs = Address.parse(meetingInfo.get(MeetingInfo.MEETING_ORGANIZER_EMAIL)); // It shouldn't be possible, but handle it anyway if (addrs.length != 1) return; String organizerEmail = addrs[0].getAddress(); String dtStamp = meetingInfo.get(MeetingInfo.MEETING_DTSTAMP); String dtStart = meetingInfo.get(MeetingInfo.MEETING_DTSTART); String dtEnd = meetingInfo.get(MeetingInfo.MEETING_DTEND); // What we're doing here is to create an Entity that looks like an Event as it would be // stored by CalendarProvider ContentValues entityValues = new ContentValues(); Entity entity = new Entity(entityValues); // Fill in times, location, title, and organizer entityValues.put("DTSTAMP", CalendarUtilities.convertEmailDateTimeToCalendarDateTime(dtStamp)); entityValues.put(Events.DTSTART, Utility.parseEmailDateTimeToMillis(dtStart)); entityValues.put(Events.DTEND, Utility.parseEmailDateTimeToMillis(dtEnd)); entityValues.put(Events.EVENT_LOCATION, meetingInfo.get(MeetingInfo.MEETING_LOCATION)); entityValues.put(Events.TITLE, meetingInfo.get(MeetingInfo.MEETING_TITLE)); entityValues.put(Events.ORGANIZER, organizerEmail); // Add ourselves as an attendee, using our account email address ContentValues attendeeValues = new ContentValues(); attendeeValues.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ATTENDEE); attendeeValues.put(Attendees.ATTENDEE_EMAIL, mAccount.mEmailAddress); entity.addSubValue(Attendees.CONTENT_URI, attendeeValues); // Add the organizer ContentValues organizerValues = new ContentValues(); organizerValues.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ORGANIZER); organizerValues.put(Attendees.ATTENDEE_EMAIL, organizerEmail); entity.addSubValue(Attendees.CONTENT_URI, organizerValues); // Create a message from the Entity we've built. The message will have fields like // to, subject, date, and text filled in. There will also be an "inline" attachment // which is in iCalendar format int flag; switch(response) { case EmailServiceConstants.MEETING_REQUEST_ACCEPTED: flag = Message.FLAG_OUTGOING_MEETING_ACCEPT; break; case EmailServiceConstants.MEETING_REQUEST_DECLINED: flag = Message.FLAG_OUTGOING_MEETING_DECLINE; break; case EmailServiceConstants.MEETING_REQUEST_TENTATIVE: default: flag = Message.FLAG_OUTGOING_MEETING_TENTATIVE; break; } Message outgoingMsg = CalendarUtilities.createMessageForEntity(mContext, entity, flag, meetingInfo.get(MeetingInfo.MEETING_UID), mAccount); // Assuming we got a message back (we might not if the event has been deleted), send it if (outgoingMsg != null) { EasOutboxService.sendMessage(mContext, mAccount.mId, outgoingMsg); } } /** * Responds to a meeting request. The MeetingResponseRequest is basically our * wrapper for the meetingResponse service call * @param req the request (message id and response code) * @throws IOException */ protected void sendMeetingResponse(MeetingResponseRequest req) throws IOException { // Retrieve the message and mailbox; punt if either are null Message msg = Message.restoreMessageWithId(mContext, req.mMessageId); if (msg == null) return; Mailbox mailbox = Mailbox.restoreMailboxWithId(mContext, msg.mMailboxKey); if (mailbox == null) return; Serializer s = new Serializer(); s.start(Tags.MREQ_MEETING_RESPONSE).start(Tags.MREQ_REQUEST); s.data(Tags.MREQ_USER_RESPONSE, Integer.toString(req.mResponse)); s.data(Tags.MREQ_COLLECTION_ID, mailbox.mServerId); s.data(Tags.MREQ_REQ_ID, msg.mServerId); s.end().end().done(); HttpResponse res = sendHttpClientPost("MeetingResponse", s.toByteArray()); int status = res.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { HttpEntity e = res.getEntity(); int len = (int)e.getContentLength(); InputStream is = res.getEntity().getContent(); if (len != 0) { new MeetingResponseParser(is, this).parse(); sendMeetingResponseMail(msg, req.mResponse); } } else if (isAuthError(status)) { throw new EasAuthenticationException(); } else { userLog("Meeting response request failed, code: " + status); throw new IOException(); } } @SuppressWarnings("deprecation") private String makeUriString(String cmd, String extra) throws IOException { // Cache the authentication string and the command string String safeUserName = URLEncoder.encode(mUserName); if (mAuthString == null) { String cs = mUserName + ':' + mPassword; mAuthString = "Basic " + Base64.encodeToString(cs.getBytes(), Base64.NO_WRAP); mCmdString = "&User=" + safeUserName + "&DeviceId=" + mDeviceId + "&DeviceType=" + mDeviceType; } String us = (mSsl ? (mTrustSsl ? "httpts" : "https") : "http") + "://" + mHostAddress + "/Microsoft-Server-ActiveSync"; if (cmd != null) { us += "?Cmd=" + cmd + mCmdString; } if (extra != null) { us += extra; } return us; } /** * Set standard HTTP headers, using a policy key if required * @param method the method we are going to send * @param usePolicyKey whether or not a policy key should be sent in the headers */ private void setHeaders(HttpRequestBase method, boolean usePolicyKey) { method.setHeader("Authorization", mAuthString); method.setHeader("MS-ASProtocolVersion", mProtocolVersion); method.setHeader("Connection", "keep-alive"); method.setHeader("User-Agent", mDeviceType + '/' + Eas.VERSION); if (usePolicyKey && (mAccount != null)) { String key = mAccount.mSecuritySyncKey; if (key == null || key.length() == 0) { return; } if (Eas.PARSER_LOG) { userLog("Policy key: " , key); } method.setHeader("X-MS-PolicyKey", key); } } private ClientConnectionManager getClientConnectionManager() { return SyncManager.getClientConnectionManager(); } private HttpClient getHttpClient(int timeout) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, timeout); HttpConnectionParams.setSocketBufferSize(params, 8192); HttpClient client = new DefaultHttpClient(getClientConnectionManager(), params); return client; } protected HttpResponse sendHttpClientPost(String cmd, byte[] bytes) throws IOException { return sendHttpClientPost(cmd, new ByteArrayEntity(bytes), COMMAND_TIMEOUT); } protected HttpResponse sendHttpClientPost(String cmd, HttpEntity entity) throws IOException { return sendHttpClientPost(cmd, entity, COMMAND_TIMEOUT); } protected HttpResponse sendPing(byte[] bytes, int heartbeat) throws IOException { Thread.currentThread().setName(mAccount.mDisplayName + ": Ping"); if (Eas.USER_LOG) { userLog("Send ping, timeout: " + heartbeat + "s, high: " + mPingHighWaterMark + 's'); } return sendHttpClientPost(PING_COMMAND, new ByteArrayEntity(bytes), (heartbeat+5)*SECONDS); } /** * Convenience method for executePostWithTimeout for use other than with the Ping command */ protected HttpResponse executePostWithTimeout(HttpClient client, HttpPost method, int timeout) throws IOException { return executePostWithTimeout(client, method, timeout, false); } /** * Handle executing an HTTP POST command with proper timeout, watchdog, and ping behavior * @param client the HttpClient * @param method the HttpPost * @param timeout the timeout before failure, in ms * @param isPingCommand whether the POST is for the Ping command (requires wakelock logic) * @return the HttpResponse * @throws IOException */ protected HttpResponse executePostWithTimeout(HttpClient client, HttpPost method, int timeout, boolean isPingCommand) throws IOException { synchronized(getSynchronizer()) { mPendingPost = method; long alarmTime = timeout + WATCHDOG_TIMEOUT_ALLOWANCE; if (isPingCommand) { SyncManager.runAsleep(mMailboxId, alarmTime); } else { SyncManager.setWatchdogAlarm(mMailboxId, alarmTime); } } try { return client.execute(method); } finally { synchronized(getSynchronizer()) { if (isPingCommand) { SyncManager.runAwake(mMailboxId); } else { SyncManager.clearWatchdogAlarm(mMailboxId); } mPendingPost = null; } } } protected HttpResponse sendHttpClientPost(String cmd, HttpEntity entity, int timeout) throws IOException { HttpClient client = getHttpClient(timeout); boolean isPingCommand = cmd.equals(PING_COMMAND); // Split the mail sending commands String extra = null; boolean msg = false; if (cmd.startsWith("SmartForward&") || cmd.startsWith("SmartReply&")) { int cmdLength = cmd.indexOf('&'); extra = cmd.substring(cmdLength); cmd = cmd.substring(0, cmdLength); msg = true; } else if (cmd.startsWith("SendMail&")) { msg = true; } String us = makeUriString(cmd, extra); HttpPost method = new HttpPost(URI.create(us)); // Send the proper Content-Type header // If entity is null (e.g. for attachments), don't set this header if (msg) { method.setHeader("Content-Type", "message/rfc822"); } else if (entity != null) { method.setHeader("Content-Type", "application/vnd.ms-sync.wbxml"); } setHeaders(method, !cmd.equals(PING_COMMAND)); method.setEntity(entity); return executePostWithTimeout(client, method, timeout, isPingCommand); } protected HttpResponse sendHttpClientOptions() throws IOException { HttpClient client = getHttpClient(COMMAND_TIMEOUT); String us = makeUriString("OPTIONS", null); HttpOptions method = new HttpOptions(URI.create(us)); setHeaders(method, false); return client.execute(method); } String getTargetCollectionClassFromCursor(Cursor c) { int type = c.getInt(Mailbox.CONTENT_TYPE_COLUMN); if (type == Mailbox.TYPE_CONTACTS) { return "Contacts"; } else if (type == Mailbox.TYPE_CALENDAR) { return "Calendar"; } else { return "Email"; } } /** * Negotiate provisioning with the server. First, get policies form the server and see if * the policies are supported by the device. Then, write the policies to the account and * tell SecurityPolicy that we have policies in effect. Finally, see if those policies are * active; if so, acknowledge the policies to the server and get a final policy key that we * use in future EAS commands and write this key to the account. * @return whether or not provisioning has been successful * @throws IOException */ private boolean tryProvision() throws IOException { // First, see if provisioning is even possible, i.e. do we support the policies required // by the server ProvisionParser pp = canProvision(); if (pp != null) { SecurityPolicy sp = SecurityPolicy.getInstance(mContext); // Get the policies from ProvisionParser PolicySet ps = pp.getPolicySet(); // Update the account with a null policyKey (the key we've gotten is // temporary and cannot be used for syncing) if (ps.writeAccount(mAccount, null, true, mContext)) { sp.updatePolicies(mAccount.mId); } if (pp.getRemoteWipe()) { // We've gotten a remote wipe command // First, we've got to acknowledge it, but wrap the wipe in try/catch so that // we wipe the device regardless of any errors in acknowledgment try { acknowledgeRemoteWipe(pp.getPolicyKey()); } catch (Exception e) { // Because remote wipe is such a high priority task, we don't want to // circumvent it if there's an exception in acknowledgment } // Then, tell SecurityPolicy to wipe the device sp.remoteWipe(); return false; } else if (sp.isActive(ps)) { // See if the required policies are in force; if they are, acknowledge the policies // to the server and get the final policy key String policyKey = acknowledgeProvision(pp.getPolicyKey()); if (policyKey != null) { // Write the final policy key to the Account and say we've been successful ps.writeAccount(mAccount, policyKey, true, mContext); return true; } } else { // Notify that we are blocked because of policies sp.policiesRequired(mAccount.mId); } } return false; } private String getPolicyType() { return (mProtocolVersionDouble >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) ? EAS_12_POLICY_TYPE : EAS_2_POLICY_TYPE; } /** * Obtain a set of policies from the server and determine whether those policies are supported * by the device. * @return the ProvisionParser (holds policies and key) if we receive policies and they are * supported by the device; null otherwise * @throws IOException */ private ProvisionParser canProvision() throws IOException { Serializer s = new Serializer(); s.start(Tags.PROVISION_PROVISION).start(Tags.PROVISION_POLICIES); s.start(Tags.PROVISION_POLICY).data(Tags.PROVISION_POLICY_TYPE, getPolicyType()) .end().end().end().done(); HttpResponse resp = sendHttpClientPost("Provision", s.toByteArray()); int code = resp.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { InputStream is = resp.getEntity().getContent(); ProvisionParser pp = new ProvisionParser(is, this); if (pp.parse()) { // If true, we received policies from the server; see if they are supported by // the framework; if so, return the ProvisionParser containing the policy set and // temporary key PolicySet ps = pp.getPolicySet(); if (SecurityPolicy.getInstance(mContext).isSupported(ps)) { return pp; } } } // On failures, simply return null return null; } /** * Acknowledge that we support the policies provided by the server, and that these policies * are in force. * @param tempKey the initial (temporary) policy key sent by the server * @return the final policy key, which can be used for syncing * @throws IOException */ private void acknowledgeRemoteWipe(String tempKey) throws IOException { acknowledgeProvisionImpl(tempKey, true); } private String acknowledgeProvision(String tempKey) throws IOException { return acknowledgeProvisionImpl(tempKey, false); } private String acknowledgeProvisionImpl(String tempKey, boolean remoteWipe) throws IOException { Serializer s = new Serializer(); s.start(Tags.PROVISION_PROVISION).start(Tags.PROVISION_POLICIES); s.start(Tags.PROVISION_POLICY); // Use the proper policy type, depending on EAS version s.data(Tags.PROVISION_POLICY_TYPE, getPolicyType()); s.data(Tags.PROVISION_POLICY_KEY, tempKey); s.data(Tags.PROVISION_STATUS, "1"); s.end().end(); // PROVISION_POLICY, PROVISION_POLICIES if (remoteWipe) { s.start(Tags.PROVISION_REMOTE_WIPE); s.data(Tags.PROVISION_STATUS, "1"); s.end(); } s.end().done(); // PROVISION_PROVISION HttpResponse resp = sendHttpClientPost("Provision", s.toByteArray()); int code = resp.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { InputStream is = resp.getEntity().getContent(); ProvisionParser pp = new ProvisionParser(is, this); if (pp.parse()) { // Return the final polic key from the ProvisionParser return pp.getPolicyKey(); } } // On failures, return null return null; } /** * Performs FolderSync * * @throws IOException * @throws EasParserException */ public void runAccountMailbox() throws IOException, EasParserException { // Initialize exit status to success mExitStatus = EmailServiceStatus.SUCCESS; try { try { SyncManager.callback() .syncMailboxListStatus(mAccount.mId, EmailServiceStatus.IN_PROGRESS, 0); } catch (RemoteException e1) { // Don't care if this fails } if (mAccount.mSyncKey == null) { mAccount.mSyncKey = "0"; userLog("Account syncKey INIT to 0"); ContentValues cv = new ContentValues(); cv.put(AccountColumns.SYNC_KEY, mAccount.mSyncKey); mAccount.update(mContext, cv); } boolean firstSync = mAccount.mSyncKey.equals("0"); if (firstSync) { userLog("Initial FolderSync"); } // When we first start up, change all mailboxes to push. ContentValues cv = new ContentValues(); cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH); if (mContentResolver.update(Mailbox.CONTENT_URI, cv, WHERE_ACCOUNT_AND_SYNC_INTERVAL_PING, new String[] {Long.toString(mAccount.mId)}) > 0) { SyncManager.kick("change ping boxes to push"); } // Determine our protocol version, if we haven't already and save it in the Account // Also re-check protocol version at least once a day (in case of upgrade) if (mAccount.mProtocolVersion == null || ((System.currentTimeMillis() - mMailbox.mSyncTime) > DAYS)) { userLog("Determine EAS protocol version"); HttpResponse resp = sendHttpClientOptions(); int code = resp.getStatusLine().getStatusCode(); userLog("OPTIONS response: ", code); if (code == HttpStatus.SC_OK) { Header header = resp.getFirstHeader("MS-ASProtocolCommands"); userLog(header.getValue()); header = resp.getFirstHeader("ms-asprotocolversions"); try { setupProtocolVersion(this, header); } catch (MessagingException e) { // Since we've already validated, this can't really happen // But if it does, we'll rethrow this... throw new IOException(); } // Save the protocol version cv.clear(); // Save the protocol version in the account cv.put(Account.PROTOCOL_VERSION, mProtocolVersion); mAccount.update(mContext, cv); cv.clear(); // Save the sync time of the account mailbox to current time cv.put(Mailbox.SYNC_TIME, System.currentTimeMillis()); mMailbox.update(mContext, cv); } else { errorLog("OPTIONS command failed; throwing IOException"); throw new IOException(); } } // Change all pushable boxes to push when we start the account mailbox if (mAccount.mSyncInterval == Account.CHECK_INTERVAL_PUSH) { cv.clear(); cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH); if (mContentResolver.update(Mailbox.CONTENT_URI, cv, SyncManager.WHERE_IN_ACCOUNT_AND_PUSHABLE, new String[] {Long.toString(mAccount.mId)}) > 0) { userLog("Push account; set pushable boxes to push..."); } } while (!mStop) { userLog("Sending Account syncKey: ", mAccount.mSyncKey); Serializer s = new Serializer(); s.start(Tags.FOLDER_FOLDER_SYNC).start(Tags.FOLDER_SYNC_KEY) .text(mAccount.mSyncKey).end().end().done(); HttpResponse resp = sendHttpClientPost("FolderSync", s.toByteArray()); if (mStop) break; int code = resp.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { HttpEntity entity = resp.getEntity(); int len = (int)entity.getContentLength(); if (len != 0) { InputStream is = entity.getContent(); // Returns true if we need to sync again if (new FolderSyncParser(is, new AccountSyncAdapter(mMailbox, this)) .parse()) { continue; } } } else if (isProvisionError(code)) { // If the sync error is a provisioning failure (perhaps the policies changed), // let's try the provisioning procedure // Provisioning must only be attempted for the account mailbox - trying to // provision any other mailbox may result in race conditions and the creation // of multiple policy keys. if (!tryProvision()) { // Set the appropriate failure status mExitStatus = EXIT_SECURITY_FAILURE; return; } else { // If we succeeded, try again... continue; } } else if (isAuthError(code)) { mExitStatus = EXIT_LOGIN_FAILURE; return; } else { userLog("FolderSync response error: ", code); } // Change all push/hold boxes to push cv.clear(); cv.put(Mailbox.SYNC_INTERVAL, Account.CHECK_INTERVAL_PUSH); if (mContentResolver.update(Mailbox.CONTENT_URI, cv, WHERE_PUSH_HOLD_NOT_ACCOUNT_MAILBOX, new String[] {Long.toString(mAccount.mId)}) > 0) { userLog("Set push/hold boxes to push..."); } try { SyncManager.callback() .syncMailboxListStatus(mAccount.mId, mExitStatus, 0); } catch (RemoteException e1) { // Don't care if this fails } // Before each run of the pingLoop, if this Account has a PolicySet, make sure it's // active; otherwise, clear out the key/flag. This should cause a provisioning // error on the next POST, and start the security sequence over again String key = mAccount.mSecuritySyncKey; if (!TextUtils.isEmpty(key)) { PolicySet ps = new PolicySet(mAccount); SecurityPolicy sp = SecurityPolicy.getInstance(mContext); if (!sp.isActive(ps)) { cv.clear(); cv.put(AccountColumns.SECURITY_FLAGS, 0); cv.putNull(AccountColumns.SECURITY_SYNC_KEY); long accountId = mAccount.mId; mContentResolver.update(ContentUris.withAppendedId( Account.CONTENT_URI, accountId), cv, null, null); sp.policiesRequired(accountId); } } // Wait for push notifications. String threadName = Thread.currentThread().getName(); try { runPingLoop(); } catch (StaleFolderListException e) { // We break out if we get told about a stale folder list userLog("Ping interrupted; folder list requires sync..."); } finally { Thread.currentThread().setName(threadName); } } } catch (IOException e) { // We catch this here to send the folder sync status callback // A folder sync failed callback will get sent from run() try { if (!mStop) { SyncManager.callback() .syncMailboxListStatus(mAccount.mId, EmailServiceStatus.CONNECTION_ERROR, 0); } } catch (RemoteException e1) { // Don't care if this fails } throw e; } } void pushFallback(long mailboxId) { Mailbox mailbox = Mailbox.restoreMailboxWithId(mContext, mailboxId); if (mailbox == null) { return; } ContentValues cv = new ContentValues(); int mins = PING_FALLBACK_PIM; if (mailbox.mType == Mailbox.TYPE_INBOX) { mins = PING_FALLBACK_INBOX; } cv.put(Mailbox.SYNC_INTERVAL, mins); mContentResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId), cv, null, null); errorLog("*** PING ERROR LOOP: Set " + mailbox.mDisplayName + " to " + mins + " min sync"); SyncManager.kick("push fallback"); } void runPingLoop() throws IOException, StaleFolderListException { int pingHeartbeat = mPingHeartbeat; userLog("runPingLoop"); // Do push for all sync services here long endTime = System.currentTimeMillis() + (30*MINUTES); HashMap<String, Integer> pingErrorMap = new HashMap<String, Integer>(); ArrayList<String> readyMailboxes = new ArrayList<String>(); ArrayList<String> notReadyMailboxes = new ArrayList<String>(); int pingWaitCount = 0; while ((System.currentTimeMillis() < endTime) && !mStop) { // Count of pushable mailboxes int pushCount = 0; // Count of mailboxes that can be pushed right now int canPushCount = 0; // Count of uninitialized boxes int uninitCount = 0; Serializer s = new Serializer(); Cursor c = mContentResolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, MailboxColumns.ACCOUNT_KEY + '=' + mAccount.mId + AND_FREQUENCY_PING_PUSH_AND_NOT_ACCOUNT_MAILBOX, null, null); notReadyMailboxes.clear(); readyMailboxes.clear(); try { // Loop through our pushed boxes seeing what is available to push while (c.moveToNext()) { pushCount++; // Two requirements for push: // 1) SyncManager tells us the mailbox is syncable (not running, not stopped) // 2) The syncKey isn't "0" (i.e. it's synced at least once) long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN); int pingStatus = SyncManager.pingStatus(mailboxId); String mailboxName = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN); if (pingStatus == SyncManager.PING_STATUS_OK) { String syncKey = c.getString(Mailbox.CONTENT_SYNC_KEY_COLUMN); if ((syncKey == null) || syncKey.equals("0")) { // We can't push until the initial sync is done pushCount--; uninitCount++; continue; } if (canPushCount++ == 0) { // Initialize the Ping command s.start(Tags.PING_PING) .data(Tags.PING_HEARTBEAT_INTERVAL, Integer.toString(pingHeartbeat)) .start(Tags.PING_FOLDERS); } String folderClass = getTargetCollectionClassFromCursor(c); s.start(Tags.PING_FOLDER) .data(Tags.PING_ID, c.getString(Mailbox.CONTENT_SERVER_ID_COLUMN)) .data(Tags.PING_CLASS, folderClass) .end(); readyMailboxes.add(mailboxName); } else if ((pingStatus == SyncManager.PING_STATUS_RUNNING) || (pingStatus == SyncManager.PING_STATUS_WAITING)) { notReadyMailboxes.add(mailboxName); } else if (pingStatus == SyncManager.PING_STATUS_UNABLE) { pushCount--; userLog(mailboxName, " in error state; ignore"); continue; } } } finally { c.close(); } if (Eas.USER_LOG) { if (!notReadyMailboxes.isEmpty()) { userLog("Ping not ready for: " + notReadyMailboxes); } if (!readyMailboxes.isEmpty()) { userLog("Ping ready for: " + readyMailboxes); } } // If we've waited 10 seconds or more, just ping with whatever boxes are ready // But use a shorter than normal heartbeat boolean forcePing = !notReadyMailboxes.isEmpty() && (pingWaitCount > 5); if ((canPushCount > 0) && ((canPushCount == pushCount) || forcePing)) { // If all pingable boxes are ready for push, send Ping to the server s.end().end().done(); pingWaitCount = 0; mPostReset = false; mPostAborted = false; // If we've been stopped, this is a good time to return if (mStop) return; long pingTime = SystemClock.elapsedRealtime(); try { // Send the ping, wrapped by appropriate timeout/alarm if (forcePing) { userLog("Forcing ping after waiting for all boxes to be ready"); } HttpResponse res = sendPing(s.toByteArray(), forcePing ? PING_FORCE_HEARTBEAT : pingHeartbeat); int code = res.getStatusLine().getStatusCode(); userLog("Ping response: ", code); // Return immediately if we've been asked to stop during the ping if (mStop) { userLog("Stopping pingLoop"); return; } if (code == HttpStatus.SC_OK) { // Make sure to clear out any pending sync errors SyncManager.removeFromSyncErrorMap(mMailboxId); HttpEntity e = res.getEntity(); int len = (int)e.getContentLength(); InputStream is = res.getEntity().getContent(); if (len != 0) { int pingResult = parsePingResult(is, mContentResolver, pingErrorMap); // If our ping completed (status = 1), and we weren't forced and we're // not at the maximum, try increasing timeout by two minutes if (pingResult == PROTOCOL_PING_STATUS_COMPLETED && !forcePing) { if (pingHeartbeat > mPingHighWaterMark) { mPingHighWaterMark = pingHeartbeat; userLog("Setting high water mark at: ", mPingHighWaterMark); } if ((pingHeartbeat < PING_MAX_HEARTBEAT) && !mPingHeartbeatDropped) { pingHeartbeat += PING_HEARTBEAT_INCREMENT; if (pingHeartbeat > PING_MAX_HEARTBEAT) { pingHeartbeat = PING_MAX_HEARTBEAT; } userLog("Increasing ping heartbeat to ", pingHeartbeat, "s"); } } } else { userLog("Ping returned empty result; throwing IOException"); throw new IOException(); } } else if (isAuthError(code)) { mExitStatus = EXIT_LOGIN_FAILURE; userLog("Authorization error during Ping: ", code); throw new IOException(); } } catch (IOException e) { String message = e.getMessage(); // If we get the exception that is indicative of a NAT timeout and if we // haven't yet "fixed" the timeout, back off by two minutes and "fix" it boolean hasMessage = message != null; userLog("IOException runPingLoop: " + (hasMessage ? message : "[no message]")); if (mPostReset) { // Nothing to do in this case; this is SyncManager telling us to try another // ping. } else if (mPostAborted || (hasMessage && message.contains("reset by peer"))) { long pingLength = SystemClock.elapsedRealtime() - pingTime; if ((pingHeartbeat > PING_MIN_HEARTBEAT) && (pingHeartbeat > mPingHighWaterMark)) { pingHeartbeat -= PING_HEARTBEAT_INCREMENT; mPingHeartbeatDropped = true; if (pingHeartbeat < PING_MIN_HEARTBEAT) { pingHeartbeat = PING_MIN_HEARTBEAT; } userLog("Decreased ping heartbeat to ", pingHeartbeat, "s"); } else if (mPostAborted) { // There's no point in throwing here; this can happen in two cases // 1) An alarm, which indicates minutes without activity; no sense // backing off // 2) SyncManager abort, due to sync of mailbox. Again, we want to // keep on trying to ping userLog("Ping aborted; retry"); } else if (pingLength < 2000) { userLog("Abort or NAT type return < 2 seconds; throwing IOException"); throw e; } else { userLog("NAT type IOException > 2 seconds?"); } } else { throw e; } } } else if (forcePing) { // In this case, there aren't any boxes that are pingable, but there are boxes // waiting (for IOExceptions) userLog("pingLoop waiting 60s for any pingable boxes"); sleep(60*SECONDS, true); } else if (pushCount > 0) { // If we want to Ping, but can't just yet, wait a little bit // TODO Change sleep to wait and use notify from SyncManager when a sync ends sleep(2*SECONDS, false); pingWaitCount++; //userLog("pingLoop waited 2s for: ", (pushCount - canPushCount), " box(es)"); } else if (uninitCount > 0) { // In this case, we're doing an initial sync of at least one mailbox. Since this // is typically a one-time case, I'm ok with trying again every 10 seconds until // we're in one of the other possible states. userLog("pingLoop waiting for initial sync of ", uninitCount, " box(es)"); sleep(10*SECONDS, true); } else { // We've got nothing to do, so we'll check again in 30 minutes at which time // we'll update the folder list. Let the device sleep in the meantime... userLog("pingLoop sleeping for 30m"); sleep(30*MINUTES, true); } } // Save away the current heartbeat mPingHeartbeat = pingHeartbeat; } void sleep(long ms, boolean runAsleep) { if (runAsleep) { SyncManager.runAsleep(mMailboxId, ms+(5*SECONDS)); } try { Thread.sleep(ms); } catch (InterruptedException e) { // Doesn't matter whether we stop early; it's the thought that counts } finally { if (runAsleep) { SyncManager.runAwake(mMailboxId); } } } private int parsePingResult(InputStream is, ContentResolver cr, HashMap<String, Integer> errorMap) throws IOException, StaleFolderListException { PingParser pp = new PingParser(is, this); if (pp.parse()) { // True indicates some mailboxes need syncing... // syncList has the serverId's of the mailboxes... mBindArguments[0] = Long.toString(mAccount.mId); mPingChangeList = pp.getSyncList(); for (String serverId: mPingChangeList) { mBindArguments[1] = serverId; Cursor c = cr.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, WHERE_ACCOUNT_KEY_AND_SERVER_ID, mBindArguments, null); try { if (c.moveToFirst()) { /** * Check the boxes reporting changes to see if there really were any... * We do this because bugs in various Exchange servers can put us into a * looping behavior by continually reporting changes in a mailbox, even when * there aren't any. * * This behavior is seemingly random, and therefore we must code defensively * by backing off of push behavior when it is detected. * * One known cause, on certain Exchange 2003 servers, is acknowledged by * Microsoft, and the server hotfix for this case can be found at * http://support.microsoft.com/kb/923282 */ // Check the status of the last sync String status = c.getString(Mailbox.CONTENT_SYNC_STATUS_COLUMN); int type = SyncManager.getStatusType(status); // This check should always be true... if (type == SyncManager.SYNC_PING) { int changeCount = SyncManager.getStatusChangeCount(status); if (changeCount > 0) { errorMap.remove(serverId); } else if (changeCount == 0) { // This means that a ping reported changes in error; we keep a count // of consecutive errors of this kind String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN); Integer failures = errorMap.get(serverId); if (failures == null) { userLog("Last ping reported changes in error for: ", name); errorMap.put(serverId, 1); } else if (failures > MAX_PING_FAILURES) { // We'll back off of push for this box pushFallback(c.getLong(Mailbox.CONTENT_ID_COLUMN)); continue; } else { userLog("Last ping reported changes in error for: ", name); errorMap.put(serverId, failures + 1); } } } // If there were no problems with previous sync, we'll start another one SyncManager.startManualSync(c.getLong(Mailbox.CONTENT_ID_COLUMN), SyncManager.SYNC_PING, null); } } finally { c.close(); } } } return pp.getSyncStatus(); } private String getEmailFilter() { String filter = Eas.FILTER_1_WEEK; switch (mAccount.mSyncLookback) { case com.android.email.Account.SYNC_WINDOW_1_DAY: { filter = Eas.FILTER_1_DAY; break; } case com.android.email.Account.SYNC_WINDOW_3_DAYS: { filter = Eas.FILTER_3_DAYS; break; } case com.android.email.Account.SYNC_WINDOW_1_WEEK: { filter = Eas.FILTER_1_WEEK; break; } case com.android.email.Account.SYNC_WINDOW_2_WEEKS: { filter = Eas.FILTER_2_WEEKS; break; } case com.android.email.Account.SYNC_WINDOW_1_MONTH: { filter = Eas.FILTER_1_MONTH; break; } case com.android.email.Account.SYNC_WINDOW_ALL: { filter = Eas.FILTER_ALL; break; } } return filter; } /** * Common code to sync E+PIM data * * @param target, an EasMailbox, EasContacts, or EasCalendar object */ public void sync(AbstractSyncAdapter target) throws IOException { Mailbox mailbox = target.mMailbox; boolean moreAvailable = true; while (!mStop && moreAvailable) { // If we have no connectivity, just exit cleanly. SyncManager will start us up again // when connectivity has returned if (!hasConnectivity()) { userLog("No connectivity in sync; finishing sync"); mExitStatus = EXIT_DONE; return; } // Every time through the loop we check to see if we're still syncable if (!target.isSyncable()) { mExitStatus = EXIT_DONE; return; } // Now, handle various requests while (true) { Request req = null; synchronized (mRequests) { if (mRequests.isEmpty()) { break; } else { req = mRequests.get(0); } } // Our two request types are PartRequest (loading attachment) and // MeetingResponseRequest (respond to a meeting request) if (req instanceof PartRequest) { getAttachment((PartRequest)req); } else if (req instanceof MeetingResponseRequest) { sendMeetingResponse((MeetingResponseRequest)req); } // If there's an exception handling the request, we'll throw it // Otherwise, we remove the request synchronized(mRequests) { mRequests.remove(req); } } Serializer s = new Serializer(); String className = target.getCollectionName(); // STOPSHIP Remove the following if statement; temporary logging for Calendar sync if (className.equals("Calendar") && Eas.PARSER_LOG) { s = new Serializer(true, true); } String syncKey = target.getSyncKey(); userLog("sync, sending ", className, " syncKey: ", syncKey); s.start(Tags.SYNC_SYNC) .start(Tags.SYNC_COLLECTIONS) .start(Tags.SYNC_COLLECTION) .data(Tags.SYNC_CLASS, className) .data(Tags.SYNC_SYNC_KEY, syncKey) .data(Tags.SYNC_COLLECTION_ID, mailbox.mServerId) .tag(Tags.SYNC_DELETES_AS_MOVES); // Start with the default timeout int timeout = COMMAND_TIMEOUT; if (!syncKey.equals("0")) { // EAS doesn't like GetChanges if the syncKey is "0"; not documented s.tag(Tags.SYNC_GET_CHANGES); } else { // Use enormous timeout for initial sync, which empirically can take a while longer timeout = 120*SECONDS; } s.data(Tags.SYNC_WINDOW_SIZE, className.equals("Email") ? EMAIL_WINDOW_SIZE : PIM_WINDOW_SIZE); // Handle options s.start(Tags.SYNC_OPTIONS); // Set the lookback appropriately (EAS calls this a "filter") for all but Contacts if (className.equals("Email")) { s.data(Tags.SYNC_FILTER_TYPE, getEmailFilter()); } else if (className.equals("Calendar")) { // TODO Force two weeks for calendar until we can set this! s.data(Tags.SYNC_FILTER_TYPE, Eas.FILTER_2_WEEKS); } // Set the truncation amount for all classes if (mProtocolVersionDouble >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) { s.start(Tags.BASE_BODY_PREFERENCE) // HTML for email; plain text for everything else .data(Tags.BASE_TYPE, (className.equals("Email") ? Eas.BODY_PREFERENCE_HTML : Eas.BODY_PREFERENCE_TEXT)) .data(Tags.BASE_TRUNCATION_SIZE, Eas.EAS12_TRUNCATION_SIZE) .end(); } else { s.data(Tags.SYNC_TRUNCATION, Eas.EAS2_5_TRUNCATION_SIZE); } s.end(); // Send our changes up to the server target.sendLocalChanges(s); s.end().end().end().done(); HttpResponse resp = sendHttpClientPost("Sync", new ByteArrayEntity(s.toByteArray()), timeout); int code = resp.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { InputStream is = resp.getEntity().getContent(); if (is != null) { moreAvailable = target.parse(is); target.cleanup(); } else { userLog("Empty input stream in sync command response"); } } else { userLog("Sync response error: ", code); if (isProvisionError(code)) { mExitStatus = EXIT_SECURITY_FAILURE; } else if (isAuthError(code)) { mExitStatus = EXIT_LOGIN_FAILURE; } else { mExitStatus = EXIT_IO_ERROR; } return; } } mExitStatus = EXIT_DONE; } protected boolean setupService() { // Make sure account and mailbox are always the latest from the database mAccount = Account.restoreAccountWithId(mContext, mAccount.mId); if (mAccount == null) return false; mMailbox = Mailbox.restoreMailboxWithId(mContext, mMailbox.mId); if (mMailbox == null) return false; mThread = Thread.currentThread(); android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); TAG = mThread.getName(); HostAuth ha = HostAuth.restoreHostAuthWithId(mContext, mAccount.mHostAuthKeyRecv); if (ha == null) return false; mHostAddress = ha.mAddress; mUserName = ha.mLogin; mPassword = ha.mPassword; // Set up our protocol version from the Account mProtocolVersion = mAccount.mProtocolVersion; // If it hasn't been set up, start with default version if (mProtocolVersion == null) { mProtocolVersion = Eas.DEFAULT_PROTOCOL_VERSION; } mProtocolVersionDouble = Double.parseDouble(mProtocolVersion); return true; } /* (non-Javadoc) * @see java.lang.Runnable#run() */ public void run() { if (!setupService()) return; try { SyncManager.callback().syncMailboxStatus(mMailboxId, EmailServiceStatus.IN_PROGRESS, 0); } catch (RemoteException e1) { // Don't care if this fails } // Whether or not we're the account mailbox try { mDeviceId = SyncManager.getDeviceId(); if ((mMailbox == null) || (mAccount == null)) { return; } else if (mMailbox.mType == Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) { runAccountMailbox(); } else { AbstractSyncAdapter target; if (mMailbox.mType == Mailbox.TYPE_CONTACTS) { target = new ContactsSyncAdapter(mMailbox, this); } else if (mMailbox.mType == Mailbox.TYPE_CALENDAR) { target = new CalendarSyncAdapter(mMailbox, this); } else { target = new EmailSyncAdapter(mMailbox, this); } // We loop here because someone might have put a request in while we were syncing // and we've missed that opportunity... do { if (mRequestTime != 0) { userLog("Looping for user request..."); mRequestTime = 0; } sync(target); } while (mRequestTime != 0); } } catch (EasAuthenticationException e) { userLog("Caught authentication error"); mExitStatus = EXIT_LOGIN_FAILURE; } catch (IOException e) { String message = e.getMessage(); userLog("Caught IOException: ", (message == null) ? "No message" : message); mExitStatus = EXIT_IO_ERROR; } catch (Exception e) { userLog("Uncaught exception in EasSyncService", e); } finally { int status; if (!mStop) { userLog("Sync finished"); SyncManager.done(this); switch (mExitStatus) { case EXIT_IO_ERROR: status = EmailServiceStatus.CONNECTION_ERROR; break; case EXIT_DONE: status = EmailServiceStatus.SUCCESS; ContentValues cv = new ContentValues(); cv.put(Mailbox.SYNC_TIME, System.currentTimeMillis()); String s = "S" + mSyncReason + ':' + status + ':' + mChangeCount; cv.put(Mailbox.SYNC_STATUS, s); mContentResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, mMailboxId), cv, null, null); break; case EXIT_LOGIN_FAILURE: status = EmailServiceStatus.LOGIN_FAILED; break; case EXIT_SECURITY_FAILURE: status = EmailServiceStatus.SECURITY_FAILURE; + // Ask for a new folder list. This should wake up the account mailbox; a + // security error in account mailbox should start the provisioning process + SyncManager.reloadFolderList(mContext, mAccount.mId, true); break; default: status = EmailServiceStatus.REMOTE_EXCEPTION; errorLog("Sync ended due to an exception."); break; } } else { userLog("Stopped sync finished."); status = EmailServiceStatus.SUCCESS; } try { SyncManager.callback().syncMailboxStatus(mMailboxId, status, 0); } catch (RemoteException e1) { // Don't care if this fails } // Make sure SyncManager knows about this SyncManager.kick("sync finished"); } } }
true
false
null
null
diff --git a/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/BugzillaTaskDataHandler.java b/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/BugzillaTaskDataHandler.java index ed1b6d610..e26f48a49 100644 --- a/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/BugzillaTaskDataHandler.java +++ b/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/BugzillaTaskDataHandler.java @@ -1,341 +1,342 @@ /******************************************************************************* * Copyright (c) 2004, 2007 Mylyn project committers 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 *******************************************************************************/ package org.eclipse.mylyn.internal.bugzilla.core; import java.io.IOException; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.mylyn.internal.bugzilla.core.IBugzillaConstants.BUGZILLA_OPERATION; import org.eclipse.mylyn.internal.bugzilla.core.IBugzillaConstants.BUGZILLA_REPORT_STATUS; import org.eclipse.mylyn.internal.bugzilla.core.IBugzillaConstants.BUGZILLA_RESOLUTION_2_0; import org.eclipse.mylyn.internal.bugzilla.core.IBugzillaConstants.BUGZILLA_RESOLUTION_3_0; import org.eclipse.mylyn.monitor.core.StatusHandler; import org.eclipse.mylyn.tasks.core.AbstractAttributeFactory; import org.eclipse.mylyn.tasks.core.AbstractTaskDataHandler; import org.eclipse.mylyn.tasks.core.RepositoryOperation; import org.eclipse.mylyn.tasks.core.RepositoryStatus; import org.eclipse.mylyn.tasks.core.RepositoryTaskAttribute; import org.eclipse.mylyn.tasks.core.RepositoryTaskData; import org.eclipse.mylyn.tasks.core.TaskRepository; /** * @author Mik Kersten * @author Rob Elves */ public class BugzillaTaskDataHandler extends AbstractTaskDataHandler { private static final String OPERATION_INPUT_ASSIGNED_TO = "assigned_to"; private static final String OPERATION_INPUT_DUP_ID = "dup_id"; private static final String OPERATION_OPTION_RESOLUTION = "resolution"; private static final String OPERATION_LABEL_CLOSE = "Mark as CLOSED"; private static final String OPERATION_LABEL_VERIFY = "Mark as VERIFIED"; private static final String OPERATION_LABEL_REOPEN = "Reopen bug"; private static final String OPERATION_LABEL_REASSIGN_DEFAULT = "Reassign to default assignee"; private static final String OPERATION_LABEL_REASSIGN = "Reassign to"; private static final String OPERATION_LABEL_DUPLICATE = "Mark as duplicate of #"; private static final String OPERATION_LABEL_RESOLVE = "Resolve as"; private static final String OPERATION_LABEL_ACCEPT = "Accept (change status to ASSIGNED)"; private AbstractAttributeFactory attributeFactory = new BugzillaAttributeFactory(); private BugzillaRepositoryConnector connector; public BugzillaTaskDataHandler(BugzillaRepositoryConnector connector) { this.connector = connector; } @Override public RepositoryTaskData getTaskData(TaskRepository repository, String taskId, IProgressMonitor monitor) throws CoreException { try { BugzillaClient client = connector.getClientManager().getClient(repository); int bugId = BugzillaRepositoryConnector.getBugId(taskId); RepositoryTaskData taskData; try { taskData = client.getTaskData(bugId); } catch (CoreException e) { // TODO: Move retry handling into client if (e.getStatus().getCode() == RepositoryStatus.ERROR_REPOSITORY_LOGIN) { taskData = client.getTaskData(bugId); } else { throw e; } } if (taskData != null) { try { configureTaskData(repository, taskData); } catch (CoreException ce) { // retry since data retrieved may be corrupt taskData = client.getTaskData(bugId); if (taskData != null) { configureTaskData(repository, taskData); } } return taskData; } return null; } catch (IOException e) { throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.PLUGIN_ID, RepositoryStatus.ERROR_IO, repository.getUrl(), e)); } } @Override public Set<RepositoryTaskData> getMultiTaskData(TaskRepository repository, Set<String> taskIds, IProgressMonitor monitor) throws CoreException { try { Set<RepositoryTaskData> result = new HashSet<RepositoryTaskData>(); BugzillaClient client = connector.getClientManager().getClient(repository); try { Map<String, RepositoryTaskData> dataReturned = client.getTaskData(taskIds); for (RepositoryTaskData repositoryTaskData : dataReturned.values()) { result.add(repositoryTaskData); } } catch (CoreException e) { // TODO: Move retry handling into client if (e.getStatus().getCode() == RepositoryStatus.ERROR_REPOSITORY_LOGIN) { Map<String, RepositoryTaskData> dataReturned = client.getTaskData(taskIds); for (RepositoryTaskData repositoryTaskData : dataReturned.values()) { result.add(repositoryTaskData); } } else { throw e; } } for (RepositoryTaskData repositoryTaskData : result) { try { configureTaskData(repository, repositoryTaskData); } catch (CoreException ce) { // retry since data retrieved may be corrupt //taskData = client.getTaskData(bugId); //if (taskData != null) { configureTaskData(repository, repositoryTaskData); // } } } return result; } catch (IOException e) { throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.PLUGIN_ID, RepositoryStatus.ERROR_IO, repository.getUrl(), e)); } } @Override public String postTaskData(TaskRepository repository, RepositoryTaskData taskData, IProgressMonitor monitor) throws CoreException { try { BugzillaClient client = connector.getClientManager().getClient(repository); try { return client.postTaskData(taskData); } catch (CoreException e) { // TODO: Move retry handling into client if (e.getStatus().getCode() == RepositoryStatus.ERROR_REPOSITORY_LOGIN) { return client.postTaskData(taskData); } else { throw e; } } } catch (IOException e) { throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.PLUGIN_ID, RepositoryStatus.ERROR_IO, repository.getUrl(), e)); } } @Override public AbstractAttributeFactory getAttributeFactory(String repositoryUrl, String repositoryKind, String taskKind) { // we don't care about the repository information right now return attributeFactory; } @Override public AbstractAttributeFactory getAttributeFactory(RepositoryTaskData taskData) { return getAttributeFactory(taskData.getRepositoryUrl(), taskData.getRepositoryKind(), taskData.getTaskKind()); } public void configureTaskData(TaskRepository repository, RepositoryTaskData taskData) throws CoreException { connector.updateAttributeOptions(repository, taskData); addValidOperations(taskData, repository.getUserName(), repository); } private void addValidOperations(RepositoryTaskData bugReport, String userName, TaskRepository repository) throws CoreException { BUGZILLA_REPORT_STATUS status; try { status = BUGZILLA_REPORT_STATUS.valueOf(bugReport.getStatus()); } catch (RuntimeException e) { StatusHandler.log(e, "Unrecognized status: " + bugReport.getStatus()); status = BUGZILLA_REPORT_STATUS.NEW; } switch (status) { case UNCONFIRMED: case REOPENED: case NEW: addOperation(repository, bugReport, BUGZILLA_OPERATION.none, userName); addOperation(repository, bugReport, BUGZILLA_OPERATION.accept, userName); addOperation(repository, bugReport, BUGZILLA_OPERATION.resolve, userName); addOperation(repository, bugReport, BUGZILLA_OPERATION.duplicate, userName); break; case ASSIGNED: addOperation(repository, bugReport, BUGZILLA_OPERATION.none, userName); addOperation(repository, bugReport, BUGZILLA_OPERATION.resolve, userName); addOperation(repository, bugReport, BUGZILLA_OPERATION.duplicate, userName); break; case RESOLVED: addOperation(repository, bugReport, BUGZILLA_OPERATION.none, userName); addOperation(repository, bugReport, BUGZILLA_OPERATION.reopen, userName); addOperation(repository, bugReport, BUGZILLA_OPERATION.verify, userName); addOperation(repository, bugReport, BUGZILLA_OPERATION.close, userName); break; case CLOSED: addOperation(repository, bugReport, BUGZILLA_OPERATION.none, userName); addOperation(repository, bugReport, BUGZILLA_OPERATION.reopen, userName); break; case VERIFIED: addOperation(repository, bugReport, BUGZILLA_OPERATION.none, userName); addOperation(repository, bugReport, BUGZILLA_OPERATION.reopen, userName); addOperation(repository, bugReport, BUGZILLA_OPERATION.close, userName); } String bugzillaVersion; try { bugzillaVersion = BugzillaCorePlugin.getRepositoryConfiguration(repository, false).getInstallVersion(); } catch (CoreException e1) { // ignore bugzillaVersion = "2.18"; } if (bugzillaVersion.compareTo("3.1") < 0 - && (status == BUGZILLA_REPORT_STATUS.NEW || status == BUGZILLA_REPORT_STATUS.ASSIGNED)) { + && (status == BUGZILLA_REPORT_STATUS.NEW || status == BUGZILLA_REPORT_STATUS.ASSIGNED + || status == BUGZILLA_REPORT_STATUS.REOPENED || status == BUGZILLA_REPORT_STATUS.UNCONFIRMED)) { // old bugzilla workflow is used addOperation(repository, bugReport, BUGZILLA_OPERATION.reassign, userName); addOperation(repository, bugReport, BUGZILLA_OPERATION.reassignbycomponent, userName); } } private void addOperation(TaskRepository repository, RepositoryTaskData bugReport, BUGZILLA_OPERATION opcode, String userName) { RepositoryOperation newOperation = null; switch (opcode) { case none: newOperation = new RepositoryOperation(opcode.toString(), "Leave as " + bugReport.getStatus() + " " + bugReport.getResolution()); newOperation.setChecked(true); break; case accept: newOperation = new RepositoryOperation(opcode.toString(), OPERATION_LABEL_ACCEPT); break; case resolve: newOperation = new RepositoryOperation(opcode.toString(), OPERATION_LABEL_RESOLVE); newOperation.setUpOptions(OPERATION_OPTION_RESOLUTION); RepositoryConfiguration config; try { config = BugzillaCorePlugin.getRepositoryConfiguration(repository, false); } catch (CoreException e) { config = null; } if (config != null) { for (String resolution : config.getResolutions()) { // DUPLICATE and MOVED have special meanings so do not show as resolution - if (resolution.compareTo("DUPLICATE")!= 0 && resolution.compareTo("MOVED")!= 0) + if (resolution.compareTo("DUPLICATE") != 0 && resolution.compareTo("MOVED") != 0) newOperation.addOption(resolution, resolution); } } else { // LATER and REMIND must not be there in Bugzilla >= 3.0 is used //If getVersion() returns "Automatic (Use Validate Settings)" we use the Version 3 Resolution - if (repository.getVersion().compareTo("3.0")>= 0) { + if (repository.getVersion().compareTo("3.0") >= 0) { for (BUGZILLA_RESOLUTION_3_0 resolution : BUGZILLA_RESOLUTION_3_0.values()) { newOperation.addOption(resolution.toString(), resolution.toString()); } } else { for (BUGZILLA_RESOLUTION_2_0 resolution : BUGZILLA_RESOLUTION_2_0.values()) { newOperation.addOption(resolution.toString(), resolution.toString()); } } } break; case duplicate: newOperation = new RepositoryOperation(opcode.toString(), OPERATION_LABEL_DUPLICATE); newOperation.setInputName(OPERATION_INPUT_DUP_ID); newOperation.setInputValue(""); break; case reassign: String localUser = userName; newOperation = new RepositoryOperation(opcode.toString(), OPERATION_LABEL_REASSIGN); newOperation.setInputName(OPERATION_INPUT_ASSIGNED_TO); newOperation.setInputValue(localUser); break; case reassignbycomponent: newOperation = new RepositoryOperation(opcode.toString(), OPERATION_LABEL_REASSIGN_DEFAULT); break; case reopen: newOperation = new RepositoryOperation(opcode.toString(), OPERATION_LABEL_REOPEN); break; case verify: newOperation = new RepositoryOperation(opcode.toString(), OPERATION_LABEL_VERIFY); break; case close: newOperation = new RepositoryOperation(opcode.toString(), OPERATION_LABEL_CLOSE); break; default: break; } if (newOperation != null) { bugReport.addOperation(newOperation); } } @Override public boolean initializeTaskData(TaskRepository repository, RepositoryTaskData data, IProgressMonitor monitor) throws CoreException { // Bugzilla needs a product to create task data return false; } // TODO: Move to AbstractTaskDataHandler @Override public Set<String> getSubTaskIds(RepositoryTaskData taskData) { Set<String> result = new HashSet<String>(); RepositoryTaskAttribute attribute = taskData.getAttribute(BugzillaReportElement.DEPENDSON.getKeyString()); if (attribute != null) { String[] ids = attribute.getValue().split(","); for (String id : ids) { id = id.trim(); if (id.length() == 0) continue; result.add(id); } } return result; } @Override public boolean canGetMultiTaskData() { return true; } }
false
false
null
null
diff --git a/gmaven-feature/gmaven-feature-support/src/main/java/org/codehaus/gmaven/feature/support/FeatureSupport.java b/gmaven-feature/gmaven-feature-support/src/main/java/org/codehaus/gmaven/feature/support/FeatureSupport.java index 335278b..959c045 100644 --- a/gmaven-feature/gmaven-feature-support/src/main/java/org/codehaus/gmaven/feature/support/FeatureSupport.java +++ b/gmaven-feature/gmaven-feature-support/src/main/java/org/codehaus/gmaven/feature/support/FeatureSupport.java @@ -1,172 +1,172 @@ /* * Copyright (C) 2006-2007 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.codehaus.gmaven.feature.support; import org.codehaus.gmaven.feature.Component; import org.codehaus.gmaven.feature.Configuration; import org.codehaus.gmaven.feature.Feature; import org.codehaus.gmaven.feature.FeatureException; import org.codehaus.gmaven.feature.Provider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provides support for {@link Feature} implementations. * * @version $Id$ * @author <a href="mailto:jason@planet57.com">Jason Dillon</a> */ public abstract class FeatureSupport implements Feature { protected final Logger log = LoggerFactory.getLogger(getClass()); protected final String key; protected final Configuration config; protected final boolean supported; protected Provider provider; protected FeatureSupport(final String key, final boolean supported) { assert key != null; this.key = key; this.supported = supported; this.config = new Configuration(); } protected FeatureSupport(final String key) { this(key, true); } public String toString() { return asString(this); } public int hashCode() { return key().hashCode(); } public String key() { return key; } public String name() { return key(); } public boolean supported() { return supported; } public void require() { if (!supported()) { throw new FeatureException("Feature not supported: " + key()); } } public Configuration config() { return config; } public Component create(final Configuration context) throws Exception { assert context != null; Component component = create(); // Merge in the context Configuration c = component.config(); c.merge(context); return component; } public Component create() throws Exception { // First we need to be supported, so require it require(); // Then install the provider CL into the TCL to get better behaved CL mucko final ClassLoader tcl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(provider().getClass().getClassLoader()); try { Component component = doCreate(); - // Merge our configuraiton + // Merge our configuration Configuration c = component.config(); c.merge(config()); return component; } finally { // Reset back to the previous TCL Thread.currentThread().setContextClassLoader(tcl); } } protected abstract Component doCreate() throws Exception; // // Provider registration hooks to work with ProviderSupport // /* package */ synchronized void register(final Provider provider) { if (this.provider != null) { throw new IllegalStateException( "Duplicate provider registration with feature: " + this + ", previous provider: " + this.provider + ", current provider: " + provider); } this.provider = provider; } protected synchronized Provider provider() { if (provider == null) { throw new IllegalStateException("Provider has not been registered with feature: " + this); } return provider; } public static String asString(final Feature feature) { assert feature != null; StringBuffer buff = new StringBuffer(); buff.append("["); buff.append(feature.key()); buff.append("]"); // noinspection StringEquality if (feature.key() != feature.name()) { buff.append(" '"); buff.append(feature.name()); buff.append("'"); } buff.append(" (supported: "); buff.append(feature.supported()); buff.append(", type: "); buff.append(feature.getClass().getName()); buff.append(")"); return buff.toString(); } } \ No newline at end of file diff --git a/gmaven-plugin/src/main/java/org/codehaus/gmaven/plugin/MojoSupport.java b/gmaven-plugin/src/main/java/org/codehaus/gmaven/plugin/MojoSupport.java index 459fc11..8b8d54a 100644 --- a/gmaven-plugin/src/main/java/org/codehaus/gmaven/plugin/MojoSupport.java +++ b/gmaven-plugin/src/main/java/org/codehaus/gmaven/plugin/MojoSupport.java @@ -1,323 +1,323 @@ /* * Copyright (C) 2006-2007 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.codehaus.gmaven.plugin; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DependencyResolutionRequiredException; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.metadata.ArtifactMetadataSource; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; import org.apache.maven.artifact.resolver.ArtifactResolutionException; import org.apache.maven.artifact.resolver.ArtifactResolver; import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.model.Dependency; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import org.codehaus.gmaven.common.ArtifactItem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Support for Mojo implementations. * * @version $Id$ * @author <a href="mailto:jason@planet57.com">Jason Dillon</a> */ public abstract class MojoSupport extends AbstractMojo { protected final Logger log = LoggerFactory.getLogger(getClass()); /** * @parameter expression="${project}" * @required * @readonly * * @noinspection UnusedDeclaration */ protected MavenProject project; /** * Main Mojo execution hook. Sub-class should use {@link #doExecute} instead. */ public void execute() throws MojoExecutionException, MojoFailureException { try { doExecute(); } catch (Exception e) { // // NOTE: Wrap to avoid truncating the stacktrace // if (e instanceof MojoExecutionException) { throw new MojoExecutionException(e.getMessage(), e); } else if (e instanceof MojoFailureException) { MojoFailureException x = new MojoFailureException(e.getMessage()); x.initCause(e); throw x; } else { throw new MojoExecutionException(e.getMessage(), e); } } } protected abstract void doExecute() throws Exception; // // Classpath Muck // protected List getProjectClasspathElements() throws DependencyResolutionRequiredException { return Collections.EMPTY_LIST; } protected ArtifactItem[] getUserClassspathElements() { return new ArtifactItem[0]; } protected URL[] createClassPath() throws Exception { List list = new ArrayList(); // Add the projects dependencies List files = getProjectClasspathElements(); if (files != null) { log.debug("Project Classpath:"); for (int i = 0; i < files.size(); ++i) { URL url = new File((String)files.get(i)).toURI().toURL(); list.add(url); log.debug(" {}", url); } } // Add user dependencies (if there are any) ArtifactItem[] items = getUserClassspathElements(); if (items != null) { log.debug("User Classpath:"); for (int i=0; i < items.length; i++) { Artifact artifact = getArtifact(items[i]); URL url = artifact.getFile().toURI().toURL(); list.add(url); log.debug(" {}", url); } } return (URL[])list.toArray(new URL[list.size()]); } // // Artifact Muck // /** * @component * @readonly * @required * * @noinspection UnusedDeclaration */ protected ArtifactFactory artifactFactory; /** * @component * @readonly * @required * * @noinspection UnusedDeclaration */ protected ArtifactResolver artifactResolver; /** * @component * @readonly * @required * * @noinspection UnusedDeclaration */ protected ArtifactMetadataSource artifactMetadataSource; /** * @parameter expression="${localRepository}" * @readonly * @required * * @noinspection UnusedDeclaration */ protected ArtifactRepository artifactRepository; /** * @parameter expression="${project.pluginArtifactRepositories}" * @required * @readonly * * @noinspection UnusedDeclaration */ protected List remoteRepositories; /** * Create a new artifact. If no version is specified, it will be retrieved from the dependency * list or from the DependencyManagement section of the pom. * * @param item The item to create an artifact for * @return An unresolved artifact for the given item. * * @throws MojoExecutionException Failed to create artifact */ protected Artifact createArtifact(final ArtifactItem item) throws MojoExecutionException { assert item != null; if (item.getVersion() == null) { fillMissingArtifactVersion(item); if (item.getVersion() == null) { throw new MojoExecutionException("Unable to find artifact version of " + item.getGroupId() + ":" + item.getArtifactId() + " in either dependency list or in project's dependency management."); } } // Convert the string version to a range VersionRange range; try { range = VersionRange.createFromVersionSpec(item.getVersion()); log.trace("Using version range: {}", range); } catch (InvalidVersionSpecificationException e) { throw new MojoExecutionException("Could not create range for version: " + item.getVersion(), e); } return artifactFactory.createDependencyArtifact( item.getGroupId(), item.getArtifactId(), range, item.getType(), item.getClassifier(), Artifact.SCOPE_PROVIDED); } /** - * Resolves the Artifact from the remote repository if nessessary. If no version is specified, it will + * Resolves the Artifact from the remote repository if necessary. If no version is specified, it will * be retrieved from the dependency list or from the DependencyManagement section of the pom. * * * @param item The item to create an artifact for; must not be null * @return The artifact for the given item * * @throws MojoExecutionException Failed to create artifact */ protected Artifact getArtifact(final ArtifactItem item) throws MojoExecutionException { assert item != null; Artifact artifact = createArtifact(item); return resolveArtifact(artifact, false); } /** - * Resolves the Artifact from the remote repository if nessessary. If no version is specified, it will + * Resolves the Artifact from the remote repository if necessary. If no version is specified, it will * be retrieved from the dependency list or from the DependencyManagement section of the pom. * * @param artifact The artifact to be resolved; must not be null - * @param transitive True to resolve the artifact transitivly + * @param transitive True to resolve the artifact transitively * @return The resolved artifact; never null * * @throws MojoExecutionException Failed to resolve artifact */ protected Artifact resolveArtifact(final Artifact artifact, final boolean transitive) throws MojoExecutionException { assert artifact != null; try { if (transitive) { artifactResolver.resolveTransitively( Collections.singleton(artifact), project.getArtifact(), project.getRemoteArtifactRepositories(), artifactRepository, artifactMetadataSource); } else { artifactResolver.resolve( artifact, project.getRemoteArtifactRepositories(), artifactRepository); } } catch (ArtifactResolutionException e) { throw new MojoExecutionException("Unable to resolve artifact", e); } catch (ArtifactNotFoundException e) { throw new MojoExecutionException("Unable to find artifact", e); } return artifact; } /** - * Tries to find missing version from dependancy list and dependency management. + * Tries to find missing version from dependency list and dependency management. * If found, the artifact is updated with the correct version. * * @param item The item to fill in missing version details into */ private void fillMissingArtifactVersion(final ArtifactItem item) { log.trace("Attempting to find missing version in {}:{}", item.getGroupId() , item.getArtifactId()); List list = project.getDependencies(); for (int i = 0; i < list.size(); ++i) { Dependency dependency = (Dependency) list.get(i); if (dependency.getGroupId().equals(item.getGroupId()) && dependency.getArtifactId().equals(item.getArtifactId()) && dependency.getType().equals(item.getType())) { log.trace("Found missing version: {} in dependency list", dependency.getVersion()); item.setVersion(dependency.getVersion()); return; } } list = project.getDependencyManagement().getDependencies(); for (int i = 0; i < list.size(); i++) { Dependency dependency = (Dependency) list.get(i); if (dependency.getGroupId().equals(item.getGroupId()) && dependency.getArtifactId().equals(item.getArtifactId()) && dependency.getType().equals(item.getType())) { log.trace("Found missing version: {} in dependency management list", dependency.getVersion()); item.setVersion(dependency.getVersion()); } } } } \ No newline at end of file diff --git a/gmaven-runtime/gmaven-runtime-support/src/main/java/org/codehaus/gmaven/runtime/support/util/ResourceLoaderImpl.java b/gmaven-runtime/gmaven-runtime-support/src/main/java/org/codehaus/gmaven/runtime/support/util/ResourceLoaderImpl.java index 43eeb0d..82978ca 100644 --- a/gmaven-runtime/gmaven-runtime-support/src/main/java/org/codehaus/gmaven/runtime/support/util/ResourceLoaderImpl.java +++ b/gmaven-runtime/gmaven-runtime-support/src/main/java/org/codehaus/gmaven/runtime/support/util/ResourceLoaderImpl.java @@ -1,91 +1,91 @@ /* * Copyright (C) 2006-2007 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.codehaus.gmaven.runtime.support.util; import org.codehaus.gmaven.runtime.support.stubgen.parser.SourceType; import org.codehaus.gmaven.runtime.util.ResourceLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.MalformedURLException; import java.net.URL; /** * Basic {@link ResourceLoader} implemenation. * * @version $Id$ * @author <a href="mailto:jason@planet57.com">Jason Dillon</a> */ public class ResourceLoaderImpl implements ResourceLoader { protected final Logger log = LoggerFactory.getLogger(getClass()); protected ClassLoader classLoader; public ResourceLoaderImpl(final ClassLoader classLoader) { assert classLoader != null; this.classLoader = classLoader; } public URL loadResource(final String name) throws MalformedURLException { return resolve(name, classLoader); } protected String toResourceName(final String className) { assert className != null; // Figure out what resource to load String resource = className; if (!resource.startsWith("/")) { resource = "/" + resource; } if (!resource.endsWith(SourceType.GROOVY_EXT)) { resource = resource.replace('.', '/'); resource += SourceType.GROOVY_EXT; } return resource; } protected URL resolve(final String className, final ClassLoader classLoader) throws MalformedURLException { assert className != null; assert classLoader != null; // log.debug("Resolve; class name: {}", className); String resource = toResourceName(className); // log.debug("Resolve; resource name {}", resource); URL url = classLoader.getResource(resource); // log.debug("From CL: {}", url); if (url == null) { - // Not sure if this is nessicary or not... + // Not sure if this is necessary or not... url = Thread.currentThread().getContextClassLoader().getResource(resource); // log.debug("From TCL: {}", url); } return url; } } \ No newline at end of file
false
false
null
null
diff --git a/org.eclipse.m2e.core/src/org/eclipse/m2e/core/internal/embedder/MavenEmbeddedRuntime.java b/org.eclipse.m2e.core/src/org/eclipse/m2e/core/internal/embedder/MavenEmbeddedRuntime.java index 6dc28ec..28c3fe9 100644 --- a/org.eclipse.m2e.core/src/org/eclipse/m2e/core/internal/embedder/MavenEmbeddedRuntime.java +++ b/org.eclipse.m2e.core/src/org/eclipse/m2e/core/internal/embedder/MavenEmbeddedRuntime.java @@ -1,297 +1,297 @@ /******************************************************************************* * Copyright (c) 2008-2010 Sonatype, Inc. * 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: * Sonatype, Inc. - initial API and implementation *******************************************************************************/ package org.eclipse.m2e.core.internal.embedder; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Platform; import org.eclipse.osgi.service.resolver.BaseDescription; import org.eclipse.osgi.service.resolver.BundleDescription; import org.eclipse.osgi.service.resolver.ExportPackageDescription; import org.eclipse.osgi.service.resolver.State; import org.eclipse.osgi.service.resolver.VersionConstraint; import org.eclipse.osgi.util.ManifestElement; import org.eclipse.m2e.core.embedder.IMavenLauncherConfiguration; import org.eclipse.m2e.core.embedder.MavenRuntime; import org.eclipse.m2e.core.embedder.MavenRuntimeManager; import org.eclipse.m2e.core.internal.Messages; /** * Embedded Maven runtime * * @author Eugene Kuleshov * @author Igor Fedorenko */ public class MavenEmbeddedRuntime implements MavenRuntime { private static final Logger log = LoggerFactory.getLogger(MavenEmbeddedRuntime.class); private static final String MAVEN_MAVEN_EMBEDDER_BUNDLE_ID = "org.eclipse.m2e.maven.runtime"; //$NON-NLS-1$ private static final String MAVEN_EXECUTOR_CLASS = org.apache.maven.cli.MavenCli.class.getName(); public static final String PLEXUS_CLASSWORLD_NAME = "plexus.core"; //$NON-NLS-1$ private static String[] LAUNCHER_CLASSPATH; private static String[] CLASSPATH; private static volatile String mavenVersion; private BundleContext bundleContext; public MavenEmbeddedRuntime(BundleContext bundleContext) { this.bundleContext = bundleContext; } public boolean isEditable() { return false; } public String getLocation() { return MavenRuntimeManager.EMBEDDED; } public String getSettings() { return null; } public boolean isAvailable() { return true; } public void createLauncherConfiguration(IMavenLauncherConfiguration collector, IProgressMonitor monitor) throws CoreException { collector.setMainType(MAVEN_EXECUTOR_CLASS, PLEXUS_CLASSWORLD_NAME); initClasspath(findMavenEmbedderBundle()); collector.addRealm(IMavenLauncherConfiguration.LAUNCHER_REALM); for(String entry : LAUNCHER_CLASSPATH) { collector.addArchiveEntry(entry); } collector.addRealm(PLEXUS_CLASSWORLD_NAME); for(String entry : CLASSPATH) { // https://issues.sonatype.org/browse/MNGECLIPSE-2507 if(!entry.contains("plexus-build-api")) { collector.addArchiveEntry(entry); } } } private synchronized void initClasspath(Bundle mavenRuntimeBundle) { if(CLASSPATH == null) { LinkedHashSet<String> allentries = new LinkedHashSet<String>(); addBundleClasspathEntries(allentries, mavenRuntimeBundle); // find and add more bundles State state = Platform.getPlatformAdmin().getState(false); BundleDescription description = state.getBundle(mavenRuntimeBundle.getBundleId()); for(String sname : new String[] {"com.ning.async-http-client", "org.jboss.netty", "org.slf4j.api"}) { Bundle dependency = findDependencyBundle(description, sname, new HashSet<BundleDescription>()); if(dependency != null) { addBundleClasspathEntries(allentries, dependency); } else { log.warn( "Could not find SOGi bundle with symbolic name ``{}'' required to launch embedded maven runtime in external process", sname); } } List<String> cp = new ArrayList<String>(); List<String> lcp = new ArrayList<String>(); for(String entry : allentries) { if(entry.contains("plexus-classworlds")) { //$NON-NLS-1$ lcp.add(entry); } else { cp.add(entry); } } CLASSPATH = cp.toArray(new String[cp.size()]); LAUNCHER_CLASSPATH = lcp.toArray(new String[lcp.size()]); } } private Bundle findDependencyBundle(BundleDescription bundleDescription, String dependencyName, Set<BundleDescription> visited) { ArrayList<VersionConstraint> dependencies = new ArrayList<VersionConstraint>(); dependencies.addAll(Arrays.asList(bundleDescription.getRequiredBundles())); dependencies.addAll(Arrays.asList(bundleDescription.getImportPackages())); for(VersionConstraint requiredSpecification : dependencies) { BundleDescription requiredDescription = getDependencyBundleDescription(requiredSpecification); if(requiredDescription != null && visited.add(requiredDescription)) { if(dependencyName.equals(requiredDescription.getName())) { return bundleContext.getBundle(requiredDescription.getBundleId()); } Bundle required = findDependencyBundle(requiredDescription, dependencyName, visited); if(required != null) { return required; } } } return null; } private BundleDescription getDependencyBundleDescription(VersionConstraint requiredSpecification) { BaseDescription supplier = requiredSpecification.getSupplier(); if(supplier instanceof BundleDescription) { return (BundleDescription) supplier; } else if(supplier instanceof ExportPackageDescription) { return ((ExportPackageDescription) supplier).getExporter(); } return null; } private void addBundleClasspathEntries(Set<String> entries, Bundle bundle) { for(String cp : parseBundleClasspath(bundle)) { String entry; if(".".equals(cp)) { entry = getNestedJarOrDir(bundle, "/"); } else { entry = getNestedJarOrDir(bundle, cp); } if(entry != null) { entries.add(entry); } } } private String[] parseBundleClasspath(Bundle bundle) { String[] result = new String[] {"."}; - String header = bundle.getHeaders().get(Constants.BUNDLE_CLASSPATH); + String header = (String) bundle.getHeaders().get(Constants.BUNDLE_CLASSPATH); ManifestElement[] classpathEntries = null; try { classpathEntries = ManifestElement.parseHeader(Constants.BUNDLE_CLASSPATH, header); } catch(BundleException ex) { log.warn("Could not parse bundle classpath of {}", bundle.toString(), ex); } if(classpathEntries != null) { result = new String[classpathEntries.length]; for(int i = 0; i < classpathEntries.length; i++ ) { result[i] = classpathEntries[i].getValue(); } } return result; } private String getNestedJarOrDir(Bundle bundle, String cp) { URL url = bundle.getEntry(cp); if(url == null) { log.debug("Bundle {} does not have entry {}", bundle.toString(), cp); return null; } try { return FileLocator.toFileURL(url).getFile(); } catch(IOException ex) { log.warn("Could not get entry {} for bundle {}", new Object[] {cp, bundle.toString(), ex}); } return null; } private Bundle findMavenEmbedderBundle() { Bundle bundle = null; Bundle[] bundles = bundleContext.getBundles(); for(int i = 0; i < bundles.length; i++ ) { if(MAVEN_MAVEN_EMBEDDER_BUNDLE_ID.equals(bundles[i].getSymbolicName())) { bundle = bundles[i]; break; } } return bundle; } public String toString() { Bundle embedder = Platform.getBundle(MAVEN_MAVEN_EMBEDDER_BUNDLE_ID); StringBuilder sb = new StringBuilder(); sb.append("Embedded (").append(getVersion()); //$NON-NLS-1$ if(embedder != null) { String version = (String) embedder.getHeaders().get(Constants.BUNDLE_VERSION); sb.append('/').append(version); } sb.append(')'); return sb.toString(); } private synchronized String getVersion(Bundle bundle) { if(mavenVersion != null) { return mavenVersion; } initClasspath(bundle); try { String mavenCoreJarPath = null; for(String path : CLASSPATH) { if(path.contains("maven-core") && path.endsWith(".jar")) { mavenCoreJarPath = path; break; } } if(mavenCoreJarPath == null) { throw new RuntimeException("Could not find maven core jar file"); } ZipFile zip = new ZipFile(mavenCoreJarPath); try { ZipEntry zipEntry = zip.getEntry("META-INF/maven/org.apache.maven/maven-core/pom.properties"); //$NON-NLS-1$ if(zipEntry != null) { Properties pomProperties = new Properties(); pomProperties.load(zip.getInputStream(zipEntry)); String version = pomProperties.getProperty("version"); //$NON-NLS-1$ if(version != null) { mavenVersion = version; return mavenVersion; } } } finally { zip.close(); } } catch(Exception e) { log.warn("Could not determine embedded maven version", e); } return Messages.MavenEmbeddedRuntime_unknown; } public String getVersion() { Bundle bundle = findMavenEmbedderBundle(); return getVersion(bundle); } }
true
false
null
null
diff --git a/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/servlet/AFacesServlet.java b/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/servlet/AFacesServlet.java index 0cfd0173..45f2623a 100644 --- a/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/servlet/AFacesServlet.java +++ b/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/servlet/AFacesServlet.java @@ -1,116 +1,109 @@ package gov.nih.nci.evs.browser.servlet; +import gov.nih.nci.evs.browser.common.AErrorHandler; + import java.io.IOException; import javax.faces.webapp.FacesServlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static gov.nih.nci.evs.browser.common.Constants.*; /** * @author garciawa2 * */ public class AFacesServlet extends HttpServlet { /** * Default Serial Version UID */ private static final long serialVersionUID = 1L; private FacesServlet delegate = null; private String errorPage = null; /** * Constructor */ public AFacesServlet() { // Do nothing } /** * (non-Javadoc) * * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig) */ public void init(ServletConfig _servletConfig) throws ServletException { delegate = new FacesServlet(); delegate.init(_servletConfig); errorPage = _servletConfig.getInitParameter(INIT_PARAM_ERROR_PAGE); } /** * (non-Javadoc) * * @see javax.servlet.GenericServlet#destroy() */ public void destroy() { delegate.destroy(); } /** * (non-Javadoc) * * @see javax.servlet.GenericServlet#getServletConfig() */ public ServletConfig getServletConfig() { return delegate.getServletConfig(); } /** * (non-Javadoc) * * @see javax.servlet.GenericServlet#getServletInfo() */ public String getServletInfo() { return delegate.getServletInfo(); } /** * (non-Javadoc) * * @see javax.servlet.http.HttpServlet#service(javax.servlet.ServletRequest, * javax.servlet.ServletResponse) */ public void service(ServletRequest _request, ServletResponse _response) throws ServletException, IOException { try { delegate.service(_request, _response); } catch (Throwable ex) { // Make Sure the Stack Trace is Printed to the Log ex.printStackTrace(); - // Set the Data to be Displayed - setPageErrorData(ex, (HttpServletRequest) _request); + // Set the Data to be Displayed + AErrorHandler.setPageErrorData(ex, (HttpServletRequest)_request); // Re-direct to Error Page redirectToErrorPage((HttpServletRequest) _request, (HttpServletResponse) _response); } } /** * @param _request * @param _response * @throws IOException */ private void redirectToErrorPage(HttpServletRequest _request, HttpServletResponse _response) throws IOException { - if (errorPage != null && !errorPage.equals("")) { + if (!"".equals(errorPage)) { _response.sendRedirect(_request.getContextPath() + errorPage); } } - /** - * @param _e - * @param _request - */ - public static void setPageErrorData(Throwable _e, - HttpServletRequest _request) { - _request.getSession().setAttribute(ERROR_MESSAGE, ERROR_UNEXPECTED); - } - }
false
false
null
null
diff --git a/src/java/com/threerings/parlor/server/ParlorProvider.java b/src/java/com/threerings/parlor/server/ParlorProvider.java index 42c4ef0e7..72d2859fa 100644 --- a/src/java/com/threerings/parlor/server/ParlorProvider.java +++ b/src/java/com/threerings/parlor/server/ParlorProvider.java @@ -1,89 +1,94 @@ // -// $Id: ParlorProvider.java,v 1.4 2001/10/02 02:09:06 mdb Exp $ +// $Id: ParlorProvider.java,v 1.5 2001/10/03 03:44:52 mdb Exp $ package com.threerings.parlor.server; import com.threerings.cocktail.cher.server.InvocationProvider; import com.threerings.cocktail.cher.server.ServiceFailedException; import com.threerings.cocktail.party.data.BodyObject; import com.threerings.cocktail.party.server.PartyServer; +import com.threerings.parlor.Log; import com.threerings.parlor.client.ParlorCodes; import com.threerings.parlor.data.GameConfig; /** * The parlor provider handles the server side of the various Parlor * services that are made available for direct invocation by the client. * Primarily these are the matchmaking mechanisms. */ public class ParlorProvider extends InvocationProvider implements ParlorCodes { /** * Constructs a parlor provider instance which will be used to handle * all parlor-related invocation service requests. This is * automatically taken care of by the parlor manager, so no other * entity need instantiate and register a parlor provider. * * @param pmgr a reference to the parlor manager active in this * server. */ public ParlorProvider (ParlorManager pmgr) { _pmgr = pmgr; } /** * Processes a request from the client to invite another user to play * a game. */ public void handleInviteRequest ( BodyObject source, int invid, String invitee, GameConfig config) { +// Log.info("Handling invite request [source=" + source + +// ", invid=" + invid + ", invitee=" + invitee + +// ", config=" + config + "]."); + String rsp = null; // ensure that the invitee is online at present try { BodyObject target = PartyServer.lookupBody(invitee); if (target == null) { throw new ServiceFailedException(INVITEE_NOT_ONLINE); } // submit the invite request to the parlor manager int inviteId = _pmgr.invite(source, target, config); sendResponse(source, invid, INVITE_RECEIVED_RESPONSE, new Integer(inviteId)); } catch (ServiceFailedException sfe) { // the exception message is the code indicating the reason // for the invitation rejection sendResponse(source, invid, INVITE_FAILED_RESPONSE, sfe.getMessage()); } } /** * Processes a request from the client to respond to an outstanding * invitation by accepting, refusing, or countering it. */ - public void handleRepsondInviteRequest ( + public void handleRespondInviteRequest ( BodyObject source, int invid, int inviteId, int code, Object arg) { // pass this on to the parlor manager _pmgr.respondToInvite(source, inviteId, code, arg); } /** * Processes a request from the client to cancel an outstanding * invitation. */ public void handleCancelInviteRequest ( BodyObject source, int invid, int inviteId) { // pass this on to the parlor manager _pmgr.cancelInvite(source, inviteId); } /** A reference to the parlor manager we're working with. */ protected ParlorManager _pmgr; }
false
false
null
null
diff --git a/GLWallpaperService/src/net/rbgrn/android/glwallpaperservice/GLWallpaperService.java b/GLWallpaperService/src/net/rbgrn/android/glwallpaperservice/GLWallpaperService.java index 068afe3..f642115 100644 --- a/GLWallpaperService/src/net/rbgrn/android/glwallpaperservice/GLWallpaperService.java +++ b/GLWallpaperService/src/net/rbgrn/android/glwallpaperservice/GLWallpaperService.java @@ -1,943 +1,944 @@ /* * 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 net.rbgrn.android.glwallpaperservice; import java.io.Writer; import java.util.ArrayList; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; import net.rbgrn.android.glwallpaperservice.BaseConfigChooser.ComponentSizeChooser; import net.rbgrn.android.glwallpaperservice.BaseConfigChooser.SimpleEGLConfigChooser; import android.service.wallpaper.WallpaperService; import android.util.Log; import android.view.SurfaceHolder; // Original code provided by Robert Green // http://www.rbgrn.net/content/354-glsurfaceview-adapted-3d-live-wallpapers public class GLWallpaperService extends WallpaperService { private static final String TAG = "GLWallpaperService"; @Override public Engine onCreateEngine() { return new GLEngine(); } public class GLEngine extends Engine { public final static int RENDERMODE_WHEN_DIRTY = 0; public final static int RENDERMODE_CONTINUOUSLY = 1; private GLThread mGLThread; private EGLConfigChooser mEGLConfigChooser; private EGLContextFactory mEGLContextFactory; private EGLWindowSurfaceFactory mEGLWindowSurfaceFactory; private GLWrapper mGLWrapper; private int mDebugFlags; public GLEngine() { super(); } @Override public void onVisibilityChanged(boolean visible) { if (visible) { onResume(); } else { onPause(); } super.onVisibilityChanged(visible); } @Override public void onCreate(SurfaceHolder surfaceHolder) { super.onCreate(surfaceHolder); // Log.d(TAG, "GLEngine.onCreate()"); } @Override public void onDestroy() { super.onDestroy(); // Log.d(TAG, "GLEngine.onDestroy()"); mGLThread.requestExitAndWait(); } @Override public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) { // Log.d(TAG, "onSurfaceChanged()"); mGLThread.onWindowResize(width, height); super.onSurfaceChanged(holder, format, width, height); } @Override public void onSurfaceCreated(SurfaceHolder holder) { Log.d(TAG, "onSurfaceCreated()"); mGLThread.surfaceCreated(holder); super.onSurfaceCreated(holder); } @Override public void onSurfaceDestroyed(SurfaceHolder holder) { Log.d(TAG, "onSurfaceDestroyed()"); mGLThread.surfaceDestroyed(); super.onSurfaceDestroyed(holder); } /** * An EGL helper class. */ public void setGLWrapper(GLWrapper glWrapper) { mGLWrapper = glWrapper; } public void setDebugFlags(int debugFlags) { mDebugFlags = debugFlags; } public int getDebugFlags() { return mDebugFlags; } public void setRenderer(Renderer renderer) { checkRenderThreadState(); if (mEGLConfigChooser == null) { mEGLConfigChooser = new SimpleEGLConfigChooser(true); } if (mEGLContextFactory == null) { mEGLContextFactory = new DefaultContextFactory(); } if (mEGLWindowSurfaceFactory == null) { mEGLWindowSurfaceFactory = new DefaultWindowSurfaceFactory(); } mGLThread = new GLThread(renderer, mEGLConfigChooser, mEGLContextFactory, mEGLWindowSurfaceFactory, mGLWrapper); mGLThread.start(); } public void setEGLContextFactory(EGLContextFactory factory) { checkRenderThreadState(); mEGLContextFactory = factory; } public void setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory factory) { checkRenderThreadState(); mEGLWindowSurfaceFactory = factory; } public void setEGLConfigChooser(EGLConfigChooser configChooser) { checkRenderThreadState(); mEGLConfigChooser = configChooser; } public void setEGLConfigChooser(boolean needDepth) { setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth)); } public void setEGLConfigChooser(int redSize, int greenSize, int blueSize, int alphaSize, int depthSize, int stencilSize) { setEGLConfigChooser(new ComponentSizeChooser(redSize, greenSize, blueSize, alphaSize, depthSize, stencilSize)); } public void setRenderMode(int renderMode) { mGLThread.setRenderMode(renderMode); } public int getRenderMode() { return mGLThread.getRenderMode(); } public void requestRender() { mGLThread.requestRender(); } public void onPause() { mGLThread.onPause(); } public void onResume() { mGLThread.onResume(); } public void queueEvent(Runnable r) { mGLThread.queueEvent(r); } private void checkRenderThreadState() { if (mGLThread != null) { throw new IllegalStateException("setRenderer has already been called for this instance."); } } } public interface Renderer { public void onSurfaceCreated(GL10 gl, EGLConfig config); public void onSurfaceChanged(GL10 gl, int width, int height); public void onDrawFrame(GL10 gl); } } class LogWriter extends Writer { private StringBuilder mBuilder = new StringBuilder(); @Override public void close() { flushBuilder(); } @Override public void flush() { flushBuilder(); } @Override public void write(char[] buf, int offset, int count) { for (int i = 0; i < count; i++) { char c = buf[offset + i]; if (c == '\n') { flushBuilder(); } else { mBuilder.append(c); } } } private void flushBuilder() { if (mBuilder.length() > 0) { Log.v("GLSurfaceView", mBuilder.toString()); mBuilder.delete(0, mBuilder.length()); } } } // ---------------------------------------------------------------------- /** * An interface for customizing the eglCreateContext and eglDestroyContext calls. * * This interface must be implemented by clients wishing to call * {@link GLWallpaperService#setEGLContextFactory(EGLContextFactory)} */ interface EGLContextFactory { EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig); void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context); } class DefaultContextFactory implements EGLContextFactory { public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig config) { return egl.eglCreateContext(display, config, EGL10.EGL_NO_CONTEXT, null); } public void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context) { egl.eglDestroyContext(display, context); } } /** * An interface for customizing the eglCreateWindowSurface and eglDestroySurface calls. * * This interface must be implemented by clients wishing to call * {@link GLWallpaperService#setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory)} */ interface EGLWindowSurfaceFactory { EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display, EGLConfig config, Object nativeWindow); void destroySurface(EGL10 egl, EGLDisplay display, EGLSurface surface); } class DefaultWindowSurfaceFactory implements EGLWindowSurfaceFactory { public EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display, EGLConfig config, Object nativeWindow) { // this is a bit of a hack to work around Droid init problems - if you don't have this, it'll get hung up on orientation changes EGLSurface eglSurface = null; while (eglSurface == null) { try { eglSurface = egl.eglCreateWindowSurface(display, config, nativeWindow, null); } catch (Throwable t) { } finally { if (eglSurface == null) { try { Thread.sleep(10); } catch (InterruptedException t) { } } } } return eglSurface; } public void destroySurface(EGL10 egl, EGLDisplay display, EGLSurface surface) { egl.eglDestroySurface(display, surface); } } interface GLWrapper { /** * Wraps a gl interface in another gl interface. * * @param gl * a GL interface that is to be wrapped. * @return either the input argument or another GL object that wraps the input argument. */ GL wrap(GL gl); } class EglHelper { private EGL10 mEgl; private EGLDisplay mEglDisplay; private EGLSurface mEglSurface; private EGLContext mEglContext; EGLConfig mEglConfig; private EGLConfigChooser mEGLConfigChooser; private EGLContextFactory mEGLContextFactory; private EGLWindowSurfaceFactory mEGLWindowSurfaceFactory; private GLWrapper mGLWrapper; public EglHelper(EGLConfigChooser chooser, EGLContextFactory contextFactory, EGLWindowSurfaceFactory surfaceFactory, GLWrapper wrapper) { this.mEGLConfigChooser = chooser; this.mEGLContextFactory = contextFactory; this.mEGLWindowSurfaceFactory = surfaceFactory; this.mGLWrapper = wrapper; } /** * Initialize EGL for a given configuration spec. * * @param configSpec */ public void start() { // Log.d("EglHelper" + instanceId, "start()"); if (mEgl == null) { // Log.d("EglHelper" + instanceId, "getting new EGL"); /* * Get an EGL instance */ mEgl = (EGL10) EGLContext.getEGL(); } else { // Log.d("EglHelper" + instanceId, "reusing EGL"); } if (mEglDisplay == null) { // Log.d("EglHelper" + instanceId, "getting new display"); /* * Get to the default display. */ mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); } else { // Log.d("EglHelper" + instanceId, "reusing display"); } if (mEglConfig == null) { // Log.d("EglHelper" + instanceId, "getting new config"); /* * We can now initialize EGL for that display */ int[] version = new int[2]; mEgl.eglInitialize(mEglDisplay, version); mEglConfig = mEGLConfigChooser.chooseConfig(mEgl, mEglDisplay); } else { // Log.d("EglHelper" + instanceId, "reusing config"); } if (mEglContext == null) { // Log.d("EglHelper" + instanceId, "creating new context"); /* * Create an OpenGL ES context. This must be done only once, an OpenGL context is a somewhat heavy object. */ mEglContext = mEGLContextFactory.createContext(mEgl, mEglDisplay, mEglConfig); if (mEglContext == null || mEglContext == EGL10.EGL_NO_CONTEXT) { throw new RuntimeException("createContext failed"); } } else { // Log.d("EglHelper" + instanceId, "reusing context"); } mEglSurface = null; } /* * React to the creation of a new surface by creating and returning an OpenGL interface that renders to that * surface. */ public GL createSurface(SurfaceHolder holder) { /* * The window size has changed, so we need to create a new surface. */ if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) { /* * Unbind and destroy the old EGL surface, if there is one. */ mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface); } /* * Create an EGL surface we can render into. */ mEglSurface = mEGLWindowSurfaceFactory.createWindowSurface(mEgl, mEglDisplay, mEglConfig, holder); if (mEglSurface == null || mEglSurface == EGL10.EGL_NO_SURFACE) { throw new RuntimeException("createWindowSurface failed"); } /* * Before we can issue GL commands, we need to make sure the context is current and bound to a surface. */ if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) { throw new RuntimeException("eglMakeCurrent failed."); } GL gl = mEglContext.getGL(); if (mGLWrapper != null) { gl = mGLWrapper.wrap(gl); } /* * if ((mDebugFlags & (DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS))!= 0) { int configFlags = 0; Writer log = * null; if ((mDebugFlags & DEBUG_CHECK_GL_ERROR) != 0) { configFlags |= GLDebugHelper.CONFIG_CHECK_GL_ERROR; } * if ((mDebugFlags & DEBUG_LOG_GL_CALLS) != 0) { log = new LogWriter(); } gl = GLDebugHelper.wrap(gl, * configFlags, log); } */ return gl; } /** * Display the current render surface. * * @return false if the context has been lost. */ public boolean swap() { mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); /* * Always check for EGL_CONTEXT_LOST, which means the context and all associated data were lost (For instance * because the device went to sleep). We need to sleep until we get a new surface. */ return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; } public void destroySurface() { if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) { mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface); mEglSurface = null; } } public void finish() { if (mEglContext != null) { mEGLContextFactory.destroyContext(mEgl, mEglDisplay, mEglContext); mEglContext = null; } if (mEglDisplay != null) { mEgl.eglTerminate(mEglDisplay); mEglDisplay = null; } } } class GLThread extends Thread { private final static boolean LOG_THREADS = false; public final static int DEBUG_CHECK_GL_ERROR = 1; public final static int DEBUG_LOG_GL_CALLS = 2; private final GLThreadManager sGLThreadManager = new GLThreadManager(); private GLThread mEglOwner; private EGLConfigChooser mEGLConfigChooser; private EGLContextFactory mEGLContextFactory; private EGLWindowSurfaceFactory mEGLWindowSurfaceFactory; private GLWrapper mGLWrapper; public SurfaceHolder mHolder; private boolean mSizeChanged = true; // Once the thread is started, all accesses to the following member // variables are protected by the sGLThreadManager monitor public boolean mDone; private boolean mPaused; private boolean mHasSurface; private boolean mWaitingForSurface; private boolean mHaveEgl; private int mWidth; private int mHeight; private int mRenderMode; private boolean mRequestRender; private boolean mEventsWaiting; // End of member variables protected by the sGLThreadManager monitor. private GLWallpaperService.Renderer mRenderer; private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>(); private EglHelper mEglHelper; GLThread(GLWallpaperService.Renderer renderer, EGLConfigChooser chooser, EGLContextFactory contextFactory, EGLWindowSurfaceFactory surfaceFactory, GLWrapper wrapper) { super(); mDone = false; mWidth = 0; mHeight = 0; mRequestRender = true; mRenderMode = GLWallpaperService.GLEngine.RENDERMODE_CONTINUOUSLY; mRenderer = renderer; this.mEGLConfigChooser = chooser; this.mEGLContextFactory = contextFactory; this.mEGLWindowSurfaceFactory = surfaceFactory; this.mGLWrapper = wrapper; } @Override public void run() { setName("GLThread " + getId()); if (LOG_THREADS) { Log.i("GLThread", "starting tid=" + getId()); } try { guardedRun(); } catch (InterruptedException e) { // fall thru and exit normally } finally { sGLThreadManager.threadExiting(this); } } /* * This private method should only be called inside a synchronized(sGLThreadManager) block. */ private void stopEglLocked() { if (mHaveEgl) { mHaveEgl = false; mEglHelper.destroySurface(); sGLThreadManager.releaseEglSurface(this); } } private void guardedRun() throws InterruptedException { mEglHelper = new EglHelper(mEGLConfigChooser, mEGLContextFactory, mEGLWindowSurfaceFactory, mGLWrapper); try { GL10 gl = null; boolean tellRendererSurfaceCreated = true; boolean tellRendererSurfaceChanged = true; /* * This is our main activity thread's loop, we go until asked to quit. */ while (!isDone()) { /* * Update the asynchronous state (window size) */ int w = 0; int h = 0; boolean changed = false; boolean needStart = false; boolean eventsWaiting = false; synchronized (sGLThreadManager) { while (true) { // Manage acquiring and releasing the SurfaceView // surface and the EGL surface. if (mPaused) { stopEglLocked(); } if (!mHasSurface) { if (!mWaitingForSurface) { stopEglLocked(); mWaitingForSurface = true; sGLThreadManager.notifyAll(); } } else { if (!mHaveEgl) { if (sGLThreadManager.tryAcquireEglSurface(this)) { mHaveEgl = true; mEglHelper.start(); mRequestRender = true; needStart = true; } } } // Check if we need to wait. If not, update any state // that needs to be updated, copy any state that // needs to be copied, and use "break" to exit the // wait loop. if (mDone) { return; } if (mEventsWaiting) { eventsWaiting = true; mEventsWaiting = false; break; } if ((!mPaused) && mHasSurface && mHaveEgl && (mWidth > 0) && (mHeight > 0) && (mRequestRender || (mRenderMode == GLWallpaperService.GLEngine.RENDERMODE_CONTINUOUSLY))) { changed = mSizeChanged; w = mWidth; h = mHeight; mSizeChanged = false; mRequestRender = false; if (mHasSurface && mWaitingForSurface) { changed = true; mWaitingForSurface = false; sGLThreadManager.notifyAll(); } break; } // By design, this is the only place where we wait(). if (LOG_THREADS) { Log.i("GLThread", "waiting tid=" + getId()); } sGLThreadManager.wait(); } } // end of synchronized(sGLThreadManager) /* * Handle queued events */ if (eventsWaiting) { Runnable r; while ((r = getEvent()) != null) { r.run(); if (isDone()) { return; } } // Go back and see if we need to wait to render. continue; } if (needStart) { tellRendererSurfaceCreated = true; changed = true; } if (changed) { gl = (GL10) mEglHelper.createSurface(mHolder); tellRendererSurfaceChanged = true; } if (tellRendererSurfaceCreated) { mRenderer.onSurfaceCreated(gl, mEglHelper.mEglConfig); tellRendererSurfaceCreated = false; } if (tellRendererSurfaceChanged) { mRenderer.onSurfaceChanged(gl, w, h); tellRendererSurfaceChanged = false; } if ((w > 0) && (h > 0)) { /* draw a frame here */ mRenderer.onDrawFrame(gl); /* * Once we're done with GL, we need to call swapBuffers() to instruct the system to display the * rendered frame */ mEglHelper.swap(); + Thread.sleep(10); } } } finally { /* * clean-up everything... */ synchronized (sGLThreadManager) { stopEglLocked(); mEglHelper.finish(); } } } private boolean isDone() { synchronized (sGLThreadManager) { return mDone; } } public void setRenderMode(int renderMode) { if (!((GLWallpaperService.GLEngine.RENDERMODE_WHEN_DIRTY <= renderMode) && (renderMode <= GLWallpaperService.GLEngine.RENDERMODE_CONTINUOUSLY))) { throw new IllegalArgumentException("renderMode"); } synchronized (sGLThreadManager) { mRenderMode = renderMode; if (renderMode == GLWallpaperService.GLEngine.RENDERMODE_CONTINUOUSLY) { sGLThreadManager.notifyAll(); } } } public int getRenderMode() { synchronized (sGLThreadManager) { return mRenderMode; } } public void requestRender() { synchronized (sGLThreadManager) { mRequestRender = true; sGLThreadManager.notifyAll(); } } public void surfaceCreated(SurfaceHolder holder) { mHolder = holder; synchronized (sGLThreadManager) { if (LOG_THREADS) { Log.i("GLThread", "surfaceCreated tid=" + getId()); } mHasSurface = true; sGLThreadManager.notifyAll(); } } public void surfaceDestroyed() { synchronized (sGLThreadManager) { if (LOG_THREADS) { Log.i("GLThread", "surfaceDestroyed tid=" + getId()); } mHasSurface = false; sGLThreadManager.notifyAll(); while (!mWaitingForSurface && isAlive() && !mDone) { try { sGLThreadManager.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } } public void onPause() { synchronized (sGLThreadManager) { mPaused = true; sGLThreadManager.notifyAll(); } } public void onResume() { synchronized (sGLThreadManager) { mPaused = false; mRequestRender = true; sGLThreadManager.notifyAll(); } } public void onWindowResize(int w, int h) { synchronized (sGLThreadManager) { mWidth = w; mHeight = h; mSizeChanged = true; sGLThreadManager.notifyAll(); } } public void requestExitAndWait() { // don't call this from GLThread thread or it is a guaranteed // deadlock! synchronized (sGLThreadManager) { mDone = true; sGLThreadManager.notifyAll(); } try { join(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } /** * Queue an "event" to be run on the GL rendering thread. * * @param r * the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { synchronized (this) { mEventQueue.add(r); synchronized (sGLThreadManager) { mEventsWaiting = true; sGLThreadManager.notifyAll(); } } } private Runnable getEvent() { synchronized (this) { if (mEventQueue.size() > 0) { return mEventQueue.remove(0); } } return null; } private class GLThreadManager { public synchronized void threadExiting(GLThread thread) { if (LOG_THREADS) { Log.i("GLThread", "exiting tid=" + thread.getId()); } thread.mDone = true; if (mEglOwner == thread) { mEglOwner = null; } notifyAll(); } /* * Tries once to acquire the right to use an EGL surface. Does not block. * * @return true if the right to use an EGL surface was acquired. */ public synchronized boolean tryAcquireEglSurface(GLThread thread) { if (mEglOwner == thread || mEglOwner == null) { mEglOwner = thread; notifyAll(); return true; } return false; } public synchronized void releaseEglSurface(GLThread thread) { if (mEglOwner == thread) { mEglOwner = null; } notifyAll(); } } } interface EGLConfigChooser { EGLConfig chooseConfig(EGL10 egl, EGLDisplay display); } abstract class BaseConfigChooser implements EGLConfigChooser { public BaseConfigChooser(int[] configSpec) { mConfigSpec = configSpec; } public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) { int[] num_config = new int[1]; egl.eglChooseConfig(display, mConfigSpec, null, 0, num_config); int numConfigs = num_config[0]; if (numConfigs <= 0) { throw new IllegalArgumentException("No configs match configSpec"); } EGLConfig[] configs = new EGLConfig[numConfigs]; egl.eglChooseConfig(display, mConfigSpec, configs, numConfigs, num_config); EGLConfig config = chooseConfig(egl, display, configs); if (config == null) { throw new IllegalArgumentException("No config chosen"); } return config; } abstract EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, EGLConfig[] configs); protected int[] mConfigSpec; public static class ComponentSizeChooser extends BaseConfigChooser { public ComponentSizeChooser(int redSize, int greenSize, int blueSize, int alphaSize, int depthSize, int stencilSize) { super(new int[] { EGL10.EGL_RED_SIZE, redSize, EGL10.EGL_GREEN_SIZE, greenSize, EGL10.EGL_BLUE_SIZE, blueSize, EGL10.EGL_ALPHA_SIZE, alphaSize, EGL10.EGL_DEPTH_SIZE, depthSize, EGL10.EGL_STENCIL_SIZE, stencilSize, EGL10.EGL_NONE }); mValue = new int[1]; mRedSize = redSize; mGreenSize = greenSize; mBlueSize = blueSize; mAlphaSize = alphaSize; mDepthSize = depthSize; mStencilSize = stencilSize; } @Override public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, EGLConfig[] configs) { EGLConfig closestConfig = null; int closestDistance = 1000; for (EGLConfig config : configs) { int d = findConfigAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0); int s = findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0); if (d >= mDepthSize && s >= mStencilSize) { int r = findConfigAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0); int g = findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0); int b = findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0); int a = findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0); int distance = Math.abs(r - mRedSize) + Math.abs(g - mGreenSize) + Math.abs(b - mBlueSize) + Math.abs(a - mAlphaSize); if (distance < closestDistance) { closestDistance = distance; closestConfig = config; } } } return closestConfig; } private int findConfigAttrib(EGL10 egl, EGLDisplay display, EGLConfig config, int attribute, int defaultValue) { if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) { return mValue[0]; } return defaultValue; } private int[] mValue; // Subclasses can adjust these values: protected int mRedSize; protected int mGreenSize; protected int mBlueSize; protected int mAlphaSize; protected int mDepthSize; protected int mStencilSize; } /** * This class will choose a supported surface as close to RGB565 as possible, with or without a depth buffer. * */ public static class SimpleEGLConfigChooser extends ComponentSizeChooser { public SimpleEGLConfigChooser(boolean withDepthBuffer) { super(4, 4, 4, 0, withDepthBuffer ? 16 : 0, 0); // Adjust target values. This way we'll accept a 4444 or // 555 buffer if there's no 565 buffer available. mRedSize = 5; mGreenSize = 6; mBlueSize = 5; } } } \ No newline at end of file
true
false
null
null
diff --git a/src/de/cloudarts/aibattleai/AIContainer.java b/src/de/cloudarts/aibattleai/AIContainer.java index 8982b3b..7e4d04a 100644 --- a/src/de/cloudarts/aibattleai/AIContainer.java +++ b/src/de/cloudarts/aibattleai/AIContainer.java @@ -1,203 +1,203 @@ package de.cloudarts.aibattleai; import java.io.IOException; import java.net.URL; import java.util.Random; import java.util.Scanner; public class AIContainer { private static final long SLEEP_MILLIS = 200; private String _playerName = "Wojtek"; private int _matchID = 0; private String _token = ""; public AIContainer(String playerName_) { if( !playerName_.isEmpty() ) { _playerName = playerName_; } } public void start() { if( !requestNewMatch() ) { return; } // actual game loop while(true) { //get game status String lastGameStatusAnswerString = requestMatchStatus(); if( isErrorAnswer(lastGameStatusAnswerString) ) { return; } if( isDrawGame(lastGameStatusAnswerString) ) { return; } if( !isItMyTurn(lastGameStatusAnswerString) ) { //wait a sec, then try again try { Thread.sleep(SLEEP_MILLIS); } catch (InterruptedException e) { e.printStackTrace(); } continue; } //so it's my turn // get game status // compute next action String[] letters = {"a", "b", "c", "d", "e", "f", "g"}; Random generator = new Random(); int actionIndex = generator.nextInt(7); String action = letters[actionIndex]; // send next action System.out.println("sending action: " + action); - System.out.println(postAction(action)); + postAction(action); // continue in loop } } private Boolean requestNewMatch() { URL u = URLCreator.getRequestMatchURL(_playerName); if (u == null ) { System.err.println("Error! could not create request url!"); return false; } String r = ""; try { r = new Scanner( u.openStream() ).useDelimiter( "\\Z" ).next(); } catch (IOException e) { e.printStackTrace(); return false; } System.out.println( "requestNewMatch: received answer:" + r ); if( isErrorAnswer(r) ) { return false; } // split answer string in matchID and secret token String[] temp = r.split(";"); if( temp.length != 2 ) { System.err.println("requestNewMatch: did expect 2 answer items, but received " + temp.length); return false; } _matchID = Integer.valueOf(temp[0]); _token = temp[1]; System.out.println("requestNewMatch: received new matchID " + _matchID + " and token " + _token); return true; } private String requestMatchStatus() { URL u = URLCreator.getRequestMatchStatusURL(_matchID); if( u == null ) { return "error"; } String r = ""; try { r = new Scanner( u.openStream() ).useDelimiter( "\\Z" ).next(); } catch (IOException e) { e.printStackTrace(); return "error"; } System.out.println( "requestMatchStatus: received answer:" + r ); return r; } private String postAction(String action_) { URL u = URLCreator.getPostActionURL(_matchID, _playerName, _token, action_); if( u == null ) { return "error"; } String r = ""; try { r = new Scanner( u.openStream() ).useDelimiter( "\\Z" ).next(); } catch (IOException e) { e.printStackTrace(); return "error"; } System.out.println( "postAction: received answer:" + r ); return r; } private Boolean isItMyTurn(String rawStatusString_) { String currentTurnPlayer = rawStatusString_.substring(0, _playerName.length()); if( currentTurnPlayer.equals(_playerName) ) { return true; } return false; } private Boolean isErrorAnswer(String answer_) { if( answer_.substring(0, "error".length()).equals("error") ) { return true; } return false; } private boolean isDrawGame(String answer_) { if( answer_.substring(0, "draw game".length()).equals("draw game") ) { return true; } return false; } }
true
true
public void start() { if( !requestNewMatch() ) { return; } // actual game loop while(true) { //get game status String lastGameStatusAnswerString = requestMatchStatus(); if( isErrorAnswer(lastGameStatusAnswerString) ) { return; } if( isDrawGame(lastGameStatusAnswerString) ) { return; } if( !isItMyTurn(lastGameStatusAnswerString) ) { //wait a sec, then try again try { Thread.sleep(SLEEP_MILLIS); } catch (InterruptedException e) { e.printStackTrace(); } continue; } //so it's my turn // get game status // compute next action String[] letters = {"a", "b", "c", "d", "e", "f", "g"}; Random generator = new Random(); int actionIndex = generator.nextInt(7); String action = letters[actionIndex]; // send next action System.out.println("sending action: " + action); System.out.println(postAction(action)); // continue in loop } }
public void start() { if( !requestNewMatch() ) { return; } // actual game loop while(true) { //get game status String lastGameStatusAnswerString = requestMatchStatus(); if( isErrorAnswer(lastGameStatusAnswerString) ) { return; } if( isDrawGame(lastGameStatusAnswerString) ) { return; } if( !isItMyTurn(lastGameStatusAnswerString) ) { //wait a sec, then try again try { Thread.sleep(SLEEP_MILLIS); } catch (InterruptedException e) { e.printStackTrace(); } continue; } //so it's my turn // get game status // compute next action String[] letters = {"a", "b", "c", "d", "e", "f", "g"}; Random generator = new Random(); int actionIndex = generator.nextInt(7); String action = letters[actionIndex]; // send next action System.out.println("sending action: " + action); postAction(action); // continue in loop } }
diff --git a/src/main/java/com/fasterxml/jackson/databind/deser/std/DelegatingDeserializer.java b/src/main/java/com/fasterxml/jackson/databind/deser/std/DelegatingDeserializer.java index 072370982..59ec3213d 100644 --- a/src/main/java/com/fasterxml/jackson/databind/deser/std/DelegatingDeserializer.java +++ b/src/main/java/com/fasterxml/jackson/databind/deser/std/DelegatingDeserializer.java @@ -1,160 +1,160 @@ package com.fasterxml.jackson.databind.deser.std; import java.io.IOException; import java.util.Collection; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.deser.*; import com.fasterxml.jackson.databind.deser.impl.ObjectIdReader; import com.fasterxml.jackson.databind.jsontype.TypeDeserializer; /** * Base class that simplifies implementations of {@link JsonDeserializer}s * that mostly delegate functionality to another deserializer implementation * (possibly forming a chaing of deserializers delegating functionality * in some cases) * * @since 2.1 */ public abstract class DelegatingDeserializer extends StdDeserializer<Object> implements ContextualDeserializer, ResolvableDeserializer { private static final long serialVersionUID = 1L; protected final JsonDeserializer<?> _delegatee; /* /********************************************************************** /* Construction /********************************************************************** */ public DelegatingDeserializer(JsonDeserializer<?> delegatee) { super(_figureType(delegatee)); _delegatee = delegatee; } protected abstract JsonDeserializer<?> newDelegatingInstance(JsonDeserializer<?> newDelegatee); private static Class<?> _figureType(JsonDeserializer<?> deser) { Class<?> cls = deser.handledType(); if (cls != null) { return cls; } return Object.class; } /* /********************************************************************** /* Overridden methods for contextualization, resolving /********************************************************************** */ @Override public void resolve(DeserializationContext ctxt) throws JsonMappingException { if (_delegatee instanceof ResolvableDeserializer) { ((ResolvableDeserializer) _delegatee).resolve(ctxt); } } @Override public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException { JsonDeserializer<?> del = ctxt.handleSecondaryContextualization(_delegatee, property); if (del == _delegatee) { return this; } return newDelegatingInstance(del); } /** * @deprecated Since 2.3, use {@link #newDelegatingInstance} instead */ @Deprecated protected JsonDeserializer<?> _createContextual(DeserializationContext ctxt, BeanProperty property, JsonDeserializer<?> newDelegatee) { if (newDelegatee == _delegatee) { return this; } return newDelegatingInstance(newDelegatee); } @Override public SettableBeanProperty findBackReference(String logicalName) { // [Issue#253]: Hope this works.... return _delegatee.findBackReference(logicalName); } /* /********************************************************************** /* Overridden deserialization methods /********************************************************************** */ @Override public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { return _delegatee.deserialize(jp, ctxt); } @SuppressWarnings("unchecked") @Override public Object deserialize(JsonParser jp, DeserializationContext ctxt, Object intoValue) throws IOException, JsonProcessingException { return ((JsonDeserializer<Object>)_delegatee).deserialize(jp, ctxt, intoValue); } @Override public Object deserializeWithType(JsonParser jp, DeserializationContext ctxt, TypeDeserializer typeDeserializer) throws IOException, JsonProcessingException { return _delegatee.deserializeWithType(jp, ctxt, typeDeserializer); } /* /********************************************************************** /* Overridden other methods /********************************************************************** */ @Override public JsonDeserializer<?> replaceDelegatee(JsonDeserializer<?> delegatee) { if (delegatee == _delegatee) { return this; } return newDelegatingInstance(delegatee); } @Override public Object getNullValue() { return _delegatee.getNullValue(); } @Override public Object getEmptyValue() { return _delegatee.getEmptyValue(); } @Override public Collection<Object> getKnownPropertyNames() { return _delegatee.getKnownPropertyNames(); } @Override - public boolean isCachable() { return false; } + public boolean isCachable() { return _delegatee.isCachable(); } @Override public ObjectIdReader getObjectIdReader() { return _delegatee.getObjectIdReader(); } @Override public JsonDeserializer<?> getDelegatee() { return _delegatee; } }
true
false
null
null
diff --git a/geogebra/geogebra/gui/app/MyFileFilter.java b/geogebra/geogebra/gui/app/MyFileFilter.java index 9379626de..65e72a6ba 100644 --- a/geogebra/geogebra/gui/app/MyFileFilter.java +++ b/geogebra/geogebra/gui/app/MyFileFilter.java @@ -1,267 +1,270 @@ /* GeoGebra - Dynamic Mathematics for Everyone http://www.geogebra.org This file is part of GeoGebra. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation. */ package geogebra.gui.app; import java.io.File; import java.util.Enumeration; import java.util.Hashtable; import java.util.Locale; import javax.swing.filechooser.FileFilter; /** * A convenience implementation of FileFilter that filters out * all files except for those type extensions that it knows about. * * Extensions are of the type ".foo", which is typically found on * Windows and Unix boxes, but not on Macinthosh. Case is ignored. * * Example - create a new filter that filerts out all files * but gif and jpg image files: * * JFileChooser chooser = new JFileChooser(); * MyFileFilter filter = new MyFileFilter( * new String{"gif", "jpg"}, "JPEG & GIF Images") * chooser.addChoosableFileFilter(filter); * chooser.showOpenDialog(this); * */ public class MyFileFilter extends FileFilter { // private static String TYPE_UNKNOWN = "Type Unknown"; // private static String HIDDEN_FILE = "Hidden File"; private Hashtable filters = null; private String description = null; private String fullDescription = null; private boolean useExtensionsInDescription = true; /** * Creates a file filter. If no filters are added, then all * files are accepted. * * @see #addExtension */ public MyFileFilter() { filters = new Hashtable(); } /** * Creates a file filter that accepts files with the given extension. * Example: new MyFileFilter("jpg"); * * @see #addExtension */ public MyFileFilter(String extension) { this(extension,null); } /** * Creates a file filter that accepts the given file type. * Example: new MyFileFilter("jpg", "JPEG Image Images"); * * Note that the "." before the extension is not needed. If * provided, it will be ignored. * * @see #addExtension */ public MyFileFilter(String extension, String description) { this(); if(extension!=null) addExtension(extension); if(description!=null) setDescription(description); } /** * Creates a file filter from the given string array. * Example: new MyFileFilter(String {"gif", "jpg"}); * * Note that the "." before the extension is not needed adn * will be ignored. * * @see #addExtension */ public MyFileFilter(String[] filters) { this(filters, null); } /** * Creates a file filter from the given string array and description. * Example: new MyFileFilter(String {"gif", "jpg"}, "Gif and JPG Images"); * * Note that the "." before the extension is not needed and will be ignored. * * @see #addExtension */ public MyFileFilter(String[] filters, String description) { this(); for (int i = 0; i < filters.length; i++) { // add filters one by one addExtension(filters[i]); } if(description!=null) setDescription(description); } /** * Return true if this file should be shown in the directory pane, * false if it shouldn't. * * Files that begin with "." are ignored. * * @see #getExtension * @see FileFilter#accepts */ public boolean accept(File f) { if(f != null) { if(f.isDirectory()) return true; String extension = getExtension(f); if(extension != null && filters.get(getExtension(f)) != null) return true;; } return false; } /** * Return the extension portion of the file's name . * * @see #getExtension * @see FileFilter#accept */ public String getExtension(File f) { if(f != null) { String filename = f.getName(); int i = filename.lastIndexOf('.'); if(i>0 && i<filename.length()-1) // Modified for Intergeo File Format (Yves Kreis) --> // return filename.substring(i+1).toLowerCase(Locale.US);; return filename.substring(i+1).toLowerCase(Locale.US); // <-- Modified for Intergeo File Format (Yves Kreis) } return null; } /** * Adds a filetype "dot" extension to filter against. * * For example: the following code will create a filter that filters * out all files except those that end in ".jpg" and ".tif": * * MyFileFilter filter = new MyFileFilter(); * filter.addExtension("jpg"); * filter.addExtension("tif"); * * Note that the "." before the extension is not needed and will be ignored. */ public void addExtension(String extension) { if(filters == null) { filters = new Hashtable(5); } // Added for Intergeo File Format (Yves Kreis) --> if (extension.indexOf(".") > -1) { extension = extension.substring(0, extension.lastIndexOf(".")); } // <-- Added for Intergeo File Format (Yves Kreis) filters.put(extension.toLowerCase(Locale.US), this); fullDescription = null; } + public String toString() { + return getDescription(); + } /** * Returns the human readable description of this filter. For * example: "JPEG and GIF Image Files (*.jpg, *.gif)" * * @see setDescription * @see setExtensionListInDescription * @see isExtensionListInDescription * @see FileFilter#getDescription */ public String getDescription() { if(fullDescription == null) { if(description == null || isExtensionListInDescription()) { fullDescription = description==null ? "(" : description + " ("; // build the description from the extension list Enumeration extensions = filters.keys(); if(extensions != null) { fullDescription += "." + (String) extensions.nextElement(); while (extensions.hasMoreElements()) { fullDescription += ", ." + (String) extensions.nextElement(); } } fullDescription += ")"; } else { fullDescription = description; } } return fullDescription; } /** * Sets the human readable description of this filter. For * example: filter.setDescription("Gif and JPG Images"); * * @see setDescription * @see setExtensionListInDescription * @see isExtensionListInDescription */ public void setDescription(String description) { this.description = description; fullDescription = null; } /** * Determines whether the extension list (.jpg, .gif, etc) should * show up in the human readable description. * * Only relevent if a description was provided in the constructor * or using setDescription(); * * @see getDescription * @see setDescription * @see isExtensionListInDescription */ public void setExtensionListInDescription(boolean b) { useExtensionsInDescription = b; fullDescription = null; } /** * Returns whether the extension list (.jpg, .gif, etc) should * show up in the human readable description. * * Only relevent if a description was provided in the constructor * or using setDescription(); * * @see getDescription * @see setDescription * @see setExtensionListInDescription */ public boolean isExtensionListInDescription() { return useExtensionsInDescription; } /** * Returns the first extension contained in the extension list. * * Added for Intergeo File Format (Yves Kreis) */ public String getExtension() { Enumeration keys = filters.keys(); if (keys.hasMoreElements()) { return (String) keys.nextElement(); } else { return ""; } } }
true
false
null
null
diff --git a/ini/trakem2/display/Display.java b/ini/trakem2/display/Display.java index 6a01258e..35172566 100644 --- a/ini/trakem2/display/Display.java +++ b/ini/trakem2/display/Display.java @@ -1,5779 +1,5779 @@ /** TrakEM2 plugin for ImageJ(C). Copyright (C) 2005-2009 Albert Cardona and Rodney Douglas. 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 (http://www.gnu.org/licenses/gpl.txt ) 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. You may contact Albert Cardona at acardona at ini.phys.ethz.ch Institute of Neuroinformatics, University of Zurich / ETH, Switzerland. **/ package ini.trakem2.display; import ij.*; import ij.gui.*; import ij.io.OpenDialog; import ij.io.DirectoryChooser; import ij.measure.Calibration; import ini.trakem2.Project; import ini.trakem2.ControlWindow; import ini.trakem2.parallel.Process; import ini.trakem2.parallel.TaskFactory; import ini.trakem2.persistence.DBObject; import ini.trakem2.persistence.Loader; import ini.trakem2.utils.IJError; import ini.trakem2.imaging.LayerStack; import ini.trakem2.imaging.PatchStack; import ini.trakem2.imaging.Blending; import ini.trakem2.imaging.Segmentation; import ini.trakem2.utils.ProjectToolbar; import ini.trakem2.utils.Utils; import ini.trakem2.utils.DNDInsertImage; import ini.trakem2.utils.Search; import ini.trakem2.utils.Bureaucrat; import ini.trakem2.utils.Worker; import ini.trakem2.utils.Dispatcher; import ini.trakem2.utils.Lock; import ini.trakem2.utils.M; import ini.trakem2.utils.OptionPanel; import ini.trakem2.tree.*; import ini.trakem2.imaging.StitchingTEM; import javax.swing.*; import javax.swing.text.Document; import javax.swing.event.*; import mpicbg.trakem2.align.AlignLayersTask; import mpicbg.trakem2.align.AlignTask; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.Line2D; import java.awt.image.BufferedImage; import java.awt.event.*; import java.util.*; import java.util.List; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.io.Writer; import java.io.File; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.Callable; import lenscorrection.DistortionCorrectionTask; import mpicbg.models.PointMatch; import mpicbg.trakem2.transform.AffineModel3D; /** A Display is a class to show a Layer and enable mouse and keyboard manipulation of all its components. */ public final class Display extends DBObject implements ActionListener, IJEventListener { /** The Layer this Display is showing. */ private Layer layer; private Displayable active = null; /** All selected Displayable objects, including the active one. */ final private Selection selection = new Selection(this); private JFrame frame; private JTabbedPane tabs; private Hashtable<Class,JScrollPane> ht_tabs; private JScrollPane scroll_patches; private JPanel panel_patches; private JScrollPane scroll_profiles; private JPanel panel_profiles; private JScrollPane scroll_zdispl; private JPanel panel_zdispl; private JScrollPane scroll_channels; private JPanel panel_channels; private JScrollPane scroll_labels; private JPanel panel_labels; private JPanel panel_layers; private JScrollPane scroll_layers; private Hashtable<Layer,LayerPanel> layer_panels = new Hashtable<Layer,LayerPanel>(); private OptionPanel tool_options; private JScrollPane scroll_options; static protected int scrollbar_width = 0; private JEditorPane annot_editor; private JLabel annot_label; private JPanel annot_panel; static private HashMap<Displayable,Document> annot_docs = new HashMap<Displayable,Document>(); private JSlider transp_slider; private DisplayNavigator navigator; private JScrollBar scroller; private DisplayCanvas canvas; // WARNING this is an AWT component, since it extends ImageCanvas private JPanel canvas_panel; // and this is a workaround, to better (perhaps) integrate the awt canvas inside a JSplitPane private JSplitPane split; private JPopupMenu popup = null; private ToolbarPanel toolbar_panel = null; /** Contains the packed alphas of every channel. */ private int c_alphas = 0xffffffff; // all 100 % visible private Channel[] channels; private Hashtable<Displayable,DisplayablePanel> ht_panels = new Hashtable<Displayable,DisplayablePanel>(); /** Handle drop events, to insert image files. */ private DNDInsertImage dnd; private boolean size_adjusted = false; private int scroll_step = 1; static private final Object DISPLAY_LOCK = new Object(); /** Keep track of all existing Display objects. */ static private Set<Display> al_displays = new HashSet<Display>(); /** The currently focused Display, if any. */ static private Display front = null; /** Displays to open when all objects have been reloaded from the database. */ static private final Hashtable<Display,Object[]> ht_later = new Hashtable<Display,Object[]>(); /** A thread to handle user actions, for example an event sent from a popup menu. */ protected final Dispatcher dispatcher = new Dispatcher("Display GUI Updater"); static private WindowAdapter window_listener = new WindowAdapter() { /** Unregister the closed Display. */ public void windowClosing(WindowEvent we) { final Object source = we.getSource(); for (final Display d : al_displays) { if (source == d.frame) { d.remove(false); // calls destroy, which calls removeDisplay break; } } } /** Set the source Display as front. */ public void windowActivated(WindowEvent we) { // find which was it to make it be the front ImageJ ij = IJ.getInstance(); if (null != ij && ij.quitting()) return; final Object source = we.getSource(); for (final Display d : al_displays) { if (source == d.frame) { front = d; // set toolbar ProjectToolbar.setProjectToolbar(); // now, select the layer in the LayerTree front.getProject().select(front.layer); // finally, set the virtual ImagePlus that ImageJ will see d.setTempCurrentImage(); // copied from ij.gui.ImageWindow, with modifications if (IJ.isMacintosh() && IJ.getInstance()!=null) { IJ.wait(10); // may be needed for Java 1.4 on OS X d.frame.setMenuBar(Menus.getMenuBar()); } return; } } // else, restore the ImageJ toolbar for non-project images //if (!source.equals(IJ.getInstance())) { // ProjectToolbar.setImageJToolbar(); //} } /** Restore the ImageJ toolbar */ public void windowDeactivated(WindowEvent we) { // Can't, the user can never click the ProjectToolbar then. This has to be done in a different way, for example checking who is the WindowManager.getCurrentImage (and maybe setting a dummy image into it) //ProjectToolbar.setImageJToolbar(); } /** Call a pack() when the window is maximized to fit the canvas correctly. */ public void windowStateChanged(WindowEvent we) { final Object source = we.getSource(); for (final Display d : al_displays) { if (source != d.frame) continue; d.pack(); break; } } }; static public final Vector<Display> getDisplays() { return new Vector<Display>(al_displays); } static public final int getDisplayCount() { return al_displays.size(); } static private MouseListener frame_mouse_listener = new MouseAdapter() { public void mouseReleased(MouseEvent me) { Object source = me.getSource(); for (final Display d : al_displays) { if (d.frame == source) { if (d.size_adjusted) { d.pack(); d.size_adjusted = false; Utils.log2("mouse released on JFrame"); } break; } } } }; private int last_frame_state = Frame.NORMAL; // THIS WHOLE SYSTEM OF LISTENERS IS BROKEN: // * when zooming in, the window growths in width a few pixels. // * when enlarging the window quickly, the canvas is not resized as large as it should. // -- the whole problem: swing threading, which I am not handling properly. It's hard. static private ComponentListener component_listener = new ComponentAdapter() { public void componentResized(ComponentEvent ce) { final Display d = getDisplaySource(ce); if (null != d) { d.size_adjusted = true; // works in combination with mouseReleased to call pack(), avoiding infinite loops. d.adjustCanvas(); d.navigator.repaint(false); // upate srcRect red frame position/size int frame_state = d.frame.getExtendedState(); if (frame_state != d.last_frame_state) { // this setup avoids infinite loops (for pack() calls componentResized as well d.last_frame_state = frame_state; if (Frame.ICONIFIED != frame_state) d.pack(); } } } public void componentMoved(ComponentEvent ce) { Display d = getDisplaySource(ce); if (null != d) d.updateInDatabase("position"); } private Display getDisplaySource(ComponentEvent ce) { final Object source = ce.getSource(); for (final Display d : al_displays) { if (source == d.frame) { return d; } } return null; } }; static private ChangeListener tabs_listener = new ChangeListener() { /** Listen to tab changes. */ public void stateChanged(final ChangeEvent ce) { final Object source = ce.getSource(); for (final Display d : al_displays) { if (source == d.tabs) { d.dispatcher.exec(new Runnable() { public void run() { // creating tabs fires the event!!! if (null == d.frame || null == d.canvas) return; final Container tab = (Container)d.tabs.getSelectedComponent(); if (tab == d.scroll_channels) { // find active channel if any for (int i=0; i<d.channels.length; i++) { if (d.channels[i].isActive()) { d.transp_slider.setValue((int)(d.channels[i].getAlpha() * 100)); break; } } } else { // recreate contents /* int count = tab.getComponentCount(); if (0 == count || (1 == count && tab.getComponent(0).getClass().equals(JLabel.class))) { */ // ALWAYS, because it could be the case that the user changes layer while on one specific tab, and then clicks on the other tab which may not be empty and shows totally the wrong contents (i.e. for another layer) ArrayList<?extends Displayable> al = null; JPanel p = null; if (tab == d.scroll_zdispl) { al = d.layer.getParent().getZDisplayables(); p = d.panel_zdispl; } else if (tab == d.scroll_patches) { al = d.layer.getDisplayables(Patch.class); p = d.panel_patches; } else if (tab == d.scroll_labels) { al = d.layer.getDisplayables(DLabel.class); p = d.panel_labels; } else if (tab == d.scroll_profiles) { al = d.layer.getDisplayables(Profile.class); p = d.panel_profiles; } else if (tab == d.scroll_layers) { // nothing to do return; } else if (tab == d.scroll_options) { // Choose according to tool d.updateToolTab(); return; } d.updateTab(p, al); //Utils.updateComponent(d.tabs.getSelectedComponent()); //Utils.log2("updated tab: " + p + " with " + al.size() + " objects."); //} if (null != d.active) { // set the transp slider to the alpha value of the active Displayable if any d.transp_slider.setValue((int)(d.active.getAlpha() * 100)); DisplayablePanel dp = d.ht_panels.get(d.active); if (null != dp) dp.setActive(true); } } }}); break; } } } }; private final ScrollLayerListener scroller_listener = new ScrollLayerListener(); private class ScrollLayerListener implements AdjustmentListener { public void adjustmentValueChanged(final AdjustmentEvent ae) { final int index = scroller.getValue(); slt.set(layer.getParent().getLayer(index)); } } private final SetLayerThread slt = new SetLayerThread(); private class SetLayerThread extends Thread { private volatile Layer layer; private final Lock lock = new Lock(); SetLayerThread() { super("SetLayerThread"); setPriority(Thread.NORM_PRIORITY); setDaemon(true); start(); } public final void set(final Layer layer) { synchronized (lock) { this.layer = layer; } synchronized (this) { notify(); } } // Does not use the thread, rather just sets it within the context of the calling thread (would be the same as making the caller thread wait.) final void setAndWait(final Layer layer) { if (null != layer) { Display.this.setLayer(layer); Display.this.updateInDatabase("layer_id"); createColumnScreenshots(); } } public void run() { while (!isInterrupted()) { while (null == this.layer) { synchronized (this) { try { wait(); } catch (InterruptedException ie) {} } } Layer layer = null; synchronized (lock) { layer = this.layer; this.layer = null; } // if (isInterrupted()) return; // after nullifying layer // setAndWait(layer); } } public void quit() { interrupt(); synchronized (this) { notify(); } } } static final public void clearColumnScreenshots(final LayerSet ls) { for (final Display d : al_displays) { if (d.layer.getParent() == ls) d.clearColumnScreenshots(); } } final public void clearColumnScreenshots() { getLayerSet().clearScreenshots(); } /** Only for DefaultMode. */ final private void createColumnScreenshots() { final int n; try { if (mode.getClass() == DefaultMode.class) { int ahead = project.getProperty("look_ahead_cache", 0); if (ahead < 0) ahead = 0; if (0 == ahead) return; n = ahead; } else return; } catch (Exception e) { IJError.print(e); return; } project.getLoader().doLater(new Callable<Object>() { public Object call() { final Layer current = Display.this.layer; // 1 - Create DisplayCanvas.Screenshot instances for the next 5 and previous 5 layers final ArrayList<DisplayCanvas.Screenshot> s = new ArrayList<DisplayCanvas.Screenshot>(); Layer now = current; Layer prev = now.getParent().previous(now); int i = 0; Layer next = now.getParent().next(now); while (now != next && i < n) { s.add(canvas.createScreenshot(next)); now = next; next = now.getParent().next(now); i++; } now = current; i = 0; while (now != prev && i < n) { s.add(0, canvas.createScreenshot(prev)); now = prev; prev = now.getParent().previous(now); i++; } // Store them all into the LayerSet offscreens hashmap, but trigger image creation in parallel threads. for (final DisplayCanvas.Screenshot sc : s) { if (!current.getParent().containsScreenshot(sc)) { sc.init(); current.getParent().storeScreenshot(sc); project.getLoader().doLater(new Callable<Object>() { public Object call() { sc.createImage(); return null; } }); } } current.getParent().trimScreenshots(); return null; } }); } /** Creates a new Display with adjusted magnification to fit in the screen. */ static public void createDisplay(final Project project, final Layer layer) { SwingUtilities.invokeLater(new Runnable() { public void run() { Display display = new Display(project, layer); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); Rectangle srcRect = new Rectangle(0, 0, (int)layer.getLayerWidth(), (int)layer.getLayerHeight()); double mag = screen.width / layer.getLayerWidth(); if (mag * layer.getLayerHeight() > screen.height) mag = screen.height / layer.getLayerHeight(); mag = display.canvas.getLowerZoomLevel2(mag); if (mag > 1.0) mag = 1.0; //display.getCanvas().setup(mag, srcRect); // would call pack() at the wrong time! // ... so instead: manually display.getCanvas().setMagnification(mag); display.getCanvas().setSrcRect(srcRect.x, srcRect.y, srcRect.width, srcRect.height); display.getCanvas().setDrawingSize((int)Math.ceil(srcRect.width * mag), (int)Math.ceil(srcRect.height * mag)); // display.updateFrameTitle(layer); ij.gui.GUI.center(display.frame); display.frame.pack(); }}); } // // The only two methods that ever modify the set of al_displays // /** Swap the current al_displays list with a new list that has the @param display in it. */ static private final void addDisplay(final Display display) { if (null == display) return; synchronized (DISPLAY_LOCK) { final Set<Display> a = new HashSet<Display>(); if (null != al_displays) a.addAll(al_displays); a.add(display); al_displays = a; front = display; } } /** Swap the current al_displays list with a new list that lacks the @param dispaly, and set a new front if needed. */ static private final void removeDisplay(final Display display) { if (null == display) return; synchronized (DISPLAY_LOCK) { Set<Display> a = new HashSet<Display>(al_displays); a.remove(display); if (null == front || front == display) { if (a.size() > 0) { front = a.iterator().next(); } else { front = null; } } al_displays = a; } } /** A new Display from scratch, to show the given Layer. */ public Display(Project project, final Layer layer) { super(project); addDisplay(this); makeGUI(layer, null); IJ.addEventListener(this); setLayer(layer); this.layer = layer; // after, or it doesn't update properly addToDatabase(); } /** For reconstruction purposes. The Display will be stored in the ht_later.*/ public Display(Project project, long id, Layer layer, Object[] props) { super(project, id); synchronized (ht_later) { Display.ht_later.put(this, props); } this.layer = layer; IJ.addEventListener(this); } /** Open a new Display centered around the given Displayable. */ public Display(Project project, Layer layer, Displayable displ) { super(project); addDisplay(this); active = displ; makeGUI(layer, null); IJ.addEventListener(this); setLayer(layer); this.layer = layer; // after set layer! addToDatabase(); } /** Reconstruct a Display from an XML entry, to be opened when everything is ready. */ public Display(Project project, long id, Layer layer, HashMap<String,String> ht_attributes) { super(project, id); if (null == layer) { Utils.log2("Display: need a non-null Layer for id=" + id); return; } Rectangle srcRect = new Rectangle(0, 0, (int)layer.getLayerWidth(), (int)layer.getLayerHeight()); double magnification = 0.25; Point p = new Point(0, 0); int c_alphas = 0xffffffff; int c_alphas_state = 0xffffffff; for (final Map.Entry<String,String> entry : ht_attributes.entrySet()) { String key = entry.getKey(); String data = entry.getValue(); if (key.equals("srcrect_x")) { // reflection! Reflection! srcRect.x = Integer.parseInt(data); } else if (key.equals("srcrect_y")) { srcRect.y = Integer.parseInt(data); } else if (key.equals("srcrect_width")) { srcRect.width = Integer.parseInt(data); } else if (key.equals("srcrect_height")) { srcRect.height = Integer.parseInt(data); } else if (key.equals("magnification")) { magnification = Double.parseDouble(data); } else if (key.equals("x")) { p.x = Integer.parseInt(data); } else if (key.equals("y")) { p.y = Integer.parseInt(data); } else if (key.equals("c_alphas")) { try { c_alphas = Integer.parseInt(data); } catch (Exception ex) { c_alphas = 0xffffffff; } } else if (key.equals("c_alphas_state")) { try { c_alphas_state = Integer.parseInt(data); } catch (Exception ex) { IJError.print(ex); c_alphas_state = 0xffffffff; } } else if (key.equals("scroll_step")) { try { setScrollStep(Integer.parseInt(data)); } catch (Exception ex) { IJError.print(ex); setScrollStep(1); } } // TODO the above is insecure, in that data is not fully checked to be within bounds. } Object[] props = new Object[]{p, new Double(magnification), srcRect, new Long(layer.getId()), new Integer(c_alphas), new Integer(c_alphas_state)}; synchronized (ht_later) { Display.ht_later.put(this, props); } this.layer = layer; IJ.addEventListener(this); } /** After reloading a project from the database, open the Displays that the project had. */ static public Bureaucrat openLater() { final Hashtable<Display,Object[]> ht_later_local; synchronized (ht_later) { if (0 == ht_later.size()) return null; ht_later_local = new Hashtable<Display,Object[]>(ht_later); ht_later.keySet().removeAll(ht_later_local.keySet()); } final Worker worker = new Worker.Task("Opening displays") { public void exec() { try { Thread.sleep(300); // waiting for Swing for (Enumeration<Display> e = ht_later_local.keys(); e.hasMoreElements(); ) { final Display d = e.nextElement(); addDisplay(d); // must be set as front before repainting any ZDisplayable! Object[] props = (Object[])ht_later_local.get(d); if (ControlWindow.isGUIEnabled()) d.makeGUI(d.layer, props); d.setLayerLater(d.layer, d.layer.get(((Long)props[3]).longValue())); //important to do it after makeGUI if (!ControlWindow.isGUIEnabled()) continue; d.updateFrameTitle(d.layer); // force a repaint if a prePaint was done TODO this should be properly managed with repaints using always the invokeLater, but then it's DOG SLOW if (d.canvas.getMagnification() > 0.499) { SwingUtilities.invokeLater(new Runnable() { public void run() { Display.repaint(d.layer); d.project.getLoader().setChanged(false); Utils.log2("A set to false"); }}); } d.project.getLoader().setChanged(false); Utils.log2("B set to false"); } if (null != front) front.getProject().select(front.layer); } catch (Throwable t) { IJError.print(t); } } }; return Bureaucrat.createAndStart(worker, ((Display)ht_later_local.keySet().iterator().next()).getProject()); // gets the project from the first Display } private void makeGUI(final Layer layer, final Object[] props) { // gather properties Point p = null; double mag = 1.0D; Rectangle srcRect = null; if (null != props) { p = (Point)props[0]; mag = ((Double)props[1]).doubleValue(); srcRect = (Rectangle)props[2]; } // transparency slider this.transp_slider = new JSlider(javax.swing.SwingConstants.HORIZONTAL, 0, 100, 100); this.transp_slider.setBackground(Color.white); this.transp_slider.setMinimumSize(new Dimension(250, 20)); this.transp_slider.setMaximumSize(new Dimension(250, 20)); this.transp_slider.setPreferredSize(new Dimension(250, 20)); TransparencySliderListener tsl = new TransparencySliderListener(); this.transp_slider.addChangeListener(tsl); this.transp_slider.addMouseListener(tsl); for (final KeyListener kl : this.transp_slider.getKeyListeners()) { this.transp_slider.removeKeyListener(kl); } // Tabbed pane on the left this.tabs = new JTabbedPane(); this.tabs.setMinimumSize(new Dimension(250, 300)); this.tabs.setBackground(Color.white); this.tabs.addChangeListener(tabs_listener); // Tab 1: Patches this.panel_patches = makeTabPanel(); this.scroll_patches = makeScrollPane(panel_patches); this.addTab("Patches", scroll_patches); // Tab 2: Profiles this.panel_profiles = makeTabPanel(); this.scroll_profiles = makeScrollPane(panel_profiles); this.addTab("Profiles", scroll_profiles); // Tab 3: pipes this.panel_zdispl = makeTabPanel(); this.scroll_zdispl = makeScrollPane(panel_zdispl); this.addTab("Z space", scroll_zdispl); // Tab 4: channels this.panel_channels = makeTabPanel(); this.scroll_channels = makeScrollPane(panel_channels); this.channels = new Channel[4]; this.channels[0] = new Channel(this, Channel.MONO); this.channels[1] = new Channel(this, Channel.RED); this.channels[2] = new Channel(this, Channel.GREEN); this.channels[3] = new Channel(this, Channel.BLUE); //this.panel_channels.add(this.channels[0]); this.panel_channels.add(this.channels[1]); this.panel_channels.add(this.channels[2]); this.panel_channels.add(this.channels[3]); this.addTab("Opacity", scroll_channels); // Tab 5: labels this.panel_labels = makeTabPanel(); this.scroll_labels = makeScrollPane(panel_labels); this.addTab("Labels", scroll_labels); // Tab 6: layers this.panel_layers = makeTabPanel(); this.scroll_layers = makeScrollPane(panel_layers); recreateLayerPanels(layer); this.scroll_layers.addMouseWheelListener(canvas); this.addTab("Layers", scroll_layers); // Tab 7: tool options this.tool_options = new OptionPanel(); // empty this.scroll_options = makeScrollPane(this.tool_options); this.scroll_options.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); this.addTab("Tool options", this.scroll_options); // Tab 8: annotations this.annot_editor = new JEditorPane(); this.annot_editor.setEnabled(false); // by default, nothing is selected this.annot_editor.setMinimumSize(new Dimension(200, 50)); this.annot_label = new JLabel("(No selected object)"); this.annot_panel = makeAnnotationsPanel(this.annot_editor, this.annot_label); this.addTab("Annotations", this.annot_panel); this.ht_tabs = new Hashtable<Class,JScrollPane>(); this.ht_tabs.put(Patch.class, scroll_patches); this.ht_tabs.put(Profile.class, scroll_profiles); this.ht_tabs.put(ZDisplayable.class, scroll_zdispl); this.ht_tabs.put(AreaList.class, scroll_zdispl); this.ht_tabs.put(Pipe.class, scroll_zdispl); this.ht_tabs.put(Polyline.class, scroll_zdispl); this.ht_tabs.put(Treeline.class, scroll_zdispl); this.ht_tabs.put(AreaTree.class, scroll_zdispl); this.ht_tabs.put(Connector.class, scroll_zdispl); this.ht_tabs.put(Ball.class, scroll_zdispl); this.ht_tabs.put(Dissector.class, scroll_zdispl); this.ht_tabs.put(DLabel.class, scroll_labels); this.ht_tabs.put(Stack.class, scroll_zdispl); // channels not included // layers not included // tools not included // annotations not included // Navigator this.navigator = new DisplayNavigator(this, layer.getLayerWidth(), layer.getLayerHeight()); // Layer scroller (to scroll slices) int extent = (int)(250.0 / layer.getParent().size()); if (extent < 10) extent = 10; this.scroller = new JScrollBar(JScrollBar.HORIZONTAL); updateLayerScroller(layer); this.scroller.addAdjustmentListener(scroller_listener); // Toolbar // Left panel, contains the transp slider, the tabbed pane, the navigation panel and the layer scroller JPanel left = new JPanel(); left.setBackground(Color.white); BoxLayout left_layout = new BoxLayout(left, BoxLayout.Y_AXIS); left.setLayout(left_layout); toolbar_panel = new ToolbarPanel(); left.add(toolbar_panel); left.add(transp_slider); left.add(tabs); left.add(navigator); left.add(scroller); // Canvas this.canvas = new DisplayCanvas(this, (int)Math.ceil(layer.getLayerWidth()), (int)Math.ceil(layer.getLayerHeight())); this.canvas_panel = new JPanel(); GridBagLayout gb = new GridBagLayout(); this.canvas_panel.setLayout(gb); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.anchor = GridBagConstraints.NORTHWEST; gb.setConstraints(this.canvas_panel, c); gb.setConstraints(this.canvas, c); // prevent new Displays from screweing up if input is globally disabled if (!project.isInputEnabled()) this.canvas.setReceivesInput(false); this.canvas_panel.add(canvas); this.navigator.addMouseWheelListener(canvas); this.transp_slider.addKeyListener(canvas); // Split pane to contain everything this.split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, canvas_panel); this.split.setOneTouchExpandable(true); // NOT present in all L&F (?) this.split.setBackground(Color.white); // fix gb.setConstraints(split.getRightComponent(), c); // JFrame to show the split pane this.frame = ControlWindow.createJFrame(layer.toString()); this.frame.setBackground(Color.white); this.frame.getContentPane().setBackground(Color.white); if (IJ.isMacintosh() && IJ.getInstance()!=null) { IJ.wait(10); // may be needed for Java 1.4 on OS X this.frame.setMenuBar(ij.Menus.getMenuBar()); } this.frame.addWindowListener(window_listener); this.frame.addComponentListener(component_listener); this.frame.getContentPane().add(split); this.frame.addMouseListener(frame_mouse_listener); //doesn't exist//this.frame.setMinimumSize(new Dimension(270, 600)); if (null != props) { // restore canvas canvas.setup(mag, srcRect); // restore visibility of each channel int cs = ((Integer)props[5]).intValue(); // aka c_alphas_state int[] sel = new int[4]; sel[0] = ((cs&0xff000000)>>24); sel[1] = ((cs&0xff0000)>>16); sel[2] = ((cs&0xff00)>>8); sel[3] = (cs&0xff); // restore channel alphas this.c_alphas = ((Integer)props[4]).intValue(); channels[0].setAlpha( (float)((c_alphas&0xff000000)>>24) / 255.0f , 0 != sel[0]); channels[1].setAlpha( (float)((c_alphas&0xff0000)>>16) / 255.0f , 0 != sel[1]); channels[2].setAlpha( (float)((c_alphas&0xff00)>>8) / 255.0f , 0 != sel[2]); channels[3].setAlpha( (float) (c_alphas&0xff) / 255.0f , 0 != sel[3]); // restore visibility in the working c_alphas this.c_alphas = ((0 != sel[0] ? (int)(255 * channels[0].getAlpha()) : 0)<<24) + ((0 != sel[1] ? (int)(255 * channels[1].getAlpha()) : 0)<<16) + ((0 != sel[2] ? (int)(255 * channels[2].getAlpha()) : 0)<<8) + (0 != sel[3] ? (int)(255 * channels[3].getAlpha()) : 0); } if (null != active && null != layer) { Rectangle r = active.getBoundingBox(); r.x -= r.width/2; r.y -= r.height/2; r.width += r.width; r.height += r.height; if (r.x < 0) r.x = 0; if (r.y < 0) r.y = 0; if (r.width > layer.getLayerWidth()) r.width = (int)layer.getLayerWidth(); if (r.height> layer.getLayerHeight())r.height= (int)layer.getLayerHeight(); double magn = layer.getLayerWidth() / (double)r.width; canvas.setup(magn, r); } // add keyListener to the whole frame this.tabs.addKeyListener(canvas); this.canvas_panel.addKeyListener(canvas); this.frame.addKeyListener(canvas); this.frame.pack(); ij.gui.GUI.center(this.frame); this.frame.setVisible(true); ProjectToolbar.setProjectToolbar(); // doesn't get it through events final Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); if (null != props) { // fix positioning outside the screen (dual to single monitor) if (p.x >= 0 && p.x < screen.width - 50 && p.y >= 0 && p.y <= screen.height - 50) this.frame.setLocation(p); else frame.setLocation(0, 0); } // fix excessive size final Rectangle box = this.frame.getBounds(); int x = box.x; int y = box.y; int width = box.width; int height = box.height; if (box.width > screen.width) { x = 0; width = screen.width; } if (box.height > screen.height) { y = 0; height = screen.height; } if (x != box.x || y != box.y) { this.frame.setLocation(x, y + (0 == y ? 30 : 0)); // added insets for bad window managers updateInDatabase("position"); } if (width != box.width || height != box.height) { this.frame.setSize(new Dimension(width -10, height -30)); // added insets for bad window managers } if (null == props) { // try to optimize canvas dimensions and magn double magn = layer.getLayerHeight() / screen.height; if (magn > 1.0) magn = 1.0; long size = 0; // limit magnification if appropriate for (final Displayable pa : layer.getDisplayables(Patch.class)) { final Rectangle ba = pa.getBoundingBox(); size += (long)(ba.width * ba.height); } if (size > 10000000) canvas.setInitialMagnification(0.25); // 10 Mb else { this.frame.setSize(new Dimension((int)(screen.width * 0.66), (int)(screen.height * 0.66))); } } updateTab(panel_patches, layer.getDisplayables(Patch.class)); Utils.updateComponent(tabs); // otherwise fails in FreeBSD java 1.4.2 when reconstructing // Set the calibration of the FakeImagePlus to that of the LayerSet ((FakeImagePlus)canvas.getFakeImagePlus()).setCalibrationSuper(layer.getParent().getCalibrationCopy()); updateFrameTitle(layer); // Set the FakeImagePlus as the current image setTempCurrentImage(); // create a drag and drop listener dnd = new DNDInsertImage(this); // start a repainting thread if (null != props) { canvas.repaint(true); // repaint() is unreliable } // Set the minimum size of the tabbed pane on the left, so it can be completely collapsed now that it has been properly displayed. This is a patch to the lack of respect for the setDividerLocation method. SwingUtilities.invokeLater(new Runnable() { public void run() { tabs.setMinimumSize(new Dimension(0, 100)); Display.scrollbar_width = Display.this.scroll_patches.getVerticalScrollBar().getPreferredSize().width; // using scroll_patches since it's the one selected by default and thus visible and painted ControlWindow.setLookAndFeel(); } }); } static public void repaintToolbar() { for (final Display d : al_displays) { if (null == d.toolbar_panel) continue; // not yet ready d.toolbar_panel.repaint(); } } private class ToolbarPanel extends JPanel implements MouseListener { Method drawButton; Field lineType; Field SIZE; Field OFFSET; Toolbar toolbar = Toolbar.getInstance(); int size; //int offset; ToolbarPanel() { setBackground(Color.white); addMouseListener(this); try { drawButton = Toolbar.class.getDeclaredMethod("drawButton", Graphics.class, Integer.TYPE); drawButton.setAccessible(true); lineType = Toolbar.class.getDeclaredField("lineType"); lineType.setAccessible(true); SIZE = Toolbar.class.getDeclaredField("SIZE"); SIZE.setAccessible(true); OFFSET = Toolbar.class.getDeclaredField("OFFSET"); OFFSET.setAccessible(true); size = ((Integer)SIZE.get(null)).intValue(); //offset = ((Integer)OFFSET.get(null)).intValue(); } catch (Exception e) { IJError.print(e); } // Magic cocktail: Dimension dim = new Dimension(250, size+size); setMinimumSize(dim); setPreferredSize(dim); setMaximumSize(dim); } public void update(Graphics g) { paint(g); } public void paint(Graphics gr) { try { // Either extend the heavy-weight Canvas, or use an image to paint to. // Otherwise, rearrangements of the layout while painting will result // in incorrectly positioned toolbar buttons. BufferedImage bi = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB); Graphics g = bi.getGraphics(); g.setColor(Color.white); g.fillRect(0, 0, getWidth(), getHeight()); int i = 0; for (; i<Toolbar.LINE; i++) { drawButton.invoke(toolbar, g, i); } drawButton.invoke(toolbar, g, lineType.get(toolbar)); for (; i<=Toolbar.TEXT; i++) { drawButton.invoke(toolbar, g, i); } drawButton.invoke(toolbar, g, Toolbar.ANGLE); // newline AffineTransform aff = new AffineTransform(); aff.translate(-size*Toolbar.TEXT, size-1); ((Graphics2D)g).setTransform(aff); for (; i<18; i++) { drawButton.invoke(toolbar, g, i); } gr.drawImage(bi, 0, 0, null); bi.flush(); g.dispose(); } catch (Exception e) { IJError.print(e); } } /* // Fails: "origin not in parent's hierarchy" ... right. private void showPopup(String name, int x, int y) { try { Field f = Toolbar.getInstance().getClass().getDeclaredField(name); f.setAccessible(true); PopupMenu p = (PopupMenu) f.get(Toolbar.getInstance()); p.show(this, x, y); } catch (Throwable t) { IJError.print(t); } } */ public void mousePressed(MouseEvent me) { int x = me.getX(); int y = me.getY(); if (y > size) { if (x > size * 7) return; // off limits x += size * 9; y -= size; } else { if (x > size * 9) return; // off limits } /* if (Utils.isPopupTrigger(me)) { if (x >= size && x <= size * 2 && y >= 0 && y <= size) { showPopup("ovalPopup", x, y); return; } else if (x >= size * 4 && x <= size * 5 && y >= 0 && y <= size) { showPopup("linePopup", x, y); return; } } */ Toolbar.getInstance().mousePressed(new MouseEvent(toolbar, me.getID(), System.currentTimeMillis(), me.getModifiers(), x, y, me.getClickCount(), me.isPopupTrigger())); repaint(); Display.toolChanged(ProjectToolbar.getToolId()); // should fire on its own but it does not (?) TODO } public void mouseReleased(MouseEvent me) {} public void mouseClicked(MouseEvent me) {} public void mouseEntered(MouseEvent me) {} public void mouseExited(MouseEvent me) {} } private JPanel makeTabPanel() { JPanel panel = new JPanel(); BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS); panel.setLayout(layout); return panel; } private JScrollPane makeScrollPane(Component c) { JScrollPane jsp = new JScrollPane(c); jsp.setBackground(Color.white); // no effect jsp.getViewport().setBackground(Color.white); // no effect // adjust scrolling to use one DisplayablePanel as the minimal unit jsp.getVerticalScrollBar().setBlockIncrement(DisplayablePanel.HEIGHT); // clicking within the track jsp.getVerticalScrollBar().setUnitIncrement(DisplayablePanel.HEIGHT); // clicking on an arrow jsp.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); jsp.setPreferredSize(new Dimension(250, 300)); jsp.setMinimumSize(new Dimension(250, 300)); return jsp; } private JPanel makeAnnotationsPanel(JEditorPane ep, JLabel label) { JPanel p = new JPanel(); GridBagLayout gb = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); p.setLayout(gb); c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.NORTHWEST; c.ipadx = 5; c.ipady = 5; c.gridx = 0; c.gridy = 0; c.weightx = 0; c.weighty = 0; JLabel title = new JLabel("Annotate:"); gb.setConstraints(title, c); p.add(title); c.gridy++; gb.setConstraints(label, c); p.add(label); c.weighty = 1; c.gridy++; c.fill = GridBagConstraints.BOTH; c.ipadx = 0; c.ipady = 0; JScrollPane sp = new JScrollPane(ep, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); sp.setPreferredSize(new Dimension(250, 300)); sp.setMinimumSize(new Dimension(250, 300)); gb.setConstraints(sp, c); p.add(sp); return p; } public JPanel getCanvasPanel() { return canvas_panel; } public DisplayCanvas getCanvas() { return canvas; } public synchronized void setLayer(final Layer layer) { if (!mode.canChangeLayer()) { scroller.setValue(Display.this.layer.getParent().indexOf(Display.this.layer)); // TODO should be done in EDT return; } if (null == layer || layer == this.layer) return; translateLayerColors(this.layer, layer); if (tabs.getSelectedComponent() == scroll_layers) { SwingUtilities.invokeLater(new Runnable() { public void run() { scrollToShow(scroll_layers, layer_panels.get(layer)); }}); } final boolean set_zdispl = null == Display.this.layer || layer.getParent() != Display.this.layer.getParent(); this.layer = layer; // Below, will fire the event as well, and call stl.set(layer) which calls setLayer with the same layer, and returns. // But just scroller.getModel().setValue(int) will ALSO fire the event. So let it do the loop. scroller.setValue(layer.getParent().indexOf(layer)); /* // OBSOLETE // update the current Layer pointer in ZDisplayable objects for (Iterator it = layer.getParent().getZDisplayables().iterator(); it.hasNext(); ) { ((ZDisplayable)it.next()).setLayer(layer); // the active layer } */ updateVisibleTab(set_zdispl); updateFrameTitle(layer); // to show the new 'z' // select the Layer in the LayerTree project.select(Display.this.layer); // does so in a separate thread // update active Displayable: // deselect all except ZDisplayables final ArrayList<Displayable> sel = selection.getSelected(); final Displayable last_active = Display.this.active; int sel_next = -1; for (final Iterator<Displayable> it = sel.iterator(); it.hasNext(); ) { final Displayable d = it.next(); if (!(d instanceof ZDisplayable)) { it.remove(); selection.remove(d); if (d == last_active && sel.size() > 0) { // set as active (by selecting it) the last one of the remaining, if any sel_next = sel.size()-1; } } } if (-1 != sel_next && sel.size() > 0) select(sel.get(sel_next), true); // repaint everything navigator.repaint(true); canvas.repaint(true); // repaint tabs (hard as hell) Utils.updateComponent(tabs); // @#$%^! The above works half the times, so explicit repaint as well: Component c = tabs.getSelectedComponent(); if (null == c) { c = scroll_patches; tabs.setSelectedComponent(scroll_patches); } Utils.updateComponent(c); // update the coloring in the ProjectTree project.getProjectTree().updateUILater(); setTempCurrentImage(); } static public void updateVisibleTabs() { for (final Display d : al_displays) { d.updateVisibleTab(true); } } static public void updateVisibleTabs(final Project p) { for (final Display d : al_displays) { if (d.project == p) d.updateVisibleTab(true); } } /** Recreate the tab that is being shown. */ public void updateVisibleTab(boolean set_zdispl) { // update only the visible tab switch (tabs.getSelectedIndex()) { case 0: ht_panels.clear(); updateTab(panel_patches, layer.getDisplayables(Patch.class)); break; case 1: ht_panels.clear(); updateTab(panel_profiles, layer.getDisplayables(Profile.class)); break; case 2: if (set_zdispl) { ht_panels.clear(); updateTab(panel_zdispl, layer.getParent().getZDisplayables()); } break; // case 3: channel opacities case 4: ht_panels.clear(); updateTab(panel_labels, layer.getDisplayables(DLabel.class)); break; // case 5: layer panels } } private void setLayerLater(final Layer layer, final Displayable active) { if (null == layer) return; this.layer = layer; if (!ControlWindow.isGUIEnabled()) return; SwingUtilities.invokeLater(new Runnable() { public void run() { // empty the tabs, except channels and pipes clearTab(panel_profiles); clearTab(panel_patches); clearTab(panel_labels); // distribute Displayable to the tabs. Ignore LayerSet instances. if (null == ht_panels) ht_panels = new Hashtable<Displayable,DisplayablePanel>(); else ht_panels.clear(); for (final Displayable d : layer.getParent().getZDisplayables()) { d.setLayer(layer); } updateTab(panel_patches, layer.getDisplayables(Patch.class)); navigator.repaint(true); // was not done when adding Utils.updateComponent(tabs.getSelectedComponent()); // setActive(active); }}); // swing issues: /* new Thread() { public void run() { setPriority(Thread.NORM_PRIORITY); try { Thread.sleep(1000); } catch (Exception e) {} setActive(active); } }.start(); */ } /** Remove all components from the tab. */ private void clearTab(final Container c) { c.removeAll(); // magic cocktail: if (tabs.getSelectedComponent() == c) { Utils.updateComponent(c); } } /** A class to listen to the transparency_slider of the DisplayablesSelectorWindow. */ private class TransparencySliderListener extends MouseAdapter implements ChangeListener { public void stateChanged(ChangeEvent ce) { //change the transparency value of the current active displayable float new_value = (float)((JSlider)ce.getSource()).getValue(); setTransparency(new_value / 100.0f); } public void mousePressed(MouseEvent me) { if (tabs.getSelectedComponent() != scroll_channels && !selection.isEmpty()) selection.addDataEditStep(new String[]{"alpha"}); } public void mouseReleased(MouseEvent me) { // update navigator window navigator.repaint(true); if (tabs.getSelectedComponent() != scroll_channels && !selection.isEmpty()) selection.addDataEditStep(new String[]{"alpha"}); } } /** Context-sensitive: to a Displayable, or to a channel. */ private void setTransparency(final float value) { Component scroll = tabs.getSelectedComponent(); if (scroll == scroll_channels) { for (int i=0; i<4; i++) { if (channels[i].getBackground() == Color.cyan) { channels[i].setAlpha(value); // will call back and repaint the Display return; } } } else if (null != active) { if (value != active.getAlpha()) { // because there's a callback from setActive that would then affect all other selected Displayable without having dragged the slider, i.e. just by being selected. selection.setAlpha(value); } } } public void setTransparencySlider(final float transp) { if (transp >= 0.0f && transp <= 1.0f) { // fire event transp_slider.setValue((int)(transp * 100)); } } /** Mark the canvas for updating the offscreen images if the given Displayable is NOT the active. */ // Used by the Displayable.setVisible for example. static public void setUpdateGraphics(final Layer layer, final Displayable displ) { for (final Display d : al_displays) { if (layer == d.layer && null != d.active && d.active != displ) { d.canvas.setUpdateGraphics(true); } } } /** Flag the DisplayCanvas of Displays showing the given Layer to update their offscreen images.*/ static public void setUpdateGraphics(final Layer layer, final boolean update) { for (final Display d : al_displays) { if (layer == d.layer) { d.canvas.setUpdateGraphics(update); } } } /** Whether to update the offscreen images or not. */ public void setUpdateGraphics(boolean b) { canvas.setUpdateGraphics(b); } /** Update the entire GUI: * 1 - The layer scroller * 2 - The visible tab panels * 3 - The toolbar * 4 - The navigator * 5 - The canvas */ static public void update() { for (final Display d : al_displays) { d.updateLayerScroller(d.layer); d.updateVisibleTab(true); d.toolbar_panel.repaint(); d.navigator.repaint(true); d.canvas.repaint(true); } } /** Find all Display instances that contain the layer and repaint them, in the Swing GUI thread. */ static public void update(final Layer layer) { if (null == layer) return; SwingUtilities.invokeLater(new Runnable() { public void run() { for (final Display d : al_displays) { if (d.isShowing(layer)) { d.repaintAll(); } } }}); } static public void update(final LayerSet set) { update(set, true); } /** Find all Display instances showing a Layer of this LayerSet, and update the dimensions of the navigator and canvas and snapshots, and repaint, in the Swing GUI thread. */ static public void update(final LayerSet set, final boolean update_canvas_dimensions) { if (null == set) return; SwingUtilities.invokeLater(new Runnable() { public void run() { for (final Display d : al_displays) { if (d.layer.getParent() == set) { d.updateSnapshots(); if (update_canvas_dimensions) d.canvas.setDimensions(set.getLayerWidth(), set.getLayerHeight()); d.repaintAll(); } } }}); } /** Release all resources held by this Display and close the frame. */ protected void destroy() { // Set a new front if any and remove from the list of open Displays removeDisplay(this); // Inactivate this Display: dispatcher.quit(); canvas.setReceivesInput(false); slt.quit(); // update the coloring in the ProjectTree and LayerTree if (!project.isBeingDestroyed()) { try { project.getProjectTree().updateUILater(); project.getLayerTree().updateUILater(); } catch (Exception e) { Utils.log2("updateUI failed at Display.destroy()"); } } frame.removeComponentListener(component_listener); frame.removeWindowListener(window_listener); frame.removeWindowFocusListener(window_listener); frame.removeWindowStateListener(window_listener); frame.removeKeyListener(canvas); frame.removeMouseListener(frame_mouse_listener); canvas_panel.removeKeyListener(canvas); canvas.removeKeyListener(canvas); tabs.removeChangeListener(tabs_listener); tabs.removeKeyListener(canvas); IJ.removeEventListener(this); bytypelistener = null; canvas.destroy(); navigator.destroy(); scroller.removeAdjustmentListener(scroller_listener); frame.setVisible(false); //no need, and throws exception//frame.dispose(); active = null; if (null != selection) selection.clear(); // repaint layer tree (to update the label color) try { project.getLayerTree().updateUILater(); // works only after setting the front above } catch (Exception e) {} // ignore swing sync bullshit when closing everything too fast // remove the drag and drop listener dnd.destroy(); } /** Find all Display instances that contain a Layer of the given project and close them without removing the Display entries from the database. */ static synchronized public void close(final Project project) { /* // concurrent modifications if more than 1 Display are being removed asynchronously for (final Display d : al_displays) { if (d.getLayer().getProject().equals(project)) { it.remove(); d.destroy(); } } */ Display[] d = new Display[al_displays.size()]; al_displays.toArray(d); for (int i=0; i<d.length; i++) { if (d[i].getProject() == project) { removeDisplay(d[i]); d[i].destroy(); } } } /** Find all Display instances that contain the layer and close them and remove the Display from the database. */ static public void close(final Layer layer) { for (final Display d : al_displays) { if (d.isShowing(layer)) { d.remove(false); // calls destroy which calls removeDisplay } } } /** Find all Display instances that are showing the layer and either move to the next or previous layer, or close it if none. */ static public void remove(final Layer layer) { for (final Display d : al_displays) { if (d.isShowing(layer)) { Layer la = layer.getParent().next(layer); if (layer == la || null == la) la = layer.getParent().previous(layer); if (null == la || layer == la) { d.remove(false); // will call destroy which calls removeDisplay } else { d.slt.set(la); } } } } public boolean remove(boolean check) { if (check) { if (!Utils.check("Delete the Display ?")) return false; } // flush the offscreen images and close the frame destroy(); removeFromDatabase(); return true; } public Layer getLayer() { return layer; } public LayerSet getLayerSet() { return layer.getParent(); } public boolean isShowing(final Layer layer) { return this.layer == layer; } public DisplayNavigator getNavigator() { return navigator; } /** Repaint both the canvas and the navigator, updating the graphics, and the title and tabs. */ public void repaintAll() { if (repaint_disabled) return; navigator.repaint(true); canvas.repaint(true); Utils.updateComponent(tabs); updateFrameTitle(); } /** Repaint the canvas updating graphics, the navigator without updating graphics, and the title. */ public void repaintAll2() { if (repaint_disabled) return; navigator.repaint(false); canvas.repaint(true); updateFrameTitle(); } static protected void repaintSnapshots(final LayerSet set) { if (repaint_disabled) return; for (final Display d : al_displays) { if (d.getLayer().getParent() == set) { d.navigator.repaint(true); Utils.updateComponent(d.tabs); } } } static protected void repaintSnapshots(final Layer layer) { if (repaint_disabled) return; for (final Display d : al_displays) { if (d.getLayer() == layer) { d.navigator.repaint(true); Utils.updateComponent(d.tabs); } } } public void pack() { dispatcher.exec(new Runnable() { public void run() { try { Thread.sleep(100); SwingUtilities.invokeAndWait(new Runnable() { public void run() { frame.pack(); navigator.repaint(false); // upate srcRect red frame position/size }}); } catch (Exception e) { IJError.print(e); } }}); } static public void pack(final LayerSet ls) { for (final Display d : al_displays) { if (d.layer.getParent() == ls) d.pack(); } } private void adjustCanvas() { SwingUtilities.invokeLater(new Runnable() { public void run() { Rectangle r = split.getRightComponent().getBounds(); canvas.setDrawingSize(r.width, r.height, true); // fix not-on-top-left problem canvas.setLocation(0, 0); //frame.pack(); // don't! Would go into an infinite loop canvas.repaint(true); updateInDatabase("srcRect"); }}); } /** Grab the last selected display (or create an new one if none) and show in it the layer,centered on the Displayable object. */ static public void setFront(final Layer layer, final Displayable displ) { if (null == front) { Display display = new Display(layer.getProject(), layer); // gets set to front display.showCentered(displ); } else if (layer == front.layer) { front.showCentered(displ); } else { // find one: for (final Display d : al_displays) { if (d.layer == layer) { d.frame.toFront(); d.showCentered(displ); return; } } // else, open new one new Display(layer.getProject(), layer).showCentered(displ); } } /** Find the displays that show the given Layer, and add the given Displayable to the GUI and sets it active only in the front Display and only if 'activate' is true. */ static protected void add(final Layer layer, final Displayable displ, final boolean activate) { for (final Display d : al_displays) { if (d.layer == layer) { if (front == d) { d.add(displ, activate, true); //front.frame.toFront(); } else { d.add(displ, false, true); } } } } static protected void add(final Layer layer, final Displayable displ) { add(layer, displ, true); } /** Add the ZDisplayable to all Displays that show a Layer belonging to the given LayerSet. */ static protected void add(final LayerSet set, final ZDisplayable zdispl) { for (final Display d : al_displays) { if (d.layer.getParent() == set) { if (front == d) { zdispl.setLayer(d.layer); // the active one d.add(zdispl, true, true); // calling add(Displayable, boolean, boolean) //front.frame.toFront(); } else { d.add(zdispl, false, true); } } } } static protected void addAll(final Layer layer, final Collection<? extends Displayable> coll) { for (final Display d : al_displays) { if (d.layer == layer) { d.addAll(coll); } } } static protected void addAll(final LayerSet set, final Collection<? extends ZDisplayable> coll) { for (final Display d : al_displays) { if (d.layer.getParent() == set) { for (final ZDisplayable zd : coll) { if (front == d) zd.setLayer(d.layer); // this is obsolete now } d.addAll(coll); } } } private final void addAll(final Collection<? extends Displayable> coll) { // if any of the elements in the collection matches the type of the current tab, update that tab // ... it's easier to just update the front tab updateVisibleTab(true); selection.clear(); navigator.repaint(true); } /** Add it to the proper panel, at the top, and set it active. */ private final void add(final Displayable d, final boolean activate, final boolean repaint_snapshot) { if (activate) { DisplayablePanel dp = ht_panels.get(d); if (null != dp) dp.setActive(true); else updateVisibleTab(d instanceof ZDisplayable); selection.clear(); selection.add(d); Display.repaint(d.getLayerSet()); // update the al_top list to contain the active one, or background image for a new Patch. Utils.log2("Added " + d); } if (repaint_snapshot) navigator.repaint(true); } /* private void addToPanel(JPanel panel, int index, DisplayablePanel dp, boolean repaint) { // remove the label if (1 == panel.getComponentCount() && panel.getComponent(0) instanceof JLabel) { panel.removeAll(); } panel.add(dp, index); if (repaint) { Utils.updateComponent(tabs); } } */ /** Find the displays that show the given Layer, and remove the given Displayable from the GUI. */ static public void remove(final Layer layer, final Displayable displ) { for (final Display d : al_displays) { if (layer == d.layer) d.remove(displ); } } private void remove(final Displayable displ) { DisplayablePanel ob = ht_panels.remove(displ); if (null != ob) { final JScrollPane jsp = ht_tabs.get(displ.getClass()); if (null != jsp) { JPanel p = (JPanel)jsp.getViewport().getView(); final boolean visible = isPartiallyWithinViewport(jsp.getViewport(), ob); p.remove(ob); if (visible) { Utils.revalidateComponent(p); } } } if (null == active || !selection.contains(displ)) { canvas.setUpdateGraphics(true); } repaint(displ, null, 5, true, false); // from Selection.deleteAll this method is called ... but it's ok: same thread, no locking problems. selection.remove(displ); } static public void remove(final ZDisplayable zdispl) { for (final Display d : al_displays) { if (zdispl.getLayerSet() == d.layer.getParent()) { d.remove((Displayable)zdispl); } } } static public void repaint(final Layer layer, final Displayable displ, final int extra) { repaint(layer, displ, displ.getBoundingBox(), extra); } static public void repaint(final Layer layer, final Displayable displ, final Rectangle r, final int extra) { repaint(layer, displ, r, extra, true); } /** Find the displays that show the given Layer, and repaint the given Displayable; does NOT update graphics for the offscreen image. */ static public void repaint(final Layer layer, final Displayable displ, final Rectangle r, final int extra, final boolean repaint_navigator) { repaint(layer, displ, r, extra, false, repaint_navigator); } /** * @param layer The layer to repaint * @param r The Rectangle to repaint, in world coordinates (aka pixel coordinates or canvas coordinates). * @param extra The number of pixels to pad @param r with. * @param update_graphics Whether to recreate the offscreen image of the canvas, which is necessary for images. * @param repaint_navigator Whether to repaint the navigator. */ static public void repaint(final Layer layer, final Displayable displ, final Rectangle r, final int extra, final boolean update_graphics, final boolean repaint_navigator) { if (repaint_disabled) return; for (final Display d : al_displays) { if (layer == d.layer) { d.repaint(displ, r, extra, repaint_navigator, update_graphics); } } } static public void repaint(final Displayable d) { if (d instanceof ZDisplayable) repaint(d.getLayerSet(), d, d.getBoundingBox(null), 5, true); repaint(d.getLayer(), d, d.getBoundingBox(null), 5, true); } /** Repaint as much as the bounding box around the given Displayable, or the r if not null. * @param update_graphics will be made true if the @param displ is a Patch or it's not the active Displayable. */ private void repaint(final Displayable displ, final Rectangle r, final int extra, final boolean repaint_navigator, boolean update_graphics) { if (repaint_disabled || null == displ) return; update_graphics = (update_graphics || displ.getClass() == Patch.class || displ != active); if (null != r) canvas.repaint(r, extra, update_graphics); else canvas.repaint(displ, extra, update_graphics); if (repaint_navigator) { DisplayablePanel dp = ht_panels.get(displ); if (null != dp) dp.repaint(); // is null when creating it, or after deleting it navigator.repaint(true); // everything } } /** Repaint the snapshot for the given Displayable both at the DisplayNavigator and on its panel,and only if it has not been painted before. This method is intended for the loader to know when to paint a snap, to avoid overhead. */ static public void repaintSnapshot(final Displayable displ) { for (final Display d : al_displays) { if (d.layer.contains(displ)) { if (!d.navigator.isPainted(displ)) { DisplayablePanel dp = d.ht_panels.get(displ); if (null != dp) dp.repaint(); // is null when creating it, or after deleting it d.navigator.repaint(displ); } } } } /** Repaint the given Rectangle in all Displays showing the layer, updating the offscreen image if any. */ static public void repaint(final Layer layer, final Rectangle r, final int extra) { repaint(layer, extra, r, true, true); } static public void repaint(final Layer layer, final int extra, final Rectangle r, final boolean update_navigator) { repaint(layer, extra, r, update_navigator, true); } static public void repaint(final Layer layer, final int extra, final Rectangle r, final boolean update_navigator, final boolean update_graphics) { if (repaint_disabled) return; for (final Display d : al_displays) { if (layer == d.layer) { d.canvas.setUpdateGraphics(update_graphics); d.canvas.repaint(r, extra); if (update_navigator) { d.navigator.repaint(true); Utils.updateComponent(d.tabs.getSelectedComponent()); } } } } /** Repaint the given Rectangle in all Displays showing the layer, optionally updating the offscreen image (if any). */ static public void repaint(final Layer layer, final Rectangle r, final int extra, final boolean update_graphics) { if (repaint_disabled) return; for (final Display d : al_displays) { if (layer == d.layer) { d.canvas.setUpdateGraphics(update_graphics); d.canvas.repaint(r, extra); d.navigator.repaint(update_graphics); if (update_graphics) Utils.updateComponent(d.tabs.getSelectedComponent()); } } } /** Repaint the DisplayablePanel (and DisplayNavigator) only for the given Displayable, in all Displays showing the given Layer. */ static public void repaint(final Layer layer, final Displayable displ) { if (repaint_disabled) return; for (final Display d : al_displays) { if (layer == d.layer) { DisplayablePanel dp = d.ht_panels.get(displ); if (null != dp) dp.repaint(); d.navigator.repaint(true); } } } static public void repaint(LayerSet set, Displayable displ, int extra) { repaint(set, displ, null, extra); } static public void repaint(LayerSet set, Displayable displ, Rectangle r, int extra) { repaint(set, displ, r, extra, true); } /** Repaint the Displayable in every Display that shows a Layer belonging to the given LayerSet. */ static public void repaint(final LayerSet set, final Displayable displ, final Rectangle r, final int extra, final boolean repaint_navigator) { if (repaint_disabled) return; if (null == set) return; for (final Display d : al_displays) { if (d.layer.getParent() == set) { if (repaint_navigator) { if (null != displ) { DisplayablePanel dp = d.ht_panels.get(displ); if (null != dp) dp.repaint(); } d.navigator.repaint(true); } if (null == displ || displ != d.active) d.setUpdateGraphics(true); // safeguard // paint the given box or the actual Displayable's box if (null != r) d.canvas.repaint(r, extra); else d.canvas.repaint(displ, extra); } } } /** Repaint the entire LayerSet, in all Displays showing a Layer of it.*/ static public void repaint(final LayerSet set) { if (repaint_disabled) return; for (final Display d : al_displays) { if (d.layer.getParent() == set) { d.navigator.repaint(true); d.canvas.repaint(true); } } } /** Repaint the given box in the LayerSet, in all Displays showing a Layer of it.*/ static public void repaint(final LayerSet set, final Rectangle box) { if (repaint_disabled) return; for (final Display d : al_displays) { if (d.layer.getParent() == set) { d.navigator.repaint(box); d.canvas.repaint(box, 0, true); } } } /** Repaint the entire Layer, in all Displays showing it, including the tabs.*/ static public void repaint(final Layer layer) { // TODO this method overlaps with update(layer) if (repaint_disabled) return; for (final Display d : al_displays) { if (layer == d.layer) { d.navigator.repaint(true); d.canvas.repaint(true); } } } /** Call repaint on all open Displays. */ static public void repaint() { if (repaint_disabled) { Utils.logAll("Can't repaint -- repainting is disabled!"); return; } for (final Display d : al_displays) { d.navigator.repaint(true); d.canvas.repaint(true); } } static private boolean repaint_disabled = false; /** Set a flag to enable/disable repainting of all Display instances. */ static protected void setRepaint(boolean b) { repaint_disabled = !b; } public Rectangle getBounds() { return frame.getBounds(); } public Point getLocation() { return frame.getLocation(); } public JFrame getFrame() { return frame; } /** Feel free to add more tabs. Don't remove any of the existing tabs or the sky will fall on your head. */ public JTabbedPane getTabbedPane() { return tabs; } /** Returns the tab index in this Display's JTabbedPane. */ public int addTab(final String title, final Component comp) { this.tabs.add(title, comp); return this.tabs.getTabCount() -1; } public void setLocation(Point p) { this.frame.setLocation(p); } public Displayable getActive() { return active; //TODO this should return selection.active !! } public void select(Displayable d) { select(d, false); } /** Select/deselect accordingly to the current state and the shift key. */ public void select(final Displayable d, final boolean shift_down) { if (null != active && active != d && active.getClass() != Patch.class) { // active is being deselected, so link underlying patches final String prop = active.getClass() == DLabel.class ? project.getProperty("label_nolinks") : project.getProperty("segmentations_nolinks"); HashSet<Displayable> glinked = null; if (null != prop && prop.equals("true")) { // do nothing: linking disabled for active's type } else if (active.linkPatches()) { // Locking state changed: glinked = active.getLinkedGroup(null); updateCheckboxes(glinked, DisplayablePanel.LOCK_STATE, true); } // Update link icons: Display.updateCheckboxes(null == glinked ? active.getLinkedGroup(null) : glinked, DisplayablePanel.LINK_STATE); } if (null == d) { //Utils.log2("Display.select: clearing selection"); canvas.setUpdateGraphics(true); selection.clear(); return; } if (!shift_down) { //Utils.log2("Display.select: single selection"); if (d != active) { selection.clear(); selection.add(d); } } else if (selection.contains(d)) { if (active == d) { selection.remove(d); //Utils.log2("Display.select: removing from a selection"); } else { //Utils.log2("Display.select: activing within a selection"); selection.setActive(d); } } else { //Utils.log2("Display.select: adding to an existing selection"); selection.add(d); } // update the image shown to ImageJ // NO longer necessary, always he same FakeImagePlus // setTempCurrentImage(); } protected void choose(int screen_x_p, int screen_y_p, int x_p, int y_p, final Class c) { choose(screen_x_p, screen_y_p, x_p, y_p, false, c); } protected void choose(int screen_x_p, int screen_y_p, int x_p, int y_p) { choose(screen_x_p, screen_y_p, x_p, y_p, false, null); } /** Find a Displayable to add to the selection under the given point (which is in offscreen coords); will use a popup menu to give the user a range of Displayable objects to select from. */ protected void choose(int screen_x_p, int screen_y_p, int x_p, int y_p, boolean shift_down, Class c) { //Utils.log("Display.choose: x,y " + x_p + "," + y_p); final ArrayList<Displayable> al = new ArrayList<Displayable>(layer.find(x_p, y_p, true)); al.addAll(layer.getParent().findZDisplayables(layer, x_p, y_p, true)); // only visible ones if (al.isEmpty()) { Displayable act = this.active; selection.clear(); canvas.setUpdateGraphics(true); //Utils.log("choose: set active to null"); // fixing lack of repainting for unknown reasons, of the active one TODO this is a temporary solution if (null != act) Display.repaint(layer, act, 5); } else if (1 == al.size()) { Displayable d = (Displayable)al.get(0); if (null != c && d.getClass() != c) { selection.clear(); return; } select(d, shift_down); //Utils.log("choose 1: set active to " + active); } else { if (al.contains(active) && !shift_down) { // do nothing } else { if (null != c) { // check if at least one of them is of class c // if only one is of class c, set as selected // else show menu for (Iterator<?> it = al.iterator(); it.hasNext(); ) { Object ob = it.next(); if (ob.getClass() != c) it.remove(); } if (0 == al.size()) { // deselect selection.clear(); return; } if (1 == al.size()) { select((Displayable)al.get(0), shift_down); return; } // else, choose among the many } choose(screen_x_p, screen_y_p, al, shift_down, x_p, y_p); } //Utils.log("choose many: set active to " + active); } } private void choose(final int screen_x_p, final int screen_y_p, final Collection<Displayable> al, final boolean shift_down, final int x_p, final int y_p) { // show a popup on the canvas to choose new Thread() { public void run() { final Object lock = new Object(); final DisplayableChooser d_chooser = new DisplayableChooser(al, lock); final JPopupMenu pop = new JPopupMenu("Select:"); for (final Displayable d : al) { JMenuItem menu_item = new JMenuItem(d.toString()); menu_item.addActionListener(d_chooser); pop.add(menu_item); } new Thread() { public void run() { pop.show(canvas, screen_x_p, screen_y_p); } }.start(); //now wait until selecting something synchronized(lock) { do { try { lock.wait(); // lock.notify() is never called! How can this work at all? TODO I need to understand this. } catch (InterruptedException ie) {} } while (d_chooser.isWaiting() && pop.isShowing()); } //grab the chosen Displayable object Displayable d = d_chooser.getChosen(); //Utils.log("Chosen: " + d.toString()); if (null == d) { Utils.log2("Display.choose: returning a null!"); } select(d, shift_down); pop.setVisible(false); // fix selection bug: never receives mouseReleased event when the popup shows getMode().mouseReleased(null, x_p, y_p, x_p, y_p, x_p, y_p); } }.start(); } /** Used by the Selection exclusively. This method will change a lot in the near future, and may disappear in favor of getSelection().getActive(). All this method does is update GUI components related to the currently active and the newly active Displayable; called through SwingUtilities.invokeLater. */ protected void setActive(final Displayable displ) { final Displayable prev_active = this.active; this.active = displ; SwingUtilities.invokeLater(new Runnable() { public void run() { if (null != displ && displ == prev_active && tabs.getSelectedComponent() != annot_panel) { // make sure the proper tab is selected. selectTab(displ); return; // the same } // deactivate previously active if (null != prev_active) { final DisplayablePanel ob = ht_panels.get(prev_active); if (null != ob) ob.setActive(false); // erase "decorations" of the previously active canvas.repaint(selection.getBox(), 4); // Adjust annotation doc synchronized (annot_docs) { boolean remove_doc = true; for (final Display d : al_displays) { if (prev_active == d.active) { remove_doc = false; break; } } if (remove_doc) annot_docs.remove(prev_active); } } // activate the new active if (null != displ) { final DisplayablePanel ob = ht_panels.get(displ); if (null != ob) ob.setActive(true); updateInDatabase("active_displayable_id"); if (displ.getClass() != Patch.class) project.select(displ); // select the node in the corresponding tree, if any. // select the proper tab, and scroll to visible if (tabs.getSelectedComponent() != annot_panel) { // don't swap tab if its the annotation one selectTab(displ); } boolean update_graphics = null == prev_active || paintsBelow(prev_active, displ); // or if it's an image, but that's by default in the repaint method repaint(displ, null, 5, false, update_graphics); // to show the border, and to repaint out of the background image transp_slider.setValue((int)(displ.getAlpha() * 100)); // Adjust annotation tab: synchronized (annot_docs) { annot_label.setText(displ.toString()); Document doc = annot_docs.get(displ); // could be open in another Display if (null == doc) { doc = annot_editor.getEditorKit().createDefaultDocument(); doc.addDocumentListener(new DocumentListener() { public void changedUpdate(DocumentEvent e) {} public void insertUpdate(DocumentEvent e) { push(); } public void removeUpdate(DocumentEvent e) { push(); } private void push() { displ.setAnnotation(annot_editor.getText()); } }); annot_docs.put(displ, doc); } annot_editor.setDocument(doc); if (null != displ.getAnnotation()) annot_editor.setText(displ.getAnnotation()); } annot_editor.setEnabled(true); } else { //ensure decorations are removed from the panels, for Displayables in a selection besides the active one Utils.updateComponent(tabs.getSelectedComponent()); annot_label.setText("(No selected object)"); annot_editor.setDocument(annot_editor.getEditorKit().createDefaultDocument()); // a clear, empty one annot_editor.setEnabled(false); } }}); } /** If the other paints under the base. */ public boolean paintsBelow(Displayable base, Displayable other) { boolean zd_base = base instanceof ZDisplayable; boolean zd_other = other instanceof ZDisplayable; if (zd_other) { if (base instanceof DLabel) return true; // zd paints under label if (!zd_base) return false; // any zd paints over a mere displ if not a label else { // both zd, compare indices ArrayList<ZDisplayable> al = other.getLayerSet().getZDisplayables(); return al.indexOf(base) > al.indexOf(other); } } else { if (!zd_base) { // both displ, compare indices ArrayList<Displayable> al = other.getLayer().getDisplayables(); return al.indexOf(base) > al.indexOf(other); } else { // base is zd, other is d if (other instanceof DLabel) return false; return true; } } } /** Select the proper tab, and also scroll it to show the given Displayable -unless it's a LayerSet, and unless the proper tab is already showing. */ private void selectTab(final Displayable displ) { Method method = null; try { if (!(displ instanceof LayerSet)) { method = Display.class.getDeclaredMethod("selectTab", new Class[]{displ.getClass()}); } } catch (Exception e) { IJError.print(e); } if (null != method) { final Method me = method; dispatcher.exec(new Runnable() { public void run() { try { me.setAccessible(true); me.invoke(Display.this, new Object[]{displ}); } catch (Exception e) { IJError.print(e); } }}); } } private void selectTab(Patch patch) { tabs.setSelectedComponent(scroll_patches); scrollToShow(scroll_patches, ht_panels.get(patch)); } private void selectTab(Profile profile) { tabs.setSelectedComponent(scroll_profiles); scrollToShow(scroll_profiles, ht_panels.get(profile)); } private void selectTab(DLabel label) { tabs.setSelectedComponent(scroll_labels); scrollToShow(scroll_labels, ht_panels.get(label)); } private void selectTab(ZDisplayable zd) { tabs.setSelectedComponent(scroll_zdispl); scrollToShow(scroll_zdispl, ht_panels.get(zd)); } private void selectTab(Pipe d) { selectTab((ZDisplayable)d); } private void selectTab(Polyline d) { selectTab((ZDisplayable)d); } private void selectTab(Treeline d) { selectTab((ZDisplayable)d); } private void selectTab(AreaTree d) { selectTab((ZDisplayable)d); } private void selectTab(Connector d) { selectTab((ZDisplayable)d); } private void selectTab(AreaList d) { selectTab((ZDisplayable)d); } private void selectTab(Ball d) { selectTab((ZDisplayable)d); } private void selectTab(Dissector d) { selectTab((ZDisplayable)d); } private void selectTab(Stack d) { selectTab((ZDisplayable)d); } /** A method to update the given tab, creating a new DisplayablePanel for each Displayable present in the given ArrayList, and storing it in the ht_panels (which is cleared first). */ private void updateTab(final JPanel tab, final ArrayList<? extends Displayable> al) { if (null == al) return; dispatcher.exec(new Runnable() { public void run() { try { if (0 == al.size()) { tab.removeAll(); } else { Component[] comp = tab.getComponents(); int next = 0; if (1 == comp.length && comp[0].getClass() == JLabel.class) { next = 1; tab.remove(0); } // In reverse order: for (ListIterator<? extends Displayable> it = al.listIterator(al.size()); it.hasPrevious(); ) { Displayable d = it.previous(); DisplayablePanel dp = null; if (next < comp.length) { dp = (DisplayablePanel)comp[next++]; // recycling panels dp.set(d); } else { dp = new DisplayablePanel(Display.this, d); tab.add(dp); } ht_panels.put(d, dp); } if (next < comp.length) { // remove from the end, to avoid potential repaints of other panels for (int i=comp.length-1; i>=next; i--) { tab.remove(i); } } } if (null != Display.this.active) scrollToShow(Display.this.active); } catch (Throwable e) { IJError.print(e); } // invokeLater: Utils.updateComponent(tabs); }}); } static public void setActive(final Object event, final Displayable displ) { if (!(event instanceof InputEvent)) return; // find which Display for (final Display d : al_displays) { if (d.isOrigin((InputEvent)event)) { d.setActive(displ); break; } } } /** Find out whether this Display is Transforming its active Displayable. */ public boolean isTransforming() { return canvas.isTransforming(); } /** Find whether any Display is transforming the given Displayable. */ static public boolean isTransforming(final Displayable displ) { for (final Display d : al_displays) { if (null != d.active && d.active == displ && d.canvas.isTransforming()) return true; } return false; } /** Check whether the source of the event is located in this instance.*/ private boolean isOrigin(InputEvent event) { Object source = event.getSource(); // find it ... check the canvas for now TODO if (canvas == source) { return true; } return false; } /** Get the layer of the front Display, or null if none.*/ static public Layer getFrontLayer() { Display d = front; if (null == d) return null; return d.layer; } /** Get the layer of an open Display of the given Project, or null if none.*/ static public Layer getFrontLayer(final Project project) { Display df = front; if (null == df) return null; if (df.project == project) return df.layer; // else, find an open Display for the given Project, if any for (final Display d : al_displays) { if (d.project == project) { d.frame.toFront(); return d.layer; } } return null; // none found } /** Get a pointer to a Display for @param project, or null if none. */ static public Display getFront(final Project project) { Display df = front; if (null == df) return null; if (df.project == project) return df; for (final Display d : al_displays) { if (d.project == project) { d.frame.toFront(); return d; } } return null; } /** Return the list of selected Displayable objects of the front Display, or an emtpy list if no Display or none selected. */ static public List<Displayable> getSelected() { Display d = front; if (null == d) return new ArrayList<Displayable>(); return d.selection.getSelected(); } /** Return the list of selected Displayable objects of class @param c of the front Display, or an emtpy list if no Display or none selected. */ static public List<Displayable> getSelected(final Class c) { Display d = front; if (null == d) return new ArrayList<Displayable>(); return d.selection.getSelected(c); } public boolean isReadOnly() { // TEMPORARY: in the future one will be able show displays as read-only to other people, remotely return false; } protected void showPopup(Component c, int x, int y) { Display d = front; if (null == d) return; d.getPopupMenu().show(c, x, y); } /** Return a context-sensitive popup menu. */ protected JPopupMenu getPopupMenu() { // called from canvas // get the job canceling dialog if (!canvas.isInputEnabled()) { return project.getLoader().getJobsPopup(this); } // create new this.popup = new JPopupMenu(); JMenuItem item = null; JMenu menu = null; if (canvas.isTransforming()) { item = new JMenuItem("Apply transform"); item.addActionListener(this); popup.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true)); // dummy, for I don't add a MenuKeyListener, but "works" through the normal key listener. It's here to provide a visual cue item = new JMenuItem("Apply transform propagating to last layer"); item.addActionListener(this); popup.add(item); if (layer.getParent().indexOf(layer) == layer.getParent().size() -1) item.setEnabled(false); if (!(getMode().getClass() == AffineTransformMode.class || getMode().getClass() == NonLinearTransformMode.class)) item.setEnabled(false); item = new JMenuItem("Apply transform propagating to first layer"); item.addActionListener(this); popup.add(item); if (0 == layer.getParent().indexOf(layer)) item.setEnabled(false); if (!(getMode().getClass() == AffineTransformMode.class || getMode().getClass() == NonLinearTransformMode.class)) item.setEnabled(false); item = new JMenuItem("Cancel transform"); item.addActionListener(this); popup.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true)); item = new JMenuItem("Specify transform..."); item.addActionListener(this); popup.add(item); if (getMode().getClass() != AffineTransformMode.class) item.setEnabled(false); if (getMode().getClass() == ManualAlignMode.class) { final JMenuItem lexport = new JMenuItem("Export landmarks"); popup.add(lexport); final JMenuItem limport = new JMenuItem("Import landmarks"); popup.add(limport); ActionListener a = new ActionListener() { public void actionPerformed(ActionEvent ae) { ManualAlignMode mam = (ManualAlignMode)getMode(); Object source = ae.getSource(); if (lexport == source) { mam.exportLandmarks(); } else if (limport == source) { mam.importLandmarks(); } } }; lexport.addActionListener(a); limport.addActionListener(a); } return popup; } final Class aclass = null == active ? null : active.getClass(); if (null != active) { if (Profile.class == aclass) { item = new JMenuItem("Duplicate, link and send to next layer"); item.addActionListener(this); popup.add(item); Layer nl = layer.getParent().next(layer); if (nl == layer) item.setEnabled(false); item = new JMenuItem("Duplicate, link and send to previous layer"); item.addActionListener(this); popup.add(item); nl = layer.getParent().previous(layer); if (nl == layer) item.setEnabled(false); menu = new JMenu("Duplicate, link and send to"); int i = 1; for (final Layer la : layer.getParent().getLayers()) { item = new JMenuItem(i + ": z = " + la.getZ()); item.addActionListener(this); menu.add(item); // TODO should label which layers contain Profile instances linked to the one being duplicated if (la == this.layer) item.setEnabled(false); i++; } popup.add(menu); item = new JMenuItem("Duplicate, link and send to..."); item.addActionListener(this); popup.add(item); popup.addSeparator(); item = new JMenuItem("Unlink from images"); item.addActionListener(this); popup.add(item); if (!active.isLinked()) item.setEnabled(false); // isLinked() checks if it's linked to a Patch in its own layer item = new JMenuItem("Show in 3D"); item.addActionListener(this); popup.add(item); popup.addSeparator(); } else if (Patch.class == aclass) { item = new JMenuItem("Unlink from images"); item.addActionListener(this); popup.add(item); if (!active.isLinked(Patch.class)) item.setEnabled(false); if (((Patch)active).isStack()) { item = new JMenuItem("Unlink slices"); item.addActionListener(this); popup.add(item); } int n_sel_patches = selection.getSelected(Patch.class).size(); if (1 == n_sel_patches) { item = new JMenuItem("Snap"); item.addActionListener(this); popup.add(item); } else if (n_sel_patches > 1) { item = new JMenuItem("Montage"); item.addActionListener(this); popup.add(item); item = new JMenuItem("Lens correction"); item.addActionListener(this); popup.add(item); item = new JMenuItem("Blend"); item.addActionListener(this); popup.add(item); } item = new JMenuItem("Remove alpha mask"); item.addActionListener(this); popup.add(item); if ( ! ((Patch)active).hasAlphaMask()) item.setEnabled(false); item = new JMenuItem("View volume"); item.addActionListener(this); popup.add(item); HashSet<Displayable> hs = active.getLinked(Patch.class); if (null == hs || 0 == hs.size()) item.setEnabled(false); item = new JMenuItem("View orthoslices"); item.addActionListener(this); popup.add(item); if (null == hs || 0 == hs.size()) item.setEnabled(false); // if no Patch instances among the directly linked, then it's not a stack popup.addSeparator(); } else { item = new JMenuItem("Unlink"); item.addActionListener(this); popup.add(item); item = new JMenuItem("Show in 3D"); item.addActionListener(this); popup.add(item); popup.addSeparator(); } if (AreaList.class == aclass) { item = new JMenuItem("Merge"); item.addActionListener(this); popup.add(item); ArrayList<?> al = selection.getSelected(); int n = 0; for (Iterator<?> it = al.iterator(); it.hasNext(); ) { if (it.next().getClass() == AreaList.class) n++; } if (n < 2) item.setEnabled(false); popup.addSeparator(); } else if (Pipe.class == aclass) { item = new JMenuItem("Reverse point order"); item.addActionListener(this); popup.add(item); popup.addSeparator(); } else if (Treeline.class == aclass || AreaTree.class == aclass) { item = new JMenuItem("Reroot"); item.addActionListener(this); popup.add(item); item = new JMenuItem("Part subtree"); item.addActionListener(this); popup.add(item); item = new JMenuItem("Mark"); item.addActionListener(this); popup.add(item); item = new JMenuItem("Clear marks (selected Trees)"); item.addActionListener(this); popup.add(item); item = new JMenuItem("Join"); item.addActionListener(this); popup.add(item); item = new JMenuItem("Show tabular view"); item.addActionListener(this); popup.add(item); final Collection<Tree<?>> trees = (Collection<Tree<?>>)(Collection<?>)selection.getSelected(Tree.class); JMenu review = new JMenu("Review"); final JMenuItem tgenerate = new JMenuItem("Generate review stacks (selected Trees)"); review.add(tgenerate); tgenerate.setEnabled(trees.size() > 0); final JMenuItem tslab = new JMenuItem("Generate review stack for current slab"); review.add(tslab); final JMenuItem tremove = new JMenuItem("Remove reviews (selected Trees)"); review.add(tremove); tremove.setEnabled(trees.size() > 0); final JMenuItem tconnectors = new JMenuItem("View table of outgoing/incoming connectors"); review.add(tconnectors); ActionListener l = new ActionListener() { public void actionPerformed(final ActionEvent ae) { if (!Utils.check("Really " + ae.getActionCommand())) { return; } dispatcher.exec(new Runnable() { public void run() { int count = 0; for (final Tree<?> t : trees) { Utils.log("Processing " + (++count) + "/" + trees.size()); Bureaucrat bu = null; if (ae.getSource() == tgenerate) bu = t.generateAllReviewStacks(); else if (ae.getSource() == tremove) bu = t.removeReviews(); else if (ae.getSource() == tslab) { Point po = canvas.consumeLastPopupPoint(); Utils.log2(po, layer, 1.0); bu = t.generateReviewStackForSlab(po.x, po.y, Display.this.layer, 1.0); } if (null != bu) try { bu.getWorker().join(); } catch (InterruptedException ie) { return; } } } }); } }; for (JMenuItem c : new JMenuItem[]{tgenerate, tslab, tremove}) c.addActionListener(l); tconnectors.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { for (final Tree<?> t : trees) TreeConnectorsView.create(t); } }); popup.add(review); JMenu go = new JMenu("Go"); item = new JMenuItem("Previous branch point or start"); item.addActionListener(this); go.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, 0, true)); item = new JMenuItem("Next branch point or end"); item.addActionListener(this); go.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, 0, true)); item = new JMenuItem("Root"); item.addActionListener(this); go.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, 0, true)); go.addSeparator(); item = new JMenuItem("Last added point"); item.addActionListener(this); go.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, 0, true)); item = new JMenuItem("Last edited point"); item.addActionListener(this); go.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, 0, true)); popup.add(go); final String[] name = new String[]{AreaTree.class.getSimpleName(), Treeline.class.getSimpleName()}; if (Treeline.class == aclass) { String a = name[0]; name[0] = name[1]; name[1] = a; } item = new JMenuItem("Duplicate " + name[0] + " as " + name[1]); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Bureaucrat.createAndStart(new Worker.Task("Converting") { public void exec() { try { getLayerSet().addChangeTreesStep(); Tree.duplicateAs(selection.getSelected(), Treeline.class == aclass ? AreaTree.class : Treeline.class); getLayerSet().addChangeTreesStep(); } catch (Exception e) { IJError.print(e); } } }, getProject()); } }); popup.add(item); popup.addSeparator(); } else if (Connector.class == aclass) { item = new JMenuItem("Merge"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { if (null == getActive() || getActive().getClass() != Connector.class) { Utils.log("Active object must be a Connector!"); return; } final List<Connector> col = (List<Connector>)(List) selection.getSelected(Connector.class); if (col.size() < 2) { Utils.log("Select more than one Connector!"); return; } if (col.get(0) != getActive()) { if (col.remove(getActive())) { col.add(0, (Connector)getActive()); } else { Utils.log("ERROR: cannot find active object in selection list!"); return; } } Bureaucrat.createAndStart(new Worker.Task("Merging connectors") { public void exec() { getLayerSet().addChangeTreesStep(); Connector base = null; try { base = Connector.merge(col); } catch (Exception e) { IJError.print(e); } if (null == base) { Utils.log("ERROR: could not merge connectors!"); getLayerSet().undoOneStep(); } else { getLayerSet().addChangeTreesStep(); } Display.repaint(); } }, getProject()); } }); popup.add(item); item.setEnabled(selection.getSelected(Connector.class).size() > 1); } item = new JMenuItem("Duplicate"); item.addActionListener(this); popup.add(item); item = new JMenuItem("Color..."); item.addActionListener(this); popup.add(item); if (active instanceof LayerSet) item.setEnabled(false); if (active.isLocked()) { item = new JMenuItem("Unlock"); item.addActionListener(this); popup.add(item); } else { item = new JMenuItem("Lock"); item.addActionListener(this); popup.add(item); } menu = new JMenu("Move"); popup.addSeparator(); LayerSet ls = layer.getParent(); item = new JMenuItem("Move to top"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0, true)); // this is just to draw the key name by the menu; it does not incur on any event being generated (that I know if), and certainly not any event being listened to by TrakEM2. if (ls.isTop(active)) item.setEnabled(false); item = new JMenuItem("Move up"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0, true)); if (ls.isTop(active)) item.setEnabled(false); item = new JMenuItem("Move down"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0, true)); if (ls.isBottom(active)) item.setEnabled(false); item = new JMenuItem("Move to bottom"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_END, 0, true)); if (ls.isBottom(active)) item.setEnabled(false); popup.add(menu); popup.addSeparator(); item = new JMenuItem("Delete..."); item.addActionListener(this); popup.add(item); try { if (Patch.class == aclass) { if (!active.isOnlyLinkedTo(Patch.class)) { item.setEnabled(false); } } } catch (Exception e) { IJError.print(e); item.setEnabled(false); } if (Patch.class == aclass) { item = new JMenuItem("Revert"); item.addActionListener(this); popup.add(item); if ( null == ((Patch)active).getOriginalPath()) item.setEnabled(false); popup.addSeparator(); } item = new JMenuItem("Properties..."); item.addActionListener(this); popup.add(item); item = new JMenuItem("Show centered"); item.addActionListener(this); popup.add(item); popup.addSeparator(); if (! (active instanceof ZDisplayable)) { int i_layer = layer.getParent().indexOf(layer); int n_layers = layer.getParent().size(); item = new JMenuItem("Send to previous layer"); item.addActionListener(this); popup.add(item); if (1 == n_layers || 0 == i_layer || active.isLinked()) item.setEnabled(false); // check if the active is a profile and contains a link to another profile in the layer it is going to be sent to, or it is linked else if (active instanceof Profile && !active.canSendTo(layer.getParent().previous(layer))) item.setEnabled(false); item = new JMenuItem("Send to next layer"); item.addActionListener(this); popup.add(item); if (1 == n_layers || n_layers -1 == i_layer || active.isLinked()) item.setEnabled(false); else if (active instanceof Profile && !active.canSendTo(layer.getParent().next(layer))) item.setEnabled(false); menu = new JMenu("Send linked group to..."); if (active.hasLinkedGroupWithinLayer(this.layer)) { int i = 1; for (final Layer la : ls.getLayers()) { String layer_title = i + ": " + la.getTitle(); if (-1 == layer_title.indexOf(' ')) layer_title += " "; item = new JMenuItem(layer_title); item.addActionListener(this); menu.add(item); if (la == this.layer) item.setEnabled(false); i++; } popup.add(menu); } else { menu.setEnabled(false); //Utils.log("Active's linked group not within layer."); } popup.add(menu); popup.addSeparator(); } } item = new JMenuItem("Undo");item.addActionListener(this); popup.add(item); if (!layer.getParent().canUndo() || canvas.isTransforming()) item.setEnabled(false); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Utils.getControlModifier(), true)); item = new JMenuItem("Redo");item.addActionListener(this); popup.add(item); if (!layer.getParent().canRedo() || canvas.isTransforming()) item.setEnabled(false); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Event.SHIFT_MASK | Event.CTRL_MASK, true)); popup.addSeparator(); // Would get so much simpler with a clojure macro ... try { menu = new JMenu("Hide/Unhide"); item = new JMenuItem("Hide deselected"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, Event.SHIFT_MASK, true)); boolean none = 0 == selection.getNSelected(); if (none) item.setEnabled(false); item = new JMenuItem("Hide deselected except images"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, Event.SHIFT_MASK | Event.ALT_MASK, true)); if (none) item.setEnabled(false); item = new JMenuItem("Hide selected"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, 0, true)); if (none) item.setEnabled(false); none = ! layer.getParent().containsDisplayable(DLabel.class); item = new JMenuItem("Hide all labels"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); item = new JMenuItem("Unhide all labels"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); none = ! layer.getParent().contains(AreaList.class); item = new JMenuItem("Hide all arealists"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); item = new JMenuItem("Unhide all arealists"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); none = ! layer.contains(Profile.class); item = new JMenuItem("Hide all profiles"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); item = new JMenuItem("Unhide all profiles"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); none = ! layer.getParent().contains(Pipe.class); item = new JMenuItem("Hide all pipes"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); item = new JMenuItem("Unhide all pipes"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); none = ! layer.getParent().contains(Polyline.class); item = new JMenuItem("Hide all polylines"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); item = new JMenuItem("Unhide all polylines"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); none = ! layer.getParent().contains(Treeline.class); item = new JMenuItem("Hide all treelines"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); item = new JMenuItem("Unhide all treelines"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); none = ! layer.getParent().contains(AreaTree.class); item = new JMenuItem("Hide all areatrees"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); item = new JMenuItem("Unhide all areatrees"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); none = ! layer.getParent().contains(Ball.class); item = new JMenuItem("Hide all balls"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); item = new JMenuItem("Unhide all balls"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); none = ! layer.getParent().contains(Connector.class); item = new JMenuItem("Hide all connectors"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); item = new JMenuItem("Unhide all connectors"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); none = ! layer.getParent().containsDisplayable(Patch.class); item = new JMenuItem("Hide all images"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); item = new JMenuItem("Unhide all images"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); item = new JMenuItem("Hide all but images"); item.addActionListener(this); menu.add(item); item = new JMenuItem("Unhide all"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, Event.ALT_MASK, true)); popup.add(menu); } catch (Exception e) { IJError.print(e); } // plugins, if any Utils.addPlugIns(popup, "Display", project, new Callable<Displayable>() { public Displayable call() { return Display.this.getActive(); }}); JMenu align_menu = new JMenu("Align"); item = new JMenuItem("Align stack slices"); item.addActionListener(this); align_menu.add(item); if (selection.isEmpty() || ! (getActive().getClass() == Patch.class && ((Patch)getActive()).isStack())) item.setEnabled(false); item = new JMenuItem("Align layers"); item.addActionListener(this); align_menu.add(item); if (1 == layer.getParent().size()) item.setEnabled(false); item = new JMenuItem("Align layers with manual landmarks"); item.addActionListener(this); align_menu.add(item); if (1 == layer.getParent().size()) item.setEnabled(false); item = new JMenuItem("Align multi-layer mosaic"); item.addActionListener(this); align_menu.add(item); if (1 == layer.getParent().size()) item.setEnabled(false); item = new JMenuItem("Montage all images in this layer"); item.addActionListener(this); align_menu.add(item); if (layer.getDisplayables(Patch.class).size() < 2) item.setEnabled(false); item = new JMenuItem("Montage selected images (SIFT)"); item.addActionListener(this); align_menu.add(item); if (selection.getSelected(Patch.class).size() < 2) item.setEnabled(false); item = new JMenuItem("Montage selected images (phase correlation)"); item.addActionListener(this); align_menu.add(item); if (selection.getSelected(Patch.class).size() < 2) item.setEnabled(false); item = new JMenuItem("Montage multiple layers (phase correlation)"); item.addActionListener(this); align_menu.add(item); popup.add(align_menu); item = new JMenuItem("Montage multiple layers (SIFT)"); item.addActionListener(this); align_menu.add(item); popup.add(align_menu); JMenuItem st = new JMenu("Transform"); StartTransformMenuListener tml = new StartTransformMenuListener(); item = new JMenuItem("Transform (affine)"); item.addActionListener(tml); st.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, 0, true)); if (null == active) item.setEnabled(false); item = new JMenuItem("Transform (non-linear)"); item.addActionListener(tml); st.add(item); if (null == active) item.setEnabled(false); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, Event.SHIFT_MASK, true)); item = new JMenuItem("Cancel transform"); st.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true)); item.setEnabled(false); // just added as a self-documenting cue; no listener item = new JMenuItem("Remove rotation, scaling and shear (selected images)"); item.addActionListener(tml); st.add(item); if (null == active) item.setEnabled(false); item = new JMenuItem("Remove rotation, scaling and shear layer-wise"); item.addActionListener(tml); st.add(item); item = new JMenuItem("Remove coordinate transforms (selected images)"); item.addActionListener(tml); st.add(item); if (null == active) item.setEnabled(false); item = new JMenuItem("Remove coordinate transforms layer-wise"); item.addActionListener(tml); st.add(item); popup.add(st); JMenu link_menu = new JMenu("Link"); item = new JMenuItem("Link images..."); item.addActionListener(this); link_menu.add(item); item = new JMenuItem("Unlink all selected images"); item.addActionListener(this); link_menu.add(item); item.setEnabled(selection.getSelected(Patch.class).size() > 0); item = new JMenuItem("Unlink all"); item.addActionListener(this); link_menu.add(item); popup.add(link_menu); JMenu adjust_menu = new JMenu("Adjust images"); item = new JMenuItem("Enhance contrast layer-wise..."); item.addActionListener(this); adjust_menu.add(item); item = new JMenuItem("Enhance contrast (selected images)..."); item.addActionListener(this); adjust_menu.add(item); if (selection.isEmpty()) item.setEnabled(false); item = new JMenuItem("Set Min and Max layer-wise..."); item.addActionListener(this); adjust_menu.add(item); item = new JMenuItem("Set Min and Max (selected images)..."); item.addActionListener(this); adjust_menu.add(item); if (selection.isEmpty()) item.setEnabled(false); item = new JMenuItem("Adjust min and max (selected images)..."); item.addActionListener(this); adjust_menu.add(item); if (selection.isEmpty()) item.setEnabled(false); item = new JMenuItem("Mask image borders (layer-wise)..."); item.addActionListener(this); adjust_menu.add(item); item = new JMenuItem("Mask image borders (selected images)..."); item.addActionListener(this); adjust_menu.add(item); if (selection.isEmpty()) item.setEnabled(false); popup.add(adjust_menu); JMenu script = new JMenu("Script"); MenuScriptListener msl = new MenuScriptListener(); item = new JMenuItem("Set preprocessor script layer-wise..."); item.addActionListener(msl); script.add(item); item = new JMenuItem("Set preprocessor script (selected images)..."); item.addActionListener(msl); script.add(item); if (selection.isEmpty()) item.setEnabled(false); item = new JMenuItem("Remove preprocessor script layer-wise..."); item.addActionListener(msl); script.add(item); item = new JMenuItem("Remove preprocessor script (selected images)..."); item.addActionListener(msl); script.add(item); if (selection.isEmpty()) item.setEnabled(false); popup.add(script); menu = new JMenu("Import"); item = new JMenuItem("Import image"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.ALT_MASK & Event.SHIFT_MASK, true)); item = new JMenuItem("Import stack..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Import stack with landmarks..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Import grid..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Import sequence as grid..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Import from text file..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Import labels as arealists..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Tags ..."); item.addActionListener(this); menu.add(item); popup.add(menu); menu = new JMenu("Export"); final boolean has_arealists = layer.getParent().contains(AreaList.class); item = new JMenuItem("Make flat image..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Arealists as labels (tif)"); item.addActionListener(this); menu.add(item); item.setEnabled(has_arealists); item = new JMenuItem("Arealists as labels (amira)"); item.addActionListener(this); menu.add(item); item.setEnabled(has_arealists); item = new JMenuItem("Image stack under selected Arealist"); item.addActionListener(this); menu.add(item); item.setEnabled(null != active && AreaList.class == active.getClass()); item = new JMenuItem("Fly through selected Treeline/AreaTree"); item.addActionListener(this); menu.add(item); item.setEnabled(null != active && Tree.class.isInstance(active)); item = new JMenuItem("Tags..."); item.addActionListener(this); menu.add(item); popup.add(menu); menu = new JMenu("Display"); item = new JMenuItem("Resize canvas/LayerSet..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Autoresize canvas/LayerSet"); item.addActionListener(this); menu.add(item); item = new JMenuItem("Properties ..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Calibration..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Grid overlay..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Adjust snapping parameters..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Adjust fast-marching parameters..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Adjust arealist paint parameters..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Show current 2D position in 3D"); item.addActionListener(this); menu.add(item); item = new JMenuItem("Show layers as orthoslices in 3D"); item.addActionListener(this); menu.add(item); popup.add(menu); menu = new JMenu("Project"); this.project.getLoader().setupMenuItems(menu, this.getProject()); item = new JMenuItem("Project properties..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Create subproject"); item.addActionListener(this); menu.add(item); if (null == canvas.getFakeImagePlus().getRoi()) item.setEnabled(false); item = new JMenuItem("Release memory..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Flush image cache"); item.addActionListener(this); menu.add(item); item = new JMenuItem("Regenerate all mipmaps"); item.addActionListener(this); menu.add(item); item = new JMenuItem("Regenerate mipmaps (selected images)"); item.addActionListener(this); menu.add(item); popup.add(menu); menu = new JMenu("Selection"); item = new JMenuItem("Select all"); item.addActionListener(this); menu.add(item); item = new JMenuItem("Select all visible"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, Utils.getControlModifier(), true)); if (0 == layer.getDisplayableList().size() && 0 == layer.getParent().getDisplayableList().size()) item.setEnabled(false); item = new JMenuItem("Select none"); item.addActionListener(this); menu.add(item); if (0 == selection.getNSelected()) item.setEnabled(false); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true)); JMenu bytype = new JMenu("Select all by type"); item = new JMenuItem("AreaList"); item.addActionListener(bytypelistener); bytype.add(item); item = new JMenuItem("AreaTree"); item.addActionListener(bytypelistener); bytype.add(item); item = new JMenuItem("Ball"); item.addActionListener(bytypelistener); bytype.add(item); item = new JMenuItem("Connector"); item.addActionListener(bytypelistener); bytype.add(item); item = new JMenuItem("Dissector"); item.addActionListener(bytypelistener); bytype.add(item); item = new JMenuItem("Image"); item.addActionListener(bytypelistener); bytype.add(item); item = new JMenuItem("Pipe"); item.addActionListener(bytypelistener); bytype.add(item); item = new JMenuItem("Polyline"); item.addActionListener(bytypelistener); bytype.add(item); item = new JMenuItem("Profile"); item.addActionListener(bytypelistener); bytype.add(item); item = new JMenuItem("Text"); item.addActionListener(bytypelistener); bytype.add(item); item = new JMenuItem("Treeline"); item.addActionListener(bytypelistener); bytype.add(item); menu.add(bytype); item = new JMenuItem("Restore selection"); item.addActionListener(this); menu.add(item); item = new JMenuItem("Select under ROI"); item.addActionListener(this); menu.add(item); if (canvas.getFakeImagePlus().getRoi() == null) item.setEnabled(false); JMenu graph = new JMenu("Graph"); GraphMenuListener gl = new GraphMenuListener(); item = new JMenuItem("Select outgoing Connectors"); item.addActionListener(gl); graph.add(item); item = new JMenuItem("Select incoming Connectors"); item.addActionListener(gl); graph.add(item); item = new JMenuItem("Select downstream targets"); item.addActionListener(gl); graph.add(item); item = new JMenuItem("Select upstream targets"); item.addActionListener(gl); graph.add(item); graph.setEnabled(!selection.isEmpty()); menu.add(graph); popup.add(menu); menu = new JMenu("Tool"); item = new JMenuItem("Rectangular ROI"); item.addActionListener(new SetToolListener(Toolbar.RECTANGLE)); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0, true)); item = new JMenuItem("Polygon ROI"); item.addActionListener(new SetToolListener(Toolbar.POLYGON)); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0, true)); item = new JMenuItem("Freehand ROI"); item.addActionListener(new SetToolListener(Toolbar.FREEROI)); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0, true)); item = new JMenuItem("Text"); item.addActionListener(new SetToolListener(Toolbar.TEXT)); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0, true)); item = new JMenuItem("Magnifier glass"); item.addActionListener(new SetToolListener(Toolbar.MAGNIFIER)); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0, true)); item = new JMenuItem("Hand"); item.addActionListener(new SetToolListener(Toolbar.HAND)); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0, true)); item = new JMenuItem("Select"); item.addActionListener(new SetToolListener(ProjectToolbar.SELECT)); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0, true)); item = new JMenuItem("Pencil"); item.addActionListener(new SetToolListener(ProjectToolbar.PENCIL)); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F10, 0, true)); item = new JMenuItem("Pen"); item.addActionListener(new SetToolListener(ProjectToolbar.PEN)); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0, true)); popup.add(menu); item = new JMenuItem("Search..."); item.addActionListener(this); popup.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, Utils.getControlModifier(), true)); //canvas.add(popup); return popup; } private final class GraphMenuListener implements ActionListener { public void actionPerformed(ActionEvent ae) { final String command = ae.getActionCommand(); final Collection<Displayable> sel = selection.getSelected(); if (null == sel || sel.isEmpty()) return; Bureaucrat.createAndStart(new Worker.Task(command) { public void exec() { final Collection<Connector> connectors = (Collection<Connector>) (Collection) getLayerSet().getZDisplayables(Connector.class); final HashSet<Displayable> to_select = new HashSet<Displayable>(); if (command.equals("Select outgoing Connectors")) { for (final Connector con : connectors) { Set<Displayable> origins = con.getOrigins(); origins.retainAll(sel); if (origins.isEmpty()) continue; to_select.add(con); } } else if (command.equals("Select incoming Connectors")) { for (final Connector con : connectors) { for (final Set<Displayable> targets : con.getTargets()) { targets.retainAll(sel); if (targets.isEmpty()) continue; to_select.add(con); } } } else if (command.equals("Select downstream targets")) { for (final Connector con : connectors) { Set<Displayable> origins = con.getOrigins(); origins.retainAll(sel); if (origins.isEmpty()) continue; // else, add all targets for (final Set<Displayable> targets : con.getTargets()) { to_select.addAll(targets); } } } else if (command.equals("Select upstream targets")) { for (final Connector con : connectors) { for (final Set<Displayable> targets : con.getTargets()) { targets.retainAll(sel); if (targets.isEmpty()) continue; to_select.addAll(con.getOrigins()); break; // origins will be the same for all targets of 'con' } } } selection.selectAll(new ArrayList<Displayable>(to_select)); }}, Display.this.project); } } protected class GridOverlay { ArrayList<Line2D> lines = new ArrayList<Line2D>(); int ox=0, oy=0, width=(int)layer.getLayerWidth(), height=(int)layer.getLayerHeight(), xoffset=0, yoffset=0, tilewidth=100, tileheight=100, linewidth=1; boolean visible = true; Color color = new Color(255,255,0,255); // yellow with full alpha /** Expects values in pixels. */ void init() { lines.clear(); // Vertical lines: if (0 != xoffset) { lines.add(new Line2D.Float(ox, oy, ox, oy+height)); } lines.add(new Line2D.Float(ox+width, oy, ox+width, oy+height)); for (int x = ox + xoffset; x <= ox + width; x += tilewidth) { lines.add(new Line2D.Float(x, oy, x, oy + height)); } // Horizontal lines: if (0 != yoffset) { lines.add(new Line2D.Float(ox, oy, ox+width, oy)); } lines.add(new Line2D.Float(ox, oy+height, ox+width, oy+height)); for (int y = oy + yoffset; y <= oy + height; y += tileheight) { lines.add(new Line2D.Float(ox, y, ox + width, y)); } } protected void paint(final Graphics2D g) { if (!visible) return; g.setStroke(new BasicStroke((float)(linewidth/canvas.getMagnification()))); g.setColor(color); for (final Line2D line : lines) { g.draw(line); } } void setup(Roi roi) { GenericDialog gd = new GenericDialog("Grid overlay"); Calibration cal = getLayerSet().getCalibration(); gd.addNumericField("Top-left corner X:", ox*cal.pixelWidth, 1, 10, cal.getUnits()); gd.addNumericField("Top-left corner Y:", oy*cal.pixelHeight, 1, 10, cal.getUnits()); gd.addNumericField("Grid total width:", width*cal.pixelWidth, 1, 10, cal.getUnits()); gd.addNumericField("Grid total height:", height*cal.pixelHeight, 1, 10, cal.getUnits()); gd.addCheckbox("Read bounds from ROI", null != roi); ((Component)gd.getCheckboxes().get(0)).setEnabled(null != roi); gd.addMessage(""); gd.addNumericField("Tile width:", tilewidth*cal.pixelWidth, 1, 10, cal.getUnits()); gd.addNumericField("Tile height:", tileheight*cal.pixelHeight, 1, 10, cal.getUnits()); gd.addNumericField("Tile offset X:", xoffset*cal.pixelWidth, 1, 10, cal.getUnits()); gd.addNumericField("Tile offset Y:", yoffset*cal.pixelHeight, 1, 10, cal.getUnits()); gd.addMessage(""); gd.addNumericField("Line width:", linewidth, 1, 10, "pixels"); gd.addSlider("Red: ", 0, 255, color.getRed()); gd.addSlider("Green: ", 0, 255, color.getGreen()); gd.addSlider("Blue: ", 0, 255, color.getBlue()); gd.addSlider("Alpha: ", 0, 255, color.getAlpha()); gd.addMessage(""); gd.addCheckbox("Visible", visible); gd.showDialog(); if (gd.wasCanceled()) return; this.ox = (int)(gd.getNextNumber() / cal.pixelWidth); this.oy = (int)(gd.getNextNumber() / cal.pixelHeight); this.width = (int)(gd.getNextNumber() / cal.pixelWidth); this.height = (int)(gd.getNextNumber() / cal.pixelHeight); if (gd.getNextBoolean() && null != roi) { Rectangle r = roi.getBounds(); this.ox = r.x; this.oy = r.y; this.width = r.width; this.height = r.height; } this.tilewidth = (int)(gd.getNextNumber() / cal.pixelWidth); this.tileheight = (int)(gd.getNextNumber() / cal.pixelHeight); this.xoffset = (int)(gd.getNextNumber() / cal.pixelWidth) % tilewidth; this.yoffset = (int)(gd.getNextNumber() / cal.pixelHeight) % tileheight; this.linewidth = (int)gd.getNextNumber(); this.color = new Color((int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber()); this.visible = gd.getNextBoolean(); init(); } } protected GridOverlay gridoverlay = null; private class StartTransformMenuListener implements ActionListener { public void actionPerformed(ActionEvent ae) { if (null == active) return; String command = ae.getActionCommand(); if (command.equals("Transform (affine)")) { getLayerSet().addTransformStepWithData(selection.getAffected()); setMode(new AffineTransformMode(Display.this)); } else if (command.equals("Transform (non-linear)")) { getLayerSet().addTransformStepWithData(selection.getAffected()); List<Displayable> col = selection.getSelected(Patch.class); for (final Displayable d : col) { if (d.isLinked()) { Utils.showMessage("Can't enter manual non-linear transformation mode:\nat least one image is linked."); return; } } setMode(new NonLinearTransformMode(Display.this, col)); } else if (command.equals("Remove coordinate transforms (selected images)")) { final List<Displayable> col = selection.getSelected(Patch.class); if (col.isEmpty()) return; removeCoordinateTransforms( (List<Patch>) (List) col); } else if (command.equals("Remove coordinate transforms layer-wise")) { GenericDialog gd = new GenericDialog("Remove Coordinate Transforms"); gd.addMessage("Remove coordinate transforms"); gd.addMessage("for all images in:"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; final ArrayList<Displayable> patches = new ArrayList<Displayable>(); for (final Layer layer : getLayerSet().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex()+1)) { patches.addAll(layer.getDisplayables(Patch.class)); } removeCoordinateTransforms( (List<Patch>) (List) patches); } else if (command.equals("Remove rotation, scaling and shear (selected images)")) { final List<Displayable> col = selection.getSelected(Patch.class); if (col.isEmpty()) return; removeScalingRotationShear( (List<Patch>) (List) col); } else if (command.equals("Remove rotation, scaling and shear layer-wise")) { // Because we love copy-paste GenericDialog gd = new GenericDialog("Remove Scaling/Rotation/Shear"); gd.addMessage("Remove scaling, translation"); gd.addMessage("and shear for all images in:"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; final ArrayList<Displayable> patches = new ArrayList<Displayable>(); for (final Layer layer : getLayerSet().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex()+1)) { patches.addAll(layer.getDisplayables(Patch.class)); } removeScalingRotationShear( (List<Patch>) (List) patches); } } } public Bureaucrat removeScalingRotationShear(final List<Patch> patches) { return Bureaucrat.createAndStart(new Worker.Task("Removing coordinate transforms") { public void exec() { getLayerSet().addTransformStep(patches); for (final Patch p : patches) { Rectangle box = p.getBoundingBox(); final AffineTransform aff = new AffineTransform(); // translate so that the center remains where it is aff.setToTranslation(box.x + (box.width - p.getWidth())/2, box.y + (box.height - p.getHeight())/2); p.setAffineTransform(aff); } getLayerSet().addTransformStep(patches); Display.repaint(); }}, this.project); } public Bureaucrat removeCoordinateTransforms(final List<Patch> patches) { return Bureaucrat.createAndStart(new Worker.Task("Removing coordinate transforms") { public void exec() { // Check if any are linked: cannot remove, would break image-to-segmentation relationship for (final Patch p : patches) { if (p.isLinked()) { Utils.logAll("Cannot remove coordinate transform: some images are linked to segmentations!"); return; } } // Collect Patch instances to modify: final HashSet<Patch> ds = new HashSet<Patch>(patches); for (final Patch p : patches) { if (null != p.getCoordinateTransform()) { ds.add(p); } } // Add undo step: getLayerSet().addDataEditStep(ds); // Remove coordinate transforms: final ArrayList<Future> fus = new ArrayList<Future>(); for (final Patch p : ds) { p.setCoordinateTransform(null); fus.add(p.getProject().getLoader().regenerateMipMaps(p)); // queue } // wait until all done for (Future fu : fus) try { fu.get(); } catch (Exception e) { IJError.print(e); } // Set current state getLayerSet().addDataEditStep(ds); }}, project); } private class MenuScriptListener implements ActionListener { public void actionPerformed(ActionEvent ae) { final String command = ae.getActionCommand(); Bureaucrat.createAndStart(new Worker.Task("Setting preprocessor script") { public void exec() { try{ if (command.equals("Set preprocessor script layer-wise...")) { Collection<Layer> ls = getLayerList("Set preprocessor script"); if (null == ls) return; String path = getScriptPath(); if (null == path) return; setScriptPathToLayers(ls, path); } else if (command.equals("Set preprocessor script (selected images)...")) { if (selection.isEmpty()) return; String path = getScriptPath(); if (null == path) return; - setScriptPath(selection.getSelected(Patch.class), path); + setScriptPath(selection.get(Patch.class), path); } else if (command.equals("Remove preprocessor script layer-wise...")) { Collection<Layer> ls = getLayerList("Remove preprocessor script"); if (null == ls) return; setScriptPathToLayers(ls, null); } else if (command.equals("Remove preprocessor script (selected images)...")) { if (selection.isEmpty()) return; - setScriptPath(selection.getSelected(Patch.class), null); + setScriptPath(selection.get(Patch.class), null); } } catch (Exception e) { IJError.print(e); } }}, Display.this.project); } private void setScriptPathToLayers(final Collection<Layer> ls, final String script) throws Exception { final ArrayList<Patch> ds = new ArrayList<Patch>(); for (final Layer la : ls) { if (Thread.currentThread().isInterrupted()) return; ds.addAll(la.getAll(Patch.class)); } setScriptPath(ds, script); // no lazy sequences ... } /** Accepts null script, to remove it if there. */ private void setScriptPath(final Collection<Patch> list, final String script) throws Exception { Process.progressive(list, new TaskFactory<Patch,Object>() { public Object process(final Patch p) { p.setPreprocessorScriptPath(script); try { p.updateMipMaps().get(); // wait for mipmap regeneration so that the processed image is in cache for mipmap regeneration } catch (Throwable t) { IJError.print(t); } return null; } }, Math.max(1, Runtime.getRuntime().availableProcessors() -1)); } private Collection<Layer> getLayerList(String title) { final GenericDialog gd = new GenericDialog(title); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.showDialog(); if (gd.wasCanceled()) return null; return layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1); // exclusive end } private String getScriptPath() { OpenDialog od = new OpenDialog("Select script", OpenDialog.getLastDirectory(), null); String dir = od.getDirectory(); if (null == dir) return null; if (IJ.isWindows()) dir = dir.replace('\\','/'); if (!dir.endsWith("/")) dir += "/"; return dir + od.getFileName(); } } private class SetToolListener implements ActionListener { final int tool; SetToolListener(int tool) { this.tool = tool; } public void actionPerformed(ActionEvent ae) { ProjectToolbar.setTool(tool); toolbar_panel.repaint(); } } private ByTypeListener bytypelistener = new ByTypeListener(this); static private class ByTypeListener implements ActionListener { final Display d; ByTypeListener(final Display d) { this.d = d; } public void actionPerformed(final ActionEvent ae) { final String command = ae.getActionCommand(); final Area aroi = M.getArea(d.canvas.getFakeImagePlus().getRoi()); d.dispatcher.exec(new Runnable() { public void run() { try { String type = command; if (type.equals("Image")) type = "Patch"; else if (type.equals("Text")) type = "DLabel"; Class c = Class.forName("ini.trakem2.display." + type); java.util.List<Displayable> a = new ArrayList<Displayable>(); if (null != aroi) { a.addAll(d.layer.getDisplayables(c, aroi, true)); a.addAll(d.layer.getParent().findZDisplayables(c, d.layer, aroi, true, true)); } else { a.addAll(d.layer.getDisplayables(c)); a.addAll(d.layer.getParent().getZDisplayables(c)); // Remove non-visible ones for (final Iterator<Displayable> it = a.iterator(); it.hasNext(); ) { if (!it.next().isVisible()) it.remove(); } } if (0 == a.size()) return; boolean selected = false; if (0 == ae.getModifiers()) { Utils.log2("first"); d.selection.clear(); d.selection.selectAll(a); selected = true; } else if (0 == (ae.getModifiers() ^ Event.SHIFT_MASK)) { Utils.log2("with shift"); d.selection.selectAll(a); // just add them to the current selection selected = true; } if (selected) { // Activate last: d.selection.setActive(a.get(a.size() -1)); } } catch (ClassNotFoundException e) { Utils.log2(e.toString()); } }}); } } /** Check if a panel for the given Displayable is completely visible in the JScrollPane */ public boolean isWithinViewport(final Displayable d) { Component comp = tabs.getSelectedComponent(); if (!(comp instanceof JScrollPane)) return false; final JScrollPane scroll = (JScrollPane)tabs.getSelectedComponent(); if (ht_tabs.get(d.getClass()) == scroll) return isWithinViewport(scroll, ht_panels.get(d)); return false; } private boolean isWithinViewport(JScrollPane scroll, DisplayablePanel dp) { if(null == dp) return false; JViewport view = scroll.getViewport(); java.awt.Dimension dimensions = view.getExtentSize(); java.awt.Point p = view.getViewPosition(); int y = dp.getY(); if ((y + DisplayablePanel.HEIGHT - p.y) <= dimensions.height && y >= p.y) { return true; } return false; } /** Check if a panel for the given Displayable is partially visible in the JScrollPane */ public boolean isPartiallyWithinViewport(final Displayable d) { final JScrollPane scroll = ht_tabs.get(d.getClass()); if (tabs.getSelectedComponent() == scroll) return isPartiallyWithinViewport(scroll.getViewport(), ht_panels.get(d)); return false; } /** Check if a panel for the given Displayable is at least partially visible in the JScrollPane */ private boolean isPartiallyWithinViewport(final JViewport view, final DisplayablePanel dp) { if(null == dp) { //Utils.log2("Display.isPartiallyWithinViewport: null DisplayablePanel ??"); return false; // to fast for you baby } final int vheight = view.getExtentSize().height, py = view.getViewPosition().y, y = dp.getY(); // Test if not outside view return !(y + DisplayablePanel.HEIGHT < py || y > py + vheight); } /** A function to make a Displayable panel be visible in the screen, by scrolling the viewport of the JScrollPane. */ private void scrollToShow(final Displayable d) { if (!(tabs.getSelectedComponent() instanceof JScrollPane)) return; dispatcher.execSwing(new Runnable() { public void run() { final JScrollPane scroll = (JScrollPane)tabs.getSelectedComponent(); if (d instanceof ZDisplayable && scroll == scroll_zdispl) { scrollToShow(scroll_zdispl, ht_panels.get(d)); return; } final Class c = d.getClass(); if (Patch.class == c && scroll == scroll_patches) { scrollToShow(scroll_patches, ht_panels.get(d)); } else if (DLabel.class == c && scroll == scroll_labels) { scrollToShow(scroll_labels, ht_panels.get(d)); } else if (Profile.class == c && scroll == scroll_profiles) { scrollToShow(scroll_profiles, ht_panels.get(d)); } }}); } private void scrollToShow(final JScrollPane scroll, final JPanel dp) { if (null == dp) return; JViewport view = scroll.getViewport(); Point current = view.getViewPosition(); Dimension extent = view.getExtentSize(); int panel_y = dp.getY(); if ((panel_y + DisplayablePanel.HEIGHT - current.y) <= extent.height && panel_y >= current.y) { // it's completely visible already return; } else { // scroll just enough // if it's above, show at the top if (panel_y - current.y < 0) { view.setViewPosition(new Point(0, panel_y)); } // if it's below (even if partially), show at the bottom else if (panel_y + 50 > current.y + extent.height) { view.setViewPosition(new Point(0, panel_y - extent.height + 50)); //Utils.log("Display.scrollToShow: panel_y: " + panel_y + " current.y: " + current.y + " extent.height: " + extent.height); } } } /** Update the title of the given Displayable in its DisplayablePanel, if any. */ static public void updateTitle(final Layer layer, final Displayable displ) { for (final Display d : al_displays) { if (layer == d.layer) { DisplayablePanel dp = d.ht_panels.get(displ); if (null != dp) dp.updateTitle(); } } } /** Update the Display's title in all Displays showing the given Layer. */ static public void updateTitle(final Layer layer) { for (final Display d : al_displays) { if (d.layer == layer) d.updateFrameTitle(); } } static public void updateTitle(final Project project) { for (final Display d : al_displays) { if (d.project == project) d.updateFrameTitle(); } } /** Update the Display's title in all Displays showing a Layer of the given LayerSet. */ static public void updateTitle(final LayerSet ls) { for (final Display d : al_displays) { if (d.layer.getParent() == ls) d.updateFrameTitle(d.layer); } } /** Set a new title in the JFrame, showing info on the layer 'z' and the magnification. */ public void updateFrameTitle() { updateFrameTitle(layer); } private void updateFrameTitle(Layer layer) { // From ij.ImagePlus class, the solution: String scale = ""; final double magnification = canvas.getMagnification(); if (magnification!=1.0) { final double percent = magnification*100.0; scale = new StringBuilder(" (").append(Utils.d2s(percent, percent==(int)percent ? 0 : 1)).append("%)").toString(); } final Calibration cal = layer.getParent().getCalibration(); String title = new StringBuilder().append(layer.getParent().indexOf(layer) + 1).append('/').append(layer.getParent().size()).append(' ').append((null == layer.getTitle() ? "" : layer.getTitle())).append(scale).append(" -- ").append(getProject().toString()).append(' ').append(' ').append(Utils.cutNumber(layer.getParent().getLayerWidth() * cal.pixelWidth, 2, true)).append('x').append(Utils.cutNumber(layer.getParent().getLayerHeight() * cal.pixelHeight, 2, true)).append(' ').append(cal.getUnit()).toString(); frame.setTitle(title); // fix the title for the FakeImageWindow and thus the WindowManager listing in the menus canvas.getFakeImagePlus().setTitle(title); } /** If shift is down, scroll to the next non-empty layer; otherwise, if scroll_step is larger than 1, then scroll 'scroll_step' layers ahead; else just the next Layer. */ public void nextLayer(final int modifiers) { final Layer l; if (0 == (modifiers ^ Event.SHIFT_MASK)) { l = layer.getParent().nextNonEmpty(layer); } else if (scroll_step > 1) { int i = layer.getParent().indexOf(this.layer); Layer la = layer.getParent().getLayer(i + scroll_step); if (null != la) l = la; else l = null; } else { l = layer.getParent().next(layer); } if (l != layer) { slt.set(l); updateInDatabase("layer_id"); } } private final void translateLayerColors(final Layer current, final Layer other) { if (current == other) return; if (layer_channels.size() > 0) { final LayerSet ls = getLayerSet(); // translate colors by distance from current layer to new Layer l final int dist = ls.indexOf(other) - ls.indexOf(current); translateLayerColor(Color.red, dist); translateLayerColor(Color.blue, dist); } } private final void translateLayerColor(final Color color, final int dist) { final LayerSet ls = getLayerSet(); final Layer l = layer_channels.get(color); if (null == l) return; updateColor(Color.white, layer_panels.get(l)); final Layer l2 = ls.getLayer(ls.indexOf(l) + dist); if (null != l2) updateColor(color, layer_panels.get(l2)); } private final void updateColor(final Color color, final LayerPanel lp) { lp.setColor(color); setColorChannel(lp.layer, color); } /** Calls setLayer(la) on the SetLayerThread. */ public void toLayer(final Layer la) { if (la.getParent() != layer.getParent()) return; // not of the same LayerSet if (la == layer) return; // nothing to do slt.set(la); updateInDatabase("layer_id"); } /** If shift is down, scroll to the previous non-empty layer; otherwise, if scroll_step is larger than 1, then scroll 'scroll_step' layers backward; else just the previous Layer. */ public void previousLayer(final int modifiers) { final Layer l; if (0 == (modifiers ^ Event.SHIFT_MASK)) { l = layer.getParent().previousNonEmpty(layer); } else if (scroll_step > 1) { int i = layer.getParent().indexOf(this.layer); Layer la = layer.getParent().getLayer(i - scroll_step); if (null != la) l = la; else l = null; } else { l = layer.getParent().previous(layer); } if (l != layer) { slt.set(l); updateInDatabase("layer_id"); } } static public void updateLayerScroller(LayerSet set) { for (final Display d : al_displays) { if (d.layer.getParent() == set) { d.updateLayerScroller(d.layer); } } } private void updateLayerScroller(Layer layer) { int size = layer.getParent().size(); if (size <= 1) { scroller.setValues(0, 1, 0, 0); scroller.setEnabled(false); } else { scroller.setEnabled(true); scroller.setValues(layer.getParent().indexOf(layer), 1, 0, size); } recreateLayerPanels(layer); } // Can't use this.layer, may still be null. User argument instead. private synchronized void recreateLayerPanels(final Layer layer) { synchronized (layer_channels) { panel_layers.removeAll(); if (0 == layer_panels.size()) { for (final Layer la : layer.getParent().getLayers()) { final LayerPanel lp = new LayerPanel(this, la); layer_panels.put(la, lp); this.panel_layers.add(lp); } } else { // Set theory at work: keep old to reuse layer_panels.keySet().retainAll(layer.getParent().getLayers()); for (final Layer la : layer.getParent().getLayers()) { LayerPanel lp = layer_panels.get(la); if (null == lp) { lp = new LayerPanel(this, la); layer_panels.put(la, lp); } this.panel_layers.add(lp); } for (final Iterator<Map.Entry<Integer,LayerPanel>> it = layer_alpha.entrySet().iterator(); it.hasNext(); ) { final Map.Entry<Integer,LayerPanel> e = it.next(); if (-1 == getLayerSet().indexOf(e.getValue().layer)) it.remove(); } for (final Iterator<Map.Entry<Color,Layer>> it = layer_channels.entrySet().iterator(); it.hasNext(); ) { final Map.Entry<Color,Layer> e = it.next(); if (-1 == getLayerSet().indexOf(e.getValue())) it.remove(); } scroll_layers.repaint(); } } } private void updateSnapshots() { Enumeration<DisplayablePanel> e = ht_panels.elements(); while (e.hasMoreElements()) { e.nextElement().repaint(); } Utils.updateComponent(tabs.getSelectedComponent()); } static public void updatePanel(Layer layer, final Displayable displ) { if (null == layer && null != front) layer = front.layer; // the front layer for (final Display d : al_displays) { if (d.layer == layer) { d.updatePanel(displ); } } } private void updatePanel(Displayable d) { JPanel c = null; if (d instanceof Profile) { c = panel_profiles; } else if (d instanceof Patch) { c = panel_patches; } else if (d instanceof DLabel) { c = panel_labels; } else if (d instanceof Pipe) { c = panel_zdispl; } if (null == c) return; DisplayablePanel dp = ht_panels.get(d); if (null != dp) { dp.repaint(); Utils.updateComponent(c); } } static public void updatePanelIndex(final Layer layer, final Displayable displ) { for (final Display d : al_displays) { if (d.layer == layer || displ instanceof ZDisplayable) { d.updatePanelIndex(displ); } } } private void updatePanelIndex(final Displayable d) { updateTab( (JPanel) ht_tabs.get(d.getClass()).getViewport().getView(), ZDisplayable.class.isAssignableFrom(d.getClass()) ? layer.getParent().getZDisplayables() : layer.getDisplayables(d.getClass())); } /** Repair possibly missing panels and other components by simply resetting the same Layer */ public void repairGUI() { Layer layer = this.layer; this.layer = null; setLayer(layer); } public void actionPerformed(final ActionEvent ae) { dispatcher.exec(new Runnable() { public void run() { String command = ae.getActionCommand(); if (command.startsWith("Job")) { if (Utils.checkYN("Really cancel job?")) { project.getLoader().quitJob(command); repairGUI(); } return; } else if (command.equals("Move to top")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.TOP, active); Display.repaint(layer.getParent(), active, 5); //Display.updatePanelIndex(layer, active); } else if (command.equals("Move up")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.UP, active); Display.repaint(layer.getParent(), active, 5); //Display.updatePanelIndex(layer, active); } else if (command.equals("Move down")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.DOWN, active); Display.repaint(layer.getParent(), active, 5); //Display.updatePanelIndex(layer, active); } else if (command.equals("Move to bottom")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.BOTTOM, active); Display.repaint(layer.getParent(), active, 5); //Display.updatePanelIndex(layer, active); } else if (command.equals("Duplicate, link and send to next layer")) { duplicateLinkAndSendTo(active, 1, layer.getParent().next(layer)); } else if (command.equals("Duplicate, link and send to previous layer")) { duplicateLinkAndSendTo(active, 0, layer.getParent().previous(layer)); } else if (command.equals("Duplicate, link and send to...")) { // fix non-scrolling popup menu GenericDialog gd = new GenericDialog("Send to"); gd.addMessage("Duplicate, link and send to..."); String[] sl = new String[layer.getParent().size()]; int next = 0; for (Iterator it = layer.getParent().getLayers().iterator(); it.hasNext(); ) { sl[next++] = project.findLayerThing(it.next()).toString(); } gd.addChoice("Layer: ", sl, sl[layer.getParent().indexOf(layer)]); gd.showDialog(); if (gd.wasCanceled()) return; Layer la = layer.getParent().getLayer(gd.getNextChoiceIndex()); if (layer == la) { Utils.showMessage("Can't duplicate, link and send to the same layer."); return; } duplicateLinkAndSendTo(active, 0, la); } else if (-1 != command.indexOf("z = ")) { // this is an item from the "Duplicate, link and send to" menu of layer z's Layer target_layer = layer.getParent().getLayer(Double.parseDouble(command.substring(command.lastIndexOf(' ') +1))); Utils.log2("layer: __" +command.substring(command.lastIndexOf(' ') +1) + "__"); if (null == target_layer) return; duplicateLinkAndSendTo(active, 0, target_layer); } else if (-1 != command.indexOf("z=")) { // WARNING the indexOf is very similar to the previous one // Send the linked group to the selected layer int iz = command.indexOf("z=")+2; Utils.log2("iz=" + iz + " other: " + command.indexOf(' ', iz+2)); int end = command.indexOf(' ', iz); if (-1 == end) end = command.length(); double lz = Double.parseDouble(command.substring(iz, end)); Layer target = layer.getParent().getLayer(lz); layer.getParent().move(selection.getAffected(), active.getLayer(), target); // TODO what happens when ZDisplayable are selected? } else if (command.equals("Unlink")) { if (null == active || active instanceof Patch) return; active.unlink(); updateSelection();//selection.update(); } else if (command.equals("Unlink from images")) { if (null == active) return; try { for (Displayable displ: selection.getSelected()) { displ.unlinkAll(Patch.class); } updateSelection();//selection.update(); } catch (Exception e) { IJError.print(e); } } else if (command.equals("Unlink slices")) { YesNoCancelDialog yn = new YesNoCancelDialog(frame, "Attention", "Really unlink all slices from each other?\nThere is no undo."); if (!yn.yesPressed()) return; final ArrayList<Patch> pa = ((Patch)active).getStackPatches(); for (int i=pa.size()-1; i>0; i--) { pa.get(i).unlink(pa.get(i-1)); } } else if (command.equals("Send to next layer")) { Rectangle box = selection.getBox(); try { // unlink Patch instances for (final Displayable displ : selection.getSelected()) { displ.unlinkAll(Patch.class); } updateSelection();//selection.update(); } catch (Exception e) { IJError.print(e); } //layer.getParent().moveDown(layer, active); // will repaint whatever appropriate layers selection.moveDown(); repaint(layer.getParent(), box); } else if (command.equals("Send to previous layer")) { Rectangle box = selection.getBox(); try { // unlink Patch instances for (final Displayable displ : selection.getSelected()) { displ.unlinkAll(Patch.class); } updateSelection();//selection.update(); } catch (Exception e) { IJError.print(e); } //layer.getParent().moveUp(layer, active); // will repaint whatever appropriate layers selection.moveUp(); repaint(layer.getParent(), box); } else if (command.equals("Show centered")) { if (active == null) return; showCentered(active); } else if (command.equals("Delete...")) { // remove all selected objects selection.deleteAll(); } else if (command.equals("Color...")) { IJ.doCommand("Color Picker..."); } else if (command.equals("Revert")) { if (null == active || active.getClass() != Patch.class) return; Patch p = (Patch)active; if (!p.revert()) { if (null == p.getOriginalPath()) Utils.log("No editions to save for patch " + p.getTitle() + " #" + p.getId()); else Utils.log("Could not revert Patch " + p.getTitle() + " #" + p.getId()); } } else if (command.equals("Remove alpha mask")) { final ArrayList<Displayable> patches = selection.getSelected(Patch.class); if (patches.size() > 0) { Bureaucrat.createAndStart(new Worker.Task("Removing alpha mask" + (patches.size() > 1 ? "s" : "")) { public void exec() { final ArrayList<Future> jobs = new ArrayList<Future>(); for (final Displayable d : patches) { final Patch p = (Patch) d; p.setAlphaMask(null); Future job = p.getProject().getLoader().regenerateMipMaps(p); // submit to queue if (null != job) jobs.add(job); } // join all for (final Future job : jobs) try { job.get(); } catch (Exception ie) {} }}, patches.get(0).getProject()); } } else if (command.equals("Undo")) { Bureaucrat.createAndStart(new Worker.Task("Undo") { public void exec() { layer.getParent().undoOneStep(); Display.repaint(layer.getParent()); }}, project); } else if (command.equals("Redo")) { Bureaucrat.createAndStart(new Worker.Task("Redo") { public void exec() { layer.getParent().redoOneStep(); Display.repaint(layer.getParent()); }}, project); } else if (command.equals("Apply transform")) { canvas.applyTransform(); } else if (command.equals("Apply transform propagating to last layer")) { if (mode.getClass() == AffineTransformMode.class || mode.getClass() == NonLinearTransformMode.class) { final LayerSet ls = getLayerSet(); final HashSet<Layer> subset = new HashSet<Layer>(ls.getLayers(ls.indexOf(Display.this.layer)+1, ls.size()-1)); // +1 to exclude current layer if (mode.getClass() == AffineTransformMode.class) ((AffineTransformMode)mode).applyAndPropagate(subset); else if (mode.getClass() == NonLinearTransformMode.class) ((NonLinearTransformMode)mode).apply(subset); setMode(new DefaultMode(Display.this)); } } else if (command.equals("Apply transform propagating to first layer")) { if (mode.getClass() == AffineTransformMode.class || mode.getClass() == NonLinearTransformMode.class) { final LayerSet ls = getLayerSet(); final HashSet<Layer> subset = new HashSet<Layer>(ls.getLayers(0, ls.indexOf(Display.this.layer) -1)); // -1 to exclude current layer if (mode.getClass() == AffineTransformMode.class) ((AffineTransformMode)mode).applyAndPropagate(subset); else if (mode.getClass() == NonLinearTransformMode.class) ((NonLinearTransformMode)mode).apply(subset); setMode(new DefaultMode(Display.this)); } } else if (command.equals("Cancel transform")) { canvas.cancelTransform(); // calls getMode().cancel() } else if (command.equals("Specify transform...")) { if (null == active) return; selection.specify(); } else if (command.equals("Hide all but images")) { ArrayList<Class> type = new ArrayList<Class>(); type.add(Patch.class); type.add(Stack.class); Collection<Displayable> col = layer.getParent().hideExcept(type, false); selection.removeAll(col); Display.updateCheckboxes(col, DisplayablePanel.VISIBILITY_STATE); Display.update(layer.getParent(), false); } else if (command.equals("Unhide all")) { Display.updateCheckboxes(layer.getParent().setAllVisible(false), DisplayablePanel.VISIBILITY_STATE); Display.update(layer.getParent(), false); } else if (command.startsWith("Hide all ")) { String type = command.substring(9, command.length() -1); // skip the ending plural 's' Collection<Displayable> col = layer.getParent().setVisible(type, false, true); selection.removeAll(col); Display.updateCheckboxes(col, DisplayablePanel.VISIBILITY_STATE); } else if (command.startsWith("Unhide all ")) { String type = command.substring(11, command.length() -1); // skip the ending plural 's' type = type.substring(0, 1).toUpperCase() + type.substring(1); updateCheckboxes(layer.getParent().setVisible(type, true, true), DisplayablePanel.VISIBILITY_STATE); } else if (command.equals("Hide deselected")) { hideDeselected(0 != (ActionEvent.ALT_MASK & ae.getModifiers())); } else if (command.equals("Hide deselected except images")) { hideDeselected(true); } else if (command.equals("Hide selected")) { selection.setVisible(false); // TODO should deselect them too? I don't think so. Display.updateCheckboxes(selection.getSelected(), DisplayablePanel.VISIBILITY_STATE); } else if (command.equals("Resize canvas/LayerSet...")) { resizeCanvas(); } else if (command.equals("Autoresize canvas/LayerSet")) { layer.getParent().setMinimumDimensions(); } else if (command.equals("Import image")) { importImage(); } else if (command.equals("Import next image")) { importNextImage(); } else if (command.equals("Import stack...")) { Display.this.getLayerSet().addChangeTreesStep(); Rectangle sr = getCanvas().getSrcRect(); Bureaucrat burro = project.getLoader().importStack(layer, sr.x + sr.width/2, sr.y + sr.height/2, null, true, null, false); burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addChangeTreesStep(); }}); } else if (command.equals("Import stack with landmarks...")) { // 1 - Find out if there's any other project open List<Project> pr = Project.getProjects(); if (1 == pr.size()) { Utils.logAll("Need another project open!"); return; } // 2 - Ask for a "landmarks" type GenericDialog gd = new GenericDialog("Landmarks"); gd.addStringField("landmarks type:", "landmarks"); final String[] none = {"-- None --"}; final Hashtable<String,Project> mpr = new Hashtable<String,Project>(); for (Project p : pr) { if (p == project) continue; mpr.put(p.toString(), p); } final String[] project_titles = mpr.keySet().toArray(new String[0]); final Hashtable<String,ProjectThing> map_target = findLandmarkNodes(project, "landmarks"); String[] target_landmark_titles = map_target.isEmpty() ? none : map_target.keySet().toArray(new String[0]); gd.addChoice("Landmarks node in this project:", target_landmark_titles, target_landmark_titles[0]); gd.addMessage(""); gd.addChoice("Source project:", project_titles, project_titles[0]); final Hashtable<String,ProjectThing> map_source = findLandmarkNodes(mpr.get(project_titles[0]), "landmarks"); String[] source_landmark_titles = map_source.isEmpty() ? none : map_source.keySet().toArray(new String[0]); gd.addChoice("Landmarks node in source project:", source_landmark_titles, source_landmark_titles[0]); final List<Patch> stacks = Display.getPatchStacks(mpr.get(project_titles[0]).getRootLayerSet()); String[] stack_titles; if (stacks.isEmpty()) { if (1 == mpr.size()) { IJ.showMessage("Project " + project_titles[0] + " does not contain any Stack."); return; } stack_titles = none; } else { stack_titles = new String[stacks.size()]; int next = 0; for (Patch pa : stacks) stack_titles[next++] = pa.toString(); } gd.addChoice("Stacks:", stack_titles, stack_titles[0]); Vector vc = gd.getChoices(); final Choice choice_target_landmarks = (Choice) vc.get(0); final Choice choice_source_projects = (Choice) vc.get(1); final Choice choice_source_landmarks = (Choice) vc.get(2); final Choice choice_stacks = (Choice) vc.get(3); final TextField input = (TextField) gd.getStringFields().get(0); input.addTextListener(new TextListener() { public void textValueChanged(TextEvent te) { final String text = input.getText(); update(choice_target_landmarks, Display.this.project, text, map_target); update(choice_source_landmarks, mpr.get(choice_source_projects.getSelectedItem()), text, map_source); } private void update(Choice c, Project p, String type, Hashtable<String,ProjectThing> table) { table.clear(); table.putAll(findLandmarkNodes(p, type)); c.removeAll(); if (table.isEmpty()) c.add(none[0]); else for (String t : table.keySet()) c.add(t); } }); choice_source_projects.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { String item = (String) e.getItem(); Project p = mpr.get(choice_source_projects.getSelectedItem()); // 1 - Update choice of landmark items map_source.clear(); map_source.putAll(findLandmarkNodes(p, input.getText())); choice_target_landmarks.removeAll(); if (map_source.isEmpty()) choice_target_landmarks.add(none[0]); else for (String t : map_source.keySet()) choice_target_landmarks.add(t); // 2 - Update choice of Stack items stacks.clear(); choice_stacks.removeAll(); stacks.addAll(Display.getPatchStacks(mpr.get(project_titles[0]).getRootLayerSet())); if (stacks.isEmpty()) choice_stacks.add(none[0]); else for (Patch pa : stacks) choice_stacks.add(pa.toString()); } }); gd.showDialog(); if (gd.wasCanceled()) return; String type = gd.getNextString(); if (null == type || 0 == type.trim().length()) { Utils.log("Invalid landmarks node type!"); return; } ProjectThing target_landmarks_node = map_target.get(gd.getNextChoice()); Project source = mpr.get(gd.getNextChoice()); ProjectThing source_landmarks_node = map_source.get(gd.getNextChoice()); Patch stack_patch = stacks.get(gd.getNextChoiceIndex()); // Store current state Display.this.getLayerSet().addLayerContentStep(layer); // Insert stack insertStack(target_landmarks_node, source, source_landmarks_node, stack_patch); // Store new state Display.this.getLayerSet().addChangeTreesStep(); } else if (command.equals("Import grid...")) { Display.this.getLayerSet().addLayerContentStep(layer); Bureaucrat burro = project.getLoader().importGrid(layer); if (null != burro) burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addLayerContentStep(layer); }}); } else if (command.equals("Import sequence as grid...")) { Display.this.getLayerSet().addChangeTreesStep(); Bureaucrat burro = project.getLoader().importSequenceAsGrid(layer); if (null != burro) burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addChangeTreesStep(); }}); } else if (command.equals("Import from text file...")) { Display.this.getLayerSet().addChangeTreesStep(); Bureaucrat burro = project.getLoader().importImages(layer); if (null != burro) burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addChangeTreesStep(); }}); } else if (command.equals("Import labels as arealists...")) { Display.this.getLayerSet().addChangeTreesStep(); Bureaucrat burro = project.getLoader().importLabelsAsAreaLists(layer, null, Double.MAX_VALUE, 0, 0.4f, false); burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addChangeTreesStep(); }}); } else if (command.equals("Make flat image...")) { // if there's a ROI, just use that as cropping rectangle Rectangle srcRect = null; Roi roi = canvas.getFakeImagePlus().getRoi(); if (null != roi) { srcRect = roi.getBounds(); } else { // otherwise, whatever is visible //srcRect = canvas.getSrcRect(); // The above is confusing. That is what ROIs are for. So paint all: srcRect = new Rectangle(0, 0, (int)Math.ceil(layer.getParent().getLayerWidth()), (int)Math.ceil(layer.getParent().getLayerHeight())); } double scale = 1.0; final String[] types = new String[]{"8-bit grayscale", "RGB Color"}; int the_type = ImagePlus.GRAY8; final GenericDialog gd = new GenericDialog("Choose", frame); gd.addSlider("Scale: ", 1, 100, 100); gd.addNumericField("Width: ", srcRect.width, 0); gd.addNumericField("height: ", srcRect.height, 0); // connect the above 3 fields: Vector numfields = gd.getNumericFields(); UpdateDimensionField udf = new UpdateDimensionField(srcRect.width, srcRect.height, (TextField) numfields.get(1), (TextField) numfields.get(2), (TextField) numfields.get(0), (Scrollbar) gd.getSliders().get(0)); for (Object ob : numfields) ((TextField)ob).addTextListener(udf); gd.addChoice("Type: ", types, types[0]); if (layer.getParent().size() > 1) { Utils.addLayerRangeChoices(Display.this.layer, gd); /// $#%! where are my lisp macros gd.addCheckbox("Include non-empty layers only", true); } gd.addMessage("Background color:"); Utils.addRGBColorSliders(gd, Color.black); gd.addCheckbox("Best quality", false); gd.addMessage(""); gd.addCheckbox("Save to file", false); gd.addCheckbox("Save for web", false); gd.showDialog(); if (gd.wasCanceled()) return; scale = gd.getNextNumber() / 100; the_type = (0 == gd.getNextChoiceIndex() ? ImagePlus.GRAY8 : ImagePlus.COLOR_RGB); if (Double.isNaN(scale) || scale <= 0.0) { Utils.showMessage("Invalid scale."); return; } // consuming and ignoring width and height: gd.getNextNumber(); gd.getNextNumber(); Layer[] layer_array = null; boolean non_empty_only = false; if (layer.getParent().size() > 1) { non_empty_only = gd.getNextBoolean(); int i_start = gd.getNextChoiceIndex(); int i_end = gd.getNextChoiceIndex(); ArrayList al = new ArrayList(); ArrayList al_zd = layer.getParent().getZDisplayables(); ZDisplayable[] zd = new ZDisplayable[al_zd.size()]; al_zd.toArray(zd); for (int i=i_start, j=0; i <= i_end; i++, j++) { Layer la = layer.getParent().getLayer(i); if (!la.isEmpty() || !non_empty_only) al.add(la); // checks both the Layer and the ZDisplayable objects in the parent LayerSet } if (0 == al.size()) { Utils.showMessage("All layers are empty!"); return; } layer_array = new Layer[al.size()]; al.toArray(layer_array); } else { layer_array = new Layer[]{Display.this.layer}; } final Color background = new Color((int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber()); final boolean quality = gd.getNextBoolean(); final boolean save_to_file = gd.getNextBoolean(); final boolean save_for_web = gd.getNextBoolean(); // in its own thread if (save_for_web) project.getLoader().makePrescaledTiles(layer_array, Patch.class, srcRect, scale, c_alphas, the_type); else project.getLoader().makeFlatImage(layer_array, srcRect, scale, c_alphas, the_type, save_to_file, quality, background); } else if (command.equals("Lock")) { selection.setLocked(true); Utils.revalidateComponent(tabs.getSelectedComponent()); } else if (command.equals("Unlock")) { selection.setLocked(false); Utils.revalidateComponent(tabs.getSelectedComponent()); } else if (command.equals("Properties...")) { active.adjustProperties(); updateSelection(); } else if (command.equals("Show current 2D position in 3D")) { Point p = canvas.consumeLastPopupPoint(); if (null == p) return; Display3D.addFatPoint("Current 2D Position", getLayerSet(), p.x, p.y, layer.getZ(), 10, Color.magenta); } else if (command.equals("Show layers as orthoslices in 3D")) { GenericDialog gd = new GenericDialog("Options"); Roi roi = canvas.getFakeImagePlus().getRoi(); Rectangle r = null == roi ? getLayerSet().get2DBounds() : roi.getBounds(); gd.addMessage("ROI 2D bounds:"); gd.addNumericField("x:", r.x, 0, 30, "pixels"); gd.addNumericField("y:", r.y, 0, 30, "pixels"); gd.addNumericField("width:", r.width, 0, 30, "pixels"); gd.addNumericField("height:", r.height, 0, 30, "pixels"); gd.addMessage("Layers to include:"); Utils.addLayerRangeChoices(layer, gd); gd.addMessage("Constrain dimensions to:"); gd.addNumericField("max width and height:", getLayerSet().getPixelsMaxDimension(), 0, 30, "pixels"); gd.addMessage("Options:"); final String[] types = {"Greyscale", "Color RGB"}; gd.addChoice("Image type:", types, types[0]); gd.addCheckbox("Invert images", false); gd.showDialog(); if (gd.wasCanceled()) return; int x = (int)gd.getNextNumber(), y = (int)gd.getNextNumber(), width = (int)gd.getNextNumber(), height = (int)gd.getNextNumber(); final int first = gd.getNextChoiceIndex(), last = gd.getNextChoiceIndex(); final List<Layer> layers = getLayerSet().getLayers(first, last); final int max_dim = (int)gd.getNextNumber(); float scale = 1; if (max_dim < Math.max(width, height)) { scale = max_dim / (float)Math.max(width, height); } final int type = 0 == gd.getNextChoiceIndex() ? ImagePlus.GRAY8 : ImagePlus.COLOR_RGB; final boolean invert = gd.getNextBoolean(); final LayerStack stack = new LayerStack(layers, new Rectangle(x, y, width, height), scale, type, Patch.class, max_dim, invert); Display3D.showOrthoslices(stack.getImagePlus(), "LayerSet [" + x + "," + y + "," + width + "," + height + "] " + first + "--" + last, x, y, scale, layers.get(0)); } else if (command.equals("Align stack slices")) { if (getActive() instanceof Patch) { final Patch slice = (Patch)getActive(); if (slice.isStack()) { // check linked group final HashSet hs = slice.getLinkedGroup(new HashSet()); for (Iterator it = hs.iterator(); it.hasNext(); ) { if (it.next().getClass() != Patch.class) { Utils.showMessage("Images are linked to other objects, can't proceed to cross-correlate them."); // labels should be fine, need to check that return; } } final LayerSet ls = slice.getLayerSet(); final HashSet<Displayable> linked = slice.getLinkedGroup(null); ls.addTransformStepWithData(linked); Bureaucrat burro = AlignTask.registerStackSlices((Patch)getActive()); // will repaint burro.addPostTask(new Runnable() { public void run() { ls.enlargeToFit(linked); // The current state when done ls.addTransformStepWithData(linked); }}); } else { Utils.log("Align stack slices: selected image is not part of a stack."); } } } else if (command.equals("Align layers with manual landmarks")) { setMode(new ManualAlignMode(Display.this)); } else if (command.equals("Align layers")) { final Layer la = layer; // caching, since scroll wheel may change it la.getParent().addTransformStep(la.getParent().getLayers()); Bureaucrat burro = AlignLayersTask.alignLayersTask( la ); burro.addPostTask(new Runnable() { public void run() { getLayerSet().enlargeToFit(getLayerSet().getDisplayables(Patch.class)); la.getParent().addTransformStep(la.getParent().getLayers()); }}); } else if (command.equals("Align multi-layer mosaic")) { final Layer la = layer; // caching, since scroll wheel may change it la.getParent().addTransformStep(); Bureaucrat burro = AlignTask.alignMultiLayerMosaicTask( la ); burro.addPostTask(new Runnable() { public void run() { getLayerSet().enlargeToFit(getLayerSet().getDisplayables(Patch.class)); la.getParent().addTransformStep(); }}); } else if (command.equals("Montage all images in this layer")) { final Layer la = layer; final List<Patch> patches = new ArrayList<Patch>( (List<Patch>) (List) la.getDisplayables(Patch.class)); if (patches.size() < 2) { Utils.showMessage("Montage needs 2 or more images selected"); return; } final Collection<Displayable> col = la.getParent().addTransformStepWithData(Arrays.asList(new Layer[]{la})); // find any locked patches final ArrayList<Patch> fixed = new ArrayList<Patch>(); for (final Patch p : patches) { if (p.isLocked2()) fixed.add(p); } if (fixed.isEmpty()) fixed.add(patches.get(0)); Bureaucrat burro = AlignTask.alignPatchesTask(patches, fixed); burro.addPostTask(new Runnable() { public void run() { getLayerSet().enlargeToFit(patches); la.getParent().addTransformStepWithData(col); }}); } else if (command.equals("Montage selected images (SIFT)")) { montage(0); } else if (command.equals("Montage selected images (phase correlation)")) { montage(1); } else if (command.equals("Montage multiple layers (phase correlation)")) { final GenericDialog gd = new GenericDialog("Choose range"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; final List<Layer> layers = getLayerSet().getLayers(gd.getNextChoiceIndex(), gd.getNextChoiceIndex()); final Collection<Displayable> col = getLayerSet().addTransformStepWithData(layers); Bureaucrat burro = StitchingTEM.montageWithPhaseCorrelation(layers); if (null == burro) return; burro.addPostTask(new Runnable() { public void run() { Collection<Displayable> ds = new ArrayList<Displayable>(); for (Layer la : layers) ds.addAll(la.getDisplayables(Patch.class)); getLayerSet().enlargeToFit(ds); getLayerSet().addTransformStepWithData(col); }}); } else if (command.equals("Montage multiple layers (SIFT)")) { final GenericDialog gd = new GenericDialog("Choose range"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; final List<Layer> layers = getLayerSet().getLayers(gd.getNextChoiceIndex(), gd.getNextChoiceIndex()); final Collection<Displayable> col = getLayerSet().addTransformStepWithData(layers); Bureaucrat burro = AlignTask.montageLayersTask(layers); burro.addPostTask(new Runnable() { public void run() { Collection<Displayable> ds = new ArrayList<Displayable>(); for (Layer la : layers) ds.addAll(la.getDisplayables(Patch.class)); getLayerSet().enlargeToFit(ds); getLayerSet().addTransformStepWithData(col); }}); } else if (command.equals("Properties ...")) { // NOTE the space before the dots, to distinguish from the "Properties..." command that works on Displayable objects. GenericDialog gd = new GenericDialog("Properties", Display.this.frame); //gd.addNumericField("layer_scroll_step: ", this.scroll_step, 0); gd.addSlider("layer_scroll_step: ", 1, layer.getParent().size(), Display.this.scroll_step); gd.addChoice("snapshots_mode", LayerSet.snapshot_modes, LayerSet.snapshot_modes[layer.getParent().getSnapshotsMode()]); gd.addCheckbox("prefer_snapshots_quality", layer.getParent().snapshotsQuality()); Loader lo = getProject().getLoader(); boolean using_mipmaps = lo.isMipMapsEnabled(); gd.addCheckbox("enable_mipmaps", using_mipmaps); gd.addCheckbox("enable_layer_pixels virtualization", layer.getParent().isPixelsVirtualizationEnabled()); double max = layer.getParent().getLayerWidth() < layer.getParent().getLayerHeight() ? layer.getParent().getLayerWidth() : layer.getParent().getLayerHeight(); gd.addSlider("max_dimension of virtualized layer pixels: ", 0, max, layer.getParent().getPixelsMaxDimension()); gd.addCheckbox("Show arrow heads in Treeline/AreaTree", layer.getParent().paint_arrows); gd.addCheckbox("Show edge confidence boxes in Treeline/AreaTree", layer.getParent().paint_edge_confidence_boxes); gd.addCheckbox("Show color cues", layer.getParent().color_cues); gd.addSlider("+/- layers to color cue", 0, 10, layer.getParent().n_layers_color_cue); gd.addCheckbox("Prepaint images", layer.getParent().prepaint); // -------- gd.showDialog(); if (gd.wasCanceled()) return; // -------- int sc = (int) gd.getNextNumber(); if (sc < 1) sc = 1; Display.this.scroll_step = sc; updateInDatabase("scroll_step"); // layer.getParent().setSnapshotsMode(gd.getNextChoiceIndex()); layer.getParent().setSnapshotsQuality(gd.getNextBoolean()); // boolean generate_mipmaps = gd.getNextBoolean(); if (using_mipmaps && generate_mipmaps) { // nothing changed } else { if (using_mipmaps) { // and !generate_mipmaps lo.flushMipMaps(true); } else { // not using mipmaps before, and true == generate_mipmaps lo.generateMipMaps(layer.getParent().getDisplayables(Patch.class)); } } // layer.getParent().setPixelsVirtualizationEnabled(gd.getNextBoolean()); layer.getParent().setPixelsMaxDimension((int)gd.getNextNumber()); layer.getParent().paint_arrows = gd.getNextBoolean(); layer.getParent().paint_edge_confidence_boxes = gd.getNextBoolean(); layer.getParent().color_cues = gd.getNextBoolean(); layer.getParent().n_layers_color_cue = (int)gd.getNextNumber(); layer.getParent().prepaint = gd.getNextBoolean(); Display.repaint(layer.getParent()); } else if (command.equals("Adjust snapping parameters...")) { AlignTask.p_snap.setup("Snap"); } else if (command.equals("Adjust fast-marching parameters...")) { Segmentation.fmp.setup(); } else if (command.equals("Adjust arealist paint parameters...")) { AreaWrapper.PP.setup(); } else if (command.equals("Search...")) { new Search(); } else if (command.equals("Select all")) { selection.selectAll(); repaint(Display.this.layer, selection.getBox(), 0); } else if (command.equals("Select all visible")) { selection.selectAllVisible(); repaint(Display.this.layer, selection.getBox(), 0); } else if (command.equals("Select none")) { Rectangle box = selection.getBox(); selection.clear(); repaint(Display.this.layer, box, 0); } else if (command.equals("Restore selection")) { selection.restore(); } else if (command.equals("Select under ROI")) { Roi roi = canvas.getFakeImagePlus().getRoi(); if (null == roi) return; selection.selectAll(roi, true); } else if (command.equals("Merge")) { Bureaucrat burro = Bureaucrat.create(new Worker.Task("Merging AreaLists") { public void exec() { ArrayList al_sel = selection.getSelected(AreaList.class); // put active at the beginning, to work as the base on which other's will get merged al_sel.remove(Display.this.active); al_sel.add(0, Display.this.active); Set<DoStep> dataedits = new HashSet<DoStep>(); dataedits.add(new Displayable.DoEdit(Display.this.active).init(Display.this.active, new String[]{"data"})); getLayerSet().addChangeTreesStep(dataedits); AreaList ali = AreaList.merge(al_sel); if (null != ali) { // remove all but the first from the selection for (int i=1; i<al_sel.size(); i++) { Object ob = al_sel.get(i); if (ob.getClass() == AreaList.class) { selection.remove((Displayable)ob); } } selection.updateTransform(ali); repaint(ali.getLayerSet(), ali, 0); } } }, Display.this.project); burro.addPostTask(new Runnable() { public void run() { Set<DoStep> dataedits = new HashSet<DoStep>(); dataedits.add(new Displayable.DoEdit(Display.this.active).init(Display.this.active, new String[]{"data"})); getLayerSet().addChangeTreesStep(dataedits); }}); burro.goHaveBreakfast(); } else if (command.equals("Reroot")) { if (!(active instanceof Tree)) return; Point p = canvas.consumeLastPopupPoint(); if (null == p) return; getLayerSet().addDataEditStep(active); ((Tree)active).reRoot(p.x, p.y, layer, canvas.getMagnification()); getLayerSet().addDataEditStep(active); Display.repaint(getLayerSet()); } else if (command.equals("Part subtree")) { if (!(active instanceof Tree)) return; Point p = canvas.consumeLastPopupPoint(); if (null == p) return; List<ZDisplayable> ts = ((Tree)active).splitNear(p.x, p.y, layer, canvas.getMagnification()); if (null == ts) return; Displayable elder = Display.this.active; for (ZDisplayable t : ts) { if (t == elder) continue; getLayerSet().add(t); // will change Display.this.active ! project.getProjectTree().addSibling(elder, t); } selection.clear(); selection.selectAll(ts); selection.add(elder); getLayerSet().addChangeTreesStep(); Display.repaint(getLayerSet()); } else if (command.equals("Show tabular view")) { if (!(active instanceof Tree)) return; ((Tree)active).createMultiTableView(); } else if (command.equals("Mark")) { if (!(active instanceof Tree)) return; Point p = canvas.consumeLastPopupPoint(); if (null == p) return; if (((Tree)active).markNear(p.x, p.y, layer, canvas.getMagnification())) { Display.repaint(getLayerSet()); } } else if (command.equals("Clear marks (selected Trees)")) { for (Displayable d : selection.getSelected(Tree.class)) { ((Tree)d).unmark(); } Display.repaint(getLayerSet()); } else if (command.equals("Join")) { if (!(active instanceof Tree)) return; final List<Tree> tlines = (List<Tree>) (List) selection.getSelected(active.getClass()); if (((Tree)active).canJoin(tlines)) { // Record current state Set<DoStep> dataedits = new HashSet<DoStep>(tlines.size()); for (final Tree tl : tlines) { dataedits.add(new Displayable.DoEdit(tl).init(tl, new String[]{"data"})); } getLayerSet().addChangeTreesStep(dataedits); // ((Tree)active).join(tlines); for (final Tree tl : tlines) { if (tl == active) continue; tl.remove2(false); } Display.repaint(getLayerSet()); // Again, to record current state (just the joined tree this time) Set<DoStep> dataedits2 = new HashSet<DoStep>(1); dataedits2.add(new Displayable.DoEdit(active).init(active, new String[]{"data"})); getLayerSet().addChangeTreesStep(dataedits2); } } else if (command.equals("Previous branch point or start")) { if (!(active instanceof Tree)) return; Point p = canvas.consumeLastPopupPoint(); if (null == p) return; center(((Treeline)active).findPreviousBranchOrRootPoint(p.x, p.y, layer, canvas.getMagnification())); } else if (command.equals("Next branch point or end")) { if (!(active instanceof Tree)) return; Point p = canvas.consumeLastPopupPoint(); if (null == p) return; center(((Tree)active).findNextBranchOrEndPoint(p.x, p.y, layer, canvas.getMagnification())); } else if (command.equals("Root")) { if (!(active instanceof Tree)) return; Point p = canvas.consumeLastPopupPoint(); if (null == p) return; center(((Tree)active).createCoordinate(((Tree)active).getRoot())); } else if (command.equals("Last added point")) { if (!(active instanceof Tree)) return; center(((Treeline)active).getLastAdded()); } else if (command.equals("Last edited point")) { if (!(active instanceof Tree)) return; center(((Treeline)active).getLastEdited()); } else if (command.equals("Reverse point order")) { if (!(active instanceof Pipe)) return; getLayerSet().addDataEditStep(active); ((Pipe)active).reverse(); Display.repaint(Display.this.layer); getLayerSet().addDataEditStep(active); } else if (command.equals("View orthoslices")) { if (!(active instanceof Patch)) return; Display3D.showOrthoslices(((Patch)active)); } else if (command.equals("View volume")) { if (!(active instanceof Patch)) return; Display3D.showVolume(((Patch)active)); } else if (command.equals("Show in 3D")) { for (Iterator it = selection.getSelected(ZDisplayable.class).iterator(); it.hasNext(); ) { ZDisplayable zd = (ZDisplayable)it.next(); Display3D.show(zd.getProject().findProjectThing(zd)); } // handle profile lists ... HashSet hs = new HashSet(); for (Iterator it = selection.getSelected(Profile.class).iterator(); it.hasNext(); ) { Displayable d = (Displayable)it.next(); ProjectThing profile_list = (ProjectThing)d.getProject().findProjectThing(d).getParent(); if (!hs.contains(profile_list)) { Display3D.show(profile_list); hs.add(profile_list); } } } else if (command.equals("Snap")) { // Take the active if it's a Patch if (!(active instanceof Patch)) return; Display.snap((Patch)active); } else if (command.equals("Blend")) { HashSet<Patch> patches = new HashSet<Patch>(); for (final Displayable d : selection.getSelected()) { if (d.getClass() == Patch.class) patches.add((Patch)d); } if (patches.size() > 1) { GenericDialog gd = new GenericDialog("Blending"); gd.addCheckbox("Respect current alpha mask", true); gd.showDialog(); if (gd.wasCanceled()) return; Blending.blend(patches, gd.getNextBoolean()); } else { IJ.log("Please select more than one overlapping image."); } } else if (command.equals("Montage")) { final Set<Displayable> affected = new HashSet<Displayable>(selection.getAffected()); // make an undo step! final LayerSet ls = layer.getParent(); ls.addTransformStepWithData(affected); Bureaucrat burro = AlignTask.alignSelectionTask( selection ); burro.addPostTask(new Runnable() { public void run() { ls.enlargeToFit(affected); ls.addTransformStepWithData(affected); }}); } else if (command.equals("Lens correction")) { final Layer la = layer; la.getParent().addDataEditStep(new HashSet<Displayable>(la.getParent().getDisplayables())); Bureaucrat burro = DistortionCorrectionTask.correctDistortionFromSelection( selection ); burro.addPostTask(new Runnable() { public void run() { // no means to know which where modified and from which layers! la.getParent().addDataEditStep(new HashSet<Displayable>(la.getParent().getDisplayables())); }}); } else if (command.equals("Link images...")) { GenericDialog gd = new GenericDialog("Options"); gd.addMessage("Linking images to images (within their own layer only):"); String[] options = {"all images to all images", "each image with any other overlapping image"}; gd.addChoice("Link: ", options, options[1]); String[] options2 = {"selected images only", "all images in this layer", "all images in all layers, within the layer only", "all images in all layers, within and across consecutive layers"}; gd.addChoice("Apply to: ", options2, options2[0]); gd.showDialog(); if (gd.wasCanceled()) return; Layer lay = layer; final HashSet<Displayable> ds = new HashSet<Displayable>(lay.getParent().getDisplayables()); lay.getParent().addDataEditStep(ds, new String[]{"data"}); boolean overlapping_only = 1 == gd.getNextChoiceIndex(); Collection<Displayable> coll = null; switch (gd.getNextChoiceIndex()) { case 0: coll = selection.getSelected(Patch.class); Patch.crosslink(coll, overlapping_only); break; case 1: coll = lay.getDisplayables(Patch.class); Patch.crosslink(coll, overlapping_only); break; case 2: coll = new ArrayList<Displayable>(); for (final Layer la : lay.getParent().getLayers()) { Collection<Displayable> acoll = la.getDisplayables(Patch.class); Patch.crosslink(acoll, overlapping_only); coll.addAll(acoll); } break; case 3: ArrayList<Layer> layers = lay.getParent().getLayers(); Collection<Displayable> lc1 = layers.get(0).getDisplayables(Patch.class); if (lay == layers.get(0)) coll = lc1; for (int i=1; i<layers.size(); i++) { Collection<Displayable> lc2 = layers.get(i).getDisplayables(Patch.class); if (null == coll && Display.this.layer == layers.get(i)) coll = lc2; Collection<Displayable> both = new ArrayList<Displayable>(); both.addAll(lc1); both.addAll(lc2); Patch.crosslink(both, overlapping_only); lc1 = lc2; } break; } if (null != coll) Display.updateCheckboxes(coll, DisplayablePanel.LINK_STATE, true); lay.getParent().addDataEditStep(ds); } else if (command.equals("Unlink all selected images")) { if (Utils.check("Really unlink selected images?")) { for (final Displayable d : selection.getSelected(Patch.class)) { d.unlink(); } } } else if (command.equals("Unlink all")) { if (Utils.check("Really unlink all objects from all layers?")) { Collection<Displayable> ds = layer.getParent().getDisplayables(); for (final Displayable d : ds) { d.unlink(); } Display.updateCheckboxes(ds, DisplayablePanel.LOCK_STATE); } } else if (command.equals("Calibration...")) { try { IJ.run(canvas.getFakeImagePlus(), "Properties...", ""); Display.updateTitle(getLayerSet()); } catch (RuntimeException re) { Utils.log2("Calibration dialog canceled."); } } else if (command.equals("Grid overlay...")) { if (null == gridoverlay) gridoverlay = new GridOverlay(); gridoverlay.setup(canvas.getFakeImagePlus().getRoi()); canvas.repaint(false); } else if (command.equals("Enhance contrast (selected images)...")) { final Layer la = layer; ArrayList<Displayable> selected = selection.getSelected(Patch.class); final HashSet<Displayable> ds = new HashSet<Displayable>(selected); la.getParent().addDataEditStep(ds); Displayable active = Display.this.getActive(); Patch ref = active.getClass() == Patch.class ? (Patch)active : null; Bureaucrat burro = getProject().getLoader().enhanceContrast(selected, ref); burro.addPostTask(new Runnable() { public void run() { la.getParent().addDataEditStep(ds); }}); } else if (command.equals("Enhance contrast layer-wise...")) { // ask for range of layers final GenericDialog gd = new GenericDialog("Choose range"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; java.util.List<Layer> layers = layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1); // exclusive end final HashSet<Displayable> ds = new HashSet<Displayable>(); for (final Layer l : layers) ds.addAll(l.getDisplayables(Patch.class)); getLayerSet().addDataEditStep(ds); Bureaucrat burro = project.getLoader().enhanceContrast(layers); burro.addPostTask(new Runnable() { public void run() { getLayerSet().addDataEditStep(ds); }}); } else if (command.equals("Set Min and Max layer-wise...")) { Displayable active = getActive(); double min = 0; double max = 0; if (null != active && active.getClass() == Patch.class) { min = ((Patch)active).getMin(); max = ((Patch)active).getMax(); } final GenericDialog gd = new GenericDialog("Min and Max"); gd.addMessage("Set min and max to all images in the layer range"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.addNumericField("min: ", min, 2); gd.addNumericField("max: ", max, 2); gd.showDialog(); if (gd.wasCanceled()) return; // min = gd.getNextNumber(); max = gd.getNextNumber(); ArrayList<Displayable> al = new ArrayList<Displayable>(); for (final Layer la : layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1)) { // exclusive end al.addAll(la.getDisplayables(Patch.class)); } final HashSet<Displayable> ds = new HashSet<Displayable>(al); getLayerSet().addDataEditStep(ds); Bureaucrat burro = project.getLoader().setMinAndMax(al, min, max); burro.addPostTask(new Runnable() { public void run() { getLayerSet().addDataEditStep(ds); }}); } else if (command.equals("Set Min and Max (selected images)...")) { Displayable active = getActive(); double min = 0; double max = 0; if (null != active && active.getClass() == Patch.class) { min = ((Patch)active).getMin(); max = ((Patch)active).getMax(); } final GenericDialog gd = new GenericDialog("Min and Max"); gd.addMessage("Set min and max to all selected images"); gd.addNumericField("min: ", min, 2); gd.addNumericField("max: ", max, 2); gd.showDialog(); if (gd.wasCanceled()) return; // min = gd.getNextNumber(); max = gd.getNextNumber(); final HashSet<Displayable> ds = new HashSet<Displayable>(selection.getSelected(Patch.class)); getLayerSet().addDataEditStep(ds); Bureaucrat burro = project.getLoader().setMinAndMax(selection.getSelected(Patch.class), min, max); burro.addPostTask(new Runnable() { public void run() { getLayerSet().addDataEditStep(ds); }}); } else if (command.equals("Adjust min and max (selected images)...")) { final List<Displayable> list = selection.getSelected(Patch.class); if (list.isEmpty()) { Utils.log("No images selected!"); return; } Bureaucrat.createAndStart(new Worker.Task("Init contrast adjustment") { public void exec() { try { setMode(new ContrastAdjustmentMode(Display.this, list)); } catch (Exception e) { Utils.log("All images must be of the same type!"); } } }, list.get(0).getProject()); } else if (command.equals("Mask image borders (layer-wise)...")) { final GenericDialog gd = new GenericDialog("Mask borders"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.addMessage("Borders:"); gd.addNumericField("left: ", 6, 2); gd.addNumericField("top: ", 6, 2); gd.addNumericField("right: ", 6, 2); gd.addNumericField("bottom: ", 6, 2); gd.showDialog(); if (gd.wasCanceled()) return; Collection<Layer> layers = layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1); final HashSet<Displayable> ds = new HashSet<Displayable>(); for (Layer l : layers) ds.addAll(l.getDisplayables(Patch.class)); getLayerSet().addDataEditStep(ds); Bureaucrat burro = project.getLoader().maskBordersLayerWise(layers, (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber()); burro.addPostTask(new Runnable() { public void run() { getLayerSet().addDataEditStep(ds); }}); } else if (command.equals("Mask image borders (selected images)...")) { final GenericDialog gd = new GenericDialog("Mask borders"); gd.addMessage("Borders:"); gd.addNumericField("left: ", 6, 2); gd.addNumericField("top: ", 6, 2); gd.addNumericField("right: ", 6, 2); gd.addNumericField("bottom: ", 6, 2); gd.showDialog(); if (gd.wasCanceled()) return; Collection<Displayable> patches = selection.getSelected(Patch.class); final HashSet<Displayable> ds = new HashSet<Displayable>(patches); getLayerSet().addDataEditStep(ds); Bureaucrat burro = project.getLoader().maskBorders(patches, (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber()); burro.addPostTask(new Runnable() { public void run() { getLayerSet().addDataEditStep(ds); }}); } else if (command.equals("Duplicate")) { // only Patch and DLabel, i.e. Layer-only resident objects that don't exist in the Project Tree final HashSet<Class> accepted = new HashSet<Class>(); accepted.add(Patch.class); accepted.add(DLabel.class); accepted.add(Stack.class); final ArrayList<Displayable> originals = new ArrayList<Displayable>(); final ArrayList<Displayable> selected = selection.getSelected(); for (final Displayable d : selected) { if (accepted.contains(d.getClass())) { originals.add(d); } } if (originals.size() > 0) { getLayerSet().addChangeTreesStep(); for (final Displayable d : originals) { if (d instanceof ZDisplayable) { d.getLayerSet().add((ZDisplayable)d.clone()); } else { d.getLayer().add(d.clone()); } } getLayerSet().addChangeTreesStep(); } else if (selected.size() > 0) { Utils.log("Can only duplicate images and text labels.\nDuplicate *other* objects in the Project Tree.\n"); } } else if (command.equals("Create subproject")) { Roi roi = canvas.getFakeImagePlus().getRoi(); if (null == roi) return; // the menu item is not active unless there is a ROI Layer first, last; if (1 == layer.getParent().size()) { first = last = layer; } else { GenericDialog gd = new GenericDialog("Choose layer range"); Utils.addLayerRangeChoices(layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; first = layer.getParent().getLayer(gd.getNextChoiceIndex()); last = layer.getParent().getLayer(gd.getNextChoiceIndex()); Utils.log2("first, last: " + first + ", " + last); } Project sub = getProject().createSubproject(roi.getBounds(), first, last); if (null == sub) { Utils.log("ERROR: failed to create subproject."); return; } final LayerSet subls = sub.getRootLayerSet(); Display.createDisplay(sub, subls.getLayer(0)); } else if (command.startsWith("Image stack under selected Arealist")) { if (null == active || active.getClass() != AreaList.class) return; GenericDialog gd = new GenericDialog("Stack options"); String[] types = {"8-bit", "16-bit", "32-bit", "RGB"}; gd.addChoice("type:", types, types[0]); gd.addSlider("Scale: ", 1, 100, 100); gd.showDialog(); if (gd.wasCanceled()) return; final int type; switch (gd.getNextChoiceIndex()) { case 0: type = ImagePlus.GRAY8; break; case 1: type = ImagePlus.GRAY16; break; case 2: type = ImagePlus.GRAY32; break; case 3: type = ImagePlus.COLOR_RGB; break; default: type = ImagePlus.GRAY8; break; } ImagePlus imp = ((AreaList)active).getStack(type, gd.getNextNumber()/100); if (null != imp) imp.show(); } else if (command.equals("Fly through selected Treeline/AreaTree")) { if (null == active || !(active instanceof Tree)) return; Bureaucrat.createAndStart(new Worker.Task("Creating fly through", true) { public void exec() { GenericDialog gd = new GenericDialog("Fly through"); gd.addNumericField("Width", 512, 0); gd.addNumericField("Height", 512, 0); String[] types = new String[]{"8-bit gray", "Color RGB"}; gd.addChoice("Image type", types, types[0]); gd.addSlider("scale", 0, 100, 100); gd.addCheckbox("save to file", false); gd.showDialog(); if (gd.wasCanceled()) return; int w = (int)gd.getNextNumber(); int h = (int)gd.getNextNumber(); int type = 0 == gd.getNextChoiceIndex() ? ImagePlus.GRAY8 : ImagePlus.COLOR_RGB; double scale = gd.getNextNumber(); if (w <=0 || h <=0) { Utils.log("Invalid width or height: " + w + ", " + h); return; } if (0 == scale || Double.isNaN(scale)) { Utils.log("Invalid scale: " + scale); return; } String dir = null; if (gd.getNextBoolean()) { DirectoryChooser dc = new DirectoryChooser("Target directory"); dir = dc.getDirectory(); if (null == dir) return; // canceled dir = Utils.fixDir(dir); } ImagePlus imp = ((Tree)active).flyThroughMarked(w, h, scale/100, type, dir); if (null == imp) { Utils.log("Mark a node first!"); return; } imp.show(); } }, project); } else if (command.startsWith("Arealists as labels")) { GenericDialog gd = new GenericDialog("Export labels"); gd.addSlider("Scale: ", 1, 100, 100); final String[] options = {"All area list", "Selected area lists"}; gd.addChoice("Export: ", options, options[0]); Utils.addLayerRangeChoices(layer, gd); gd.addCheckbox("Visible only", true); gd.showDialog(); if (gd.wasCanceled()) return; final float scale = (float)(gd.getNextNumber() / 100); java.util.List al = 0 == gd.getNextChoiceIndex() ? layer.getParent().getZDisplayables(AreaList.class) : selection.getSelected(AreaList.class); if (null == al) { Utils.log("No area lists found to export."); return; } // Generics are ... a pain? I don't understand them? They fail when they shouldn't? And so easy to workaround that they are a shame? al = (java.util.List<Displayable>) al; int first = gd.getNextChoiceIndex(); int last = gd.getNextChoiceIndex(); boolean visible_only = gd.getNextBoolean(); if (-1 != command.indexOf("(amira)")) { AreaList.exportAsLabels(al, canvas.getFakeImagePlus().getRoi(), scale, first, last, visible_only, true, true); } else if (-1 != command.indexOf("(tif)")) { AreaList.exportAsLabels(al, canvas.getFakeImagePlus().getRoi(), scale, first, last, visible_only, false, false); } } else if (command.equals("Project properties...")) { project.adjustProperties(); } else if (command.equals("Release memory...")) { Bureaucrat.createAndStart(new Worker("Releasing memory") { public void run() { startedWorking(); try { GenericDialog gd = new GenericDialog("Release Memory"); int max = (int)(IJ.maxMemory() / 1000000); gd.addSlider("Megabytes: ", 0, max, max/2); gd.showDialog(); if (!gd.wasCanceled()) { int n_mb = (int)gd.getNextNumber(); project.getLoader().releaseToFit((long)n_mb*1000000); } } catch (Throwable e) { IJError.print(e); } finally { finishedWorking(); } } }, project); } else if (command.equals("Flush image cache")) { Loader.releaseAllCaches(); } else if (command.equals("Regenerate all mipmaps")) { project.getLoader().regenerateMipMaps(getLayerSet().getDisplayables(Patch.class)); } else if (command.equals("Regenerate mipmaps (selected images)")) { project.getLoader().regenerateMipMaps(selection.getSelected(Patch.class)); } else if (command.equals("Tags...")) { // get a file first File f = Utils.chooseFile(null, "tags", ".xml"); if (null == f) return; if (!Utils.saveToFile(f, getLayerSet().exportTags())) { Utils.logAll("ERROR when saving tags to file " + f.getAbsolutePath()); } } else if (command.equals("Tags ...")) { String[] ff = Utils.selectFile("Import tags"); if (null == ff) return; GenericDialog gd = new GenericDialog("Import tags"); String[] modes = new String[]{"Append to current tags", "Replace current tags"}; gd.addChoice("Import tags mode:", modes, modes[0]); gd.addMessage("Replacing current tags\nwill remove all tags\n from all nodes first!"); gd.showDialog(); if (gd.wasCanceled()) return; getLayerSet().importTags(new StringBuilder(ff[0]).append('/').append(ff[1]).toString(), 1 == gd.getNextChoiceIndex()); } else { Utils.log2("Display: don't know what to do with command " + command); } }}); } private static class UpdateDimensionField implements TextListener { final TextField width, height, scale; final Scrollbar bar; final int initial_width, initial_height; UpdateDimensionField(int initial_width, int initial_height, TextField width, TextField height, TextField scale, Scrollbar bar) { this.initial_width = initial_width; this.initial_height = initial_height; this.width = width; this.height = height; this.scale = scale; this.bar = bar; } public void textValueChanged(TextEvent e) { try { final TextField source = (TextField) e.getSource(); if (scale == source && (scale.isFocusOwner() || bar.isFocusOwner())) { final double sc = Double.parseDouble(scale.getText()) / 100; // update both width.setText(Integer.toString((int) (sc * initial_width + 0.5))); height.setText(Integer.toString((int) (sc * initial_height + 0.5))); } else if (width == source && width.isFocusOwner()) { /* final int width = Integer.toString((int) (width.getText() + 0.5)); final double sc = width / (double)initial_width; scale.setText(Integer.toString((int)(sc * 100 + 0.5))); height.setText(Integer.toString((int)(sc * initial_height + 0.5))); */ set(width, height, initial_width, initial_height); } else if (height == source && height.isFocusOwner()) { set(height, width, initial_height, initial_width); } } catch (NumberFormatException nfe) { Utils.logAll("Unparsable number: " + nfe.getMessage()); } catch (Exception ee) { IJError.print(ee); } } private void set(TextField source, TextField target, int initial_source, int initial_target) { final int dim = (int) ((Double.parseDouble(source.getText()) + 0.5)); final double sc = dim / (double)initial_source; scale.setText(Utils.cutNumber(sc * 100, 3)); target.setText(Integer.toString((int)(sc * initial_target + 0.5))); } } /** Update in all displays the Transform for the given Displayable if it's selected. */ static public void updateTransform(final Displayable displ) { for (final Display d : al_displays) { if (d.selection.contains(displ)) d.selection.updateTransform(displ); } } /** Order the profiles of the parent profile_list by Z order, and fix the ProjectTree.*/ /* private void fixZOrdering(Profile profile) { ProjectThing thing = project.findProjectThing(profile); if (null == thing) { Utils.log2("Display.fixZOrdering: null thing?"); return; } ((ProjectThing)thing.getParent()).fixZOrdering(); project.getProjectTree().updateList(thing.getParent()); } */ /** The number of layers to scroll through with the wheel; 1 by default.*/ public int getScrollStep() { return this.scroll_step; } public void setScrollStep(int scroll_step) { if (scroll_step < 1) scroll_step = 1; this.scroll_step = scroll_step; updateInDatabase("scroll_step"); } protected Bureaucrat importImage() { Worker worker = new Worker("Import image") { /// all this verbosity is what happens when functions are not first class citizens. I could abstract it away by passing a string name "importImage" and invoking it with reflection, but that is an even bigger PAIN public void run() { startedWorking(); try { /// Rectangle srcRect = canvas.getSrcRect(); int x = srcRect.x + srcRect.width / 2; int y = srcRect.y + srcRect.height/ 2; Patch p = project.getLoader().importImage(project, x, y); if (null == p) { finishedWorking(); Utils.showMessage("Could not open the image."); return; } Display.this.getLayerSet().addLayerContentStep(layer); layer.add(p); // will add it to the proper Displays Display.this.getLayerSet().addLayerContentStep(layer); /// } catch (Exception e) { IJError.print(e); } finishedWorking(); } }; return Bureaucrat.createAndStart(worker, getProject()); } protected Bureaucrat importNextImage() { Worker worker = new Worker("Import image") { /// all this verbosity is what happens when functions are not first class citizens. I could abstract it away by passing a string name "importImage" and invoking it with reflection, but that is an even bigger PAIN public void run() { startedWorking(); try { Rectangle srcRect = canvas.getSrcRect(); int x = srcRect.x + srcRect.width / 2;// - imp.getWidth() / 2; int y = srcRect.y + srcRect.height/ 2;// - imp.getHeight()/ 2; Patch p = project.getLoader().importNextImage(project, x, y); if (null == p) { Utils.showMessage("Could not open next image."); finishedWorking(); return; } Display.this.getLayerSet().addLayerContentStep(layer); layer.add(p); // will add it to the proper Displays Display.this.getLayerSet().addLayerContentStep(layer); } catch (Exception e) { IJError.print(e); } finishedWorking(); } }; return Bureaucrat.createAndStart(worker, getProject()); } /** Make the given channel have the given alpha (transparency). */ public void setChannel(int c, float alpha) { int a = (int)(255 * alpha); int l = (c_alphas&0xff000000)>>24; int r = (c_alphas&0xff0000)>>16; int g = (c_alphas&0xff00)>>8; int b = c_alphas&0xff; switch (c) { case Channel.MONO: // all to the given alpha c_alphas = (l<<24) + (r<<16) + (g<<8) + b; // parenthesis are NECESSARY break; case Channel.RED: // modify only the red c_alphas = (l<<24) + (a<<16) + (g<<8) + b; break; case Channel.GREEN: c_alphas = (l<<24) + (r<<16) + (a<<8) + b; break; case Channel.BLUE: c_alphas = (l<<24) + (r<<16) + (g<<8) + a; break; } //Utils.log2("c_alphas: " + c_alphas); //canvas.setUpdateGraphics(true); canvas.repaint(true); updateInDatabase("c_alphas"); } /** Set the channel as active and the others as inactive. */ public void setActiveChannel(Channel channel) { for (int i=0; i<4; i++) { if (channel != channels[i]) channels[i].setActive(false); else channel.setActive(true); } Utils.updateComponent(panel_channels); transp_slider.setValue((int)(channel.getAlpha() * 100)); } public int getDisplayChannelAlphas() { return c_alphas; } // rename this method and the getDisplayChannelAlphas ! They sound the same! public int getChannelAlphas() { return ((int)(channels[0].getAlpha() * 255)<<24) + ((int)(channels[1].getAlpha() * 255)<<16) + ((int)(channels[2].getAlpha() * 255)<<8) + (int)(channels[3].getAlpha() * 255); } public int getChannelAlphasState() { return ((channels[0].isSelected() ? 255 : 0)<<24) + ((channels[1].isSelected() ? 255 : 0)<<16) + ((channels[2].isSelected() ? 255 : 0)<<8) + (channels[3].isSelected() ? 255 : 0); } /** Show the layer in the front Display, or in a new Display if the front Display is showing a layer from a different LayerSet. */ static public void showFront(final Layer layer) { Display display = front; if (null == display || display.layer.getParent() != layer.getParent()) { display = new Display(layer.getProject(), layer, null); // gets set to front } else { display.setLayer(layer); } } /** Show the given Displayable centered and selected. If select is false, the selection is cleared. */ static public void showCentered(Layer layer, Displayable displ, boolean select, boolean shift_down) { // see if the given layer belongs to the layer set being displayed Display display = front; // to ensure thread consistency to some extent if (null == display || display.layer.getParent() != layer.getParent()) { display = new Display(layer.getProject(), layer, displ); // gets set to front } else if (display.layer != layer) { display.setLayer(layer); } if (select) { if (!shift_down) display.selection.clear(); display.selection.add(displ); } else { display.selection.clear(); } display.showCentered(displ); } /** Center the view, if possible, on x,y. It's not possible when zoomed out, in which case it will try to do its best. */ public final void center(final double x, final double y) { SwingUtilities.invokeLater(new Runnable() { public void run() { Rectangle r = (Rectangle)canvas.getSrcRect().clone(); r.x = (int)x - r.width/2; r.y = (int)y - r.height/2; canvas.center(r, canvas.getMagnification()); }}); } public final void center(final Coordinate c) { if (null == c) return; slt.set(c.layer); center(c.x, c.y); } public final void centerIfNotWithinSrcRect(final Coordinate c) { if (null == c) return; slt.set(c.layer); Rectangle srcRect = canvas.getSrcRect(); if (srcRect.contains((int)(c.x+0.5), (int)(c.y+0.5))) return; center(c.x, c.y); } public final void animateBrowsingTo(final Coordinate c) { if (null == c) return; final double padding = 50/canvas.getMagnification(); // 50 screen pixels canvas.animateBrowsing(new Rectangle((int)(c.x - padding), (int)(c.y - padding), (int)(2*padding), (int)(2*padding)), c.layer); } static public final void centerAt(final Coordinate c) { centerAt(c, false, false); } static public final void centerAt(final Coordinate<Displayable> c, final boolean select, final boolean shift_down) { if (null == c) return; SwingUtilities.invokeLater(new Runnable() { public void run() { Layer la = c.layer; if (null == la) { if (null == c.object) return; la = c.object.getProject().getRootLayerSet().getLayer(0); if (null == la) return; // nothing to center on } Display display = front; if (null == display || la.getParent() != display.getLayerSet()) { display = new Display(la.getProject(), la); // gets set to front } display.center(c); if (select) { if (!shift_down) display.selection.clear(); display.selection.add(c.object); } }}); } private final void showCentered(final Displayable displ) { if (null == displ) return; SwingUtilities.invokeLater(new Runnable() { public void run() { displ.setVisible(true); Rectangle box = displ.getBoundingBox(); if (0 == box.width && 0 == box.height) { box.width = 100; // old: (int)layer.getLayerWidth(); box.height = 100; // old: (int)layer.getLayerHeight(); } else if (0 == box.width) { box.width = box.height; } else if (0 == box.height) { box.height = box.width; } canvas.showCentered(box); scrollToShow(displ); if (displ instanceof ZDisplayable) { // scroll to first layer that has a point ZDisplayable zd = (ZDisplayable)displ; setLayer(zd.getFirstLayer()); } }}); } public void eventOccurred(final int eventID) { if (IJEventListener.FOREGROUND_COLOR_CHANGED == eventID) { if (this != front || null == active || !project.isInputEnabled()) return; selection.setColor(Toolbar.getForegroundColor()); Display.repaint(front.layer, selection.getBox(), 0); } else if (IJEventListener.TOOL_CHANGED == eventID) { Display.repaintToolbar(); } } public void imageClosed(ImagePlus imp) {} public void imageOpened(ImagePlus imp) {} /** Release memory captured by the offscreen images */ static public void flushAll() { for (final Display d : al_displays) { d.canvas.flush(); } //System.gc(); Thread.yield(); } /** Can be null. */ static public Display getFront() { return front; } static public void setCursorToAll(final Cursor c) { for (final Display d : al_displays) { d.frame.setCursor(c); } } protected void setCursor(Cursor c) { frame.setCursor(c); } /** Used by the Displayable to update the visibility and locking state checkboxes in other Displays. */ static public void updateCheckboxes(final Displayable displ, final int cb, final boolean state) { for (final Display d : al_displays) { DisplayablePanel dp = d.ht_panels.get(displ); if (null != dp) { dp.updateCheckbox(cb, state); } } } /** Set the checkbox @param cb state to @param state value, for each Displayable. Assumes all Displayable objects belong to one specific project. */ static public void updateCheckboxes(final Collection<Displayable> displs, final int cb, final boolean state) { if (null == displs || 0 == displs.size()) return; final Project p = displs.iterator().next().getProject(); for (final Display d : al_displays) { if (d.getProject() != p) continue; for (final Displayable displ : displs) { DisplayablePanel dp = d.ht_panels.get(displ); if (null != dp) { dp.updateCheckbox(cb, state); } } } } /** Update the checkbox @param cb state to an appropriate value for each Displayable. Assumes all Displayable objects belong to one specific project. */ static public void updateCheckboxes(final Collection<Displayable> displs, final int cb) { if (null == displs || 0 == displs.size()) return; final Project p = displs.iterator().next().getProject(); for (final Display d : al_displays) { if (d.getProject() != p) continue; for (final Displayable displ : displs) { DisplayablePanel dp = d.ht_panels.get(displ); if (null != dp) { dp.updateCheckbox(cb); } } } } protected boolean isActiveWindow() { return frame.isActive(); } /** Toggle user input; pan and zoom are always enabled though.*/ static public void setReceivesInput(final Project project, final boolean b) { for (final Display d : al_displays) { if (d.project == project) d.canvas.setReceivesInput(b); } } /** Export the DTD that defines this object. */ static public void exportDTD(final StringBuilder sb_header, final HashSet hs, final String indent) { if (hs.contains("t2_display")) return; // TODO to avoid collisions the type shoud be in a namespace such as tm2:display hs.add("t2_display"); sb_header.append(indent).append("<!ELEMENT t2_display EMPTY>\n") .append(indent).append("<!ATTLIST t2_display id NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display layer_id NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display x NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display y NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display magnification NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display srcrect_x NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display srcrect_y NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display srcrect_width NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display srcrect_height NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display scroll_step NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display c_alphas NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display c_alphas_state NMTOKEN #REQUIRED>\n") ; } /** Export all displays of the given project as XML entries. */ static public void exportXML(final Project project, final Writer writer, final String indent, final Object any) throws Exception { final StringBuilder sb_body = new StringBuilder(); final String in = indent + "\t"; for (final Display d : al_displays) { if (d.project != project) continue; final Rectangle r = d.frame.getBounds(); final Rectangle srcRect = d.canvas.getSrcRect(); final double magnification = d.canvas.getMagnification(); sb_body.append(indent).append("<t2_display id=\"").append(d.id).append("\"\n") .append(in).append("layer_id=\"").append(d.layer.getId()).append("\"\n") .append(in).append("c_alphas=\"").append(d.c_alphas).append("\"\n") .append(in).append("c_alphas_state=\"").append(d.getChannelAlphasState()).append("\"\n") .append(in).append("x=\"").append(r.x).append("\"\n") .append(in).append("y=\"").append(r.y).append("\"\n") .append(in).append("magnification=\"").append(magnification).append("\"\n") .append(in).append("srcrect_x=\"").append(srcRect.x).append("\"\n") .append(in).append("srcrect_y=\"").append(srcRect.y).append("\"\n") .append(in).append("srcrect_width=\"").append(srcRect.width).append("\"\n") .append(in).append("srcrect_height=\"").append(srcRect.height).append("\"\n") .append(in).append("scroll_step=\"").append(d.scroll_step).append("\"\n") ; sb_body.append(indent).append("/>\n"); } writer.write(sb_body.toString()); } private void updateToolTab() { OptionPanel op = null; switch (ProjectToolbar.getToolId()) { case ProjectToolbar.PENCIL: op = Segmentation.fmp.asOptionPanel(); break; case ProjectToolbar.BRUSH: op = AreaWrapper.PP.asOptionPanel(); break; default: break; } scroll_options.getViewport().removeAll(); if (null != op) { op.bottomPadding(); scroll_options.setViewportView(op); } scroll_options.invalidate(); scroll_options.validate(); scroll_options.repaint(); } // Never called; ProjectToolbar.toolChanged is also never called, which should forward here. static public void toolChanged(final String tool_name) { Utils.log2("tool name: " + tool_name); for (final Display d : al_displays) { d.updateToolTab(); Utils.updateComponent(d.toolbar_panel); Utils.log2("updating toolbar_panel"); } } static public void toolChanged(final int tool) { //Utils.log2("int tool is " + tool); if (ProjectToolbar.PEN == tool) { // erase bounding boxes for (final Display d : al_displays) { if (null != d.active) d.repaint(d.layer, d.selection.getBox(), 2); } } for (final Display d: al_displays) { d.updateToolTab(); } if (null != front) { try { WindowManager.setTempCurrentImage(front.canvas.getFakeImagePlus()); } catch (Exception e) {} // may fail when changing tools while opening a Display } } public Selection getSelection() { return selection; } public final boolean isSelected(final Displayable d) { return selection.contains(d); } static public void updateSelection() { Display.updateSelection(null); } static public void updateSelection(final Display calling) { final HashSet hs = new HashSet(); for (final Display d : al_displays) { if (hs.contains(d.layer)) continue; hs.add(d.layer); if (null == d || null == d.selection) { Utils.log2("d is : "+ d + " d.selection is " + d.selection); } else { d.selection.update(); // recomputes box } if (d != calling) { // TODO this is so dirty! if (d.selection.getNLinked() > 1) d.canvas.setUpdateGraphics(true); // this is overkill anyway d.canvas.repaint(d.selection.getLinkedBox(), Selection.PADDING); d.navigator.repaint(true); // everything } } } static public void clearSelection(final Layer layer) { for (final Display d : al_displays) { if (d.layer == layer) d.selection.clear(); } } static public void clearSelection() { for (final Display d : al_displays) { d.selection.clear(); } } static public void clearSelection(final Project p) { for (final Display d : al_displays) { if (d.project == p) d.selection.clear(); } } private void setTempCurrentImage() { WindowManager.setCurrentWindow(canvas.getFakeImagePlus().getWindow(), true); WindowManager.setTempCurrentImage(canvas.getFakeImagePlus()); } /** Check if any display will paint the given Displayable within its srcRect. */ static public boolean willPaint(final Displayable displ) { Rectangle box = null; for (final Display d : al_displays) { if (displ.getLayer() == d.layer) { if (null == box) box = displ.getBoundingBox(null); if (d.canvas.getSrcRect().intersects(box)) { return true; } } } return false; } public void hideDeselected(final boolean not_images) { // hide deselected final ArrayList all = layer.getParent().getZDisplayables(); // a copy all.addAll(layer.getDisplayables()); all.removeAll(selection.getSelected()); if (not_images) all.removeAll(layer.getDisplayables(Patch.class)); for (final Displayable d : (ArrayList<Displayable>)all) { if (d.isVisible()) { d.setVisible(false); Display.updateCheckboxes(d, DisplayablePanel.VISIBILITY_STATE, false); } } Display.update(layer); } /** Cleanup internal lists that may contain the given Displayable. */ static public void flush(final Displayable displ) { for (final Display d : al_displays) { d.selection.removeFromPrev(displ); } } public void resizeCanvas() { GenericDialog gd = new GenericDialog("Resize LayerSet"); gd.addNumericField("new width: ", layer.getLayerWidth(), 1, 8, "pixels"); gd.addNumericField("new height: ", layer.getLayerHeight(), 1, 8, "pixels"); gd.addChoice("Anchor: ", LayerSet.ANCHORS, LayerSet.ANCHORS[7]); gd.showDialog(); if (gd.wasCanceled()) return; float new_width = (float)gd.getNextNumber(); float new_height = (float)gd.getNextNumber(); layer.getParent().setDimensions(new_width, new_height, gd.getNextChoiceIndex()); // will complain and prevent cropping existing Displayable objects } /* // To record layer changes -- but it's annoying, this is visualization not data. static class DoSetLayer implements DoStep { final Display display; final Layer layer; DoSetLayer(final Display display) { this.display = display; this.layer = display.layer; } public Displayable getD() { return null; } public boolean isEmpty() { return false; } public boolean apply(final int action) { display.setLayer(layer); } public boolean isIdenticalTo(final Object ob) { if (!ob instanceof DoSetLayer) return false; final DoSetLayer dsl = (DoSetLayer) ob; return dsl.display == this.display && dsl.layer == this.layer; } } */ protected void duplicateLinkAndSendTo(final Displayable active, final int position, final Layer other_layer) { if (null == active || !(active instanceof Profile)) return; if (active.getLayer() == other_layer) return; // can't do that! // set current state Set<DoStep> dataedits = new HashSet<DoStep>(); dataedits.add(new Displayable.DoEdit(active).init(active, new String[]{"data"})); // the links! getLayerSet().addChangeTreesStep(dataedits); Profile profile = project.getProjectTree().duplicateChild((Profile)active, position, other_layer); if (null == profile) { getLayerSet().removeLastUndoStep(); return; } active.link(profile); other_layer.add(profile); slt.setAndWait(other_layer); selection.add(profile); // set new state dataedits = new HashSet<DoStep>(); dataedits.add(new Displayable.DoEdit(active).init(active, new String[]{"data"})); // the links! dataedits.add(new Displayable.DoEdit(profile).init(profile, new String[]{"data"})); // the links! getLayerSet().addChangeTreesStep(dataedits); } private final HashMap<Color,Layer> layer_channels = new HashMap<Color,Layer>(); private final TreeMap<Integer,LayerPanel> layer_alpha = new TreeMap<Integer,LayerPanel>(); private final HashMap<Layer,Byte> layer_composites = new HashMap<Layer,Byte>(); boolean invert_colors = false; protected byte getLayerCompositeMode(final Layer layer) { synchronized (layer_composites) { Byte b = layer_composites.get(layer); return null == b ? Displayable.COMPOSITE_NORMAL : b; } } protected void setLayerCompositeMode(final Layer layer, final byte compositeMode) { synchronized (layer_composites) { if (-1 == compositeMode || Displayable.COMPOSITE_NORMAL == compositeMode) { layer_composites.remove(layer); } else { layer_composites.put(layer, compositeMode); } } } protected void resetLayerComposites() { synchronized (layer_composites) { layer_composites.clear(); } canvas.repaint(true); } /** Remove all red/blue coloring of layers, and repaint canvas. */ protected void resetLayerColors() { synchronized (layer_channels) { for (final Layer l : new ArrayList<Layer>(layer_channels.values())) { // avoid concurrent modification exception final LayerPanel lp = layer_panels.get(l); lp.setColor(Color.white); setColorChannel(lp.layer, Color.white); lp.slider.setEnabled(true); } layer_channels.clear(); } canvas.repaint(true); } /** Set all layer alphas to zero, and repaint canvas. */ protected void resetLayerAlphas() { synchronized (layer_channels) { for (final LayerPanel lp : new ArrayList<LayerPanel>(layer_alpha.values())) { lp.setAlpha(0); } layer_alpha.clear(); // should have already been cleared } canvas.repaint(true); } /** Add to layer_alpha table, or remove if alpha is zero. */ protected void storeLayerAlpha(final LayerPanel lp, final float a) { synchronized (layer_channels) { if (M.equals(0, a)) { layer_alpha.remove(lp.layer.getParent().indexOf(lp.layer)); } else { layer_alpha.put(lp.layer.getParent().indexOf(lp.layer), lp); } } } static protected final int REPAINT_SINGLE_LAYER = 0; static protected final int REPAINT_MULTI_LAYER = 1; static protected final int REPAINT_RGB_LAYER = 2; /** Sets the values atomically, returns the painting mode. */ protected int getPaintMode(final HashMap<Color,Layer> hm, final ArrayList<LayerPanel> list) { synchronized (layer_channels) { if (layer_channels.size() > 0) { hm.putAll(layer_channels); hm.put(Color.green, this.layer); return REPAINT_RGB_LAYER; } list.addAll(layer_alpha.values()); final int len = list.size(); if (len > 1) return REPAINT_MULTI_LAYER; if (1 == len) { if (list.get(0).layer == this.layer) return REPAINT_SINGLE_LAYER; // normal mode return REPAINT_MULTI_LAYER; } return REPAINT_SINGLE_LAYER; } } /** Set a layer to be painted as a specific color channel in the canvas. * Only Color.red and Color.blue are accepted. * Color.green is reserved for the current layer. */ protected void setColorChannel(final Layer layer, final Color color) { synchronized (layer_channels) { if (Color.white == color) { // Remove for (final Iterator<Layer> it = layer_channels.values().iterator(); it.hasNext(); ) { if (it.next() == layer) { it.remove(); break; } } canvas.repaint(); } else if (Color.red == color || Color.blue == color) { // Reset current of that color, if any, to white final Layer l = layer_channels.remove(color); if (null != l) layer_panels.get(l).setColor(Color.white); // Replace or set new layer_channels.put(color, layer); tabs.repaint(); canvas.repaint(); } else { Utils.log2("Trying to set unacceptable color for layer " + layer + " : " + color); } // enable/disable sliders final boolean b = 0 == layer_channels.size(); for (final LayerPanel lp : layer_panels.values()) lp.slider.setEnabled(b); } this.canvas.repaint(true); } static public final void updateComponentTreeUI() { try { for (final Display d : al_displays) SwingUtilities.updateComponentTreeUI(d.frame); } catch (Exception e) { IJError.print(e); } } /** Snap a Patch to the most overlapping Patch, if any. * This method is a shallow wrap around AlignTask.snap, setting proper undo steps. */ static public final Bureaucrat snap(final Patch patch) { final Set<Displayable> linked = patch.getLinkedGroup(null); patch.getLayerSet().addTransformStep(linked); Bureaucrat burro = AlignTask.snap(patch, null, false); burro.addPostTask(new Runnable() { public void run() { patch.getLayerSet().addTransformStep(linked); }}); return burro; } private Mode mode = new DefaultMode(this); public void setMode(final Mode mode) { ProjectToolbar.setTool(ProjectToolbar.SELECT); this.mode = mode; canvas.repaint(true); scroller.setEnabled(mode.canChangeLayer()); } public Mode getMode() { return mode; } static private final Hashtable<String,ProjectThing> findLandmarkNodes(Project p, String landmarks_type) { Set<ProjectThing> landmark_nodes = p.getRootProjectThing().findChildrenOfTypeR(landmarks_type); Hashtable<String,ProjectThing> map = new Hashtable<String,ProjectThing>(); for (ProjectThing pt : landmark_nodes) { map.put(pt.toString() + "# " + pt.getId(), pt); } return map; } /** @param stack_patch is just a Patch of a series of Patch that make a stack of Patches. */ private boolean insertStack(ProjectThing target_landmarks, Project source, ProjectThing source_landmarks, Patch stack_patch) { List<Ball> l1 = new ArrayList<Ball>(); List<Ball> l2 = new ArrayList<Ball>(); Collection<ProjectThing> b1s = source_landmarks.findChildrenOfType("ball"); // source is the one that has the stack_patch Collection<ProjectThing> b2s = target_landmarks.findChildrenOfType("ball"); // target is this HashSet<String> seen = new HashSet<String>(); for (ProjectThing b1 : b1s) { Ball ball1 = (Ball) b1.getObject(); if (null == ball1) { Utils.log("ERROR: there's an empty 'ball' node in target project" + project.toString()); return false; } String title1 = ball1.getTitle(); for (ProjectThing b2 : b2s) { Ball ball2 = (Ball) b2.getObject(); if (null == ball2) { Utils.log("ERROR: there's an empty 'ball' node in source project" + source.toString()); return false; } if (title1.equals(ball2.getTitle())) { if (seen.contains(title1)) continue; seen.add(title1); l1.add(ball1); l2.add(ball2); } } } if (l1.size() < 4) { Utils.log("ERROR: found only " + l1.size() + " common landmarks: needs at least 4!"); return false; } // Extract coordinates of source project landmarks, in patch stack coordinate space List<float[]> c1 = new ArrayList<float[]>(); for (Ball ball1 : l1) { Map<Layer,double[]> m = ball1.getRawBalls(); if (1 != m.size()) { Utils.log("ERROR: ball object " + ball1 + " from target project " + project + " has " + m.size() + " balls instead of just 1."); return false; } Map.Entry<Layer,double[]> e = m.entrySet().iterator().next(); Layer layer = e.getKey(); double[] xyr = e.getValue(); float[] fin = new float[]{(float)xyr[0], (float)xyr[1]}; AffineTransform affine = ball1.getAffineTransformCopy(); try { affine.preConcatenate(stack_patch.getAffineTransform().createInverse()); } catch (Exception nite) { IJError.print(nite); return false; } float[] fout = new float[2]; affine.transform(fin, 0, fout, 0, 1); c1.add(new float[]{fout[0], fout[1], layer.getParent().indexOf(layer)}); } // Extract coordinates of target (this) project landmarks, in calibrated world space List<float[]> c2 = new ArrayList<float[]>(); for (Ball ball2 : l2) { double[][] b = ball2.getBalls(); if (1 != b.length) { Utils.log("ERROR: ball object " + ball2 + " from source project " + source + " has " + b.length + " balls instead of just 1."); return false; } float[] fin = new float[]{(float)b[0][0], (float)b[0][1]}; AffineTransform affine = ball2.getAffineTransformCopy(); float[] fout = new float[2]; affine.transform(fin, 0, fout, 0, 1); c2.add(new float[]{fout[0], fout[1], (float)b[0][2]}); } // Print landmarks: Utils.log("Landmarks:"); for (Iterator<float[]> it1 = c1.iterator(), it2 = c2.iterator(); it1.hasNext(); ) { Utils.log(Utils.toString(it1.next()) + " <--> " + Utils.toString(it2.next())); } // Create point matches List<PointMatch> pm = new ArrayList<PointMatch>(); for (Iterator<float[]> it1 = c1.iterator(), it2 = c2.iterator(); it1.hasNext(); ) { pm.add(new mpicbg.models.PointMatch(new mpicbg.models.Point(it1.next()), new mpicbg.models.Point(it2.next()))); } // Estimate AffineModel3D AffineModel3D aff3d = new AffineModel3D(); try { aff3d.fit(pm); } catch (Exception e) { IJError.print(e); return false; } // Create and add the Stack String path = stack_patch.getImageFilePath(); Stack st = new Stack(project, new File(path).getName(), 0, 0, getLayerSet().getLayers().get(0), path); st.setInvertibleCoordinateTransform(aff3d); getLayerSet().add(st); return true; } static private List<Patch> getPatchStacks(final LayerSet ls) { HashSet<Patch> stacks = new HashSet<Patch>(); for (Patch pa : (Collection<Patch>) (Collection) ls.getDisplayables(Patch.class)) { PatchStack ps = pa.makePatchStack(); if (1 == ps.getNSlices()) continue; stacks.add(ps.getPatch(0)); } return new ArrayList<Patch>(stacks); } private void montage(int type) { final Layer la = layer; if (selection.getSelected(Patch.class).size() < 2) { Utils.showMessage("Montage needs 2 or more images selected"); return; } final Collection<Displayable> col = la.getParent().addTransformStepWithData(Arrays.asList(new Layer[]{la})); Bureaucrat burro; switch (type) { case 0: burro = AlignTask.alignSelectionTask(selection); break; case 1: burro = StitchingTEM.montageWithPhaseCorrelation( (Collection<Patch>) (Collection) selection.getSelected(Patch.class)); break; default: Utils.log("Unknown montage type " + type); return; } if (null == burro) return; burro.addPostTask(new Runnable() { public void run() { la.getParent().enlargeToFit(selection.getAffected()); la.getParent().addTransformStepWithData(col); }}); } }
false
false
null
null
diff --git a/src/com/jpii/navalbattle/pavo/OmniMap.java b/src/com/jpii/navalbattle/pavo/OmniMap.java index b9f7f968..2d5ee8ab 100644 --- a/src/com/jpii/navalbattle/pavo/OmniMap.java +++ b/src/com/jpii/navalbattle/pavo/OmniMap.java @@ -1,65 +1,68 @@ package com.jpii.navalbattle.pavo; import java.awt.event.*; import java.awt.image.*; import java.awt.*; import maximusvladimir.dagen.Rand; import com.jpii.navalbattle.data.Constants; import com.jpii.navalbattle.renderer.Helper; import com.jpii.navalbattle.renderer.RenderConstants; public class OmniMap extends Renderable { int mx,my; World w; public OmniMap(World w) { super(); this.w = w; setSize(100,100); buffer = (new BufferedImage(getWidth(), getHeight(),BufferedImage.TYPE_INT_RGB)); } public void mouseMoved(MouseEvent me) { mx = me.getX(); my = me.getY(); render(); } public void render() { Graphics2D g = PavoHelper.createGraphics(getBuffer()); Rand rand = new Rand(Constants.MAIN_SEED); for (int x = 0; x < 100/3; x++) { for (int y = 0; y < 100/3; y++) { int strx = x * PavoHelper.getGameWidth(w.getWorldSize()); int stry = y * PavoHelper.getGameHeight(w.getWorldSize()); float frsh = McRegion.getPoint(strx,stry); int opcode = (int)(frsh*255.0f); if (opcode > 255) opcode = 255; if (opcode < 0) opcode = 0; g.setColor(new Color(opcode,opcode,opcode)); if (opcode < 130) { - int nawo = rand.nextInt(-5, 8); - g.setColor(Helper.adjust(Helper.randomise(new Color(83+nawo,83+nawo,132+nawo), - 5, rand, false), 1 - ((frsh)/2 / RenderConstants.GEN_WATER_HEIGHT), 30)); + g.setColor(new Color(83,83,132)); + //int nawo = rand.nextInt(-5, 8); + //g.setColor(Helper.adjust(Helper.randomise(new Color(83+nawo,83+nawo,132+nawo), + //5, rand, false), 1 - ((frsh)/2 / RenderConstants.GEN_WATER_HEIGHT), 30)); } else if (opcode < 135) { - g.setColor(Helper.adjust(Helper.randomise(RenderConstants.GEN_SAND_COLOR, - RenderConstants.GEN_COLOR_DIFF, rand, false), (1.0-frsh)/2, 50)); + g.setColor(RenderConstants.GEN_SAND_COLOR); + //g.setColor(Helper.adjust(Helper.randomise(RenderConstants.GEN_SAND_COLOR, + //RenderConstants.GEN_COLOR_DIFF, rand, false), (1.0-frsh)/2, 50)); } else{ - g.setColor(Helper.adjust(Helper.randomise(RenderConstants.GEN_GRASS_COLOR, - RenderConstants.GEN_COLOR_DIFF, rand, false), (1.0-frsh)/2, 50)); + g.setColor(RenderConstants.GEN_GRASS_COLOR); + //g.setColor(Helper.adjust(Helper.randomise(RenderConstants.GEN_GRASS_COLOR, + // RenderConstants.GEN_COLOR_DIFF, rand, false), (1.0-frsh)/2, 50)); } g.fillRect(x*3,y*3,4,4); //g.drawLine(x,y,x,y); } } int rwx = (int) (Math.abs(w.getScreenX()) * 33.333333 / (PavoHelper.getGameWidth(w.getWorldSize()) * 100))*3; int rwy = (int) (Math.abs(w.getScreenY()) * 33.333333 / (PavoHelper.getGameHeight(w.getWorldSize()) * 100))*3; g.setColor(Color.red); g.fillRect(rwx-1,rwy-1,2,2); } } diff --git a/src/com/jpii/navalbattle/pavo/TimeManager.java b/src/com/jpii/navalbattle/pavo/TimeManager.java index 8a355855..b71910eb 100644 --- a/src/com/jpii/navalbattle/pavo/TimeManager.java +++ b/src/com/jpii/navalbattle/pavo/TimeManager.java @@ -1,95 +1,95 @@ package com.jpii.navalbattle.pavo; import java.awt.*; import java.awt.image.BufferedImage; public class TimeManager extends Renderable { public static int DayNightTotalLengthSeconds = 120; - public static int NightDarkness = 175; + public static int NightDarkness = 70; private int hour = 0; private String desc = ""; private double currentTime = ((double)DayNightTotalLengthSeconds)/2; private Color cdr = new Color(0,0,0,0); private Color lcd = new Color(0,0,0,0); private int timeD = 0; private int minute = 0; private int lsw, lsh; public TimeManager() { lsw = DynamicConstants.WND_WDTH; lsh = DynamicConstants.WND_HGHT; } public void update() { int le = DayNightTotalLengthSeconds; int alph = 0; double tofd = currentTime; if (currentTime < DayNightTotalLengthSeconds) currentTime += (DayNightTotalLengthSeconds/1000.0); else currentTime = 0; int nightl = 5; if (tofd > 0 && tofd < le / nightl/2) { double t = tofd; alph = (int)(t * NightDarkness / (le / nightl/2)); if (alph < 0) alph = 0; if (alph > 255) alph = 255; desc = "Sunset"; timeD = 0; } else if (tofd > le / nightl/2 && tofd < le / nightl * 2) { alph = NightDarkness; desc = "Night"; timeD = 1; } else if (tofd > le / nightl * 2 && tofd < (le / nightl * 2) + (le / nightl / 2)) { double t = ((le / nightl * 2) + (le / nightl / 2))- tofd; alph = (int)(t * NightDarkness / (le / nightl /2)); if (alph < 0) alph = 0; if (alph > 255) alph = 255; desc = "Sunrise"; timeD = 2; } else { desc = "Day"; timeD = 3; } cdr = new Color(11,15,23,alph); if (!lcd.equals(cdr) || lsw != DynamicConstants.WND_WDTH || lsh != DynamicConstants.WND_HGHT) { buffer = new BufferedImage(DynamicConstants.WND_WDTH,DynamicConstants.WND_HGHT,BufferedImage.TYPE_INT_ARGB); lsw = DynamicConstants.WND_WDTH; lsh = DynamicConstants.WND_HGHT; Graphics g = buffer.getGraphics(); g.setColor(cdr); g.fillRect(0,0,DynamicConstants.WND_WDTH,DynamicConstants.WND_HGHT); lcd = cdr; } double thour = (((tofd) * 24) / DayNightTotalLengthSeconds)+18.0; if (thour > 24) { thour = 24 - thour; } if (thour < 0) thour = thour * -1; //minute = ((int)((tofd * 1440) / DayNightTotalLengthSeconds));// - (hour * 60); int d = (int)(thour); minute = (int)((thour - d) * 60); hour = d; } public int getState() { return timeD; } public String getTimeDescription() { return desc; } public int getCurrentHour() { return hour; } public int getCurrentMinutes() { return minute; } } diff --git a/src/com/jpii/navalbattle/pavo/WindowManager.java b/src/com/jpii/navalbattle/pavo/WindowManager.java index 214ebde2..34b2998a 100644 --- a/src/com/jpii/navalbattle/pavo/WindowManager.java +++ b/src/com/jpii/navalbattle/pavo/WindowManager.java @@ -1,84 +1,84 @@ package com.jpii.navalbattle.pavo; import java.awt.Graphics2D; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.util.ArrayList; public class WindowManager extends Renderable{ ArrayList<GameWindow> wins; public WindowManager() { wins = new ArrayList<GameWindow>(); Inst = this; } public void add(GameWindow wnd) { wins.add(wnd); } public void remove(GameWindow wnd) { wins.remove(wnd); } public GameWindow get(int index) { return wins.get(index); } public int size() { return wins.size(); } public void mouseMove(MouseEvent me) { } public static WindowManager Inst; public boolean mouseUp(MouseEvent me) { int mx = me.getX(); int my = me.getY(); boolean flag = false; for (int c = 0; c < wins.size(); c++) { GameWindow gw = wins.get(c); if (gw!=null) { - if (gw.isTitleShown()) { + if (gw.isTitleShown() && gw.isVisible()) { if (mx >= gw.getWidth()-23+gw.getX() && mx <= gw.getWidth()-3+gw.getX() && my >= gw.getY() + 2 && my <= gw.getY() + 20) { gw.onCloseCalled(); flag = true; } gw.checkOtherDown(me); } } } return flag; } public void mouseDown(MouseEvent me) { } public boolean mouseDragged(MouseEvent me) { int mx = me.getX(); int my = me.getY(); boolean flag = false; for (int c = 0; c < wins.size(); c++) { GameWindow gw = wins.get(c); if (gw!=null) { - if (gw.isTitleShown()) { + if (gw.isTitleShown() && gw.isVisible()) { if (mx >= gw.getX() - 10 && mx <= gw.getX()+gw.getWidth()+10 && my >= gw.getY()-10 && my <= gw.getY()+34) { gw.setLoc(mx - (gw.getWidth()/2), my - 12); return true; } } } } return flag; } public void render() { buffer = new BufferedImage(DynamicConstants.WND_WDTH,DynamicConstants.WND_HGHT,BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = PavoHelper.createGraphics(getBuffer()); for (int c = 0; c < wins.size(); c++) { GameWindow gw = wins.get(c); if (gw!=null) { if (gw.isVisible()) { int gwx = gw.getX(); int gwy = gw.getY(); BufferedImage gwb = gw.getBuffer(); g2.drawImage(gwb, gwx,gwy, null); } } } } }
false
false
null
null
diff --git a/src/org/flowvisor/FlowVisor.java b/src/org/flowvisor/FlowVisor.java index 6850afd..c9adb91 100644 --- a/src/org/flowvisor/FlowVisor.java +++ b/src/org/flowvisor/FlowVisor.java @@ -1,447 +1,447 @@ package org.flowvisor; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.apache.xmlrpc.webserver.WebServer; import org.flowvisor.api.APIServer; import org.flowvisor.api.JettyServer; import org.flowvisor.config.ConfDBHandler; import org.flowvisor.config.ConfigError; import org.flowvisor.config.FVConfig; import org.flowvisor.config.FVConfigurationController; import org.flowvisor.config.FlowSpaceImpl; import org.flowvisor.config.FlowvisorImpl; import org.flowvisor.config.SliceImpl; import org.flowvisor.config.SwitchImpl; import org.flowvisor.events.FVEventHandler; import org.flowvisor.events.FVEventLoop; import org.flowvisor.exceptions.UnhandledEvent; import org.flowvisor.log.FVLog; import org.flowvisor.log.LogLevel; import org.flowvisor.log.StderrLogger; import org.flowvisor.log.ThreadLogger; import org.flowvisor.message.FVMessageFactory; import org.flowvisor.ofswitch.OFSwitchAcceptor; import org.flowvisor.ofswitch.TopologyController; import org.flowvisor.resources.SlicerLimits; import org.openflow.example.cli.Option; import org.openflow.example.cli.Options; import org.openflow.example.cli.ParseException; import org.openflow.example.cli.SimpleCLI; public class FlowVisor { // VENDOR EXTENSION ID public final static int FLOWVISOR_VENDOR_EXTENSION = 0x80000001; // VERSION - public final static String FLOWVISOR_VERSION = "flowvisor-0.11.1"; + public final static String FLOWVISOR_VERSION = "flowvisor-0.11.2"; public final static int FLOWVISOR_DB_VERSION = 2; // Max slicename len ; used in LLDP for now; needs to be 1 byte public final static int MAX_SLICENAME_LEN = 255; /********/ String configFile = null; List<FVEventHandler> handlers; private int port; private int jettyPort = -1; private WebServer apiServer; static FlowVisor instance; private SlicerLimits sliceLimits; FVMessageFactory factory; private static final Options options = Options.make(new Option[] { new Option("d", "debug", LogLevel.NOTE.toString(), "Override default logging threshold in config"), new Option("l", "logging", "Log to stderr instead of syslog"), new Option("p", "port", 0, "Override port from config"), new Option("h", "help", "Print help"), new Option("j", "jetty port",-1, "Override jetty port from config"), }); public FlowVisor() { this.port = 0; this.handlers = new ArrayList<FVEventHandler>(); this.factory = new FVMessageFactory(); } /* * Unregister this event handler from the system */ /** * @return the configFile */ public String getConfigFile() { return configFile; } /** * @param configFile * the configFile to set */ public void setConfigFile(String configFile) { this.configFile = configFile; } /** * @return the port */ public int getPort() { return port; } public int getJettyPort(){ return jettyPort; } /** * @param port * the port to set */ public void setPort(int port) { try { FlowvisorImpl.getProxy().setAPIWSPort(port); } catch (ConfigError e) { FVLog.log(LogLevel.WARN, null, "Failed to set api port"); } } public void setJettyPort(int port){ try { FlowvisorImpl.getProxy().setJettyPort(port); } catch (ConfigError e) { FVLog.log(LogLevel.WARN, null, "Failed to set jetty port"); } } /** * @return the factory */ public FVMessageFactory getFactory() { return factory; } /** * @param factory * the factory to set */ public void setFactory(FVMessageFactory factory) { this.factory = factory; } public synchronized boolean unregisterHandler(FVEventHandler handler) { if (handlers.contains(handler)) { handlers.remove(handler); return true; } return false; } public void run() throws ConfigError, IOException, UnhandledEvent { FlowVisor.setInstance(this); Runtime.getRuntime().addShutdownHook(new ShutdownHook()); // init polling loop FVLog.log(LogLevel.INFO, null, "initializing poll loop"); FVEventLoop pollLoop = new FVEventLoop(); sliceLimits = new SlicerLimits(); JettyServer.spawnJettyServer(FVConfig.getJettyPort());//jettyPort); if (port == 0) port = FVConfig.getListenPort(); // init topology discovery, if configured for it if (TopologyController.isConfigured()) handlers.add(TopologyController.spawn(pollLoop)); // init switchAcceptor OFSwitchAcceptor acceptor = new OFSwitchAcceptor(pollLoop, port, 16); acceptor.setSlicerLimits(sliceLimits); handlers.add(acceptor); // start XMLRPC UserAPI server; FIXME not async! try { this.apiServer = APIServer.spawn(); } catch (Exception e) { FVLog.log(LogLevel.FATAL, null, "failed to spawn APIServer"); e.printStackTrace(); System.exit(-1); } // print some system state boolean flowdb = false; try { if (FVConfig.getFlowTracking()) flowdb = true; } catch (ConfigError e) { // assume off if not set FVConfig.setFlowTracking(false); this.checkPointConfig(); } if (!flowdb) FVLog.log(LogLevel.INFO, null, "flowdb: Disabled"); // start event processing pollLoop.doEventLoop(); } /** * FlowVisor Daemon Executable Main * * Takes a config file as only parameter * * @param args * config file * @throws Throwable */ public static void main(String args[]) throws Throwable { ThreadLogger threadLogger = new ThreadLogger(); Thread.setDefaultUncaughtExceptionHandler(threadLogger); long lastRestart = System.currentTimeMillis(); FVConfigurationController.init(new ConfDBHandler()); while (true) { FlowVisor fv = new FlowVisor(); fv.parseArgs(args); try { // load config from file updateDB(); if (fv.configFile != null) FVConfig.readFromFile(fv.configFile); else // Set temp file for config checkpointing. fv.configFile = "/tmp/flowisor"; fv.run(); } catch (NullPointerException e) { e.printStackTrace(); System.err.println("Errors occurred. Please make sure that the database exists and/or no other FlowVisor is running."); System.exit(0); } catch (Throwable e) { e.printStackTrace(); FVLog.log(LogLevel.CRIT, null, "MAIN THREAD DIED!!!"); FVLog.log(LogLevel.CRIT, null, "----------------------------"); threadLogger.uncaughtException(Thread.currentThread(), e); FVLog.log(LogLevel.CRIT, null, "----------------------------"); if ((lastRestart + 5000) > System.currentTimeMillis()) { System.err.println("respawning too fast -- DYING"); FVLog.log(LogLevel.CRIT, null, "respawning too fast -- DYING"); fv.tearDown(); throw e; } else { FVLog.log(LogLevel.CRIT, null, "restarting after main thread died"); lastRestart = System.currentTimeMillis(); fv.tearDown(); } fv = null; System.gc(); // give the system a bit to clean up after itself Thread.sleep(1000); } } } private void parseArgs(String[] args) { SimpleCLI cmd = null; try { cmd = SimpleCLI.parse(options, args); } catch (ParseException e) { usage("ParseException: " + e.toString()); } if (cmd == null) usage("need to specify arguments"); int i = cmd.getOptind(); if (i >= args.length) setConfigFile(null); else setConfigFile(args[i]); if (cmd.hasOption("d")) { FVLog.setThreshold(LogLevel.valueOf(cmd.getOptionValue("d"))); System.err.println("Set default logging threshold to " + FVLog.getThreshold()); } if (cmd.hasOption("l")) { System.err.println("Setting debugging mode: all logs to stderr"); FVLog.setDefaultLogger(new StderrLogger()); } if (cmd.hasOption("p")) { int p = Integer.valueOf(cmd.getOptionValue("p")); setPort(p); System.err.println("Writting port to config: setting to " + p); } if(cmd.hasOption("j")){ int jp = Integer.valueOf(cmd.getOptionValue("j")); setJettyPort(jp); System.err.println("Writting jetty port to config: setting to " + jp); } } private void tearDown() { if (this.apiServer != null) this.apiServer.shutdown(); // shutdown the API Server List<FVEventHandler> tmp = this.handlers; this.handlers = new LinkedList<FVEventHandler>(); for (Iterator<FVEventHandler> it = tmp.iterator(); it.hasNext();) { FVEventHandler handler = it.next(); it.remove(); handler.tearDown(); } } /** * Print usage message and warning string then exit * * @param string * warning */ private static void usage(String string) { System.err.println("FlowVisor version: " + FLOWVISOR_VERSION); System.err .println("Rob Sherwood: rsherwood@telekom.com/rob.sherwood@stanford.edu"); System.err .println("---------------------------------------------------------------"); System.err.println("err: " + string); SimpleCLI.printHelp("FlowVisor [options] config.xml", FlowVisor.getOptions()); System.exit(-1); } private static Options getOptions() { return FlowVisor.options; } /** * Get the running fv instance * * @return */ public static FlowVisor getInstance() { return instance; } /** * Set the running fv instance * * @param instance */ public static void setInstance(FlowVisor instance) { FlowVisor.instance = instance; } /** * Returns a unique, shallow copy of the list of event handlers registered * in the flowvisor * * Is unique to prevent concurrency problems, i.e., when wakling through the * list and a handler gets deleted * * @return */ public synchronized ArrayList<FVEventHandler> getHandlersCopy() { return new ArrayList<FVEventHandler>(handlers); } public void addHandler(FVEventHandler handler) { this.handlers.add(handler); } public void removeHandler(FVEventHandler handler) { this.handlers.remove(handler); } public void setHandlers(ArrayList<FVEventHandler> handlers) { this.handlers = handlers; } /** * Save the running config back to disk * * Write to a temp file and only if it succeeds, move it into place * * FIXME: add versioning */ public void checkPointConfig() { // FIXME dump db file!! String tmpFile = this.configFile + ".tmp"; // assumes no one else can // write to same dir // else security problem // do we want checkpointing? try { if (!FVConfig.getCheckPoint()) return; } catch (ConfigError e1) { FVLog.log(LogLevel.WARN, null, "Checkpointing config not set: assuming you want checkpointing"); } try { FVConfig.writeToFile(tmpFile); } catch (FileNotFoundException e) { FVLog.log(LogLevel.CRIT, null, "failed to save config: tried to write to '" + tmpFile + "' but got FileNotFoundException"); return; } // sometimes, Java has the stoopidest ways of doing things :-( File tmp = new File(tmpFile); if (tmp.length() == 0) { FVLog.log(LogLevel.CRIT, null, "failed to save config: tried to write to '" + tmpFile + "' but wrote empty file"); return; } tmp.renameTo(new File(this.configFile)); FVLog.log(LogLevel.INFO, null, "Saved config to disk at " + this.configFile); } public String getInstanceName() { // TODO pull from FVConfig; needed for slice stiching return "magic flowvisor1"; } private static void updateDB() { int db_version = FlowvisorImpl.getProxy().fetchDBVersion(); if (db_version == FLOWVISOR_DB_VERSION) return; if (db_version > FLOWVISOR_DB_VERSION) FVLog.log(LogLevel.WARN, null, "Your FlowVisor comes from the future."); FlowvisorImpl.getProxy().updateDB(db_version); SliceImpl.getProxy().updateDB(db_version); FlowSpaceImpl.getProxy().updateDB(db_version); SwitchImpl.getProxy().updateDB(db_version); } } diff --git a/src/org/flowvisor/resources/ratelimit/FixedIntervalRefillStrategy.java b/src/org/flowvisor/resources/ratelimit/FixedIntervalRefillStrategy.java index 0c142f3..ff63b34 100644 --- a/src/org/flowvisor/resources/ratelimit/FixedIntervalRefillStrategy.java +++ b/src/org/flowvisor/resources/ratelimit/FixedIntervalRefillStrategy.java @@ -1,33 +1,32 @@ package org.flowvisor.resources.ratelimit; import java.util.concurrent.TimeUnit; import org.flowvisor.log.FVLog; import org.flowvisor.log.LogLevel; public class FixedIntervalRefillStrategy implements RefillStrategy { private final long numTokens; private final long period; private long nextRefillTime; public FixedIntervalRefillStrategy(long numTokens, long period, TimeUnit unit) { this.numTokens = numTokens; this.period = unit.toNanos(period); this.nextRefillTime = -1; } public synchronized long refill() { long now = System.nanoTime(); - FVLog.log(LogLevel.DEBUG, null, "now is ", now, " nextrefilltime is ", nextRefillTime); if (now < nextRefillTime) { return 0; } nextRefillTime = now + period; return numTokens; } }
false
false
null
null
diff --git a/de.hswt.hrm.inspection.ui/src/de/hswt/hrm/inspection/ui/part/ReportPhysicalComposite.java b/de.hswt.hrm.inspection.ui/src/de/hswt/hrm/inspection/ui/part/ReportPhysicalComposite.java index b98768d9..e7665ced 100755 --- a/de.hswt.hrm.inspection.ui/src/de/hswt/hrm/inspection/ui/part/ReportPhysicalComposite.java +++ b/de.hswt.hrm.inspection.ui/src/de/hswt/hrm/inspection/ui/part/ReportPhysicalComposite.java @@ -1,469 +1,470 @@ package de.hswt.hrm.inspection.ui.part; import java.util.Collection; import javax.annotation.PostConstruct; import javax.inject.Inject; import org.eclipse.e4.core.contexts.IEclipseContext; import org.eclipse.jface.window.IShellProvider; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Section; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.hswt.hrm.common.database.exception.DatabaseException; import de.hswt.hrm.common.observer.Observable; import de.hswt.hrm.common.observer.Observer; import de.hswt.hrm.common.ui.swt.forms.FormUtil; import de.hswt.hrm.common.ui.swt.layouts.LayoutUtil; import de.hswt.hrm.common.ui.swt.utils.ContentProposalUtil; import de.hswt.hrm.component.model.Component; import de.hswt.hrm.i18n.I18n; import de.hswt.hrm.i18n.I18nFactory; import de.hswt.hrm.inspection.model.Inspection; import de.hswt.hrm.inspection.model.PhysicalRating; import de.hswt.hrm.inspection.model.SamplingPointType; import de.hswt.hrm.inspection.service.InspectionService; import de.hswt.hrm.misc.comment.model.Comment; import de.hswt.hrm.misc.comment.service.CommentService; import de.hswt.hrm.plant.model.Plant; import de.hswt.hrm.scheme.model.SchemeComponent; public class ReportPhysicalComposite extends AbstractComponentRatingComposite { @Inject private InspectionService inspectionService; @Inject private IEclipseContext context; @Inject private CommentService commentService; @Inject private IShellProvider shellProvider; private Collection<PhysicalRating> ratings; private FormToolkit formToolkit = new FormToolkit(Display.getDefault()); private Button nothingRadioButton; private Button climateParameterRadioButton; private Button photoRadioButton; private Button dustRadioButton; private Combo commentCombo; private List gradeList; private List weightList; private List list; private static final Logger LOG = LoggerFactory .getLogger(ReportPhysicalComposite.class); private static final I18n I18N = I18nFactory.getI18n(ReportPhysicalComposite.class); private final Observable<Integer> grade = new Observable<>(); private final Observable<SamplingPointType> samplePointType = new Observable<>(); private SchemeComponent currentSchemeComponent; private Inspection inspection; /** * Create the composite. * * Do not use this constructor when instantiate this composite! It is only * included to make the WindowsBuilder working. * * @param parent * @param style */ private ReportPhysicalComposite(Composite parent, int style) { super(parent, SWT.NONE); createControls(); } /** * Create the composite. * * @param parent * @param style */ public ReportPhysicalComposite(Composite parent) { super(parent, SWT.NONE); formToolkit.dispose(); formToolkit = FormUtil.createToolkit(); } @PostConstruct public void createControls() { GridLayout gl = new GridLayout(1, false); gl.marginBottom = 5; gl.marginLeft = 5; gl.marginWidth = 0; gl.marginHeight = 0; setLayout(gl); setBackground(getDisplay().getSystemColor(SWT.COLOR_WHITE)); Composite c = new Composite(this, SWT.NONE); c.setLayoutData(LayoutUtil.createFillData()); c.setLayout(new FillLayout()); ScrolledComposite sc = new ScrolledComposite(c, SWT.H_SCROLL | SWT.V_SCROLL); sc.setExpandVertical(true); sc.setExpandHorizontal(true); Composite composite = new Composite(sc, SWT.None); composite.setBackgroundMode(SWT.INHERIT_FORCE); gl = new GridLayout(2, true); gl.marginWidth = 0; gl.marginHeight = 0; composite.setLayout(gl); sc.setContent(composite); Section physicalSection = formToolkit.createSection(composite, Section.TITLE_BAR); formToolkit.paintBordersFor(physicalSection); physicalSection.setText(I18N.tr("Physical rating")); physicalSection.setLayoutData(LayoutUtil.createHorzFillData()); FormUtil.initSectionColors(physicalSection); Section imageSection = formToolkit.createSection(composite, Section.TITLE_BAR); formToolkit.paintBordersFor(imageSection); imageSection.setText(I18N.tr("Photos")); imageSection.setLayoutData(LayoutUtil.createHorzFillData()); FormUtil.initSectionColors(imageSection); Section tagSection = formToolkit.createSection(composite, Section.TITLE_BAR); formToolkit.paintBordersFor(tagSection); tagSection.setText(I18N.tr("Scheme tags")); tagSection.setLayoutData(LayoutUtil.createHorzFillData(2)); FormUtil.initSectionColors(tagSection); /****************************** * physical rating components *****************************/ Composite physicalComposite = new Composite(physicalSection, SWT.NONE); physicalComposite.setBackgroundMode(SWT.INHERIT_DEFAULT); formToolkit.adapt(physicalComposite); formToolkit.paintBordersFor(physicalComposite); gl = new GridLayout(4, false); gl.marginWidth = 0; physicalComposite.setLayout(gl); physicalSection.setClient(physicalComposite); Label gradeLabel = new Label(physicalComposite, SWT.NONE); gradeLabel.setLayoutData(LayoutUtil.createHorzFillData(2)); formToolkit.adapt(gradeLabel, true, true); gradeLabel.setText(I18N.tr("Grade")); Label weightLabel = new Label(physicalComposite, SWT.NONE); weightLabel.setLayoutData(LayoutUtil.createHorzFillData(2)); formToolkit.adapt(weightLabel, true, true); weightLabel.setText(I18N.tr("Weight")); gradeList = new List(physicalComposite, SWT.BORDER); gradeList.setLayoutData(LayoutUtil.createHorzFillData(2)); formToolkit.adapt(gradeList, true, true); // 0 = not rated for (int i = 0; i < 6; i++) { gradeList.add(Integer.toString(i)); } gradeList.select(0); gradeList.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { int selection = gradeList.getSelectionIndex(); if (selection == -1) { selection = 0; } grade.set(selection); PhysicalRating rating = getRatingForComponent(currentSchemeComponent); rating.setRating(selection); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); weightList = new List(physicalComposite, SWT.BORDER); weightList.setLayoutData(LayoutUtil.createHorzFillData(2)); formToolkit.adapt(weightList, true, true); for (int i = 1; i <= 6; i++) { weightList.add(Integer.toString(i)); } weightList.select(0); weightList.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { int selection = weightList.getSelectionIndex(); if (selection == -1) { selection = 0; } PhysicalRating rating = getRatingForComponent(currentSchemeComponent); if (rating == null) { return; } rating.setRating(selection); } }); Label commentLabel = new Label(physicalComposite, SWT.NONE); commentLabel.setLayoutData(LayoutUtil.createLeftGridData()); formToolkit.adapt(commentLabel, true, true); commentLabel.setText(I18N.tr("Comment")); commentCombo = new Combo(physicalComposite, SWT.MULTI); commentCombo.setLayoutData(LayoutUtil.createHorzFillData(3)); commentCombo.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { PhysicalRating rating = getRatingForComponent(currentSchemeComponent); if (rating == null) { return; } rating.setNote(commentCombo.getText()); } }); formToolkit.adapt(commentCombo); formToolkit.paintBordersFor(commentCombo); initCommentAutoCompletion(commentCombo); /*************************************** * Photo/image section ***************************************/ Composite imageComposite = new Composite(imageSection, SWT.NONE); imageComposite.setBackgroundMode(SWT.INHERIT_DEFAULT); formToolkit.adapt(imageComposite); formToolkit.paintBordersFor(imageComposite); gl = new GridLayout(2, false); gl.marginWidth = 0; imageComposite.setLayout(gl); imageSection.setClient(imageComposite); list = new List(imageComposite, SWT.BORDER); list.setLayoutData(LayoutUtil.createFillData(1, 6)); formToolkit.adapt(list, true, true); Button addPhotoButton = new Button(imageComposite, SWT.NONE); formToolkit.adapt(addPhotoButton, true, true); addPhotoButton.setText(I18N.tr("Add photo")); addPhotoButton.setLayoutData(LayoutUtil.createRightGridData()); addPhotoButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { addPhoto(); } }); Button removeImageButton = new Button(imageComposite, SWT.NONE); formToolkit.adapt(removeImageButton, true, true); removeImageButton.setText(I18N.tr("Remove")); removeImageButton.setLayoutData(LayoutUtil.createRightGridData()); new Label(imageComposite, SWT.NONE); new Label(imageComposite, SWT.NONE); new Label(imageComposite, SWT.NONE); /******************************** * tags composite *******************************/ Composite tagsComposite = new Composite(tagSection, SWT.NONE); gl = new GridLayout(2, true); gl.marginHeight = 0; gl.marginWidth = 0; tagsComposite.setLayout(gl); tagsComposite.setLayoutData(LayoutUtil.createHorzFillData(2)); tagsComposite.setBackground(getDisplay() .getSystemColor(SWT.COLOR_WHITE)); tagSection.setClient(tagsComposite); nothingRadioButton = new Button(tagsComposite, SWT.RADIO); formToolkit.adapt(nothingRadioButton, true, true); nothingRadioButton.setLayoutData(LayoutUtil.createHorzFillData()); nothingRadioButton.setText(I18N.tr("Nothing")); nothingRadioButton.setSelection(true); nothingRadioButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { samplePointType.set(SamplingPointType.none); } }); climateParameterRadioButton = new Button(tagsComposite, SWT.RADIO); formToolkit.adapt(climateParameterRadioButton, true, true); climateParameterRadioButton.setLayoutData(LayoutUtil .createHorzFillData()); climateParameterRadioButton.setText(I18N.tr("Climate parameter")); climateParameterRadioButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { samplePointType.set(SamplingPointType.climateParameter); } }); photoRadioButton = new Button(tagsComposite, SWT.RADIO); formToolkit.adapt(photoRadioButton, true, true); photoRadioButton.setLayoutData(LayoutUtil.createHorzFillData()); photoRadioButton.setText(I18N.tr("Photo")); photoRadioButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { samplePointType.set(SamplingPointType.photo); } }); dustRadioButton = new Button(tagsComposite, SWT.RADIO); formToolkit.adapt(dustRadioButton, true, true); dustRadioButton.setLayoutData(LayoutUtil.createHorzFillData()); dustRadioButton.setText(I18N.tr("Dust concentration determination")); dustRadioButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { samplePointType.set(SamplingPointType.dustConcentration); } }); sc.setMinSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT)); } public void addGradeSelectionObserver(Observer<Integer> o) { grade.addObserver(o); } public void addSamplePointObserver(Observer<SamplingPointType> o) { samplePointType.addObserver(o); } private void initCommentAutoCompletion(Combo combo) { Collection<Comment> comments; try { comments = commentService.findAll(); String[] s = new String[comments.size()]; int i = 0; for (Comment c : comments) { s[i] = c.getText(); i++; } combo.setItems(s); ContentProposalUtil.enableContentProposal(combo); } catch (DatabaseException e) { LOG.debug("An error occured", e); } } private void addPhoto() { // TODO request for one or more photos (wizard, dialog?) } @Override public void inspectionChanged(Inspection inspection) { if (inspection == null) { return; } this.inspection = inspection; updateInspectionRatings(); } @Override public void inspectionComponentSelectionChanged(SchemeComponent component) { if (component == null) { return; } currentSchemeComponent = component; PhysicalRating rating = getRatingForComponent(component); if (rating != null) { updateRatingValues(rating); } else { gradeList.select(0); weightList.select(0); commentCombo.setText(""); } } private void updateRatingValues(PhysicalRating rating) { + gradeList.select(rating.getRating()); grade.set(gradeList.getSelectionIndex()); weightList.select(rating.getQuantifier()); - if (rating.getNote().isPresent()) { + if (rating.getNote() !=null) { commentCombo.setText(rating.getNote().get()); } } private PhysicalRating getRatingForComponent(SchemeComponent component) { for (PhysicalRating rating : ratings) { if (rating.getComponent().equals(component)) { return rating; } } PhysicalRating rating = new PhysicalRating(inspection, currentSchemeComponent); ratings.add(rating); return rating; } @Override public void plantChanged(Plant plant) { // TODO Auto-generated method stub } private void updateInspectionRatings() { try { ratings = inspectionService.findPhysicalRating(inspection); } catch (DatabaseException e) { LOG.error("An error occured"); } } @Override public void dispose() { formToolkit.dispose(); super.dispose(); } @Override protected void checkSubclass() { // Disable the check that prevents subclassing of SWT components } }
false
false
null
null
diff --git a/de.hswt.hrm.scheme.ui/src/de/hswt/hrm/scheme/ui/TreeManager.java b/de.hswt.hrm.scheme.ui/src/de/hswt/hrm/scheme/ui/TreeManager.java index dd90a9c9..b04636e9 100644 --- a/de.hswt.hrm.scheme.ui/src/de/hswt/hrm/scheme/ui/TreeManager.java +++ b/de.hswt.hrm.scheme.ui/src/de/hswt/hrm/scheme/ui/TreeManager.java @@ -1,61 +1,62 @@ package de.hswt.hrm.scheme.ui; import java.util.HashMap; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import de.hswt.hrm.scheme.model.Category; import de.hswt.hrm.scheme.model.Direction; import de.hswt.hrm.scheme.model.RenderedComponent; import de.hswt.hrm.scheme.model.ThumbnailImage; /** * This class manages the TreeItems of a Tree that displays the GridImages. * The GridImages are organized by their category. * * @author Michael Sieger * */ public class TreeManager { private final IImageTreeModel model; private final Tree tree; public TreeManager(IImageTreeModel model, Tree tree) { super(); this.model = model; this.tree = tree; generateTreeItems(); } private void generateTreeItems(){ tree.clearAll(true); HashMap<Category, TreeItem> categoryItems = new HashMap<>(); for(RenderedComponent comp : model.getImages()){ Category c = comp.getComponent().getCategory(); TreeItem categoryItem = categoryItems.get(c); if(categoryItem == null){ categoryItem = new TreeItem(tree, SWT.NONE); + categoryItem.setText(c.getName()); categoryItems.put(c, categoryItem); } TreeItem item = new TreeItem(categoryItem, SWT.NONE); - item.setText(c.getName()); + item.setText(comp.getComponent().getName()); addImage(Direction.downUp, comp, item); addImage(Direction.upDown, comp, item); addImage(Direction.leftRight, comp, item); addImage(Direction.rightLeft, comp, item); } } private void addImage(Direction d, RenderedComponent comp, TreeItem parent){ ThumbnailImage image = comp.getByDirection(d); if(image != null){ TreeItem item = new TreeItem(parent, SWT.NONE); item.setImage(image.getThumbnail()); item.setData(new TreeData(comp, d)); } } }
false
true
private void generateTreeItems(){ tree.clearAll(true); HashMap<Category, TreeItem> categoryItems = new HashMap<>(); for(RenderedComponent comp : model.getImages()){ Category c = comp.getComponent().getCategory(); TreeItem categoryItem = categoryItems.get(c); if(categoryItem == null){ categoryItem = new TreeItem(tree, SWT.NONE); categoryItems.put(c, categoryItem); } TreeItem item = new TreeItem(categoryItem, SWT.NONE); item.setText(c.getName()); addImage(Direction.downUp, comp, item); addImage(Direction.upDown, comp, item); addImage(Direction.leftRight, comp, item); addImage(Direction.rightLeft, comp, item); } }
private void generateTreeItems(){ tree.clearAll(true); HashMap<Category, TreeItem> categoryItems = new HashMap<>(); for(RenderedComponent comp : model.getImages()){ Category c = comp.getComponent().getCategory(); TreeItem categoryItem = categoryItems.get(c); if(categoryItem == null){ categoryItem = new TreeItem(tree, SWT.NONE); categoryItem.setText(c.getName()); categoryItems.put(c, categoryItem); } TreeItem item = new TreeItem(categoryItem, SWT.NONE); item.setText(comp.getComponent().getName()); addImage(Direction.downUp, comp, item); addImage(Direction.upDown, comp, item); addImage(Direction.leftRight, comp, item); addImage(Direction.rightLeft, comp, item); } }
diff --git a/java/engine/org/apache/derby/impl/sql/depend/BasicDependencyManager.java b/java/engine/org/apache/derby/impl/sql/depend/BasicDependencyManager.java index 84ab5543a..c5159260a 100644 --- a/java/engine/org/apache/derby/impl/sql/depend/BasicDependencyManager.java +++ b/java/engine/org/apache/derby/impl/sql/depend/BasicDependencyManager.java @@ -1,1143 +1,1137 @@ /* Derby - Class org.apache.derby.impl.sql.depend.BasicDependencyManager 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.derby.impl.sql.depend; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import org.apache.derby.catalog.DependableFinder; import org.apache.derby.catalog.UUID; import org.apache.derby.iapi.error.StandardException; import org.apache.derby.iapi.services.context.ContextManager; import org.apache.derby.iapi.services.io.FormatableBitSet; import org.apache.derby.iapi.services.sanity.SanityManager; import org.apache.derby.iapi.sql.compile.CompilerContext; import org.apache.derby.iapi.sql.compile.Parser; import org.apache.derby.iapi.sql.conn.LanguageConnectionContext; import org.apache.derby.iapi.sql.conn.StatementContext; import org.apache.derby.iapi.sql.depend.Dependency; import org.apache.derby.iapi.sql.depend.DependencyManager; import org.apache.derby.iapi.sql.depend.Dependent; import org.apache.derby.iapi.sql.depend.Provider; import org.apache.derby.iapi.sql.depend.ProviderInfo; import org.apache.derby.iapi.sql.depend.ProviderList; import org.apache.derby.iapi.sql.dictionary.DataDictionary; import org.apache.derby.iapi.sql.dictionary.DependencyDescriptor; import org.apache.derby.iapi.sql.dictionary.SchemaDescriptor; import org.apache.derby.iapi.sql.dictionary.TableDescriptor; import org.apache.derby.iapi.sql.dictionary.ViewDescriptor; import org.apache.derby.iapi.store.access.TransactionController; import org.apache.derby.impl.sql.compile.CreateViewNode; /** * The dependency manager tracks needs that dependents have of providers. * <p> * A dependency can be either persistent or non-persistent. Persistent * dependencies are stored in the data dictionary, and non-persistent * dependencies are stored within the dependency manager itself (in memory). * <p> * <em>Synchronization:</em> The need for synchronization is different depending * on whether the dependency is an in-memory dependency or a stored dependency. * When accessing and modifying in-memory dependencies, Java synchronization * must be used (specifically, we synchronize on {@code this}). When accessing * and modifying stored dependencies, which are stored in the data dictionary, * we expect that the locking protocols will provide the synchronization needed. * Note that stored dependencies should not be accessed while holding the * monitor of {@code this}, as this may result in deadlocks. So far the need * for synchronization across both in-memory and stored dependencies hasn't * occured. */ public class BasicDependencyManager implements DependencyManager { /** * DataDictionary for this database. */ private final DataDictionary dd; /** * Map of in-memory dependencies for Dependents. * In-memory means that one or both of the Dependent * or Provider are non-persistent (isPersistent() returns false). * * Key is the UUID of the Dependent (from getObjectID()). * Value is a List containing Dependency objects, each * of whihc links the same Dependent to a Provider. * Dependency objects in the List are unique. * */ //@GuardedBy("this") private final Map dependents = new HashMap(); /** * Map of in-memory dependencies for Providers. * In-memory means that one or both of the Dependent * or Provider are non-persistent (isPersistent() returns false). * * Key is the UUID of the Provider (from getObjectID()). * Value is a List containing Dependency objects, each * of which links the same Provider to a Dependent. * Dependency objects in the List are unique. * */ //@GuardedBy("this") private final Map providers = new HashMap(); // // DependencyManager interface // /** adds a dependency from the dependent on the provider. This will be considered to be the default type of dependency, when dependency types show up. <p> Implementations of addDependency should be fast -- performing alot of extra actions to add a dependency would be a detriment. @param d the dependent @param p the provider @exception StandardException thrown if something goes wrong */ public void addDependency(Dependent d, Provider p, ContextManager cm) throws StandardException { addDependency(d, p, cm, null); } /** * Adds the dependency to the data dictionary or the in-memory dependency * map. * <p> * The action taken is detmermined by whether the dependent and/or the * provider are persistent. * * @param d the dependent * @param p the provider * @param cm context manager * @param tc transaction controller, used to determine if any transactional * operations should be attempted carried out in a nested transaction. * If {@code tc} is {@code null}, the user transaction is used. * @throws StandardException if adding the dependency fails */ private void addDependency(Dependent d, Provider p, ContextManager cm, TransactionController tc) throws StandardException { // Dependencies are either in-memory or stored, but not both. if (! d.isPersistent() || ! p.isPersistent()) { addInMemoryDependency(d, p, cm); } else { addStoredDependency(d, p, cm, tc); } } /** * Adds the dependency as an in-memory dependency. * * @param d the dependent * @param p the provider * @param cm context manager * @throws StandardException if adding the dependency fails * @see #addStoredDependency */ private synchronized void addInMemoryDependency(Dependent d, Provider p, ContextManager cm) throws StandardException { Dependency dy = new BasicDependency(d, p); // Duplicate dependencies are not added to the lists. // If we find that the dependency we are trying to add in // one list is a duplicate, then it should be a duplicate in the // other list. boolean addedToDeps = false; boolean addedToProvs = false; addedToDeps = addDependencyToTable(dependents, d.getObjectID(), dy); if (addedToDeps) { addedToProvs = addDependencyToTable(providers, p.getObjectID(), dy); } else if (SanityManager.DEBUG) { addedToProvs = addDependencyToTable(providers, p.getObjectID(), dy); } // Dependency should have been added to both or neither. if (SanityManager.DEBUG) { if (addedToDeps != addedToProvs) { SanityManager.THROWASSERT( "addedToDeps (" + addedToDeps + ") and addedToProvs (" + addedToProvs + ") are expected to agree"); } } // Add the dependency to the StatementContext, so that // it can be cleared on a pre-execution error. StatementContext sc = (StatementContext) cm.getContext( org.apache.derby.iapi.reference.ContextId.LANG_STATEMENT); sc.addDependency(dy); } /** * Adds the dependency as a stored dependency. * <p> * We expect that transactional locking (in the data dictionary) is enough * to protect us from concurrent changes when adding stored dependencies. * Adding synchronization here and accessing the data dictionary (which is * transactional) may cause deadlocks. * * @param d the dependent * @param p the provider * @param cm context manager * @param tc transaction controller (may be {@code null}) * @throws StandardException if adding the dependency fails * @see #addInMemoryDependency */ private void addStoredDependency(Dependent d, Provider p, ContextManager cm, TransactionController tc) throws StandardException { LanguageConnectionContext lcc = getLanguageConnectionContext(cm); // tc == null means do it in the user transaction TransactionController tcToUse = (tc == null) ? lcc.getTransactionExecute() : tc; // Call the DataDictionary to store the dependency. dd.addDescriptor(new DependencyDescriptor(d, p), null, DataDictionary.SYSDEPENDS_CATALOG_NUM, true, tcToUse); } /** drops a single dependency @param d the dependent @param p the provider @exception StandardException thrown if something goes wrong */ private void dropDependency(LanguageConnectionContext lcc, Dependent d, Provider p) throws StandardException { if (SanityManager.DEBUG) { // right now, this routine isn't called for in-memory dependencies if (! d.isPersistent() || ! p.isPersistent()) { SanityManager.NOTREACHED(); } } DependencyDescriptor dependencyDescriptor = new DependencyDescriptor(d, p); dd.dropStoredDependency( dependencyDescriptor, lcc.getTransactionExecute() ); } /** mark all dependencies on the named provider as invalid. When invalidation types show up, this will use the default invalidation type. The dependencies will still exist once they are marked invalid; clearDependencies should be used to remove dependencies that a dependent has or provider gives. <p> Implementations of this can take a little time, but are not really expected to recompile things against any changes made to the provider that caused the invalidation. The dependency system makes no guarantees about the state of the provider -- implementations can call this before or after actually changing the provider to its new state. <p> Implementations should throw StandardException if the invalidation should be disallowed. @param p the provider @param action The action causing the invalidate @exception StandardException thrown if unable to make it invalid */ public void invalidateFor(Provider p, int action, LanguageConnectionContext lcc) throws StandardException { /* ** Non-persistent dependencies are stored in memory, and need to ** use "synchronized" to ensure their lists don't change while ** the invalidation is taking place. Persistent dependencies are ** stored in the data dictionary, and we should *not* do anything ** transactional (like reading from a system table) from within ** a synchronized method, as it could cause deadlock. ** ** Presumably, the transactional locking in the data dictionary ** is enough to protect us, so that we don't have to put any ** synchronization in the DependencyManager. */ if (p.isPersistent()) coreInvalidateFor(p, action, lcc); else { synchronized (this) { coreInvalidateFor(p, action, lcc); } } } /** * A version of invalidateFor that does not provide synchronization among * invalidators. * * @param p the provider * @param action the action causing the invalidation * @param lcc language connection context * * @throws StandardException if something goes wrong */ private void coreInvalidateFor(Provider p, int action, LanguageConnectionContext lcc) throws StandardException { List list = getDependents(p); - if (list == null) - { + if (list.isEmpty()) { return; } // affectedCols is passed in from table descriptor provider to indicate // which columns it cares; subsetCols is affectedCols' intersection // with column bit map found in the provider of SYSDEPENDS line to // find out which columns really matter. If SYSDEPENDS line's // dependent is view (or maybe others), provider is table, yet it // doesn't have column bit map because the view was created in a // previous version of server which doesn't support column dependency, // and we really want it to have (such as in drop column), in any case // if we passed in table descriptor to this function with a bit map, // we really need this, we generate the bitmaps on the fly and update // SYSDEPENDS FormatableBitSet affectedCols = null, subsetCols = null; if (p instanceof TableDescriptor) { affectedCols = ((TableDescriptor) p).getReferencedColumnMap(); if (affectedCols != null) subsetCols = new FormatableBitSet(affectedCols.getLength()); } { StandardException noInvalidate = null; // We cannot use an iterator here as the invalidations can remove // entries from this list. for (int ei = list.size() - 1; ei >= 0; ei--) { if (ei >= list.size()) continue; Dependency dependency = (Dependency) list.get(ei); Dependent dep = dependency.getDependent(); if (affectedCols != null) { TableDescriptor td = (TableDescriptor) dependency.getProvider(); FormatableBitSet providingCols = td.getReferencedColumnMap(); if (providingCols == null) { if (dep instanceof ViewDescriptor) { ViewDescriptor vd = (ViewDescriptor) dep; SchemaDescriptor compSchema; compSchema = dd.getSchemaDescriptor(vd.getCompSchemaId(), null); CompilerContext newCC = lcc.pushCompilerContext(compSchema); Parser pa = newCC.getParser(); // Since this is always nested inside another SQL // statement, so topLevel flag should be false CreateViewNode cvn = (CreateViewNode)pa.parseStatement( vd.getViewText()); // need a current dependent for bind newCC.setCurrentDependent(dep); cvn.bindStatement(); ProviderInfo[] providerInfos = cvn.getProviderInfo(); lcc.popCompilerContext(newCC); boolean interferent = false; for (int i = 0; i < providerInfos.length; i++) { Provider provider = null; provider = (Provider) providerInfos[i]. getDependableFinder(). getDependable(dd, providerInfos[i].getObjectId()); if (provider instanceof TableDescriptor) { TableDescriptor tab = (TableDescriptor)provider; FormatableBitSet colMap = tab.getReferencedColumnMap(); if (colMap == null) continue; // if later on an error is raised such as in // case of interference, this dependency line // upgrade will not happen due to rollback tab.setReferencedColumnMap(null); dropDependency(lcc, vd, tab); tab.setReferencedColumnMap(colMap); addDependency(vd, tab, lcc.getContextManager()); if (tab.getObjectID().equals(td.getObjectID())) { System.arraycopy(affectedCols.getByteArray(), 0, subsetCols.getByteArray(), 0, affectedCols.getLengthInBytes()); subsetCols.and(colMap); if (subsetCols.anySetBit() != -1) { interferent = true; ((TableDescriptor) p).setReferencedColumnMap(subsetCols); } } } // if provider instanceof TableDescriptor } // for providerInfos if (! interferent) continue; } // if dep instanceof ViewDescriptor else ((TableDescriptor) p).setReferencedColumnMap(null); } // if providingCols == null else { System.arraycopy(affectedCols.getByteArray(), 0, subsetCols.getByteArray(), 0, affectedCols.getLengthInBytes()); subsetCols.and(providingCols); if (subsetCols.anySetBit() == -1) continue; ((TableDescriptor) p).setReferencedColumnMap(subsetCols); } } // generate a list of invalidations that fail. try { dep.prepareToInvalidate(p, action, lcc); } catch (StandardException sqle) { if (noInvalidate == null) { noInvalidate = sqle; } else { try { sqle.initCause(noInvalidate); noInvalidate = sqle; } catch (IllegalStateException ise) { // We weren't able to chain the exceptions. That's // OK, since we always have the first exception we // caught. Just skip the current exception. } } } if (noInvalidate == null) { if (affectedCols != null) ((TableDescriptor) p).setReferencedColumnMap(affectedCols); // REVISIT: future impl will want to mark the individual // dependency as invalid as well as the dependent... dep.makeInvalid(action, lcc); } } if (noInvalidate != null) throw noInvalidate; } } /** Erases all of the dependencies the dependent has, be they valid or invalid, of any dependency type. This action is usually performed as the first step in revalidating a dependent; it first erases all the old dependencies, then revalidates itself generating a list of new dependencies, and then marks itself valid if all its new dependencies are valid. <p> There might be a future want to clear all dependencies for a particular provider, e.g. when destroying the provider. However, at present, they are assumed to stick around and it is the responsibility of the dependent to erase them when revalidating against the new version of the provider. <p> clearDependencies will delete dependencies if they are stored; the delete is finalized at the next commit. @param d the dependent * * @exception StandardException Thrown on failure */ public void clearDependencies(LanguageConnectionContext lcc, Dependent d) throws StandardException { clearDependencies(lcc, d, null); } /** * @inheritDoc */ public void clearDependencies(LanguageConnectionContext lcc, Dependent d, TransactionController tc) throws StandardException { UUID id = d.getObjectID(); // Remove all the stored dependencies. if (d.isPersistent()) { boolean wait = (tc == null); dd.dropDependentsStoredDependencies(id, ((wait)?lcc.getTransactionExecute():tc), wait); } // Now remove the in-memory dependencies, if any. synchronized(this) { List deps = (List) dependents.get(id); if (deps != null) { Iterator depsIter = deps.iterator(); // go through the list notifying providers to remove // the dependency from their lists while (depsIter.hasNext()) { Dependency dy = (Dependency)depsIter.next(); clearProviderDependency(dy.getProviderKey(), dy); } dependents.remove(id); } } } /** * Clear the specified in memory dependency. * This is useful for clean-up when an exception occurs. * (We clear all in-memory dependencies added in the current * StatementContext.) */ public synchronized void clearInMemoryDependency(Dependency dy) { final UUID deptId = dy.getDependent().getObjectID(); final UUID provId = dy.getProviderKey(); List deps = (List) dependents.get(deptId); // NOTE - this is a NEGATIVE Sanity mode check, in sane mode we continue // to ensure the dependency manager is consistent. if (!SanityManager.DEBUG) { // dependency has already been removed if (deps == null) return; } List provs = (List) providers.get(provId); if (SanityManager.DEBUG) { // if both are null then everything is OK if ((deps != null) || (provs != null)) { // ensure that the Dependency dy is either // in both lists or in neither. Even if dy // is out of the list we can have non-null // deps and provs here because other dependencies // with the the same providers or dependents can exist // int depCount = 0; if (deps != null) { for (int ci = 0; ci < deps.size(); ci++) { if (dy.equals(deps.get(ci))) depCount++; } } int provCount = 0; if (provs != null) { for (int ci = 0; ci < provs.size(); ci++) { if (dy.equals(provs.get(ci))) provCount++; } } SanityManager.ASSERT(depCount == provCount, "Dependency count mismatch count in deps: " + depCount + ", count in provs " + provCount + ", dy.getDependent().getObjectID() = " + deptId + ", dy.getProvider().getObjectID() = " + provId); } // dependency has already been removed, // matches code that is protected by !DEBUG above if (deps == null) return; } // dependency has already been removed if (provs == null) return; deps.remove(dy); if (deps.isEmpty()) dependents.remove(deptId); provs.remove(dy); if (provs.isEmpty()) providers.remove(provId); } /** * @see DependencyManager#getPersistentProviderInfos * * @exception StandardException Thrown on error */ public ProviderInfo[] getPersistentProviderInfos(Dependent dependent) throws StandardException { List list = getProviders(dependent); if (list.isEmpty()) { return EMPTY_PROVIDER_INFO; } Iterator provIter = list.iterator(); List pih = new ArrayList(); while (provIter.hasNext()) { Provider p = (Provider)provIter.next(); if (p.isPersistent()) { pih.add(new BasicProviderInfo( p.getObjectID(), p.getDependableFinder(), p.getObjectName() )); } } return (ProviderInfo[]) pih.toArray(EMPTY_PROVIDER_INFO); } private static final ProviderInfo[] EMPTY_PROVIDER_INFO = new ProviderInfo[0]; /** * @see DependencyManager#getPersistentProviderInfos * * @exception StandardException Thrown on error */ public ProviderInfo[] getPersistentProviderInfos(ProviderList pl) throws StandardException { Enumeration e = pl.elements(); int numProviders = 0; ProviderInfo[] retval; /* ** We make 2 passes - the first to count the number of persistent ** providers and the second to populate the array of ProviderInfos. */ while (e != null && e.hasMoreElements()) { Provider prov = (Provider) e.nextElement(); if (prov.isPersistent()) { numProviders++; } } e = pl.elements(); retval = new ProviderInfo[numProviders]; int piCtr = 0; while (e != null && e.hasMoreElements()) { Provider prov = (Provider) e.nextElement(); if (prov.isPersistent()) { retval[piCtr++] = new BasicProviderInfo( prov.getObjectID(), prov.getDependableFinder(), prov.getObjectName() ); } } return retval; } /** * @see DependencyManager#clearColumnInfoInProviders * * @param pl provider list * * @exception StandardException Thrown on error */ public void clearColumnInfoInProviders(ProviderList pl) throws StandardException { Enumeration e = pl.elements(); while (e.hasMoreElements()) { Provider pro = (Provider) e.nextElement(); if (pro instanceof TableDescriptor) ((TableDescriptor) pro).setReferencedColumnMap(null); } } /** * Copy dependencies from one dependent to another. * * @param copy_From the dependent to copy from * @param copyTo the dependent to copy to * @param persistentOnly only copy persistent dependencies * @param cm Current ContextManager * * @exception StandardException Thrown on error. */ public void copyDependencies(Dependent copy_From, Dependent copyTo, boolean persistentOnly, ContextManager cm) throws StandardException { copyDependencies(copy_From, copyTo, persistentOnly, cm, null); } /** * @inheritDoc */ public void copyDependencies( Dependent copy_From, Dependent copyTo, boolean persistentOnly, ContextManager cm, TransactionController tc) throws StandardException { List list = getProviders(copy_From); Iterator depsIter = list.iterator(); while (depsIter.hasNext()) { Provider provider = (Provider)depsIter.next(); if (!persistentOnly || provider.isPersistent()) { this.addDependency(copyTo, provider, cm, tc); } } } /** * Returns a string representation of the SQL action, hence no * need to internationalize, which is causing the invokation * of the Dependency Manager. * * @param action The action * * @return String The String representation */ public String getActionString(int action) { switch (action) { case ALTER_TABLE: return "ALTER TABLE"; case RENAME: //for rename table and column return "RENAME"; case RENAME_INDEX: return "RENAME INDEX"; case COMPILE_FAILED: return "COMPILE FAILED"; case DROP_TABLE: return "DROP TABLE"; case DROP_INDEX: return "DROP INDEX"; case DROP_VIEW: return "DROP VIEW"; case CREATE_INDEX: return "CREATE INDEX"; case ROLLBACK: return "ROLLBACK"; case CHANGED_CURSOR: return "CHANGED CURSOR"; case CREATE_CONSTRAINT: return "CREATE CONSTRAINT"; case DROP_CONSTRAINT: return "DROP CONSTRAINT"; case DROP_METHOD_ALIAS: return "DROP ROUTINE"; case PREPARED_STATEMENT_RELEASE: return "PREPARED STATEMENT RELEASE"; case DROP_SPS: return "DROP STORED PREPARED STATEMENT"; case USER_RECOMPILE_REQUEST: return "USER REQUESTED INVALIDATION"; case BULK_INSERT: return "BULK INSERT"; case CREATE_VIEW: return "CREATE_VIEW"; case DROP_JAR: return "DROP_JAR"; case REPLACE_JAR: return "REPLACE_JAR"; case SET_CONSTRAINTS_ENABLE: return "SET_CONSTRAINTS_ENABLE"; case SET_CONSTRAINTS_DISABLE: return "SET_CONSTRAINTS_DISABLE"; case INTERNAL_RECOMPILE_REQUEST: return "INTERNAL RECOMPILE REQUEST"; case CREATE_TRIGGER: return "CREATE TRIGGER"; case DROP_TRIGGER: return "DROP TRIGGER"; case SET_TRIGGERS_ENABLE: return "SET TRIGGERS ENABLED"; case SET_TRIGGERS_DISABLE: return "SET TRIGGERS DISABLED"; case MODIFY_COLUMN_DEFAULT: return "MODIFY COLUMN DEFAULT"; case COMPRESS_TABLE: return "COMPRESS TABLE"; case DROP_COLUMN: return "DROP COLUMN"; case DROP_COLUMN_RESTRICT: return "DROP COLUMN RESTRICT"; case DROP_STATISTICS: return "DROP STATISTICS"; case UPDATE_STATISTICS: return "UPDATE STATISTICS"; case TRUNCATE_TABLE: return "TRUNCATE TABLE"; case DROP_SYNONYM: return "DROP SYNONYM"; case REVOKE_PRIVILEGE: return "REVOKE PRIVILEGE"; case REVOKE_PRIVILEGE_RESTRICT: return "REVOKE PRIVILEGE RESTRICT"; case REVOKE_ROLE: return "REVOKE ROLE"; case RECHECK_PRIVILEGES: return "RECHECK PRIVILEGES"; case DROP_SEQUENCE: return "DROP SEQUENCE"; case DROP_UDT: return "DROP TYPE"; default: if (SanityManager.DEBUG) { SanityManager.THROWASSERT("getActionString() passed an invalid value (" + action + ")"); } // NOTE: This is not internationalized because we should never // reach here. return "UNKNOWN"; } } /** * Count the number of active dependencies, both stored and in memory, * in the system. * * @return int The number of active dependencies in the system. @exception StandardException thrown if something goes wrong */ public int countDependencies() throws StandardException { // Add the stored dependencies. List storedDeps = dd.getAllDependencyDescriptorsList(); int numDependencies = storedDeps.size(); synchronized(this) { Iterator deps = dependents.values().iterator(); Iterator provs = providers.values().iterator(); // Count the in memory dependencies. while (deps.hasNext()) { numDependencies += ((List) deps.next()).size(); } while (provs.hasNext()) { numDependencies += ((List) provs.next()).size(); } } return numDependencies; } // // class interface // public BasicDependencyManager(DataDictionary dd) { this.dd = dd; } // // class implementation // /** * Add a new dependency to the specified table if it does not * already exist in that table. * * @return boolean Whether or not the dependency get added. */ private boolean addDependencyToTable(Map table, Object key, Dependency dy) { List deps = (List) table.get(key); if (deps == null) { deps = new ArrayList(); deps.add(dy); table.put(key, deps); } else { /* Make sure that we're not adding a duplicate dependency */ UUID provKey = dy.getProvider().getObjectID(); UUID depKey = dy.getDependent().getObjectID(); for (ListIterator depsIT = deps.listIterator(); depsIT.hasNext(); ) { Dependency curDY = (Dependency)depsIT.next(); if (curDY.getProvider().getObjectID().equals(provKey) && curDY.getDependent().getObjectID().equals(depKey)) { return false; } } deps.add(dy); } if (SanityManager.DEBUG) { if (SanityManager.DEBUG_ON("memoryLeakTrace")) { if (table.size() > 100) System.out.println("memoryLeakTrace:BasicDependencyManager:table " + table.size()); if (deps.size() > 50) System.out.println("memoryLeakTrace:BasicDependencyManager:deps " + deps.size()); } } return true; } /** * removes a dependency for a given provider. assumes * that the dependent removal is being dealt with elsewhere. * Won't assume that the dependent only appears once in the list. */ - protected void clearProviderDependency(UUID p, Dependency d) { + //@GuardedBy("this") + private void clearProviderDependency(UUID p, Dependency d) { List deps = (List) providers.get(p); if (deps == null) return; deps.remove(d); if (deps.size() == 0) providers.remove(p); } /** * Replace the DependencyDescriptors in an List with Dependencys. * * @param storedList The List of DependencyDescriptors representing * stored dependencies. * @param providerForList The provider if this list is being created * for a list of dependents. Null otherwise. * * @return List The converted List * * @exception StandardException thrown if something goes wrong */ private List getDependencyDescriptorList(List storedList, Provider providerForList) throws StandardException { if (storedList.size() != 0) { /* For each DependencyDescriptor, we need to instantiate * object descriptors of the appropriate type for both * the dependent and provider, create a Dependency with * that Dependent and Provider and substitute the Dependency * back into the same place in the List * so that the call gets an enumerations of Dependencys. */ for (ListIterator depsIterator = storedList.listIterator(); depsIterator.hasNext(); ) { Dependent tempD; Provider tempP; DependableFinder finder = null; DependencyDescriptor depDesc = (DependencyDescriptor) depsIterator.next(); finder = depDesc.getDependentFinder(); tempD = (Dependent) finder.getDependable(dd, depDesc.getUUID() ); if (providerForList != null) { // Use the provider being passed in. tempP = providerForList; // Sanity check the object identifiers match. if (SanityManager.DEBUG) { if (!tempP.getObjectID().equals(depDesc.getProviderID())) { SanityManager.THROWASSERT("mismatch providers"); } } } else { finder = depDesc.getProviderFinder(); tempP = (Provider) finder.getDependable(dd, depDesc.getProviderID() ); } depsIterator.set(new BasicDependency(tempD, tempP)); } } return storedList; } /** * Returns the LanguageConnectionContext to use. * * @param cm Current ContextManager * * @return LanguageConnectionContext The LanguageConnectionContext to use. */ private LanguageConnectionContext getLanguageConnectionContext(ContextManager cm) { // find the language context. return (LanguageConnectionContext) cm.getContext(LanguageConnectionContext.CONTEXT_ID); } /** * Returns a list of all providers that this dependent has (even invalid * ones). Includes all dependency types. * * @param d the dependent * @return A list of providers (possibly empty). * @throws StandardException thrown if something goes wrong */ private List getProviders (Dependent d) throws StandardException { List provs = new ArrayList(); synchronized (this) { List deps = (List) dependents.get(d.getObjectID()); if (deps != null) { Iterator depsIter = deps.iterator(); while (depsIter.hasNext()) { provs.add(((Dependency)depsIter.next()).getProvider()); } } } // If the dependent is persistent, we have to take stored dependencies // into consideration as well. if (d.isPersistent()) { List storedList = getDependencyDescriptorList( dd.getDependentsDescriptorList( d.getObjectID().toString() ), (Provider) null ); Iterator depIter = storedList.iterator(); while (depIter.hasNext()) { provs.add(((Dependency)depIter.next()).getProvider()); } } return provs; } /** * Returns an enumeration of all dependencies that this * provider is supporting for any dependent at all (even * invalid ones). Includes all dependency types. * * @param p the provider - * @return {@code null} or a list of dependents (possibly empty). + * @return A list of dependents (possibly empty). * @throws StandardException if something goes wrong */ private List getDependents (Provider p) throws StandardException { - List deps; + List deps = new ArrayList(); synchronized (this) { - deps = (List) providers.get(p.getObjectID()); + List memDeps = (List) providers.get(p.getObjectID()); + if (memDeps != null) { + deps.addAll(memDeps); + } } // If the provider is persistent, then we have to add providers for // stored dependencies as well. if (p.isPersistent()) { List storedList = getDependencyDescriptorList( dd.getProvidersDescriptorList( p.getObjectID().toString() ), p ); - if (deps == null) { - deps = storedList; - } else { - // We can't modify the list we got from 'providers', create a - // new one to merge the two lists. - List merged = new ArrayList(deps.size() + storedList.size()); - merged.addAll(deps); - merged.addAll(storedList); - deps = merged; - } + deps.addAll(storedList); } return deps; } }
false
false
null
null
diff --git a/src/gov/nist/javax/sip/header/ims/PChargingVector.java b/src/gov/nist/javax/sip/header/ims/PChargingVector.java index db33bb8d..73871a13 100644 --- a/src/gov/nist/javax/sip/header/ims/PChargingVector.java +++ b/src/gov/nist/javax/sip/header/ims/PChargingVector.java @@ -1,224 +1,226 @@ /* * Conditions Of Use * * This software was developed by employees of the National Institute of * Standards and Technology (NIST), an agency of the Federal Government. * Pursuant to title 15 Untied States Code Section 105, works of NIST * employees are not subject to copyright protection in the United States * and are considered to be in the public domain. As a result, a formal * license is not needed to use the software. * * This software is provided by NIST as a service and is expressly * provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED * OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT * AND DATA ACCURACY. NIST does not warrant or make any representations * regarding the use of the software or the results thereof, including but * not limited to the correctness, accuracy, reliability or usefulness of * the software. * * Permission to use this software is contingent upon your acceptance * of the terms of this agreement * * . * */ /******************************************* * PRODUCT OF PT INOVACAO - EST DEPARTMENT * *******************************************/ package gov.nist.javax.sip.header.ims; import java.text.ParseException; import javax.sip.header.ExtensionHeader; import gov.nist.javax.sip.header.ims.PChargingVectorHeader; import gov.nist.javax.sip.header.ims.ParameterNamesIms; /** * P-Charging-Vector header SIP Private Header: RFC 3455. * * @author ALEXANDRE MIGUEL SILVA SANTOS */ public class PChargingVector extends gov.nist.javax.sip.header.ParametersHeader implements PChargingVectorHeader, SIPHeaderNamesIms, ExtensionHeader { /** * Default Constructor */ public PChargingVector() { super(P_CHARGING_VECTOR); } /* * (non-Javadoc) * * @see gov.nist.javax.sip.header.ParametersHeader#encodeBody() */ protected String encodeBody() { StringBuffer encoding = new StringBuffer(); /* * no need to check for the presence of icid-value. According to the * spec above this is a mandatory field. if it does not exist, then we * should throw an exception - */ - encoding.append(ParameterNamesIms.ICID_VALUE).append(EQUALS).append( - getICID()); - + * + * JvB 26/5: fix for issue #159, check for quotes around icid value + */ + gov.nist.core.NameValue nv = getNameValue( ParameterNamesIms.ICID_VALUE ); + nv.encode( encoding ); + //the remaining parameters are optional. // check for their presence, then add the parameter if it exists. if (parameters.containsKey(ParameterNamesIms.ICID_GENERATED_AT)) encoding.append(SEMICOLON).append( ParameterNamesIms.ICID_GENERATED_AT).append(EQUALS).append( getICIDGeneratedAt()); if (parameters.containsKey(ParameterNamesIms.TERM_IOI)) encoding.append(SEMICOLON).append(ParameterNamesIms.TERM_IOI) .append(EQUALS).append(getTerminatingIOI()); if (parameters.containsKey(ParameterNamesIms.ORIG_IOI)) encoding.append(SEMICOLON).append(ParameterNamesIms.ICID_VALUE) .append(EQUALS).append(getOriginatingIOI()); return encoding.toString(); } /** * <p> * Get the icid-value parameter value * </p> * * @return the value of the icid-value parameter */ public String getICID() { return getParameter(ParameterNamesIms.ICID_VALUE); } /** * <p> * Set the icid-value parameter * </p> * * @param icid - * value to set in the icid-value parameter * @throws ParseException */ public void setICID(String icid) throws ParseException { if (icid == null) throw new NullPointerException( "JAIN-SIP Exception, " + "P-Charging-Vector, setICID(), the icid parameter is null."); setParameter(ParameterNamesIms.ICID_VALUE, icid); } /** * <p> * Get the icid-generated-at parameter value * </p> * * @return the icid-generated-at parameter value */ public String getICIDGeneratedAt() { return getParameter(ParameterNamesIms.ICID_GENERATED_AT); } /** * <p> * Set the icid-generated-at parameter * </p> * * @param host - * value to set in the icid-generated-at parameter * @throws ParseException */ public void setICIDGeneratedAt(String host) throws ParseException { if (host == null) throw new NullPointerException( "JAIN-SIP Exception, " + "P-Charging-Vector, setICIDGeneratedAt(), the host parameter is null."); setParameter(ParameterNamesIms.ICID_GENERATED_AT, host); } /** * <p> * Get the orig-ioi parameter value * </p> * * @return the orig-ioi parameter value */ public String getOriginatingIOI() { return getParameter(ParameterNamesIms.ORIG_IOI); } /** * <p> * Set the orig-ioi parameter * </p> * * @param origIOI - * value to set in the orig-ioi parameter. If value is null or * empty, the parameter is removed * @throws ParseException */ public void setOriginatingIOI(String origIOI) throws ParseException { if (origIOI == null || origIOI.length() == 0) { removeParameter(ParameterNamesIms.ORIG_IOI); } else setParameter(ParameterNamesIms.ORIG_IOI, origIOI); } /** * <p> * Get the term-ioi parameter value * </p> * * @return the term-ioi parameter value */ public String getTerminatingIOI() { return getParameter(ParameterNamesIms.TERM_IOI); } /** * <p> * Set the term-ioi parameter * </p> * * @param termIOI - * value to set in the term-ioi parameter. If value is null or * empty, the parameter is removed * @throws ParseException */ public void setTerminatingIOI(String termIOI) throws ParseException { if (termIOI == null || termIOI.length() == 0) { removeParameter(ParameterNamesIms.TERM_IOI); } else setParameter(ParameterNamesIms.TERM_IOI, termIOI); } public void setValue(String value) throws ParseException { throw new ParseException(value, 0); } }
true
false
null
null
diff --git a/src/nu/validator/htmlparser/impl/TreeBuilder.java b/src/nu/validator/htmlparser/impl/TreeBuilder.java index f9988d0..5ca303b 100644 --- a/src/nu/validator/htmlparser/impl/TreeBuilder.java +++ b/src/nu/validator/htmlparser/impl/TreeBuilder.java @@ -1,5617 +1,5624 @@ /* * Copyright (c) 2007 Henri Sivonen * Copyright (c) 2007-2010 Mozilla Foundation * Portions of comments Copyright 2004-2008 Apple Computer, Inc., Mozilla * Foundation, and Opera Software ASA. * * 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. */ /* * The comments following this one that use the same comment syntax as this * comment are quotes from the WHATWG HTML 5 spec as of 27 June 2007 * amended as of June 28 2007. * That document came with this statement: * "© Copyright 2004-2007 Apple Computer, Inc., Mozilla Foundation, and * Opera Software ASA. You are granted a license to use, reproduce and * create derivative works of this document." */ package nu.validator.htmlparser.impl; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import nu.validator.htmlparser.annotation.Const; import nu.validator.htmlparser.annotation.IdType; import nu.validator.htmlparser.annotation.Inline; import nu.validator.htmlparser.annotation.Literal; import nu.validator.htmlparser.annotation.Local; import nu.validator.htmlparser.annotation.NoLength; import nu.validator.htmlparser.annotation.NsUri; import nu.validator.htmlparser.common.DoctypeExpectation; import nu.validator.htmlparser.common.DocumentMode; import nu.validator.htmlparser.common.DocumentModeHandler; import nu.validator.htmlparser.common.Interner; import nu.validator.htmlparser.common.TokenHandler; import nu.validator.htmlparser.common.XmlViolationPolicy; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public abstract class TreeBuilder<T> implements TokenHandler, TreeBuilderState<T> { /** * Array version of U+FFFD. */ private static final @NoLength char[] REPLACEMENT_CHARACTER = { '\uFFFD' }; // Start dispatch groups final static int OTHER = 0; final static int A = 1; final static int BASE = 2; final static int BODY = 3; final static int BR = 4; final static int BUTTON = 5; final static int CAPTION = 6; final static int COL = 7; final static int COLGROUP = 8; final static int FORM = 9; final static int FRAME = 10; final static int FRAMESET = 11; final static int IMAGE = 12; final static int INPUT = 13; final static int ISINDEX = 14; final static int LI = 15; final static int LINK_OR_BASEFONT_OR_BGSOUND = 16; final static int MATH = 17; final static int META = 18; final static int SVG = 19; final static int HEAD = 20; final static int HR = 22; final static int HTML = 23; final static int NOBR = 24; final static int NOFRAMES = 25; final static int NOSCRIPT = 26; final static int OPTGROUP = 27; final static int OPTION = 28; final static int P = 29; final static int PLAINTEXT = 30; final static int SCRIPT = 31; final static int SELECT = 32; final static int STYLE = 33; final static int TABLE = 34; final static int TEXTAREA = 35; final static int TITLE = 36; final static int TR = 37; final static int XMP = 38; final static int TBODY_OR_THEAD_OR_TFOOT = 39; final static int TD_OR_TH = 40; final static int DD_OR_DT = 41; final static int H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6 = 42; final static int MARQUEE_OR_APPLET = 43; final static int PRE_OR_LISTING = 44; final static int B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U = 45; final static int UL_OR_OL_OR_DL = 46; final static int IFRAME = 47; final static int EMBED_OR_IMG = 48; final static int AREA_OR_WBR = 49; final static int DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU = 50; final static int ADDRESS_OR_DIR_OR_ARTICLE_OR_ASIDE_OR_DATAGRID_OR_DETAILS_OR_HGROUP_OR_FIGURE_OR_FOOTER_OR_HEADER_OR_NAV_OR_SECTION = 51; final static int RUBY_OR_SPAN_OR_SUB_OR_SUP_OR_VAR = 52; final static int RT_OR_RP = 53; final static int COMMAND = 54; final static int PARAM_OR_SOURCE = 55; final static int MGLYPH_OR_MALIGNMARK = 56; final static int MI_MO_MN_MS_MTEXT = 57; final static int ANNOTATION_XML = 58; final static int FOREIGNOBJECT_OR_DESC = 59; final static int NOEMBED = 60; final static int FIELDSET = 61; final static int OUTPUT_OR_LABEL = 62; final static int OBJECT = 63; final static int FONT = 64; final static int KEYGEN = 65; // start insertion modes private static final int INITIAL = 0; private static final int BEFORE_HTML = 1; private static final int BEFORE_HEAD = 2; private static final int IN_HEAD = 3; private static final int IN_HEAD_NOSCRIPT = 4; private static final int AFTER_HEAD = 5; private static final int IN_BODY = 6; private static final int IN_TABLE = 7; private static final int IN_CAPTION = 8; private static final int IN_COLUMN_GROUP = 9; private static final int IN_TABLE_BODY = 10; private static final int IN_ROW = 11; private static final int IN_CELL = 12; private static final int IN_SELECT = 13; private static final int IN_SELECT_IN_TABLE = 14; private static final int AFTER_BODY = 15; private static final int IN_FRAMESET = 16; private static final int AFTER_FRAMESET = 17; private static final int AFTER_AFTER_BODY = 18; private static final int AFTER_AFTER_FRAMESET = 19; private static final int TEXT = 20; private static final int FRAMESET_OK = 21; // start charset states private static final int CHARSET_INITIAL = 0; private static final int CHARSET_C = 1; private static final int CHARSET_H = 2; private static final int CHARSET_A = 3; private static final int CHARSET_R = 4; private static final int CHARSET_S = 5; private static final int CHARSET_E = 6; private static final int CHARSET_T = 7; private static final int CHARSET_EQUALS = 8; private static final int CHARSET_SINGLE_QUOTED = 9; private static final int CHARSET_DOUBLE_QUOTED = 10; private static final int CHARSET_UNQUOTED = 11; // end pseudo enums // [NOCPP[ private final static String[] HTML4_PUBLIC_IDS = { "-//W3C//DTD HTML 4.0 Frameset//EN", "-//W3C//DTD HTML 4.0 Transitional//EN", "-//W3C//DTD HTML 4.0//EN", "-//W3C//DTD HTML 4.01 Frameset//EN", "-//W3C//DTD HTML 4.01 Transitional//EN", "-//W3C//DTD HTML 4.01//EN" }; // ]NOCPP] @Literal private final static String[] QUIRKY_PUBLIC_IDS = { "+//silmaril//dtd html pro v0r11 19970101//", "-//advasoft ltd//dtd html 3.0 aswedit + extensions//", "-//as//dtd html 3.0 aswedit + extensions//", "-//ietf//dtd html 2.0 level 1//", "-//ietf//dtd html 2.0 level 2//", "-//ietf//dtd html 2.0 strict level 1//", "-//ietf//dtd html 2.0 strict level 2//", "-//ietf//dtd html 2.0 strict//", "-//ietf//dtd html 2.0//", "-//ietf//dtd html 2.1e//", "-//ietf//dtd html 3.0//", "-//ietf//dtd html 3.2 final//", "-//ietf//dtd html 3.2//", "-//ietf//dtd html 3//", "-//ietf//dtd html level 0//", "-//ietf//dtd html level 1//", "-//ietf//dtd html level 2//", "-//ietf//dtd html level 3//", "-//ietf//dtd html strict level 0//", "-//ietf//dtd html strict level 1//", "-//ietf//dtd html strict level 2//", "-//ietf//dtd html strict level 3//", "-//ietf//dtd html strict//", "-//ietf//dtd html//", "-//metrius//dtd metrius presentational//", "-//microsoft//dtd internet explorer 2.0 html strict//", "-//microsoft//dtd internet explorer 2.0 html//", "-//microsoft//dtd internet explorer 2.0 tables//", "-//microsoft//dtd internet explorer 3.0 html strict//", "-//microsoft//dtd internet explorer 3.0 html//", "-//microsoft//dtd internet explorer 3.0 tables//", "-//netscape comm. corp.//dtd html//", "-//netscape comm. corp.//dtd strict html//", "-//o'reilly and associates//dtd html 2.0//", "-//o'reilly and associates//dtd html extended 1.0//", "-//o'reilly and associates//dtd html extended relaxed 1.0//", "-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//", "-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//", "-//spyglass//dtd html 2.0 extended//", "-//sq//dtd html 2.0 hotmetal + extensions//", "-//sun microsystems corp.//dtd hotjava html//", "-//sun microsystems corp.//dtd hotjava strict html//", "-//w3c//dtd html 3 1995-03-24//", "-//w3c//dtd html 3.2 draft//", "-//w3c//dtd html 3.2 final//", "-//w3c//dtd html 3.2//", "-//w3c//dtd html 3.2s draft//", "-//w3c//dtd html 4.0 frameset//", "-//w3c//dtd html 4.0 transitional//", "-//w3c//dtd html experimental 19960712//", "-//w3c//dtd html experimental 970421//", "-//w3c//dtd w3 html//", "-//w3o//dtd w3 html 3.0//", "-//webtechs//dtd mozilla html 2.0//", "-//webtechs//dtd mozilla html//" }; private static final int NOT_FOUND_ON_STACK = Integer.MAX_VALUE; // [NOCPP[ private static final @Local String HTML_LOCAL = "html"; // ]NOCPP] private int mode = INITIAL; private int originalMode = INITIAL; /** * Used only when moving back to IN_BODY. */ private boolean framesetOk = true; private boolean inForeign = false; protected Tokenizer tokenizer; // [NOCPP[ protected ErrorHandler errorHandler; private DocumentModeHandler documentModeHandler; private DoctypeExpectation doctypeExpectation = DoctypeExpectation.HTML; // ]NOCPP] private boolean scriptingEnabled = false; private boolean needToDropLF; // [NOCPP[ private boolean wantingComments; // ]NOCPP] private boolean fragment; private @Local String contextName; private @NsUri String contextNamespace; private T contextNode; private StackNode<T>[] stack; private int currentPtr = -1; private StackNode<T>[] listOfActiveFormattingElements; private int listPtr = -1; private T formPointer; private T headPointer; /** * Used to work around Gecko limitations. Not used in Java. */ private T deepTreeSurrogateParent; protected char[] charBuffer; protected int charBufferLen = 0; private boolean quirks = false; // [NOCPP[ private boolean reportingDoctype = true; private XmlViolationPolicy namePolicy = XmlViolationPolicy.ALTER_INFOSET; private final Map<String, LocatorImpl> idLocations = new HashMap<String, LocatorImpl>(); private boolean html4; // ]NOCPP] protected TreeBuilder() { fragment = false; } /** * Reports an condition that would make the infoset incompatible with XML * 1.0 as fatal. * * @throws SAXException * @throws SAXParseException */ protected void fatal() throws SAXException { } // [NOCPP[ protected final void fatal(Exception e) throws SAXException { SAXParseException spe = new SAXParseException(e.getMessage(), tokenizer, e); if (errorHandler != null) { errorHandler.fatalError(spe); } throw spe; } final void fatal(String s) throws SAXException { SAXParseException spe = new SAXParseException(s, tokenizer); if (errorHandler != null) { errorHandler.fatalError(spe); } throw spe; } // ]NOCPP] /** * Reports a Parse Error. * * @param message * the message * @throws SAXException */ final void err(String message) throws SAXException { // [NOCPP[ if (errorHandler == null) { return; } errNoCheck(message); // ]NOCPP] } /** * Reports a Parse Error without checking if an error handler is present. * * @param message * the message * @throws SAXException */ final void errNoCheck(String message) throws SAXException { // [NOCPP[ SAXParseException spe = new SAXParseException(message, tokenizer); errorHandler.error(spe); // ]NOCPP] } /** * Reports a warning * * @param message * the message * @throws SAXException */ final void warn(String message) throws SAXException { // [NOCPP[ if (errorHandler == null) { return; } SAXParseException spe = new SAXParseException(message, tokenizer); errorHandler.warning(spe); // ]NOCPP] } @SuppressWarnings("unchecked") public final void startTokenization(Tokenizer self) throws SAXException { tokenizer = self; stack = new StackNode[64]; listOfActiveFormattingElements = new StackNode[64]; needToDropLF = false; originalMode = INITIAL; currentPtr = -1; listPtr = -1; Portability.releaseElement(formPointer); formPointer = null; Portability.releaseElement(headPointer); headPointer = null; Portability.releaseElement(deepTreeSurrogateParent); deepTreeSurrogateParent = null; // [NOCPP[ html4 = false; idLocations.clear(); wantingComments = wantsComments(); // ]NOCPP] start(fragment); charBufferLen = 0; charBuffer = new char[1024]; framesetOk = true; if (fragment) { T elt; if (contextNode != null) { elt = contextNode; Portability.retainElement(elt); } else { elt = createHtmlElementSetAsRoot(tokenizer.emptyAttributes()); } StackNode<T> node = new StackNode<T>( "http://www.w3.org/1999/xhtml", ElementName.HTML, elt); currentPtr++; stack[currentPtr] = node; resetTheInsertionMode(); if ("title" == contextName || "textarea" == contextName) { tokenizer.setStateAndEndTagExpectation(Tokenizer.RCDATA, contextName); } else if ("style" == contextName || "xmp" == contextName || "iframe" == contextName || "noembed" == contextName || "noframes" == contextName || (scriptingEnabled && "noscript" == contextName)) { tokenizer.setStateAndEndTagExpectation(Tokenizer.RAWTEXT, contextName); } else if ("plaintext" == contextName) { tokenizer.setStateAndEndTagExpectation(Tokenizer.PLAINTEXT, contextName); } else if ("script" == contextName) { tokenizer.setStateAndEndTagExpectation(Tokenizer.SCRIPT_DATA, contextName); } else { tokenizer.setStateAndEndTagExpectation(Tokenizer.DATA, contextName); } Portability.releaseLocal(contextName); contextName = null; Portability.releaseElement(contextNode); contextNode = null; Portability.releaseElement(elt); } else { mode = INITIAL; inForeign = false; } } public final void doctype(@Local String name, String publicIdentifier, String systemIdentifier, boolean forceQuirks) throws SAXException { needToDropLF = false; if (!inForeign) { switch (mode) { case INITIAL: // [NOCPP[ if (reportingDoctype) { // ]NOCPP] String emptyString = Portability.newEmptyString(); appendDoctypeToDocument(name == null ? "" : name, publicIdentifier == null ? emptyString : publicIdentifier, systemIdentifier == null ? emptyString : systemIdentifier); Portability.releaseString(emptyString); // [NOCPP[ } switch (doctypeExpectation) { case HTML: // ]NOCPP] if (isQuirky(name, publicIdentifier, systemIdentifier, forceQuirks)) { err("Quirky doctype. Expected \u201C<!DOCTYPE html>\u201D."); documentModeInternal(DocumentMode.QUIRKS_MODE, publicIdentifier, systemIdentifier, false); } else if (isAlmostStandards(publicIdentifier, systemIdentifier)) { err("Almost standards mode doctype. Expected \u201C<!DOCTYPE html>\u201D."); documentModeInternal( DocumentMode.ALMOST_STANDARDS_MODE, publicIdentifier, systemIdentifier, false); } else { // [NOCPP[ if ((Portability.literalEqualsString( "-//W3C//DTD HTML 4.0//EN", publicIdentifier) && (systemIdentifier == null || Portability.literalEqualsString( "http://www.w3.org/TR/REC-html40/strict.dtd", systemIdentifier))) || (Portability.literalEqualsString( "-//W3C//DTD HTML 4.01//EN", publicIdentifier) && (systemIdentifier == null || Portability.literalEqualsString( "http://www.w3.org/TR/html4/strict.dtd", systemIdentifier))) || (Portability.literalEqualsString( "-//W3C//DTD XHTML 1.0 Strict//EN", publicIdentifier) && Portability.literalEqualsString( "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd", systemIdentifier)) || (Portability.literalEqualsString( "-//W3C//DTD XHTML 1.1//EN", publicIdentifier) && Portability.literalEqualsString( "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd", systemIdentifier)) ) { warn("Obsolete doctype. Expected \u201C<!DOCTYPE html>\u201D."); } else if (!((systemIdentifier == null || Portability.literalEqualsString( "about:legacy-compat", systemIdentifier)) && publicIdentifier == null)) { err("Legacy doctype. Expected \u201C<!DOCTYPE html>\u201D."); } // ]NOCPP] documentModeInternal( DocumentMode.STANDARDS_MODE, publicIdentifier, systemIdentifier, false); } // [NOCPP[ break; case HTML401_STRICT: html4 = true; tokenizer.turnOnAdditionalHtml4Errors(); if (isQuirky(name, publicIdentifier, systemIdentifier, forceQuirks)) { err("Quirky doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); documentModeInternal(DocumentMode.QUIRKS_MODE, publicIdentifier, systemIdentifier, true); } else if (isAlmostStandards(publicIdentifier, systemIdentifier)) { err("Almost standards mode doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); documentModeInternal( DocumentMode.ALMOST_STANDARDS_MODE, publicIdentifier, systemIdentifier, true); } else { if ("-//W3C//DTD HTML 4.01//EN".equals(publicIdentifier)) { if (!"http://www.w3.org/TR/html4/strict.dtd".equals(systemIdentifier)) { warn("The doctype did not contain the system identifier prescribed by the HTML 4.01 specification. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); } } else { err("The doctype was not the HTML 4.01 Strict doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); } documentModeInternal( DocumentMode.STANDARDS_MODE, publicIdentifier, systemIdentifier, true); } break; case HTML401_TRANSITIONAL: html4 = true; tokenizer.turnOnAdditionalHtml4Errors(); if (isQuirky(name, publicIdentifier, systemIdentifier, forceQuirks)) { err("Quirky doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); documentModeInternal(DocumentMode.QUIRKS_MODE, publicIdentifier, systemIdentifier, true); } else if (isAlmostStandards(publicIdentifier, systemIdentifier)) { if ("-//W3C//DTD HTML 4.01 Transitional//EN".equals(publicIdentifier) && systemIdentifier != null) { if (!"http://www.w3.org/TR/html4/loose.dtd".equals(systemIdentifier)) { warn("The doctype did not contain the system identifier prescribed by the HTML 4.01 specification. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); } } else { err("The doctype was not a non-quirky HTML 4.01 Transitional doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); } documentModeInternal( DocumentMode.ALMOST_STANDARDS_MODE, publicIdentifier, systemIdentifier, true); } else { err("The doctype was not the HTML 4.01 Transitional doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); documentModeInternal( DocumentMode.STANDARDS_MODE, publicIdentifier, systemIdentifier, true); } break; case AUTO: html4 = isHtml4Doctype(publicIdentifier); if (html4) { tokenizer.turnOnAdditionalHtml4Errors(); } if (isQuirky(name, publicIdentifier, systemIdentifier, forceQuirks)) { err("Quirky doctype. Expected e.g. \u201C<!DOCTYPE html>\u201D."); documentModeInternal(DocumentMode.QUIRKS_MODE, publicIdentifier, systemIdentifier, html4); } else if (isAlmostStandards(publicIdentifier, systemIdentifier)) { if ("-//W3C//DTD HTML 4.01 Transitional//EN".equals(publicIdentifier)) { if (!"http://www.w3.org/TR/html4/loose.dtd".equals(systemIdentifier)) { warn("The doctype did not contain the system identifier prescribed by the HTML 4.01 specification. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); } } else { err("Almost standards mode doctype. Expected e.g. \u201C<!DOCTYPE html>\u201D."); } documentModeInternal( DocumentMode.ALMOST_STANDARDS_MODE, publicIdentifier, systemIdentifier, html4); } else { if ("-//W3C//DTD HTML 4.01//EN".equals(publicIdentifier)) { if (!"http://www.w3.org/TR/html4/strict.dtd".equals(systemIdentifier)) { warn("The doctype did not contain the system identifier prescribed by the HTML 4.01 specification. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); } } else { if (!(publicIdentifier == null && systemIdentifier == null)) { err("Legacy doctype. Expected e.g. \u201C<!DOCTYPE html>\u201D."); } } documentModeInternal( DocumentMode.STANDARDS_MODE, publicIdentifier, systemIdentifier, html4); } break; case NO_DOCTYPE_ERRORS: if (isQuirky(name, publicIdentifier, systemIdentifier, forceQuirks)) { documentModeInternal(DocumentMode.QUIRKS_MODE, publicIdentifier, systemIdentifier, false); } else if (isAlmostStandards(publicIdentifier, systemIdentifier)) { documentModeInternal( DocumentMode.ALMOST_STANDARDS_MODE, publicIdentifier, systemIdentifier, false); } else { documentModeInternal( DocumentMode.STANDARDS_MODE, publicIdentifier, systemIdentifier, false); } break; } // ]NOCPP] /* * * Then, switch to the root element mode of the tree * construction stage. */ mode = BEFORE_HTML; return; default: break; } } /* * A DOCTYPE token Parse error. */ err("Stray doctype."); /* * Ignore the token. */ return; } // [NOCPP[ private boolean isHtml4Doctype(String publicIdentifier) { if (publicIdentifier != null && (Arrays.binarySearch(TreeBuilder.HTML4_PUBLIC_IDS, publicIdentifier) > -1)) { return true; } return false; } // ]NOCPP] public final void comment(@NoLength char[] buf, int start, int length) throws SAXException { needToDropLF = false; // [NOCPP[ if (!wantingComments) { return; } // ]NOCPP] if (!inForeign) { switch (mode) { case INITIAL: case BEFORE_HTML: case AFTER_AFTER_BODY: case AFTER_AFTER_FRAMESET: /* * A comment token Append a Comment node to the Document * object with the data attribute set to the data given in * the comment token. */ appendCommentToDocument(buf, start, length); return; case AFTER_BODY: /* * A comment token Append a Comment node to the first * element in the stack of open elements (the html element), * with the data attribute set to the data given in the * comment token. */ flushCharacters(); appendComment(stack[0].node, buf, start, length); return; default: break; } } /* * A comment token Append a Comment node to the current node with the * data attribute set to the data given in the comment token. */ flushCharacters(); appendComment(stack[currentPtr].node, buf, start, length); return; } /** * @see nu.validator.htmlparser.common.TokenHandler#characters(char[], int, * int) */ public final void characters(@Const @NoLength char[] buf, int start, int length) throws SAXException { if (needToDropLF) { if (buf[start] == '\n') { start++; length--; if (length == 0) { return; } } needToDropLF = false; } if (inForeign) { accumulateCharacters(buf, start, length); return; } // optimize the most common case switch (mode) { case IN_BODY: case IN_CELL: case IN_CAPTION: reconstructTheActiveFormattingElements(); // fall through case TEXT: accumulateCharacters(buf, start, length); return; case IN_TABLE: case IN_TABLE_BODY: case IN_ROW: accumulateCharactersForced(buf, start, length); return; default: int end = start + length; charactersloop: for (int i = start; i < end; i++) { switch (buf[i]) { case ' ': case '\t': case '\n': case '\r': case '\u000C': /* * A character token that is one of one of U+0009 * CHARACTER TABULATION, U+000A LINE FEED (LF), * U+000C FORM FEED (FF), or U+0020 SPACE */ switch (mode) { case INITIAL: case BEFORE_HTML: case BEFORE_HEAD: /* * Ignore the token. */ start = i + 1; continue; case IN_HEAD: case IN_HEAD_NOSCRIPT: case AFTER_HEAD: case IN_COLUMN_GROUP: case IN_FRAMESET: case AFTER_FRAMESET: /* * Append the character to the current node. */ continue; case FRAMESET_OK: case IN_BODY: case IN_CELL: case IN_CAPTION: if (start < i) { accumulateCharacters(buf, start, i - start); start = i; } /* * Reconstruct the active formatting * elements, if any. */ flushCharacters(); reconstructTheActiveFormattingElements(); /* * Append the token's character to the * current node. */ break charactersloop; case IN_SELECT: case IN_SELECT_IN_TABLE: break charactersloop; case IN_TABLE: case IN_TABLE_BODY: case IN_ROW: accumulateCharactersForced(buf, i, 1); start = i + 1; continue; case AFTER_BODY: case AFTER_AFTER_BODY: case AFTER_AFTER_FRAMESET: if (start < i) { accumulateCharacters(buf, start, i - start); start = i; } /* * Reconstruct the active formatting * elements, if any. */ flushCharacters(); reconstructTheActiveFormattingElements(); /* * Append the token's character to the * current node. */ continue; } default: /* * A character token that is not one of one of * U+0009 CHARACTER TABULATION, U+000A LINE FEED * (LF), U+000C FORM FEED (FF), or U+0020 SPACE */ switch (mode) { case INITIAL: /* * Parse error. */ // [NOCPP[ switch (doctypeExpectation) { case AUTO: err("Non-space characters found without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D."); break; case HTML: err("Non-space characters found without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D."); break; case HTML401_STRICT: err("Non-space characters found without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); break; case HTML401_TRANSITIONAL: err("Non-space characters found without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); break; case NO_DOCTYPE_ERRORS: } // ]NOCPP] /* * * Set the document to quirks mode. */ documentModeInternal( DocumentMode.QUIRKS_MODE, null, null, false); /* * Then, switch to the root element mode of * the tree construction stage */ mode = BEFORE_HTML; /* * and reprocess the current token. */ i--; continue; case BEFORE_HTML: /* * Create an HTMLElement node with the tag * name html, in the HTML namespace. Append * it to the Document object. */ // No need to flush characters here, // because there's nothing to flush. appendHtmlElementToDocumentAndPush(); /* Switch to the main mode */ mode = BEFORE_HEAD; /* * reprocess the current token. */ i--; continue; case BEFORE_HEAD: if (start < i) { accumulateCharacters(buf, start, i - start); start = i; } /* * /Act as if a start tag token with the tag * name "head" and no attributes had been * seen, */ flushCharacters(); appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_HEAD; /* * then reprocess the current token. * * This will result in an empty head element * being generated, with the current token * being reprocessed in the "after head" * insertion mode. */ i--; continue; case IN_HEAD: if (start < i) { accumulateCharacters(buf, start, i - start); start = i; } /* * Act as if an end tag token with the tag * name "head" had been seen, */ flushCharacters(); pop(); mode = AFTER_HEAD; /* * and reprocess the current token. */ i--; continue; case IN_HEAD_NOSCRIPT: if (start < i) { accumulateCharacters(buf, start, i - start); start = i; } /* * Parse error. Act as if an end tag with * the tag name "noscript" had been seen */ err("Non-space character inside \u201Cnoscript\u201D inside \u201Chead\u201D."); flushCharacters(); pop(); mode = IN_HEAD; /* * and reprocess the current token. */ i--; continue; case AFTER_HEAD: if (start < i) { accumulateCharacters(buf, start, i - start); start = i; } /* * Act as if a start tag token with the tag * name "body" and no attributes had been * seen, */ flushCharacters(); appendToCurrentNodeAndPushBodyElement(); mode = FRAMESET_OK; /* * and then reprocess the current token. */ i--; continue; case FRAMESET_OK: framesetOk = false; mode = IN_BODY; i--; continue; case IN_BODY: case IN_CELL: case IN_CAPTION: if (start < i) { accumulateCharacters(buf, start, i - start); start = i; } /* * Reconstruct the active formatting * elements, if any. */ flushCharacters(); reconstructTheActiveFormattingElements(); /* * Append the token's character to the * current node. */ break charactersloop; case IN_TABLE: case IN_TABLE_BODY: case IN_ROW: accumulateCharactersForced(buf, i, 1); start = i + 1; continue; case IN_COLUMN_GROUP: if (start < i) { accumulateCharacters(buf, start, i - start); start = i; } /* * Act as if an end tag with the tag name * "colgroup" had been seen, and then, if * that token wasn't ignored, reprocess the * current token. */ if (currentPtr == 0) { err("Non-space in \u201Ccolgroup\u201D when parsing fragment."); start = i + 1; continue; } flushCharacters(); pop(); mode = IN_TABLE; i--; continue; case IN_SELECT: case IN_SELECT_IN_TABLE: break charactersloop; case AFTER_BODY: err("Non-space character after body."); fatal(); mode = framesetOk ? FRAMESET_OK : IN_BODY; i--; continue; case IN_FRAMESET: if (start < i) { accumulateCharacters(buf, start, i - start); start = i; } /* * Parse error. */ err("Non-space in \u201Cframeset\u201D."); /* * Ignore the token. */ start = i + 1; continue; case AFTER_FRAMESET: if (start < i) { accumulateCharacters(buf, start, i - start); start = i; } /* * Parse error. */ err("Non-space after \u201Cframeset\u201D."); /* * Ignore the token. */ start = i + 1; continue; case AFTER_AFTER_BODY: /* * Parse error. */ err("Non-space character in page trailer."); /* * Switch back to the main mode and * reprocess the token. */ mode = framesetOk ? FRAMESET_OK : IN_BODY; i--; continue; case AFTER_AFTER_FRAMESET: /* * Parse error. */ err("Non-space character in page trailer."); /* * Switch back to the main mode and * reprocess the token. */ mode = IN_FRAMESET; i--; continue; } } } if (start < end) { accumulateCharacters(buf, start, end - start); } } } /** * @see nu.validator.htmlparser.common.TokenHandler#zeroOriginatingReplacementCharacter() */ @Override public void zeroOriginatingReplacementCharacter() throws SAXException { if (inForeign || mode == TEXT) { characters(REPLACEMENT_CHARACTER, 0, 1); } } public final void eof() throws SAXException { flushCharacters(); eofloop: for (;;) { if (inForeign) { err("End of file in a foreign namespace context."); break eofloop; } switch (mode) { case INITIAL: /* * Parse error. */ // [NOCPP[ switch (doctypeExpectation) { case AUTO: err("End of file seen without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D."); break; case HTML: err("End of file seen without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D."); break; case HTML401_STRICT: err("End of file seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); break; case HTML401_TRANSITIONAL: err("End of file seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); break; case NO_DOCTYPE_ERRORS: } // ]NOCPP] /* * * Set the document to quirks mode. */ documentModeInternal(DocumentMode.QUIRKS_MODE, null, null, false); /* * Then, switch to the root element mode of the tree * construction stage */ mode = BEFORE_HTML; /* * and reprocess the current token. */ continue; case BEFORE_HTML: /* * Create an HTMLElement node with the tag name html, in the * HTML namespace. Append it to the Document object. */ appendHtmlElementToDocumentAndPush(); // XXX application cache manifest /* Switch to the main mode */ mode = BEFORE_HEAD; /* * reprocess the current token. */ continue; case BEFORE_HEAD: appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_HEAD; continue; case IN_HEAD: if (errorHandler != null && currentPtr > 1) { err("End of file seen and there were open elements."); } while (currentPtr > 0) { popOnEof(); } mode = AFTER_HEAD; continue; case IN_HEAD_NOSCRIPT: err("End of file seen and there were open elements."); while (currentPtr > 1) { popOnEof(); } mode = IN_HEAD; continue; case AFTER_HEAD: appendToCurrentNodeAndPushBodyElement(); mode = IN_BODY; continue; case IN_COLUMN_GROUP: if (currentPtr == 0) { assert fragment; break eofloop; } else { popOnEof(); mode = IN_TABLE; continue; } case FRAMESET_OK: case IN_CAPTION: case IN_CELL: case IN_BODY: // [NOCPP[ openelementloop: for (int i = currentPtr; i >= 0; i--) { int group = stack[i].group; switch (group) { case DD_OR_DT: case LI: case P: case TBODY_OR_THEAD_OR_TFOOT: case TD_OR_TH: case BODY: case HTML: break; default: err("End of file seen and there were open elements."); break openelementloop; } } // ]NOCPP] break eofloop; case TEXT: err("End of file seen when expecting text or an end tag."); // XXX mark script as already executed if (originalMode == AFTER_HEAD) { popOnEof(); } popOnEof(); mode = originalMode; continue; case IN_TABLE_BODY: case IN_ROW: case IN_TABLE: case IN_SELECT: case IN_SELECT_IN_TABLE: case IN_FRAMESET: if (errorHandler != null && currentPtr > 0) { errNoCheck("End of file seen and there were open elements."); } break eofloop; case AFTER_BODY: case AFTER_FRAMESET: case AFTER_AFTER_BODY: case AFTER_AFTER_FRAMESET: default: // [NOCPP[ if (currentPtr == 0) { // This silliness is here to poison // buggy compiler optimizations in // GWT System.currentTimeMillis(); } // ]NOCPP] break eofloop; } } while (currentPtr > 0) { popOnEof(); } if (!fragment) { popOnEof(); } /* Stop parsing. */ } /** * @see nu.validator.htmlparser.common.TokenHandler#endTokenization() */ public final void endTokenization() throws SAXException { Portability.releaseElement(formPointer); formPointer = null; Portability.releaseElement(headPointer); headPointer = null; Portability.releaseElement(deepTreeSurrogateParent); deepTreeSurrogateParent = null; if (stack != null) { while (currentPtr > -1) { stack[currentPtr].release(); currentPtr--; } Portability.releaseArray(stack); stack = null; } if (listOfActiveFormattingElements != null) { while (listPtr > -1) { if (listOfActiveFormattingElements[listPtr] != null) { listOfActiveFormattingElements[listPtr].release(); } listPtr--; } Portability.releaseArray(listOfActiveFormattingElements); listOfActiveFormattingElements = null; } // [NOCPP[ idLocations.clear(); // ]NOCPP] if (charBuffer != null) { Portability.releaseArray(charBuffer); charBuffer = null; } end(); } public final void startTag(ElementName elementName, HtmlAttributes attributes, boolean selfClosing) throws SAXException { flushCharacters(); // [NOCPP[ if (errorHandler != null) { // ID uniqueness @IdType String id = attributes.getId(); if (id != null) { LocatorImpl oldLoc = idLocations.get(id); if (oldLoc != null) { err("Duplicate ID \u201C" + id + "\u201D."); errorHandler.warning(new SAXParseException( "The first occurrence of ID \u201C" + id + "\u201D was here.", oldLoc)); } else { idLocations.put(id, new LocatorImpl(tokenizer)); } } } // ]NOCPP] int eltPos; needToDropLF = false; boolean needsPostProcessing = false; starttagloop: for (;;) { int group = elementName.group; @Local String name = elementName.name; if (inForeign) { StackNode<T> currentNode = stack[currentPtr]; @NsUri String currNs = currentNode.ns; int currGroup = currentNode.group; if (("http://www.w3.org/1999/xhtml" == currNs) || ("http://www.w3.org/1998/Math/MathML" == currNs && ((MGLYPH_OR_MALIGNMARK != group && MI_MO_MN_MS_MTEXT == currGroup) || (SVG == group && ANNOTATION_XML == currGroup))) || ("http://www.w3.org/2000/svg" == currNs && (TITLE == currGroup || (FOREIGNOBJECT_OR_DESC == currGroup)))) { needsPostProcessing = true; // fall through to non-foreign behavior } else { switch (group) { case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U: case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU: case BODY: case BR: case RUBY_OR_SPAN_OR_SUB_OR_SUP_OR_VAR: case DD_OR_DT: case UL_OR_OL_OR_DL: case EMBED_OR_IMG: case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6: case HEAD: case HR: case LI: case META: case NOBR: case P: case PRE_OR_LISTING: case TABLE: err("HTML start tag \u201C" + name + "\u201D in a foreign namespace context."); while (!isSpecialParentInForeign(stack[currentPtr])) { pop(); } if (!hasForeignInScope()) { inForeign = false; } continue starttagloop; case FONT: if (attributes.contains(AttributeName.COLOR) || attributes.contains(AttributeName.FACE) || attributes.contains(AttributeName.SIZE)) { err("HTML start tag \u201C" + name + "\u201D in a foreign namespace context."); while (!isSpecialParentInForeign(stack[currentPtr])) { pop(); } if (!hasForeignInScope()) { inForeign = false; } continue starttagloop; } // else fall thru default: if ("http://www.w3.org/2000/svg" == currNs) { attributes.adjustForSvg(); if (selfClosing) { appendVoidElementToCurrentMayFosterCamelCase( currNs, elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFosterCamelCase( currNs, elementName, attributes); } attributes = null; // CPP break starttagloop; } else { attributes.adjustForMath(); if (selfClosing) { appendVoidElementToCurrentMayFoster( currNs, elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFosterNoScoping( currNs, elementName, attributes); } attributes = null; // CPP break starttagloop; } } // switch } // foreignObject / annotation-xml } switch (mode) { case IN_TABLE_BODY: switch (group) { case TR: clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot()); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_ROW; attributes = null; // CPP break starttagloop; case TD_OR_TH: err("\u201C" + name + "\u201D start tag in table body."); clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot()); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", ElementName.TR, HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_ROW; continue; case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: eltPos = findLastInTableScopeOrRootTbodyTheadTfoot(); if (eltPos == 0) { err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } else { clearStackBackTo(eltPos); pop(); mode = IN_TABLE; continue; } default: // fall through to IN_TABLE } case IN_ROW: switch (group) { case TD_OR_TH: clearStackBackTo(findLastOrRoot(TreeBuilder.TR)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_CELL; insertMarker(); attributes = null; // CPP break starttagloop; case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: eltPos = findLastOrRoot(TreeBuilder.TR); if (eltPos == 0) { assert fragment; err("No table row to close."); break starttagloop; } clearStackBackTo(eltPos); pop(); mode = IN_TABLE_BODY; continue; default: // fall through to IN_TABLE } case IN_TABLE: intableloop: for (;;) { switch (group) { case CAPTION: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); insertMarker(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_CAPTION; attributes = null; // CPP break starttagloop; case COLGROUP: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_COLUMN_GROUP; attributes = null; // CPP break starttagloop; case COL: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", ElementName.COLGROUP, HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_COLUMN_GROUP; continue starttagloop; case TBODY_OR_THEAD_OR_TFOOT: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_TABLE_BODY; attributes = null; // CPP break starttagloop; case TR: case TD_OR_TH: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", ElementName.TBODY, HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_TABLE_BODY; continue starttagloop; case TABLE: err("Start tag for \u201Ctable\u201D seen but the previous \u201Ctable\u201D is still open."); eltPos = findLastInTableScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; break starttagloop; } generateImpliedEndTags(); // XXX is the next if dead code? if (errorHandler != null && !isCurrent("table")) { errNoCheck("Unclosed elements on stack."); } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); continue starttagloop; case SCRIPT: // XXX need to manage much more stuff // here if // supporting // document.write() appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; case STYLE: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case INPUT: if (!Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "hidden", attributes.getValue(AttributeName.TYPE))) { break intableloop; } appendVoidElementToCurrent( "http://www.w3.org/1999/xhtml", name, attributes, formPointer); selfClosing = false; attributes = null; // CPP break starttagloop; case FORM: if (formPointer != null) { err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag."); break starttagloop; } else { err("Start tag \u201Cform\u201D seen in \u201Ctable\u201D."); appendVoidFormToCurrent(attributes); attributes = null; // CPP break starttagloop; } default: err("Start tag \u201C" + name + "\u201D seen in \u201Ctable\u201D."); // fall through to IN_BODY break intableloop; } } case IN_CAPTION: switch (group) { case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: err("Stray \u201C" + name + "\u201D start tag in \u201Ccaption\u201D."); eltPos = findLastInTableScope("caption"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { break starttagloop; } generateImpliedEndTags(); if (errorHandler != null && currentPtr != eltPos) { errNoCheck("Unclosed elements on stack."); } while (currentPtr >= eltPos) { pop(); } clearTheListOfActiveFormattingElementsUpToTheLastMarker(); mode = IN_TABLE; continue; default: // fall through to IN_BODY } case IN_CELL: switch (group) { case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: eltPos = findLastInTableScopeTdTh(); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("No cell to close."); break starttagloop; } else { closeTheCell(eltPos); continue; } default: // fall through to IN_BODY } case FRAMESET_OK: switch (group) { case FRAMESET: if (mode == FRAMESET_OK) { if (currentPtr == 0 || stack[1].group != BODY) { assert fragment; err("Stray \u201Cframeset\u201D start tag."); break starttagloop; } else { err("\u201Cframeset\u201D start tag seen."); detachFromParent(stack[1].node); while (currentPtr > 0) { pop(); } appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_FRAMESET; attributes = null; // CPP break starttagloop; } } else { err("Stray \u201Cframeset\u201D start tag."); break starttagloop; } // NOT falling through! case PRE_OR_LISTING: case LI: case DD_OR_DT: case BUTTON: case MARQUEE_OR_APPLET: case OBJECT: case TABLE: case AREA_OR_WBR: case BR: case EMBED_OR_IMG: case INPUT: case KEYGEN: case HR: case TEXTAREA: case XMP: case IFRAME: case SELECT: if (mode == FRAMESET_OK) { framesetOk = false; mode = IN_BODY; } // fall through to IN_BODY default: // fall through to IN_BODY } case IN_BODY: inbodyloop: for (;;) { switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case BASE: case LINK_OR_BASEFONT_OR_BGSOUND: case META: case STYLE: case SCRIPT: case TITLE: case COMMAND: // Fall through to IN_HEAD break inbodyloop; case BODY: err("\u201Cbody\u201D start tag found but the \u201Cbody\u201D element is already open."); if (addAttributesToBody(attributes)) { attributes = null; // CPP } break starttagloop; case P: case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU: case UL_OR_OL_OR_DL: case ADDRESS_OR_DIR_OR_ARTICLE_OR_ASIDE_OR_DATAGRID_OR_DETAILS_OR_HGROUP_OR_FIGURE_OR_FOOTER_OR_HEADER_OR_NAV_OR_SECTION: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6: implicitlyCloseP(); if (stack[currentPtr].group == H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6) { err("Heading cannot be a child of another heading."); pop(); } appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case FIELDSET: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); attributes = null; // CPP break starttagloop; case PRE_OR_LISTING: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); needToDropLF = true; attributes = null; // CPP break starttagloop; case FORM: if (formPointer != null) { err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag."); break starttagloop; } else { implicitlyCloseP(); appendToCurrentNodeAndPushFormElementMayFoster(attributes); attributes = null; // CPP break starttagloop; } case LI: case DD_OR_DT: eltPos = currentPtr; for (;;) { StackNode<T> node = stack[eltPos]; // weak // ref if (node.group == group) { // LI or // DD_OR_DT generateImpliedEndTagsExceptFor(node.name); if (errorHandler != null && eltPos != currentPtr) { errNoCheck("Unclosed elements inside a list."); } while (currentPtr >= eltPos) { pop(); } break; } else if (node.scoping || (node.special && node.name != "p" && node.name != "address" && node.name != "div")) { break; } eltPos--; } implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case PLAINTEXT: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); tokenizer.setStateAndEndTagExpectation( Tokenizer.PLAINTEXT, elementName); attributes = null; // CPP break starttagloop; case A: int activeAPos = findInListOfActiveFormattingElementsContainsBetweenEndAndLastMarker("a"); if (activeAPos != -1) { err("An \u201Ca\u201D start tag seen with already an active \u201Ca\u201D element."); StackNode<T> activeA = listOfActiveFormattingElements[activeAPos]; activeA.retain(); adoptionAgencyEndTag("a"); removeFromStack(activeA); activeAPos = findInListOfActiveFormattingElements(activeA); if (activeAPos != -1) { removeFromListOfActiveFormattingElements(activeAPos); } activeA.release(); } reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushFormattingElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U: case FONT: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushFormattingElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case NOBR: reconstructTheActiveFormattingElements(); if (TreeBuilder.NOT_FOUND_ON_STACK != findLastInScope("nobr")) { err("\u201Cnobr\u201D start tag seen when there was an open \u201Cnobr\u201D element in scope."); adoptionAgencyEndTag("nobr"); } appendToCurrentNodeAndPushFormattingElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case BUTTON: eltPos = findLastInScope(name); if (eltPos != TreeBuilder.NOT_FOUND_ON_STACK) { err("\u201Cbutton\u201D start tag seen when there was an open \u201Cbutton\u201D element in scope."); generateImpliedEndTags(); if (errorHandler != null && !isCurrent(name)) { errNoCheck("End tag \u201Cbutton\u201D seen but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } continue starttagloop; } else { reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); attributes = null; // CPP break starttagloop; } case OBJECT: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); insertMarker(); attributes = null; // CPP break starttagloop; case MARQUEE_OR_APPLET: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); insertMarker(); attributes = null; // CPP break starttagloop; case TABLE: // The only quirk. Blame Hixie and // Acid2. if (!quirks) { implicitlyCloseP(); } appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_TABLE; attributes = null; // CPP break starttagloop; case BR: case EMBED_OR_IMG: case AREA_OR_WBR: reconstructTheActiveFormattingElements(); // FALL THROUGH to PARAM_OR_SOURCE case PARAM_OR_SOURCE: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case HR: implicitlyCloseP(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case IMAGE: err("Saw a start tag \u201Cimage\u201D."); elementName = ElementName.IMG; continue starttagloop; case KEYGEN: case INPUT: reconstructTheActiveFormattingElements(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", name, attributes, formPointer); selfClosing = false; attributes = null; // CPP break starttagloop; case ISINDEX: err("\u201Cisindex\u201D seen."); if (formPointer != null) { break starttagloop; } implicitlyCloseP(); HtmlAttributes formAttrs = new HtmlAttributes(0); int actionIndex = attributes.getIndex(AttributeName.ACTION); if (actionIndex > -1) { formAttrs.addAttribute( AttributeName.ACTION, attributes.getValue(actionIndex) // [NOCPP[ , XmlViolationPolicy.ALLOW // ]NOCPP] ); } appendToCurrentNodeAndPushFormElementMayFoster(formAttrs); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", ElementName.HR, HtmlAttributes.EMPTY_ATTRIBUTES); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", ElementName.LABEL, HtmlAttributes.EMPTY_ATTRIBUTES); int promptIndex = attributes.getIndex(AttributeName.PROMPT); if (promptIndex > -1) { char[] prompt = Portability.newCharArrayFromString(attributes.getValue(promptIndex)); appendCharacters(stack[currentPtr].node, prompt, 0, prompt.length); Portability.releaseArray(prompt); } else { appendIsindexPrompt(stack[currentPtr].node); } HtmlAttributes inputAttributes = new HtmlAttributes( 0); inputAttributes.addAttribute( AttributeName.NAME, Portability.newStringFromLiteral("isindex") // [NOCPP[ , XmlViolationPolicy.ALLOW // ]NOCPP] ); for (int i = 0; i < attributes.getLength(); i++) { AttributeName attributeQName = attributes.getAttributeName(i); if (AttributeName.NAME == attributeQName || AttributeName.PROMPT == attributeQName) { attributes.releaseValue(i); } else if (AttributeName.ACTION != attributeQName) { inputAttributes.addAttribute( attributeQName, attributes.getValue(i) // [NOCPP[ , XmlViolationPolicy.ALLOW // ]NOCPP] ); } } attributes.clearWithoutReleasingContents(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", "input", inputAttributes, formPointer); pop(); // label appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", ElementName.HR, HtmlAttributes.EMPTY_ATTRIBUTES); pop(); // form selfClosing = false; // Portability.delete(formAttrs); // Portability.delete(inputAttributes); // Don't delete attributes, they are deleted // later break starttagloop; case TEXTAREA: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); tokenizer.setStateAndEndTagExpectation( Tokenizer.RCDATA, elementName); originalMode = mode; mode = TEXT; needToDropLF = true; attributes = null; // CPP break starttagloop; case XMP: implicitlyCloseP(); reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case NOSCRIPT: if (!scriptingEnabled) { reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; } else { // fall through } case NOFRAMES: case IFRAME: case NOEMBED: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case SELECT: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); switch (mode) { case IN_TABLE: case IN_CAPTION: case IN_COLUMN_GROUP: case IN_TABLE_BODY: case IN_ROW: case IN_CELL: mode = IN_SELECT_IN_TABLE; break; default: mode = IN_SELECT; break; } attributes = null; // CPP break starttagloop; case OPTGROUP: case OPTION: /* * If the stack of open elements has an option * element in scope, then act as if an end tag * with the tag name "option" had been seen. */ if (findLastInScope("option") != TreeBuilder.NOT_FOUND_ON_STACK) { optionendtagloop: for (;;) { if (isCurrent("option")) { pop(); break optionendtagloop; } eltPos = currentPtr; for (;;) { if (stack[eltPos].name == "option") { generateImpliedEndTags(); if (errorHandler != null && !isCurrent("option")) { errNoCheck("End tag \u201C" + name + "\u201D seen but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } break optionendtagloop; } eltPos--; } } } /* * Reconstruct the active formatting elements, * if any. */ reconstructTheActiveFormattingElements(); /* * Insert an HTML element for the token. */ appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case RT_OR_RP: /* * If the stack of open elements has a ruby * element in scope, then generate implied end * tags. If the current node is not then a ruby * element, this is a parse error; pop all the * nodes from the current node up to the node * immediately before the bottommost ruby * element on the stack of open elements. * * Insert an HTML element for the token. */ eltPos = findLastInScope("ruby"); if (eltPos != NOT_FOUND_ON_STACK) { generateImpliedEndTags(); } if (eltPos != currentPtr) { err("Unclosed children in \u201Cruby\u201D."); while (currentPtr > eltPos) { pop(); } } appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case MATH: reconstructTheActiveFormattingElements(); attributes.adjustForMath(); if (selfClosing) { appendVoidElementToCurrentMayFoster( "http://www.w3.org/1998/Math/MathML", elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1998/Math/MathML", elementName, attributes); inForeign = true; } attributes = null; // CPP break starttagloop; case SVG: reconstructTheActiveFormattingElements(); attributes.adjustForSvg(); if (selfClosing) { appendVoidElementToCurrentMayFosterCamelCase( "http://www.w3.org/2000/svg", elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/2000/svg", elementName, attributes); inForeign = true; } attributes = null; // CPP break starttagloop; case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: case FRAME: case FRAMESET: case HEAD: err("Stray start tag \u201C" + name + "\u201D."); break starttagloop; case OUTPUT_OR_LABEL: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); attributes = null; // CPP break starttagloop; default: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; } } case IN_HEAD: inheadloop: for (;;) { switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case BASE: case COMMAND: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case META: case LINK_OR_BASEFONT_OR_BGSOUND: // Fall through to IN_HEAD_NOSCRIPT break inheadloop; case TITLE: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RCDATA, elementName); attributes = null; // CPP break starttagloop; case NOSCRIPT: if (scriptingEnabled) { appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); } else { appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_HEAD_NOSCRIPT; } attributes = null; // CPP break starttagloop; case SCRIPT: // XXX need to manage much more stuff // here if // supporting // document.write() appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; case STYLE: case NOFRAMES: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case HEAD: /* Parse error. */ err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open."); /* Ignore the token. */ break starttagloop; default: pop(); mode = AFTER_HEAD; continue starttagloop; } } case IN_HEAD_NOSCRIPT: switch (group) { case HTML: // XXX did Hixie really mean to omit "base" // here? err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case LINK_OR_BASEFONT_OR_BGSOUND: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case META: checkMetaCharset(attributes); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case STYLE: case NOFRAMES: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case HEAD: err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open."); break starttagloop; case NOSCRIPT: err("Start tag for \u201Cnoscript\u201D seen when \u201Cnoscript\u201D was already open."); break starttagloop; default: err("Bad start tag in \u201C" + name + "\u201D in \u201Chead\u201D."); pop(); mode = IN_HEAD; continue; } case IN_COLUMN_GROUP: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case COL: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; default: if (currentPtr == 0) { assert fragment; err("Garbage in \u201Ccolgroup\u201D fragment."); break starttagloop; } pop(); mode = IN_TABLE; continue; } case IN_SELECT_IN_TABLE: switch (group) { case CAPTION: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: case TABLE: err("\u201C" + name + "\u201D start tag with \u201Cselect\u201D open."); eltPos = findLastInTableScope("select"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; break starttagloop; // http://www.w3.org/Bugs/Public/show_bug.cgi?id=8375 } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); continue; default: // fall through to IN_SELECT } case IN_SELECT: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case OPTION: if (isCurrent("option")) { pop(); } appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case OPTGROUP: if (isCurrent("option")) { pop(); } if (isCurrent("optgroup")) { pop(); } appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case SELECT: err("\u201Cselect\u201D start tag where end tag expected."); eltPos = findLastInTableScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; err("No \u201Cselect\u201D in table scope."); break starttagloop; } else { while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); break starttagloop; } case INPUT: case TEXTAREA: case KEYGEN: err("\u201C" + name + "\u201D start tag seen in \u201Cselect\2201D."); eltPos = findLastInTableScope("select"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; break starttagloop; } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); continue; case SCRIPT: // XXX need to manage much more stuff // here if // supporting // document.write() appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } case AFTER_BODY: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); mode = framesetOk ? FRAMESET_OK : IN_BODY; continue; } case IN_FRAMESET: switch (group) { case FRAMESET: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case FRAME: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; default: // fall through to AFTER_FRAMESET } case AFTER_FRAMESET: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case NOFRAMES: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } case INITIAL: /* * Parse error. */ // [NOCPP[ switch (doctypeExpectation) { case AUTO: err("Start tag seen without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D."); break; case HTML: err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D."); break; case HTML401_STRICT: err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); break; case HTML401_TRANSITIONAL: err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); break; case NO_DOCTYPE_ERRORS: } // ]NOCPP] /* * * Set the document to quirks mode. */ documentModeInternal(DocumentMode.QUIRKS_MODE, null, null, false); /* * Then, switch to the root element mode of the tree * construction stage */ mode = BEFORE_HTML; /* * and reprocess the current token. */ continue; case BEFORE_HTML: switch (group) { case HTML: // optimize error check and streaming SAX by // hoisting // "html" handling here. if (attributes == HtmlAttributes.EMPTY_ATTRIBUTES) { // This has the right magic side effect // that // it // makes attributes in SAX Tree mutable. appendHtmlElementToDocumentAndPush(); } else { appendHtmlElementToDocumentAndPush(attributes); } // XXX application cache should fire here mode = BEFORE_HEAD; attributes = null; // CPP break starttagloop; default: /* * Create an HTMLElement node with the tag name * html, in the HTML namespace. Append it to the * Document object. */ appendHtmlElementToDocumentAndPush(); /* Switch to the main mode */ mode = BEFORE_HEAD; /* * reprocess the current token. */ continue; } case BEFORE_HEAD: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case HEAD: /* * A start tag whose tag name is "head" * * Create an element for the token. * * Set the head element pointer to this new element * node. * * Append the new element to the current node and * push it onto the stack of open elements. */ appendToCurrentNodeAndPushHeadElement(attributes); /* * Change the insertion mode to "in head". */ mode = IN_HEAD; attributes = null; // CPP break starttagloop; default: /* * Any other start tag token * * Act as if a start tag token with the tag name * "head" and no attributes had been seen, */ appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_HEAD; /* * then reprocess the current token. * * This will result in an empty head element being * generated, with the current token being * reprocessed in the "after head" insertion mode. */ continue; } case AFTER_HEAD: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case BODY: if (attributes.getLength() == 0) { // This has the right magic side effect // that // it // makes attributes in SAX Tree mutable. appendToCurrentNodeAndPushBodyElement(); } else { appendToCurrentNodeAndPushBodyElement(attributes); } framesetOk = false; mode = IN_BODY; attributes = null; // CPP break starttagloop; case FRAMESET: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_FRAMESET; attributes = null; // CPP break starttagloop; case BASE: err("\u201Cbase\u201D element outside \u201Chead\u201D."); pushHeadPointerOntoStack(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; pop(); // head attributes = null; // CPP break starttagloop; case LINK_OR_BASEFONT_OR_BGSOUND: err("\u201Clink\u201D element outside \u201Chead\u201D."); pushHeadPointerOntoStack(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; pop(); // head attributes = null; // CPP break starttagloop; case META: err("\u201Cmeta\u201D element outside \u201Chead\u201D."); checkMetaCharset(attributes); pushHeadPointerOntoStack(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; pop(); // head attributes = null; // CPP break starttagloop; case SCRIPT: err("\u201Cscript\u201D element between \u201Chead\u201D and \u201Cbody\u201D."); pushHeadPointerOntoStack(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; case STYLE: case NOFRAMES: err("\u201C" + name + "\u201D element between \u201Chead\u201D and \u201Cbody\u201D."); pushHeadPointerOntoStack(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case TITLE: err("\u201Ctitle\u201D element outside \u201Chead\u201D."); pushHeadPointerOntoStack(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RCDATA, elementName); attributes = null; // CPP break starttagloop; case HEAD: err("Stray start tag \u201Chead\u201D."); break starttagloop; default: appendToCurrentNodeAndPushBodyElement(); mode = FRAMESET_OK; continue; } case AFTER_AFTER_BODY: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); fatal(); mode = framesetOk ? FRAMESET_OK : IN_BODY; continue; } case AFTER_AFTER_FRAMESET: switch (group) { + case HTML: + err("Stray \u201Chtml\u201D start tag."); + if (!fragment) { + addAttributesToHtml(attributes); + attributes = null; // CPP + } + break starttagloop; case NOFRAMES: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } case TEXT: assert false; break starttagloop; // Avoid infinite loop if the assertion // fails } } if (needsPostProcessing && inForeign && !hasForeignInScope()) { /* * If, after doing so, the insertion mode is still "in foreign * content", but there is no element in scope that has a namespace * other than the HTML namespace, switch the insertion mode to the * secondary insertion mode. */ inForeign = false; } if (errorHandler != null && selfClosing) { errNoCheck("Self-closing syntax (\u201C/>\u201D) used on a non-void HTML element. Ignoring the slash and treating as a start tag."); } if (attributes != HtmlAttributes.EMPTY_ATTRIBUTES) { Portability.delete(attributes); } } private boolean isSpecialParentInForeign(StackNode<T> stackNode) { @NsUri String ns = stackNode.ns; if ("http://www.w3.org/1999/xhtml" == ns) { return true; } if (ns == "http://www.w3.org/2000/svg") { return stackNode.group == FOREIGNOBJECT_OR_DESC || stackNode.group == TITLE; } assert ns == "http://www.w3.org/1998/Math/MathML" : "Unexpected namespace."; return stackNode.group == MI_MO_MN_MS_MTEXT; } /** * * <p> * C++ memory note: The return value must be released. * * @return * @throws SAXException * @throws StopSniffingException */ public static String extractCharsetFromContent(String attributeValue) { // This is a bit ugly. Converting the string to char array in order to // make the portability layer smaller. int charsetState = CHARSET_INITIAL; int start = -1; int end = -1; char[] buffer = Portability.newCharArrayFromString(attributeValue); charsetloop: for (int i = 0; i < buffer.length; i++) { char c = buffer[i]; switch (charsetState) { case CHARSET_INITIAL: switch (c) { case 'c': case 'C': charsetState = CHARSET_C; continue; default: continue; } case CHARSET_C: switch (c) { case 'h': case 'H': charsetState = CHARSET_H; continue; default: charsetState = CHARSET_INITIAL; continue; } case CHARSET_H: switch (c) { case 'a': case 'A': charsetState = CHARSET_A; continue; default: charsetState = CHARSET_INITIAL; continue; } case CHARSET_A: switch (c) { case 'r': case 'R': charsetState = CHARSET_R; continue; default: charsetState = CHARSET_INITIAL; continue; } case CHARSET_R: switch (c) { case 's': case 'S': charsetState = CHARSET_S; continue; default: charsetState = CHARSET_INITIAL; continue; } case CHARSET_S: switch (c) { case 'e': case 'E': charsetState = CHARSET_E; continue; default: charsetState = CHARSET_INITIAL; continue; } case CHARSET_E: switch (c) { case 't': case 'T': charsetState = CHARSET_T; continue; default: charsetState = CHARSET_INITIAL; continue; } case CHARSET_T: switch (c) { case '\t': case '\n': case '\u000C': case '\r': case ' ': continue; case '=': charsetState = CHARSET_EQUALS; continue; default: return null; } case CHARSET_EQUALS: switch (c) { case '\t': case '\n': case '\u000C': case '\r': case ' ': continue; case '\'': start = i + 1; charsetState = CHARSET_SINGLE_QUOTED; continue; case '\"': start = i + 1; charsetState = CHARSET_DOUBLE_QUOTED; continue; default: start = i; charsetState = CHARSET_UNQUOTED; continue; } case CHARSET_SINGLE_QUOTED: switch (c) { case '\'': end = i; break charsetloop; default: continue; } case CHARSET_DOUBLE_QUOTED: switch (c) { case '\"': end = i; break charsetloop; default: continue; } case CHARSET_UNQUOTED: switch (c) { case '\t': case '\n': case '\u000C': case '\r': case ' ': case ';': end = i; break charsetloop; default: continue; } } } String charset = null; if (start != -1) { if (end == -1) { end = buffer.length; } charset = Portability.newStringFromBuffer(buffer, start, end - start); } Portability.releaseArray(buffer); return charset; } private void checkMetaCharset(HtmlAttributes attributes) throws SAXException { String content = attributes.getValue(AttributeName.CONTENT); String internalCharsetLegacy = null; if (content != null) { internalCharsetLegacy = TreeBuilder.extractCharsetFromContent(content); // [NOCPP[ if (errorHandler != null && internalCharsetLegacy != null && !Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "content-type", attributes.getValue(AttributeName.HTTP_EQUIV))) { warn("Attribute \u201Ccontent\u201D would be sniffed as an internal character encoding declaration but there was no matching \u201Chttp-equiv='Content-Type'\u201D attribute."); } // ]NOCPP] } if (internalCharsetLegacy == null) { String internalCharsetHtml5 = attributes.getValue(AttributeName.CHARSET); if (internalCharsetHtml5 != null) { tokenizer.internalEncodingDeclaration(internalCharsetHtml5); requestSuspension(); } } else { tokenizer.internalEncodingDeclaration(internalCharsetLegacy); Portability.releaseString(internalCharsetLegacy); requestSuspension(); } } public final void endTag(ElementName elementName) throws SAXException { flushCharacters(); needToDropLF = false; int eltPos; int group = elementName.group; @Local String name = elementName.name; endtagloop: for (;;) { assert !inForeign || currentPtr >= 0 : "In foreign without a root element?"; if (inForeign && stack[currentPtr].ns != "http://www.w3.org/1999/xhtml") { if (errorHandler != null && stack[currentPtr].name != name) { errNoCheck("End tag \u201C" + name + "\u201D did not match the name of the current open element (\u201C" + stack[currentPtr].popName + "\u201D)."); } eltPos = currentPtr; for (;;) { if (stack[eltPos].name == name) { while (currentPtr >= eltPos) { pop(); } break endtagloop; } if (stack[--eltPos].ns == "http://www.w3.org/1999/xhtml") { break; } } } switch (mode) { case IN_ROW: switch (group) { case TR: eltPos = findLastOrRoot(TreeBuilder.TR); if (eltPos == 0) { assert fragment; err("No table row to close."); break endtagloop; } clearStackBackTo(eltPos); pop(); mode = IN_TABLE_BODY; break endtagloop; case TABLE: eltPos = findLastOrRoot(TreeBuilder.TR); if (eltPos == 0) { assert fragment; err("No table row to close."); break endtagloop; } clearStackBackTo(eltPos); pop(); mode = IN_TABLE_BODY; continue; case TBODY_OR_THEAD_OR_TFOOT: if (findLastInTableScope(name) == TreeBuilder.NOT_FOUND_ON_STACK) { err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } eltPos = findLastOrRoot(TreeBuilder.TR); if (eltPos == 0) { assert fragment; err("No table row to close."); break endtagloop; } clearStackBackTo(eltPos); pop(); mode = IN_TABLE_BODY; continue; case BODY: case CAPTION: case COL: case COLGROUP: case HTML: case TD_OR_TH: err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; default: // fall through to IN_TABLE } case IN_TABLE_BODY: switch (group) { case TBODY_OR_THEAD_OR_TFOOT: eltPos = findLastOrRoot(name); if (eltPos == 0) { err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } clearStackBackTo(eltPos); pop(); mode = IN_TABLE; break endtagloop; case TABLE: eltPos = findLastInTableScopeOrRootTbodyTheadTfoot(); if (eltPos == 0) { assert fragment; err("Stray end tag \u201Ctable\u201D."); break endtagloop; } clearStackBackTo(eltPos); pop(); mode = IN_TABLE; continue; case BODY: case CAPTION: case COL: case COLGROUP: case HTML: case TD_OR_TH: case TR: err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; default: // fall through to IN_TABLE } case IN_TABLE: switch (group) { case TABLE: eltPos = findLast("table"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; err("Stray end tag \u201Ctable\u201D."); break endtagloop; } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); break endtagloop; case BODY: case CAPTION: case COL: case COLGROUP: case HTML: case TBODY_OR_THEAD_OR_TFOOT: case TD_OR_TH: case TR: err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; default: err("Stray end tag \u201C" + name + "\u201D."); // fall through to IN_BODY } case IN_CAPTION: switch (group) { case CAPTION: eltPos = findLastInTableScope("caption"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { break endtagloop; } generateImpliedEndTags(); if (errorHandler != null && currentPtr != eltPos) { errNoCheck("Unclosed elements on stack."); } while (currentPtr >= eltPos) { pop(); } clearTheListOfActiveFormattingElementsUpToTheLastMarker(); mode = IN_TABLE; break endtagloop; case TABLE: err("\u201Ctable\u201D closed but \u201Ccaption\u201D was still open."); eltPos = findLastInTableScope("caption"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { break endtagloop; } generateImpliedEndTags(); if (errorHandler != null && currentPtr != eltPos) { errNoCheck("Unclosed elements on stack."); } while (currentPtr >= eltPos) { pop(); } clearTheListOfActiveFormattingElementsUpToTheLastMarker(); mode = IN_TABLE; continue; case BODY: case COL: case COLGROUP: case HTML: case TBODY_OR_THEAD_OR_TFOOT: case TD_OR_TH: case TR: err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; default: // fall through to IN_BODY } case IN_CELL: switch (group) { case TD_OR_TH: eltPos = findLastInTableScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } generateImpliedEndTags(); if (errorHandler != null && !isCurrent(name)) { errNoCheck("Unclosed elements."); } while (currentPtr >= eltPos) { pop(); } clearTheListOfActiveFormattingElementsUpToTheLastMarker(); mode = IN_ROW; break endtagloop; case TABLE: case TBODY_OR_THEAD_OR_TFOOT: case TR: if (findLastInTableScope(name) == TreeBuilder.NOT_FOUND_ON_STACK) { err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } closeTheCell(findLastInTableScopeTdTh()); continue; case BODY: case CAPTION: case COL: case COLGROUP: case HTML: err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; default: // fall through to IN_BODY } case FRAMESET_OK: case IN_BODY: switch (group) { case BODY: if (!isSecondOnStackBody()) { assert fragment; err("Stray end tag \u201Cbody\u201D."); break endtagloop; } assert currentPtr >= 1; if (errorHandler != null) { uncloseloop1: for (int i = 2; i <= currentPtr; i++) { switch (stack[i].group) { case DD_OR_DT: case LI: case OPTGROUP: case OPTION: // is this possible? case P: case RT_OR_RP: case TD_OR_TH: case TBODY_OR_THEAD_OR_TFOOT: break; default: err("End tag for \u201Cbody\u201D seen but there were unclosed elements."); break uncloseloop1; } } } mode = AFTER_BODY; break endtagloop; case HTML: if (!isSecondOnStackBody()) { assert fragment; err("Stray end tag \u201Chtml\u201D."); break endtagloop; } if (errorHandler != null) { uncloseloop2: for (int i = 0; i <= currentPtr; i++) { switch (stack[i].group) { case DD_OR_DT: case LI: case P: case TBODY_OR_THEAD_OR_TFOOT: case TD_OR_TH: case BODY: case HTML: break; default: err("End tag for \u201Chtml\u201D seen but there were unclosed elements."); break uncloseloop2; } } } mode = AFTER_BODY; continue; case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU: case UL_OR_OL_OR_DL: case PRE_OR_LISTING: case FIELDSET: case BUTTON: case ADDRESS_OR_DIR_OR_ARTICLE_OR_ASIDE_OR_DATAGRID_OR_DETAILS_OR_HGROUP_OR_FIGURE_OR_FOOTER_OR_HEADER_OR_NAV_OR_SECTION: eltPos = findLastInScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("Stray end tag \u201C" + name + "\u201D."); } else { generateImpliedEndTags(); if (errorHandler != null && !isCurrent(name)) { errNoCheck("End tag \u201C" + name + "\u201D seen but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } } break endtagloop; case FORM: if (formPointer == null) { err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } Portability.releaseElement(formPointer); formPointer = null; eltPos = findLastInScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } generateImpliedEndTags(); if (errorHandler != null && !isCurrent(name)) { errNoCheck("End tag \u201C" + name + "\u201D seen but there were unclosed elements."); } removeFromStack(eltPos); break endtagloop; case P: eltPos = findLastInButtonScope("p"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("No \u201Cp\u201D element in scope but a \u201Cp\u201D end tag seen."); // XXX inline this case if (inForeign) { err("HTML start tag \u201C" + name + "\u201D in a foreign namespace context."); while (stack[currentPtr].ns != "http://www.w3.org/1999/xhtml") { pop(); } inForeign = false; } appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, HtmlAttributes.EMPTY_ATTRIBUTES); break endtagloop; } generateImpliedEndTagsExceptFor("p"); assert eltPos != TreeBuilder.NOT_FOUND_ON_STACK; if (errorHandler != null && eltPos != currentPtr) { errNoCheck("End tag for \u201Cp\u201D seen, but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } break endtagloop; case LI: eltPos = findLastInListScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("No \u201Cli\u201D element in list scope but a \u201Cli\u201D end tag seen."); } else { generateImpliedEndTagsExceptFor(name); if (errorHandler != null && eltPos != currentPtr) { errNoCheck("End tag for \u201Cli\u201D seen, but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } } break endtagloop; case DD_OR_DT: eltPos = findLastInScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("No \u201C" + name + "\u201D element in scope but a \u201C" + name + "\u201D end tag seen."); } else { generateImpliedEndTagsExceptFor(name); if (errorHandler != null && eltPos != currentPtr) { errNoCheck("End tag for \u201C" + name + "\u201D seen, but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } } break endtagloop; case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6: eltPos = findLastInScopeHn(); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("Stray end tag \u201C" + name + "\u201D."); } else { generateImpliedEndTags(); if (errorHandler != null && !isCurrent(name)) { errNoCheck("End tag \u201C" + name + "\u201D seen but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } } break endtagloop; case A: case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U: case FONT: case NOBR: adoptionAgencyEndTag(name); break endtagloop; case OBJECT: case MARQUEE_OR_APPLET: eltPos = findLastInScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("Stray end tag \u201C" + name + "\u201D."); } else { generateImpliedEndTags(); if (errorHandler != null && !isCurrent(name)) { errNoCheck("End tag \u201C" + name + "\u201D seen but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } clearTheListOfActiveFormattingElementsUpToTheLastMarker(); } break endtagloop; case BR: err("End tag \u201Cbr\u201D."); if (inForeign) { err("HTML start tag \u201C" + name + "\u201D in a foreign namespace context."); while (stack[currentPtr].ns != "http://www.w3.org/1999/xhtml") { pop(); } inForeign = false; } reconstructTheActiveFormattingElements(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, HtmlAttributes.EMPTY_ATTRIBUTES); break endtagloop; case AREA_OR_WBR: case PARAM_OR_SOURCE: case EMBED_OR_IMG: case IMAGE: case INPUT: case KEYGEN: // XXX?? case HR: case ISINDEX: case IFRAME: case NOEMBED: // XXX??? case NOFRAMES: // XXX?? case SELECT: case TABLE: case TEXTAREA: // XXX?? err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; case NOSCRIPT: if (scriptingEnabled) { err("Stray end tag \u201Cnoscript\u201D."); break endtagloop; } else { // fall through } default: if (isCurrent(name)) { pop(); break endtagloop; } eltPos = currentPtr; for (;;) { StackNode<T> node = stack[eltPos]; if (node.name == name) { generateImpliedEndTags(); if (errorHandler != null && !isCurrent(name)) { errNoCheck("End tag \u201C" + name + "\u201D seen but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } break endtagloop; } else if (node.scoping || node.special) { err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } eltPos--; } } case IN_COLUMN_GROUP: switch (group) { case COLGROUP: if (currentPtr == 0) { assert fragment; err("Garbage in \u201Ccolgroup\u201D fragment."); break endtagloop; } pop(); mode = IN_TABLE; break endtagloop; case COL: err("Stray end tag \u201Ccol\u201D."); break endtagloop; default: if (currentPtr == 0) { assert fragment; err("Garbage in \u201Ccolgroup\u201D fragment."); break endtagloop; } pop(); mode = IN_TABLE; continue; } case IN_SELECT_IN_TABLE: switch (group) { case CAPTION: case TABLE: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: err("\u201C" + name + "\u201D end tag with \u201Cselect\u201D open."); if (findLastInTableScope(name) != TreeBuilder.NOT_FOUND_ON_STACK) { eltPos = findLastInTableScope("select"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; break endtagloop; // http://www.w3.org/Bugs/Public/show_bug.cgi?id=8375 } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); continue; } else { break endtagloop; } default: // fall through to IN_SELECT } case IN_SELECT: switch (group) { case OPTION: if (isCurrent("option")) { pop(); break endtagloop; } else { err("Stray end tag \u201Coption\u201D"); break endtagloop; } case OPTGROUP: if (isCurrent("option") && "optgroup" == stack[currentPtr - 1].name) { pop(); } if (isCurrent("optgroup")) { pop(); } else { err("Stray end tag \u201Coptgroup\u201D"); } break endtagloop; case SELECT: eltPos = findLastInTableScope("select"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; err("Stray end tag \u201Cselect\u201D"); break endtagloop; } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); break endtagloop; default: err("Stray end tag \u201C" + name + "\u201D"); break endtagloop; } case AFTER_BODY: switch (group) { case HTML: if (fragment) { err("Stray end tag \u201Chtml\u201D"); break endtagloop; } else { mode = AFTER_AFTER_BODY; break endtagloop; } default: err("Saw an end tag after \u201Cbody\u201D had been closed."); mode = framesetOk ? FRAMESET_OK : IN_BODY; continue; } case IN_FRAMESET: switch (group) { case FRAMESET: if (currentPtr == 0) { assert fragment; err("Stray end tag \u201Cframeset\u201D"); break endtagloop; } pop(); if ((!fragment) && !isCurrent("frameset")) { mode = AFTER_FRAMESET; } break endtagloop; default: err("Stray end tag \u201C" + name + "\u201D"); break endtagloop; } case AFTER_FRAMESET: switch (group) { case HTML: mode = AFTER_AFTER_FRAMESET; break endtagloop; default: err("Stray end tag \u201C" + name + "\u201D"); break endtagloop; } case INITIAL: /* * Parse error. */ // [NOCPP[ switch (doctypeExpectation) { case AUTO: err("End tag seen without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D."); break; case HTML: err("End tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D."); break; case HTML401_STRICT: err("End tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); break; case HTML401_TRANSITIONAL: err("End tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); break; case NO_DOCTYPE_ERRORS: } // ]NOCPP] /* * * Set the document to quirks mode. */ documentModeInternal(DocumentMode.QUIRKS_MODE, null, null, false); /* * Then, switch to the root element mode of the tree * construction stage */ mode = BEFORE_HTML; /* * and reprocess the current token. */ continue; case BEFORE_HTML: switch (group) { case HEAD: case BR: case HTML: case BODY: /* * Create an HTMLElement node with the tag name * html, in the HTML namespace. Append it to the * Document object. */ appendHtmlElementToDocumentAndPush(); /* Switch to the main mode */ mode = BEFORE_HEAD; /* * reprocess the current token. */ continue; default: err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } case BEFORE_HEAD: switch (group) { case HEAD: case BR: case HTML: case BODY: appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_HEAD; continue; default: err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } case IN_HEAD: switch (group) { case HEAD: pop(); mode = AFTER_HEAD; break endtagloop; case BR: case HTML: case BODY: pop(); mode = AFTER_HEAD; continue; default: err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } case IN_HEAD_NOSCRIPT: switch (group) { case NOSCRIPT: pop(); mode = IN_HEAD; break endtagloop; case BR: err("Stray end tag \u201C" + name + "\u201D."); pop(); mode = IN_HEAD; continue; default: err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } case AFTER_HEAD: switch (group) { case HTML: case BODY: case BR: appendToCurrentNodeAndPushBodyElement(); mode = FRAMESET_OK; continue; default: err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } case AFTER_AFTER_BODY: err("Stray \u201C" + name + "\u201D end tag."); mode = framesetOk ? FRAMESET_OK : IN_BODY; continue; case AFTER_AFTER_FRAMESET: err("Stray \u201C" + name + "\u201D end tag."); mode = IN_FRAMESET; continue; case TEXT: // XXX need to manage insertion point here pop(); if (originalMode == AFTER_HEAD) { silentPop(); } mode = originalMode; break endtagloop; } } // endtagloop if (inForeign && !hasForeignInScope()) { /* * If, after doing so, the insertion mode is still "in foreign * content", but there is no element in scope that has a namespace * other than the HTML namespace, switch the insertion mode to the * secondary insertion mode. */ inForeign = false; } } private int findLastInTableScopeOrRootTbodyTheadTfoot() { for (int i = currentPtr; i > 0; i--) { if (stack[i].group == TreeBuilder.TBODY_OR_THEAD_OR_TFOOT) { return i; } } return 0; } private int findLast(@Local String name) { for (int i = currentPtr; i > 0; i--) { if (stack[i].name == name) { return i; } } return TreeBuilder.NOT_FOUND_ON_STACK; } private int findLastInTableScope(@Local String name) { for (int i = currentPtr; i > 0; i--) { if (stack[i].name == name) { return i; } else if (stack[i].name == "table") { return TreeBuilder.NOT_FOUND_ON_STACK; } } return TreeBuilder.NOT_FOUND_ON_STACK; } private int findLastInButtonScope(@Local String name) { for (int i = currentPtr; i > 0; i--) { if (stack[i].name == name) { return i; } else if (stack[i].scoping || stack[i].name == "button") { return TreeBuilder.NOT_FOUND_ON_STACK; } } return TreeBuilder.NOT_FOUND_ON_STACK; } private int findLastInScope(@Local String name) { for (int i = currentPtr; i > 0; i--) { if (stack[i].name == name) { return i; } else if (stack[i].scoping) { return TreeBuilder.NOT_FOUND_ON_STACK; } } return TreeBuilder.NOT_FOUND_ON_STACK; } private int findLastInListScope(@Local String name) { for (int i = currentPtr; i > 0; i--) { if (stack[i].name == name) { return i; } else if (stack[i].scoping || stack[i].name == "ul" || stack[i].name == "ol") { return TreeBuilder.NOT_FOUND_ON_STACK; } } return TreeBuilder.NOT_FOUND_ON_STACK; } private int findLastInScopeHn() { for (int i = currentPtr; i > 0; i--) { if (stack[i].group == TreeBuilder.H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6) { return i; } else if (stack[i].scoping) { return TreeBuilder.NOT_FOUND_ON_STACK; } } return TreeBuilder.NOT_FOUND_ON_STACK; } private boolean hasForeignInScope() { for (int i = currentPtr; i > 0; i--) { if (stack[i].ns != "http://www.w3.org/1999/xhtml") { return true; } else if (stack[i].scoping) { return false; } } return false; } private void generateImpliedEndTagsExceptFor(@Local String name) throws SAXException { for (;;) { StackNode<T> node = stack[currentPtr]; switch (node.group) { case P: case LI: case DD_OR_DT: case OPTION: case OPTGROUP: case RT_OR_RP: if (node.name == name) { return; } pop(); continue; default: return; } } } private void generateImpliedEndTags() throws SAXException { for (;;) { switch (stack[currentPtr].group) { case P: case LI: case DD_OR_DT: case OPTION: case OPTGROUP: case RT_OR_RP: pop(); continue; default: return; } } } private boolean isSecondOnStackBody() { return currentPtr >= 1 && stack[1].group == TreeBuilder.BODY; } private void documentModeInternal(DocumentMode m, String publicIdentifier, String systemIdentifier, boolean html4SpecificAdditionalErrorChecks) throws SAXException { quirks = (m == DocumentMode.QUIRKS_MODE); if (documentModeHandler != null) { documentModeHandler.documentMode( m // [NOCPP[ , publicIdentifier, systemIdentifier, html4SpecificAdditionalErrorChecks // ]NOCPP] ); } // [NOCPP[ documentMode(m, publicIdentifier, systemIdentifier, html4SpecificAdditionalErrorChecks); // ]NOCPP] } private boolean isAlmostStandards(String publicIdentifier, String systemIdentifier) { if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "-//w3c//dtd xhtml 1.0 transitional//en", publicIdentifier)) { return true; } if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "-//w3c//dtd xhtml 1.0 frameset//en", publicIdentifier)) { return true; } if (systemIdentifier != null) { if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "-//w3c//dtd html 4.01 transitional//en", publicIdentifier)) { return true; } if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "-//w3c//dtd html 4.01 frameset//en", publicIdentifier)) { return true; } } return false; } private boolean isQuirky(@Local String name, String publicIdentifier, String systemIdentifier, boolean forceQuirks) { if (forceQuirks) { return true; } if (name != HTML_LOCAL) { return true; } if (publicIdentifier != null) { for (int i = 0; i < TreeBuilder.QUIRKY_PUBLIC_IDS.length; i++) { if (Portability.lowerCaseLiteralIsPrefixOfIgnoreAsciiCaseString( TreeBuilder.QUIRKY_PUBLIC_IDS[i], publicIdentifier)) { return true; } } if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "-//w3o//dtd w3 html strict 3.0//en//", publicIdentifier) || Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "-/w3c/dtd html 4.0 transitional/en", publicIdentifier) || Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "html", publicIdentifier)) { return true; } } if (systemIdentifier == null) { if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "-//w3c//dtd html 4.01 transitional//en", publicIdentifier)) { return true; } else if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "-//w3c//dtd html 4.01 frameset//en", publicIdentifier)) { return true; } } else if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd", systemIdentifier)) { return true; } return false; } private void closeTheCell(int eltPos) throws SAXException { generateImpliedEndTags(); if (errorHandler != null && eltPos != currentPtr) { errNoCheck("Unclosed elements."); } while (currentPtr >= eltPos) { pop(); } clearTheListOfActiveFormattingElementsUpToTheLastMarker(); mode = IN_ROW; return; } private int findLastInTableScopeTdTh() { for (int i = currentPtr; i > 0; i--) { @Local String name = stack[i].name; if ("td" == name || "th" == name) { return i; } else if (name == "table") { return TreeBuilder.NOT_FOUND_ON_STACK; } } return TreeBuilder.NOT_FOUND_ON_STACK; } private void clearStackBackTo(int eltPos) throws SAXException { while (currentPtr > eltPos) { // > not >= intentional pop(); } } private void resetTheInsertionMode() { inForeign = false; StackNode<T> node; @Local String name; @NsUri String ns; for (int i = currentPtr; i >= 0; i--) { node = stack[i]; name = node.name; ns = node.ns; if (i == 0) { if (!(contextNamespace == "http://www.w3.org/1999/xhtml" && (contextName == "td" || contextName == "th"))) { name = contextName; ns = contextNamespace; } else { mode = framesetOk ? FRAMESET_OK : IN_BODY; // XXX from Hixie's email return; } } if ("select" == name) { mode = IN_SELECT; return; } else if ("td" == name || "th" == name) { mode = IN_CELL; return; } else if ("tr" == name) { mode = IN_ROW; return; } else if ("tbody" == name || "thead" == name || "tfoot" == name) { mode = IN_TABLE_BODY; return; } else if ("caption" == name) { mode = IN_CAPTION; return; } else if ("colgroup" == name) { mode = IN_COLUMN_GROUP; return; } else if ("table" == name) { mode = IN_TABLE; return; } else if ("http://www.w3.org/1999/xhtml" != ns) { inForeign = true; mode = framesetOk ? FRAMESET_OK : IN_BODY; return; } else if ("head" == name) { mode = framesetOk ? FRAMESET_OK : IN_BODY; // really return; } else if ("body" == name) { mode = framesetOk ? FRAMESET_OK : IN_BODY; return; } else if ("frameset" == name) { mode = IN_FRAMESET; return; } else if ("html" == name) { if (headPointer == null) { mode = BEFORE_HEAD; } else { mode = AFTER_HEAD; } return; } else if (i == 0) { mode = framesetOk ? FRAMESET_OK : IN_BODY; return; } } } /** * @throws SAXException * */ private void implicitlyCloseP() throws SAXException { int eltPos = findLastInButtonScope("p"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { return; } generateImpliedEndTagsExceptFor("p"); if (errorHandler != null && eltPos != currentPtr) { err("Unclosed elements."); } while (currentPtr >= eltPos) { pop(); } } private boolean clearLastStackSlot() { stack[currentPtr] = null; return true; } private boolean clearLastListSlot() { listOfActiveFormattingElements[listPtr] = null; return true; } @SuppressWarnings("unchecked") private void push(StackNode<T> node) throws SAXException { currentPtr++; if (currentPtr == stack.length) { StackNode<T>[] newStack = new StackNode[stack.length + 64]; System.arraycopy(stack, 0, newStack, 0, stack.length); Portability.releaseArray(stack); stack = newStack; } stack[currentPtr] = node; elementPushed(node.ns, node.popName, node.node); } @SuppressWarnings("unchecked") private void silentPush(StackNode<T> node) throws SAXException { currentPtr++; if (currentPtr == stack.length) { StackNode<T>[] newStack = new StackNode[stack.length + 64]; System.arraycopy(stack, 0, newStack, 0, stack.length); Portability.releaseArray(stack); stack = newStack; } stack[currentPtr] = node; } @SuppressWarnings("unchecked") private void append(StackNode<T> node) { listPtr++; if (listPtr == listOfActiveFormattingElements.length) { StackNode<T>[] newList = new StackNode[listOfActiveFormattingElements.length + 64]; System.arraycopy(listOfActiveFormattingElements, 0, newList, 0, listOfActiveFormattingElements.length); Portability.releaseArray(listOfActiveFormattingElements); listOfActiveFormattingElements = newList; } listOfActiveFormattingElements[listPtr] = node; } @Inline private void insertMarker() { append(null); } private void clearTheListOfActiveFormattingElementsUpToTheLastMarker() { while (listPtr > -1) { if (listOfActiveFormattingElements[listPtr] == null) { --listPtr; return; } listOfActiveFormattingElements[listPtr].release(); --listPtr; } } @Inline private boolean isCurrent(@Local String name) { return name == stack[currentPtr].name; } private void removeFromStack(int pos) throws SAXException { if (currentPtr == pos) { pop(); } else { fatal(); stack[pos].release(); System.arraycopy(stack, pos + 1, stack, pos, currentPtr - pos); assert clearLastStackSlot(); currentPtr--; } } private void removeFromStack(StackNode<T> node) throws SAXException { if (stack[currentPtr] == node) { pop(); } else { int pos = currentPtr - 1; while (pos >= 0 && stack[pos] != node) { pos--; } if (pos == -1) { // dead code? return; } fatal(); node.release(); System.arraycopy(stack, pos + 1, stack, pos, currentPtr - pos); currentPtr--; } } private void removeFromListOfActiveFormattingElements(int pos) { assert listOfActiveFormattingElements[pos] != null; listOfActiveFormattingElements[pos].release(); if (pos == listPtr) { assert clearLastListSlot(); listPtr--; return; } assert pos < listPtr; System.arraycopy(listOfActiveFormattingElements, pos + 1, listOfActiveFormattingElements, pos, listPtr - pos); assert clearLastListSlot(); listPtr--; } private void adoptionAgencyEndTag(@Local String name) throws SAXException { // If you crash around here, perhaps some stack node variable claimed to // be a weak ref isn't. for (;;) { int formattingEltListPos = listPtr; while (formattingEltListPos > -1) { StackNode<T> listNode = listOfActiveFormattingElements[formattingEltListPos]; // weak // ref if (listNode == null) { formattingEltListPos = -1; break; } else if (listNode.name == name) { break; } formattingEltListPos--; } if (formattingEltListPos == -1) { err("No element \u201C" + name + "\u201D to close."); return; } StackNode<T> formattingElt = listOfActiveFormattingElements[formattingEltListPos]; // this // *looks* // like // a // weak // ref // to // the // list // of // formatting // elements int formattingEltStackPos = currentPtr; boolean inScope = true; while (formattingEltStackPos > -1) { StackNode<T> node = stack[formattingEltStackPos]; // weak ref if (node == formattingElt) { break; } else if (node.scoping) { inScope = false; } formattingEltStackPos--; } if (formattingEltStackPos == -1) { err("No element \u201C" + name + "\u201D to close."); removeFromListOfActiveFormattingElements(formattingEltListPos); return; } if (!inScope) { err("No element \u201C" + name + "\u201D to close."); return; } // stackPos now points to the formatting element and it is in scope if (errorHandler != null && formattingEltStackPos != currentPtr) { errNoCheck("End tag \u201C" + name + "\u201D violates nesting rules."); } int furthestBlockPos = formattingEltStackPos + 1; while (furthestBlockPos <= currentPtr) { StackNode<T> node = stack[furthestBlockPos]; // weak ref if (node.scoping || node.special) { break; } furthestBlockPos++; } if (furthestBlockPos > currentPtr) { // no furthest block while (currentPtr >= formattingEltStackPos) { pop(); } removeFromListOfActiveFormattingElements(formattingEltListPos); return; } StackNode<T> commonAncestor = stack[formattingEltStackPos - 1]; // weak // ref StackNode<T> furthestBlock = stack[furthestBlockPos]; // weak ref // detachFromParent(furthestBlock.node); XXX AAA CHANGE int bookmark = formattingEltListPos; int nodePos = furthestBlockPos; StackNode<T> lastNode = furthestBlock; // weak ref for (;;) { nodePos--; StackNode<T> node = stack[nodePos]; // weak ref int nodeListPos = findInListOfActiveFormattingElements(node); if (nodeListPos == -1) { assert formattingEltStackPos < nodePos; assert bookmark < nodePos; assert furthestBlockPos > nodePos; removeFromStack(nodePos); // node is now a bad pointer in // C++ furthestBlockPos--; continue; } // now node is both on stack and in the list if (nodePos == formattingEltStackPos) { break; } if (nodePos == furthestBlockPos) { bookmark = nodeListPos + 1; } // if (hasChildren(node.node)) { XXX AAA CHANGE assert node == listOfActiveFormattingElements[nodeListPos]; assert node == stack[nodePos]; T clone = createElement("http://www.w3.org/1999/xhtml", node.name, node.attributes.cloneAttributes(null)); StackNode<T> newNode = new StackNode<T>(node.group, node.ns, node.name, clone, node.scoping, node.special, node.fosterParenting, node.popName, node.attributes); // creation // ownership // goes // to // stack node.dropAttributes(); // adopt ownership to newNode stack[nodePos] = newNode; newNode.retain(); // retain for list listOfActiveFormattingElements[nodeListPos] = newNode; node.release(); // release from stack node.release(); // release from list node = newNode; Portability.releaseElement(clone); // } XXX AAA CHANGE detachFromParent(lastNode.node); appendElement(lastNode.node, node.node); lastNode = node; } if (commonAncestor.fosterParenting) { fatal(); detachFromParent(lastNode.node); insertIntoFosterParent(lastNode.node); } else { detachFromParent(lastNode.node); appendElement(lastNode.node, commonAncestor.node); } T clone = createElement("http://www.w3.org/1999/xhtml", formattingElt.name, formattingElt.attributes.cloneAttributes(null)); StackNode<T> formattingClone = new StackNode<T>( formattingElt.group, formattingElt.ns, formattingElt.name, clone, formattingElt.scoping, formattingElt.special, formattingElt.fosterParenting, formattingElt.popName, formattingElt.attributes); // Ownership // transfers // to // stack // below formattingElt.dropAttributes(); // transfer ownership to // formattingClone appendChildrenToNewParent(furthestBlock.node, clone); appendElement(clone, furthestBlock.node); removeFromListOfActiveFormattingElements(formattingEltListPos); insertIntoListOfActiveFormattingElements(formattingClone, bookmark); assert formattingEltStackPos < furthestBlockPos; removeFromStack(formattingEltStackPos); // furthestBlockPos is now off by one and points to the slot after // it insertIntoStack(formattingClone, furthestBlockPos); Portability.releaseElement(clone); } } private void insertIntoStack(StackNode<T> node, int position) throws SAXException { assert currentPtr + 1 < stack.length; assert position <= currentPtr + 1; if (position == currentPtr + 1) { push(node); } else { System.arraycopy(stack, position, stack, position + 1, (currentPtr - position) + 1); currentPtr++; stack[position] = node; } } private void insertIntoListOfActiveFormattingElements( StackNode<T> formattingClone, int bookmark) { formattingClone.retain(); assert listPtr + 1 < listOfActiveFormattingElements.length; if (bookmark <= listPtr) { System.arraycopy(listOfActiveFormattingElements, bookmark, listOfActiveFormattingElements, bookmark + 1, (listPtr - bookmark) + 1); } listPtr++; listOfActiveFormattingElements[bookmark] = formattingClone; } private int findInListOfActiveFormattingElements(StackNode<T> node) { for (int i = listPtr; i >= 0; i--) { if (node == listOfActiveFormattingElements[i]) { return i; } } return -1; } private int findInListOfActiveFormattingElementsContainsBetweenEndAndLastMarker( @Local String name) { for (int i = listPtr; i >= 0; i--) { StackNode<T> node = listOfActiveFormattingElements[i]; if (node == null) { return -1; } else if (node.name == name) { return i; } } return -1; } private int findLastOrRoot(@Local String name) { for (int i = currentPtr; i > 0; i--) { if (stack[i].name == name) { return i; } } return 0; } private int findLastOrRoot(int group) { for (int i = currentPtr; i > 0; i--) { if (stack[i].group == group) { return i; } } return 0; } /** * Attempt to add attribute to the body element. * @param attributes the attributes * @return <code>true</code> iff the attributes were added * @throws SAXException */ private boolean addAttributesToBody(HtmlAttributes attributes) throws SAXException { // [NOCPP[ checkAttributes(attributes, "http://www.w3.org/1999/xhtml"); // ]NOCPP] if (currentPtr >= 1) { StackNode<T> body = stack[1]; if (body.group == TreeBuilder.BODY) { addAttributesToElement(body.node, attributes); return true; } } return false; } private void addAttributesToHtml(HtmlAttributes attributes) throws SAXException { // [NOCPP[ checkAttributes(attributes, "http://www.w3.org/1999/xhtml"); // ]NOCPP] addAttributesToElement(stack[0].node, attributes); } private void pushHeadPointerOntoStack() throws SAXException { assert headPointer != null; assert !fragment; assert mode == AFTER_HEAD; fatal(); silentPush(new StackNode<T>("http://www.w3.org/1999/xhtml", ElementName.HEAD, headPointer)); } /** * @throws SAXException * */ private void reconstructTheActiveFormattingElements() throws SAXException { if (listPtr == -1) { return; } StackNode<T> mostRecent = listOfActiveFormattingElements[listPtr]; if (mostRecent == null || isInStack(mostRecent)) { return; } int entryPos = listPtr; for (;;) { entryPos--; if (entryPos == -1) { break; } if (listOfActiveFormattingElements[entryPos] == null) { break; } if (isInStack(listOfActiveFormattingElements[entryPos])) { break; } } while (entryPos < listPtr) { entryPos++; StackNode<T> entry = listOfActiveFormattingElements[entryPos]; T clone = createElement("http://www.w3.org/1999/xhtml", entry.name, entry.attributes.cloneAttributes(null)); StackNode<T> entryClone = new StackNode<T>(entry.group, entry.ns, entry.name, clone, entry.scoping, entry.special, entry.fosterParenting, entry.popName, entry.attributes); entry.dropAttributes(); // transfer ownership to entryClone StackNode<T> currentNode = stack[currentPtr]; if (currentNode.fosterParenting) { insertIntoFosterParent(clone); } else { appendElement(clone, currentNode.node); } push(entryClone); // stack takes ownership of the local variable listOfActiveFormattingElements[entryPos] = entryClone; // overwriting the old entry on the list, so release & retain entry.release(); entryClone.retain(); } } private void insertIntoFosterParent(T child) throws SAXException { int eltPos = findLastOrRoot(TreeBuilder.TABLE); StackNode<T> node = stack[eltPos]; T elt = node.node; if (eltPos == 0) { appendElement(child, elt); return; } insertFosterParentedChild(child, elt, stack[eltPos - 1].node); } private boolean isInStack(StackNode<T> node) { for (int i = currentPtr; i >= 0; i--) { if (stack[i] == node) { return true; } } return false; } private void pop() throws SAXException { StackNode<T> node = stack[currentPtr]; assert clearLastStackSlot(); currentPtr--; elementPopped(node.ns, node.popName, node.node); node.release(); } private void silentPop() throws SAXException { StackNode<T> node = stack[currentPtr]; assert clearLastStackSlot(); currentPtr--; node.release(); } private void popOnEof() throws SAXException { StackNode<T> node = stack[currentPtr]; assert clearLastStackSlot(); currentPtr--; markMalformedIfScript(node.node); elementPopped(node.ns, node.popName, node.node); node.release(); } // [NOCPP[ private void checkAttributes(HtmlAttributes attributes, @NsUri String ns) throws SAXException { if (errorHandler != null) { int len = attributes.getXmlnsLength(); for (int i = 0; i < len; i++) { AttributeName name = attributes.getXmlnsAttributeName(i); if (name == AttributeName.XMLNS) { if (html4) { err("Attribute \u201Cxmlns\u201D not allowed here. (HTML4-only error.)"); } else { String xmlns = attributes.getXmlnsValue(i); if (!ns.equals(xmlns)) { err("Bad value \u201C" + xmlns + "\u201D for the attribute \u201Cxmlns\u201D (only \u201C" + ns + "\u201D permitted here)."); switch (namePolicy) { case ALTER_INFOSET: // fall through case ALLOW: warn("Attribute \u201Cxmlns\u201D is not serializable as XML 1.0."); break; case FATAL: fatal("Attribute \u201Cxmlns\u201D is not serializable as XML 1.0."); break; } } } } else if (ns != "http://www.w3.org/1999/xhtml" && name == AttributeName.XMLNS_XLINK) { String xmlns = attributes.getXmlnsValue(i); if (!"http://www.w3.org/1999/xlink".equals(xmlns)) { err("Bad value \u201C" + xmlns + "\u201D for the attribute \u201Cxmlns:link\u201D (only \u201Chttp://www.w3.org/1999/xlink\u201D permitted here)."); switch (namePolicy) { case ALTER_INFOSET: // fall through case ALLOW: warn("Attribute \u201Cxmlns:xlink\u201D with the value \u201Chttp://www.w3org/1999/xlink\u201D is not serializable as XML 1.0 without changing document semantics."); break; case FATAL: fatal("Attribute \u201Cxmlns:xlink\u201D with the value \u201Chttp://www.w3org/1999/xlink\u201D is not serializable as XML 1.0 without changing document semantics."); break; } } } else { err("Attribute \u201C" + attributes.getXmlnsLocalName(i) + "\u201D not allowed here."); switch (namePolicy) { case ALTER_INFOSET: // fall through case ALLOW: warn("Attribute with the local name \u201C" + attributes.getXmlnsLocalName(i) + "\u201D is not serializable as XML 1.0."); break; case FATAL: fatal("Attribute with the local name \u201C" + attributes.getXmlnsLocalName(i) + "\u201D is not serializable as XML 1.0."); break; } } } } attributes.processNonNcNames(this, namePolicy); } private String checkPopName(@Local String name) throws SAXException { if (NCName.isNCName(name)) { return name; } else { switch (namePolicy) { case ALLOW: warn("Element name \u201C" + name + "\u201D cannot be represented as XML 1.0."); return name; case ALTER_INFOSET: warn("Element name \u201C" + name + "\u201D cannot be represented as XML 1.0."); return NCName.escapeName(name); case FATAL: fatal("Element name \u201C" + name + "\u201D cannot be represented as XML 1.0."); } } return null; // keep compiler happy } // ]NOCPP] private void appendHtmlElementToDocumentAndPush(HtmlAttributes attributes) throws SAXException { // [NOCPP[ checkAttributes(attributes, "http://www.w3.org/1999/xhtml"); // ]NOCPP] T elt = createHtmlElementSetAsRoot(attributes); StackNode<T> node = new StackNode<T>("http://www.w3.org/1999/xhtml", ElementName.HTML, elt); push(node); Portability.releaseElement(elt); } private void appendHtmlElementToDocumentAndPush() throws SAXException { appendHtmlElementToDocumentAndPush(tokenizer.emptyAttributes()); } private void appendToCurrentNodeAndPushHeadElement(HtmlAttributes attributes) throws SAXException { // [NOCPP[ checkAttributes(attributes, "http://www.w3.org/1999/xhtml"); // ]NOCPP] T elt = createElement("http://www.w3.org/1999/xhtml", "head", attributes); appendElement(elt, stack[currentPtr].node); headPointer = elt; Portability.retainElement(headPointer); StackNode<T> node = new StackNode<T>("http://www.w3.org/1999/xhtml", ElementName.HEAD, elt); push(node); Portability.releaseElement(elt); } private void appendToCurrentNodeAndPushBodyElement(HtmlAttributes attributes) throws SAXException { appendToCurrentNodeAndPushElement("http://www.w3.org/1999/xhtml", ElementName.BODY, attributes); } private void appendToCurrentNodeAndPushBodyElement() throws SAXException { appendToCurrentNodeAndPushBodyElement(tokenizer.emptyAttributes()); } private void appendToCurrentNodeAndPushFormElementMayFoster( HtmlAttributes attributes) throws SAXException { // [NOCPP[ checkAttributes(attributes, "http://www.w3.org/1999/xhtml"); // ]NOCPP] T elt = createElement("http://www.w3.org/1999/xhtml", "form", attributes); formPointer = elt; Portability.retainElement(formPointer); StackNode<T> current = stack[currentPtr]; if (current.fosterParenting) { fatal(); insertIntoFosterParent(elt); } else { appendElement(elt, current.node); } StackNode<T> node = new StackNode<T>("http://www.w3.org/1999/xhtml", ElementName.FORM, elt); push(node); Portability.releaseElement(elt); } private void appendToCurrentNodeAndPushFormattingElementMayFoster( @NsUri String ns, ElementName elementName, HtmlAttributes attributes) throws SAXException { // [NOCPP[ checkAttributes(attributes, ns); // ]NOCPP] // This method can't be called for custom elements T elt = createElement(ns, elementName.name, attributes); StackNode<T> current = stack[currentPtr]; if (current.fosterParenting) { fatal(); insertIntoFosterParent(elt); } else { appendElement(elt, current.node); } StackNode<T> node = new StackNode<T>(ns, elementName, elt, attributes.cloneAttributes(null)); push(node); append(node); node.retain(); // append doesn't retain itself Portability.releaseElement(elt); } private void appendToCurrentNodeAndPushElement(@NsUri String ns, ElementName elementName, HtmlAttributes attributes) throws SAXException { // [NOCPP[ checkAttributes(attributes, ns); // ]NOCPP] // This method can't be called for custom elements T elt = createElement(ns, elementName.name, attributes); appendElement(elt, stack[currentPtr].node); StackNode<T> node = new StackNode<T>(ns, elementName, elt); push(node); Portability.releaseElement(elt); } private void appendToCurrentNodeAndPushElementMayFoster(@NsUri String ns, ElementName elementName, HtmlAttributes attributes) throws SAXException { @Local String popName = elementName.name; // [NOCPP[ checkAttributes(attributes, ns); if (elementName.custom) { popName = checkPopName(popName); } // ]NOCPP] T elt = createElement(ns, popName, attributes); StackNode<T> current = stack[currentPtr]; if (current.fosterParenting) { fatal(); insertIntoFosterParent(elt); } else { appendElement(elt, current.node); } StackNode<T> node = new StackNode<T>(ns, elementName, elt, popName); push(node); Portability.releaseElement(elt); } private void appendToCurrentNodeAndPushElementMayFosterNoScoping( @NsUri String ns, ElementName elementName, HtmlAttributes attributes) throws SAXException { @Local String popName = elementName.name; // [NOCPP[ checkAttributes(attributes, ns); if (elementName.custom) { popName = checkPopName(popName); } // ]NOCPP] T elt = createElement(ns, popName, attributes); StackNode<T> current = stack[currentPtr]; if (current.fosterParenting) { fatal(); insertIntoFosterParent(elt); } else { appendElement(elt, current.node); } StackNode<T> node = new StackNode<T>(ns, elementName, elt, popName, false); push(node); Portability.releaseElement(elt); } private void appendToCurrentNodeAndPushElementMayFosterCamelCase( @NsUri String ns, ElementName elementName, HtmlAttributes attributes) throws SAXException { @Local String popName = elementName.camelCaseName; // [NOCPP[ checkAttributes(attributes, ns); if (elementName.custom) { popName = checkPopName(popName); } // ]NOCPP] T elt = createElement(ns, popName, attributes); StackNode<T> current = stack[currentPtr]; if (current.fosterParenting) { fatal(); insertIntoFosterParent(elt); } else { appendElement(elt, current.node); } StackNode<T> node = new StackNode<T>(ns, elementName, elt, popName, ElementName.FOREIGNOBJECT == elementName); push(node); Portability.releaseElement(elt); } private void appendToCurrentNodeAndPushElementMayFoster(@NsUri String ns, ElementName elementName, HtmlAttributes attributes, T form) throws SAXException { // [NOCPP[ checkAttributes(attributes, ns); // ]NOCPP] // Can't be called for custom elements T elt = createElement(ns, elementName.name, attributes, fragment ? null : form); StackNode<T> current = stack[currentPtr]; if (current.fosterParenting) { fatal(); insertIntoFosterParent(elt); } else { appendElement(elt, current.node); } StackNode<T> node = new StackNode<T>(ns, elementName, elt); push(node); Portability.releaseElement(elt); } private void appendVoidElementToCurrentMayFoster( @NsUri String ns, @Local String name, HtmlAttributes attributes, T form) throws SAXException { // [NOCPP[ checkAttributes(attributes, ns); // ]NOCPP] // Can't be called for custom elements T elt = createElement(ns, name, attributes, fragment ? null : form); StackNode<T> current = stack[currentPtr]; if (current.fosterParenting) { fatal(); insertIntoFosterParent(elt); } else { appendElement(elt, current.node); } elementPushed(ns, name, elt); elementPopped(ns, name, elt); Portability.releaseElement(elt); } private void appendVoidElementToCurrentMayFoster( @NsUri String ns, ElementName elementName, HtmlAttributes attributes) throws SAXException { @Local String popName = elementName.name; // [NOCPP[ checkAttributes(attributes, ns); if (elementName.custom) { popName = checkPopName(popName); } // ]NOCPP] T elt = createElement(ns, popName, attributes); StackNode<T> current = stack[currentPtr]; if (current.fosterParenting) { fatal(); insertIntoFosterParent(elt); } else { appendElement(elt, current.node); } elementPushed(ns, popName, elt); elementPopped(ns, popName, elt); Portability.releaseElement(elt); } private void appendVoidElementToCurrentMayFosterCamelCase( @NsUri String ns, ElementName elementName, HtmlAttributes attributes) throws SAXException { @Local String popName = elementName.camelCaseName; // [NOCPP[ checkAttributes(attributes, ns); if (elementName.custom) { popName = checkPopName(popName); } // ]NOCPP] T elt = createElement(ns, popName, attributes); StackNode<T> current = stack[currentPtr]; if (current.fosterParenting) { fatal(); insertIntoFosterParent(elt); } else { appendElement(elt, current.node); } elementPushed(ns, popName, elt); elementPopped(ns, popName, elt); Portability.releaseElement(elt); } private void appendVoidElementToCurrent( @NsUri String ns, @Local String name, HtmlAttributes attributes, T form) throws SAXException { // [NOCPP[ checkAttributes(attributes, ns); // ]NOCPP] // Can't be called for custom elements T elt = createElement(ns, name, attributes, fragment ? null : form); StackNode<T> current = stack[currentPtr]; appendElement(elt, current.node); elementPushed(ns, name, elt); elementPopped(ns, name, elt); Portability.releaseElement(elt); } private void appendVoidFormToCurrent(HtmlAttributes attributes) throws SAXException { // [NOCPP[ checkAttributes(attributes, "http://www.w3.org/1999/xhtml"); // ]NOCPP] T elt = createElement("http://www.w3.org/1999/xhtml", "form", attributes); formPointer = elt; // ownership transferred to form pointer StackNode<T> current = stack[currentPtr]; appendElement(elt, current.node); elementPushed("http://www.w3.org/1999/xhtml", "form", elt); elementPopped("http://www.w3.org/1999/xhtml", "form", elt); } // [NOCPP[ private final void accumulateCharactersForced(@Const @NoLength char[] buf, int start, int length) throws SAXException { int newLen = charBufferLen + length; if (newLen > charBuffer.length) { char[] newBuf = new char[newLen]; System.arraycopy(charBuffer, 0, newBuf, 0, charBufferLen); Portability.releaseArray(charBuffer); charBuffer = newBuf; } System.arraycopy(buf, start, charBuffer, charBufferLen, length); charBufferLen = newLen; } // ]NOCPP] protected void accumulateCharacters(@Const @NoLength char[] buf, int start, int length) throws SAXException { appendCharacters(stack[currentPtr].node, buf, start, length); } // ------------------------------- // protected final void requestSuspension() { tokenizer.requestSuspension(); } protected abstract T createElement(@NsUri String ns, @Local String name, HtmlAttributes attributes) throws SAXException; protected T createElement(@NsUri String ns, @Local String name, HtmlAttributes attributes, T form) throws SAXException { return createElement("http://www.w3.org/1999/xhtml", name, attributes); } protected abstract T createHtmlElementSetAsRoot(HtmlAttributes attributes) throws SAXException; protected abstract void detachFromParent(T element) throws SAXException; protected abstract boolean hasChildren(T element) throws SAXException; protected abstract void appendElement(T child, T newParent) throws SAXException; protected abstract void appendChildrenToNewParent(T oldParent, T newParent) throws SAXException; protected abstract void insertFosterParentedChild(T child, T table, T stackParent) throws SAXException; protected abstract void insertFosterParentedCharacters( @NoLength char[] buf, int start, int length, T table, T stackParent) throws SAXException; protected abstract void appendCharacters(T parent, @NoLength char[] buf, int start, int length) throws SAXException; protected abstract void appendIsindexPrompt(T parent) throws SAXException; protected abstract void appendComment(T parent, @NoLength char[] buf, int start, int length) throws SAXException; protected abstract void appendCommentToDocument(@NoLength char[] buf, int start, int length) throws SAXException; protected abstract void addAttributesToElement(T element, HtmlAttributes attributes) throws SAXException; protected void markMalformedIfScript(T elt) throws SAXException { } protected void start(boolean fragmentMode) throws SAXException { } protected void end() throws SAXException { } protected void appendDoctypeToDocument(@Local String name, String publicIdentifier, String systemIdentifier) throws SAXException { } protected void elementPushed(@NsUri String ns, @Local String name, T node) throws SAXException { } protected void elementPopped(@NsUri String ns, @Local String name, T node) throws SAXException { } // [NOCPP[ protected void documentMode(DocumentMode m, String publicIdentifier, String systemIdentifier, boolean html4SpecificAdditionalErrorChecks) throws SAXException { } /** * @see nu.validator.htmlparser.common.TokenHandler#wantsComments() */ public boolean wantsComments() { return wantingComments; } public void setIgnoringComments(boolean ignoreComments) { wantingComments = !ignoreComments; } /** * Sets the errorHandler. * * @param errorHandler * the errorHandler to set */ public final void setErrorHandler(ErrorHandler errorHandler) { this.errorHandler = errorHandler; } /** * Returns the errorHandler. * * @return the errorHandler */ public ErrorHandler getErrorHandler() { return errorHandler; } /** * The argument MUST be an interned string or <code>null</code>. * * @param context */ public final void setFragmentContext(@Local String context) { this.contextName = context; this.contextNamespace = "http://www.w3.org/1999/xhtml"; this.contextNode = null; this.fragment = (contextName != null); this.quirks = false; } // ]NOCPP] /** * The argument MUST be an interned string or <code>null</code>. * * @param context */ public final void setFragmentContext(@Local String context, @NsUri String ns, T node, boolean quirks) { this.contextName = context; Portability.retainLocal(context); this.contextNamespace = ns; this.contextNode = node; Portability.retainElement(node); this.fragment = (contextName != null); this.quirks = quirks; } protected final T currentNode() { return stack[currentPtr].node; } /** * Returns the scriptingEnabled. * * @return the scriptingEnabled */ public boolean isScriptingEnabled() { return scriptingEnabled; } /** * Sets the scriptingEnabled. * * @param scriptingEnabled * the scriptingEnabled to set */ public void setScriptingEnabled(boolean scriptingEnabled) { this.scriptingEnabled = scriptingEnabled; } // [NOCPP[ /** * Sets the doctypeExpectation. * * @param doctypeExpectation * the doctypeExpectation to set */ public void setDoctypeExpectation(DoctypeExpectation doctypeExpectation) { this.doctypeExpectation = doctypeExpectation; } public void setNamePolicy(XmlViolationPolicy namePolicy) { this.namePolicy = namePolicy; } /** * Sets the documentModeHandler. * * @param documentModeHandler * the documentModeHandler to set */ public void setDocumentModeHandler(DocumentModeHandler documentModeHandler) { this.documentModeHandler = documentModeHandler; } /** * Sets the reportingDoctype. * * @param reportingDoctype * the reportingDoctype to set */ public void setReportingDoctype(boolean reportingDoctype) { this.reportingDoctype = reportingDoctype; } // ]NOCPP] /** * Flushes the pending characters. Public for document.write use cases only. * @throws SAXException */ public final void flushCharacters() throws SAXException { if (charBufferLen > 0) { if ((mode == IN_TABLE || mode == IN_TABLE_BODY || mode == IN_ROW) && charBufferContainsNonWhitespace()) { err("Misplaced non-space characters insided a table."); reconstructTheActiveFormattingElements(); if (!stack[currentPtr].fosterParenting) { // reconstructing gave us a new current node appendCharacters(currentNode(), charBuffer, 0, charBufferLen); charBufferLen = 0; return; } int eltPos = findLastOrRoot(TreeBuilder.TABLE); StackNode<T> node = stack[eltPos]; T elt = node.node; if (eltPos == 0) { appendCharacters(elt, charBuffer, 0, charBufferLen); charBufferLen = 0; return; } insertFosterParentedCharacters(charBuffer, 0, charBufferLen, elt, stack[eltPos - 1].node); charBufferLen = 0; return; } appendCharacters(currentNode(), charBuffer, 0, charBufferLen); charBufferLen = 0; } } private boolean charBufferContainsNonWhitespace() { for (int i = 0; i < charBufferLen; i++) { switch (charBuffer[i]) { case ' ': case '\t': case '\n': case '\r': case '\u000C': continue; default: return true; } } return false; } /** * Creates a comparable snapshot of the tree builder state. Snapshot * creation is only supported immediately after a script end tag has been * processed. In C++ the caller is responsible for calling * <code>delete</code> on the returned object. * * @return a snapshot. * @throws SAXException */ @SuppressWarnings("unchecked") public TreeBuilderState<T> newSnapshot() throws SAXException { StackNode<T>[] listCopy = new StackNode[listPtr + 1]; for (int i = 0; i < listCopy.length; i++) { StackNode<T> node = listOfActiveFormattingElements[i]; if (node != null) { StackNode<T> newNode = new StackNode<T>(node.group, node.ns, node.name, node.node, node.scoping, node.special, node.fosterParenting, node.popName, node.attributes.cloneAttributes(null)); listCopy[i] = newNode; } else { listCopy[i] = null; } } StackNode<T>[] stackCopy = new StackNode[currentPtr + 1]; for (int i = 0; i < stackCopy.length; i++) { StackNode<T> node = stack[i]; int listIndex = findInListOfActiveFormattingElements(node); if (listIndex == -1) { StackNode<T> newNode = new StackNode<T>(node.group, node.ns, node.name, node.node, node.scoping, node.special, node.fosterParenting, node.popName, null); stackCopy[i] = newNode; } else { stackCopy[i] = listCopy[listIndex]; stackCopy[i].retain(); } } Portability.retainElement(formPointer); return new StateSnapshot<T>(stackCopy, listCopy, formPointer, headPointer, deepTreeSurrogateParent, mode, originalMode, framesetOk, inForeign, needToDropLF, quirks); } public boolean snapshotMatches(TreeBuilderState<T> snapshot) { StackNode<T>[] stackCopy = snapshot.getStack(); int stackLen = snapshot.getStackLength(); StackNode<T>[] listCopy = snapshot.getListOfActiveFormattingElements(); int listLen = snapshot.getListOfActiveFormattingElementsLength(); if (stackLen != currentPtr + 1 || listLen != listPtr + 1 || formPointer != snapshot.getFormPointer() || headPointer != snapshot.getHeadPointer() || deepTreeSurrogateParent != snapshot.getDeepTreeSurrogateParent() || mode != snapshot.getMode() || originalMode != snapshot.getOriginalMode() || framesetOk != snapshot.isFramesetOk() || inForeign != snapshot.isInForeign() || needToDropLF != snapshot.isNeedToDropLF() || quirks != snapshot.isQuirks()) { // maybe just assert quirks return false; } for (int i = listLen - 1; i >= 0; i--) { if (listCopy[i] == null && listOfActiveFormattingElements[i] == null) { continue; } else if (listCopy[i] == null || listOfActiveFormattingElements[i] == null) { return false; } if (listCopy[i].node != listOfActiveFormattingElements[i].node) { return false; // it's possible that this condition is overly // strict } } for (int i = stackLen - 1; i >= 0; i--) { if (stackCopy[i].node != stack[i].node) { return false; } } return true; } @SuppressWarnings("unchecked") public void loadState( TreeBuilderState<T> snapshot, Interner interner) throws SAXException { StackNode<T>[] stackCopy = snapshot.getStack(); int stackLen = snapshot.getStackLength(); StackNode<T>[] listCopy = snapshot.getListOfActiveFormattingElements(); int listLen = snapshot.getListOfActiveFormattingElementsLength(); for (int i = 0; i <= listPtr; i++) { if (listOfActiveFormattingElements[i] != null) { listOfActiveFormattingElements[i].release(); } } if (listOfActiveFormattingElements.length < listLen) { Portability.releaseArray(listOfActiveFormattingElements); listOfActiveFormattingElements = new StackNode[listLen]; } listPtr = listLen - 1; for (int i = 0; i <= currentPtr; i++) { stack[i].release(); } if (stack.length < stackLen) { Portability.releaseArray(stack); stack = new StackNode[stackLen]; } currentPtr = stackLen - 1; for (int i = 0; i < listLen; i++) { StackNode<T> node = listCopy[i]; if (node != null) { StackNode<T> newNode = new StackNode<T>(node.group, node.ns, Portability.newLocalFromLocal(node.name, interner), node.node, node.scoping, node.special, node.fosterParenting, Portability.newLocalFromLocal(node.popName, interner), node.attributes.cloneAttributes(null)); listOfActiveFormattingElements[i] = newNode; } else { listOfActiveFormattingElements[i] = null; } } for (int i = 0; i < stackLen; i++) { StackNode<T> node = stackCopy[i]; int listIndex = findInArray(node, listCopy); if (listIndex == -1) { StackNode<T> newNode = new StackNode<T>(node.group, node.ns, Portability.newLocalFromLocal(node.name, interner), node.node, node.scoping, node.special, node.fosterParenting, Portability.newLocalFromLocal(node.popName, interner), null); stack[i] = newNode; } else { stack[i] = listOfActiveFormattingElements[listIndex]; stack[i].retain(); } } Portability.releaseElement(formPointer); formPointer = snapshot.getFormPointer(); Portability.retainElement(formPointer); Portability.releaseElement(headPointer); headPointer = snapshot.getHeadPointer(); Portability.retainElement(headPointer); Portability.releaseElement(deepTreeSurrogateParent); deepTreeSurrogateParent = snapshot.getDeepTreeSurrogateParent(); Portability.retainElement(deepTreeSurrogateParent); mode = snapshot.getMode(); originalMode = snapshot.getOriginalMode(); framesetOk = snapshot.isFramesetOk(); inForeign = snapshot.isInForeign(); needToDropLF = snapshot.isNeedToDropLF(); quirks = snapshot.isQuirks(); } private int findInArray(StackNode<T> node, StackNode<T>[] arr) { for (int i = listPtr; i >= 0; i--) { if (node == arr[i]) { return i; } } return -1; } /** * @see nu.validator.htmlparser.impl.TreeBuilderState#getFormPointer() */ public T getFormPointer() { return formPointer; } /** * Returns the headPointer. * * @return the headPointer */ public T getHeadPointer() { return headPointer; } /** * Returns the deepTreeSurrogateParent. * * @return the deepTreeSurrogateParent */ public T getDeepTreeSurrogateParent() { return deepTreeSurrogateParent; } /** * @see nu.validator.htmlparser.impl.TreeBuilderState#getListOfActiveFormattingElements() */ public StackNode<T>[] getListOfActiveFormattingElements() { return listOfActiveFormattingElements; } /** * @see nu.validator.htmlparser.impl.TreeBuilderState#getStack() */ public StackNode<T>[] getStack() { return stack; } /** * Returns the mode. * * @return the mode */ public int getMode() { return mode; } /** * Returns the originalMode. * * @return the originalMode */ public int getOriginalMode() { return originalMode; } /** * Returns the framesetOk. * * @return the framesetOk */ public boolean isFramesetOk() { return framesetOk; } /** * Returns the foreignFlag. * * @see nu.validator.htmlparser.common.TokenHandler#isInForeign() * @return the foreignFlag */ public boolean isInForeign() { return inForeign; } /** * Returns the needToDropLF. * * @return the needToDropLF */ public boolean isNeedToDropLF() { return needToDropLF; } /** * Returns the quirks. * * @return the quirks */ public boolean isQuirks() { return quirks; } /** * @see nu.validator.htmlparser.impl.TreeBuilderState#getListOfActiveFormattingElementsLength() */ public int getListOfActiveFormattingElementsLength() { return listPtr + 1; } /** * @see nu.validator.htmlparser.impl.TreeBuilderState#getStackLength() */ public int getStackLength() { return currentPtr + 1; } }
true
true
public final void startTag(ElementName elementName, HtmlAttributes attributes, boolean selfClosing) throws SAXException { flushCharacters(); // [NOCPP[ if (errorHandler != null) { // ID uniqueness @IdType String id = attributes.getId(); if (id != null) { LocatorImpl oldLoc = idLocations.get(id); if (oldLoc != null) { err("Duplicate ID \u201C" + id + "\u201D."); errorHandler.warning(new SAXParseException( "The first occurrence of ID \u201C" + id + "\u201D was here.", oldLoc)); } else { idLocations.put(id, new LocatorImpl(tokenizer)); } } } // ]NOCPP] int eltPos; needToDropLF = false; boolean needsPostProcessing = false; starttagloop: for (;;) { int group = elementName.group; @Local String name = elementName.name; if (inForeign) { StackNode<T> currentNode = stack[currentPtr]; @NsUri String currNs = currentNode.ns; int currGroup = currentNode.group; if (("http://www.w3.org/1999/xhtml" == currNs) || ("http://www.w3.org/1998/Math/MathML" == currNs && ((MGLYPH_OR_MALIGNMARK != group && MI_MO_MN_MS_MTEXT == currGroup) || (SVG == group && ANNOTATION_XML == currGroup))) || ("http://www.w3.org/2000/svg" == currNs && (TITLE == currGroup || (FOREIGNOBJECT_OR_DESC == currGroup)))) { needsPostProcessing = true; // fall through to non-foreign behavior } else { switch (group) { case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U: case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU: case BODY: case BR: case RUBY_OR_SPAN_OR_SUB_OR_SUP_OR_VAR: case DD_OR_DT: case UL_OR_OL_OR_DL: case EMBED_OR_IMG: case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6: case HEAD: case HR: case LI: case META: case NOBR: case P: case PRE_OR_LISTING: case TABLE: err("HTML start tag \u201C" + name + "\u201D in a foreign namespace context."); while (!isSpecialParentInForeign(stack[currentPtr])) { pop(); } if (!hasForeignInScope()) { inForeign = false; } continue starttagloop; case FONT: if (attributes.contains(AttributeName.COLOR) || attributes.contains(AttributeName.FACE) || attributes.contains(AttributeName.SIZE)) { err("HTML start tag \u201C" + name + "\u201D in a foreign namespace context."); while (!isSpecialParentInForeign(stack[currentPtr])) { pop(); } if (!hasForeignInScope()) { inForeign = false; } continue starttagloop; } // else fall thru default: if ("http://www.w3.org/2000/svg" == currNs) { attributes.adjustForSvg(); if (selfClosing) { appendVoidElementToCurrentMayFosterCamelCase( currNs, elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFosterCamelCase( currNs, elementName, attributes); } attributes = null; // CPP break starttagloop; } else { attributes.adjustForMath(); if (selfClosing) { appendVoidElementToCurrentMayFoster( currNs, elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFosterNoScoping( currNs, elementName, attributes); } attributes = null; // CPP break starttagloop; } } // switch } // foreignObject / annotation-xml } switch (mode) { case IN_TABLE_BODY: switch (group) { case TR: clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot()); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_ROW; attributes = null; // CPP break starttagloop; case TD_OR_TH: err("\u201C" + name + "\u201D start tag in table body."); clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot()); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", ElementName.TR, HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_ROW; continue; case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: eltPos = findLastInTableScopeOrRootTbodyTheadTfoot(); if (eltPos == 0) { err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } else { clearStackBackTo(eltPos); pop(); mode = IN_TABLE; continue; } default: // fall through to IN_TABLE } case IN_ROW: switch (group) { case TD_OR_TH: clearStackBackTo(findLastOrRoot(TreeBuilder.TR)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_CELL; insertMarker(); attributes = null; // CPP break starttagloop; case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: eltPos = findLastOrRoot(TreeBuilder.TR); if (eltPos == 0) { assert fragment; err("No table row to close."); break starttagloop; } clearStackBackTo(eltPos); pop(); mode = IN_TABLE_BODY; continue; default: // fall through to IN_TABLE } case IN_TABLE: intableloop: for (;;) { switch (group) { case CAPTION: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); insertMarker(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_CAPTION; attributes = null; // CPP break starttagloop; case COLGROUP: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_COLUMN_GROUP; attributes = null; // CPP break starttagloop; case COL: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", ElementName.COLGROUP, HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_COLUMN_GROUP; continue starttagloop; case TBODY_OR_THEAD_OR_TFOOT: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_TABLE_BODY; attributes = null; // CPP break starttagloop; case TR: case TD_OR_TH: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", ElementName.TBODY, HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_TABLE_BODY; continue starttagloop; case TABLE: err("Start tag for \u201Ctable\u201D seen but the previous \u201Ctable\u201D is still open."); eltPos = findLastInTableScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; break starttagloop; } generateImpliedEndTags(); // XXX is the next if dead code? if (errorHandler != null && !isCurrent("table")) { errNoCheck("Unclosed elements on stack."); } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); continue starttagloop; case SCRIPT: // XXX need to manage much more stuff // here if // supporting // document.write() appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; case STYLE: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case INPUT: if (!Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "hidden", attributes.getValue(AttributeName.TYPE))) { break intableloop; } appendVoidElementToCurrent( "http://www.w3.org/1999/xhtml", name, attributes, formPointer); selfClosing = false; attributes = null; // CPP break starttagloop; case FORM: if (formPointer != null) { err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag."); break starttagloop; } else { err("Start tag \u201Cform\u201D seen in \u201Ctable\u201D."); appendVoidFormToCurrent(attributes); attributes = null; // CPP break starttagloop; } default: err("Start tag \u201C" + name + "\u201D seen in \u201Ctable\u201D."); // fall through to IN_BODY break intableloop; } } case IN_CAPTION: switch (group) { case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: err("Stray \u201C" + name + "\u201D start tag in \u201Ccaption\u201D."); eltPos = findLastInTableScope("caption"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { break starttagloop; } generateImpliedEndTags(); if (errorHandler != null && currentPtr != eltPos) { errNoCheck("Unclosed elements on stack."); } while (currentPtr >= eltPos) { pop(); } clearTheListOfActiveFormattingElementsUpToTheLastMarker(); mode = IN_TABLE; continue; default: // fall through to IN_BODY } case IN_CELL: switch (group) { case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: eltPos = findLastInTableScopeTdTh(); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("No cell to close."); break starttagloop; } else { closeTheCell(eltPos); continue; } default: // fall through to IN_BODY } case FRAMESET_OK: switch (group) { case FRAMESET: if (mode == FRAMESET_OK) { if (currentPtr == 0 || stack[1].group != BODY) { assert fragment; err("Stray \u201Cframeset\u201D start tag."); break starttagloop; } else { err("\u201Cframeset\u201D start tag seen."); detachFromParent(stack[1].node); while (currentPtr > 0) { pop(); } appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_FRAMESET; attributes = null; // CPP break starttagloop; } } else { err("Stray \u201Cframeset\u201D start tag."); break starttagloop; } // NOT falling through! case PRE_OR_LISTING: case LI: case DD_OR_DT: case BUTTON: case MARQUEE_OR_APPLET: case OBJECT: case TABLE: case AREA_OR_WBR: case BR: case EMBED_OR_IMG: case INPUT: case KEYGEN: case HR: case TEXTAREA: case XMP: case IFRAME: case SELECT: if (mode == FRAMESET_OK) { framesetOk = false; mode = IN_BODY; } // fall through to IN_BODY default: // fall through to IN_BODY } case IN_BODY: inbodyloop: for (;;) { switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case BASE: case LINK_OR_BASEFONT_OR_BGSOUND: case META: case STYLE: case SCRIPT: case TITLE: case COMMAND: // Fall through to IN_HEAD break inbodyloop; case BODY: err("\u201Cbody\u201D start tag found but the \u201Cbody\u201D element is already open."); if (addAttributesToBody(attributes)) { attributes = null; // CPP } break starttagloop; case P: case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU: case UL_OR_OL_OR_DL: case ADDRESS_OR_DIR_OR_ARTICLE_OR_ASIDE_OR_DATAGRID_OR_DETAILS_OR_HGROUP_OR_FIGURE_OR_FOOTER_OR_HEADER_OR_NAV_OR_SECTION: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6: implicitlyCloseP(); if (stack[currentPtr].group == H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6) { err("Heading cannot be a child of another heading."); pop(); } appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case FIELDSET: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); attributes = null; // CPP break starttagloop; case PRE_OR_LISTING: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); needToDropLF = true; attributes = null; // CPP break starttagloop; case FORM: if (formPointer != null) { err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag."); break starttagloop; } else { implicitlyCloseP(); appendToCurrentNodeAndPushFormElementMayFoster(attributes); attributes = null; // CPP break starttagloop; } case LI: case DD_OR_DT: eltPos = currentPtr; for (;;) { StackNode<T> node = stack[eltPos]; // weak // ref if (node.group == group) { // LI or // DD_OR_DT generateImpliedEndTagsExceptFor(node.name); if (errorHandler != null && eltPos != currentPtr) { errNoCheck("Unclosed elements inside a list."); } while (currentPtr >= eltPos) { pop(); } break; } else if (node.scoping || (node.special && node.name != "p" && node.name != "address" && node.name != "div")) { break; } eltPos--; } implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case PLAINTEXT: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); tokenizer.setStateAndEndTagExpectation( Tokenizer.PLAINTEXT, elementName); attributes = null; // CPP break starttagloop; case A: int activeAPos = findInListOfActiveFormattingElementsContainsBetweenEndAndLastMarker("a"); if (activeAPos != -1) { err("An \u201Ca\u201D start tag seen with already an active \u201Ca\u201D element."); StackNode<T> activeA = listOfActiveFormattingElements[activeAPos]; activeA.retain(); adoptionAgencyEndTag("a"); removeFromStack(activeA); activeAPos = findInListOfActiveFormattingElements(activeA); if (activeAPos != -1) { removeFromListOfActiveFormattingElements(activeAPos); } activeA.release(); } reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushFormattingElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U: case FONT: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushFormattingElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case NOBR: reconstructTheActiveFormattingElements(); if (TreeBuilder.NOT_FOUND_ON_STACK != findLastInScope("nobr")) { err("\u201Cnobr\u201D start tag seen when there was an open \u201Cnobr\u201D element in scope."); adoptionAgencyEndTag("nobr"); } appendToCurrentNodeAndPushFormattingElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case BUTTON: eltPos = findLastInScope(name); if (eltPos != TreeBuilder.NOT_FOUND_ON_STACK) { err("\u201Cbutton\u201D start tag seen when there was an open \u201Cbutton\u201D element in scope."); generateImpliedEndTags(); if (errorHandler != null && !isCurrent(name)) { errNoCheck("End tag \u201Cbutton\u201D seen but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } continue starttagloop; } else { reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); attributes = null; // CPP break starttagloop; } case OBJECT: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); insertMarker(); attributes = null; // CPP break starttagloop; case MARQUEE_OR_APPLET: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); insertMarker(); attributes = null; // CPP break starttagloop; case TABLE: // The only quirk. Blame Hixie and // Acid2. if (!quirks) { implicitlyCloseP(); } appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_TABLE; attributes = null; // CPP break starttagloop; case BR: case EMBED_OR_IMG: case AREA_OR_WBR: reconstructTheActiveFormattingElements(); // FALL THROUGH to PARAM_OR_SOURCE case PARAM_OR_SOURCE: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case HR: implicitlyCloseP(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case IMAGE: err("Saw a start tag \u201Cimage\u201D."); elementName = ElementName.IMG; continue starttagloop; case KEYGEN: case INPUT: reconstructTheActiveFormattingElements(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", name, attributes, formPointer); selfClosing = false; attributes = null; // CPP break starttagloop; case ISINDEX: err("\u201Cisindex\u201D seen."); if (formPointer != null) { break starttagloop; } implicitlyCloseP(); HtmlAttributes formAttrs = new HtmlAttributes(0); int actionIndex = attributes.getIndex(AttributeName.ACTION); if (actionIndex > -1) { formAttrs.addAttribute( AttributeName.ACTION, attributes.getValue(actionIndex) // [NOCPP[ , XmlViolationPolicy.ALLOW // ]NOCPP] ); } appendToCurrentNodeAndPushFormElementMayFoster(formAttrs); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", ElementName.HR, HtmlAttributes.EMPTY_ATTRIBUTES); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", ElementName.LABEL, HtmlAttributes.EMPTY_ATTRIBUTES); int promptIndex = attributes.getIndex(AttributeName.PROMPT); if (promptIndex > -1) { char[] prompt = Portability.newCharArrayFromString(attributes.getValue(promptIndex)); appendCharacters(stack[currentPtr].node, prompt, 0, prompt.length); Portability.releaseArray(prompt); } else { appendIsindexPrompt(stack[currentPtr].node); } HtmlAttributes inputAttributes = new HtmlAttributes( 0); inputAttributes.addAttribute( AttributeName.NAME, Portability.newStringFromLiteral("isindex") // [NOCPP[ , XmlViolationPolicy.ALLOW // ]NOCPP] ); for (int i = 0; i < attributes.getLength(); i++) { AttributeName attributeQName = attributes.getAttributeName(i); if (AttributeName.NAME == attributeQName || AttributeName.PROMPT == attributeQName) { attributes.releaseValue(i); } else if (AttributeName.ACTION != attributeQName) { inputAttributes.addAttribute( attributeQName, attributes.getValue(i) // [NOCPP[ , XmlViolationPolicy.ALLOW // ]NOCPP] ); } } attributes.clearWithoutReleasingContents(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", "input", inputAttributes, formPointer); pop(); // label appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", ElementName.HR, HtmlAttributes.EMPTY_ATTRIBUTES); pop(); // form selfClosing = false; // Portability.delete(formAttrs); // Portability.delete(inputAttributes); // Don't delete attributes, they are deleted // later break starttagloop; case TEXTAREA: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); tokenizer.setStateAndEndTagExpectation( Tokenizer.RCDATA, elementName); originalMode = mode; mode = TEXT; needToDropLF = true; attributes = null; // CPP break starttagloop; case XMP: implicitlyCloseP(); reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case NOSCRIPT: if (!scriptingEnabled) { reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; } else { // fall through } case NOFRAMES: case IFRAME: case NOEMBED: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case SELECT: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); switch (mode) { case IN_TABLE: case IN_CAPTION: case IN_COLUMN_GROUP: case IN_TABLE_BODY: case IN_ROW: case IN_CELL: mode = IN_SELECT_IN_TABLE; break; default: mode = IN_SELECT; break; } attributes = null; // CPP break starttagloop; case OPTGROUP: case OPTION: /* * If the stack of open elements has an option * element in scope, then act as if an end tag * with the tag name "option" had been seen. */ if (findLastInScope("option") != TreeBuilder.NOT_FOUND_ON_STACK) { optionendtagloop: for (;;) { if (isCurrent("option")) { pop(); break optionendtagloop; } eltPos = currentPtr; for (;;) { if (stack[eltPos].name == "option") { generateImpliedEndTags(); if (errorHandler != null && !isCurrent("option")) { errNoCheck("End tag \u201C" + name + "\u201D seen but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } break optionendtagloop; } eltPos--; } } } /* * Reconstruct the active formatting elements, * if any. */ reconstructTheActiveFormattingElements(); /* * Insert an HTML element for the token. */ appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case RT_OR_RP: /* * If the stack of open elements has a ruby * element in scope, then generate implied end * tags. If the current node is not then a ruby * element, this is a parse error; pop all the * nodes from the current node up to the node * immediately before the bottommost ruby * element on the stack of open elements. * * Insert an HTML element for the token. */ eltPos = findLastInScope("ruby"); if (eltPos != NOT_FOUND_ON_STACK) { generateImpliedEndTags(); } if (eltPos != currentPtr) { err("Unclosed children in \u201Cruby\u201D."); while (currentPtr > eltPos) { pop(); } } appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case MATH: reconstructTheActiveFormattingElements(); attributes.adjustForMath(); if (selfClosing) { appendVoidElementToCurrentMayFoster( "http://www.w3.org/1998/Math/MathML", elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1998/Math/MathML", elementName, attributes); inForeign = true; } attributes = null; // CPP break starttagloop; case SVG: reconstructTheActiveFormattingElements(); attributes.adjustForSvg(); if (selfClosing) { appendVoidElementToCurrentMayFosterCamelCase( "http://www.w3.org/2000/svg", elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/2000/svg", elementName, attributes); inForeign = true; } attributes = null; // CPP break starttagloop; case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: case FRAME: case FRAMESET: case HEAD: err("Stray start tag \u201C" + name + "\u201D."); break starttagloop; case OUTPUT_OR_LABEL: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); attributes = null; // CPP break starttagloop; default: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; } } case IN_HEAD: inheadloop: for (;;) { switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case BASE: case COMMAND: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case META: case LINK_OR_BASEFONT_OR_BGSOUND: // Fall through to IN_HEAD_NOSCRIPT break inheadloop; case TITLE: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RCDATA, elementName); attributes = null; // CPP break starttagloop; case NOSCRIPT: if (scriptingEnabled) { appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); } else { appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_HEAD_NOSCRIPT; } attributes = null; // CPP break starttagloop; case SCRIPT: // XXX need to manage much more stuff // here if // supporting // document.write() appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; case STYLE: case NOFRAMES: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case HEAD: /* Parse error. */ err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open."); /* Ignore the token. */ break starttagloop; default: pop(); mode = AFTER_HEAD; continue starttagloop; } } case IN_HEAD_NOSCRIPT: switch (group) { case HTML: // XXX did Hixie really mean to omit "base" // here? err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case LINK_OR_BASEFONT_OR_BGSOUND: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case META: checkMetaCharset(attributes); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case STYLE: case NOFRAMES: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case HEAD: err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open."); break starttagloop; case NOSCRIPT: err("Start tag for \u201Cnoscript\u201D seen when \u201Cnoscript\u201D was already open."); break starttagloop; default: err("Bad start tag in \u201C" + name + "\u201D in \u201Chead\u201D."); pop(); mode = IN_HEAD; continue; } case IN_COLUMN_GROUP: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case COL: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; default: if (currentPtr == 0) { assert fragment; err("Garbage in \u201Ccolgroup\u201D fragment."); break starttagloop; } pop(); mode = IN_TABLE; continue; } case IN_SELECT_IN_TABLE: switch (group) { case CAPTION: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: case TABLE: err("\u201C" + name + "\u201D start tag with \u201Cselect\u201D open."); eltPos = findLastInTableScope("select"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; break starttagloop; // http://www.w3.org/Bugs/Public/show_bug.cgi?id=8375 } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); continue; default: // fall through to IN_SELECT } case IN_SELECT: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case OPTION: if (isCurrent("option")) { pop(); } appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case OPTGROUP: if (isCurrent("option")) { pop(); } if (isCurrent("optgroup")) { pop(); } appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case SELECT: err("\u201Cselect\u201D start tag where end tag expected."); eltPos = findLastInTableScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; err("No \u201Cselect\u201D in table scope."); break starttagloop; } else { while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); break starttagloop; } case INPUT: case TEXTAREA: case KEYGEN: err("\u201C" + name + "\u201D start tag seen in \u201Cselect\2201D."); eltPos = findLastInTableScope("select"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; break starttagloop; } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); continue; case SCRIPT: // XXX need to manage much more stuff // here if // supporting // document.write() appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } case AFTER_BODY: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); mode = framesetOk ? FRAMESET_OK : IN_BODY; continue; } case IN_FRAMESET: switch (group) { case FRAMESET: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case FRAME: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; default: // fall through to AFTER_FRAMESET } case AFTER_FRAMESET: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case NOFRAMES: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } case INITIAL: /* * Parse error. */ // [NOCPP[ switch (doctypeExpectation) { case AUTO: err("Start tag seen without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D."); break; case HTML: err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D."); break; case HTML401_STRICT: err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); break; case HTML401_TRANSITIONAL: err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); break; case NO_DOCTYPE_ERRORS: } // ]NOCPP] /* * * Set the document to quirks mode. */ documentModeInternal(DocumentMode.QUIRKS_MODE, null, null, false); /* * Then, switch to the root element mode of the tree * construction stage */ mode = BEFORE_HTML; /* * and reprocess the current token. */ continue; case BEFORE_HTML: switch (group) { case HTML: // optimize error check and streaming SAX by // hoisting // "html" handling here. if (attributes == HtmlAttributes.EMPTY_ATTRIBUTES) { // This has the right magic side effect // that // it // makes attributes in SAX Tree mutable. appendHtmlElementToDocumentAndPush(); } else { appendHtmlElementToDocumentAndPush(attributes); } // XXX application cache should fire here mode = BEFORE_HEAD; attributes = null; // CPP break starttagloop; default: /* * Create an HTMLElement node with the tag name * html, in the HTML namespace. Append it to the * Document object. */ appendHtmlElementToDocumentAndPush(); /* Switch to the main mode */ mode = BEFORE_HEAD; /* * reprocess the current token. */ continue; } case BEFORE_HEAD: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case HEAD: /* * A start tag whose tag name is "head" * * Create an element for the token. * * Set the head element pointer to this new element * node. * * Append the new element to the current node and * push it onto the stack of open elements. */ appendToCurrentNodeAndPushHeadElement(attributes); /* * Change the insertion mode to "in head". */ mode = IN_HEAD; attributes = null; // CPP break starttagloop; default: /* * Any other start tag token * * Act as if a start tag token with the tag name * "head" and no attributes had been seen, */ appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_HEAD; /* * then reprocess the current token. * * This will result in an empty head element being * generated, with the current token being * reprocessed in the "after head" insertion mode. */ continue; } case AFTER_HEAD: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case BODY: if (attributes.getLength() == 0) { // This has the right magic side effect // that // it // makes attributes in SAX Tree mutable. appendToCurrentNodeAndPushBodyElement(); } else { appendToCurrentNodeAndPushBodyElement(attributes); } framesetOk = false; mode = IN_BODY; attributes = null; // CPP break starttagloop; case FRAMESET: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_FRAMESET; attributes = null; // CPP break starttagloop; case BASE: err("\u201Cbase\u201D element outside \u201Chead\u201D."); pushHeadPointerOntoStack(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; pop(); // head attributes = null; // CPP break starttagloop; case LINK_OR_BASEFONT_OR_BGSOUND: err("\u201Clink\u201D element outside \u201Chead\u201D."); pushHeadPointerOntoStack(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; pop(); // head attributes = null; // CPP break starttagloop; case META: err("\u201Cmeta\u201D element outside \u201Chead\u201D."); checkMetaCharset(attributes); pushHeadPointerOntoStack(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; pop(); // head attributes = null; // CPP break starttagloop; case SCRIPT: err("\u201Cscript\u201D element between \u201Chead\u201D and \u201Cbody\u201D."); pushHeadPointerOntoStack(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; case STYLE: case NOFRAMES: err("\u201C" + name + "\u201D element between \u201Chead\u201D and \u201Cbody\u201D."); pushHeadPointerOntoStack(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case TITLE: err("\u201Ctitle\u201D element outside \u201Chead\u201D."); pushHeadPointerOntoStack(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RCDATA, elementName); attributes = null; // CPP break starttagloop; case HEAD: err("Stray start tag \u201Chead\u201D."); break starttagloop; default: appendToCurrentNodeAndPushBodyElement(); mode = FRAMESET_OK; continue; } case AFTER_AFTER_BODY: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); fatal(); mode = framesetOk ? FRAMESET_OK : IN_BODY; continue; } case AFTER_AFTER_FRAMESET: switch (group) { case NOFRAMES: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } case TEXT: assert false; break starttagloop; // Avoid infinite loop if the assertion // fails } } if (needsPostProcessing && inForeign && !hasForeignInScope()) { /* * If, after doing so, the insertion mode is still "in foreign * content", but there is no element in scope that has a namespace * other than the HTML namespace, switch the insertion mode to the * secondary insertion mode. */ inForeign = false; } if (errorHandler != null && selfClosing) { errNoCheck("Self-closing syntax (\u201C/>\u201D) used on a non-void HTML element. Ignoring the slash and treating as a start tag."); } if (attributes != HtmlAttributes.EMPTY_ATTRIBUTES) { Portability.delete(attributes); } }
public final void startTag(ElementName elementName, HtmlAttributes attributes, boolean selfClosing) throws SAXException { flushCharacters(); // [NOCPP[ if (errorHandler != null) { // ID uniqueness @IdType String id = attributes.getId(); if (id != null) { LocatorImpl oldLoc = idLocations.get(id); if (oldLoc != null) { err("Duplicate ID \u201C" + id + "\u201D."); errorHandler.warning(new SAXParseException( "The first occurrence of ID \u201C" + id + "\u201D was here.", oldLoc)); } else { idLocations.put(id, new LocatorImpl(tokenizer)); } } } // ]NOCPP] int eltPos; needToDropLF = false; boolean needsPostProcessing = false; starttagloop: for (;;) { int group = elementName.group; @Local String name = elementName.name; if (inForeign) { StackNode<T> currentNode = stack[currentPtr]; @NsUri String currNs = currentNode.ns; int currGroup = currentNode.group; if (("http://www.w3.org/1999/xhtml" == currNs) || ("http://www.w3.org/1998/Math/MathML" == currNs && ((MGLYPH_OR_MALIGNMARK != group && MI_MO_MN_MS_MTEXT == currGroup) || (SVG == group && ANNOTATION_XML == currGroup))) || ("http://www.w3.org/2000/svg" == currNs && (TITLE == currGroup || (FOREIGNOBJECT_OR_DESC == currGroup)))) { needsPostProcessing = true; // fall through to non-foreign behavior } else { switch (group) { case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U: case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU: case BODY: case BR: case RUBY_OR_SPAN_OR_SUB_OR_SUP_OR_VAR: case DD_OR_DT: case UL_OR_OL_OR_DL: case EMBED_OR_IMG: case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6: case HEAD: case HR: case LI: case META: case NOBR: case P: case PRE_OR_LISTING: case TABLE: err("HTML start tag \u201C" + name + "\u201D in a foreign namespace context."); while (!isSpecialParentInForeign(stack[currentPtr])) { pop(); } if (!hasForeignInScope()) { inForeign = false; } continue starttagloop; case FONT: if (attributes.contains(AttributeName.COLOR) || attributes.contains(AttributeName.FACE) || attributes.contains(AttributeName.SIZE)) { err("HTML start tag \u201C" + name + "\u201D in a foreign namespace context."); while (!isSpecialParentInForeign(stack[currentPtr])) { pop(); } if (!hasForeignInScope()) { inForeign = false; } continue starttagloop; } // else fall thru default: if ("http://www.w3.org/2000/svg" == currNs) { attributes.adjustForSvg(); if (selfClosing) { appendVoidElementToCurrentMayFosterCamelCase( currNs, elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFosterCamelCase( currNs, elementName, attributes); } attributes = null; // CPP break starttagloop; } else { attributes.adjustForMath(); if (selfClosing) { appendVoidElementToCurrentMayFoster( currNs, elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFosterNoScoping( currNs, elementName, attributes); } attributes = null; // CPP break starttagloop; } } // switch } // foreignObject / annotation-xml } switch (mode) { case IN_TABLE_BODY: switch (group) { case TR: clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot()); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_ROW; attributes = null; // CPP break starttagloop; case TD_OR_TH: err("\u201C" + name + "\u201D start tag in table body."); clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot()); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", ElementName.TR, HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_ROW; continue; case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: eltPos = findLastInTableScopeOrRootTbodyTheadTfoot(); if (eltPos == 0) { err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } else { clearStackBackTo(eltPos); pop(); mode = IN_TABLE; continue; } default: // fall through to IN_TABLE } case IN_ROW: switch (group) { case TD_OR_TH: clearStackBackTo(findLastOrRoot(TreeBuilder.TR)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_CELL; insertMarker(); attributes = null; // CPP break starttagloop; case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: eltPos = findLastOrRoot(TreeBuilder.TR); if (eltPos == 0) { assert fragment; err("No table row to close."); break starttagloop; } clearStackBackTo(eltPos); pop(); mode = IN_TABLE_BODY; continue; default: // fall through to IN_TABLE } case IN_TABLE: intableloop: for (;;) { switch (group) { case CAPTION: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); insertMarker(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_CAPTION; attributes = null; // CPP break starttagloop; case COLGROUP: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_COLUMN_GROUP; attributes = null; // CPP break starttagloop; case COL: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", ElementName.COLGROUP, HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_COLUMN_GROUP; continue starttagloop; case TBODY_OR_THEAD_OR_TFOOT: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_TABLE_BODY; attributes = null; // CPP break starttagloop; case TR: case TD_OR_TH: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", ElementName.TBODY, HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_TABLE_BODY; continue starttagloop; case TABLE: err("Start tag for \u201Ctable\u201D seen but the previous \u201Ctable\u201D is still open."); eltPos = findLastInTableScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; break starttagloop; } generateImpliedEndTags(); // XXX is the next if dead code? if (errorHandler != null && !isCurrent("table")) { errNoCheck("Unclosed elements on stack."); } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); continue starttagloop; case SCRIPT: // XXX need to manage much more stuff // here if // supporting // document.write() appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; case STYLE: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case INPUT: if (!Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "hidden", attributes.getValue(AttributeName.TYPE))) { break intableloop; } appendVoidElementToCurrent( "http://www.w3.org/1999/xhtml", name, attributes, formPointer); selfClosing = false; attributes = null; // CPP break starttagloop; case FORM: if (formPointer != null) { err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag."); break starttagloop; } else { err("Start tag \u201Cform\u201D seen in \u201Ctable\u201D."); appendVoidFormToCurrent(attributes); attributes = null; // CPP break starttagloop; } default: err("Start tag \u201C" + name + "\u201D seen in \u201Ctable\u201D."); // fall through to IN_BODY break intableloop; } } case IN_CAPTION: switch (group) { case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: err("Stray \u201C" + name + "\u201D start tag in \u201Ccaption\u201D."); eltPos = findLastInTableScope("caption"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { break starttagloop; } generateImpliedEndTags(); if (errorHandler != null && currentPtr != eltPos) { errNoCheck("Unclosed elements on stack."); } while (currentPtr >= eltPos) { pop(); } clearTheListOfActiveFormattingElementsUpToTheLastMarker(); mode = IN_TABLE; continue; default: // fall through to IN_BODY } case IN_CELL: switch (group) { case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: eltPos = findLastInTableScopeTdTh(); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("No cell to close."); break starttagloop; } else { closeTheCell(eltPos); continue; } default: // fall through to IN_BODY } case FRAMESET_OK: switch (group) { case FRAMESET: if (mode == FRAMESET_OK) { if (currentPtr == 0 || stack[1].group != BODY) { assert fragment; err("Stray \u201Cframeset\u201D start tag."); break starttagloop; } else { err("\u201Cframeset\u201D start tag seen."); detachFromParent(stack[1].node); while (currentPtr > 0) { pop(); } appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_FRAMESET; attributes = null; // CPP break starttagloop; } } else { err("Stray \u201Cframeset\u201D start tag."); break starttagloop; } // NOT falling through! case PRE_OR_LISTING: case LI: case DD_OR_DT: case BUTTON: case MARQUEE_OR_APPLET: case OBJECT: case TABLE: case AREA_OR_WBR: case BR: case EMBED_OR_IMG: case INPUT: case KEYGEN: case HR: case TEXTAREA: case XMP: case IFRAME: case SELECT: if (mode == FRAMESET_OK) { framesetOk = false; mode = IN_BODY; } // fall through to IN_BODY default: // fall through to IN_BODY } case IN_BODY: inbodyloop: for (;;) { switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case BASE: case LINK_OR_BASEFONT_OR_BGSOUND: case META: case STYLE: case SCRIPT: case TITLE: case COMMAND: // Fall through to IN_HEAD break inbodyloop; case BODY: err("\u201Cbody\u201D start tag found but the \u201Cbody\u201D element is already open."); if (addAttributesToBody(attributes)) { attributes = null; // CPP } break starttagloop; case P: case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU: case UL_OR_OL_OR_DL: case ADDRESS_OR_DIR_OR_ARTICLE_OR_ASIDE_OR_DATAGRID_OR_DETAILS_OR_HGROUP_OR_FIGURE_OR_FOOTER_OR_HEADER_OR_NAV_OR_SECTION: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6: implicitlyCloseP(); if (stack[currentPtr].group == H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6) { err("Heading cannot be a child of another heading."); pop(); } appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case FIELDSET: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); attributes = null; // CPP break starttagloop; case PRE_OR_LISTING: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); needToDropLF = true; attributes = null; // CPP break starttagloop; case FORM: if (formPointer != null) { err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag."); break starttagloop; } else { implicitlyCloseP(); appendToCurrentNodeAndPushFormElementMayFoster(attributes); attributes = null; // CPP break starttagloop; } case LI: case DD_OR_DT: eltPos = currentPtr; for (;;) { StackNode<T> node = stack[eltPos]; // weak // ref if (node.group == group) { // LI or // DD_OR_DT generateImpliedEndTagsExceptFor(node.name); if (errorHandler != null && eltPos != currentPtr) { errNoCheck("Unclosed elements inside a list."); } while (currentPtr >= eltPos) { pop(); } break; } else if (node.scoping || (node.special && node.name != "p" && node.name != "address" && node.name != "div")) { break; } eltPos--; } implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case PLAINTEXT: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); tokenizer.setStateAndEndTagExpectation( Tokenizer.PLAINTEXT, elementName); attributes = null; // CPP break starttagloop; case A: int activeAPos = findInListOfActiveFormattingElementsContainsBetweenEndAndLastMarker("a"); if (activeAPos != -1) { err("An \u201Ca\u201D start tag seen with already an active \u201Ca\u201D element."); StackNode<T> activeA = listOfActiveFormattingElements[activeAPos]; activeA.retain(); adoptionAgencyEndTag("a"); removeFromStack(activeA); activeAPos = findInListOfActiveFormattingElements(activeA); if (activeAPos != -1) { removeFromListOfActiveFormattingElements(activeAPos); } activeA.release(); } reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushFormattingElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U: case FONT: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushFormattingElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case NOBR: reconstructTheActiveFormattingElements(); if (TreeBuilder.NOT_FOUND_ON_STACK != findLastInScope("nobr")) { err("\u201Cnobr\u201D start tag seen when there was an open \u201Cnobr\u201D element in scope."); adoptionAgencyEndTag("nobr"); } appendToCurrentNodeAndPushFormattingElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case BUTTON: eltPos = findLastInScope(name); if (eltPos != TreeBuilder.NOT_FOUND_ON_STACK) { err("\u201Cbutton\u201D start tag seen when there was an open \u201Cbutton\u201D element in scope."); generateImpliedEndTags(); if (errorHandler != null && !isCurrent(name)) { errNoCheck("End tag \u201Cbutton\u201D seen but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } continue starttagloop; } else { reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); attributes = null; // CPP break starttagloop; } case OBJECT: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); insertMarker(); attributes = null; // CPP break starttagloop; case MARQUEE_OR_APPLET: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); insertMarker(); attributes = null; // CPP break starttagloop; case TABLE: // The only quirk. Blame Hixie and // Acid2. if (!quirks) { implicitlyCloseP(); } appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_TABLE; attributes = null; // CPP break starttagloop; case BR: case EMBED_OR_IMG: case AREA_OR_WBR: reconstructTheActiveFormattingElements(); // FALL THROUGH to PARAM_OR_SOURCE case PARAM_OR_SOURCE: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case HR: implicitlyCloseP(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case IMAGE: err("Saw a start tag \u201Cimage\u201D."); elementName = ElementName.IMG; continue starttagloop; case KEYGEN: case INPUT: reconstructTheActiveFormattingElements(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", name, attributes, formPointer); selfClosing = false; attributes = null; // CPP break starttagloop; case ISINDEX: err("\u201Cisindex\u201D seen."); if (formPointer != null) { break starttagloop; } implicitlyCloseP(); HtmlAttributes formAttrs = new HtmlAttributes(0); int actionIndex = attributes.getIndex(AttributeName.ACTION); if (actionIndex > -1) { formAttrs.addAttribute( AttributeName.ACTION, attributes.getValue(actionIndex) // [NOCPP[ , XmlViolationPolicy.ALLOW // ]NOCPP] ); } appendToCurrentNodeAndPushFormElementMayFoster(formAttrs); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", ElementName.HR, HtmlAttributes.EMPTY_ATTRIBUTES); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", ElementName.LABEL, HtmlAttributes.EMPTY_ATTRIBUTES); int promptIndex = attributes.getIndex(AttributeName.PROMPT); if (promptIndex > -1) { char[] prompt = Portability.newCharArrayFromString(attributes.getValue(promptIndex)); appendCharacters(stack[currentPtr].node, prompt, 0, prompt.length); Portability.releaseArray(prompt); } else { appendIsindexPrompt(stack[currentPtr].node); } HtmlAttributes inputAttributes = new HtmlAttributes( 0); inputAttributes.addAttribute( AttributeName.NAME, Portability.newStringFromLiteral("isindex") // [NOCPP[ , XmlViolationPolicy.ALLOW // ]NOCPP] ); for (int i = 0; i < attributes.getLength(); i++) { AttributeName attributeQName = attributes.getAttributeName(i); if (AttributeName.NAME == attributeQName || AttributeName.PROMPT == attributeQName) { attributes.releaseValue(i); } else if (AttributeName.ACTION != attributeQName) { inputAttributes.addAttribute( attributeQName, attributes.getValue(i) // [NOCPP[ , XmlViolationPolicy.ALLOW // ]NOCPP] ); } } attributes.clearWithoutReleasingContents(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", "input", inputAttributes, formPointer); pop(); // label appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", ElementName.HR, HtmlAttributes.EMPTY_ATTRIBUTES); pop(); // form selfClosing = false; // Portability.delete(formAttrs); // Portability.delete(inputAttributes); // Don't delete attributes, they are deleted // later break starttagloop; case TEXTAREA: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); tokenizer.setStateAndEndTagExpectation( Tokenizer.RCDATA, elementName); originalMode = mode; mode = TEXT; needToDropLF = true; attributes = null; // CPP break starttagloop; case XMP: implicitlyCloseP(); reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case NOSCRIPT: if (!scriptingEnabled) { reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; } else { // fall through } case NOFRAMES: case IFRAME: case NOEMBED: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case SELECT: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); switch (mode) { case IN_TABLE: case IN_CAPTION: case IN_COLUMN_GROUP: case IN_TABLE_BODY: case IN_ROW: case IN_CELL: mode = IN_SELECT_IN_TABLE; break; default: mode = IN_SELECT; break; } attributes = null; // CPP break starttagloop; case OPTGROUP: case OPTION: /* * If the stack of open elements has an option * element in scope, then act as if an end tag * with the tag name "option" had been seen. */ if (findLastInScope("option") != TreeBuilder.NOT_FOUND_ON_STACK) { optionendtagloop: for (;;) { if (isCurrent("option")) { pop(); break optionendtagloop; } eltPos = currentPtr; for (;;) { if (stack[eltPos].name == "option") { generateImpliedEndTags(); if (errorHandler != null && !isCurrent("option")) { errNoCheck("End tag \u201C" + name + "\u201D seen but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } break optionendtagloop; } eltPos--; } } } /* * Reconstruct the active formatting elements, * if any. */ reconstructTheActiveFormattingElements(); /* * Insert an HTML element for the token. */ appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case RT_OR_RP: /* * If the stack of open elements has a ruby * element in scope, then generate implied end * tags. If the current node is not then a ruby * element, this is a parse error; pop all the * nodes from the current node up to the node * immediately before the bottommost ruby * element on the stack of open elements. * * Insert an HTML element for the token. */ eltPos = findLastInScope("ruby"); if (eltPos != NOT_FOUND_ON_STACK) { generateImpliedEndTags(); } if (eltPos != currentPtr) { err("Unclosed children in \u201Cruby\u201D."); while (currentPtr > eltPos) { pop(); } } appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case MATH: reconstructTheActiveFormattingElements(); attributes.adjustForMath(); if (selfClosing) { appendVoidElementToCurrentMayFoster( "http://www.w3.org/1998/Math/MathML", elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1998/Math/MathML", elementName, attributes); inForeign = true; } attributes = null; // CPP break starttagloop; case SVG: reconstructTheActiveFormattingElements(); attributes.adjustForSvg(); if (selfClosing) { appendVoidElementToCurrentMayFosterCamelCase( "http://www.w3.org/2000/svg", elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/2000/svg", elementName, attributes); inForeign = true; } attributes = null; // CPP break starttagloop; case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: case FRAME: case FRAMESET: case HEAD: err("Stray start tag \u201C" + name + "\u201D."); break starttagloop; case OUTPUT_OR_LABEL: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); attributes = null; // CPP break starttagloop; default: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; } } case IN_HEAD: inheadloop: for (;;) { switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case BASE: case COMMAND: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case META: case LINK_OR_BASEFONT_OR_BGSOUND: // Fall through to IN_HEAD_NOSCRIPT break inheadloop; case TITLE: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RCDATA, elementName); attributes = null; // CPP break starttagloop; case NOSCRIPT: if (scriptingEnabled) { appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); } else { appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_HEAD_NOSCRIPT; } attributes = null; // CPP break starttagloop; case SCRIPT: // XXX need to manage much more stuff // here if // supporting // document.write() appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; case STYLE: case NOFRAMES: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case HEAD: /* Parse error. */ err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open."); /* Ignore the token. */ break starttagloop; default: pop(); mode = AFTER_HEAD; continue starttagloop; } } case IN_HEAD_NOSCRIPT: switch (group) { case HTML: // XXX did Hixie really mean to omit "base" // here? err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case LINK_OR_BASEFONT_OR_BGSOUND: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case META: checkMetaCharset(attributes); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case STYLE: case NOFRAMES: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case HEAD: err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open."); break starttagloop; case NOSCRIPT: err("Start tag for \u201Cnoscript\u201D seen when \u201Cnoscript\u201D was already open."); break starttagloop; default: err("Bad start tag in \u201C" + name + "\u201D in \u201Chead\u201D."); pop(); mode = IN_HEAD; continue; } case IN_COLUMN_GROUP: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case COL: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; default: if (currentPtr == 0) { assert fragment; err("Garbage in \u201Ccolgroup\u201D fragment."); break starttagloop; } pop(); mode = IN_TABLE; continue; } case IN_SELECT_IN_TABLE: switch (group) { case CAPTION: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: case TABLE: err("\u201C" + name + "\u201D start tag with \u201Cselect\u201D open."); eltPos = findLastInTableScope("select"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; break starttagloop; // http://www.w3.org/Bugs/Public/show_bug.cgi?id=8375 } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); continue; default: // fall through to IN_SELECT } case IN_SELECT: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case OPTION: if (isCurrent("option")) { pop(); } appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case OPTGROUP: if (isCurrent("option")) { pop(); } if (isCurrent("optgroup")) { pop(); } appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case SELECT: err("\u201Cselect\u201D start tag where end tag expected."); eltPos = findLastInTableScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; err("No \u201Cselect\u201D in table scope."); break starttagloop; } else { while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); break starttagloop; } case INPUT: case TEXTAREA: case KEYGEN: err("\u201C" + name + "\u201D start tag seen in \u201Cselect\2201D."); eltPos = findLastInTableScope("select"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; break starttagloop; } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); continue; case SCRIPT: // XXX need to manage much more stuff // here if // supporting // document.write() appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } case AFTER_BODY: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); mode = framesetOk ? FRAMESET_OK : IN_BODY; continue; } case IN_FRAMESET: switch (group) { case FRAMESET: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case FRAME: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; default: // fall through to AFTER_FRAMESET } case AFTER_FRAMESET: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case NOFRAMES: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } case INITIAL: /* * Parse error. */ // [NOCPP[ switch (doctypeExpectation) { case AUTO: err("Start tag seen without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D."); break; case HTML: err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D."); break; case HTML401_STRICT: err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); break; case HTML401_TRANSITIONAL: err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); break; case NO_DOCTYPE_ERRORS: } // ]NOCPP] /* * * Set the document to quirks mode. */ documentModeInternal(DocumentMode.QUIRKS_MODE, null, null, false); /* * Then, switch to the root element mode of the tree * construction stage */ mode = BEFORE_HTML; /* * and reprocess the current token. */ continue; case BEFORE_HTML: switch (group) { case HTML: // optimize error check and streaming SAX by // hoisting // "html" handling here. if (attributes == HtmlAttributes.EMPTY_ATTRIBUTES) { // This has the right magic side effect // that // it // makes attributes in SAX Tree mutable. appendHtmlElementToDocumentAndPush(); } else { appendHtmlElementToDocumentAndPush(attributes); } // XXX application cache should fire here mode = BEFORE_HEAD; attributes = null; // CPP break starttagloop; default: /* * Create an HTMLElement node with the tag name * html, in the HTML namespace. Append it to the * Document object. */ appendHtmlElementToDocumentAndPush(); /* Switch to the main mode */ mode = BEFORE_HEAD; /* * reprocess the current token. */ continue; } case BEFORE_HEAD: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case HEAD: /* * A start tag whose tag name is "head" * * Create an element for the token. * * Set the head element pointer to this new element * node. * * Append the new element to the current node and * push it onto the stack of open elements. */ appendToCurrentNodeAndPushHeadElement(attributes); /* * Change the insertion mode to "in head". */ mode = IN_HEAD; attributes = null; // CPP break starttagloop; default: /* * Any other start tag token * * Act as if a start tag token with the tag name * "head" and no attributes had been seen, */ appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_HEAD; /* * then reprocess the current token. * * This will result in an empty head element being * generated, with the current token being * reprocessed in the "after head" insertion mode. */ continue; } case AFTER_HEAD: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case BODY: if (attributes.getLength() == 0) { // This has the right magic side effect // that // it // makes attributes in SAX Tree mutable. appendToCurrentNodeAndPushBodyElement(); } else { appendToCurrentNodeAndPushBodyElement(attributes); } framesetOk = false; mode = IN_BODY; attributes = null; // CPP break starttagloop; case FRAMESET: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_FRAMESET; attributes = null; // CPP break starttagloop; case BASE: err("\u201Cbase\u201D element outside \u201Chead\u201D."); pushHeadPointerOntoStack(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; pop(); // head attributes = null; // CPP break starttagloop; case LINK_OR_BASEFONT_OR_BGSOUND: err("\u201Clink\u201D element outside \u201Chead\u201D."); pushHeadPointerOntoStack(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; pop(); // head attributes = null; // CPP break starttagloop; case META: err("\u201Cmeta\u201D element outside \u201Chead\u201D."); checkMetaCharset(attributes); pushHeadPointerOntoStack(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; pop(); // head attributes = null; // CPP break starttagloop; case SCRIPT: err("\u201Cscript\u201D element between \u201Chead\u201D and \u201Cbody\u201D."); pushHeadPointerOntoStack(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; case STYLE: case NOFRAMES: err("\u201C" + name + "\u201D element between \u201Chead\u201D and \u201Cbody\u201D."); pushHeadPointerOntoStack(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case TITLE: err("\u201Ctitle\u201D element outside \u201Chead\u201D."); pushHeadPointerOntoStack(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RCDATA, elementName); attributes = null; // CPP break starttagloop; case HEAD: err("Stray start tag \u201Chead\u201D."); break starttagloop; default: appendToCurrentNodeAndPushBodyElement(); mode = FRAMESET_OK; continue; } case AFTER_AFTER_BODY: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); fatal(); mode = framesetOk ? FRAMESET_OK : IN_BODY; continue; } case AFTER_AFTER_FRAMESET: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case NOFRAMES: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } case TEXT: assert false; break starttagloop; // Avoid infinite loop if the assertion // fails } } if (needsPostProcessing && inForeign && !hasForeignInScope()) { /* * If, after doing so, the insertion mode is still "in foreign * content", but there is no element in scope that has a namespace * other than the HTML namespace, switch the insertion mode to the * secondary insertion mode. */ inForeign = false; } if (errorHandler != null && selfClosing) { errNoCheck("Self-closing syntax (\u201C/>\u201D) used on a non-void HTML element. Ignoring the slash and treating as a start tag."); } if (attributes != HtmlAttributes.EMPTY_ATTRIBUTES) { Portability.delete(attributes); } }
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/ElevatorBoardEdge.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/ElevatorBoardEdge.java index 82b1bbd6c..85d4f56f9 100644 --- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/ElevatorBoardEdge.java +++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/ElevatorBoardEdge.java @@ -1,107 +1,108 @@ /* This program 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 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 org.opentripplanner.routing.edgetype; import org.opentripplanner.routing.core.AbstractEdge; import org.opentripplanner.routing.core.EdgeNarrative; import org.opentripplanner.routing.core.State; import org.opentripplanner.routing.core.StateEditor; import org.opentripplanner.routing.core.TraverseMode; import org.opentripplanner.routing.core.TraverseOptions; import org.opentripplanner.routing.core.Vertex; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.Coordinate; /** * A relatively high cost edge for boarding an elevator. * @author mattwigway * */ public class ElevatorBoardEdge extends AbstractEdge { private static final long serialVersionUID = 3925814840369402222L; /** * The polyline geometry of this edge. * It's generally a polyline with two coincident points, but some elevators have horizontal * dimension, e.g. the ones on the Eiffel Tower. */ private Geometry the_geom; public ElevatorBoardEdge(Vertex from, Vertex to) { super(from, to); // set up the geometry Coordinate[] coords = new Coordinate[2]; coords[0] = new Coordinate(from.getX(), from.getY()); coords[1] = new Coordinate(to.getX(), to.getY()); // TODO: SRID? the_geom = new GeometryFactory().createLineString(coords); } @Override public State traverse(State s0) { EdgeNarrative en = new FixedModeEdge(this, s0.getOptions().getModes().getNonTransitMode()); - TraverseOptions options = s0.getOptions(); + TraverseOptions options = s0.getOptions(); StateEditor s1 = s0.edit(this, en); s1.incrementWeight(options.elevatorBoardCost); - s1.incrementTimeInSeconds(options.elevatorBoardTime); + s1.incrementTimeInSeconds(options.elevatorBoardTime); return s1.makeState(); } @Override public double getDistance() { return 0; } @Override public Geometry getGeometry() { return null; } @Override public TraverseMode getMode() { return TraverseMode.WALK; } @Override public String getName() { return "Elevator"; } /** - * Since board edges always are called Elevator (figure out how to fix this), - * the name is utterly and completely bogus. + * Since board edges always are called Elevator, + * the name is utterly and completely bogus but is never included + * in plans.. */ @Override public boolean hasBogusName() { return true; } public boolean equals(Object o) { if (o instanceof ElevatorBoardEdge) { ElevatorBoardEdge other = (ElevatorBoardEdge) o; return other.getFromVertex().equals(fromv) && other.getToVertex().equals(tov); } return false; } public String toString() { return "ElevatorBoardEdge(" + fromv + " -> " + tov + ")"; } }
false
false
null
null
diff --git a/src/idv/Zero/KerKerInput/Methods/BPMFInput.java b/src/idv/Zero/KerKerInput/Methods/BPMFInput.java index fb490f6..6e910eb 100755 --- a/src/idv/Zero/KerKerInput/Methods/BPMFInput.java +++ b/src/idv/Zero/KerKerInput/Methods/BPMFInput.java @@ -1,340 +1,340 @@ package idv.Zero.KerKerInput.Methods; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.util.Log; import android.view.KeyEvent; import idv.Zero.KerKerInput.KerKerInputCore; import idv.Zero.KerKerInput.Keyboard; import idv.Zero.KerKerInput.R; import idv.Zero.KerKerInput.Methods.BPMFInputHelpers.ZhuYinComponentHelper; public class BPMFInput extends idv.Zero.KerKerInput.IKerKerInputMethod { private enum InputState {STATE_INPUT, STATE_CHOOSE}; private InputState currentState; private String inputBufferRaw = ""; private List<CharSequence> _currentCandidates; private HashMap<Character, String> K2N; private String _dbpath; private int _currentPage; private int _totalPages; private SQLiteDatabase db; public void initInputMethod(KerKerInputCore core) { super.initInputMethod(core); initKeyNameData(); _currentPage = 0; _currentCandidates = new ArrayList<CharSequence>(); Context c = core.getFrontend(); _dbpath = c.getDatabasePath("cin.db").toString(); try { db = SQLiteDatabase.openDatabase(_dbpath, null, SQLiteDatabase.OPEN_READONLY); db.setLocale(Locale.TRADITIONAL_CHINESE); db.close(); } catch(SQLiteException ex) { System.out.println("Error, no database file found. Copying..."); // Create the database (and the directories required) then close it. db = c.openOrCreateDatabase("cin.db", 0, null); db.close(); try { OutputStream dos = new FileOutputStream(_dbpath); InputStream dis = c.getResources().openRawResource(R.raw.bpmf); byte[] buffer = new byte[4096]; while (dis.read(buffer) > 0) { dos.write(buffer); } dos.flush(); dos.close(); dis.close(); } catch (IOException e) { e.printStackTrace(); } } } public void onEnterInputMethod() { currentState = InputState.STATE_INPUT; inputBufferRaw = ""; updateCandidates(); // Copied, re-open it. db = SQLiteDatabase.openDatabase(_dbpath, null, SQLiteDatabase.OPEN_READONLY); db.setLocale(Locale.TRADITIONAL_CHINESE); } public void onLeaveInputMethod() { db.close(); } public String getName() { return "注音"; } public Keyboard getDesiredKeyboard() { return new Keyboard(_core.getFrontend(), R.xml.kb_zhuyin, R.id.mode_normal); } public void commitCurrentComposingBuffer() { commitText(getCompositeString()); } public boolean onKeyEvent(int keyCode, int[] keyCodes) { return handleBPMFKeyEvent(keyCode, keyCodes); } private boolean handleBPMFKeyEvent(int keyCode, int[] keyCodes) { if (currentState == InputState.STATE_INPUT) { if (keyCode == Keyboard.KEYCODE_DELETE) { if (inputBufferRaw.length() > 0) { inputBufferRaw = inputBufferRaw.substring(0, inputBufferRaw.length() - 1); } else _core.getFrontend().sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL); } else if (keyCode == 32) // space { if (_currentCandidates.size() > 0) { currentState = InputState.STATE_CHOOSE; handleBPMFKeyEvent(32, null); } else _core.getFrontend().sendKeyChar((char) keyCode); } else if (keyCode == 10) // RETURN { if (inputBufferRaw.length() > 0) commitText(getCompositeString()); else _core.getFrontend().sendKeyChar((char) keyCode); } else { char c = (char)keyCode; inputBufferRaw = ZhuYinComponentHelper.getComposedRawString(inputBufferRaw, Character.toString(c)); // 如果是音調符號,直接進入選字模式。 if (inputBufferRaw.length() > 0 && (c == '3' || c == '4' || c == '6' || c == '7')) currentState = InputState.STATE_CHOOSE; } _core.setCompositeBuffer(getCompositeString()); updateCandidates(); } else if (currentState == InputState.STATE_CHOOSE) { switch (keyCode) { case Keyboard.KEYCODE_DELETE: currentState = InputState.STATE_INPUT; if (inputBufferRaw.length() > 0) { inputBufferRaw = inputBufferRaw.substring(0, inputBufferRaw.length() - 1); _core.setCompositeBuffer(getCompositeString()); updateCandidates(); } else Log.e("BPMFInput", "InputBuffer is requested to delete, but the buffer is empty"); break; // TODO: Make sure DPad & Keyboard L/R keyCode case -103: // DPad Left if (_currentPage > 0) _currentPage--; else _currentPage = _totalPages - 1; break; case -104: // DPad Right if (_currentPage < _totalPages - 1) _currentPage++; else _currentPage = 0; break; case ' ': case 10: keyCode = KeyEvent.KEYCODE_0; default: if (keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9) { // This prevents user hit tone symbol twice makes program crash. // It's because first sign interpreted as bpmf symbol, and second one is treated as candidate choose. // Also prevent user select non-exist candidates on physical kb. if (_totalPages < 0) break; int CANDIDATES_PER_PAGE = (_currentCandidates.size() / _totalPages); if ((_currentPage * CANDIDATES_PER_PAGE + keyCode - KeyEvent.KEYCODE_0 - 1) < _currentCandidates.size()) { commitCandidate(_currentPage * CANDIDATES_PER_PAGE + keyCode - KeyEvent.KEYCODE_0 - 1); } } break; } } return true; } private CharSequence getCompositeString() { StringBuilder str = new StringBuilder(); int length = inputBufferRaw.length(); for(int i=0;i<length;i++) { if (K2N.containsKey(inputBufferRaw.charAt(i))) str.append(K2N.get(inputBufferRaw.charAt(i))); } return str.toString(); } private void updateCandidates() { if (inputBufferRaw.length() == 0) { // bz: fixme: mod here _currentCandidates.clear(); _core.hideCandidatesView(); return; } try { // Cursor currentQuery = db.rawQuery("Select val from bpmf where key glob '" + inputBufferRaw.toString() + "*'", null); Cursor currentQuery = db.rawQuery("Select val from bpmf where key >= '" + inputBufferRaw.toString() + "' AND key < '" + inputBufferRaw.toString() + "zzz' ORDER BY cnt DESC", null); if (currentQuery.getCount() == 0) { inputBufferRaw = inputBufferRaw.substring(0, inputBufferRaw.length() - 1); _currentCandidates.clear(); _core.setCompositeBuffer(getCompositeString()); _core.showPopup(R.string.no_such_mapping); _core.hideCandidatesView(); currentState = InputState.STATE_INPUT; updateCandidates(); } else { int count = Math.min(currentQuery.getCount(), 50); int colIdx = currentQuery.getColumnIndex("val"); _currentCandidates = new ArrayList<CharSequence>(count); currentQuery.moveToNext(); String last_ca = ""; for(int i=0;i<count;i++) { String ca = currentQuery.getString(colIdx); // bz: list are sorted by sqlite3, skip repeating word(s) - if (ca != last_ca) + if ( !ca.equals(last_ca) ) { _currentCandidates.add(ca); } currentQuery.moveToNext(); last_ca = ca; } _core.showCandidatesView(); _core.setCandidates(_currentCandidates); } currentQuery.close(); } catch(Exception e) {} finally { } } public void commitCandidate(int selectedCandidate) { if (selectedCandidate < 0) selectedCandidate = 0; if (_currentCandidates.size() == 0) return; commitText(_currentCandidates.get(selectedCandidate)); } public void setTotalPages(int totalPages) { _totalPages = totalPages; } public void setCurrentPage(int currentPage) { _currentPage = currentPage; } private void commitText(CharSequence str) { _core.commitText(str); inputBufferRaw = ""; updateCandidates(); currentState = InputState.STATE_INPUT; } private void initKeyNameData() { K2N = new HashMap<Character, String>(); K2N.put(',', "ㄝ"); K2N.put('-', "ㄦ"); K2N.put('.', "ㄡ"); K2N.put('/', "ㄥ"); K2N.put('0', "ㄢ"); K2N.put('1', "ㄅ"); K2N.put('2', "ㄉ"); K2N.put('3', "ˇ"); K2N.put('4', "ˋ"); K2N.put('5', "ㄓ"); K2N.put('6', "ˊ"); K2N.put('7', "˙"); K2N.put('8', "ㄚ"); K2N.put('9', "ㄞ"); K2N.put(';', "ㄤ"); K2N.put('a', "ㄇ"); K2N.put('b', "ㄖ"); K2N.put('c', "ㄏ"); K2N.put('d', "ㄎ"); K2N.put('e', "ㄍ"); K2N.put('f', "ㄑ"); K2N.put('g', "ㄕ"); K2N.put('h', "ㄘ"); K2N.put('i', "ㄛ"); K2N.put('j', "ㄨ"); K2N.put('k', "ㄜ"); K2N.put('l', "ㄠ"); K2N.put('m', "ㄩ"); K2N.put('n', "ㄙ"); K2N.put('o', "ㄟ"); K2N.put('p', "ㄣ"); K2N.put('q', "ㄆ"); K2N.put('r', "ㄐ"); K2N.put('s', "ㄋ"); K2N.put('t', "ㄔ"); K2N.put('u', "ㄧ"); K2N.put('v', "ㄒ"); K2N.put('w', "ㄊ"); K2N.put('x', "ㄌ"); K2N.put('y', "ㄗ"); K2N.put('z', "ㄈ"); } }
true
false
null
null
diff --git a/struts2/plugin/src-test/com/intellij/struts2/BasicHighlightingTestCase.java b/struts2/plugin/src-test/com/intellij/struts2/BasicHighlightingTestCase.java index b5403900b3..30ce02e1c1 100644 --- a/struts2/plugin/src-test/com/intellij/struts2/BasicHighlightingTestCase.java +++ b/struts2/plugin/src-test/com/intellij/struts2/BasicHighlightingTestCase.java @@ -1,175 +1,179 @@ /* * Copyright 2008 The 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 com.intellij.struts2; import com.intellij.codeInspection.LocalInspectionTool; import com.intellij.facet.FacetManager; import com.intellij.openapi.application.Result; import com.intellij.openapi.application.RunResult; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.struts2.facet.StrutsFacet; import com.intellij.struts2.facet.StrutsFacetType; import com.intellij.struts2.facet.ui.StrutsFileSet; import com.intellij.testFramework.builders.JavaModuleFixtureBuilder; import com.intellij.testFramework.fixtures.*; +import com.intellij.javaee.JavaeeUtil; +import com.intellij.javaee.web.facet.WebFacetType; +import com.intellij.javaee.web.facet.WebFacet; import org.jetbrains.annotations.NonNls; import java.io.File; import java.io.IOException; import java.util.Set; /** * Base class for highlighting tests. * * @author Yann C&eacute;bron */ public abstract class BasicHighlightingTestCase<T extends JavaModuleFixtureBuilder> extends BasicStrutsTestCase { protected CodeInsightTestFixture myFixture; protected ModuleFixture myModuleTestFixture; protected Project myProject; protected Module myModule; protected StrutsFacet myFacet; protected Class<T> getModuleFixtureBuilderClass() { //noinspection unchecked return (Class<T>) JavaModuleFixtureBuilder.class; } /** * Inspections to run for highlighting tests. * * @return Inspection tools. */ protected abstract LocalInspectionTool[] getHighlightingInspections(); /** * Return true if the test uses JAVA sources. * * @return false. */ protected boolean hasJavaSources() { return false; } protected void setUp() throws Exception { super.setUp(); final TestFixtureBuilder<IdeaProjectTestFixture> projectBuilder = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(); final T moduleBuilder = projectBuilder.addModule(getModuleFixtureBuilderClass()); myFixture = IdeaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture(projectBuilder.getFixture()); myFixture.setTestDataPath(getTestDataPath()); configureModule(moduleBuilder); myFixture.enableInspections(getHighlightingInspections()); myFixture.setUp(); myProject = myFixture.getProject(); myModuleTestFixture = moduleBuilder.getFixture(); myModule = myModuleTestFixture.getModule(); myFacet = createFacet(); } protected void configureModule(final T moduleBuilder) throws Exception { moduleBuilder.addContentRoot(myFixture.getTempDirPath()); moduleBuilder.addContentRoot(getTestDataPath()); if (hasJavaSources()) { final String path = myFixture.getTempDirPath(); new File(path + "/src").mkdir(); // ?? necessary moduleBuilder.addContentRoot(getTestDataPath() + "/src"); moduleBuilder.addSourceRoot("src"); } addStrutsJars(moduleBuilder); } /** * Adds the S2 jars. * * @param moduleBuilder Current module builder. * @throws Exception On internal errors. */ protected final void addStrutsJars(final T moduleBuilder) throws Exception { addLibrary(moduleBuilder, "struts2", "struts2-core-2.1.6.jar", "freemarker-2.3.13.jar", "ognl-2.6.11.jar", "xwork-2.1.2.jar"); } protected void addLibrary(final T moduleBuilder, @NonNls final String libraryName, @NonNls final String... jarPaths) { final File testDataBasePathFile = new File(getTestDataBasePath()); // little hack to get absolute path.. moduleBuilder.addLibraryJars(libraryName, testDataBasePathFile.getAbsolutePath(), jarPaths); } protected final StrutsFacet createFacet() { final RunResult<StrutsFacet> runResult = new WriteCommandAction<StrutsFacet>(myProject) { protected void run(final Result<StrutsFacet> result) throws Throwable { String name = StrutsFacetType.INSTANCE.getPresentableName(); - final StrutsFacet facet = FacetManager.getInstance(myModule).addFacet(StrutsFacetType.INSTANCE, name, null); + final WebFacet webFacet = JavaeeUtil.addFacet(myModule, WebFacetType.INSTANCE); + final StrutsFacet facet = FacetManager.getInstance(myModule).addFacet(StrutsFacetType.INSTANCE, name, webFacet); result.setResult(facet); } }.execute(); final Throwable throwable = runResult.getThrowable(); if (throwable != null) { throw new RuntimeException("error setting up StrutsFacet", throwable); } return runResult.getResultObject(); } protected void tearDown() throws Exception { myFixture.tearDown(); myFixture = null; myModuleTestFixture = null; myProject = null; myModule = null; myFacet = null; super.tearDown(); } private void addToFileSet(final StrutsFileSet fileSet, @NonNls final String path) { final VirtualFile file; try { file = myFixture.copyFileToProject(path); } catch (IOException e) { throw new RuntimeException("error copying struts.xml from '" + path + "'", e); } assertNotNull("could not find file: '" + path + "'", file); fileSet.addFile(file); } protected void createStrutsFileSet(@NonNls final String... fileNames) { final StrutsFileSet fileSet = new StrutsFileSet("test", "test"); for (final String fileName : fileNames) { addToFileSet(fileSet, fileName); } final Set<StrutsFileSet> strutsFileSetSet = myFacet.getConfiguration().getFileSets(); strutsFileSetSet.clear(); strutsFileSetSet.add(fileSet); } } \ No newline at end of file
false
false
null
null
diff --git a/org.eclipse.b3.beelang.tests/src/org/eclipse/b3/beelang/junit/JUnitB3FileRunnerFactory.java b/org.eclipse.b3.beelang.tests/src/org/eclipse/b3/beelang/junit/JUnitB3FileRunnerFactory.java index 79777826..ca271950 100644 --- a/org.eclipse.b3.beelang.tests/src/org/eclipse/b3/beelang/junit/JUnitB3FileRunnerFactory.java +++ b/org.eclipse.b3.beelang.tests/src/org/eclipse/b3/beelang/junit/JUnitB3FileRunnerFactory.java @@ -1,215 +1,225 @@ /******************************************************************************* * Copyright (c) 2009, Cloudsmith Inc. * The code, documentation and other materials contained herein have been * licensed under the Eclipse Public License - v 1.0 by the copyright holder * listed above, as the Initial Contributor under such license. The text of * such license is available at www.eclipse.org. ******************************************************************************/ package org.eclipse.b3.beelang.junit; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.ArrayList; +import java.util.LinkedList; import java.util.List; import org.eclipse.b3.BeeLangRuntimeModule; import org.eclipse.b3.backend.core.B3Engine; import org.eclipse.b3.backend.core.B3EngineException; import org.eclipse.b3.backend.evaluator.b3backend.B3JavaImport; import org.eclipse.b3.backend.evaluator.b3backend.BExecutionContext; import org.eclipse.b3.backend.evaluator.b3backend.BFunction; import org.eclipse.b3.backend.evaluator.typesystem.TypeUtils; import org.eclipse.b3.beeLang.BeeModel; import org.eclipse.b3.beelang.tests.Activator; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.resource.ContentHandler; import org.eclipse.xtext.resource.XtextResource; import org.eclipse.xtext.resource.XtextResourceSet; import org.junit.runner.Description; import org.junit.runner.Runner; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; import org.junit.runners.ParentRunner; +import org.junit.runners.model.InitializationError; import com.google.inject.Guice; import com.google.inject.Injector; /** * <p> * A factory class for building JUnit 4 runners capable of executing B3 language functions as JUnit tests. A separate * runner is built for each of the <code>{@link B3Files}</code> defined for the class passed to the factory's * constructor. A runner built by this factory executes every B3 function which name start with the prefix of "test" * from the B3 file it was built for as a separate JUnit test. * </p> * * @author michal.ruzicka@cloudsmith.com * * @see B3Files * @see JUnitB3TestRunner */ class JUnitB3FileRunnerFactory { public static final String TEST_FUNCTION_PREFIX = "test"; protected static final Object[] EMPTY_PARAMETER_ARRAY = new Object[] {}; protected static final Type[] EMPTY_TYPE_ARRAY = new Type[] {}; protected class JUnitB3FileRunner extends ParentRunner<JUnitB3FileRunner.TestFunctionDescriptor> { protected class TestFunctionDescriptor { protected BFunction testFunction; protected Description testFunctionDescription; public TestFunctionDescriptor(BFunction function) { testFunction = function; testFunctionDescription = Description.createTestDescription(definitionClass, String.format("%s(%s)", function.getName(), b3FileName)); } public BFunction getFunction() { return testFunction; } public Description getDescription() { return testFunctionDescription; } } protected String b3FilePath; protected String b3FileName; protected ArrayList<TestFunctionDescriptor> testFunctionDescriptors; protected B3Engine b3Engine; public JUnitB3FileRunner(String b3File) throws Exception { super(definitionClass); if(b3File.charAt(0) != '/') b3File = '/' + b3File; URI b3FileURI = URI.createPlatformPluginURI(Activator.PLUGIN_ID + b3File, true); XtextResource resource = (XtextResource) beeLangResourceSet.createResource(b3FileURI, ContentHandler.UNSPECIFIED_CONTENT_TYPE); try { resource.load(null); } catch(IOException e) { throw new Exception("Failed to load B3 file: " + b3File, e); } // TODO: consult resource.getErrors() and report possible errors b3FilePath = b3File; b3FileName = b3FileURI.lastSegment(); BeeModel beeModel = (BeeModel) resource.getParseResult().getRootASTElement(); BExecutionContext b3Context = (b3Engine = new B3Engine()).getContext(); testFunctionDescriptors = new ArrayList<TestFunctionDescriptor>(); try { // Define all imports as constants for(Type type : beeModel.getImports()) { if(type instanceof B3JavaImport) { Class<?> klass = TypeUtils.getRaw(type); b3Context.defineValue(((B3JavaImport) type).getName(), klass, klass); } } // Define all functions and create descriptors of test functions for(BFunction function : beeModel.getFunctions()) { b3Context.defineFunction(function); String functionName = function.getName(); if(functionName.length() > TEST_FUNCTION_PREFIX.length() && functionName.startsWith(TEST_FUNCTION_PREFIX) && function.getParameterTypes().length == 0) testFunctionDescriptors.add(new TestFunctionDescriptor(function)); } } catch(B3EngineException e) { throw new Exception("Failed to initialize B3Engine in preparation for testing of: " + b3File, e); } } @Override protected String getName() { return b3FilePath; } @Override protected Description describeChild(TestFunctionDescriptor child) { return child.getDescription(); } @Override protected void runChild(TestFunctionDescriptor child, RunNotifier notifier) { Description childDescription = child.getDescription(); String childFunctionName = child.getFunction().getName(); notifier.fireTestStarted(childDescription); try { b3Engine.getContext().callFunction(childFunctionName, EMPTY_PARAMETER_ARRAY, EMPTY_TYPE_ARRAY); } catch(Throwable e) { notifier.fireTestFailure(new Failure(childDescription, e)); } finally { notifier.fireTestFinished(childDescription); } } @Override protected List<TestFunctionDescriptor> getChildren() { return testFunctionDescriptors; } } protected XtextResourceSet beeLangResourceSet; protected final Class<?> definitionClass; protected List<Runner> b3FileRunners; { Injector beeLangInjector = Guice.createInjector(new BeeLangRuntimeModule()); beeLangResourceSet = beeLangInjector.getProvider(XtextResourceSet.class).get(); } - public JUnitB3FileRunnerFactory(Class<?> klass) throws Throwable { + public JUnitB3FileRunnerFactory(Class<?> klass) throws InitializationError { definitionClass = klass; Annotation[] testClassAnnotations = klass.getAnnotations(); for(Annotation annotation : testClassAnnotations) { if(annotation instanceof B3Files) { createB3FileRunners(((B3Files) annotation).value()); return; } } - throw new Exception("No B3Files specified for class " + klass.getName()); + throw new InitializationError("No @B3Files annotation specified for class " + klass.getName()); } - protected void createB3FileRunners(String[] b3Files) throws Throwable { + protected void createB3FileRunners(String[] b3Files) throws InitializationError { ArrayList<Runner> runners = new ArrayList<Runner>(b3Files.length); + LinkedList<Throwable> errors = new LinkedList<Throwable>(); for(String b3File : b3Files) { - runners.add(new JUnitB3FileRunner(b3File)); + try { + runners.add(new JUnitB3FileRunner(b3File)); + } catch(Throwable t) { + errors.add(t); + } } + if(!errors.isEmpty()) + throw new InitializationError(errors); + b3FileRunners = runners; } public List<Runner> getB3FileRunners() { return b3FileRunners; } } diff --git a/org.eclipse.b3.beelang.tests/src/org/eclipse/b3/beelang/junit/JUnitB3TestRunner.java b/org.eclipse.b3.beelang.tests/src/org/eclipse/b3/beelang/junit/JUnitB3TestRunner.java index 29c21e05..05de0713 100644 --- a/org.eclipse.b3.beelang.tests/src/org/eclipse/b3/beelang/junit/JUnitB3TestRunner.java +++ b/org.eclipse.b3.beelang.tests/src/org/eclipse/b3/beelang/junit/JUnitB3TestRunner.java @@ -1,42 +1,43 @@ /******************************************************************************* * Copyright (c) 2009, Cloudsmith Inc. * The code, documentation and other materials contained herein have been * licensed under the Eclipse Public License - v 1.0 by the copyright holder * listed above, as the Initial Contributor under such license. The text of * such license is available at www.eclipse.org. ******************************************************************************/ package org.eclipse.b3.beelang.junit; import org.junit.runners.Suite; +import org.junit.runners.model.InitializationError; /** * <p> * The custom runner <code>JUnitB3TestRunner</code> is a wrapper around the functionality implemented in * <code>{@link JUnitB3FileRunnerFactory}</code> which makes it possible to run B3 language functions as JUnit tests. * </p> * * The runner is used as follows: * * <pre> * &#064;RunWith (JUnitB3TestRunner.class) * &#064;B3Files ( { &quot;/b3/basic.b3&quot;, &quot;/b3/advanced.b3&quot; }) * public class AllB3Tests { * } * </pre> * * @author michal.ruzicka@cloudsmith.com * * @see B3Files * @see JUnitB3FileRunnerFactory */ public class JUnitB3TestRunner extends Suite { /** * Only called reflectively. Do not use programmatically. */ - public JUnitB3TestRunner(Class<?> klass) throws Throwable { + public JUnitB3TestRunner(Class<?> klass) throws InitializationError { super(klass, new JUnitB3FileRunnerFactory(klass).getB3FileRunners()); } }
false
false
null
null
diff --git a/test/playRepository/GitRepositoryTest.java b/test/playRepository/GitRepositoryTest.java index 1a927e3c..802114a3 100644 --- a/test/playRepository/GitRepositoryTest.java +++ b/test/playRepository/GitRepositoryTest.java @@ -1,455 +1,455 @@ package playRepository; import models.Project; import models.PullRequest; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.MergeCommand; import org.eclipse.jgit.api.MergeResult; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.NoFilepatternException; import org.eclipse.jgit.lib.*; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevTree; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.treewalk.TreeWalk; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.List; import static org.fest.assertions.Assertions.assertThat; import static org.fest.assertions.Fail.fail; public class GitRepositoryTest { @Before public void before() { GitRepository.setRepoPrefix("resources/test/repo/git/"); GitRepository.setRepoForMergingPrefix("resources/test/repo/git-merging/"); } @After public void after() { rm_rf(new File(GitRepository.getRepoPrefix())); rm_rf(new File(GitRepository.getRepoForMergingPrefix())); } @Test public void gitRepository() throws Exception { // Given String userName = "yobi"; String projectName = "testProject"; // When GitRepository repo = new GitRepository(userName, projectName); // Then assertThat(repo).isNotNull(); } @Test public void create() throws Exception { // Given String userName = "yobi"; String projectName = "testProject"; GitRepository repo = new GitRepository(userName, projectName); // When repo.create(); // Then File file = new File(GitRepository.getRepoPrefix() + userName + "/" + projectName + ".git"); assertThat(file.exists()).isTrue(); file = new File(GitRepository.getRepoPrefix() + userName + "/" + projectName + ".git" + "/objects"); assertThat(file.exists()).isTrue(); file = new File(GitRepository.getRepoPrefix() + userName + "/" + projectName + ".git" + "/refs"); assertThat(file.exists()).isTrue(); // cleanup repo.close(); } @Test public void getPatch() throws IOException, NoFilepatternException, GitAPIException { // given String userName = "yobi"; String projectName = "testProject"; String wcPath = GitRepository.getRepoPrefix() + userName + "/" + projectName; String repoPath = wcPath + "/.git"; File repoDir = new File(repoPath); Repository repo = new RepositoryBuilder().setGitDir(repoDir).build(); repo.create(false); Git git = new Git(repo); String testFilePath = wcPath + "/readme.txt"; BufferedWriter out = new BufferedWriter(new FileWriter(testFilePath)); // when out.write("hello 1"); out.flush(); git.add().addFilepattern("readme.txt").call(); git.commit().setMessage("commit 1").call(); out.write("hello 2"); out.flush(); git.add().addFilepattern("readme.txt").call(); RevCommit commit = git.commit().setMessage("commit 2").call(); GitRepository gitRepo = new GitRepository(userName, projectName + "/"); String patch = gitRepo.getPatch(commit.getId().getName()); // then assertThat(patch).contains("-hello 1"); assertThat(patch).contains("+hello 1hello 2"); } @Test public void getHistory() throws IOException, NoFilepatternException, GitAPIException { // given String userName = "yobi"; String projectName = "testProject"; String wcPath = GitRepository.getRepoPrefix() + userName + "/" + projectName; String repoPath = wcPath + "/.git"; File repoDir = new File(repoPath); Repository repo = new RepositoryBuilder().setGitDir(repoDir).build(); repo.create(false); Git git = new Git(repo); String testFilePath = wcPath + "/readme.txt"; BufferedWriter out = new BufferedWriter(new FileWriter(testFilePath)); // when out.write("hello 1"); out.flush(); git.add().addFilepattern("readme.txt").call(); git.commit().setMessage("commit 1").call(); out.write("hello 2"); out.flush(); git.add().addFilepattern("readme.txt").call(); git.commit().setMessage("commit 2").call(); out.write("hello 3"); out.flush(); git.add().addFilepattern("readme.txt").call(); git.commit().setMessage("commit 3").call(); GitRepository gitRepo = new GitRepository(userName, projectName + "/"); List<Commit> history2 = gitRepo.getHistory(0, 2, "HEAD"); List<Commit> history5 = gitRepo.getHistory(0, 5, "HEAD"); // then assertThat(history2.size()).isEqualTo(2); assertThat(history2.get(0).getMessage()).isEqualTo("commit 3"); assertThat(history2.get(1).getMessage()).isEqualTo("commit 2"); assertThat(history5.size()).isEqualTo(3); assertThat(history5.get(0).getMessage()).isEqualTo("commit 3"); assertThat(history5.get(1).getMessage()).isEqualTo("commit 2"); assertThat(history5.get(2).getMessage()).isEqualTo("commit 1"); } @Test public void cloneRepository() throws Exception { // Given String userName = "whiteship"; String projectName = "testProject"; Project original = createProject(userName, projectName); Project fork = createProject("keesun", projectName); rm_rf(new File(GitRepository.getGitDirectory(original))); rm_rf(new File(GitRepository.getGitDirectory(fork))); GitRepository fromRepo = new GitRepository(userName, projectName); fromRepo.create(); // When String gitUrl = GitRepository.getGitDirectoryURL(original); GitRepository.cloneRepository(gitUrl, fork); // Then File file = new File(GitRepository.getGitDirectory(fork)); assertThat(file.exists()).isTrue(); } @Test public void cloneRepositoryWithNonBareMode() throws IOException, GitAPIException { // Given Project originProject = createProject("whiteship", "test"); rm_rf(new File(GitRepository.getGitDirectory(originProject))); new GitRepository(originProject.owner, originProject.name).create(); String cloneWorkingTreePath = GitRepository.getDirectoryForMerging(originProject.owner, originProject.name); rm_rf(new File(cloneWorkingTreePath)); // When Git.cloneRepository() .setURI(GitRepository.getGitDirectoryURL(originProject)) .setDirectory(new File(cloneWorkingTreePath)) .call(); // Then assertThat(new File(cloneWorkingTreePath).exists()).isTrue(); assertThat(new File(cloneWorkingTreePath + "/.git").exists()).isTrue(); Repository cloneRepository = new RepositoryBuilder() .setWorkTree(new File(cloneWorkingTreePath)) .setGitDir(new File(cloneWorkingTreePath + "/.git")) .build(); assertThat(cloneRepository.getFullBranch()).isEqualTo("refs/heads/master"); // When Git cloneGit = new Git(cloneRepository); // toProject를 clone 받은 워킹 디렉토리에서 테스트 파일 만들고 커밋하고 푸쉬하기 String readmeFileName = "readme.md"; String testFilePath = cloneWorkingTreePath + "/" + readmeFileName; BufferedWriter out = new BufferedWriter(new FileWriter(testFilePath)); out.write("hello 1"); out.flush(); cloneGit.add().addFilepattern(readmeFileName).call(); cloneGit.commit().setMessage("commit 1").call(); cloneGit.push().call(); // Then Repository originRepository = GitRepository.buildGitRepository(originProject); String readmeFileInClone = new String(getRawFile(cloneRepository, readmeFileName)); assertThat(readmeFileInClone).isEqualTo("hello 1"); String readmeFileInOrigin = new String(getRawFile(originRepository, readmeFileName)); assertThat(readmeFileInOrigin).isEqualTo("hello 1"); cloneRepository.close(); originRepository.close(); } @Ignore @Test public void findFileInfo() throws Exception { // Given String userName = "yobi"; String projectName = "testProject"; GitRepository repo = new GitRepository(userName, projectName); // When repo.findFileInfo("readme"); // Then } @Ignore @Test public void getRawFile() throws Exception { // Given String userName = "yobi"; String projectName = "testProject"; GitRepository repo = new GitRepository(userName, projectName); // When - repo.getRawFile("readme"); + repo.getRawFile("HEAD", "readme"); // Then } @Test public void buildCloneRepository() throws GitAPIException, IOException { // Given Project original = createProject("keesun", "test"); PullRequest pullRequest = createPullRequest(original); new GitRepository("keesun", "test").create(); // When Repository repository = GitRepository.buildCloneRepository(pullRequest); // Then assertThat(repository).isNotNull(); String repositoryWorkingDirectory = GitRepository.getDirectoryForMerging(original.owner, original.name); assertThat(repositoryWorkingDirectory).isNotNull(); String clonePath = "resources/test/repo/git-merging/keesun/test.git"; assertThat(repositoryWorkingDirectory).isEqualTo(clonePath); assertThat(new File(clonePath).exists()).isTrue(); assertThat(new File(clonePath + "/.git").exists()).isTrue(); } @Test public void deleteBranch() throws IOException, GitAPIException { // Given Project original = createProject("keesun", "test"); PullRequest pullRequest = createPullRequest(original); new GitRepository(original).create(); Repository repository = GitRepository.buildCloneRepository(pullRequest); Git git = new Git(repository); String branchName = "refs/heads/maste"; // When GitRepository.deleteBranch(repository, branchName); // Then List<Ref> refs = git.branchList().call(); for(Ref ref : refs) { if(ref.getName().equals(branchName)) { fail("deleting branch was failed"); } } } @Test public void fetch() throws IOException, GitAPIException { // Given Project original = createProject("keesun", "test"); PullRequest pullRequest = createPullRequest(original); new GitRepository(original).create(); Repository repository = GitRepository.buildCloneRepository(pullRequest); RevCommit commit = newCommit(original, repository, "readme.md", "hello 1", "commit 1"); new Git(repository).push().call(); // When String dstBranchName = "refs/heads/master-fetch"; GitRepository.fetch(repository, original, "refs/heads/master", dstBranchName); // Then ObjectId branch = repository.resolve(dstBranchName); assertThat(branch.getName()).isEqualTo(commit.getId().getName()); } private RevCommit newCommit(Project project, Repository repository, String fileName, String content, String message) throws IOException, GitAPIException { String workingTreePath = GitRepository.getDirectoryForMerging(project.owner, project.name); String testFilePath = workingTreePath + "/" + fileName; BufferedWriter out = new BufferedWriter(new FileWriter(testFilePath)); out.write(content); out.flush(); out.close(); Git git = new Git(repository); git.add().addFilepattern(fileName).call(); return git.commit().setMessage(message).call(); } @Test public void checkout() throws IOException, GitAPIException { // Given Project original = createProject("keesun", "test"); PullRequest pullRequest = createPullRequest(original); new GitRepository(original).create(); Repository repository = GitRepository.buildCloneRepository(pullRequest); // 커밋이 없으면 HEAD도 없어서 브랜치 만들 때 에러가 발생하기 때문에 일단 하나 커밋한다. newCommit(original, repository, "readme.md", "hello 1", "commit 1"); Git git = new Git(repository); String branchName = "new-branch"; git.branchCreate() .setName(branchName) .setForce(true) .call(); // When GitRepository.checkout(repository, branchName); // Then assertThat(repository.getFullBranch()).isEqualTo("refs/heads/" + branchName); } @Test public void merge() throws IOException, GitAPIException { // Given Project original = createProject("keesun", "test"); PullRequest pullRequest = createPullRequest(original); GitRepository gitRepository = new GitRepository(original); gitRepository.create(); Repository repository = GitRepository.buildCloneRepository(pullRequest); // master에 commit 1 추가 newCommit(original, repository, "readme.md", "hello 1", "commit 1"); // new-branch 생성 Git git = new Git(repository); String branchName = "new-branch"; git.branchCreate() .setName(branchName) .setForce(true) .call(); // new-branch 로 이동 GitRepository.checkout(repository, branchName); // new-branch에 commit 2 추가 String fileName = "hello.md"; String content = "hello 2"; newCommit(original, repository, fileName, content, "commit 2"); // master 로 이동 GitRepository.checkout(repository, "master"); // When GitRepository.merge(repository, branchName); // Then assertThat(new String(getRawFile(repository, fileName))).isEqualTo(content); gitRepository.close(); repository.close(); } @Test public void push() throws IOException, GitAPIException { // Given Project original = createProject("keesun", "test"); PullRequest pullRequest = createPullRequest(original); new GitRepository(original).create(); Repository repository = GitRepository.buildCloneRepository(pullRequest); // master에 commit 1 추가 String fileName = "readme.md"; String content = "hello 1"; newCommit(original, repository, fileName, content, "commit 1"); // When String branchName = "master"; GitRepository.push(repository, GitRepository.getGitDirectoryURL(original), branchName, branchName); // Then Repository originalRepo = new RepositoryBuilder() .setGitDir(new File(GitRepository.getGitDirectory(original))) .build(); assertThat(new String(getRawFile(originalRepo, fileName))).isEqualTo(content); originalRepo.close(); } private Project createProject(String owner, String name) { Project project = new Project(); project.owner = owner; project.name = name; return project; } private PullRequest createPullRequest(Project project) { PullRequest pullRequest = new PullRequest(); pullRequest.toProject = project; return pullRequest; } private void rm_rf(File file) { assert file != null; if (file.isDirectory()) { File[] list = file.listFiles(); assert list != null; for(int i = 0; i < list.length; i++){ rm_rf(list[i]); } } System.gc(); file.delete(); } private byte[] getRawFile(Repository repository, String path) throws IOException { RevTree tree = new RevWalk(repository).parseTree(repository.resolve(Constants.HEAD)); TreeWalk treeWalk = TreeWalk.forPath(repository, path, tree); if (treeWalk.isSubtree()) { return null; } else { return repository.open(treeWalk.getObjectId(0)).getBytes(); } } } \ No newline at end of file
true
false
null
null
diff --git a/src/SELMA/CompilerEntry.java b/src/SELMA/CompilerEntry.java index 56379e0..e756279 100644 --- a/src/SELMA/CompilerEntry.java +++ b/src/SELMA/CompilerEntry.java @@ -1,36 +1,37 @@ package SELMA; import SELMA.SELMATree.SR_Kind; import SELMA.SELMATree.SR_Type; import SELMA.SELMATree.SR_Func; public class CompilerEntry extends CheckerEntry { public int addr; public int val; public String signature; public CompilerEntry(SR_Type type, SR_Kind kind, int addr) { super(type, kind); this.addr = addr; } public CompilerEntry(SR_Type type, SR_Kind kind, int addr, SR_Func func) { super(type, kind, func); this.addr = addr; } public CompilerEntry setVal(String intval) { val = Integer.parseInt(intval); return this; } public CompilerEntry setBool(String bool) { val = bool.equals("true") ? 1 : 0; return this; } - public CompilerEntry setChar(char c) { - val = (int) c; + public CompilerEntry setChar(int c) { + val = c; + // System.err.println("Setting " + c + " on " + addr + " = " + val); return this; } }
true
false
null
null
diff --git a/commcare-api/src/main/java/org/ei/commcare/api/service/CommCareFormImportService.java b/commcare-api/src/main/java/org/ei/commcare/api/service/CommCareFormImportService.java index ecda2f2..81542a8 100644 --- a/commcare-api/src/main/java/org/ei/commcare/api/service/CommCareFormImportService.java +++ b/commcare-api/src/main/java/org/ei/commcare/api/service/CommCareFormImportService.java @@ -1,102 +1,102 @@ package org.ei.commcare.api.service; import com.google.gson.Gson; import com.google.gson.JsonParseException; import com.google.gson.annotations.SerializedName; import org.ei.commcare.api.contract.CommCareFormDefinition; import org.ei.commcare.api.contract.CommCareFormDefinitions; import org.ei.commcare.api.domain.CommCareFormContent; import org.ei.commcare.api.domain.CommcareForm; import org.ei.commcare.api.repository.AllExportTokens; import org.ei.commcare.api.util.CommCareHttpClient; import org.ei.commcare.api.util.CommCareHttpResponse; import org.ei.commcare.api.util.CommCareImportProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; @Service public class CommCareFormImportService { private final CommCareHttpClient httpClient; private CommCareFormDefinitions formDefinitions; private AllExportTokens allExportTokens; private static Logger logger = Logger.getLogger(CommCareFormImportService.class.toString()); @Autowired public CommCareFormImportService(AllExportTokens allExportTokens, CommCareHttpClient httpClient, CommCareImportProperties properties) { this.httpClient = httpClient; this.allExportTokens = allExportTokens; this.formDefinitions = properties.definitions(); } public List<CommcareForm> fetchForms() throws IOException { return processAllForms(fetchAllForms()); } private List<CommCareFormWithResponse> fetchAllForms() throws IOException { List<CommCareFormWithResponse> formWithResponses = new ArrayList<CommCareFormWithResponse>(); for (CommCareFormDefinition formDefinition : formDefinitions.definitions()) { String previousToken = allExportTokens.findByNameSpace(formDefinition.nameSpace()).value(); CommCareHttpResponse responseFromCommCareHQ = httpClient.get(formDefinition.url(previousToken), formDefinitions.userName(), formDefinitions.password()); if (responseFromCommCareHQ.hasValidExportToken()) { allExportTokens.updateToken(formDefinition.nameSpace(), responseFromCommCareHQ.tokenForNextExport()); formWithResponses.add(new CommCareFormWithResponse(formDefinition, responseFromCommCareHQ)); } } return formWithResponses; } private List<CommcareForm> processAllForms(List<CommCareFormWithResponse> careFormWithResponses) { List<CommcareForm> forms = new ArrayList<CommcareForm>(); for (CommCareFormWithResponse formWithResponse : careFormWithResponses) { CommCareFormDefinition definition = formWithResponse.formDefinition; CommCareHttpResponse response = formWithResponse.response; CommCareExportedForms exportedFormData; try { exportedFormData = new Gson().fromJson(response.contentAsString(), CommCareExportedForms.class); } catch (JsonParseException e) { throw new RuntimeException(response.contentAsString() + e); } for (List<String> formData : exportedFormData.formContents()) { forms.add(new CommcareForm(definition, new CommCareFormContent(exportedFormData.headers(), formData))); } } return forms; } private class CommCareFormWithResponse { private final CommCareFormDefinition formDefinition; private final CommCareHttpResponse response; public CommCareFormWithResponse(CommCareFormDefinition formDefinition, CommCareHttpResponse response) { this.formDefinition = formDefinition; this.response = response; } } private static class CommCareExportedForms { - @SerializedName("#.#") private CommCareExportedHeadersAndContent content; + @SerializedName("#") private CommCareExportedHeadersAndContent content; private static class CommCareExportedHeadersAndContent { private List<String> headers; private List<List<String>> rows; } public List<String> headers() { return content.headers; } public List<List<String>> formContents() { return content.rows; } } } diff --git a/commcare-api/src/test/java/org/ei/commcare/api/service/CommCareFormImportServiceTest.java b/commcare-api/src/test/java/org/ei/commcare/api/service/CommCareFormImportServiceTest.java index 9007367..d1d67ef 100644 --- a/commcare-api/src/test/java/org/ei/commcare/api/service/CommCareFormImportServiceTest.java +++ b/commcare-api/src/test/java/org/ei/commcare/api/service/CommCareFormImportServiceTest.java @@ -1,184 +1,184 @@ package org.ei.commcare.api.service; import org.apache.commons.io.IOUtils; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.CredentialsProvider; import org.apache.http.message.BasicHeader; import org.ei.commcare.api.domain.CommcareForm; import org.ei.commcare.api.domain.ExportToken; import org.ei.commcare.api.repository.AllExportTokens; import org.ei.commcare.api.util.CommCareHttpClient; import org.ei.commcare.api.util.CommCareHttpResponse; import org.ei.commcare.api.util.CommCareImportProperties; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import java.io.IOException; import java.util.*; import static junit.framework.Assert.assertEquals; import static org.ei.commcare.api.util.CommCareImportProperties.COMMCARE_EXPORT_DEFINITION_FILE; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.MockitoAnnotations.initMocks; import static org.powermock.api.mockito.PowerMockito.when; public class CommCareFormImportServiceTest { @Mock private CommCareHttpClient httpClient; @Mock private CredentialsProvider provider; @Mock private HttpResponse response; @Mock private AllExportTokens allExportTokens; @Before public void setUp() throws Exception { initMocks(this); } @Test public void shouldFetchOneFormWithTwoInstancesFromCommCare() throws Exception { String nameSpace = "http://openrosa.org/formdesigner/4FBE07FF-2434-40B3-B151-D2EBE2F4FB4F"; String urlOfExport = "https://www.commcarehq.org/a/abhilasha/reports/export/?export_tag=%22" + nameSpace + "%22&format=json&previous_export="; Properties properties = new Properties(); properties.setProperty(COMMCARE_EXPORT_DEFINITION_FILE, "/test-data/commcare-export.json"); when(allExportTokens.findByNameSpace(nameSpace)).thenReturn(new ExportToken(nameSpace, "")); when(httpClient.get(urlOfExport, "someUser@gmail.com", "somePassword")).thenReturn(formResponse(200, "/test-data/form.1.dump.json", "NEW-TOKEN")); CommCareFormImportService formImportService = new CommCareFormImportService(allExportTokens, httpClient, new CommCareImportProperties(properties)); List<CommcareForm> forms = formImportService.fetchForms(); verify(httpClient).get(urlOfExport, "someUser@gmail.com", "somePassword"); assertEquals(2, forms.size()); assertForm(forms.get(0), new String[]{"form-1-instance-1-value-1", "form-1-instance-1-value-2"}, "Registration"); assertForm(forms.get(1), new String[]{"form-1-instance-2-value-1", "form-1-instance-2-value-2"}, "Registration"); } @Test public void shouldFetchMultipleFormsWithMultipleInstancesFromCommCare() throws Exception { String nameSpaceOfFirstExport = "http://openrosa.org/formdesigner/UUID-OF-FIRST-FORM"; String nameSpaceOfSecondExport = "http://openrosa.org/formdesigner/UUID-OF-SECOND-FORM"; String urlOfFirstExport = "https://www.commcarehq.org/a/abhilasha/reports/export/?export_tag=%22" + nameSpaceOfFirstExport + "%22&format=json&previous_export="; String urlOfSecondExport = "https://www.commcarehq.org/a/abhilasha/reports/export/?export_tag=%22" + nameSpaceOfSecondExport + "%22&format=json&previous_export="; Properties properties = new Properties(); properties.setProperty(COMMCARE_EXPORT_DEFINITION_FILE, "/test-data/commcare-export-with-two-urls.json"); when(allExportTokens.findByNameSpace(nameSpaceOfFirstExport)).thenReturn(new ExportToken(nameSpaceOfFirstExport, "")); when(httpClient.get(urlOfFirstExport, "someUser@gmail.com", "somePassword")).thenReturn(formResponse(200, "/test-data/form.1.dump.json", "NEW-TOKEN")); when(allExportTokens.findByNameSpace(nameSpaceOfSecondExport)).thenReturn(new ExportToken(nameSpaceOfSecondExport, "")); when(httpClient.get(urlOfSecondExport, "someUser@gmail.com", "somePassword")).thenReturn(formResponse(200, "/test-data/form.2.dump.json", "NEW-TOKEN")); CommCareFormImportService formImportService = new CommCareFormImportService(allExportTokens, httpClient, new CommCareImportProperties(properties)); List<CommcareForm> forms = formImportService.fetchForms(); verify(httpClient).get(urlOfFirstExport, "someUser@gmail.com", "somePassword"); verify(httpClient).get(urlOfSecondExport, "someUser@gmail.com", "somePassword"); verify(allExportTokens).updateToken(nameSpaceOfFirstExport, "NEW-TOKEN"); verify(allExportTokens).updateToken(nameSpaceOfSecondExport, "NEW-TOKEN"); assertEquals(4, forms.size()); assertForm(forms.get(0), new String[]{"form-1-instance-1-value-1", "form-1-instance-1-value-2"}, "Registration"); assertForm(forms.get(1), new String[]{"form-1-instance-2-value-1", "form-1-instance-2-value-2"}, "Registration"); assertForm(forms.get(2), new String[]{"form-2-instance-1-value-1", "form-2-instance-1-value-2"}, "SomeOtherForm"); assertForm(forms.get(3), new String[]{"form-2-instance-2-value-1", "form-2-instance-2-value-2"}, "SomeOtherForm"); } @Test public void shouldUseURLWithoutPreviousTokenWhenThereIsNoToken() throws Exception { String nameSpace = "http://openrosa.org/formdesigner/4FBE07FF-2434-40B3-B151-D2EBE2F4FB4F"; String urlOfExport = "https://www.commcarehq.org/a/abhilasha/reports/export/?export_tag=%22" + nameSpace + "%22&format=json&previous_export="; Properties properties = new Properties(); properties.setProperty(COMMCARE_EXPORT_DEFINITION_FILE, "/test-data/commcare-export.json"); when(allExportTokens.findByNameSpace(nameSpace)).thenReturn(new ExportToken(nameSpace, "")); when(httpClient.get(urlOfExport, "someUser@gmail.com", "somePassword")).thenReturn(formResponse(200, "/test-data/form.1.dump.json", "NEW-TOKEN")); CommCareFormImportService formImportService = new CommCareFormImportService(allExportTokens, httpClient, new CommCareImportProperties(properties)); formImportService.fetchForms(); verify(httpClient).get(urlOfExport, "someUser@gmail.com", "somePassword"); } @Test public void shouldUseURLWithPreviousTokenWhenThereIsAToken() throws Exception { String nameSpace = "http://openrosa.org/formdesigner/4FBE07FF-2434-40B3-B151-D2EBE2F4FB4F"; String urlOfExport = "https://www.commcarehq.org/a/abhilasha/reports/export/?export_tag=%22" + nameSpace + "%22&format=json&previous_export=OLD-TOKEN"; Properties properties = new Properties(); properties.setProperty(COMMCARE_EXPORT_DEFINITION_FILE, "/test-data/commcare-export.json"); when(allExportTokens.findByNameSpace(nameSpace)).thenReturn(new ExportToken(nameSpace, "OLD-TOKEN")); when(httpClient.get(urlOfExport, "someUser@gmail.com", "somePassword")).thenReturn(formResponse(200, "/test-data/form.1.dump.json", "NEW-TOKEN")); CommCareFormImportService formImportService = new CommCareFormImportService(allExportTokens, httpClient, new CommCareImportProperties(properties)); formImportService.fetchForms(); verify(httpClient).get(urlOfExport, "someUser@gmail.com", "somePassword"); } @Test public void shouldSaveTheExportTokenAfterFetchingData() throws Exception { String nameSpace = "http://openrosa.org/formdesigner/4FBE07FF-2434-40B3-B151-D2EBE2F4FB4F"; String urlOfExport = "https://www.commcarehq.org/a/abhilasha/reports/export/?export_tag=%22" + nameSpace + "%22&format=json&previous_export=OLD-TOKEN"; Properties properties = new Properties(); properties.setProperty(COMMCARE_EXPORT_DEFINITION_FILE, "/test-data/commcare-export.json"); when(allExportTokens.findByNameSpace(nameSpace)).thenReturn(new ExportToken(nameSpace, "OLD-TOKEN")); when(httpClient.get(urlOfExport, "someUser@gmail.com", "somePassword")).thenReturn(formResponse(200, "/test-data/form.1.dump.json", "NEW-TOKEN")); CommCareFormImportService formImportService = new CommCareFormImportService(allExportTokens, httpClient, new CommCareImportProperties(properties)); formImportService.fetchForms(); verify(allExportTokens).updateToken(nameSpace, "NEW-TOKEN"); } @Test public void shouldNotProcessFormOrUpdateTokenWhenResponseSaysThatThereIsNoNewData() throws Exception { String nameSpace = "http://openrosa.org/formdesigner/4FBE07FF-2434-40B3-B151-D2EBE2F4FB4F"; String urlOfExport = "https://www.commcarehq.org/a/abhilasha/reports/export/?export_tag=%22" + nameSpace + "%22&format=json&previous_export=OLD-TOKEN"; Properties properties = new Properties(); properties.setProperty(COMMCARE_EXPORT_DEFINITION_FILE, "/test-data/commcare-export.json"); when(allExportTokens.findByNameSpace(nameSpace)).thenReturn(new ExportToken(nameSpace, "OLD-TOKEN")); when(httpClient.get(urlOfExport, "someUser@gmail.com", "somePassword")).thenReturn(formResponse(302, "/test-data/form.with.empty.data.json", null)); CommCareFormImportService formImportService = new CommCareFormImportService(allExportTokens, httpClient, new CommCareImportProperties(properties)); List<CommcareForm> forms = formImportService.fetchForms(); assertThat(forms.size(), is(0)); verify(allExportTokens).findByNameSpace(nameSpace); verifyNoMoreInteractions(allExportTokens); } private CommCareHttpResponse formResponse(int statusCode, String jsonDump, String newTokenValue) throws IOException { List<Header> headers = new ArrayList<Header>(); headers.add(new BasicHeader("X-Abc-Header", "Def")); if (newTokenValue != null) { headers.add(new BasicHeader("X-CommCareHQ-Export-Token", newTokenValue)); } return new CommCareHttpResponse(statusCode, headers.toArray(new Header[0]), IOUtils.toByteArray(getClass().getResourceAsStream(jsonDump))); } private void assertForm(CommcareForm actualForm, String[] expectedValuesOfForm, String formName) { assertEquals(actualForm.definition().name(), formName); HashMap<String, String> mapping = new HashMap<String, String>(); - mapping.put("header.col.1", "FirstValue"); - mapping.put("header.col.2", "SecondValue"); + mapping.put("header|col|1", "FirstValue"); + mapping.put("header|col|2", "SecondValue"); Map<String,String> data = actualForm.content().getValuesOfFieldsSpecifiedByPath(mapping); assertEquals(2, data.size()); assertEquals(expectedValuesOfForm[0], data.get("FirstValue")); assertEquals(expectedValuesOfForm[1], data.get("SecondValue")); } } diff --git a/drishti-web/src/main/java/org/ei/drishti/web/listener/ApplicationStartupListener.java b/drishti-web/src/main/java/org/ei/drishti/web/listener/ApplicationStartupListener.java index bc4a04a..0d2d4f9 100644 --- a/drishti-web/src/main/java/org/ei/drishti/web/listener/ApplicationStartupListener.java +++ b/drishti-web/src/main/java/org/ei/drishti/web/listener/ApplicationStartupListener.java @@ -1,22 +1,25 @@ package org.ei.drishti.web.listener; import org.ei.drishti.scheduler.CommCareScheduler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; @Component public class ApplicationStartupListener implements ApplicationListener<ContextRefreshedEvent> { + public static final String APPLICATION_ID = "org.springframework.web.context.WebApplicationContext:/drishti/drishti"; private final CommCareScheduler scheduler; @Autowired public ApplicationStartupListener(CommCareScheduler scheduler) { this.scheduler = scheduler; } @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { - scheduler.startTimedScheduler(); + if (APPLICATION_ID.equals(contextRefreshedEvent.getApplicationContext().getId())) { + scheduler.startTimedScheduler(); + } } }
false
false
null
null
diff --git a/src/backend/Simulation.java b/src/backend/Simulation.java index 2264f32..a8c7db1 100644 --- a/src/backend/Simulation.java +++ b/src/backend/Simulation.java @@ -1,98 +1,98 @@ package backend; import java.io.File; import java.util.ArrayList; import java.util.concurrent.CopyOnWriteArrayList; import math.Vec; import backend.environment.Element; import backend.environment.Obstacle; import backend.environment.Waypoint; public class Simulation extends Thread { public CopyOnWriteArrayList<Element> elements; public HeightMap hm = null; private ArrayList<Object> snapshots; public int timeStep = 20, stepsPerSave = 10; private volatile int time = 0, totalTime = 0; public boolean isRunning = false; public Simulation() { elements = new CopyOnWriteArrayList<Element>(); //we add some waypoints for testing purposes - Waypoint prev = null, first = null; + /*Waypoint prev = null, first = null; for(int i = 0; i < 10; i++) { Waypoint cur = new Waypoint(new Vec(Math.random()*1000-500, Math.random()*1000-500)); if(prev != null) prev.setTarget(cur); if(first == null) first = cur; prev = cur; elements.add(cur); } if(prev != null && first != null && prev != first) - prev.setTarget(first); + prev.setTarget(first);*/ //create an obstacle - /*elements.add(new Obstacle( + elements.add(new Obstacle( new Waypoint(50, 0), new Waypoint(60, 50), new Waypoint(0, 100), new Waypoint(0, 0) - ));*/ + )); snapshots = new ArrayList<Object>(); hm = new HeightMap(new File("./maps/GC2.map")); setName("Simulation"); //hm = new HeightMap(); } public void run() { try { while(true) { Thread.sleep(timeStep); if(!isRunning) continue; boolean upTT = totalTime <= time; time += timeStep; if(upTT) totalTime = time; if(time == totalTime && time % (timeStep*stepsPerSave) == 0) { snapshots.add(elements.clone()); } for(Element e : elements) e.calculateUpdate(elements); for(Element e : elements) e.update(); } } catch(InterruptedException ie) {} } public void setTime(int t) { time = Math.max(t - t%timeStep, 0); } public void setTotalTime(int t) { totalTime = Math.max(t - t%timeStep, 0); } public int getTime() { return time; } public int getTotalTime() { return totalTime; } public void loadHeightMap(File map) { hm = new HeightMap(map); } public void setHeightMap(HeightMap hm) { this.hm = hm; } } diff --git a/src/backend/environment/Prey.java b/src/backend/environment/Prey.java index 80851b4..507f12f 100644 --- a/src/backend/environment/Prey.java +++ b/src/backend/environment/Prey.java @@ -1,174 +1,174 @@ package backend.environment; import java.util.HashMap; import java.util.List; import math.Vec; public class Prey extends Animal { Waypoint previousTarget = null; public Prey(Prey other) { super(other); } public Prey(Vec position, Vec velocity) { super(position, velocity); } public Prey() { super(); } public Prey(double x, double y, double xvel, double yvel, double size) { super(x,y,xvel,yvel,size); } public double weighted(double x) { return Math.pow(x, 3)*4+0.5; } public void setTarget(Waypoint t) { previousTarget = getTarget(); super.setTarget(t); } /* Here we have two general approaches when dealing with multiple vectors: * 1. take a weighted average of the vectors * 2. use an accumulator: order the vectors by priority, start adding them up and when the * total length exceeds some length limit, stop adding and truncate * * here we have a number of sources of vectors: * 1. collision avoidance pushes the prey away from fellow prey * 2. velocity matching makes the prey try and match it's fellow prey member's velocities (to go in the same direction) * 3. flock centering pulls the prey towards all the other prey members * * //A total source vector for each of these sources is calculated using weighted averaging. Then the three vectors are placed in * //an accumulator to find the final velocity. * We used to use an accumulator, now we take an "informed weighted sum" of the weighted averages. To understand what I mean by "informed" * consider the case where we weight collisionAvoidance 0.2, flockCentering 0.2, velocityMatching 0.1 and predatorAvoidance 0.5. * Now if there were no predator's to avoid, then the other factors should make a total weighting of 1 and not 0.5. This "accounting for * absent impulses" is what we understand as "informed". * * Note: Collision avoidance and flock centering aren't linearly dependent on the distance of the other prey. */ public void calculateUpdate(List<Element> influences) { //calculate the sums Vec collisionAvoidance = new Vec(), velocityMatching = new Vec(), flockCentering = new Vec(), predatorAvoidance = new Vec(), waypointAttraction = new Vec(), obstacleAvoidance = new Vec(); /* obstacleAvoidance has a dynamic weight. this is * because we can't afford to EVER run into obstacles. */ double collisionAvoidanceWeight = 0.15, velocityMatchingWeight = 0.1, flockCenteringWeight = 0.15, predatorAvoidanceWeight = 0.4, waypointAttractionWeight = 0.2; int neighbourhoodCount = 0, predatorCount = 0, obstacleCount = 0; HashMap<Waypoint, Integer> flockTargets = new HashMap<Waypoint, Integer>(); for(Element e : influences) { if(e instanceof Obstacle) { Vec mostLeft = null, mostRight = null; double mostLeftAngle = 0, mostRightAngle = 0; Vec dir = velocity.unit(); for(Waypoint w : (Obstacle)e) { //get the cos of the angle between this waypoint and the dir vector Vec wdir = w.getPosition().minus(getPosition()); double dot = dir.dot(wdir.unit()); //this will be in [-1,1] dot = 1-(dot+1)/2; //now it's in [0,1] with 0 being 0 degrees and 1 being 180 //figure out which side (left or right) this angle is on dot *= dir.crossCompare(wdir); System.out.println(dot); if(mostLeft == null || mostLeftAngle > dot) { mostLeft = wdir; mostLeftAngle = dot; } if(mostRight == null || mostRightAngle < dot) { mostRight = wdir; mostRightAngle = dot; } } System.out.println(mostLeft + " " + mostRight + "\n"); if(mostLeft != null || mostRight != null) { - obstacleAvoidance = (Math.abs(mostLeftAngle) > Math.abs(mostRightAngle) ? mostLeft : mostRight).unit(); + obstacleAvoidance = (Math.abs(mostLeftAngle) < Math.abs(mostRightAngle) ? mostLeft : mostRight).unit(); obstacleCount++; } } else { Vec dir = e.getPosition().minus(getPosition()); if(dir.size() > 0 && dir.size() <= getRadius()) { if(e instanceof Prey) { neighbourhoodCount ++; collisionAvoidance = collisionAvoidance.plus(dir.unit().mult(Math.pow((getRadius()-dir.size())/getRadius(),1)).neg()); //this needs to be fixed, it's very haxxy that I must divide by e.getMaxSpeed() to get the truncated-to-unit vector, e.velocity velocityMatching = velocityMatching.plus(e.getVelocity().mult(1.0/e.getMaxSpeed())); flockCentering = flockCentering.plus(dir.unit().mult(Math.pow(dir.size()/getRadius(),1))); //take target suggestions from flock members who are in front if(e.getPosition().minus(getPosition()).dot(velocity) > 0) { Integer count = flockTargets.get(e.getTarget()); count = (count == null ? 0 : count) + 1; flockTargets.put(e.getTarget(), count); } } else if(e instanceof Predator) { predatorCount ++; predatorAvoidance = predatorAvoidance.plus(dir.unit().mult(Math.pow((getRadius()-dir.size())/getRadius(), 1.0/3)).neg()); } } } } if(getTarget() != null) { waypointAttraction = target.getPosition().minus(getPosition()).truncate(1); //if we reach the waypoint we start moving to the next one if(getPosition().minus(getTarget().getPosition()).size() < getSize()+getTarget().getSize()) setTarget(getTarget().getTarget()); //otherwise we see if the majority of the flock has updated their target else { Waypoint mVote = null; double flockCount = 0, totalFlock = 0; for(Waypoint w : flockTargets.keySet()) { if(w != previousTarget && flockTargets.get(w) > flockCount) { flockCount = flockTargets.get(w); mVote = w; } totalFlock += flockTargets.get(w); } if(mVote != null) { /* if we are sufficiently close to the waypoint and sufficiently many flock * members have started towards the next, then we can move to the next one */ if(flockCount/totalFlock > 0.5 && getPosition().minus(getTarget().getPosition()).size() < getTarget().getRadius()*0.5) setTarget(mVote); } } } //take the average weighting if(predatorCount > 0) predatorAvoidance = predatorAvoidance.mult(1.0/predatorCount); if(neighbourhoodCount > 0) { collisionAvoidance = collisionAvoidance.mult(1.0/neighbourhoodCount); velocityMatching = velocityMatching.mult(1.0/neighbourhoodCount); flockCentering = flockCentering.mult(1.0/neighbourhoodCount); } if(obstacleCount > 0) obstacleAvoidance = obstacleAvoidance.mult(1.0/obstacleCount); //if(waypointCount > 0) waypointAttraction = waypointAttraction.mult(1.0/waypointCount); //now perform accumulation\ /*Vec ret = new Vec(predatorAvoidance); if(ret.size() < 1) ret = ret.plus(collisionAvoidance).plus(flockCentering).mult(0.5); if(ret.size() < 1) ret = ret.plus(velocityMatching);*/ Vec ret = predatorAvoidance.mult(predatorAvoidanceWeight) .plus(collisionAvoidance.mult(collisionAvoidanceWeight) .plus(flockCentering.mult(flockCenteringWeight) .plus(velocityMatching.mult(velocityMatchingWeight) .plus(waypointAttraction.mult(waypointAttractionWeight))))) .mult(1.0/(predatorAvoidanceWeight+collisionAvoidanceWeight+flockCenteringWeight+velocityMatchingWeight+waypointAttractionWeight)); velocity = velocity.plus(ret.truncate(1)).plus(obstacleAvoidance.mult(10)).truncate(1); } public Object clone() { return new Prey(this); } }
false
false
null
null
diff --git a/wiki30-realtime-wysiwyg-plugin/src/main/java/org/xwiki/gwt/wysiwyg/client/plugin/symbol/RTSymbolPicker.java b/wiki30-realtime-wysiwyg-plugin/src/main/java/org/xwiki/gwt/wysiwyg/client/plugin/symbol/RTSymbolPicker.java index 12c95a8..0cc502e 100644 --- a/wiki30-realtime-wysiwyg-plugin/src/main/java/org/xwiki/gwt/wysiwyg/client/plugin/symbol/RTSymbolPicker.java +++ b/wiki30-realtime-wysiwyg-plugin/src/main/java/org/xwiki/gwt/wysiwyg/client/plugin/symbol/RTSymbolPicker.java @@ -1,387 +1,393 @@ /* * 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.symbol; import org.xwiki.gwt.user.client.ui.CompositeDialogBox; import org.xwiki.gwt.wysiwyg.client.Images; import org.xwiki.gwt.wysiwyg.client.Strings; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.user.client.ui.Image; /** * A popup panel which allows you to pick a symbol from a symbol palette by clicking on that symbol. * * @version $Id: 604d7dde909a34a4d409544fd17b8553954f78fe $ */ public class RTSymbolPicker extends CompositeDialogBox implements SelectionHandler<String> { /** * The default list of symbols. */ private static final Object[][] RT_SYMBOLS = { {"&amp;", "\u0026", "&#38;", true, "ampersand"}, - {"&quot;", "\\u0022", "&#34;", true, "quotation mark"}, +// {"&quot;", "\u0022", "&#34;", true, "quotation mark"}, + {"&quot;", "\"", "&#34;", true, "quotation mark"}, // finance {"&cent;", "\u00A2", "&#162;", true, "cent sign"}, {"&euro;", "\u20AC", "&#8364;", true, "euro sign"}, {"&pound;", "\u00A3", "&#163;", true, "pound sign"}, {"&yen;", "\u00A5", "&#165;", true, "yen sign"}, // signs {"&copy;", "\u00A9", "&#169;", true, "copyright sign"}, {"&reg;", "\u00AE", "&#174;", true, "registered sign"}, {"&trade;", "\u2122", "&#8482;", true, "trade mark sign"}, {"&permil;", "\u2030", "&#8240;", true, "per mille sign"}, {"&micro;", "\u00B5", "&#181;", true, "micro sign"}, {"&middot;", "\u00B7", "&#183;", true, "middle dot"}, {"&bull;", "\u2022", "&#8226;", true, "bullet"}, {"&hellip;", "\u2026", "&#8230;", true, "three dot leader"}, {"&prime;", "\u2032", "&#8242;", true, "minutes / feet"}, {"&Prime;", "\u2033", "&#8243;", true, "seconds / inches"}, {"&sect;", "\u00A7", "&#167;", true, "section sign"}, {"&para;", "\u00B6", "&#182;", true, "paragraph sign"}, {"&szlig;", "\u00DF", "&#223;", true, "sharp s / ess-zed"}, // quotations {"&lsaquo;", "\u2039", "&#8249;", true, "single left-pointing angle quotation mark"}, {"&rsaquo;", "\u203A", "&#8250;", true, "single right-pointing angle quotation mark"}, {"&laquo;", "\u00AB", "&#171;", true, "left pointing guillemet"}, {"&raquo;", "\u00BB", "&#187;", true, "right pointing guillemet"}, {"&lsquo;", "\u2018", "&#8216;", true, "left single quotation mark"}, {"&rsquo;", "\u2019", "&#8217;", true, "right single quotation mark"}, {"&ldquo;", "\u201C", "&#8220;", true, "left double quotation mark"}, {"&rdquo;", "\u201D", "&#8221;", true, "right double quotation mark"}, {"&sbquo;", "\u201A", "&#8218;", true, "single low-9 quotation mark"}, {"&bdquo;", "\u201E", "&#8222;", true, "double low-9 quotation mark"}, {"&lt;", "\u003C", "&#60;", true, "less-than sign"}, {"&gt;", "\u003E", "&#62;", true, "greater-than sign"}, {"&le;", "\u2264", "&#8804;", true, "less-than or equal to"}, {"&ge;", "\u2265", "&#8805;", true, "greater-than or equal to"}, {"&ndash;", "\u2013", "&#8211;", true, "en dash"}, {"&mdash;", "\u2014", "&#8212;", true, "em dash"}, {"&macr;", "\u00AF", "&#175;", true, "macron"}, {"&oline;", "\u203E", "&#8254;", true, "overline"}, {"&curren;", "\u00A4", "&#164;", true, "currency sign"}, {"&brvbar;", "\u00A6", "&#166;", true, "broken bar"}, {"&uml;", "\u00A8", "&#168;", true, "diaeresis"}, {"&iexcl;", "\u00A1", "&#161;", true, "inverted exclamation mark"}, {"&iquest;", "\u00BF", "&#191;", true, "turned question mark"}, {"&circ;", "\u02C6", "&#710;", true, "circumflex accent"}, {"&tilde;", "\u02DC", "&#732;", true, "small tilde"}, {"&deg;", "\u00B0", "&#176;", true, "degree sign"}, {"&minus;", "\u2212", "&#8722;", true, "minus sign"}, {"&plusmn;", "\u00B1", "&#177;", true, "plus-minus sign"}, {"&divide;", "\u00F7", "&#247;", true, "division sign"}, {"&frasl;", "\u2044", "&#8260;", true, "fraction slash"}, {"&times;", "\u00D7", "&#215;", true, "multiplication sign"}, {"&sup1;", "\u00B9", "&#185;", true, "superscript one"}, {"&sup2;", "\u00B2", "&#178;", true, "superscript two"}, {"&sup3;", "\u00B3", "&#179;", true, "superscript three"}, {"&frac14;", "\u00BC", "&#188;", true, "fraction one quarter"}, {"&frac12;", "\u00BD", "&#189;", true, "fraction one half"}, {"&frac34;", "\u00BE", "&#190;", true, "fraction three quarters"}, // math / logical {"&fnof;", "\u0192", "&#402;", true, "function / florin"}, {"&int;", "\u222B", "&#8747;", true, "integral"}, {"&sum;", "\u2211", "&#8721;", true, "n-ary sumation"}, {"&infin;", "\u221E", "&#8734;", true, "infinity"}, {"&radic;", "\u221A", "&#8730;", true, "square root"}, {"&sim;", "\u223C", "&#8764;", false, "similar to"}, {"&cong;", "\u2245", "&#8773;", false, "approximately equal to"}, {"&asymp;", "\u2248", "&#8776;", true, "almost equal to"}, {"&ne;", "\u2260", "&#8800;", true, "not equal to"}, {"&equiv;", "\u2261", "&#8801;", true, "identical to"}, {"&isin;", "\u2208", "&#8712;", false, "element of"}, {"&notin;", "\u2209", "&#8713;", false, "not an element of"}, {"&ni;", "\u220B", "&#8715;", false, "contains as member"}, {"&prod;", "\u220F", "&#8719;", true, "n-ary product"}, {"&and;", "\u2227", "&#8743;", false, "logical and"}, {"&or;", "\u2228", "&#8744;", false, "logical or"}, {"&not;", "\u00AC", "&#172;", true, "not sign"}, {"&cap;", "\u2229", "&#8745;", true, "intersection"}, {"&cup;", "\u222A", "&#8746;", false, "union"}, {"&part;", "\u2202", "&#8706;", true, "partial differential"}, {"&forall;", "\u2200", "&#8704;", false, "for all"}, {"&exist;", "\u2203", "&#8707;", false, "there exists"}, {"&empty;", "\u2205", "&#8709;", false, "diameter"}, {"&nabla;", "\u2207", "&#8711;", false, "backward difference"}, {"&lowast;", "\u2217", "&#8727;", false, "asterisk operator"}, {"&prop;", "\u221D", "&#8733;", false, "proportional to"}, {"&ang;", "\u2220", "&#8736;", false, "angle"}, // undefined {"&acute;", "\u00B4", "&#180;", true, "acute accent"}, {"&cedil;", "\u00B8", "&#184;", true, "cedilla"}, {"&ordf;", "\u00AA", "&#170;", true, "feminine ordinal indicator"}, {"&ordm;", "\u00BA", "&#186;", true, "masculine ordinal indicator"}, {"&dagger;", "\u2020", "&#8224;", true, "dagger"}, {"&Dagger;", "\u2021", "&#8225;", true, "double dagger"}, // alphabetical special chars {"&Agrave;", "\u00C0", "&#192;", true, "A - grave"}, {"&Aacute;", "\u00C1", "&#193;", true, "A - acute"}, {"&Acirc;", "\u00C2", "&#194;", true, "A - circumflex"}, {"&Atilde;", "\u00C3", "&#195;", true, "A - tilde"}, {"&Auml;", "\u00C4", "&#196;", true, "A - diaeresis"}, {"&Aring;", "\u00C5", "&#197;", true, "A - ring above"}, {"&AElig;", "\u00C6", "&#198;", true, "ligature AE"}, {"&Ccedil;", "\u00C7", "&#199;", true, "C - cedilla"}, {"&Egrave;", "\u00C8", "&#200;", true, "E - grave"}, {"&Eacute;", "\u00C9", "&#201;", true, "E - acute"}, {"&Ecirc;", "\u00CA", "&#202;", true, "E - circumflex"}, {"&Euml;", "\u00CB", "&#203;", true, "E - diaeresis"}, {"&Igrave;", "\u00CC", "&#204;", true, "I - grave"}, {"&Iacute;", "\u00CD", "&#205;", true, "I - acute"}, {"&Icirc;", "\u00CE", "&#206;", true, "I - circumflex"}, {"&Iuml;", "\u00CF", "&#207;", true, "I - diaeresis"}, {"&ETH;", "\u00D0", "&#208;", true, "ETH"}, {"&Ntilde;", "\u00D1", "&#209;", true, "N - tilde"}, {"&Ograve;", "\u00D2", "&#210;", true, "O - grave"}, {"&Oacute;", "\u00D3", "&#211;", true, "O - acute"}, {"&Ocirc;", "\u00D4", "&#212;", true, "O - circumflex"}, {"&Otilde;", "\u00D5", "&#213;", true, "O - tilde"}, {"&Ouml;", "\u00D6", "&#214;", true, "O - diaeresis"}, {"&Oslash;", "\u00D8", "&#216;", true, "O - slash"}, {"&OElig;", "\u0152", "&#338;", true, "ligature OE"}, {"&Scaron;", "\u0160", "&#352;", true, "S - caron"}, {"&Ugrave;", "\u00D9", "&#217;", true, "U - grave"}, {"&Uacute;", "\u00DA", "&#218;", true, "U - acute"}, {"&Ucirc;", "\u00DB", "&#219;", true, "U - circumflex"}, {"&Uuml;", "\u00DC", "&#220;", true, "U - diaeresis"}, {"&Yacute;", "\u00DD", "&#221;", true, "Y - acute"}, {"&Yuml;", "\u0178", "&#376;", true, "Y - diaeresis"}, {"&THORN;", "\u00DE", "&#222;", true, "THORN"}, {"&agrave;", "\u00E0", "&#224;", true, "a - grave"}, {"&aacute;", "\u00E1", "&#225;", true, "a - acute"}, {"&acirc;", "\u00E2", "&#226;", true, "a - circumflex"}, {"&atilde;", "\u00E3", "&#227;", true, "a - tilde"}, {"&auml;", "\u00E4", "&#228;", true, "a - diaeresis"}, {"&aring;", "\u00E5", "&#229;", true, "a - ring above"}, {"&aelig;", "\u00E6", "&#230;", true, "ligature ae"}, {"&ccedil;", "\u00E7", "&#231;", true, "c - cedilla"}, {"&egrave;", "\u00E8", "&#232;", true, "e - grave"}, {"&eacute;", "\u00E9", "&#233;", true, "e - acute"}, {"&ecirc;", "\u00EA", "&#234;", true, "e - circumflex"}, {"&euml;", "\u00EB", "&#235;", true, "e - diaeresis"}, {"&igrave;", "\u00EC", "&#236;", true, "i - grave"}, {"&iacute;", "\u00ED", "&#237;", true, "i - acute"}, {"&icirc;", "\u00EE", "&#238;", true, "i - circumflex"}, {"&iuml;", "\u00EF", "&#239;", true, "i - diaeresis"}, {"&eth;", "\u00F0", "&#240;", true, "eth"}, {"&ntilde;", "\u00F1", "&#241;", true, "n - tilde"}, {"&ograve;", "\u00F2", "&#242;", true, "o - grave"}, {"&oacute;", "\u00F3", "&#243;", true, "o - acute"}, {"&ocirc;", "\u00F4", "&#244;", true, "o - circumflex"}, {"&otilde;", "\u00F5", "&#245;", true, "o - tilde"}, {"&ouml;", "\u00F6", "&#246;", true, "o - diaeresis"}, {"&oslash;", "\u00F8", "&#248;", true, "o slash"}, {"&oelig;", "\u0153", "&#339;", true, "ligature oe"}, {"&scaron;", "\u0161", "&#353;", true, "s - caron"}, {"&ugrave;", "\u00F9", "&#249;", true, "u - grave"}, {"&uacute;", "\u00FA", "&#250;", true, "u - acute"}, {"&ucirc;", "\u00FB", "&#251;", true, "u - circumflex"}, {"&uuml;", "\u00FC", "&#252;", true, "u - diaeresis"}, {"&yacute;", "\u00FD", "&#253;", true, "y - acute"}, {"&thorn;", "\u00FE", "&#254;", true, "thorn"}, {"&yuml;", "\u00FF", "&#255;", true, "y - diaeresis"}, {"&Alpha;", "\u0391", "&#913;", true, "Alpha"}, {"&Beta;", "\u0392", "&#914;", true, "Beta"}, {"&Gamma;", "\u0393", "&#915;", true, "Gamma"}, {"&Delta;", "\u0394", "&#916;", true, "Delta"}, {"&Epsilon;", "\u0395", "&#917;", true, "Epsilon"}, {"&Zeta;", "\u0396", "&#918;", true, "Zeta"}, {"&Eta;", "\u0397", "&#919;", true, "Eta"}, {"&Theta;", "\u0398", "&#920;", true, "Theta"}, {"&Iota;", "\u0399", "&#921;", true, "Iota"}, {"&Kappa;", "\u039A", "&#922;", true, "Kappa"}, {"&Lambda;", "\u039B", "&#923;", true, "Lambda"}, {"&Mu;", "\u039C", "&#924;", true, "Mu"}, {"&Nu;", "\u039D", "&#925;", true, "Nu"}, {"&Xi;", "\u039E", "&#926;", true, "Xi"}, {"&Omicron;", "\u039F", "&#927;", true, "Omicron"}, {"&Pi;", "\u03A0", "&#928;", true, "Pi"}, {"&Rho;", "\u03A1", "&#929;", true, "Rho"}, {"&Sigma;", "\u03A3", "&#931;", true, "Sigma"}, {"&Tau;", "\u03A4", "&#932;", true, "Tau"}, {"&Upsilon;", "\u03A5", "&#933;", true, "Upsilon"}, {"&Phi;", "\u03A6", "&#934;", true, "Phi"}, {"&Chi;", "\u03A7", "&#935;", true, "Chi"}, {"&Psi;", "\u03A8", "&#936;", true, "Psi"}, {"&Omega;", "\u03A9", "&#937;", true, "Omega"}, {"&alpha;", "\u03B1", "&#945;", true, "alpha"}, {"&beta;", "\u03B2", "&#946;", true, "beta"}, {"&gamma;", "\u03B3", "&#947;", true, "gamma"}, {"&delta;", "\u03B4", "&#948;", true, "delta"}, {"&epsilon;", "\u03B5", "&#949;", true, "epsilon"}, {"&zeta;", "\u03B6", "&#950;", true, "zeta"}, {"&eta;", "\u03B7", "&#951;", true, "eta"}, {"&theta;", "\u03B8", "&#952;", true, "theta"}, {"&iota;", "\u03B9", "&#953;", true, "iota"}, {"&kappa;", "\u03BA", "&#954;", true, "kappa"}, {"&lambda;", "\u03BB", "&#955;", true, "lambda"}, {"&mu;", "\u03BC", "&#956;", true, "mu"}, {"&nu;", "\u03BD", "&#957;", true, "nu"}, {"&xi;", "\u03BE", "&#958;", true, "xi"}, {"&omicron;", "\u03BF", "&#959;", true, "omicron"}, {"&pi;", "\u03C0", "&#960;", true, "pi"}, {"&rho;", "\u03C1", "&#961;", true, "rho"}, {"&sigmaf;", "\u03C2", "&#962;", true, "final sigma"}, {"&sigma;", "\u03C3", "&#963;", true, "sigma"}, {"&tau;", "\u03C4", "&#964;", true, "tau"}, {"&upsilon;", "\u03C5", "&#965;", true, "upsilon"}, {"&phi;", "\u03C6", "&#966;", true, "phi"}, {"&chi;", "\u03C7", "&#967;", true, "chi"}, {"&psi;", "\u03C8", "&#968;", true, "psi"}, {"&omega;", "\u03C9", "&#969;", true, "omega"}, // symbols {"&alefsym;", "\u2135", "&#8501;", false, "alef symbol"}, {"&piv;", "\u03D6", "&#982;", false, "pi symbol"}, {"&real;", "\u211C", "&#8476;", false, "real part symbol"}, {"&thetasym;", "\u03D1", "&#977;", false, "theta symbol"}, {"&upsih;", "\u03D2", "&#978;", false, "upsilon - hook symbol"}, {"&weierp;", "\u2118", "&#8472;", false, "Weierstrass p"}, {"&image;", "\u2111", "&#8465;", false, "imaginary part"}, // arrows {"&larr;", "\u2190", "&#8592;", true, "leftwards arrow"}, {"&uarr;", "\u2191", "&#8593;", true, "upwards arrow"}, {"&rarr;", "\u2192", "&#8594;", true, "rightwards arrow"}, {"&darr;", "\u2193", "&#8595;", true, "downwards arrow"}, {"&harr;", "\u2194", "&#8596;", true, "left right arrow"}, {"&crarr;", "\u21B5", "&#8629;", false, "carriage return"}, {"&lArr;", "\u21D0", "&#8656;", false, "leftwards double arrow"}, {"&uArr;", "\u21D1", "&#8657;", false, "upwards double arrow"}, {"&rArr;", "\u21D2", "&#8658;", false, "rightwards double arrow"}, {"&dArr;", "\u21D3", "&#8659;", false, "downwards double arrow"}, {"&hArr;", "\u21D4", "&#8660;", false, "left right double arrow"}, {"&there4;", "\u2234", "&#8756;", false, "therefore"}, {"&sub;", "\u2282", "&#8834;", false, "subset of"}, {"&sup;", "\u2283", "&#8835;", false, "superset of"}, {"&nsub;", "\u2284", "&#8836;", false, "not a subset of"}, {"&sube;", "\u2286", "&#8838;", false, "subset of or equal to"}, {"&supe;", "\u2287", "&#8839;", false, "superset of or equal to"}, {"&oplus;", "\u2295", "&#8853;", false, "circled plus"}, {"&otimes;", "\u2297", "&#8855;", false, "circled times"}, {"&perp;", "\u22A5", "&#8869;", false, "perpendicular"}, {"&sdot;", "\u22C5", "&#8901;", false, "dot operator"}, {"&lceil;", "\u2308", "&#8968;", false, "left ceiling"}, {"&rceil;", "\u2309", "&#8969;", false, "right ceiling"}, {"&lfloor;", "\u230A", "&#8970;", false, "left floor"}, {"&rfloor;", "\u230B", "&#8971;", false, "right floor"}, {"&lang;", "\u2329", "&#9001;", false, "left-pointing angle bracket"}, {"&rang;", "\u232A", "&#9002;", false, "right-pointing angle bracket"}, {"&loz;", "\u25CA", "&#9674;", true, "lozenge"}, {"&spades;", "\u2660", "&#9824;", false, "black spade suit"}, {"&clubs;", "\u2663", "&#9827;", true, "black club suit"}, {"&hearts;", "\u2665", "&#9829;", true, "black heart suit"}, {"&diams;", "\u2666", "&#9830;", true, "black diamond suit"}, {"&ensp;", "\u2002", "&#8194;", false, "en space"}, {"&emsp;", "\u2003", "&#8195;", false, "em space"}, {"&thinsp;", "\u2009", "&#8201;", false, "thin space"}, {"&zwnj;", "\u200C", "&#8204;", false, "zero width non-joiner"}, {"&zwj;", "\u200D", "&#8205;", false, "zero width joiner"}, {"&lrm;", "\u200E", "&#8206;", false, "left-to-right mark"}, {"&rlm;", "\u200F", "&#8207;", false, "right-to-left mark"}, {"&shy;", "\u00AD", "&#173;", false, "soft hyphen"} }; /** * Column index of the HTML ENTITY representing the character */ static final int CHAR_HTML_ENTITY = 0; /** * Column index of the UNICODE of the character */ static final int CHAR_UNICODE = 1; /** * Column index of the flag to enable/disable the character */ - static final int CHAR_ENABLED = 2; + static final int CHAR_HTML_CODE = 2; + + /** + * Column index of the flag to enable/disable the character + */ + static final int CHAR_ENABLED = 3; /** * Column index of the description of the character */ - static final int CHAR_TITLE = 3; + static final int CHAR_TITLE = 4; /** * The default number of rows in the grid that makes up the symbol palette. */ private static final int SYMBOLS_PER_ROW = 20; /** * The default number of columns in the grid that makes up the symbol palette. */ private static final int SYMBOLS_PER_COL = 10; /** * The symbol palette used for picking the symbol. */ private final RTSymbolPalette symbolPalette; /** * Creates a new symbol picker using the default list of symbols. */ public RTSymbolPicker() { super(false, true); getDialog().setIcon(new Image(Images.INSTANCE.charmap())); getDialog().setCaption(Strings.INSTANCE.charmap()); getDialog().addStyleName("xSymbolPicker"); symbolPalette = new RTSymbolPalette(RT_SYMBOLS, SYMBOLS_PER_ROW, SYMBOLS_PER_COL); symbolPalette.addSelectionHandler(this); initWidget(symbolPalette); } /** * {@inheritDoc} * * @see SelectionHandler#onSelection(SelectionEvent) */ public void onSelection(SelectionEvent<String> event) { if (event.getSource() == symbolPalette) { hide(); } } /** * @return the selected symbol */ public String getSymbol() { return symbolPalette.getSelectedSymbol(); } /** * {@inheritDoc} * * @see CompositeDialogBox#center() */ public void center() { // Reset the selected symbol each time the symbol picker is shown. symbolPalette.setSelectedSymbol(null); super.center(); } }
false
false
null
null
diff --git a/src/hdfs/org/apache/hadoop/hdfs/DFSClient.java b/src/hdfs/org/apache/hadoop/hdfs/DFSClient.java index c57f3bee0..56f89fb21 100644 --- a/src/hdfs/org/apache/hadoop/hdfs/DFSClient.java +++ b/src/hdfs/org/apache/hadoop/hdfs/DFSClient.java @@ -1,3450 +1,3459 @@ /** * 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.hdfs; import org.apache.hadoop.io.*; import org.apache.hadoop.io.retry.RetryPolicies; import org.apache.hadoop.io.retry.RetryPolicy; import org.apache.hadoop.io.retry.RetryProxy; import org.apache.hadoop.fs.*; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.ipc.*; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.net.NodeBase; import org.apache.hadoop.conf.*; import org.apache.hadoop.hdfs.DistributedFileSystem.DiskStatus; import org.apache.hadoop.hdfs.protocol.*; import org.apache.hadoop.hdfs.protocol.DataTransferProtocol.PipelineAck; import org.apache.hadoop.hdfs.security.token.block.InvalidBlockTokenException; import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier; import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier; import org.apache.hadoop.hdfs.server.common.HdfsConstants; import org.apache.hadoop.hdfs.server.common.UpgradeStatusReport; import org.apache.hadoop.hdfs.server.datanode.DataNode; import org.apache.hadoop.hdfs.server.namenode.NameNode; import org.apache.hadoop.hdfs.server.namenode.NotReplicatedYetException; import org.apache.hadoop.security.AccessControlException; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.SecretManager.InvalidToken; import org.apache.hadoop.util.*; import org.apache.commons.logging.*; import java.io.*; import java.net.*; import java.util.*; import java.util.zip.CRC32; import java.util.concurrent.TimeUnit; import java.util.concurrent.ConcurrentHashMap; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import javax.net.SocketFactory; /******************************************************** * DFSClient can connect to a Hadoop Filesystem and * perform basic file tasks. It uses the ClientProtocol * to communicate with a NameNode daemon, and connects * directly to DataNodes to read/write block data. * * Hadoop DFS users should obtain an instance of * DistributedFileSystem, which uses DFSClient to handle * filesystem tasks. * ********************************************************/ public class DFSClient implements FSConstants, java.io.Closeable { public static final Log LOG = LogFactory.getLog(DFSClient.class); public static final int MAX_BLOCK_ACQUIRE_FAILURES = 3; private static final int TCP_WINDOW_SIZE = 128 * 1024; // 128 KB public final ClientProtocol namenode; private final ClientProtocol rpcNamenode; final UserGroupInformation ugi; volatile boolean clientRunning = true; Random r = new Random(); final String clientName; final LeaseChecker leasechecker = new LeaseChecker(); private Configuration conf; private long defaultBlockSize; private short defaultReplication; private SocketFactory socketFactory; private int socketTimeout; private int datanodeWriteTimeout; final int writePacketSize; private final FileSystem.Statistics stats; private int maxBlockAcquireFailures; public static ClientProtocol createNamenode(Configuration conf) throws IOException { return createNamenode(NameNode.getAddress(conf), conf); } public static ClientProtocol createNamenode( InetSocketAddress nameNodeAddr, Configuration conf) throws IOException { return createNamenode(createRPCNamenode(nameNodeAddr, conf, UserGroupInformation.getCurrentUser())); } private static ClientProtocol createRPCNamenode(InetSocketAddress nameNodeAddr, Configuration conf, UserGroupInformation ugi) throws IOException { return (ClientProtocol)RPC.getProxy(ClientProtocol.class, ClientProtocol.versionID, nameNodeAddr, ugi, conf, NetUtils.getSocketFactory(conf, ClientProtocol.class)); } private static ClientProtocol createNamenode(ClientProtocol rpcNamenode) throws IOException { RetryPolicy createPolicy = RetryPolicies.retryUpToMaximumCountWithFixedSleep( 5, LEASE_SOFTLIMIT_PERIOD, TimeUnit.MILLISECONDS); Map<Class<? extends Exception>,RetryPolicy> remoteExceptionToPolicyMap = new HashMap<Class<? extends Exception>, RetryPolicy>(); remoteExceptionToPolicyMap.put(AlreadyBeingCreatedException.class, createPolicy); Map<Class<? extends Exception>,RetryPolicy> exceptionToPolicyMap = new HashMap<Class<? extends Exception>, RetryPolicy>(); exceptionToPolicyMap.put(RemoteException.class, RetryPolicies.retryByRemoteException( RetryPolicies.TRY_ONCE_THEN_FAIL, remoteExceptionToPolicyMap)); RetryPolicy methodPolicy = RetryPolicies.retryByException( RetryPolicies.TRY_ONCE_THEN_FAIL, exceptionToPolicyMap); Map<String,RetryPolicy> methodNameToPolicyMap = new HashMap<String,RetryPolicy>(); methodNameToPolicyMap.put("create", methodPolicy); return (ClientProtocol) RetryProxy.create(ClientProtocol.class, rpcNamenode, methodNameToPolicyMap); } static ClientDatanodeProtocol createClientDatanodeProtocolProxy ( DatanodeID datanodeid, Configuration conf, Block block, Token<BlockTokenIdentifier> token) throws IOException { InetSocketAddress addr = NetUtils.createSocketAddr( datanodeid.getHost() + ":" + datanodeid.getIpcPort()); if (ClientDatanodeProtocol.LOG.isDebugEnabled()) { ClientDatanodeProtocol.LOG.info("ClientDatanodeProtocol addr=" + addr); } UserGroupInformation ticket = UserGroupInformation .createRemoteUser(block.toString()); ticket.addToken(token); return (ClientDatanodeProtocol)RPC.getProxy(ClientDatanodeProtocol.class, ClientDatanodeProtocol.versionID, addr, ticket, conf, NetUtils .getDefaultSocketFactory(conf)); } /** * Same as this(NameNode.getAddress(conf), conf); * @see #DFSClient(InetSocketAddress, Configuration) */ public DFSClient(Configuration conf) throws IOException { this(NameNode.getAddress(conf), conf); } /** * Same as this(nameNodeAddr, conf, null); * @see #DFSClient(InetSocketAddress, Configuration, org.apache.hadoop.fs.FileSystem.Statistics) */ public DFSClient(InetSocketAddress nameNodeAddr, Configuration conf ) throws IOException { this(nameNodeAddr, conf, null); } /** * Same as this(nameNodeAddr, null, conf, stats); * @see #DFSClient(InetSocketAddress, ClientProtocol, Configuration, org.apache.hadoop.fs.FileSystem.Statistics) */ public DFSClient(InetSocketAddress nameNodeAddr, Configuration conf, FileSystem.Statistics stats) throws IOException { this(nameNodeAddr, null, conf, stats); } /** * Create a new DFSClient connected to the given nameNodeAddr or rpcNamenode. * Exactly one of nameNodeAddr or rpcNamenode must be null. */ DFSClient(InetSocketAddress nameNodeAddr, ClientProtocol rpcNamenode, Configuration conf, FileSystem.Statistics stats) throws IOException { this.conf = conf; this.stats = stats; this.socketTimeout = conf.getInt("dfs.socket.timeout", HdfsConstants.READ_TIMEOUT); this.datanodeWriteTimeout = conf.getInt("dfs.datanode.socket.write.timeout", HdfsConstants.WRITE_TIMEOUT); this.socketFactory = NetUtils.getSocketFactory(conf, ClientProtocol.class); // dfs.write.packet.size is an internal config variable this.writePacketSize = conf.getInt("dfs.write.packet.size", 64*1024); this.maxBlockAcquireFailures = getMaxBlockAcquireFailures(conf); ugi = UserGroupInformation.getCurrentUser(); String taskId = conf.get("mapred.task.id"); if (taskId != null) { this.clientName = "DFSClient_" + taskId; } else { this.clientName = "DFSClient_" + r.nextInt(); } defaultBlockSize = conf.getLong("dfs.block.size", DEFAULT_BLOCK_SIZE); defaultReplication = (short) conf.getInt("dfs.replication", 3); if (nameNodeAddr != null && rpcNamenode == null) { this.rpcNamenode = createRPCNamenode(nameNodeAddr, conf, ugi); this.namenode = createNamenode(this.rpcNamenode); } else if (nameNodeAddr == null && rpcNamenode != null) { //This case is used for testing. this.namenode = this.rpcNamenode = rpcNamenode; } else { throw new IllegalArgumentException( "Expecting exactly one of nameNodeAddr and rpcNamenode being null: " + "nameNodeAddr=" + nameNodeAddr + ", rpcNamenode=" + rpcNamenode); } } static int getMaxBlockAcquireFailures(Configuration conf) { return conf.getInt("dfs.client.max.block.acquire.failures", MAX_BLOCK_ACQUIRE_FAILURES); } private void checkOpen() throws IOException { if (!clientRunning) { IOException result = new IOException("Filesystem closed"); throw result; } } /** * Close the file system, abandoning all of the leases and files being * created and close connections to the namenode. */ public synchronized void close() throws IOException { if(clientRunning) { leasechecker.close(); clientRunning = false; try { leasechecker.interruptAndJoin(); } catch (InterruptedException ie) { } // close connections to the namenode RPC.stopProxy(rpcNamenode); } } /** * Get the default block size for this cluster * @return the default block size in bytes */ public long getDefaultBlockSize() { return defaultBlockSize; } public long getBlockSize(String f) throws IOException { try { return namenode.getPreferredBlockSize(f); } catch (IOException ie) { LOG.warn("Problem getting block size: " + StringUtils.stringifyException(ie)); throw ie; } } public Token<DelegationTokenIdentifier> getDelegationToken(Text renewer) throws IOException { return namenode.getDelegationToken(renewer); } public long renewDelegationToken(Token<DelegationTokenIdentifier> token) throws InvalidToken, IOException { try { return namenode.renewDelegationToken(token); } catch (RemoteException re) { throw re.unwrapRemoteException(InvalidToken.class, AccessControlException.class); } } public void cancelDelegationToken(Token<DelegationTokenIdentifier> token) throws InvalidToken, IOException { try { namenode.cancelDelegationToken(token); } catch (RemoteException re) { throw re.unwrapRemoteException(InvalidToken.class, AccessControlException.class); } } /** * Report corrupt blocks that were discovered by the client. */ public void reportBadBlocks(LocatedBlock[] blocks) throws IOException { namenode.reportBadBlocks(blocks); } public short getDefaultReplication() { return defaultReplication; } /** * @deprecated Use getBlockLocations instead * * Get hints about the location of the indicated block(s). * * getHints() returns a list of hostnames that store data for * a specific file region. It returns a set of hostnames for * every block within the indicated region. * * This function is very useful when writing code that considers * data-placement when performing operations. For example, the * MapReduce system tries to schedule tasks on the same machines * as the data-block the task processes. */ @Deprecated public String[][] getHints(String src, long start, long length) throws IOException { BlockLocation[] blkLocations = getBlockLocations(src, start, length); if ((blkLocations == null) || (blkLocations.length == 0)) { return new String[0][]; } int blkCount = blkLocations.length; String[][]hints = new String[blkCount][]; for (int i=0; i < blkCount ; i++) { String[] hosts = blkLocations[i].getHosts(); hints[i] = new String[hosts.length]; hints[i] = hosts; } return hints; } private static LocatedBlocks callGetBlockLocations(ClientProtocol namenode, String src, long start, long length) throws IOException { try { return namenode.getBlockLocations(src, start, length); } catch(RemoteException re) { throw re.unwrapRemoteException(AccessControlException.class, FileNotFoundException.class); } } /** * Get block location info about file * * getBlockLocations() returns a list of hostnames that store * data for a specific file region. It returns a set of hostnames * for every block within the indicated region. * * This function is very useful when writing code that considers * data-placement when performing operations. For example, the * MapReduce system tries to schedule tasks on the same machines * as the data-block the task processes. */ public BlockLocation[] getBlockLocations(String src, long start, long length) throws IOException { LocatedBlocks blocks = callGetBlockLocations(namenode, src, start, length); if (blocks == null) { return new BlockLocation[0]; } int nrBlocks = blocks.locatedBlockCount(); BlockLocation[] blkLocations = new BlockLocation[nrBlocks]; int idx = 0; for (LocatedBlock blk : blocks.getLocatedBlocks()) { assert idx < nrBlocks : "Incorrect index"; DatanodeInfo[] locations = blk.getLocations(); String[] hosts = new String[locations.length]; String[] names = new String[locations.length]; String[] racks = new String[locations.length]; for (int hCnt = 0; hCnt < locations.length; hCnt++) { hosts[hCnt] = locations[hCnt].getHostName(); names[hCnt] = locations[hCnt].getName(); NodeBase node = new NodeBase(names[hCnt], locations[hCnt].getNetworkLocation()); racks[hCnt] = node.toString(); } blkLocations[idx] = new BlockLocation(names, hosts, racks, blk.getStartOffset(), blk.getBlockSize()); idx++; } return blkLocations; } public DFSInputStream open(String src) throws IOException { return open(src, conf.getInt("io.file.buffer.size", 4096), true, null); } /** * Create an input stream that obtains a nodelist from the * namenode, and then reads from all the right places. Creates * inner subclass of InputStream that does the right out-of-band * work. */ DFSInputStream open(String src, int buffersize, boolean verifyChecksum, FileSystem.Statistics stats ) throws IOException { checkOpen(); // Get block info from namenode return new DFSInputStream(src, buffersize, verifyChecksum); } /** * Create a new dfs file and return an output stream for writing into it. * * @param src stream name * @param overwrite do not check for file existence if true * @return output stream * @throws IOException */ public OutputStream create(String src, boolean overwrite ) throws IOException { return create(src, overwrite, defaultReplication, defaultBlockSize, null); } /** * Create a new dfs file and return an output stream for writing into it * with write-progress reporting. * * @param src stream name * @param overwrite do not check for file existence if true * @return output stream * @throws IOException */ public OutputStream create(String src, boolean overwrite, Progressable progress ) throws IOException { return create(src, overwrite, defaultReplication, defaultBlockSize, null); } /** * Create a new dfs file with the specified block replication * and return an output stream for writing into the file. * * @param src stream name * @param overwrite do not check for file existence if true * @param replication block replication * @return output stream * @throws IOException */ public OutputStream create(String src, boolean overwrite, short replication, long blockSize ) throws IOException { return create(src, overwrite, replication, blockSize, null); } /** * Create a new dfs file with the specified block replication * with write-progress reporting and return an output stream for writing * into the file. * * @param src stream name * @param overwrite do not check for file existence if true * @param replication block replication * @return output stream * @throws IOException */ public OutputStream create(String src, boolean overwrite, short replication, long blockSize, Progressable progress ) throws IOException { return create(src, overwrite, replication, blockSize, progress, conf.getInt("io.file.buffer.size", 4096)); } /** * Call * {@link #create(String,FsPermission,boolean,short,long,Progressable,int)} * with default permission. * @see FsPermission#getDefault() */ public OutputStream create(String src, boolean overwrite, short replication, long blockSize, Progressable progress, int buffersize ) throws IOException { return create(src, FsPermission.getDefault(), overwrite, replication, blockSize, progress, buffersize); } /** * Create a new dfs file with the specified block replication * with write-progress reporting and return an output stream for writing * into the file. * * @param src stream name * @param permission The permission of the directory being created. * If permission == null, use {@link FsPermission#getDefault()}. * @param overwrite do not check for file existence if true * @param replication block replication * @return output stream * @throws IOException * @see ClientProtocol#create(String, FsPermission, String, boolean, short, long) */ public OutputStream create(String src, FsPermission permission, boolean overwrite, short replication, long blockSize, Progressable progress, int buffersize ) throws IOException { checkOpen(); if (permission == null) { permission = FsPermission.getDefault(); } FsPermission masked = permission.applyUMask(FsPermission.getUMask(conf)); LOG.debug(src + ": masked=" + masked); OutputStream result = new DFSOutputStream(src, masked, overwrite, replication, blockSize, progress, buffersize, conf.getInt("io.bytes.per.checksum", 512)); leasechecker.put(src, result); return result; } /** * Append to an existing HDFS file. * * @param src file name * @param buffersize buffer size * @param progress for reporting write-progress * @return an output stream for writing into the file * @throws IOException * @see ClientProtocol#append(String, String) */ OutputStream append(String src, int buffersize, Progressable progress ) throws IOException { checkOpen(); HdfsFileStatus stat = null; LocatedBlock lastBlock = null; try { stat = getFileInfo(src); lastBlock = namenode.append(src, clientName); } catch(RemoteException re) { throw re.unwrapRemoteException(FileNotFoundException.class, AccessControlException.class, NSQuotaExceededException.class, DSQuotaExceededException.class); } OutputStream result = new DFSOutputStream(src, buffersize, progress, lastBlock, stat, conf.getInt("io.bytes.per.checksum", 512)); leasechecker.put(src, result); return result; } /** * Set replication for an existing file. * * @see ClientProtocol#setReplication(String, short) * @param replication * @throws IOException * @return true is successful or false if file does not exist */ public boolean setReplication(String src, short replication ) throws IOException { try { return namenode.setReplication(src, replication); } catch(RemoteException re) { throw re.unwrapRemoteException(AccessControlException.class, NSQuotaExceededException.class, DSQuotaExceededException.class); } } /** * Rename file or directory. * See {@link ClientProtocol#rename(String, String)}. */ public boolean rename(String src, String dst) throws IOException { checkOpen(); try { return namenode.rename(src, dst); } catch(RemoteException re) { throw re.unwrapRemoteException(AccessControlException.class, NSQuotaExceededException.class, DSQuotaExceededException.class); } } /** * Delete file or directory. * See {@link ClientProtocol#delete(String)}. */ @Deprecated public boolean delete(String src) throws IOException { checkOpen(); return namenode.delete(src, true); } /** * delete file or directory. * delete contents of the directory if non empty and recursive * set to true */ public boolean delete(String src, boolean recursive) throws IOException { checkOpen(); try { return namenode.delete(src, recursive); } catch(RemoteException re) { throw re.unwrapRemoteException(AccessControlException.class); } } /** Implemented using getFileInfo(src) */ public boolean exists(String src) throws IOException { checkOpen(); return getFileInfo(src) != null; } /** @deprecated Use getHdfsFileStatus() instead */ @Deprecated public boolean isDirectory(String src) throws IOException { HdfsFileStatus fs = getFileInfo(src); if (fs != null) return fs.isDir(); else throw new FileNotFoundException("File does not exist: " + src); } /** * Get a partial listing of the indicated directory * * Recommend to use HdfsFileStatus.EMPTY_NAME as startAfter * if the application wants to fetch a listing starting from * the first entry in the directory * * @param src the directory name * @param startAfter the name to start listing after * @return a partial listing starting after startAfter */ public DirectoryListing listPaths(String src, byte[] startAfter) throws IOException { checkOpen(); try { return namenode.getListing(src, startAfter); } catch(RemoteException re) { throw re.unwrapRemoteException(AccessControlException.class); } } public HdfsFileStatus getFileInfo(String src) throws IOException { checkOpen(); try { return namenode.getFileInfo(src); } catch(RemoteException re) { throw re.unwrapRemoteException(AccessControlException.class); } } /** * Get the checksum of a file. * @param src The file path * @return The checksum * @see DistributedFileSystem#getFileChecksum(Path) */ MD5MD5CRC32FileChecksum getFileChecksum(String src) throws IOException { checkOpen(); return getFileChecksum(src, namenode, socketFactory, socketTimeout); } /** * Get the checksum of a file. * @param src The file path * @return The checksum */ public static MD5MD5CRC32FileChecksum getFileChecksum(String src, ClientProtocol namenode, SocketFactory socketFactory, int socketTimeout ) throws IOException { //get all block locations List<LocatedBlock> locatedblocks = callGetBlockLocations(namenode, src, 0, Long.MAX_VALUE).getLocatedBlocks(); final DataOutputBuffer md5out = new DataOutputBuffer(); int bytesPerCRC = 0; long crcPerBlock = 0; boolean refetchBlocks = false; int lastRetriedIndex = -1; //get block checksum for each block for(int i = 0; i < locatedblocks.size(); i++) { if (refetchBlocks) { // refetch to get fresh tokens locatedblocks = callGetBlockLocations(namenode, src, 0, Long.MAX_VALUE) .getLocatedBlocks(); refetchBlocks = false; } LocatedBlock lb = locatedblocks.get(i); final Block block = lb.getBlock(); final DatanodeInfo[] datanodes = lb.getLocations(); //try each datanode location of the block final int timeout = 3000 * datanodes.length + socketTimeout; boolean done = false; for(int j = 0; !done && j < datanodes.length; j++) { //connect to a datanode final Socket sock = socketFactory.createSocket(); NetUtils.connect(sock, NetUtils.createSocketAddr(datanodes[j].getName()), timeout); sock.setSoTimeout(timeout); DataOutputStream out = new DataOutputStream( new BufferedOutputStream(NetUtils.getOutputStream(sock), DataNode.SMALL_BUFFER_SIZE)); DataInputStream in = new DataInputStream(NetUtils.getInputStream(sock)); // get block MD5 try { if (LOG.isDebugEnabled()) { LOG.debug("write to " + datanodes[j].getName() + ": " + DataTransferProtocol.OP_BLOCK_CHECKSUM + ", block=" + block); } out.writeShort(DataTransferProtocol.DATA_TRANSFER_VERSION); out.write(DataTransferProtocol.OP_BLOCK_CHECKSUM); out.writeLong(block.getBlockId()); out.writeLong(block.getGenerationStamp()); lb.getBlockToken().write(out); out.flush(); final short reply = in.readShort(); if (reply != DataTransferProtocol.OP_STATUS_SUCCESS) { if (reply == DataTransferProtocol.OP_STATUS_ERROR_ACCESS_TOKEN && i > lastRetriedIndex) { if (LOG.isDebugEnabled()) { LOG.debug("Got access token error in response to OP_BLOCK_CHECKSUM " + "for file " + src + " for block " + block + " from datanode " + datanodes[j].getName() + ". Will retry the block once."); } lastRetriedIndex = i; done = true; // actually it's not done; but we'll retry i--; // repeat at i-th block refetchBlocks = true; break; } else { throw new IOException("Bad response " + reply + " for block " + block + " from datanode " + datanodes[j].getName()); } } //read byte-per-checksum final int bpc = in.readInt(); if (i == 0) { //first block bytesPerCRC = bpc; } else if (bpc != bytesPerCRC) { throw new IOException("Byte-per-checksum not matched: bpc=" + bpc + " but bytesPerCRC=" + bytesPerCRC); } //read crc-per-block final long cpb = in.readLong(); if (locatedblocks.size() > 1 && i == 0) { crcPerBlock = cpb; } //read md5 final MD5Hash md5 = MD5Hash.read(in); md5.write(md5out); done = true; if (LOG.isDebugEnabled()) { if (i == 0) { LOG.debug("set bytesPerCRC=" + bytesPerCRC + ", crcPerBlock=" + crcPerBlock); } LOG.debug("got reply from " + datanodes[j].getName() + ": md5=" + md5); } } catch (IOException ie) { LOG.warn("src=" + src + ", datanodes[" + j + "].getName()=" + datanodes[j].getName(), ie); } finally { IOUtils.closeStream(in); IOUtils.closeStream(out); IOUtils.closeSocket(sock); } } if (!done) { throw new IOException("Fail to get block MD5 for " + block); } } //compute file MD5 final MD5Hash fileMD5 = MD5Hash.digest(md5out.getData()); return new MD5MD5CRC32FileChecksum(bytesPerCRC, crcPerBlock, fileMD5); } /** * Set permissions to a file or directory. * @param src path name. * @param permission * @throws <code>FileNotFoundException</code> is file does not exist. */ public void setPermission(String src, FsPermission permission ) throws IOException { checkOpen(); try { namenode.setPermission(src, permission); } catch(RemoteException re) { throw re.unwrapRemoteException(AccessControlException.class, FileNotFoundException.class); } } /** * Set file or directory owner. * @param src path name. * @param username user id. * @param groupname user group. * @throws <code>FileNotFoundException</code> is file does not exist. */ public void setOwner(String src, String username, String groupname ) throws IOException { checkOpen(); try { namenode.setOwner(src, username, groupname); } catch(RemoteException re) { throw re.unwrapRemoteException(AccessControlException.class, FileNotFoundException.class); } } public DiskStatus getDiskStatus() throws IOException { long rawNums[] = namenode.getStats(); return new DiskStatus(rawNums[0], rawNums[1], rawNums[2]); } /** */ public long totalRawCapacity() throws IOException { long rawNums[] = namenode.getStats(); return rawNums[0]; } /** */ public long totalRawUsed() throws IOException { long rawNums[] = namenode.getStats(); return rawNums[1]; } /** * Returns count of blocks with no good replicas left. Normally should be * zero. * @throws IOException */ public long getMissingBlocksCount() throws IOException { return namenode.getStats()[ClientProtocol.GET_STATS_MISSING_BLOCKS_IDX]; } /** * Returns count of blocks with one of more replica missing. * @throws IOException */ public long getUnderReplicatedBlocksCount() throws IOException { return namenode.getStats()[ClientProtocol.GET_STATS_UNDER_REPLICATED_IDX]; } /** * Returns count of blocks with at least one replica marked corrupt. * @throws IOException */ public long getCorruptBlocksCount() throws IOException { return namenode.getStats()[ClientProtocol.GET_STATS_CORRUPT_BLOCKS_IDX]; } public DatanodeInfo[] datanodeReport(DatanodeReportType type) throws IOException { return namenode.getDatanodeReport(type); } /** * Enter, leave or get safe mode. * See {@link ClientProtocol#setSafeMode(FSConstants.SafeModeAction)} * for more details. * * @see ClientProtocol#setSafeMode(FSConstants.SafeModeAction) */ public boolean setSafeMode(SafeModeAction action) throws IOException { return namenode.setSafeMode(action); } /** * Save namespace image. * See {@link ClientProtocol#saveNamespace()} * for more details. * * @see ClientProtocol#saveNamespace() */ void saveNamespace() throws AccessControlException, IOException { try { namenode.saveNamespace(); } catch(RemoteException re) { throw re.unwrapRemoteException(AccessControlException.class); } } /** * Refresh the hosts and exclude files. (Rereads them.) * See {@link ClientProtocol#refreshNodes()} * for more details. * * @see ClientProtocol#refreshNodes() */ public void refreshNodes() throws IOException { namenode.refreshNodes(); } /** * Dumps DFS data structures into specified file. * See {@link ClientProtocol#metaSave(String)} * for more details. * * @see ClientProtocol#metaSave(String) */ public void metaSave(String pathname) throws IOException { namenode.metaSave(pathname); } /** * @see ClientProtocol#finalizeUpgrade() */ public void finalizeUpgrade() throws IOException { namenode.finalizeUpgrade(); } /** * @see ClientProtocol#distributedUpgradeProgress(FSConstants.UpgradeAction) */ public UpgradeStatusReport distributedUpgradeProgress(UpgradeAction action ) throws IOException { return namenode.distributedUpgradeProgress(action); } /** */ public boolean mkdirs(String src) throws IOException { return mkdirs(src, null); } /** * Create a directory (or hierarchy of directories) with the given * name and permission. * * @param src The path of the directory being created * @param permission The permission of the directory being created. * If permission == null, use {@link FsPermission#getDefault()}. * @return True if the operation success. * @see ClientProtocol#mkdirs(String, FsPermission) */ public boolean mkdirs(String src, FsPermission permission)throws IOException{ checkOpen(); if (permission == null) { permission = FsPermission.getDefault(); } FsPermission masked = permission.applyUMask(FsPermission.getUMask(conf)); LOG.debug(src + ": masked=" + masked); try { return namenode.mkdirs(src, masked); } catch(RemoteException re) { throw re.unwrapRemoteException(AccessControlException.class, NSQuotaExceededException.class, DSQuotaExceededException.class); } } ContentSummary getContentSummary(String src) throws IOException { try { return namenode.getContentSummary(src); } catch(RemoteException re) { throw re.unwrapRemoteException(AccessControlException.class, FileNotFoundException.class); } } /** * Sets or resets quotas for a directory. * @see org.apache.hadoop.hdfs.protocol.ClientProtocol#setQuota(String, long, long) */ void setQuota(String src, long namespaceQuota, long diskspaceQuota) throws IOException { // sanity check if ((namespaceQuota <= 0 && namespaceQuota != FSConstants.QUOTA_DONT_SET && namespaceQuota != FSConstants.QUOTA_RESET) || (diskspaceQuota <= 0 && diskspaceQuota != FSConstants.QUOTA_DONT_SET && diskspaceQuota != FSConstants.QUOTA_RESET)) { throw new IllegalArgumentException("Invalid values for quota : " + namespaceQuota + " and " + diskspaceQuota); } try { namenode.setQuota(src, namespaceQuota, diskspaceQuota); } catch(RemoteException re) { throw re.unwrapRemoteException(AccessControlException.class, FileNotFoundException.class, NSQuotaExceededException.class, DSQuotaExceededException.class); } } /** * set the modification and access time of a file * @throws FileNotFoundException if the path is not a file */ public void setTimes(String src, long mtime, long atime) throws IOException { checkOpen(); try { namenode.setTimes(src, mtime, atime); } catch(RemoteException re) { throw re.unwrapRemoteException(AccessControlException.class, FileNotFoundException.class); } } /** * Pick the best node from which to stream the data. * Entries in <i>nodes</i> are already in the priority order */ private DatanodeInfo bestNode(DatanodeInfo nodes[], AbstractMap<DatanodeInfo, DatanodeInfo> deadNodes) throws IOException { if (nodes != null) { for (int i = 0; i < nodes.length; i++) { if (!deadNodes.containsKey(nodes[i])) { return nodes[i]; } } } throw new IOException("No live nodes contain current block"); } boolean isLeaseCheckerStarted() { return leasechecker.daemon != null; } /** Lease management*/ class LeaseChecker implements Runnable { /** A map from src -> DFSOutputStream of files that are currently being * written by this client. */ private final SortedMap<String, OutputStream> pendingCreates = new TreeMap<String, OutputStream>(); private Daemon daemon = null; synchronized void put(String src, OutputStream out) { if (clientRunning) { if (daemon == null) { daemon = new Daemon(this); daemon.start(); } pendingCreates.put(src, out); } } synchronized void remove(String src) { pendingCreates.remove(src); } void interruptAndJoin() throws InterruptedException { Daemon daemonCopy = null; synchronized (this) { if (daemon != null) { daemon.interrupt(); daemonCopy = daemon; } } if (daemonCopy != null) { LOG.debug("Wait for lease checker to terminate"); daemonCopy.join(); } } synchronized void close() { while (!pendingCreates.isEmpty()) { String src = pendingCreates.firstKey(); OutputStream out = pendingCreates.remove(src); if (out != null) { try { out.close(); } catch (IOException ie) { LOG.error("Exception closing file " + src+ " : " + ie, ie); } } } } private void renew() throws IOException { synchronized(this) { if (pendingCreates.isEmpty()) { return; } } namenode.renewLease(clientName); } /** * Periodically check in with the namenode and renew all the leases * when the lease period is half over. */ public void run() { long lastRenewed = 0; while (clientRunning && !Thread.interrupted()) { if (System.currentTimeMillis() - lastRenewed > (LEASE_SOFTLIMIT_PERIOD / 2)) { try { renew(); lastRenewed = System.currentTimeMillis(); } catch (IOException ie) { LOG.warn("Problem renewing lease for " + clientName, ie); } } try { Thread.sleep(1000); } catch (InterruptedException ie) { if (LOG.isDebugEnabled()) { LOG.debug(this + " is interrupted.", ie); } return; } } } /** {@inheritDoc} */ public String toString() { String s = getClass().getSimpleName(); if (LOG.isTraceEnabled()) { return s + "@" + DFSClient.this + ": " + StringUtils.stringifyException(new Throwable("for testing")); } return s; } } /** Utility class to encapsulate data node info and its ip address. */ private static class DNAddrPair { DatanodeInfo info; InetSocketAddress addr; DNAddrPair(DatanodeInfo info, InetSocketAddress addr) { this.info = info; this.addr = addr; } } /** This is a wrapper around connection to datadone * and understands checksum, offset etc */ public static class BlockReader extends FSInputChecker { private Socket dnSock; //for now just sending checksumOk. private DataInputStream in; private DataChecksum checksum; private long lastChunkOffset = -1; private long lastChunkLen = -1; private long lastSeqNo = -1; private long startOffset; private long firstChunkOffset; private int bytesPerChecksum; private int checksumSize; private boolean gotEOS = false; byte[] skipBuf = null; ByteBuffer checksumBytes = null; int dataLeft = 0; boolean isLastPacket = false; /* FSInputChecker interface */ /* same interface as inputStream java.io.InputStream#read() * used by DFSInputStream#read() * This violates one rule when there is a checksum error: * "Read should not modify user buffer before successful read" * because it first reads the data to user buffer and then checks * the checksum. */ @Override public synchronized int read(byte[] buf, int off, int len) throws IOException { //for the first read, skip the extra bytes at the front. if (lastChunkLen < 0 && startOffset > firstChunkOffset && len > 0) { // Skip these bytes. But don't call this.skip()! int toSkip = (int)(startOffset - firstChunkOffset); if ( skipBuf == null ) { skipBuf = new byte[bytesPerChecksum]; } if ( super.read(skipBuf, 0, toSkip) != toSkip ) { // should never happen throw new IOException("Could not skip required number of bytes"); } } boolean eosBefore = gotEOS; int nRead = super.read(buf, off, len); // if gotEOS was set in the previous read and checksum is enabled : if (gotEOS && !eosBefore && nRead >= 0 && needChecksum()) { //checksum is verified and there are no errors. checksumOk(dnSock); } return nRead; } @Override public synchronized long skip(long n) throws IOException { /* How can we make sure we don't throw a ChecksumException, at least * in majority of the cases?. This one throws. */ if ( skipBuf == null ) { skipBuf = new byte[bytesPerChecksum]; } long nSkipped = 0; while ( nSkipped < n ) { int toSkip = (int)Math.min(n-nSkipped, skipBuf.length); int ret = read(skipBuf, 0, toSkip); if ( ret <= 0 ) { return nSkipped; } nSkipped += ret; } return nSkipped; } @Override public int read() throws IOException { throw new IOException("read() is not expected to be invoked. " + "Use read(buf, off, len) instead."); } @Override public boolean seekToNewSource(long targetPos) throws IOException { /* Checksum errors are handled outside the BlockReader. * DFSInputStream does not always call 'seekToNewSource'. In the * case of pread(), it just tries a different replica without seeking. */ return false; } @Override public void seek(long pos) throws IOException { throw new IOException("Seek() is not supported in BlockInputChecker"); } @Override protected long getChunkPosition(long pos) { throw new RuntimeException("getChunkPosition() is not supported, " + "since seek is not required"); } /** * Makes sure that checksumBytes has enough capacity * and limit is set to the number of checksum bytes needed * to be read. */ private void adjustChecksumBytes(int dataLen) { int requiredSize = ((dataLen + bytesPerChecksum - 1)/bytesPerChecksum)*checksumSize; if (checksumBytes == null || requiredSize > checksumBytes.capacity()) { checksumBytes = ByteBuffer.wrap(new byte[requiredSize]); } else { checksumBytes.clear(); } checksumBytes.limit(requiredSize); } @Override protected synchronized int readChunk(long pos, byte[] buf, int offset, int len, byte[] checksumBuf) throws IOException { // Read one chunk. if ( gotEOS ) { if ( startOffset < 0 ) { //This is mainly for debugging. can be removed. throw new IOException( "BlockRead: already got EOS or an error" ); } startOffset = -1; return -1; } // Read one DATA_CHUNK. long chunkOffset = lastChunkOffset; if ( lastChunkLen > 0 ) { chunkOffset += lastChunkLen; } if ( (pos + firstChunkOffset) != chunkOffset ) { throw new IOException("Mismatch in pos : " + pos + " + " + firstChunkOffset + " != " + chunkOffset); } // Read next packet if the previous packet has been read completely. if (dataLeft <= 0) { //Read packet headers. int packetLen = in.readInt(); long offsetInBlock = in.readLong(); long seqno = in.readLong(); boolean lastPacketInBlock = in.readBoolean(); if (LOG.isDebugEnabled()) { LOG.debug("DFSClient readChunk got seqno " + seqno + " offsetInBlock " + offsetInBlock + " lastPacketInBlock " + lastPacketInBlock + " packetLen " + packetLen); } int dataLen = in.readInt(); // Sanity check the lengths if ( dataLen < 0 || ( (dataLen % bytesPerChecksum) != 0 && !lastPacketInBlock ) || (seqno != (lastSeqNo + 1)) ) { throw new IOException("BlockReader: error in packet header" + "(chunkOffset : " + chunkOffset + ", dataLen : " + dataLen + ", seqno : " + seqno + " (last: " + lastSeqNo + "))"); } lastSeqNo = seqno; isLastPacket = lastPacketInBlock; dataLeft = dataLen; adjustChecksumBytes(dataLen); if (dataLen > 0) { IOUtils.readFully(in, checksumBytes.array(), 0, checksumBytes.limit()); } } int chunkLen = Math.min(dataLeft, bytesPerChecksum); if ( chunkLen > 0 ) { // len should be >= chunkLen IOUtils.readFully(in, buf, offset, chunkLen); checksumBytes.get(checksumBuf, 0, checksumSize); } dataLeft -= chunkLen; lastChunkOffset = chunkOffset; lastChunkLen = chunkLen; if ((dataLeft == 0 && isLastPacket) || chunkLen == 0) { gotEOS = true; } if ( chunkLen == 0 ) { return -1; } return chunkLen; } private BlockReader( String file, long blockId, DataInputStream in, DataChecksum checksum, boolean verifyChecksum, long startOffset, long firstChunkOffset, Socket dnSock ) { super(new Path("/blk_" + blockId + ":of:" + file)/*too non path-like?*/, 1, verifyChecksum, checksum.getChecksumSize() > 0? checksum : null, checksum.getBytesPerChecksum(), checksum.getChecksumSize()); this.dnSock = dnSock; this.in = in; this.checksum = checksum; this.startOffset = Math.max( startOffset, 0 ); this.firstChunkOffset = firstChunkOffset; lastChunkOffset = firstChunkOffset; lastChunkLen = -1; bytesPerChecksum = this.checksum.getBytesPerChecksum(); checksumSize = this.checksum.getChecksumSize(); } public static BlockReader newBlockReader(Socket sock, String file, long blockId, Token<BlockTokenIdentifier> accessToken, long genStamp, long startOffset, long len, int bufferSize) throws IOException { return newBlockReader(sock, file, blockId, accessToken, genStamp, startOffset, len, bufferSize, true); } /** Java Doc required */ public static BlockReader newBlockReader( Socket sock, String file, long blockId, Token<BlockTokenIdentifier> accessToken, long genStamp, long startOffset, long len, int bufferSize, boolean verifyChecksum) throws IOException { return newBlockReader(sock, file, blockId, accessToken, genStamp, startOffset, len, bufferSize, verifyChecksum, ""); } public static BlockReader newBlockReader( Socket sock, String file, long blockId, Token<BlockTokenIdentifier> accessToken, long genStamp, long startOffset, long len, int bufferSize, boolean verifyChecksum, String clientName) throws IOException { // in and out will be closed when sock is closed (by the caller) DataOutputStream out = new DataOutputStream( new BufferedOutputStream(NetUtils.getOutputStream(sock,HdfsConstants.WRITE_TIMEOUT))); //write the header. out.writeShort( DataTransferProtocol.DATA_TRANSFER_VERSION ); out.write( DataTransferProtocol.OP_READ_BLOCK ); out.writeLong( blockId ); out.writeLong( genStamp ); out.writeLong( startOffset ); out.writeLong( len ); Text.writeString(out, clientName); accessToken.write(out); out.flush(); // // Get bytes in block, set streams // DataInputStream in = new DataInputStream( new BufferedInputStream(NetUtils.getInputStream(sock), bufferSize)); short status = in.readShort(); if (status != DataTransferProtocol.OP_STATUS_SUCCESS) { if (status == DataTransferProtocol.OP_STATUS_ERROR_ACCESS_TOKEN) { throw new InvalidBlockTokenException( "Got access token error for OP_READ_BLOCK, self=" + sock.getLocalSocketAddress() + ", remote=" + sock.getRemoteSocketAddress() + ", for file " + file + ", for block " + blockId + "_" + genStamp); } else { throw new IOException("Got error for OP_READ_BLOCK, self=" + sock.getLocalSocketAddress() + ", remote=" + sock.getRemoteSocketAddress() + ", for file " + file + ", for block " + blockId + "_" + genStamp); } } DataChecksum checksum = DataChecksum.newDataChecksum( in ); //Warning when we get CHECKSUM_NULL? // Read the first chunk offset. long firstChunkOffset = in.readLong(); if ( firstChunkOffset < 0 || firstChunkOffset > startOffset || firstChunkOffset >= (startOffset + checksum.getBytesPerChecksum())) { throw new IOException("BlockReader: error in first chunk offset (" + firstChunkOffset + ") startOffset is " + startOffset + " for file " + file); } return new BlockReader( file, blockId, in, checksum, verifyChecksum, startOffset, firstChunkOffset, sock ); } @Override public synchronized void close() throws IOException { startOffset = -1; checksum = null; // in will be closed when its Socket is closed. } /** kind of like readFully(). Only reads as much as possible. * And allows use of protected readFully(). */ public int readAll(byte[] buf, int offset, int len) throws IOException { return readFully(this, buf, offset, len); } /* When the reader reaches end of a block and there are no checksum * errors, we send OP_STATUS_CHECKSUM_OK to datanode to inform that * checksum was verified and there was no error. */ private void checksumOk(Socket sock) { try { OutputStream out = NetUtils.getOutputStream(sock, HdfsConstants.WRITE_TIMEOUT); byte buf[] = { (DataTransferProtocol.OP_STATUS_CHECKSUM_OK >>> 8) & 0xff, (DataTransferProtocol.OP_STATUS_CHECKSUM_OK) & 0xff }; out.write(buf); out.flush(); } catch (IOException e) { // its ok not to be able to send this. LOG.debug("Could not write to datanode " + sock.getInetAddress() + ": " + e.getMessage()); } } } /**************************************************************** * DFSInputStream provides bytes from a named file. It handles * negotiation of the namenode and various datanodes as necessary. ****************************************************************/ - class DFSInputStream extends FSInputStream { + private class DFSInputStream extends FSInputStream { private Socket s = null; private boolean closed = false; private String src; private long prefetchSize = 10 * defaultBlockSize; private BlockReader blockReader = null; private boolean verifyChecksum; private LocatedBlocks locatedBlocks = null; private DatanodeInfo currentNode = null; private Block currentBlock = null; private long pos = 0; private long blockEnd = -1; /** * This variable tracks the number of failures since the start of the * most recent user-facing operation. That is to say, it should be reset * whenever the user makes a call on this stream, and if at any point * during the retry logic, the failure count exceeds a threshold, * the errors will be thrown back to the operation. * * Specifically this counts the number of times the client has gone * back to the namenode to get a new list of block locations, and is * capped at maxBlockAcquireFailures */ private int failures = 0; /* XXX Use of CocurrentHashMap is temp fix. Need to fix * parallel accesses to DFSInputStream (through ptreads) properly */ private ConcurrentHashMap<DatanodeInfo, DatanodeInfo> deadNodes = new ConcurrentHashMap<DatanodeInfo, DatanodeInfo>(); private int buffersize = 1; private byte[] oneByteBuf = new byte[1]; // used for 'int read()' void addToDeadNodes(DatanodeInfo dnInfo) { deadNodes.put(dnInfo, dnInfo); } DFSInputStream(String src, int buffersize, boolean verifyChecksum ) throws IOException { this.verifyChecksum = verifyChecksum; this.buffersize = buffersize; this.src = src; prefetchSize = conf.getLong("dfs.read.prefetch.size", prefetchSize); openInfo(); } /** * Grab the open-file info from namenode */ synchronized void openInfo() throws IOException { LocatedBlocks newInfo = callGetBlockLocations(namenode, src, 0, prefetchSize); if (newInfo == null) { throw new FileNotFoundException("File does not exist: " + src); } if (locatedBlocks != null) { Iterator<LocatedBlock> oldIter = locatedBlocks.getLocatedBlocks().iterator(); Iterator<LocatedBlock> newIter = newInfo.getLocatedBlocks().iterator(); while (oldIter.hasNext() && newIter.hasNext()) { if (! oldIter.next().getBlock().equals(newIter.next().getBlock())) { throw new IOException("Blocklist for " + src + " has changed!"); } } } this.locatedBlocks = newInfo; this.currentNode = null; } public synchronized long getFileLength() { return (locatedBlocks == null) ? 0 : locatedBlocks.getFileLength(); } /** * Returns the datanode from which the stream is currently reading. */ public DatanodeInfo getCurrentDatanode() { return currentNode; } /** * Returns the block containing the target position. */ public Block getCurrentBlock() { return currentBlock; } /** * Return collection of blocks that has already been located. */ synchronized List<LocatedBlock> getAllBlocks() throws IOException { return getBlockRange(0, this.getFileLength()); } /** * Get block at the specified position. * Fetch it from the namenode if not cached. * * @param offset * @param updatePosition whether to update current position * @return located block * @throws IOException */ private synchronized LocatedBlock getBlockAt(long offset, boolean updatePosition) throws IOException { assert (locatedBlocks != null) : "locatedBlocks is null"; // search cached blocks first int targetBlockIdx = locatedBlocks.findBlock(offset); if (targetBlockIdx < 0) { // block is not cached targetBlockIdx = LocatedBlocks.getInsertIndex(targetBlockIdx); // fetch more blocks LocatedBlocks newBlocks; newBlocks = callGetBlockLocations(namenode, src, offset, prefetchSize); assert (newBlocks != null) : "Could not find target position " + offset; locatedBlocks.insertRange(targetBlockIdx, newBlocks.getLocatedBlocks()); } LocatedBlock blk = locatedBlocks.get(targetBlockIdx); // update current position if (updatePosition) { this.pos = offset; this.blockEnd = blk.getStartOffset() + blk.getBlockSize() - 1; this.currentBlock = blk.getBlock(); } return blk; } /** Fetch a block from namenode and cache it */ private synchronized void fetchBlockAt(long offset) throws IOException { int targetBlockIdx = locatedBlocks.findBlock(offset); if (targetBlockIdx < 0) { // block is not cached targetBlockIdx = LocatedBlocks.getInsertIndex(targetBlockIdx); } // fetch blocks LocatedBlocks newBlocks; newBlocks = callGetBlockLocations(namenode, src, offset, prefetchSize); if (newBlocks == null) { throw new IOException("Could not find target position " + offset); } locatedBlocks.insertRange(targetBlockIdx, newBlocks.getLocatedBlocks()); } /** * Get blocks in the specified range. * Fetch them from the namenode if not cached. * * @param offset * @param length * @return consequent segment of located blocks * @throws IOException */ private synchronized List<LocatedBlock> getBlockRange(long offset, long length) throws IOException { assert (locatedBlocks != null) : "locatedBlocks is null"; List<LocatedBlock> blockRange = new ArrayList<LocatedBlock>(); // search cached blocks first int blockIdx = locatedBlocks.findBlock(offset); if (blockIdx < 0) { // block is not cached blockIdx = LocatedBlocks.getInsertIndex(blockIdx); } long remaining = length; long curOff = offset; while(remaining > 0) { LocatedBlock blk = null; if(blockIdx < locatedBlocks.locatedBlockCount()) blk = locatedBlocks.get(blockIdx); if (blk == null || curOff < blk.getStartOffset()) { LocatedBlocks newBlocks; newBlocks = callGetBlockLocations(namenode, src, curOff, remaining); locatedBlocks.insertRange(blockIdx, newBlocks.getLocatedBlocks()); continue; } assert curOff >= blk.getStartOffset() : "Block not found"; blockRange.add(blk); long bytesRead = blk.getStartOffset() + blk.getBlockSize() - curOff; remaining -= bytesRead; curOff += bytesRead; blockIdx++; } return blockRange; } /** * Open a DataInputStream to a DataNode so that it can be read from. * We get block ID and the IDs of the destinations at startup, from the namenode. */ private synchronized DatanodeInfo blockSeekTo(long target) throws IOException { if (target >= getFileLength()) { throw new IOException("Attempted to read past end of file"); } if ( blockReader != null ) { blockReader.close(); blockReader = null; } if (s != null) { s.close(); s = null; } // // Connect to best DataNode for desired Block, with potential offset // DatanodeInfo chosenNode = null; int refetchToken = 1; // only need to get a new access token once while (true) { // // Compute desired block // LocatedBlock targetBlock = getBlockAt(target, true); assert (target==this.pos) : "Wrong postion " + pos + " expect " + target; long offsetIntoBlock = target - targetBlock.getStartOffset(); DNAddrPair retval = chooseDataNode(targetBlock); chosenNode = retval.info; InetSocketAddress targetAddr = retval.addr; try { s = socketFactory.createSocket(); NetUtils.connect(s, targetAddr, socketTimeout); s.setSoTimeout(socketTimeout); Block blk = targetBlock.getBlock(); Token<BlockTokenIdentifier> accessToken = targetBlock.getBlockToken(); blockReader = BlockReader.newBlockReader(s, src, blk.getBlockId(), accessToken, blk.getGenerationStamp(), offsetIntoBlock, blk.getNumBytes() - offsetIntoBlock, buffersize, verifyChecksum, clientName); return chosenNode; } catch (IOException ex) { if (ex instanceof InvalidBlockTokenException && refetchToken > 0) { LOG.info("Will fetch a new access token and retry, " + "access token was invalid when connecting to " + targetAddr + " : " + ex); /* * Get a new access token and retry. Retry is needed in 2 cases. 1) * When both NN and DN re-started while DFSClient holding a cached * access token. 2) In the case that NN fails to update its * access key at pre-set interval (by a wide margin) and * subsequently restarts. In this case, DN re-registers itself with * NN and receives a new access key, but DN will delete the old * access key from its memory since it's considered expired based on * the estimated expiration date. */ refetchToken--; fetchBlockAt(target); } else { LOG.info("Failed to connect to " + targetAddr + ", add to deadNodes and continue", ex); // Put chosen node into dead list, continue addToDeadNodes(chosenNode); } if (s != null) { try { s.close(); } catch (IOException iex) { } } s = null; } } } /** * Close it down! */ @Override public synchronized void close() throws IOException { if (closed) { return; } checkOpen(); if ( blockReader != null ) { blockReader.close(); blockReader = null; } if (s != null) { s.close(); s = null; } super.close(); closed = true; } @Override public synchronized int read() throws IOException { int ret = read( oneByteBuf, 0, 1 ); return ( ret <= 0 ) ? -1 : (oneByteBuf[0] & 0xff); } /* This is a used by regular read() and handles ChecksumExceptions. * name readBuffer() is chosen to imply similarity to readBuffer() in * ChecksuFileSystem */ private synchronized int readBuffer(byte buf[], int off, int len) throws IOException { IOException ioe; /* we retry current node only once. So this is set to true only here. * Intention is to handle one common case of an error that is not a * failure on datanode or client : when DataNode closes the connection * since client is idle. If there are other cases of "non-errors" then * then a datanode might be retried by setting this to true again. */ boolean retryCurrentNode = true; while (true) { // retry as many times as seekToNewSource allows. try { return blockReader.read(buf, off, len); } catch ( ChecksumException ce ) { LOG.warn("Found Checksum error for " + currentBlock + " from " + currentNode.getName() + " at " + ce.getPos()); reportChecksumFailure(src, currentBlock, currentNode); ioe = ce; retryCurrentNode = false; } catch ( IOException e ) { if (!retryCurrentNode) { LOG.warn("Exception while reading from " + currentBlock + " of " + src + " from " + currentNode + ": " + StringUtils.stringifyException(e)); } ioe = e; } boolean sourceFound = false; if (retryCurrentNode) { /* possibly retry the same node so that transient errors don't * result in application level failures (e.g. Datanode could have * closed the connection because the client is idle for too long). */ sourceFound = seekToBlockSource(pos); } else { addToDeadNodes(currentNode); sourceFound = seekToNewSource(pos); } if (!sourceFound) { throw ioe; } retryCurrentNode = false; } } /** * Read the entire buffer. */ @Override public synchronized int read(byte buf[], int off, int len) throws IOException { checkOpen(); if (closed) { throw new IOException("Stream closed"); } failures = 0; if (pos < getFileLength()) { int retries = 2; while (retries > 0) { try { if (pos > blockEnd) { currentNode = blockSeekTo(pos); } int realLen = Math.min(len, (int) (blockEnd - pos + 1)); int result = readBuffer(buf, off, realLen); if (result >= 0) { pos += result; } else { // got a EOS from reader though we expect more data on it. throw new IOException("Unexpected EOS from the reader"); } if (stats != null && result != -1) { stats.incrementBytesRead(result); } return result; } catch (ChecksumException ce) { throw ce; } catch (IOException e) { if (retries == 1) { LOG.warn("DFS Read: " + StringUtils.stringifyException(e)); } blockEnd = -1; if (currentNode != null) { addToDeadNodes(currentNode); } if (--retries == 0) { throw e; } } } } return -1; } private DNAddrPair chooseDataNode(LocatedBlock block) throws IOException { while (true) { DatanodeInfo[] nodes = block.getLocations(); try { DatanodeInfo chosenNode = bestNode(nodes, deadNodes); InetSocketAddress targetAddr = NetUtils.createSocketAddr(chosenNode.getName()); return new DNAddrPair(chosenNode, targetAddr); } catch (IOException ie) { String blockInfo = block.getBlock() + " file=" + src; if (failures >= maxBlockAcquireFailures) { throw new IOException("Could not obtain block: " + blockInfo); } if (nodes == null || nodes.length == 0) { LOG.info("No node available for block: " + blockInfo); } LOG.info("Could not obtain block " + block.getBlock() + " from any node: " + ie + ". Will get new block locations from namenode and retry..."); try { Thread.sleep(3000); } catch (InterruptedException iex) { } deadNodes.clear(); //2nd option is to remove only nodes[blockId] openInfo(); block = getBlockAt(block.getStartOffset(), false); failures++; continue; } } } private void fetchBlockByteRange(LocatedBlock block, long start, long end, byte[] buf, int offset) throws IOException { // // Connect to best DataNode for desired Block, with potential offset // Socket dn = null; int refetchToken = 1; // only need to get a new access token once while (true) { // cached block locations may have been updated by chooseDataNode() // or fetchBlockAt(). Always get the latest list of locations at the // start of the loop. block = getBlockAt(block.getStartOffset(), false); DNAddrPair retval = chooseDataNode(block); DatanodeInfo chosenNode = retval.info; InetSocketAddress targetAddr = retval.addr; BlockReader reader = null; try { dn = socketFactory.createSocket(); NetUtils.connect(dn, targetAddr, socketTimeout); dn.setSoTimeout(socketTimeout); Token<BlockTokenIdentifier> accessToken = block.getBlockToken(); int len = (int) (end - start + 1); reader = BlockReader.newBlockReader(dn, src, block.getBlock().getBlockId(), accessToken, block.getBlock().getGenerationStamp(), start, len, buffersize, verifyChecksum, clientName); int nread = reader.readAll(buf, offset, len); if (nread != len) { throw new IOException("truncated return from reader.read(): " + "excpected " + len + ", got " + nread); } return; } catch (ChecksumException e) { LOG.warn("fetchBlockByteRange(). Got a checksum exception for " + src + " at " + block.getBlock() + ":" + e.getPos() + " from " + chosenNode.getName()); reportChecksumFailure(src, block.getBlock(), chosenNode); } catch (IOException e) { if (e instanceof InvalidBlockTokenException && refetchToken > 0) { LOG.info("Will get a new access token and retry, " + "access token was invalid when connecting to " + targetAddr + " : " + e); refetchToken--; fetchBlockAt(block.getStartOffset()); continue; } else { LOG.warn("Failed to connect to " + targetAddr + " for file " + src + " for block " + block.getBlock() + ":" + StringUtils.stringifyException(e)); } } finally { IOUtils.closeStream(reader); IOUtils.closeSocket(dn); } // Put chosen node into dead list, continue addToDeadNodes(chosenNode); } } /** * Read bytes starting from the specified position. * * @param position start read from this position * @param buffer read buffer * @param offset offset into buffer * @param length number of bytes to read * * @return actual number of bytes read */ @Override public int read(long position, byte[] buffer, int offset, int length) throws IOException { // sanity checks checkOpen(); if (closed) { throw new IOException("Stream closed"); } failures = 0; long filelen = getFileLength(); if ((position < 0) || (position >= filelen)) { return -1; } int realLen = length; if ((position + length) > filelen) { realLen = (int)(filelen - position); } // determine the block and byte range within the block // corresponding to position and realLen List<LocatedBlock> blockRange = getBlockRange(position, realLen); int remaining = realLen; for (LocatedBlock blk : blockRange) { long targetStart = position - blk.getStartOffset(); long bytesToRead = Math.min(remaining, blk.getBlockSize() - targetStart); fetchBlockByteRange(blk, targetStart, targetStart + bytesToRead - 1, buffer, offset); remaining -= bytesToRead; position += bytesToRead; offset += bytesToRead; } assert remaining == 0 : "Wrong number of bytes read."; if (stats != null) { stats.incrementBytesRead(realLen); } return realLen; } @Override public long skip(long n) throws IOException { if ( n > 0 ) { long curPos = getPos(); long fileLen = getFileLength(); if( n+curPos > fileLen ) { n = fileLen - curPos; } seek(curPos+n); return n; } return n < 0 ? -1 : 0; } /** * Seek to a new arbitrary location */ @Override public synchronized void seek(long targetPos) throws IOException { if (targetPos > getFileLength()) { throw new IOException("Cannot seek after EOF"); } boolean done = false; if (pos <= targetPos && targetPos <= blockEnd) { // // If this seek is to a positive position in the current // block, and this piece of data might already be lying in // the TCP buffer, then just eat up the intervening data. // int diff = (int)(targetPos - pos); if (diff <= TCP_WINDOW_SIZE) { try { pos += blockReader.skip(diff); if (pos == targetPos) { done = true; } } catch (IOException e) {//make following read to retry LOG.debug("Exception while seek to " + targetPos + " from " + currentBlock +" of " + src + " from " + currentNode + ": " + StringUtils.stringifyException(e)); } } } if (!done) { pos = targetPos; blockEnd = -1; } } /** * Same as {@link #seekToNewSource(long)} except that it does not exclude * the current datanode and might connect to the same node. */ private synchronized boolean seekToBlockSource(long targetPos) throws IOException { currentNode = blockSeekTo(targetPos); return true; } /** * Seek to given position on a node other than the current node. If * a node other than the current node is found, then returns true. * If another node could not be found, then returns false. */ @Override public synchronized boolean seekToNewSource(long targetPos) throws IOException { boolean markedDead = deadNodes.containsKey(currentNode); addToDeadNodes(currentNode); DatanodeInfo oldNode = currentNode; DatanodeInfo newNode = blockSeekTo(targetPos); if (!markedDead) { /* remove it from deadNodes. blockSeekTo could have cleared * deadNodes and added currentNode again. Thats ok. */ deadNodes.remove(oldNode); } if (!oldNode.getStorageID().equals(newNode.getStorageID())) { currentNode = newNode; return true; } else { return false; } } /** */ @Override public synchronized long getPos() throws IOException { return pos; } /** */ @Override public synchronized int available() throws IOException { if (closed) { throw new IOException("Stream closed"); } return (int) (getFileLength() - pos); } /** * We definitely don't support marks */ @Override public boolean markSupported() { return false; } @Override public void mark(int readLimit) { } @Override public void reset() throws IOException { throw new IOException("Mark/reset not supported"); } } - - static class DFSDataInputStream extends FSDataInputStream { + + /** + * The Hdfs implementation of {@link FSDataInputStream} + */ + public static class DFSDataInputStream extends FSDataInputStream { DFSDataInputStream(DFSInputStream in) throws IOException { super(in); } /** * Returns the datanode from which the stream is currently reading. */ public DatanodeInfo getCurrentDatanode() { return ((DFSInputStream)in).getCurrentDatanode(); } /** * Returns the block containing the target position. */ public Block getCurrentBlock() { return ((DFSInputStream)in).getCurrentBlock(); } /** * Return collection of blocks that has already been located. */ synchronized List<LocatedBlock> getAllBlocks() throws IOException { return ((DFSInputStream)in).getAllBlocks(); } + /** + * @return The visible length of the file. + */ + public long getVisibleLength() throws IOException { + return ((DFSInputStream)in).getFileLength(); + } } /**************************************************************** * DFSOutputStream creates files from a stream of bytes. * * The client application writes data that is cached internally by * this stream. Data is broken up into packets, each packet is * typically 64K in size. A packet comprises of chunks. Each chunk * is typically 512 bytes and has an associated checksum with it. * * When a client application fills up the currentPacket, it is * enqueued into dataQueue. The DataStreamer thread picks up * packets from the dataQueue, sends it to the first datanode in * the pipeline and moves it from the dataQueue to the ackQueue. * The ResponseProcessor receives acks from the datanodes. When an * successful ack for a packet is received from all datanodes, the * ResponseProcessor removes the corresponding packet from the * ackQueue. * * In case of error, all outstanding packets and moved from * ackQueue. A new pipeline is setup by eliminating the bad * datanode from the original pipeline. The DataStreamer now * starts sending packets from the dataQueue. ****************************************************************/ class DFSOutputStream extends FSOutputSummer implements Syncable { private Socket s; boolean closed = false; private String src; private DataOutputStream blockStream; private DataInputStream blockReplyStream; private Block block; private Token<BlockTokenIdentifier> accessToken; final private long blockSize; private DataChecksum checksum; private LinkedList<Packet> dataQueue = new LinkedList<Packet>(); private LinkedList<Packet> ackQueue = new LinkedList<Packet>(); private Packet currentPacket = null; private int maxPackets = 80; // each packet 64K, total 5MB // private int maxPackets = 1000; // each packet 64K, total 64MB private DataStreamer streamer = new DataStreamer();; private ResponseProcessor response = null; private long currentSeqno = 0; private long bytesCurBlock = 0; // bytes writen in current block private int packetSize = 0; // write packet size, including the header. private int chunksPerPacket = 0; private DatanodeInfo[] nodes = null; // list of targets for current block private volatile boolean hasError = false; private volatile int errorIndex = 0; private volatile IOException lastException = null; private long artificialSlowdown = 0; private long lastFlushOffset = -1; // offset when flush was invoked private boolean persistBlocks = false; // persist blocks on namenode private int recoveryErrorCount = 0; // number of times block recovery failed private int maxRecoveryErrorCount = 5; // try block recovery 5 times private volatile boolean appendChunk = false; // appending to existing partial block private long initialFileSize = 0; // at time of file open Token<BlockTokenIdentifier> getAccessToken() { return accessToken; } private void setLastException(IOException e) { if (lastException == null) { lastException = e; } } private class Packet { ByteBuffer buffer; // only one of buf and buffer is non-null byte[] buf; long seqno; // sequencenumber of buffer in block long offsetInBlock; // offset in block boolean lastPacketInBlock; // is this the last packet in block? int numChunks; // number of chunks currently in packet int maxChunks; // max chunks in packet int dataStart; int dataPos; int checksumStart; int checksumPos; // create a new packet Packet(int pktSize, int chunksPerPkt, long offsetInBlock) { this.lastPacketInBlock = false; this.numChunks = 0; this.offsetInBlock = offsetInBlock; this.seqno = currentSeqno; currentSeqno++; buffer = null; buf = new byte[pktSize]; checksumStart = DataNode.PKT_HEADER_LEN + SIZE_OF_INTEGER; checksumPos = checksumStart; dataStart = checksumStart + chunksPerPkt * checksum.getChecksumSize(); dataPos = dataStart; maxChunks = chunksPerPkt; } void writeData(byte[] inarray, int off, int len) { if ( dataPos + len > buf.length) { throw new BufferOverflowException(); } System.arraycopy(inarray, off, buf, dataPos, len); dataPos += len; } void writeChecksum(byte[] inarray, int off, int len) { if (checksumPos + len > dataStart) { throw new BufferOverflowException(); } System.arraycopy(inarray, off, buf, checksumPos, len); checksumPos += len; } /** * Returns ByteBuffer that contains one full packet, including header. */ ByteBuffer getBuffer() { /* Once this is called, no more data can be added to the packet. * setting 'buf' to null ensures that. * This is called only when the packet is ready to be sent. */ if (buffer != null) { return buffer; } //prepare the header and close any gap between checksum and data. int dataLen = dataPos - dataStart; int checksumLen = checksumPos - checksumStart; if (checksumPos != dataStart) { /* move the checksum to cover the gap. * This can happen for the last packet. */ System.arraycopy(buf, checksumStart, buf, dataStart - checksumLen , checksumLen); } int pktLen = SIZE_OF_INTEGER + dataLen + checksumLen; //normally dataStart == checksumPos, i.e., offset is zero. buffer = ByteBuffer.wrap(buf, dataStart - checksumPos, DataNode.PKT_HEADER_LEN + pktLen); buf = null; buffer.mark(); /* write the header and data length. * The format is described in comment before DataNode.BlockSender */ buffer.putInt(pktLen); // pktSize buffer.putLong(offsetInBlock); buffer.putLong(seqno); buffer.put((byte) ((lastPacketInBlock) ? 1 : 0)); //end of pkt header buffer.putInt(dataLen); // actual data length, excluding checksum. buffer.reset(); return buffer; } } // // The DataStreamer class is responsible for sending data packets to the // datanodes in the pipeline. It retrieves a new blockid and block locations // from the namenode, and starts streaming packets to the pipeline of // Datanodes. Every packet has a sequence number associated with // it. When all the packets for a block are sent out and acks for each // if them are received, the DataStreamer closes the current block. // private class DataStreamer extends Daemon { private volatile boolean closed = false; public void run() { while (!closed && clientRunning) { // if the Responder encountered an error, shutdown Responder if (hasError && response != null) { try { response.close(); response.join(); response = null; } catch (InterruptedException e) { } } Packet one = null; synchronized (dataQueue) { // process IO errors if any boolean doSleep = processDatanodeError(hasError, false); // wait for a packet to be sent. while ((!closed && !hasError && clientRunning && dataQueue.size() == 0) || doSleep) { try { dataQueue.wait(1000); } catch (InterruptedException e) { } doSleep = false; } if (closed || hasError || dataQueue.size() == 0 || !clientRunning) { continue; } try { // get packet to be sent. one = dataQueue.getFirst(); long offsetInBlock = one.offsetInBlock; // get new block from namenode. if (blockStream == null) { LOG.debug("Allocating new block"); nodes = nextBlockOutputStream(src); this.setName("DataStreamer for file " + src + " block " + block); response = new ResponseProcessor(nodes); response.start(); } if (offsetInBlock >= blockSize) { throw new IOException("BlockSize " + blockSize + " is smaller than data size. " + " Offset of packet in block " + offsetInBlock + " Aborting file " + src); } ByteBuffer buf = one.getBuffer(); // move packet from dataQueue to ackQueue dataQueue.removeFirst(); dataQueue.notifyAll(); synchronized (ackQueue) { ackQueue.addLast(one); ackQueue.notifyAll(); } // write out data to remote datanode blockStream.write(buf.array(), buf.position(), buf.remaining()); if (one.lastPacketInBlock) { blockStream.writeInt(0); // indicate end-of-block } blockStream.flush(); if (LOG.isDebugEnabled()) { LOG.debug("DataStreamer block " + block + " wrote packet seqno:" + one.seqno + " size:" + buf.remaining() + " offsetInBlock:" + one.offsetInBlock + " lastPacketInBlock:" + one.lastPacketInBlock); } } catch (Throwable e) { LOG.warn("DataStreamer Exception: " + StringUtils.stringifyException(e)); if (e instanceof IOException) { setLastException((IOException)e); } hasError = true; } } if (closed || hasError || !clientRunning) { continue; } // Is this block full? if (one.lastPacketInBlock) { synchronized (ackQueue) { while (!hasError && ackQueue.size() != 0 && clientRunning) { try { ackQueue.wait(); // wait for acks to arrive from datanodes } catch (InterruptedException e) { } } } LOG.debug("Closing old block " + block); this.setName("DataStreamer for file " + src); response.close(); // ignore all errors in Response try { response.join(); response = null; } catch (InterruptedException e) { } if (closed || hasError || !clientRunning) { continue; } synchronized (dataQueue) { try { blockStream.close(); blockReplyStream.close(); } catch (IOException e) { } nodes = null; response = null; blockStream = null; blockReplyStream = null; } } if (progress != null) { progress.progress(); } // This is used by unit test to trigger race conditions. if (artificialSlowdown != 0 && clientRunning) { try { Thread.sleep(artificialSlowdown); } catch (InterruptedException e) {} } } } // shutdown thread void close() { closed = true; synchronized (dataQueue) { dataQueue.notifyAll(); } synchronized (ackQueue) { ackQueue.notifyAll(); } this.interrupt(); } } // // Processes reponses from the datanodes. A packet is removed // from the ackQueue when its response arrives. // private class ResponseProcessor extends Thread { private volatile boolean closed = false; private DatanodeInfo[] targets = null; private boolean lastPacketInBlock = false; ResponseProcessor (DatanodeInfo[] targets) { this.targets = targets; } public void run() { this.setName("ResponseProcessor for block " + block); PipelineAck ack = new PipelineAck(); while (!closed && clientRunning && !lastPacketInBlock) { // process responses from datanodes. try { // read an ack from the pipeline ack.readFields(blockReplyStream); if (LOG.isDebugEnabled()) { LOG.debug("DFSClient " + ack); } long seqno = ack.getSeqno(); if (seqno == PipelineAck.HEART_BEAT.getSeqno()) { continue; } else if (seqno == -2) { // no nothing } else { Packet one = null; synchronized (ackQueue) { one = ackQueue.getFirst(); } if (one.seqno != seqno) { throw new IOException("Responseprocessor: Expecting seqno " + " for block " + block + one.seqno + " but received " + seqno); } lastPacketInBlock = one.lastPacketInBlock; } // processes response status from all datanodes. for (int i = ack.getNumOfReplies()-1; i >=0 && clientRunning; i--) { short reply = ack.getReply(i); if (reply != DataTransferProtocol.OP_STATUS_SUCCESS) { errorIndex = i; // first bad datanode throw new IOException("Bad response " + reply + " for block " + block + " from datanode " + targets[i].getName()); } } synchronized (ackQueue) { ackQueue.removeFirst(); ackQueue.notifyAll(); } } catch (Exception e) { if (!closed) { hasError = true; if (e instanceof IOException) { setLastException((IOException)e); } LOG.warn("DFSOutputStream ResponseProcessor exception " + " for block " + block + StringUtils.stringifyException(e)); closed = true; } } synchronized (dataQueue) { dataQueue.notifyAll(); } synchronized (ackQueue) { ackQueue.notifyAll(); } } } void close() { closed = true; this.interrupt(); } } // If this stream has encountered any errors so far, shutdown // threads and mark stream as closed. Returns true if we should // sleep for a while after returning from this call. // private boolean processDatanodeError(boolean hasError, boolean isAppend) { if (!hasError) { return false; } if (response != null) { LOG.info("Error Recovery for block " + block + " waiting for responder to exit. "); return true; } if (errorIndex >= 0) { LOG.warn("Error Recovery for block " + block + " bad datanode[" + errorIndex + "] " + (nodes == null? "nodes == null": nodes[errorIndex].getName())); } if (blockStream != null) { try { blockStream.close(); blockReplyStream.close(); } catch (IOException e) { } } blockStream = null; blockReplyStream = null; // move packets from ack queue to front of the data queue synchronized (ackQueue) { dataQueue.addAll(0, ackQueue); ackQueue.clear(); } boolean success = false; while (!success && clientRunning) { DatanodeInfo[] newnodes = null; if (nodes == null) { String msg = "Could not get block locations. " + "Source file \"" + src + "\" - Aborting..."; LOG.warn(msg); setLastException(new IOException(msg)); closed = true; if (streamer != null) streamer.close(); return false; } StringBuilder pipelineMsg = new StringBuilder(); for (int j = 0; j < nodes.length; j++) { pipelineMsg.append(nodes[j].getName()); if (j < nodes.length - 1) { pipelineMsg.append(", "); } } // remove bad datanode from list of datanodes. // If errorIndex was not set (i.e. appends), then do not remove // any datanodes // if (errorIndex < 0) { newnodes = nodes; } else { if (nodes.length <= 1) { lastException = new IOException("All datanodes " + pipelineMsg + " are bad. Aborting..."); closed = true; if (streamer != null) streamer.close(); return false; } LOG.warn("Error Recovery for block " + block + " in pipeline " + pipelineMsg + ": bad datanode " + nodes[errorIndex].getName()); newnodes = new DatanodeInfo[nodes.length-1]; System.arraycopy(nodes, 0, newnodes, 0, errorIndex); System.arraycopy(nodes, errorIndex+1, newnodes, errorIndex, newnodes.length-errorIndex); } // Tell the primary datanode to do error recovery // by stamping appropriate generation stamps. // LocatedBlock newBlock = null; ClientDatanodeProtocol primary = null; DatanodeInfo primaryNode = null; try { // Pick the "least" datanode as the primary datanode to avoid deadlock. primaryNode = Collections.min(Arrays.asList(newnodes)); primary = createClientDatanodeProtocolProxy(primaryNode, conf, block, accessToken); newBlock = primary.recoverBlock(block, isAppend, newnodes); } catch (IOException e) { recoveryErrorCount++; if (recoveryErrorCount > maxRecoveryErrorCount) { if (nodes.length > 1) { // if the primary datanode failed, remove it from the list. // The original bad datanode is left in the list because it is // conservative to remove only one datanode in one iteration. for (int j = 0; j < nodes.length; j++) { if (nodes[j].equals(primaryNode)) { errorIndex = j; // forget original bad node. } } // remove primary node from list newnodes = new DatanodeInfo[nodes.length-1]; System.arraycopy(nodes, 0, newnodes, 0, errorIndex); System.arraycopy(nodes, errorIndex+1, newnodes, errorIndex, newnodes.length-errorIndex); nodes = newnodes; LOG.warn("Error Recovery for block " + block + " failed " + " because recovery from primary datanode " + primaryNode + " failed " + recoveryErrorCount + " times. " + " Pipeline was " + pipelineMsg + ". Marking primary datanode as bad."); recoveryErrorCount = 0; errorIndex = -1; return true; // sleep when we return from here } String emsg = "Error Recovery for block " + block + " failed " + " because recovery from primary datanode " + primaryNode + " failed " + recoveryErrorCount + " times. " + " Pipeline was " + pipelineMsg + ". Aborting..."; LOG.warn(emsg); lastException = new IOException(emsg); closed = true; if (streamer != null) streamer.close(); return false; // abort with IOexception } LOG.warn("Error Recovery for block " + block + " failed " + " because recovery from primary datanode " + primaryNode + " failed " + recoveryErrorCount + " times. " + " Pipeline was " + pipelineMsg + ". Will retry..."); return true; // sleep when we return from here } finally { RPC.stopProxy(primary); } recoveryErrorCount = 0; // block recovery successful // If the block recovery generated a new generation stamp, use that // from now on. Also, setup new pipeline // newBlock should never be null and it should contain a newly // generated access token. block = newBlock.getBlock(); accessToken = newBlock.getBlockToken(); nodes = newBlock.getLocations(); this.hasError = false; lastException = null; errorIndex = 0; success = createBlockOutputStream(nodes, clientName, true); } response = new ResponseProcessor(nodes); response.start(); return false; // do not sleep, continue processing } private void isClosed() throws IOException { if (closed && lastException != null) { throw lastException; } } // // returns the list of targets, if any, that is being currently used. // DatanodeInfo[] getPipeline() { synchronized (dataQueue) { if (nodes == null) { return null; } DatanodeInfo[] value = new DatanodeInfo[nodes.length]; for (int i = 0; i < nodes.length; i++) { value[i] = nodes[i]; } return value; } } private Progressable progress; private DFSOutputStream(String src, long blockSize, Progressable progress, int bytesPerChecksum) throws IOException { super(new CRC32(), bytesPerChecksum, 4); this.src = src; this.blockSize = blockSize; this.progress = progress; if (progress != null) { LOG.debug("Set non-null progress callback on DFSOutputStream "+src); } if ( bytesPerChecksum < 1 || blockSize % bytesPerChecksum != 0) { throw new IOException("io.bytes.per.checksum(" + bytesPerChecksum + ") and blockSize(" + blockSize + ") do not match. " + "blockSize should be a " + "multiple of io.bytes.per.checksum"); } checksum = DataChecksum.newDataChecksum(DataChecksum.CHECKSUM_CRC32, bytesPerChecksum); } /** * Create a new output stream to the given DataNode. * @see ClientProtocol#create(String, FsPermission, String, boolean, short, long) */ DFSOutputStream(String src, FsPermission masked, boolean overwrite, short replication, long blockSize, Progressable progress, int buffersize, int bytesPerChecksum) throws IOException { this(src, blockSize, progress, bytesPerChecksum); computePacketChunkSize(writePacketSize, bytesPerChecksum); try { namenode.create( src, masked, clientName, overwrite, replication, blockSize); } catch(RemoteException re) { throw re.unwrapRemoteException(AccessControlException.class, NSQuotaExceededException.class, DSQuotaExceededException.class); } streamer.start(); } /** * Create a new output stream to the given DataNode. * @see ClientProtocol#create(String, FsPermission, String, boolean, short, long) */ DFSOutputStream(String src, int buffersize, Progressable progress, LocatedBlock lastBlock, HdfsFileStatus stat, int bytesPerChecksum) throws IOException { this(src, stat.getBlockSize(), progress, bytesPerChecksum); initialFileSize = stat.getLen(); // length of file when opened // // The last partial block of the file has to be filled. // if (lastBlock != null) { block = lastBlock.getBlock(); accessToken = lastBlock.getBlockToken(); long usedInLastBlock = stat.getLen() % blockSize; int freeInLastBlock = (int)(blockSize - usedInLastBlock); // calculate the amount of free space in the pre-existing // last crc chunk int usedInCksum = (int)(stat.getLen() % bytesPerChecksum); int freeInCksum = bytesPerChecksum - usedInCksum; // if there is space in the last block, then we have to // append to that block if (freeInLastBlock > blockSize) { throw new IOException("The last block for file " + src + " is full."); } // indicate that we are appending to an existing block bytesCurBlock = lastBlock.getBlockSize(); if (usedInCksum > 0 && freeInCksum > 0) { // if there is space in the last partial chunk, then // setup in such a way that the next packet will have only // one chunk that fills up the partial chunk. // computePacketChunkSize(0, freeInCksum); resetChecksumChunk(freeInCksum); this.appendChunk = true; } else { // if the remaining space in the block is smaller than // that expected size of of a packet, then create // smaller size packet. // computePacketChunkSize(Math.min(writePacketSize, freeInLastBlock), bytesPerChecksum); } // setup pipeline to append to the last block XXX retries?? nodes = lastBlock.getLocations(); errorIndex = -1; // no errors yet. if (nodes.length < 1) { throw new IOException("Unable to retrieve blocks locations " + " for last block " + block + "of file " + src); } processDatanodeError(true, true); streamer.start(); } else { computePacketChunkSize(writePacketSize, bytesPerChecksum); streamer.start(); } } private void computePacketChunkSize(int psize, int csize) { int chunkSize = csize + checksum.getChecksumSize(); int n = DataNode.PKT_HEADER_LEN + SIZE_OF_INTEGER; chunksPerPacket = Math.max((psize - n + chunkSize-1)/chunkSize, 1); packetSize = n + chunkSize*chunksPerPacket; if (LOG.isDebugEnabled()) { LOG.debug("computePacketChunkSize: src=" + src + ", chunkSize=" + chunkSize + ", chunksPerPacket=" + chunksPerPacket + ", packetSize=" + packetSize); } } /** * Open a DataOutputStream to a DataNode so that it can be written to. * This happens when a file is created and each time a new block is allocated. * Must get block ID and the IDs of the destinations from the namenode. * Returns the list of target datanodes. */ private DatanodeInfo[] nextBlockOutputStream(String client) throws IOException { LocatedBlock lb = null; boolean retry = false; DatanodeInfo[] nodes; int count = conf.getInt("dfs.client.block.write.retries", 3); boolean success; do { hasError = false; lastException = null; errorIndex = 0; retry = false; nodes = null; success = false; long startTime = System.currentTimeMillis(); lb = locateFollowingBlock(startTime); block = lb.getBlock(); accessToken = lb.getBlockToken(); nodes = lb.getLocations(); // // Connect to first DataNode in the list. // success = createBlockOutputStream(nodes, clientName, false); if (!success) { LOG.info("Abandoning block " + block); namenode.abandonBlock(block, src, clientName); // Connection failed. Let's wait a little bit and retry retry = true; try { if (System.currentTimeMillis() - startTime > 5000) { LOG.info("Waiting to find target node: " + nodes[0].getName()); } Thread.sleep(6000); } catch (InterruptedException iex) { } } } while (retry && --count >= 0); if (!success) { throw new IOException("Unable to create new block."); } return nodes; } // connects to the first datanode in the pipeline // Returns true if success, otherwise return failure. // private boolean createBlockOutputStream(DatanodeInfo[] nodes, String client, boolean recoveryFlag) { short pipelineStatus = (short)DataTransferProtocol.OP_STATUS_SUCCESS; String firstBadLink = ""; if (LOG.isDebugEnabled()) { for (int i = 0; i < nodes.length; i++) { LOG.debug("pipeline = " + nodes[i].getName()); } } // persist blocks on namenode on next flush persistBlocks = true; try { LOG.debug("Connecting to " + nodes[0].getName()); InetSocketAddress target = NetUtils.createSocketAddr(nodes[0].getName()); s = socketFactory.createSocket(); int timeoutValue = 3000 * nodes.length + socketTimeout; NetUtils.connect(s, target, timeoutValue); s.setSoTimeout(timeoutValue); s.setSendBufferSize(DEFAULT_DATA_SOCKET_SIZE); LOG.debug("Send buf size " + s.getSendBufferSize()); long writeTimeout = HdfsConstants.WRITE_TIMEOUT_EXTENSION * nodes.length + datanodeWriteTimeout; // // Xmit header info to datanode // DataOutputStream out = new DataOutputStream( new BufferedOutputStream(NetUtils.getOutputStream(s, writeTimeout), DataNode.SMALL_BUFFER_SIZE)); blockReplyStream = new DataInputStream(NetUtils.getInputStream(s)); out.writeShort( DataTransferProtocol.DATA_TRANSFER_VERSION ); out.write( DataTransferProtocol.OP_WRITE_BLOCK ); out.writeLong( block.getBlockId() ); out.writeLong( block.getGenerationStamp() ); out.writeInt( nodes.length ); out.writeBoolean( recoveryFlag ); // recovery flag Text.writeString( out, client ); out.writeBoolean(false); // Not sending src node information out.writeInt( nodes.length - 1 ); for (int i = 1; i < nodes.length; i++) { nodes[i].write(out); } accessToken.write(out); checksum.writeHeader( out ); out.flush(); // receive ack for connect pipelineStatus = blockReplyStream.readShort(); firstBadLink = Text.readString(blockReplyStream); if (pipelineStatus != DataTransferProtocol.OP_STATUS_SUCCESS) { if (pipelineStatus == DataTransferProtocol.OP_STATUS_ERROR_ACCESS_TOKEN) { throw new InvalidBlockTokenException( "Got access token error for connect ack with firstBadLink as " + firstBadLink); } else { throw new IOException("Bad connect ack with firstBadLink as " + firstBadLink); } } blockStream = out; return true; // success } catch (IOException ie) { LOG.info("Exception in createBlockOutputStream " + ie); // find the datanode that matches if (firstBadLink.length() != 0) { for (int i = 0; i < nodes.length; i++) { if (nodes[i].getName().equals(firstBadLink)) { errorIndex = i; break; } } } hasError = true; setLastException(ie); blockReplyStream = null; return false; // error } } private LocatedBlock locateFollowingBlock(long start ) throws IOException { int retries = conf.getInt("dfs.client.block.write.locateFollowingBlock.retries", 5); long sleeptime = 400; while (true) { long localstart = System.currentTimeMillis(); while (true) { try { return namenode.addBlock(src, clientName); } catch (RemoteException e) { IOException ue = e.unwrapRemoteException(FileNotFoundException.class, AccessControlException.class, NSQuotaExceededException.class, DSQuotaExceededException.class); if (ue != e) { throw ue; // no need to retry these exceptions } if (NotReplicatedYetException.class.getName(). equals(e.getClassName())) { if (retries == 0) { throw e; } else { --retries; LOG.info(StringUtils.stringifyException(e)); if (System.currentTimeMillis() - localstart > 5000) { LOG.info("Waiting for replication for " + (System.currentTimeMillis() - localstart) / 1000 + " seconds"); } try { LOG.warn("NotReplicatedYetException sleeping " + src + " retries left " + retries); Thread.sleep(sleeptime); sleeptime *= 2; } catch (InterruptedException ie) { } } } else { throw e; } } } } } // @see FSOutputSummer#writeChunk() @Override protected synchronized void writeChunk(byte[] b, int offset, int len, byte[] checksum) throws IOException { checkOpen(); isClosed(); int cklen = checksum.length; int bytesPerChecksum = this.checksum.getBytesPerChecksum(); if (len > bytesPerChecksum) { throw new IOException("writeChunk() buffer size is " + len + " is larger than supported bytesPerChecksum " + bytesPerChecksum); } if (checksum.length != this.checksum.getChecksumSize()) { throw new IOException("writeChunk() checksum size is supposed to be " + this.checksum.getChecksumSize() + " but found to be " + checksum.length); } synchronized (dataQueue) { // If queue is full, then wait till we can create enough space while (!closed && dataQueue.size() + ackQueue.size() > maxPackets) { try { dataQueue.wait(); } catch (InterruptedException e) { } } isClosed(); if (currentPacket == null) { currentPacket = new Packet(packetSize, chunksPerPacket, bytesCurBlock); if (LOG.isDebugEnabled()) { LOG.debug("DFSClient writeChunk allocating new packet seqno=" + currentPacket.seqno + ", src=" + src + ", packetSize=" + packetSize + ", chunksPerPacket=" + chunksPerPacket + ", bytesCurBlock=" + bytesCurBlock); } } currentPacket.writeChecksum(checksum, 0, cklen); currentPacket.writeData(b, offset, len); currentPacket.numChunks++; bytesCurBlock += len; // If packet is full, enqueue it for transmission // if (currentPacket.numChunks == currentPacket.maxChunks || bytesCurBlock == blockSize) { if (LOG.isDebugEnabled()) { LOG.debug("DFSClient writeChunk packet full seqno=" + currentPacket.seqno + ", src=" + src + ", bytesCurBlock=" + bytesCurBlock + ", blockSize=" + blockSize + ", appendChunk=" + appendChunk); } // // if we allocated a new packet because we encountered a block // boundary, reset bytesCurBlock. // if (bytesCurBlock == blockSize) { currentPacket.lastPacketInBlock = true; bytesCurBlock = 0; lastFlushOffset = -1; } dataQueue.addLast(currentPacket); dataQueue.notifyAll(); currentPacket = null; // If this was the first write after reopening a file, then the above // write filled up any partial chunk. Tell the summer to generate full // crc chunks from now on. if (appendChunk) { appendChunk = false; resetChecksumChunk(bytesPerChecksum); } int psize = Math.min((int)(blockSize-bytesCurBlock), writePacketSize); computePacketChunkSize(psize, bytesPerChecksum); } } //LOG.debug("DFSClient writeChunk done length " + len + // " checksum length " + cklen); } /** * All data is written out to datanodes. It is not guaranteed * that data has been flushed to persistent store on the * datanode. Block allocations are persisted on namenode. */ public synchronized void sync() throws IOException { try { /* Record current blockOffset. This might be changed inside * flushBuffer() where a partial checksum chunk might be flushed. * After the flush, reset the bytesCurBlock back to its previous value, * any partial checksum chunk will be sent now and in next packet. */ long saveOffset = bytesCurBlock; // flush checksum buffer, but keep checksum buffer intact flushBuffer(true); LOG.debug("DFSClient flush() : saveOffset " + saveOffset + " bytesCurBlock " + bytesCurBlock + " lastFlushOffset " + lastFlushOffset); // Flush only if we haven't already flushed till this offset. if (lastFlushOffset != bytesCurBlock) { // record the valid offset of this flush lastFlushOffset = bytesCurBlock; // wait for all packets to be sent and acknowledged flushInternal(); } else { // just discard the current packet since it is already been sent. currentPacket = null; } // Restore state of stream. Record the last flush offset // of the last full chunk that was flushed. // bytesCurBlock = saveOffset; // If any new blocks were allocated since the last flush, // then persist block locations on namenode. // if (persistBlocks) { namenode.fsync(src, clientName); persistBlocks = false; } } catch (IOException e) { lastException = new IOException("IOException flush:" + e); closed = true; closeThreads(); throw e; } } /** * Waits till all existing data is flushed and confirmations * received from datanodes. */ private synchronized void flushInternal() throws IOException { checkOpen(); isClosed(); while (!closed) { synchronized (dataQueue) { isClosed(); // // If there is data in the current buffer, send it across // if (currentPacket != null) { dataQueue.addLast(currentPacket); dataQueue.notifyAll(); currentPacket = null; } // wait for all buffers to be flushed to datanodes if (!closed && dataQueue.size() != 0) { try { dataQueue.wait(); } catch (InterruptedException e) { } continue; } } // wait for all acks to be received back from datanodes synchronized (ackQueue) { if (!closed && ackQueue.size() != 0) { try { ackQueue.wait(); } catch (InterruptedException e) { } continue; } } // acquire both the locks and verify that we are // *really done*. In the case of error recovery, // packets might move back from ackQueue to dataQueue. // synchronized (dataQueue) { synchronized (ackQueue) { if (dataQueue.size() + ackQueue.size() == 0) { break; // we are done } } } } } /** * Closes this output stream and releases any system * resources associated with this stream. */ @Override public void close() throws IOException { if(closed) return; closeInternal(); leasechecker.remove(src); if (s != null) { s.close(); s = null; } } // shutdown datastreamer and responseprocessor threads. private void closeThreads() throws IOException { try { streamer.close(); streamer.join(); // shutdown response after streamer has exited. if (response != null) { response.close(); response.join(); response = null; } } catch (InterruptedException e) { throw new IOException("Failed to shutdown response thread"); } } /** * Closes this output stream and releases any system * resources associated with this stream. */ private synchronized void closeInternal() throws IOException { checkOpen(); isClosed(); try { flushBuffer(); // flush from all upper layers // Mark that this packet is the last packet in block. // If there are no outstanding packets and the last packet // was not the last one in the current block, then create a // packet with empty payload. synchronized (dataQueue) { if (currentPacket == null && bytesCurBlock != 0) { currentPacket = new Packet(packetSize, chunksPerPacket, bytesCurBlock); } if (currentPacket != null) { currentPacket.lastPacketInBlock = true; } } flushInternal(); // flush all data to Datanodes isClosed(); // check to see if flushInternal had any exceptions closed = true; // allow closeThreads() to showdown threads closeThreads(); synchronized (dataQueue) { if (blockStream != null) { blockStream.writeInt(0); // indicate end-of-block to datanode blockStream.close(); blockReplyStream.close(); } if (s != null) { s.close(); s = null; } } streamer = null; blockStream = null; blockReplyStream = null; long localstart = System.currentTimeMillis(); boolean fileComplete = false; while (!fileComplete) { fileComplete = namenode.complete(src, clientName); if (!fileComplete) { try { Thread.sleep(400); if (System.currentTimeMillis() - localstart > 5000) { LOG.info("Could not complete file " + src + " retrying..."); } } catch (InterruptedException ie) { } } } } finally { closed = true; } } void setArtificialSlowdown(long period) { artificialSlowdown = period; } synchronized void setChunksPerPacket(int value) { chunksPerPacket = Math.min(chunksPerPacket, value); packetSize = DataNode.PKT_HEADER_LEN + SIZE_OF_INTEGER + (checksum.getBytesPerChecksum() + checksum.getChecksumSize()) * chunksPerPacket; } synchronized void setTestFilename(String newname) { src = newname; } /** * Returns the size of a file as it was when this stream was opened */ long getInitialLen() { return initialFileSize; } } void reportChecksumFailure(String file, Block blk, DatanodeInfo dn) { DatanodeInfo [] dnArr = { dn }; LocatedBlock [] lblocks = { new LocatedBlock(blk, dnArr) }; reportChecksumFailure(file, lblocks); } // just reports checksum failure and ignores any exception during the report. void reportChecksumFailure(String file, LocatedBlock lblocks[]) { try { reportBadBlocks(lblocks); } catch (IOException ie) { LOG.info("Found corruption while reading " + file + ". Error repairing corrupt blocks. Bad blocks remain. " + StringUtils.stringifyException(ie)); } } /** {@inheritDoc} */ public String toString() { return getClass().getSimpleName() + "[clientName=" + clientName + ", ugi=" + ugi + "]"; } } diff --git a/src/test/org/apache/hadoop/hdfs/TestFileStatus.java b/src/test/org/apache/hadoop/hdfs/TestFileStatus.java index 6ab029d29..a4461333b 100644 --- a/src/test/org/apache/hadoop/hdfs/TestFileStatus.java +++ b/src/test/org/apache/hadoop/hdfs/TestFileStatus.java @@ -1,229 +1,234 @@ /** * 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.hdfs; import junit.framework.TestCase; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Random; import org.apache.commons.logging.impl.Log4JLogger; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.FSDataOutputStream; +import org.apache.hadoop.hdfs.DFSClient.DFSDataInputStream; import org.apache.hadoop.hdfs.protocol.HdfsFileStatus; import org.apache.hadoop.hdfs.server.namenode.FSNamesystem; import org.apache.hadoop.hdfs.server.namenode.NameNode; import org.apache.log4j.Level; /** * This class tests the FileStatus API. */ public class TestFileStatus extends TestCase { { ((Log4JLogger)FSNamesystem.LOG).getLogger().setLevel(Level.ALL); ((Log4JLogger)FileSystem.LOG).getLogger().setLevel(Level.ALL); } static final long seed = 0xDEADBEEFL; static final int blockSize = 8192; static final int fileSize = 16384; private void writeFile(FileSystem fileSys, Path name, int repl, int fileSize, int blockSize) throws IOException { // create and write a file that contains three blocks of data FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096), (short)repl, (long)blockSize); byte[] buffer = new byte[fileSize]; Random rand = new Random(seed); rand.nextBytes(buffer); stm.write(buffer); stm.close(); } private void checkFile(FileSystem fileSys, Path name, int repl) throws IOException { DFSTestUtil.waitReplication(fileSys, name, (short) repl); } /** * Tests various options of DFSShell. */ public void testFileStatus() throws IOException { Configuration conf = new Configuration(); conf.setInt(DFSConfigKeys.DFS_LIST_LIMIT, 2); MiniDFSCluster cluster = new MiniDFSCluster(conf, 1, true, null); FileSystem fs = cluster.getFileSystem(); final HftpFileSystem hftpfs = cluster.getHftpFileSystem(); final DFSClient dfsClient = new DFSClient(NameNode.getAddress(conf), conf); try { // // check that / exists // Path path = new Path("/"); System.out.println("Path : \"" + path.toString() + "\""); assertTrue("/ should be a directory", fs.getFileStatus(path).isDir() == true); // make sure getFileInfo returns null for files which do not exist HdfsFileStatus fileInfo = dfsClient.getFileInfo("/noSuchFile"); assertTrue(fileInfo == null); // create a file in home directory // Path file1 = new Path("filestatus.dat"); writeFile(fs, file1, 1, fileSize, blockSize); System.out.println("Created file filestatus.dat with one " + " replicas."); checkFile(fs, file1, 1); System.out.println("Path : \"" + file1 + "\""); // test getFileStatus on a file FileStatus status = fs.getFileStatus(file1); assertTrue(file1 + " should be a file", status.isDir() == false); assertTrue(status.getBlockSize() == blockSize); assertTrue(status.getReplication() == 1); assertTrue(status.getLen() == fileSize); assertEquals(fs.makeQualified(file1).toString(), status.getPath().toString()); + // test getVisbileLen + DFSDataInputStream fin = (DFSDataInputStream)fs.open(file1); + assertEquals(status.getLen(), fin.getVisibleLength()); + // test listStatus on a file FileStatus[] stats = fs.listStatus(file1); assertEquals(1, stats.length); status = stats[0]; assertTrue(file1 + " should be a file", status.isDir() == false); assertTrue(status.getBlockSize() == blockSize); assertTrue(status.getReplication() == 1); assertTrue(status.getLen() == fileSize); assertEquals(fs.makeQualified(file1).toString(), status.getPath().toString()); // test file status on a directory Path dir = new Path("/test/mkdirs"); // test listStatus on a non-existent file/directory stats = fs.listStatus(dir); assertEquals(null, stats); try { status = fs.getFileStatus(dir); fail("getFileStatus of non-existent path should fail"); } catch (FileNotFoundException fe) { assertTrue(fe.getMessage().startsWith("File does not exist")); } // create the directory assertTrue(fs.mkdirs(dir)); assertTrue(fs.exists(dir)); System.out.println("Dir : \"" + dir + "\""); // test getFileStatus on an empty directory status = fs.getFileStatus(dir); assertTrue(dir + " should be a directory", status.isDir()); assertTrue(dir + " should be zero size ", status.getLen() == 0); assertEquals(fs.makeQualified(dir).toString(), status.getPath().toString()); // test listStatus on an empty directory stats = fs.listStatus(dir); assertEquals(dir + " should be empty", 0, stats.length); assertEquals(dir + " should be zero size ", 0, fs.getContentSummary(dir).getLength()); assertEquals(dir + " should be zero size using hftp", 0, hftpfs.getContentSummary(dir).getLength()); assertTrue(dir + " should be zero size ", fs.getFileStatus(dir).getLen() == 0); System.out.println("Dir : \"" + dir + "\""); // create another file that is smaller than a block. // Path file2 = new Path(dir, "filestatus2.dat"); writeFile(fs, file2, 1, blockSize/4, blockSize); System.out.println("Created file filestatus2.dat with one " + " replicas."); checkFile(fs, file2, 1); System.out.println("Path : \"" + file2 + "\""); // verify file attributes status = fs.getFileStatus(file2); assertTrue(status.getBlockSize() == blockSize); assertTrue(status.getReplication() == 1); file2 = fs.makeQualified(file2); assertEquals(file2.toString(), status.getPath().toString()); // create another file in the same directory Path file3 = new Path(dir, "filestatus3.dat"); writeFile(fs, file3, 1, blockSize/4, blockSize); System.out.println("Created file filestatus3.dat with one " + " replicas."); checkFile(fs, file3, 1); file3 = fs.makeQualified(file3); // verify that the size of the directory increased by the size // of the two files final int expected = blockSize/2; assertEquals(dir + " size should be " + expected, expected, fs.getContentSummary(dir).getLength()); assertEquals(dir + " size should be " + expected + " using hftp", expected, hftpfs.getContentSummary(dir).getLength()); // test listStatus on a non-empty directory stats = fs.listStatus(dir); assertEquals(dir + " should have two entries", 2, stats.length); assertEquals(file2.toString(), stats[0].getPath().toString()); assertEquals(file3.toString(), stats[1].getPath().toString()); // test iterative listing // now dir has 2 entries, create one more Path dir3 = fs.makeQualified(new Path(dir, "dir3")); fs.mkdirs(dir3); dir3 = fs.makeQualified(dir3); stats = fs.listStatus(dir); assertEquals(dir + " should have three entries", 3, stats.length); assertEquals(dir3.toString(), stats[0].getPath().toString()); assertEquals(file2.toString(), stats[1].getPath().toString()); assertEquals(file3.toString(), stats[2].getPath().toString()); // now dir has 3 entries, create two more Path dir4 = fs.makeQualified(new Path(dir, "dir4")); fs.mkdirs(dir4); dir4 = fs.makeQualified(dir4); Path dir5 = fs.makeQualified(new Path(dir, "dir5")); fs.mkdirs(dir5); dir5 = fs.makeQualified(dir5); stats = fs.listStatus(dir); assertEquals(dir + " should have five entries", 5, stats.length); assertEquals(dir3.toString(), stats[0].getPath().toString()); assertEquals(dir4.toString(), stats[1].getPath().toString()); assertEquals(dir5.toString(), stats[2].getPath().toString()); assertEquals(file2.toString(), stats[3].getPath().toString()); assertEquals(file3.toString(), stats[4].getPath().toString()); } finally { fs.close(); cluster.shutdown(); } } }
false
false
null
null
diff --git a/src/main/java/com/feedme/activity/AddChildActivity.java b/src/main/java/com/feedme/activity/AddChildActivity.java index 6f95dc4..cb6ee1b 100644 --- a/src/main/java/com/feedme/activity/AddChildActivity.java +++ b/src/main/java/com/feedme/activity/AddChildActivity.java @@ -1,256 +1,256 @@ package com.feedme.activity; import android.app.*; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.*; import com.feedme.R; import com.feedme.dao.BabyDao; import com.feedme.model.Baby; import java.util.Calendar; import java.util.List; /** * User: dayel.ostraco * Date: 1/16/12 * Time: 12:27 PM */ public class AddChildActivity extends ChildActivity { private Button babyDob; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add_child); googleAnalyticsTracker.startNewSession(TRACKING_ID, this); googleAnalyticsTracker.trackPageView("/Add-Child"); final BabyDao babyDao = new BabyDao(getApplicationContext()); final Baby baby = (Baby) getIntent().getSerializableExtra("baby"); // button listener for add child button final EditText babyName = (EditText) findViewById(R.id.babyName); final Spinner babySex = (Spinner) findViewById(R.id.babySex); final EditText babyHeight = (EditText) findViewById(R.id.babyHeight); final EditText babyWeight = (EditText) findViewById(R.id.babyWeight); final ImageView babyImage = (ImageView) findViewById(R.id.babyPicture); if (baby != null) { if (baby.getPicturePath() != null && !baby.getPicturePath().equals("")) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 12; Bitmap bmImg = BitmapFactory.decodeFile(baby.getPicturePath(), options); babyImage.setImageBitmap(getResizedBitmap(bmImg, 75, 75, 90)); babyImage.setMaxWidth(100); babyImage.setMaxHeight(100); babyImage.setMinimumWidth(100); babyImage.setMinimumHeight(100); } else { babyImage.setImageResource(R.drawable.babyicon); babyImage.setMaxWidth(100); babyImage.setMaxHeight(100); babyImage.setMinimumWidth(100); babyImage.setMinimumHeight(100); } } Button addChildButton = (Button) findViewById(R.id.addChildButton); Button takePicture = (Button) findViewById(R.id.takePicture); Button selectPicture = (Button) findViewById(R.id.pickPicture); babyDob = (Button) findViewById(R.id.babyDob); // add a click listener to the button babyDob.setOnClickListener(showDateDialog()); // get the current date final Calendar c = Calendar.getInstance(); mYear = c.get(Calendar.YEAR); mMonth = c.get(Calendar.MONTH); mDay = c.get(Calendar.DAY_OF_MONTH); // display the current date updateDateDisplay(); //populate male/female spinner ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.babySex, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); Spinner s = (Spinner) findViewById(R.id.babySex); s.setAdapter(adapter); //In the even that the user clicked Take Picture or Select Picture and fired off a new Intent from the Add // Child screen. if (getIntent().getStringExtra("picturePath") != null) { baby.setPicturePath(getIntent().getStringExtra("picturePath")); babyName.setText(baby.getName()); babyHeight.setText(baby.getHeight()); babyWeight.setText(baby.getWeight()); babyDob.setText(baby.getDob()); //Set Spinner Value for Baby Sex if (baby.getDob().equals("Male")) { babySex.setSelection(0); } else { babySex.setSelection(1); } } //Take Picture Button - takePicture.setOnClickListener(takePictureListener(baby.getId(), ADD_CHILD_ACTIVITY_ID)); + takePicture.setOnClickListener(takePictureListener(0, ADD_CHILD_ACTIVITY_ID)); //Select Picture Button - selectPicture.setOnClickListener(selectPictureListener(baby.getId(), ADD_CHILD_ACTIVITY_ID)); + selectPicture.setOnClickListener(selectPictureListener(0, ADD_CHILD_ACTIVITY_ID)); //declare alert dialog final AlertDialog alertDialog = new AlertDialog.Builder(this).create(); //Add Child Button addChildButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //if name, weight, and height aren't filled out, throw an alert if (babyName.getText().toString().equals("") || babyHeight.getText().toString().equals("") || babyWeight.getText().toString().equals("")) { alertDialog.setTitle("Oops!"); alertDialog.setMessage("Please fill out the form completely."); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alertDialog.show(); } else { Baby addBaby = new Baby(babyName.getText().toString(), babySex.getSelectedItem().toString(), babyHeight.getText().toString(), babyWeight.getText().toString(), babyDob.getText().toString(), baby.getPicturePath()); // Inserting baby Log.d("Insert: ", "Inserting .."); babyDao.addBaby(addBaby); Log.d("BABY:ADD: ", addBaby.dump()); // Reading all babies Log.d("Reading: ", "Reading all babies.."); List<Baby> babies = babyDao.getAllBabies(); for (Baby baby : babies) { String log = "Id: " + baby.getId() + " ,Name: " + baby.getName() + " ,Sex: " + baby.getSex() + " ,Height: " + baby.getHeight() + " ,Weight: " + baby.getWeight() + " ," + "DOB: " + baby.getDob(); // Writing babies to log Log.d("Name: ", log); } babyName.setText(""); babyHeight.setText(""); babyWeight.setText(""); babyDob.setText(""); Intent intent = new Intent(getApplicationContext(), HomeActivity.class); startActivityForResult(intent, ADD_CHILD_ACTIVITY_ID); } } }); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DATE_DIALOG_ID: return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay); } return null; } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.home: startActivity(new Intent(AddChildActivity.this, HomeActivity.class)); break; case R.id.settings: startActivity(new Intent(AddChildActivity.this, SettingsActivity.class)); break; case R.id.report: startActivity(new Intent(AddChildActivity.this, ReportBugActivity.class)); break; } return true; } // updates the date we display in the TextView private void updateDateDisplay() { babyDob.setText( new StringBuilder() // Month is 0 based so add 1 .append(mMonth + 1).append("-") .append(mDay).append("-") .append(mYear).append(" ")); } // the callback received when the user "sets" the date in the dialog private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mYear = year; mMonth = monthOfYear; mDay = dayOfMonth; updateDateDisplay(); } }; }
false
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add_child); googleAnalyticsTracker.startNewSession(TRACKING_ID, this); googleAnalyticsTracker.trackPageView("/Add-Child"); final BabyDao babyDao = new BabyDao(getApplicationContext()); final Baby baby = (Baby) getIntent().getSerializableExtra("baby"); // button listener for add child button final EditText babyName = (EditText) findViewById(R.id.babyName); final Spinner babySex = (Spinner) findViewById(R.id.babySex); final EditText babyHeight = (EditText) findViewById(R.id.babyHeight); final EditText babyWeight = (EditText) findViewById(R.id.babyWeight); final ImageView babyImage = (ImageView) findViewById(R.id.babyPicture); if (baby != null) { if (baby.getPicturePath() != null && !baby.getPicturePath().equals("")) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 12; Bitmap bmImg = BitmapFactory.decodeFile(baby.getPicturePath(), options); babyImage.setImageBitmap(getResizedBitmap(bmImg, 75, 75, 90)); babyImage.setMaxWidth(100); babyImage.setMaxHeight(100); babyImage.setMinimumWidth(100); babyImage.setMinimumHeight(100); } else { babyImage.setImageResource(R.drawable.babyicon); babyImage.setMaxWidth(100); babyImage.setMaxHeight(100); babyImage.setMinimumWidth(100); babyImage.setMinimumHeight(100); } } Button addChildButton = (Button) findViewById(R.id.addChildButton); Button takePicture = (Button) findViewById(R.id.takePicture); Button selectPicture = (Button) findViewById(R.id.pickPicture); babyDob = (Button) findViewById(R.id.babyDob); // add a click listener to the button babyDob.setOnClickListener(showDateDialog()); // get the current date final Calendar c = Calendar.getInstance(); mYear = c.get(Calendar.YEAR); mMonth = c.get(Calendar.MONTH); mDay = c.get(Calendar.DAY_OF_MONTH); // display the current date updateDateDisplay(); //populate male/female spinner ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.babySex, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); Spinner s = (Spinner) findViewById(R.id.babySex); s.setAdapter(adapter); //In the even that the user clicked Take Picture or Select Picture and fired off a new Intent from the Add // Child screen. if (getIntent().getStringExtra("picturePath") != null) { baby.setPicturePath(getIntent().getStringExtra("picturePath")); babyName.setText(baby.getName()); babyHeight.setText(baby.getHeight()); babyWeight.setText(baby.getWeight()); babyDob.setText(baby.getDob()); //Set Spinner Value for Baby Sex if (baby.getDob().equals("Male")) { babySex.setSelection(0); } else { babySex.setSelection(1); } } //Take Picture Button takePicture.setOnClickListener(takePictureListener(baby.getId(), ADD_CHILD_ACTIVITY_ID)); //Select Picture Button selectPicture.setOnClickListener(selectPictureListener(baby.getId(), ADD_CHILD_ACTIVITY_ID)); //declare alert dialog final AlertDialog alertDialog = new AlertDialog.Builder(this).create(); //Add Child Button addChildButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //if name, weight, and height aren't filled out, throw an alert if (babyName.getText().toString().equals("") || babyHeight.getText().toString().equals("") || babyWeight.getText().toString().equals("")) { alertDialog.setTitle("Oops!"); alertDialog.setMessage("Please fill out the form completely."); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alertDialog.show(); } else { Baby addBaby = new Baby(babyName.getText().toString(), babySex.getSelectedItem().toString(), babyHeight.getText().toString(), babyWeight.getText().toString(), babyDob.getText().toString(), baby.getPicturePath()); // Inserting baby Log.d("Insert: ", "Inserting .."); babyDao.addBaby(addBaby); Log.d("BABY:ADD: ", addBaby.dump()); // Reading all babies Log.d("Reading: ", "Reading all babies.."); List<Baby> babies = babyDao.getAllBabies(); for (Baby baby : babies) { String log = "Id: " + baby.getId() + " ,Name: " + baby.getName() + " ,Sex: " + baby.getSex() + " ,Height: " + baby.getHeight() + " ,Weight: " + baby.getWeight() + " ," + "DOB: " + baby.getDob(); // Writing babies to log Log.d("Name: ", log); } babyName.setText(""); babyHeight.setText(""); babyWeight.setText(""); babyDob.setText(""); Intent intent = new Intent(getApplicationContext(), HomeActivity.class); startActivityForResult(intent, ADD_CHILD_ACTIVITY_ID); } } }); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add_child); googleAnalyticsTracker.startNewSession(TRACKING_ID, this); googleAnalyticsTracker.trackPageView("/Add-Child"); final BabyDao babyDao = new BabyDao(getApplicationContext()); final Baby baby = (Baby) getIntent().getSerializableExtra("baby"); // button listener for add child button final EditText babyName = (EditText) findViewById(R.id.babyName); final Spinner babySex = (Spinner) findViewById(R.id.babySex); final EditText babyHeight = (EditText) findViewById(R.id.babyHeight); final EditText babyWeight = (EditText) findViewById(R.id.babyWeight); final ImageView babyImage = (ImageView) findViewById(R.id.babyPicture); if (baby != null) { if (baby.getPicturePath() != null && !baby.getPicturePath().equals("")) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 12; Bitmap bmImg = BitmapFactory.decodeFile(baby.getPicturePath(), options); babyImage.setImageBitmap(getResizedBitmap(bmImg, 75, 75, 90)); babyImage.setMaxWidth(100); babyImage.setMaxHeight(100); babyImage.setMinimumWidth(100); babyImage.setMinimumHeight(100); } else { babyImage.setImageResource(R.drawable.babyicon); babyImage.setMaxWidth(100); babyImage.setMaxHeight(100); babyImage.setMinimumWidth(100); babyImage.setMinimumHeight(100); } } Button addChildButton = (Button) findViewById(R.id.addChildButton); Button takePicture = (Button) findViewById(R.id.takePicture); Button selectPicture = (Button) findViewById(R.id.pickPicture); babyDob = (Button) findViewById(R.id.babyDob); // add a click listener to the button babyDob.setOnClickListener(showDateDialog()); // get the current date final Calendar c = Calendar.getInstance(); mYear = c.get(Calendar.YEAR); mMonth = c.get(Calendar.MONTH); mDay = c.get(Calendar.DAY_OF_MONTH); // display the current date updateDateDisplay(); //populate male/female spinner ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.babySex, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); Spinner s = (Spinner) findViewById(R.id.babySex); s.setAdapter(adapter); //In the even that the user clicked Take Picture or Select Picture and fired off a new Intent from the Add // Child screen. if (getIntent().getStringExtra("picturePath") != null) { baby.setPicturePath(getIntent().getStringExtra("picturePath")); babyName.setText(baby.getName()); babyHeight.setText(baby.getHeight()); babyWeight.setText(baby.getWeight()); babyDob.setText(baby.getDob()); //Set Spinner Value for Baby Sex if (baby.getDob().equals("Male")) { babySex.setSelection(0); } else { babySex.setSelection(1); } } //Take Picture Button takePicture.setOnClickListener(takePictureListener(0, ADD_CHILD_ACTIVITY_ID)); //Select Picture Button selectPicture.setOnClickListener(selectPictureListener(0, ADD_CHILD_ACTIVITY_ID)); //declare alert dialog final AlertDialog alertDialog = new AlertDialog.Builder(this).create(); //Add Child Button addChildButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //if name, weight, and height aren't filled out, throw an alert if (babyName.getText().toString().equals("") || babyHeight.getText().toString().equals("") || babyWeight.getText().toString().equals("")) { alertDialog.setTitle("Oops!"); alertDialog.setMessage("Please fill out the form completely."); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alertDialog.show(); } else { Baby addBaby = new Baby(babyName.getText().toString(), babySex.getSelectedItem().toString(), babyHeight.getText().toString(), babyWeight.getText().toString(), babyDob.getText().toString(), baby.getPicturePath()); // Inserting baby Log.d("Insert: ", "Inserting .."); babyDao.addBaby(addBaby); Log.d("BABY:ADD: ", addBaby.dump()); // Reading all babies Log.d("Reading: ", "Reading all babies.."); List<Baby> babies = babyDao.getAllBabies(); for (Baby baby : babies) { String log = "Id: " + baby.getId() + " ,Name: " + baby.getName() + " ,Sex: " + baby.getSex() + " ,Height: " + baby.getHeight() + " ,Weight: " + baby.getWeight() + " ," + "DOB: " + baby.getDob(); // Writing babies to log Log.d("Name: ", log); } babyName.setText(""); babyHeight.setText(""); babyWeight.setText(""); babyDob.setText(""); Intent intent = new Intent(getApplicationContext(), HomeActivity.class); startActivityForResult(intent, ADD_CHILD_ACTIVITY_ID); } } }); }
diff --git a/src/main/java/ai/ilikeplaces/entities/HumansTribe.java b/src/main/java/ai/ilikeplaces/entities/HumansTribe.java index ecba8ce0..f89bf056 100644 --- a/src/main/java/ai/ilikeplaces/entities/HumansTribe.java +++ b/src/main/java/ai/ilikeplaces/entities/HumansTribe.java @@ -1,93 +1,93 @@ package ai.ilikeplaces.entities; import ai.ilikeplaces.doc.BIDIRECTIONAL; import ai.ilikeplaces.doc.FIXME; import ai.ilikeplaces.doc.UNIDIRECTIONAL; import ai.ilikeplaces.doc.WARNING; import ai.ilikeplaces.exception.DBException; import ai.ilikeplaces.logic.Listeners.widgets.UserProperty; import ai.ilikeplaces.logic.crud.DB; import ai.ilikeplaces.logic.validators.unit.HumanId; import ai.ilikeplaces.util.Return; import javax.persistence.*; import java.io.Serializable; import java.util.Set; /** * Created by IntelliJ IDEA. * User: Ravindranath Akila * Date: 10/12/11 * Time: 7:47 PM */ @WARNING("THIS ENTITY IS NOT GUARANTEED TO 'BE' EVEN THOUGH A HUMAN IS SIGNED UP. SO CREATE IT IF NOT PRESENT!") @Entity public class HumansTribe implements HumansFriend, HumanIdFace, HumanEqualsFace , Serializable { public String humanId; public Set<Tribe> tribes; @Id public String getHumanId() { return humanId; } @Override public String getDisplayName() { return UserProperty.HUMANS_IDENTITY_CACHE.get(getHumanId(), "").getHuman().getDisplayName(); } @Override @Transient public boolean isFriend(final String friendsHumanId) { final Return<Boolean> r = DB.getHumanCRUDHumanLocal(true).doDirtyIsHumansNetPeople(new ai.ilikeplaces.logic.validators.unit.HumanId(this.humanId), new ai.ilikeplaces.logic.validators.unit.HumanId(friendsHumanId)); if (r.returnStatus() != 0) { throw new DBException(r.returnError()); } return r.returnValue(); } @Override public boolean notFriend(final String friendsHumanId) { return !isFriend(friendsHumanId); } public void setHumanId(final String humanId) { this.humanId = humanId; } @Transient public HumansTribe setHumanIdR(final String humanId) { this.humanId = humanId; return this; } @BIDIRECTIONAL(ownerside = BIDIRECTIONAL.OWNING.NOT) @ManyToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY) public Set<Tribe> getTribes() { return tribes; } public void setTribes(final Set<Tribe> tribes) { this.tribes = tribes; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null) { return false; } if (getClass() == o.getClass()) { - final Mute that = (Mute) o; + final HumanEqualsFace that = (HumanEqualsFace) o; return !(this.getHumanId() == null || that.getHumanId() == null) && this.getHumanId().equals(that.getHumanId()); } else { return HumanEquals.staticMatchHumanId(this, o); } } } diff --git a/src/main/java/ai/ilikeplaces/entities/Mute.java b/src/main/java/ai/ilikeplaces/entities/Mute.java index da7856be..950f05c0 100644 --- a/src/main/java/ai/ilikeplaces/entities/Mute.java +++ b/src/main/java/ai/ilikeplaces/entities/Mute.java @@ -1,120 +1,120 @@ package ai.ilikeplaces.entities; import ai.ilikeplaces.doc.License; import ai.ilikeplaces.util.EntityLifeCycleListener; import javax.persistence.*; import java.io.Serializable; /** * Okay, we need to * <p/> * 1. Remember that entries to this entity will be foreign keys. That is, so that anybody can use this entity. * <p/> * 2. This entity should be super efficient since it will be used everywhere. * <p/> * Created by IntelliJ IDEA. * User: <a href="http://www.ilikeplaces.com"> http://www.ilikeplaces.com </a> * Date: Jan 25, 2010 * Time: 1:01:22 PM */ @License(content = "This code is licensed under GNU AFFERO GENERAL PUBLIC LICENSE Version 3") @Entity public class Mute extends HumanEquals implements Serializable { public Long muteId; public static final String muteIdCOL = "muteId"; public Integer muteType;//Wall, Album public String muteContent; public String muteMetadata;//Anybody can store relevant metadata here final static public int muteTypeHUMAN = 1; final static public int muteTypeMISC = 0; @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getMuteId() { return muteId; } public void setMuteId(final Long muteId) { this.muteId = muteId; } public Mute setMuteIdR(final Long muteId) { this.muteId = muteId; return this; } public Integer getMuteType() { return muteType; } public void setMuteType(final Integer muteType) { this.muteType = muteType; } public Mute setMuteTypeR(final Integer muteType) { this.muteType = muteType; return this; } public String getMuteContent() { return muteContent; } public void setMuteContent(final String muteContent) { this.muteContent = muteContent; } public Mute setMuteContentR(final String muteContent) { this.muteContent = muteContent; return this; } public String getMuteMetadata() { return muteMetadata; } public void setMuteMetadata(final String muteMetadata) { this.muteMetadata = muteMetadata; } public Mute setMuteMetadataR(final String muteMetadata) { this.muteMetadata = muteMetadata; return this; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null) { return false; } if (getClass() == o.getClass()) { - final Mute that = (Mute) o; + final HumanEqualsFace that = (HumanEqualsFace) o; return (!(this.getHumanId() == null || that.getHumanId() == null)) && this.getHumanId().equals(that.getHumanId()); } else { return matchHumanId(o); } } /** * * @return getMuteContent() being optimistic that it contains the humanId */ @Override public String getHumanId() { return getMuteContent(); } } \ No newline at end of file diff --git a/src/main/java/ai/ilikeplaces/logic/validators/unit/HumanId.java b/src/main/java/ai/ilikeplaces/logic/validators/unit/HumanId.java index 068c0a79..1842a3f3 100644 --- a/src/main/java/ai/ilikeplaces/logic/validators/unit/HumanId.java +++ b/src/main/java/ai/ilikeplaces/logic/validators/unit/HumanId.java @@ -1,82 +1,82 @@ package ai.ilikeplaces.logic.validators.unit; import ai.ilikeplaces.doc.License; import ai.ilikeplaces.entities.HumanEquals; import ai.ilikeplaces.entities.HumanEqualsFace; import ai.ilikeplaces.entities.HumanIdFace; import ai.ilikeplaces.entities.Mute; import ai.ilikeplaces.util.RefObj; import net.sf.oval.Validator; import net.sf.oval.configuration.annotation.IsInvariant; import net.sf.oval.constraint.Length; import net.sf.oval.constraint.NotNull; import net.sf.oval.exception.ConstraintsViolatedException; /** * Created by IntelliJ IDEA. * User: <a href="http://www.ilikeplaces.com"> http://www.ilikeplaces.com </a> * Date: Jan 22, 2010 * Time: 2:16:43 AM */ @License(content = "This code is licensed under GNU AFFERO GENERAL PUBLIC LICENSE Version 3") public class HumanId extends RefObj<String> implements HumanEqualsFace, HumanIdFace { public HumanId() { } public HumanId(final String humanId) { obj = humanId; } public HumanId(final String humanId, final boolean doValidateAndThrow) { if (doValidateAndThrow) { /*Threading issue possible here as the validator thread will accesses the object before creation finishes*/ setObjAsValid(humanId); } else { obj = humanId; } } public HumanId getSelfAsValid(final Validator... validator) { return (HumanId) super.getSelfAsValid(validator); } @IsInvariant @NotNull @net.sf.oval.constraint.Email(message = "SORRY! HUMAN ID SHOULD BE AN EMAIL ADDRESS.") @Length(max = 255) @Override public String getObj() { return obj; } public String getHumanId() { return getObjectAsValid(); } @Override public void setHumanId(final String humanId__) { super.setObj(humanId__); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null) { return false; } if (getClass() == o.getClass()) { - final Mute that = (Mute) o; + final HumanEqualsFace that = (HumanEqualsFace) o; return !(this.getHumanId() == null || that.getHumanId() == null) && this.getHumanId().equals(that.getHumanId()); } else { return HumanEquals.staticMatchHumanId(this,o); } } }
false
false
null
null
diff --git a/src/edgruberman/bukkit/simpletemplate/util/CustomPlugin.java b/src/edgruberman/bukkit/simpletemplate/util/CustomPlugin.java index 727f6bf..71bdd0b 100644 --- a/src/edgruberman/bukkit/simpletemplate/util/CustomPlugin.java +++ b/src/edgruberman/bukkit/simpletemplate/util/CustomPlugin.java @@ -1,181 +1,181 @@ package edgruberman.bukkit.simpletemplate.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; import java.text.MessageFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.logging.Handler; import java.util.logging.Level; import org.bukkit.configuration.Configuration; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.java.JavaPlugin; /** * @author EdGruberman (ed@rjump.com) - * @version 1.3.1 + * @version 1.3.2 */ public class CustomPlugin extends JavaPlugin { public static final Charset CONFIGURATION_TARGET = Charset.defaultCharset(); public static final Charset CONFIGURATION_SOURCE = Charset.forName("UTF-8"); public static final String CONFIGURATION_ARCHIVE = "{0} - Archive version {1} - {2,date,yyyyMMddHHmmss}.yml"; // 0 = Name, 1 = Version, 2 = Date public static final String CONFIGURATION_FILE = "config.yml"; public static final Level DEFAULT_LOG = Level.INFO; public static final String LINE_SEPARATOR = System.getProperty("line.separator"); /** minimum version required for configuration files; indexed by relative file name (e.g. "config.yml") */ private final Map<String, Version> configurationMinimums = new HashMap<String, Version>(); private FileConfiguration config = null; private char pathSeparator = '.'; public void putConfigMinimum(final String version) { this.putConfigMinimum(CustomPlugin.CONFIGURATION_FILE, version); } public void putConfigMinimum(final String resource, final String version) { this.configurationMinimums.put(resource, new Version(version)); } public CustomPlugin setPathSeparator(final char separator) { this.pathSeparator = separator; return this; } @Override public FileConfiguration getConfig() { if (this.config == null) this.reloadConfig(); return this.config; } @Override public void reloadConfig() { this.config = this.loadConfig(CustomPlugin.CONFIGURATION_FILE, this.pathSeparator, this.configurationMinimums.get(CustomPlugin.CONFIGURATION_FILE)); this.setLogLevel(this.getConfig().getString("log-level")); this.getLogger().log(Level.FINEST, "YAML configuration file encoding: {0}", CustomPlugin.CONFIGURATION_TARGET); } @Override public void saveDefaultConfig() { this.extractConfig(CustomPlugin.CONFIGURATION_FILE, false); } /** @param resource same as in {@link #loadConfig(String, char, Version)} */ public FileConfiguration loadConfig(final String resource) { return this.loadConfig(resource, this.pathSeparator, this.configurationMinimums.get(resource)); } /** @param resource file name relative to plugin data folder and base of jar (embedded file extracted to file system if does not exist) */ public FileConfiguration loadConfig(final String resource, final char pathSeparator, final Version required) { // extract default if not existing this.extractConfig(resource, false); final File existing = new File(this.getDataFolder(), resource); final YamlConfiguration yaml = new YamlConfiguration(); yaml.options().pathSeparator(pathSeparator); try { yaml.load(existing); } catch (final InvalidConfigurationException e) { throw new IllegalStateException("Unable to load configuration file: " + existing.getPath() + " (Ensure file is encoded as " + CustomPlugin.CONFIGURATION_TARGET + ")", e); } catch (final Exception e) { throw new RuntimeException("Unable to load configuration file: " + existing.getPath(), e); } - yaml.setDefaults(this.loadEmbeddedConfig(CustomPlugin.CONFIGURATION_FILE)); + yaml.setDefaults(this.loadEmbeddedConfig(resource)); if (required == null) return yaml; // verify required or later version final Version version = new Version(yaml.getString("version")); if (version.compareTo(required) >= 0) return yaml; this.archiveConfig(resource, version); // extract default and reload return this.loadConfig(resource, this.pathSeparator, null); } /** extract embedded configuration file from jar, translating character encoding to default character set */ public void extractConfig(final String resource, final boolean replace) { final File config = new File(this.getDataFolder(), resource); if (config.exists() && !replace) return; this.getLogger().log(Level.FINE, "Extracting configuration file {1} {0} as {2}", new Object[] { resource, CustomPlugin.CONFIGURATION_SOURCE.name(), CustomPlugin.CONFIGURATION_TARGET.name() }); config.getParentFile().mkdirs(); final char[] cbuf = new char[1024]; int read; try { final Reader in = new BufferedReader(new InputStreamReader(this.getResource(resource), CustomPlugin.CONFIGURATION_SOURCE)); final Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(config), CustomPlugin.CONFIGURATION_TARGET)); while((read = in.read(cbuf)) > 0) out.write(cbuf, 0, read); out.close(); in.close(); } catch (final Exception e) { throw new IllegalArgumentException("Could not extract configuration file \"" + resource + "\" to " + config.getPath() + "\"", e); } } /** make a backup copy of an existing configuration file */ public void archiveConfig(final String resource, final Version version) { final File backup = new File(this.getDataFolder(), MessageFormat.format(CustomPlugin.CONFIGURATION_ARCHIVE, resource.replaceAll("(?i)\\.yml$", ""), version, new Date())); final File existing = new File(this.getDataFolder(), resource); if (!existing.renameTo(backup)) throw new IllegalStateException("Unable to archive configuration file \"" + existing.getPath() + "\" with version \"" + version + "\" to \"" + backup.getPath() + "\""); this.getLogger().warning("Archived configuration file \"" + existing.getPath() + "\" with version \"" + version + "\" to \"" + backup.getPath() + "\""); } /** load configuration from jar without extracting to file system **/ public Configuration loadEmbeddedConfig(final String resource) { final YamlConfiguration config = new YamlConfiguration(); final InputStream defaults = this.getResource(resource); if (defaults == null) return config; final InputStreamReader reader = new InputStreamReader(defaults, CustomPlugin.CONFIGURATION_SOURCE); final StringBuilder builder = new StringBuilder(); final BufferedReader input = new BufferedReader(reader); try { try { String line; while ((line = input.readLine()) != null) builder.append(line).append(CustomPlugin.LINE_SEPARATOR); } finally { input.close(); } config.loadFromString(builder.toString()); } catch (final Exception e) { throw new RuntimeException("Unable to load embedded configuration: " + resource, e); } return config; } public void setLogLevel(final String name) { Level level; try { level = Level.parse(name); } catch (final Exception e) { level = CustomPlugin.DEFAULT_LOG; this.getLogger().warning("Log level defaulted to " + level.getName() + "; Unrecognized java.util.logging.Level: " + name + "; " + e); } // only set the parent handler lower if necessary, otherwise leave it alone for other configurations that have set it for (final Handler h : this.getLogger().getParent().getHandlers()) if (h.getLevel().intValue() > level.intValue()) h.setLevel(level); this.getLogger().setLevel(level); this.getLogger().log(Level.CONFIG, "Log level set to: {0} ({1,number,#})" , new Object[] { this.getLogger().getLevel(), this.getLogger().getLevel().intValue() }); } }
false
false
null
null
diff --git a/warc-indexer/src/main/java/uk/bl/wa/indexer/WARCIndexer.java b/warc-indexer/src/main/java/uk/bl/wa/indexer/WARCIndexer.java index 1a1ddc0f..6520de8b 100755 --- a/warc-indexer/src/main/java/uk/bl/wa/indexer/WARCIndexer.java +++ b/warc-indexer/src/main/java/uk/bl/wa/indexer/WARCIndexer.java @@ -1,797 +1,797 @@ package uk.bl.wa.indexer; import static org.archive.io.warc.WARCConstants.HEADER_KEY_TYPE; import static org.archive.io.warc.WARCConstants.RESPONSE; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpParser; import org.apache.commons.httpclient.ProtocolException; import org.apache.commons.io.input.BoundedInputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpHeaders; import org.apache.tika.metadata.Metadata; import org.apache.tika.mime.MediaType; import org.archive.io.ArchiveRecord; import org.archive.io.ArchiveRecordHeader; import org.archive.io.arc.ARCRecord; import org.archive.io.warc.WARCConstants; import org.archive.io.warc.WARCRecord; import org.archive.net.UURI; import org.archive.net.UURIFactory; import org.archive.util.ArchiveUtils; import org.archive.wayback.accesscontrol.staticmap.StaticMapExclusionFilterFactory; import org.archive.wayback.core.CaptureSearchResult; import org.archive.wayback.resourceindex.filters.ExclusionFilter; import org.archive.wayback.util.url.AggressiveUrlCanonicalizer; import com.google.common.base.Splitter; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigRenderOptions; import uk.bl.wa.extract.LanguageDetector; import uk.bl.wa.extract.LinkExtractor; import uk.bl.wa.nanite.droid.DroidDetector; import uk.bl.wa.parsers.HtmlFeatureParser; import uk.bl.wa.sentimentalj.Sentiment; import uk.bl.wa.sentimentalj.SentimentalJ; import uk.bl.wa.util.PostcodeGeomapper; import uk.bl.wa.util.solr.SolrFields; import uk.bl.wa.util.solr.SolrRecord; import uk.bl.wa.util.solr.TikaExtractor; import uk.gov.nationalarchives.droid.command.action.CommandExecutionException; import eu.scape_project.bitwiser.utils.FuzzyHash; import eu.scape_project.bitwiser.utils.SSDeep; /** * * Core indexer class that takes a web archive record and generates a Solr record. * * TODO Currently a rather crude, monolithic code structure. Should pull the different metadata generation logic out into separate classes or at least methods. * * @author Andrew Jackson <Andrew.Jackson@bl.uk> * */ public class WARCIndexer { private static Log log = LogFactory.getLog(WARCIndexer.class); private static final long BUFFER_SIZE = 1024*1024l; // 10485760 bytes = 10MB. private List<String> url_excludes; private List<String> protocol_includes; private List<String> response_includes; private static final Pattern postcodePattern = Pattern.compile("[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}"); private TikaExtractor tika = null; private DroidDetector dd = null; private boolean runDroid = true; private boolean droidUseBinarySignaturesOnly = false; private boolean passUriToFormatTools = false; private MessageDigest md5 = null; private AggressiveUrlCanonicalizer canon = new AggressiveUrlCanonicalizer(); /** */ private LanguageDetector ld = new LanguageDetector(); /** */ private HtmlFeatureParser hfp = new HtmlFeatureParser(); private boolean extractLinkDomains = true; private boolean extractLinkHosts = true; private boolean extractLinks = false; private boolean extractText = true; private boolean extractElementsUsed = true; private boolean extractContentFirstBytes = true; private int firstBytesLength = 32; /** */ private SentimentalJ sentij = new SentimentalJ(); /** */ private PostcodeGeomapper pcg = new PostcodeGeomapper(); /** Wayback-style URI filtering: */ StaticMapExclusionFilterFactory smef = null; /* ------------------------------------------------------------ */ /** * Default constructor, with empty configuration. */ public WARCIndexer() throws NoSuchAlgorithmException { this( ConfigFactory.parseString( ConfigFactory.load().root().render( ConfigRenderOptions.concise() ) ) ); } /** * Preferred constructor, allows passing in configuration from execution environment. */ public WARCIndexer( Config conf ) throws NoSuchAlgorithmException { // Optional configurations: this.extractLinks = conf.getBoolean("warc.index.extract.linked.resources" ); this.extractLinkHosts = conf.getBoolean("warc.index.extract.linked.hosts" ); this.extractLinkDomains = conf.getBoolean("warc.index.extract.linked.domains" ); this.extractText = conf.getBoolean("warc.index.extract.content.text" ); this.extractElementsUsed = conf.getBoolean("warc.index.extract.content.elements_used" ); this.extractContentFirstBytes = conf.getBoolean("warc.index.extract.content.first_bytes.enabled" ); this.firstBytesLength = conf.getInt("warc.index.extract.content.first_bytes.num_bytes" ); this.runDroid = conf.getBoolean("warc.index.id.droid.enabled" ); this.passUriToFormatTools = conf.getBoolean("warc.index.id.useResourceURI"); this.droidUseBinarySignaturesOnly = conf.getBoolean("warc.index.id.droid.useBinarySignaturesOnly" ); // URLs to exclude: this.url_excludes = conf.getStringList("warc.index.extract.url_exclude"); // Protocols to include: this.protocol_includes = conf.getStringList("warc.index.extract.protocol_include"); // Response codes to include: this.response_includes = conf.getStringList("warc.index.extract.response_include"); // URL Filtering options: if( conf.getBoolean("warc.index.exclusions.enabled")) { smef = new StaticMapExclusionFilterFactory(); smef.setFile(conf.getString("warc.index.exclusions.file")); smef.setCheckInterval(conf.getInt("warc.index.exclusions.check_interval")); try { smef.init(); } catch (IOException e) { log.error("Failed to load exclusions file."); throw new RuntimeException("StaticMapExclusionFilterFactory failed with IOException when loading "+smef.getFile()); } } // Instanciate required helpers: md5 = MessageDigest.getInstance( "MD5" ); // Attempt to set up Droid: try { dd = new DroidDetector(); dd.setBinarySignaturesOnly( droidUseBinarySignaturesOnly ); dd.setMaxBytesToScan( BUFFER_SIZE ); } catch( CommandExecutionException e ) { e.printStackTrace(); dd = null; } tika = new TikaExtractor( conf ); } /** * This extracts metadata and text from the ArchiveRecord and creates a suitable SolrRecord. * * @param archiveName * @param record * @return * @throws IOException */ public SolrRecord extract( String archiveName, ArchiveRecord record ) throws IOException { return this.extract(archiveName, record, this.extractText ); } /** * This extracts metadata from the ArchiveRecord and creates a suitable SolrRecord. * Removes the text field if flag set. * * @param archiveName * @param record * @param isTextIncluded * @return * @throws IOException */ public SolrRecord extract( String archiveName, ArchiveRecord record, boolean isTextIncluded) throws IOException { ArchiveRecordHeader header = record.getHeader(); SolrRecord solr = new SolrRecord(); if( !header.getHeaderFields().isEmpty() ) { if( header.getHeaderFieldKeys().contains( HEADER_KEY_TYPE ) && !header.getHeaderValue( HEADER_KEY_TYPE ).equals( RESPONSE ) ) { return null; } if( header.getUrl() == null ) return null; String fullUrl = header.getUrl(); // Check the filters: if( this.checkProtocol(fullUrl) == false ) return null; if( this.checkUrl(fullUrl) == false ) return null; if( this.checkExclusionFilter(fullUrl) == false) return null; // Check the record type: log.debug("WARC record "+header.getHeaderValue(WARCConstants.HEADER_KEY_ID)+" type: " + header.getHeaderValue( WARCConstants.HEADER_KEY_TYPE )); // By checking if KEY_TYPE is there, we accept all ARC records, or WARC records of type response. if( header.getHeaderFieldKeys().contains( HEADER_KEY_TYPE ) && !header.getHeaderValue( HEADER_KEY_TYPE ).equals( RESPONSE ) ) { return null; } // Basic headers // Dates String waybackDate = ( header.getDate().replaceAll( "[^0-9]", "" ) ); solr.doc.setField( SolrFields.WAYBACK_DATE, waybackDate ); solr.doc.setField( SolrFields.CRAWL_YEAR, extractYear(header.getDate()) ); solr.doc.setField(SolrFields.CRAWL_DATE, parseCrawlDate(waybackDate)); // Basic metadata: byte[] md5digest = md5.digest( fullUrl.getBytes( "UTF-8" ) ); String md5hex = new String( Base64.encodeBase64( md5digest ) ); solr.doc.setField( SolrFields.ID, waybackDate + "/" + md5hex); solr.doc.setField( SolrFields.ID_LONG, Long.parseLong(waybackDate + "00") + ( (md5digest[1] << 8) + md5digest[0] ) ); solr.doc.setField( SolrFields.HASH, header.getHeaderValue(WARCConstants.HEADER_KEY_PAYLOAD_DIGEST) ); solr.doc.setField( SolrFields.SOLR_URL, fullUrl); solr.doc.setField( SolrFields.HASH_AND_URL, header.getHeaderValue(WARCConstants.HEADER_KEY_PAYLOAD_DIGEST) + "_" + fullUrl ); // Also pull out the file extension, if any: solr.doc.addField( SolrFields.CONTENT_TYPE_EXT, parseExtension( fullUrl ) ); // Strip down very long URLs to avoid "org.apache.commons.httpclient.URIException: Created (escaped) uuri > 2083" if( fullUrl.length() > 2000 ) fullUrl = fullUrl.substring( 0, 2000 ); String[] urlParts = canon.urlStringToKey( fullUrl ).split( "/" ); // Spot 'slash pages': if( urlParts.length == 1 || ( urlParts.length >= 2 && urlParts[ 1 ].matches( "^index\\.[a-z]+$" ) ) ) solr.doc.setField( SolrFields.SOLR_URL_TYPE, SolrFields.SOLR_URL_TYPE_SLASHPAGE ); // Spot 'robots.txt': if( urlParts.length >= 2 && urlParts[ 1 ].equalsIgnoreCase( "robots.txt" ) ) solr.doc.setField( SolrFields.SOLR_URL_TYPE, SolrFields.SOLR_URL_TYPE_ROBOTS_TXT ); // Record the domain (strictly, the host): String host = urlParts[ 0 ]; solr.doc.setField( SolrFields.SOLR_HOST, host ); solr.doc.setField( SolrFields.DOMAIN, LinkExtractor.extractPrivateSuffixFromHost( host ) ); solr.doc.setField( SolrFields.PUBLIC_SUFFIX, LinkExtractor.extractPublicSuffixFromHost( host ) ); InputStream tikainput = null; // Only parse HTTP headers for HTTP URIs if( fullUrl.startsWith( "http" ) ) { // Parse HTTP headers: String statusCode = null; if( record instanceof WARCRecord ) { // There are not always headers! The code should check first. String statusLine = HttpParser.readLine( record, "UTF-8" ); if( statusLine != null && statusLine.startsWith( "HTTP" ) ) { String firstLine[] = statusLine.split( " " ); if( firstLine.length > 1 ) { statusCode = firstLine[ 1 ].trim(); try { this.processHeaders( solr, statusCode, HttpParser.parseHeaders( record, "UTF-8" ) ); } catch( ProtocolException p ) { log.error( "ProtocolException [" + statusCode + "]: " + header.getHeaderValue( WARCConstants.HEADER_KEY_FILENAME ) + "@" + header.getHeaderValue( WARCConstants.ABSOLUTE_OFFSET_KEY ), p ); } } else { log.warn( "Could not parse status line: " + statusLine ); } } else { log.warn( "Invalid status line: " + header.getHeaderValue( WARCConstants.HEADER_KEY_FILENAME ) + "@" + header.getHeaderValue( WARCConstants.ABSOLUTE_OFFSET_KEY ) ); } // No need for this, as the headers have already been read from the InputStream (above): // WARCRecordUtils.getPayload(record); tikainput = record; } else if( record instanceof ARCRecord ) { ARCRecord arcr = ( ARCRecord ) record; statusCode = "" + arcr.getStatusCode(); this.processHeaders( solr, statusCode, arcr.getHttpHeaders() ); arcr.skipHttpHeader(); tikainput = arcr; } else { log.error( "FAIL! Unsupported archive record type." ); return solr; } // Skip recording non-content URLs (i.e. 2xx responses only please): if( this.checkResponseCode(statusCode) == false ) { log.error("Skipping this record based on status code "+statusCode+": "+header.getUrl()); return null; } } // ----------------------------------------------------- // Parse payload using Tika: // ----------------------------------------------------- // Mark the start of the payload, and then run Tika on it: tikainput = new BufferedInputStream( new BoundedInputStream( tikainput, BUFFER_SIZE ), ( int ) BUFFER_SIZE ); tikainput.mark( ( int ) header.getLength() ); if( passUriToFormatTools ) { solr = tika.extract( solr, tikainput, header.getUrl() ); } else { solr = tika.extract( solr, tikainput, null ); } // Pull out the first few bytes, to hunt for new format by magic: try { tikainput.reset(); byte[] ffb = new byte[this.firstBytesLength]; int read = tikainput.read(ffb); if( read >= 4 ) { String hexBytes = Hex.encodeHexString( ffb ); solr.addField( SolrFields.CONTENT_FFB, hexBytes.substring( 0, 2 * 4 ) ); StringBuilder separatedHexBytes = new StringBuilder(); for( String hexByte : Splitter.fixedLength( 2 ).split( hexBytes ) ) { separatedHexBytes.append( hexByte ); separatedHexBytes.append( " " ); } if( this.extractContentFirstBytes ) { solr.addField(SolrFields.CONTENT_FIRST_BYTES, separatedHexBytes.toString().trim()); } } } catch( IOException i ) { log.error( i + ": " + i.getMessage() + ";ffb; " + header.getUrl() + "@" + header.getOffset() ); } // Also run DROID (restricted range): if( dd != null && runDroid == true ) { try { tikainput.reset(); // Pass the URL in so DROID can fall back on that: Metadata metadata = new Metadata(); if( passUriToFormatTools ) { UURI uuri = UURIFactory.getInstance( fullUrl ); // Droid seems unhappy about spaces in filenames, so hack to avoid: String cleanUrl = uuri.getName().replace( " ", "+" ); metadata.set( Metadata.RESOURCE_NAME_KEY, cleanUrl ); } // Run Droid: MediaType mt = dd.detect( tikainput, metadata ); solr.addField( SolrFields.CONTENT_TYPE_DROID, mt.toString() ); } catch( Exception i ) { // Note that DROID complains about some URLs with an IllegalArgumentException. log.error( i + ": " + i.getMessage() + ";dd; " + fullUrl + " @" + header.getOffset() ); } } // Derive normalised/simplified content type: processContentType( solr, header ); // Pass on to other extractors as required, resetting the stream before each: // Entropy, compressibility, fussy hashes, etc. Metadata metadata = new Metadata(); try { tikainput.reset(); // JSoup link extractor for (x)html, deposit in 'links' field. String mime = ( String ) solr.doc.getField( SolrFields.SOLR_CONTENT_TYPE ).getValue(); HashMap<String, String> hosts = new HashMap<String, String>(); HashMap<String, String> suffixes = new HashMap<String, String>(); HashMap<String, String> domains = new HashMap<String, String>(); if( mime.startsWith( "text" ) ) { // JSoup NEEDS the URL to function: metadata.set( Metadata.RESOURCE_NAME_KEY, header.getUrl() ); ParseRunner parser = new ParseRunner( hfp, tikainput, metadata ); Thread thread = new Thread( parser, Long.toString( System.currentTimeMillis() ) ); try { thread.start(); thread.join( 30000L ); thread.interrupt(); } catch( Exception e ) { log.error( "WritableSolrRecord.extract(): " + e.getMessage() ); } // Process links: String links_list = metadata.get( HtmlFeatureParser.LINK_LIST ); if( links_list != null ) { String lhost, ldomain, lsuffix; for( String link : links_list.split( " " ) ) { lhost = LinkExtractor.extractHost( link ); if( !lhost.equals( LinkExtractor.MALFORMED_HOST ) ) { hosts.put( lhost, "" ); } lsuffix = LinkExtractor.extractPublicSuffix( link ); if( lsuffix != null ) { suffixes.put( lsuffix, "" ); } ldomain = LinkExtractor.extractPrivateSuffix( link ); if( ldomain != null ) { domains.put( ldomain, "" ); } // Also store actual resource-level links: if( this.extractLinks ) solr.addField( SolrFields.SOLR_LINKS, link ); } // Store the data from the links: Iterator<String> iterator = null; if( this.extractLinkHosts ) { iterator = hosts.keySet().iterator(); while( iterator.hasNext() ) { solr.addField( SolrFields.SOLR_LINKS_HOSTS, iterator.next() ); } } if( this.extractLinkDomains ) { iterator = domains.keySet().iterator(); while( iterator.hasNext() ) { solr.addField( SolrFields.SOLR_LINKS_DOMAINS, iterator.next() ); } } iterator = suffixes.keySet().iterator(); while( iterator.hasNext() ) { solr.addField( SolrFields.SOLR_LINKS_PUBLIC_SUFFIXES, iterator.next() ); } } // Process element usage: if( this.extractElementsUsed ) { String de = metadata.get( HtmlFeatureParser.DISTINCT_ELEMENTS ); if( de != null ) { for( String e : de.split( " " ) ) { solr.addField( SolrFields.ELEMENTS_USED, e ); } } } for( String lurl : metadata.getValues( Metadata.LICENSE_URL ) ) { solr.addField( SolrFields.LICENSE_URL, lurl ); } } else if( mime.startsWith( "image" ) ) { // TODO Extract image properties. } else if( mime.startsWith( "application/pdf" ) ) { // TODO e.g. Use PDFBox Preflight to analyse? https://pdfbox.apache.org/userguide/preflight.html } } catch( Exception i ) { log.error( i + ": " + i.getMessage() + ";x; " + header.getUrl() + "@" + header.getOffset() ); } // --- The following extractors don't need to re-read the payload --- // Pull out the text: if( solr.doc.getField( SolrFields.SOLR_EXTRACTED_TEXT ) != null ) { String text = ( String ) solr.doc.getField( SolrFields.SOLR_EXTRACTED_TEXT ).getFirstValue(); text = text.trim(); if( !"".equals( text ) ) { /* ---------------------------------------------------------- */ if( metadata.get( Metadata.CONTENT_LANGUAGE ) == null ) { String li = ld.detectLanguage( text ); if( li != null ) solr.addField( SolrFields.CONTENT_LANGUAGE, li ); } else { solr.addField( SolrFields.CONTENT_LANGUAGE, metadata.get( Metadata.CONTENT_LANGUAGE ) ); } /* ---------------------------------------------------------- */ // Sentiment Analysis: int sentilen = 10000; if( sentilen > text.length() ) sentilen = text.length(); String sentitext = text.substring( 0, sentilen ); // metadata.get(HtmlFeatureParser.FIRST_PARAGRAPH); Sentiment senti = sentij.analyze( sentitext ); double sentilog = Math.signum( senti.getComparative() ) * ( Math.log( 1.0 + Math.abs( senti.getComparative() ) ) / 40.0 ); int sentii = ( int ) ( SolrFields.SENTIMENTS.length * ( 0.5 + sentilog ) ); if( sentii < 0 ) { log.debug( "Caught a sentiment rating less than zero: " + sentii + " from " + sentilog ); sentii = 0; } if( sentii >= SolrFields.SENTIMENTS.length ) { log.debug( "Caught a sentiment rating too large to be in range: " + sentii + " from " + sentilog ); sentii = SolrFields.SENTIMENTS.length - 1; } // if( sentii != 3 ) // log.debug("Got sentiment: " + sentii+" "+sentilog+" "+ SolrFields.SENTIMENTS[sentii] ); // Map to sentiment scale: solr.addField( SolrFields.SENTIMENT, SolrFields.SENTIMENTS[ sentii ] ); solr.addField( SolrFields.SENTIMENT_SCORE, "" + senti.getComparative() ); /* ---------------------------------------------------------- */ // Postcode Extractor (based on text extracted by Tika) Matcher pcm = postcodePattern.matcher( text ); Set<String> pcs = new HashSet<String>(); while( pcm.find() ) pcs.add( pcm.group() ); for( String pc : pcs ) { solr.addField( SolrFields.POSTCODE, pc ); String pcd = pc.substring( 0, pc.lastIndexOf( " " ) ); solr.addField( SolrFields.POSTCODE_DISTRICT, pcd ); String location = pcg.getLatLogForPostcodeDistrict( pcd ); if( location != null ) solr.addField( SolrFields.LOCATIONS, location ); } // TODO Named entity extraction /* ---------------------------------------------------------- */ // Canonicalize the text - strip newlines etc. Pattern whitespace = Pattern.compile( "\\s+" ); Matcher matcher = whitespace.matcher( text ); text = matcher.replaceAll( " " ).toLowerCase().trim(); /* ---------------------------------------------------------- */ // Add SSDeep hash for the text, to spot similar texts. SSDeep ssd = new SSDeep(); FuzzyHash tfh = ssd.fuzzy_hash_buf( text.getBytes( "UTF-8" ) ); solr.addField( SolrFields.SSDEEP_PREFIX + tfh.getBlocksize(), tfh.getHash() ); solr.addField( SolrFields.SSDEEP_PREFIX + ( tfh.getBlocksize() * 2 ), tfh.getHash2() ); solr.addField( SolrFields.SSDEEP_NGRAM_PREFIX + tfh.getBlocksize(), tfh.getHash() ); solr.addField( SolrFields.SSDEEP_NGRAM_PREFIX + ( tfh.getBlocksize() * 2 ), tfh.getHash2() ); } } // TODO ACT/WctEnricher, currently invoked in the reduce stage to lower query hits, but should shift here. // Remove the Text Field if required if( !isTextIncluded ){ solr.doc.removeField(SolrFields.SOLR_EXTRACTED_TEXT); } } return solr; } /* ----------------------------------- */ private void processHeaders(SolrRecord solr, String statusCode, Header[] httpHeaders) { try { // This is a simple test that the status code setting worked: int statusCodeInt = Integer.parseInt( statusCode ); if( statusCodeInt < 0 || statusCodeInt > 1000 ) throw new Exception( "Status code out of range: " + statusCodeInt ); // Get the other headers: for( Header h : httpHeaders ) { // Get the type from the server if( h.getName().equals( HttpHeaders.CONTENT_TYPE ) ) solr.addField( SolrFields.CONTENT_TYPE_SERVED, h.getValue() ); // Also, grab the X-Powered-By or Server headers if present: if( h.getName().equals( "X-Powered-By" ) ) solr.addField( SolrFields.GENERATOR, h.getValue() ); if( h.getName().equals( HttpHeaders.SERVER ) ) solr.addField( SolrFields.SERVER, h.getValue() ); } } catch( NumberFormatException e ) { log.error( "Exception when parsing status code: " + statusCode + ": " + e ); solr.addField( SolrFields.PARSE_ERROR, e.getClass().getName() + " when parsing statusCode: " + e.getMessage() ); } catch( Exception e ) { log.error( "Exception when parsing headers: " + e ); solr.addField( SolrFields.PARSE_ERROR, e.getClass().getName() + ": " + e.getMessage() ); } } /** * * @param fullUrl * @return */ protected static String parseExtension( String fullUrl ) { if( fullUrl.lastIndexOf( "/" ) != -1 ) { String path = fullUrl.substring( fullUrl.lastIndexOf( "/" ) ); if( path.indexOf( "?" ) != -1 ) { path = path.substring( 0, path.indexOf( "?" ) ); } if( path.indexOf( "&" ) != -1 ) { path = path.substring( 0, path.indexOf( "&" ) ); } if( path.indexOf( "." ) != -1 ) { String ext = path.substring( path.lastIndexOf( "." ) ); ext = ext.toLowerCase(); // Avoid odd/malformed extensions: // if( ext.contains("%") ) // ext = ext.substring(0, path.indexOf("%")); ext = ext.replaceAll( "[^0-9a-z]", "" ); return ext; } } return null; } /** * Timestamp parsing, for the Crawl Date. */ private static SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'" ); static { formatter.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); } /** * * @param waybackDate * @return */ protected static String parseCrawlDate( String waybackDate ) { try { // Some ARC records have 12-, 16- or 17-digit dates if( waybackDate.length() == 12 ) { return formatter.format( ArchiveUtils.parse12DigitDate( waybackDate ) ); } else if( waybackDate.length() == 14 ) { return formatter.format( ArchiveUtils.parse14DigitDate( waybackDate ) ); } else if( waybackDate.length() == 16 ) { return formatter.format( ArchiveUtils.parse17DigitDate( waybackDate + "0" ) ); } else if( waybackDate.length() >= 17 ) { return formatter.format( ArchiveUtils.parse17DigitDate( waybackDate.substring( 0, 17 ) ) ); } } catch( ParseException p ) { p.printStackTrace(); } return null; } /** * * @param timestamp * @return */ public static String extractYear( String timestamp ) { // Default to 'unknown': String waybackYear = "unknown"; String waybackDate = timestamp.replaceAll( "[^0-9]", "" ); if( waybackDate != null ) waybackYear = waybackDate.substring( 0, 4 ); // Reject bad values by resetting to 'unknown': if( "0000".equals( waybackYear ) ) waybackYear = "unknown"; // Return return waybackYear; } /** * * @param solr * @param header * @param serverType */ private void processContentType( SolrRecord solr, ArchiveRecordHeader header) { // Get the current content-type: String contentType = ( String ) solr.doc.getFieldValue( SolrFields.SOLR_CONTENT_TYPE ); String serverType = ( String ) solr.doc.getFieldValue( SolrFields.CONTENT_TYPE_SERVED ); // Store the raw content type from Tika: solr.doc.setField( SolrFields.CONTENT_TYPE_TIKA, contentType ); // Also get the other content types: MediaType mt_tika = MediaType.parse( contentType ); if( solr.doc.get( SolrFields.CONTENT_TYPE_DROID ) != null ) { MediaType mt_droid = MediaType.parse( ( String ) solr.doc.get( SolrFields.CONTENT_TYPE_DROID ).getFirstValue() ); if( mt_tika == null || mt_tika.equals( MediaType.OCTET_STREAM ) ) { contentType = mt_droid.toString(); } else if( mt_droid.getBaseType().equals( mt_tika.getBaseType() ) && mt_droid.getParameters().get( "version" ) != null ) { // Union of results: mt_tika = new MediaType( mt_tika, mt_droid.getParameters() ); contentType = mt_tika.toString(); } if( mt_droid.getParameters().get( "version" ) != null ) { solr.doc.addField( SolrFields.CONTENT_VERSION, mt_droid.getParameters().get( "version" ) ); } } // Allow header MIME - if( contentType.isEmpty() ) { + if( contentType != null && contentType.isEmpty() ) { if( header.getHeaderFieldKeys().contains( "WARC-Identified-Payload-Type" ) ) { contentType = ( ( String ) header.getHeaderFields().get( "WARC-Identified-Payload-Type" ) ); } else { contentType = header.getMimetype(); } } // Determine content type: solr.doc.setField( SolrFields.FULL_CONTENT_TYPE, contentType ); // Fall back on serverType for plain text: if( contentType != null && contentType.startsWith( "text/plain" ) ) { if( serverType != null ) { contentType = serverType; } } // Strip parameters out of main type field: solr.doc.setField( SolrFields.SOLR_CONTENT_TYPE, contentType.replaceAll( ";.*$", "" ) ); // Also add a more general, simplified type, as appropriate: // FIXME clean up this messy code: if( contentType.matches( "^image/.*$" ) ) { solr.doc.setField( SolrFields.SOLR_NORMALISED_CONTENT_TYPE, "image" ); } else if( contentType.matches( "^(audio|video)/.*$" ) ) { solr.doc.setField( SolrFields.SOLR_NORMALISED_CONTENT_TYPE, "media" ); } else if( contentType.matches( "^text/htm.*$" ) ) { solr.doc.setField( SolrFields.SOLR_NORMALISED_CONTENT_TYPE, "html" ); } else if( contentType.matches( "^application/pdf.*$" ) ) { solr.doc.setField( SolrFields.SOLR_NORMALISED_CONTENT_TYPE, "pdf" ); } else if( contentType.matches( "^.*word$" ) ) { solr.doc.setField( SolrFields.SOLR_NORMALISED_CONTENT_TYPE, "word" ); } else if( contentType.matches( "^.*excel$" ) ) { solr.doc.setField( SolrFields.SOLR_NORMALISED_CONTENT_TYPE, "excel" ); } else if( contentType.matches( "^.*powerpoint$" ) ) { solr.doc.setField( SolrFields.SOLR_NORMALISED_CONTENT_TYPE, "powerpoint" ); } else if( contentType.matches( "^text/plain.*$" ) ) { solr.doc.setField( SolrFields.SOLR_NORMALISED_CONTENT_TYPE, "text" ); } else { solr.doc.setField( SolrFields.SOLR_NORMALISED_CONTENT_TYPE, "other" ); } // Remove text from JavaScript, CSS, ... if( contentType.startsWith( "application/javascript" ) || contentType.startsWith( "text/javascript" ) || contentType.startsWith( "text/css" ) ) { solr.doc.removeField( SolrFields.SOLR_EXTRACTED_TEXT ); } } private boolean checkUrl( String url ) { for( String exclude : url_excludes ) { if( !"".equals(exclude) && url.matches( ".*" + exclude + ".*" ) ) { return false; } } return true; } private boolean checkProtocol( String url ) { for( String include : protocol_includes ) { if( "".equals(include) || url.startsWith( include ) ) { return true; } } return false; } private boolean checkResponseCode( String statusCode ) { if( statusCode == null ) return false; // Check for match: for( String include : response_includes ) { if( "".equals(include) || statusCode.startsWith( include ) ) { return true; } } // Exclude return false; } private boolean checkExclusionFilter( String uri ) { // Default to no exclusions: if( smef == null ) return true; // Otherwise: ExclusionFilter ef = smef.get(); CaptureSearchResult r = new CaptureSearchResult(); //r.setOriginalUrl(uri); r.setUrlKey(uri); try { if( ef.filterObject(r) == ExclusionFilter.FILTER_INCLUDE ) { return true; } } catch( Exception e ) { log.error("Exclusion filtering failed with exception: "+e); e.printStackTrace(); } log.debug("EXCLUDING this URL due to filter: "+uri); // Exclude: return false; } private class ParseRunner implements Runnable { HtmlFeatureParser hfp; Metadata metadata; InputStream input; public ParseRunner( HtmlFeatureParser parser, InputStream tikainput, Metadata metadata ) { this.hfp = parser; this.metadata = metadata; this.input = tikainput; } @Override public void run() { try { hfp.parse( input, null, metadata, null ); } catch( Exception e ) { log.error( "HtmlFeatureParser.parse(): " + e.getMessage() ); } } } }
true
false
null
null
diff --git a/src/se/mockachino/proxy/CglibAsmUtil.java b/src/se/mockachino/proxy/CglibAsmUtil.java index e4cef2c..7919fc2 100644 --- a/src/se/mockachino/proxy/CglibAsmUtil.java +++ b/src/se/mockachino/proxy/CglibAsmUtil.java @@ -1,93 +1,86 @@ package se.mockachino.proxy; import net.sf.cglib.proxy.*; import se.mockachino.Primitives; import se.mockachino.ProxyMetadata; import se.mockachino.exceptions.UsageError; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.List; import java.util.Set; public class CglibAsmUtil { private final static Class[] CLASSES = {ProxyMetadata.class}; private static final boolean HAS_OBJENESIS = hasObjenesis(); private static boolean hasObjenesis() { try { Class<?> clazz = Class.forName("org.objenesis.ObjenesisStd"); return true; } catch (ClassNotFoundException e) { return false; } } - private static final CallbackFilter IGNORE_BRIDGE_METHODS = new CallbackFilter() { - public int accept(Method method) { - return method.isBridge() ? 1 : 0; - } - }; - static <T> T getCglibProxy(Class<T> clazz, final InvocationHandler handler, Set<Class<?>> extraInterfaces) throws Exception { net.sf.cglib.proxy.InvocationHandler callback = new net.sf.cglib.proxy.InvocationHandler() { @Override public Object invoke(Object o, Method method, Object[] objects) throws Throwable { return handler.invoke(o, method, objects); } }; Class[] classes = CglibAsmUtil.CLASSES; if (extraInterfaces.size() > 0) { classes = new Class[1 + extraInterfaces.size()]; classes[0] = ProxyMetadata.class; int i = 1; for (Class<?> extraInterface : extraInterfaces) { classes[i] = extraInterface; i++; } } Enhancer enhancer = new Enhancer() { @Override @SuppressWarnings("unchecked") protected void filterConstructors(Class sc, List constructors) { } }; enhancer.setSuperclass(clazz); enhancer.setInterfaces(classes); if (HAS_OBJENESIS) { enhancer.setUseFactory(true); enhancer.setCallbackTypes(new Class[]{net.sf.cglib.proxy.InvocationHandler.class}); - enhancer.setCallbackFilter(IGNORE_BRIDGE_METHODS); Factory factory = (Factory) ObjenesisUtil.newInstance(enhancer.createClass()); factory.setCallbacks(new Callback[]{callback}); return (T) factory; } enhancer.setCallback(callback); Exception constructorError = null; for (Constructor<?> constructor : clazz.getConstructors()) { Class<?>[] types = constructor.getParameterTypes(); Object[] args = new Object[types.length]; for (int i = 0; i < types.length; i++) { args[i] = Primitives.forType(types[i]); } try { return (T) enhancer.create(types, args); } catch (Exception e) { if (constructorError == null) { constructorError = e; } } } if (constructorError != null) { throw constructorError; } throw new UsageError("Class " + clazz.getSimpleName() + " has no non-private constructors."); } } diff --git a/test/blackbox/se/mockachino/MockClassTest.java b/test/blackbox/se/mockachino/MockClassTest.java index a438abb..c44cd9a 100644 --- a/test/blackbox/se/mockachino/MockClassTest.java +++ b/test/blackbox/se/mockachino/MockClassTest.java @@ -1,66 +1,65 @@ package se.mockachino; import org.junit.Test; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static se.mockachino.Mockachino.mock; import static se.mockachino.Mockachino.*; import static se.mockachino.matchers.Matchers.*; import static se.mockachino.Settings.*; public class MockClassTest { public static class TestClass { public TestClass(int a, String s) { } } private static class SecretClass { private SecretClass(int a, String s) { } } private static class ExceptionClass { public ExceptionClass() { throw new RuntimeException("Ouch"); } public ExceptionClass(int a, String s) { throw new RuntimeException("Ouch"); } public ExceptionClass(int a, String s, boolean b) { } } private static class BrokenClass { public BrokenClass() { throw new Error("Broken"); } } @Test public void testMockClassWithParams() { TestClass mock = mock(TestClass.class); assertTrue(mock.toString().startsWith("Mock:TestClass:")); } @Test public void testMockPrivateClass() { SecretClass mock = mock(SecretClass.class); assertTrue(mock.toString().startsWith("Mock:SecretClass:")); } @Test public void testException() { ExceptionClass mock = mock(ExceptionClass.class); assertTrue(mock.toString().startsWith("Mock:ExceptionClass:")); } @Test public void testSimpleObjenesis() { BrokenClass mock = mock(BrokenClass.class); assertTrue(mock.toString().startsWith("Mock:BrokenClass:")); } - }
false
false
null
null
diff --git a/descent.core/src/descent/internal/compiler/parser/ASTDmdNode.java b/descent.core/src/descent/internal/compiler/parser/ASTDmdNode.java index ee1741b4..59b8aad8 100644 --- a/descent.core/src/descent/internal/compiler/parser/ASTDmdNode.java +++ b/descent.core/src/descent/internal/compiler/parser/ASTDmdNode.java @@ -1,2641 +1,2641 @@ package descent.internal.compiler.parser; import static descent.internal.compiler.parser.DYNCAST.DYNCAST_DSYMBOL; import static descent.internal.compiler.parser.DYNCAST.DYNCAST_EXPRESSION; import static descent.internal.compiler.parser.DYNCAST.DYNCAST_TUPLE; import static descent.internal.compiler.parser.DYNCAST.DYNCAST_TYPE; import static descent.internal.compiler.parser.LINK.LINKd; import static descent.internal.compiler.parser.MATCH.MATCHconst; import static descent.internal.compiler.parser.MATCH.MATCHexact; import static descent.internal.compiler.parser.MATCH.MATCHnomatch; import static descent.internal.compiler.parser.PROT.PROTpackage; import static descent.internal.compiler.parser.PROT.PROTprivate; import static descent.internal.compiler.parser.PROT.PROTprotected; import static descent.internal.compiler.parser.STC.STClazy; import static descent.internal.compiler.parser.STC.STCmanifest; import static descent.internal.compiler.parser.STC.STCout; import static descent.internal.compiler.parser.STC.STCref; import static descent.internal.compiler.parser.TOK.TOKarray; import static descent.internal.compiler.parser.TOK.TOKassocarrayliteral; import static descent.internal.compiler.parser.TOK.TOKblit; import static descent.internal.compiler.parser.TOK.TOKconstruct; import static descent.internal.compiler.parser.TOK.TOKdefault; import static descent.internal.compiler.parser.TOK.TOKdelegate; import static descent.internal.compiler.parser.TOK.TOKdotexp; import static descent.internal.compiler.parser.TOK.TOKfloat64; import static descent.internal.compiler.parser.TOK.TOKforeach_reverse; import static descent.internal.compiler.parser.TOK.TOKfunction; import static descent.internal.compiler.parser.TOK.TOKnull; import static descent.internal.compiler.parser.TOK.TOKslice; import static descent.internal.compiler.parser.TOK.TOKstring; import static descent.internal.compiler.parser.TOK.TOKsuper; import static descent.internal.compiler.parser.TOK.TOKsymoff; import static descent.internal.compiler.parser.TOK.TOKtuple; import static descent.internal.compiler.parser.TOK.TOKtype; import static descent.internal.compiler.parser.TOK.TOKvar; import static descent.internal.compiler.parser.TY.Tarray; import static descent.internal.compiler.parser.TY.Tbit; import static descent.internal.compiler.parser.TY.Tclass; import static descent.internal.compiler.parser.TY.Tdelegate; import static descent.internal.compiler.parser.TY.Terror; import static descent.internal.compiler.parser.TY.Tfunction; import static descent.internal.compiler.parser.TY.Tident; import static descent.internal.compiler.parser.TY.Tpointer; import static descent.internal.compiler.parser.TY.Tsarray; import static descent.internal.compiler.parser.TY.Tstruct; import static descent.internal.compiler.parser.TY.Ttuple; import static descent.internal.compiler.parser.TY.Tvoid; import java.util.List; import org.eclipse.core.runtime.Assert; import descent.core.compiler.CharOperation; import descent.core.compiler.IProblem; import descent.internal.compiler.parser.ast.ASTNode; import descent.internal.compiler.parser.ast.IASTVisitor; // class Object in DMD compiler public abstract class ASTDmdNode extends ASTNode { public final static int COST_MAX = 250; public final static int WANTflags = 1; public final static int WANTvalue = 2; public final static int WANTinterpret = 4; public final static int ARGUMENT = 1; public final static int CATCH = 2; public final static int ALIGN_DECLARATION = 3; public final static int ANON_DECLARATION = 4; public final static int COMPILE_DECLARATION = 5; public final static int CONDITIONAL_DECLARATION = 6; public final static int LINK_DECLARATION = 7; public final static int PRAGMA_DECLARATION = 8; public final static int DEBUG_SYMBOL = 9; public final static int ALIAS_DECLARATION = 10; public final static int FUNC_DECLARATION = 11; public final static int CTOR_DECLARATION = 12; public final static int DELETE_DECLARATION = 13; public final static int DTOR_DECLARATION = 14; public final static int FUNC_LITERAL_DECLARATION = 15; public final static int INVARIANT_DECLARATION = 16; public final static int NEW_DECLARATION = 17; public final static int STATIC_CTOR_DECLARATION = 18; public final static int STATIC_DTOR_DECLARATION = 19; public final static int UNIT_TEST_DECLARATION = 20; public final static int PROT_DECLARATION = 21; public final static int STORAGE_CLASS_DECLARATION = 22; public final static int BASE_CLASS = 23; public final static int TYPEDEF_DECLARATION = 24; public final static int VAR_DECLARATION = 25; public final static int ENUM_MEMBER = 26; public final static int IMPORT = 27; public final static int MODIFIER_DECLARATION = 28; public final static int MULTI_IMPORT = 29; public final static int CLASS_DECLARATION = 30; public final static int INTERFACE_DECLARATION = 31; public final static int STRUCT_DECLARATION = 32; public final static int UNION_DECLARATION = 33; public final static int ENUM_DECLARATION = 34; public final static int MODULE = 35; public final static int TEMPLATE_DECLARATION = 36; public final static int TEMPLATE_INSTANCE = 37; public final static int TEMPLATE_MIXIN = 38; public final static int STATIC_ASSERT = 39; public final static int VERSION = 40; public final static int VERSION_SYMBOL = 41; public final static int ARRAY_LITERAL_EXP = 42; public final static int ADD_ASSIGN_EXP = 43; public final static int INCREMENT_EXP = 44; public final static int ADD_EXP = 45; public final static int AND_AND_EXP = 46; public final static int AND_ASSIGN_EXP = 47; public final static int AND_EXP = 48; public final static int ASSIGN_EXP = 49; public final static int CAT_ASSIGN_EXP = 50; public final static int CAT_EXP = 51; public final static int CMP_EXP = 52; public final static int COMMA_EXP = 53; public final static int COND_EXP = 54; public final static int DIV_ASSIGN_EXP = 55; public final static int DIV_EXP = 56; public final static int EQUAL_EXP = 57; public final static int IDENTITY_EXP = 58; public final static int IN_EXP = 59; public final static int MIN_ASSIGN_EXP = 60; public final static int DECREMENT_EXP = 61; public final static int MIN_EXP = 62; public final static int MOD_ASSIGN_EXP = 63; public final static int MOD_EXP = 64; public final static int MUL_ASSIGN_EXP = 65; public final static int MUL_EXP = 66; public final static int OR_ASSIGN_EXP = 67; public final static int OR_EXP = 68; public final static int OR_OR_EXP = 69; public final static int POST_EXP = 70; public final static int SHL_ASSIGN_EXP = 71; public final static int SHL_EXP = 72; public final static int SHR_ASSIGN_EXP = 73; public final static int SHR_EXP = 74; public final static int USHR_ASSIGN_EXP = 75; public final static int USHR_EXP = 76; public final static int XOR_ASSIGN_EXP = 77; public final static int XOR_EXP = 78; public final static int DECLARATION_EXP = 79; public final static int DOLLAR_EXP = 80; public final static int FUNC_EXP = 81; public final static int IDENTIFIER_EXP = 82; public final static int TEMPLATE_INSTANCE_WRAPPER = 83; public final static int IFTYPE_EXP = 84; public final static int INTEGER_EXP = 85; public final static int SWITCH_ERROR_STATEMENT = 86; public final static int NEW_ANON_CLASS_EXP = 87; public final static int NEW_EXP = 88; public final static int NULL_EXP = 89; public final static int REAL_EXP = 90; public final static int SCOPE_EXP = 91; public final static int STRING_EXP = 92; public final static int THIS_EXP = 93; public final static int SUPER_EXP = 94; public final static int TYPE_DOT_ID_EXP = 95; public final static int TYPE_EXP = 96; public final static int TYPEID_EXP = 97; public final static int ADDR_EXP = 98; public final static int ARRAY_EXP = 99; public final static int ASSERT_EXP = 100; public final static int CALL_EXP = 101; public final static int CAST_EXP = 102; public final static int COM_EXP = 103; public final static int COMPILE_EXP = 104; public final static int DELETE_EXP = 105; public final static int DOT_ID_EXP = 106; public final static int DOT_TEMPLATE_INSTANCE_EXP = 107; public final static int FILE_EXP = 108; public final static int NEG_EXP = 109; public final static int NOT_EXP = 110; public final static int BOOL_EXP = 111; public final static int PTR_EXP = 112; public final static int SLICE_EXP = 113; public final static int UADD_EXP = 114; public final static int ARRAY_INITIALIZER = 115; public final static int EXP_INITIALIZER = 116; public final static int STRUCT_INITIALIZER = 117; public final static int VOID_INITIALIZER = 118; public final static int MODIFIER = 119; public final static int MODULE_DECLARATION = 120; public final static int ASM_STATEMENT = 121; public final static int BREAK_STATEMENT = 122; public final static int CASE_STATEMENT = 123; public final static int COMPILE_STATEMENT = 124; public final static int COMPOUND_STATEMENT = 125; public final static int ASM_BLOCK = 126; public final static int CONDITIONAL_STATEMENT = 127; public final static int CONTINUE_STATEMENT = 128; public final static int DEFAULT_STATEMENT = 129; public final static int DO_STATEMENT = 130; public final static int EXP_STATEMENT = 131; public final static int DECLARATION_STATEMENT = 132; public final static int FOREACH_STATEMENT = 133; public final static int FOR_STATEMENT = 134; public final static int GOTO_CASE_STATEMENT = 135; public final static int GOTO_DEFAULT_STATEMENT = 136; public final static int GOTO_STATEMENT = 137; public final static int IF_STATEMENT = 138; public final static int LABEL_STATEMENT = 139; public final static int ON_SCOPE_STATEMENT = 140; public final static int PRAGMA_STATEMENT = 141; public final static int RETURN_STATEMENT = 142; public final static int STATIC_ASSERT_STATEMENT = 143; public final static int SWITCH_STATEMENT = 144; public final static int SYNCHRONIZED_STATEMENT = 145; public final static int THROW_STATEMENT = 146; public final static int VOLATILE_STATEMENT = 148; public final static int WHILE_STATEMENT = 149; public final static int WITH_STATEMENT = 150; public final static int TEMPLATE_ALIAS_PARAMETER = 151; public final static int TEMPLATE_TUPLE_PARAMETER = 152; public final static int TEMPLATE_TYPE_PARAMETER = 153; public final static int TEMPLATE_VALUE_PARAMETER = 154; public final static int TYPE_A_ARRAY = 155; public final static int TYPE_BASIC = 156; public final static int TYPE_D_ARRAY = 157; public final static int TYPE_DELEGATE = 158; public final static int TYPE_FUNCTION = 159; public final static int TYPE_POINTER = 160; public final static int TYPE_IDENTIFIER = 161; public final static int TYPE_INSTANCE = 162; public final static int TYPE_TYPEOF = 163; public final static int TYPE_S_ARRAY = 164; public final static int TYPE_SLICE = 165; public final static int TYPE_TYPEDEF = 166; public final static int TYPE_ENUM = 167; public final static int TUPLE_DECLARATION = 168; public final static int TYPE_TUPLE = 169; public final static int VAR_EXP = 170; public final static int DOT_VAR_EXP = 171; public final static int TYPE_STRUCT = 172; public final static int DSYMBOL_EXP = 173; public final static int TYPE_CLASS = 174; public final static int THIS_DECLARATION = 175; public final static int ARRAY_SCOPE_SYMBOL = 176; public final static int SCOPE_DSYMBOL = 177; public final static int TEMPLATE_EXP = 178; public final static int TRY_FINALLY_STATEMENT = 179; public final static int TRY_CATCH_STATEMENT = 180; public final static int LABEL_DSYMBOL = 181; public final static int HALT_EXP = 182; public final static int SYM_OFF_EXP = 183; public final static int SCOPE_STATEMENT = 184; public final static int DELEGATE_EXP = 185; public final static int TUPLE_EXP = 186; public final static int UNROLLED_LOOP_STATEMENT = 187; public final static int COMPLEX_EXP = 188; public final static int ASSOC_ARRAY_LITERAL_EXP = 189; public final static int FOREACH_RANGE_STATEMENT = 190; public final static int TRAITS_EXP = 191; public final static int COMMENT = 192; public final static int PRAGMA = 193; public final static int ARRAY_LENGTH_EXP = 194; public final static int DOT_TEMPLATE_EXP = 195; public final static int TYPE_REFERENCE = 196; public final static int TYPE_RETURN = 197; public final static int FILE_INIT_EXP = 198; public final static int LINE_INIT_EXP = 199; public final static int DEFAULT_INIT_EXP = 200; public final static int POSTBLIT_DECLARATION = 201; public final static int TEMPLATE_THIS_PARAMETER = 202; public final static int OVER_EXP = 203; public final static int STRUCT_LITERAL_EXP = 204; public final static int INDEX_EXP = 205; public final static int ALIAS_THIS = 206; // Defined here because MATCH and Match overlap on Windows public static class Match { public int count; // number of matches found public MATCH last; // match level of lastf public FuncDeclaration lastf; // last matching function we found public FuncDeclaration nextf; // current matching function public FuncDeclaration anyf; // pick a func, any func, to use for error recovery }; private final static class EXP_SOMETHING_INTERPRET extends Expression { public EXP_SOMETHING_INTERPRET() { super(null, 0, null); } @Override public int getNodeType() { return 0; } @Override public String toChars(SemanticContext context) { return null; } @Override protected void accept0(IASTVisitor visitor) { } } public final static Expression EXP_CANT_INTERPRET = new EXP_SOMETHING_INTERPRET(); public final static Expression EXP_CONTINUE_INTERPRET = new EXP_SOMETHING_INTERPRET(); public final static Expression EXP_BREAK_INTERPRET = new EXP_SOMETHING_INTERPRET(); public final static Expression EXP_GOTO_INTERPRET = new EXP_SOMETHING_INTERPRET(); public final static Expression EXP_VOID_INTERPRET = new EXP_SOMETHING_INTERPRET(); /*************************************************************************** * Helper function for ClassDeclaration::accessCheck() Returns: 0 no access * 1 access */ public static boolean accessCheckX(Dsymbol smember, Dsymbol sfunc, AggregateDeclaration dthis, AggregateDeclaration cdscope) { Assert.isNotNull(dthis); if (dthis.hasPrivateAccess(sfunc) || dthis.isFriendOf(cdscope)) { if (smember.toParent() == dthis) { return true; } else { ClassDeclaration cdthis = dthis.isClassDeclaration(); if (cdthis != null) { for (int i = 0; i < cdthis.baseclasses.size(); i++) { BaseClass b = cdthis.baseclasses.get(i); PROT access; access = b.base.getAccess(smember); if (access.level >= PROTprotected.level || accessCheckX(smember, sfunc, b.base, cdscope)) { return true; } } } } } else { if (smember.toParent() != dthis) { ClassDeclaration cdthis = dthis.isClassDeclaration(); if (cdthis != null) { for (int i = 0; i < cdthis.baseclasses.size(); i++) { BaseClass b = cdthis.baseclasses.get(i); if (accessCheckX(smember, sfunc, b.base, cdscope)) { return true; } } } } } return false; } public static void inferApplyArgTypes(TOK op, Arguments arguments, Expression aggr, SemanticContext context) { if (arguments == null || arguments.isEmpty()) { return; } /* * Return if no arguments need types. */ for (int u = 0; true; u++) { if (u == arguments.size()) { return; } Argument arg = arguments.get(u); if (arg.type == null) { break; } } AggregateDeclaration ad; FuncDeclaration fd; Argument arg = arguments.get(0); Type taggr = aggr.type; if (taggr == null) { return; } Type tab = taggr.toBasetype(context); switch (tab.ty) { case Tarray: case Tsarray: case Ttuple: if (arguments.size() == 2) { if (arg.type == null) { arg.type = Type.tsize_t; // key type } arg = arguments.get(1); } if (arg.type == null && tab.ty != Ttuple) { arg.type = tab.nextOf(); // value type } break; case Taarray: { TypeAArray taa = (TypeAArray) tab; if (arguments.size() == 2) { if (arg.type == null) { arg.type = taa.index; // key type } arg = arguments.get(1); } if (arg.type == null) { arg.type = taa.next; // value type } break; } case Tclass: { ad = ((TypeClass) tab).sym; // goto Laggr; /* * Look for an int opApply(int delegate(ref Type [, ...]) dg); * overload */ Dsymbol s = search_function(ad, (op == TOKforeach_reverse) ? Id.applyReverse : Id.apply, context); if (s != null) { fd = s.isFuncDeclaration(); if (fd != null) { inferApplyArgTypesX(fd, arguments, context); } } break; } case Tstruct: { ad = ((TypeStruct) tab).sym; // goto Laggr; /* * Look for an int opApply(int delegate(inout Type [, ...]) dg); * overload */ Dsymbol s = search_function(ad, (op == TOKforeach_reverse) ? Id.applyReverse : Id.apply, context); if (s != null) { fd = s.isFuncDeclaration(); if (fd != null) { inferApplyArgTypesX(fd, arguments, context); } } break; } case Tdelegate: { if (false && aggr.op == TOKdelegate) { DelegateExp de = (DelegateExp) aggr; fd = de.func.isFuncDeclaration(); if (fd != null) { inferApplyArgTypesX(fd, arguments, context); } } else { inferApplyArgTypesY((TypeFunction) tab.nextOf(), arguments, context); } break; } default: break; // ignore error, caught later } } public static void inferApplyArgTypesX(FuncDeclaration fstart, Arguments arguments, SemanticContext context) { Declaration d; Declaration next; for (d = fstart; d != null; d = next) { FuncDeclaration f; FuncAliasDeclaration fa; AliasDeclaration a; fa = d.isFuncAliasDeclaration(); if (fa != null) { inferApplyArgTypesX(fa.funcalias, arguments, context); next = fa.overnext; } else if ((f = d.isFuncDeclaration()) != null) { next = f.overnext; TypeFunction tf = (TypeFunction) f.type; if (inferApplyArgTypesY(tf, arguments, context)) { continue; } if (arguments.size() == 0) { return; } } else if ((a = d.isAliasDeclaration()) != null) { Dsymbol s = a.toAlias(context); next = s.isDeclaration(); if (next == a) { break; } if (next == fstart) { break; } } else { if (context.acceptsErrors()) { context.acceptProblem(Problem.newSemanticTypeError( IProblem.DivisionByZero, d)); } break; } } } public static boolean inferApplyArgTypesY(TypeFunction tf, Arguments arguments, SemanticContext context) { int nparams; Argument p; if (Argument.dim(tf.parameters, context) != 1) { return true; } p = Argument.getNth(tf.parameters, 0, context); if (p.type.ty != Tdelegate) { return true; } tf = (TypeFunction) p.type.nextOf(); Assert.isTrue(tf.ty == Tfunction); /* * We now have tf, the type of the delegate. Match it against the * arguments, filling in missing argument types. */ nparams = Argument.dim(tf.parameters, context); if (nparams == 0 || tf.varargs != 0) { return true; // not enough parameters } if (arguments.size() != nparams) { return true; // not enough parameters } for (int u = 0; u < nparams; u++) { Argument arg = arguments.get(u); Argument param = Argument.getNth(tf.parameters, u, context); if (arg.type != null) { if (!arg.type.equals(param.type)) { /* * Cannot resolve argument types. Indicate an error by * setting the number of arguments to 0. */ arguments.clear(); return false; } continue; } arg.type = param.type; } return false; } public static Expression resolveProperties(Scope sc, Expression e, SemanticContext context) { if (e.type != null) { Type t = e.type.toBasetype(context); boolean condition; if (context.isD2()) { condition = t.ty == Tfunction || e.op == TOK.TOKoverloadset; } else { condition = t.ty == Tfunction; } if (condition) { Expression e2 = e; e = new CallExp(e.filename, e.lineNumber, e); e.copySourceRange(e2); e = e.semantic(sc, context); } /* * Look for e being a lazy parameter; rewrite as delegate call */ else if (e.op == TOKvar) { VarExp ve = (VarExp) e; if ((ve.var.storage_class & STClazy) != 0) { e = new CallExp(e.filename, e.lineNumber, e); e = e.semantic(sc, context); } } else if (e.op == TOKdotexp) { if (context.acceptsErrors()) { context.acceptProblem(Problem.newSemanticTypeError( IProblem.SymbolHasNoValue, e, e.toChars(context))); } } } return e; } /****************************** * Perform canThrow() on an array of Expressions. * @param context TODO */ public static boolean arrayExpressionCanThrow(Expressions exps, SemanticContext context) { if (exps != null) { for (int i = 0; i < exps.size(); i++) { Expression e = (Expression) exps.get(i); if (e != null && e.canThrow(context)) return true; } } return false; } public static Dsymbol search_function(ScopeDsymbol ad, char[] funcid, SemanticContext context) { Dsymbol s; FuncDeclaration fd; TemplateDeclaration td; s = ad.search(null, 0, funcid, 0, context); if (s != null) { Dsymbol s2; s2 = s.toAlias(context); fd = s2.isFuncDeclaration(); if (fd != null && fd.type.ty == Tfunction) { return fd; } td = s2.isTemplateDeclaration(); if (td != null) { return td; } } return null; } public void accessCheck(Scope sc, Expression e, Declaration d, SemanticContext context) { accessCheck(sc, e, d, context, null); } public void accessCheck(Scope sc, Expression e, Declaration d, SemanticContext context, ASTDmdNode reference) { if (e == null) { if ((d.prot() == PROTprivate && d.getModule() != sc.module || d.prot() == PROTpackage && !hasPackageAccess(sc, d))) { if (context.acceptsErrors()) { context.acceptProblem(Problem.newSemanticTypeError(IProblem.SymbolIsNotAccessible, this, d.kind(), d .getModule().toChars(context), d.toChars(context), sc.module.toChars(context))); } } } else if (e.type.ty == Tclass) { // Do access check ClassDeclaration cd; cd = (((TypeClass) e.type).sym); if (e.op == TOKsuper) { ClassDeclaration cd2; cd2 = sc.func.toParent().isClassDeclaration(); if (cd2 != null) { cd = cd2; } } cd.accessCheck(sc, d, context, reference != null ? reference : e); } else if (e.type.ty == Tstruct) { // Do access check StructDeclaration cd; cd = (((TypeStruct) e.type).sym); cd.accessCheck(sc, d, context, reference != null ? reference : e); } } public static void argExpTypesToCBuffer(OutBuffer buf, Expressions arguments, HdrGenState hgs, SemanticContext context) { if (arguments != null) { OutBuffer argbuf = new OutBuffer(); for (int i = 0; i < arguments.size(); i++) { Expression arg = arguments.get(i); if (i != 0) { buf.writeByte(','); } argbuf.reset(); arg.type.toCBuffer2(argbuf, hgs, 0, context); buf.write(argbuf); } } } public static void argsToCBuffer(OutBuffer buf, Expressions arguments, HdrGenState hgs, SemanticContext context) { if (arguments != null) { for (int i = 0; i < arguments.size(); i++) { Expression arg = arguments.get(i); if (arg != null) { if (i != 0) { buf.writeByte(','); } expToCBuffer(buf, hgs, arg, PREC.PREC_assign, context); } } } } public static void arrayExpressionSemantic(Expressions exps, Scope sc, SemanticContext context) { if (exps != null) { for (int i = 0; i < exps.size(); i++) { Expression e = exps.get(i); e = e.semantic(sc, context); exps.set(i, e); } } } private Expression createTypeInfoArray(Scope sc, List<Expression> exps, int dim) { // TODO semantic return null; } public DYNCAST dyncast() { return DYNCAST.DYNCAST_OBJECT; } public static final void expToCBuffer(OutBuffer buf, HdrGenState hgs, Expression e, PREC pr, SemanticContext context) { expToCBuffer(buf, hgs, e, pr.ordinal(), context); } public static void expToCBuffer(OutBuffer buf, HdrGenState hgs, Expression e, int pr, SemanticContext context) { // SEMANTIC if (e == null || e.op == null) { return; } if (e.op.precedence.ordinal() < pr || (pr == PREC.PREC_rel.ordinal() && e.op.precedence.ordinal() == pr) ) { buf.writeByte('('); e.toCBuffer(buf, hgs, context); buf.writeByte(')'); } else { e.toCBuffer(buf, hgs, context); } } protected void fatal(SemanticContext context) { context.fatalWasSignaled = true; } public static boolean findCondition(HashtableOfCharArrayAndObject ids, char[] ident) { return ids != null && ids.containsKey(ident); } public static boolean findCondition(HashtableOfCharArrayAndObject ids, IdentifierExp ident) { if (ident == null || ident.ident == null) { return false; } return ids != null && ids.containsKey(ident.ident); } public void functionArguments(char[] filename, int lineNumber, Scope sc, TypeFunction tf, Expressions arguments, SemanticContext context) { int n; int done; Type tb; // Assert.isNotNull(arguments); int nargs = arguments != null ? arguments.size() : 0; int nparams = Argument.dim(tf.parameters, context); if (nargs > nparams && tf.varargs == 0) { if (context.acceptsErrors()) { context.acceptProblem(Problem.newSemanticTypeError( IProblem.ExpectedNumberArguments, this, String.valueOf(nparams), String.valueOf(nargs))); } } n = (nargs > nparams) ? nargs : nparams; // n = max(nargs, nparams) done = 0; for (int i = 0; i < n; i++) { Expression arg; if (i < nargs) { arg = arguments.get(i); } else { arg = null; } if (i < nparams) { Argument p = Argument.getNth(tf.parameters, i, context); boolean gotoL2 = false; if (arg == null) { if (p.defaultArg == null) { if (tf.varargs == 2 && i + 1 == nparams) { // goto L2; gotoL2 = true; } if (!gotoL2) { if (context.acceptsErrors()) { context.acceptProblem(Problem.newSemanticTypeError( IProblem.ExpectedNumberArguments, this, String.valueOf(nparams), String.valueOf(nargs))); } } break; } if (!gotoL2) { arg = p.defaultArg; if (context.isD2()) { if (arg.op == TOKdefault) { DefaultInitExp de = (DefaultInitExp) arg; arg = de.resolve(filename, lineNumber, sc, context); } else { arg = arg.copy(); } } else { arg = arg.copy(); } arguments.add(arg); nargs++; } } if ((tf.varargs == 2 && i + 1 == nparams) || gotoL2) { boolean gotoL1 = false; if (!gotoL2) { if (arg.implicitConvTo(p.type, context) != MATCH.MATCHnomatch) { if (nargs != nparams) { context.acceptProblem(Problem.newSemanticTypeError( IProblem.ExpectedNumberArguments, this, String.valueOf(nparams), String.valueOf(nargs))); } gotoL1 = true; // goto L1; } } if (!gotoL1 || gotoL2) { // L2: tb = p.type.toBasetype(context); Type tret = p.isLazyArray(context); switch (tb.ty) { case Tsarray: case Tarray: { // Create a static array variable v of type // arg.type IdentifierExp id = context.uniqueId("__arrayArg"); Type t = new TypeSArray(((TypeArray) tb).next, new IntegerExp(filename, lineNumber, nargs - i), context.encoder); t = t.semantic(filename, lineNumber, sc, context); VarDeclaration v = new VarDeclaration(filename, lineNumber, t, id, new VoidInitializer(filename, lineNumber)); v.semantic(sc, context); v.parent = sc.parent; Expression c = new DeclarationExp(filename, lineNumber, v); c.type = v.type; for (int u = i; u < nargs; u++) { Expression a = arguments.get(u); if (tret != null && !((TypeArray)tb).next.equals(a.type)) { a = a.toDelegate(sc, tret, context); } Expression e = new VarExp(filename, lineNumber, v); e = new IndexExp(filename, lineNumber, e, new IntegerExp(filename, lineNumber, u + 1 - nparams)); AssignExp ae = new AssignExp(filename, lineNumber, e, a); if (context.isD2()) { ae.op = TOK.TOKconstruct; } if (c != null) { c = new CommaExp(filename, lineNumber, c, ae); } else { c = ae; } } arg = new VarExp(filename, lineNumber, v); if (c != null) { arg = new CommaExp(filename, lineNumber, c, arg); } break; } case Tclass: { /* * Set arg to be: new Tclass(arg0, arg1, * ..., argn) */ Expressions args = new Expressions(nargs - 1); args.setDim(nargs - 1); for (int u = i; u < nargs; u++) { args.set(u - i, arguments.get(u)); } arg = new NewExp(filename, lineNumber, null, null, p.type, args); break; } default: if (arg == null) { if (context.acceptsErrors()) { context.acceptProblem(Problem.newSemanticTypeError(IProblem.NotEnoughArguments, this)); } return; } break; } arg = arg.semantic(sc, context); arguments.setDim(i + 1); done = 1; } } // L1: if (context.isD2()) { if (!((p.storageClass & STClazy) != 0 && p.type.ty == Tvoid)) { if (p.type != arg.type) { arg = arg.implicitCastTo(sc, p.type, context); arg = arg.optimize(WANTvalue, context); } } if ((p.storageClass & STCref) != 0) { arg = arg.toLvalue(sc, arg, context); } else if ((p.storageClass & STCout) != 0) { arg = arg.modifiableLvalue(sc, arg, context); } // Convert static arrays to pointers tb = arg.type.toBasetype(context); if (tb.ty == Tsarray) { arg = arg.checkToPointer(context); } if (tb.ty == Tstruct && 0 == (p.storageClass & (STCref | STCout))) { arg = callCpCtor(filename, lineNumber, sc, arg, context); } // Convert lazy argument to a delegate if ((p.storageClass & STClazy) != 0) { arg = arg.toDelegate(sc, p.type, context); } /* * Look for arguments that cannot 'escape' from the called * function. */ if (!tf.parameterEscapes(p, context)) { /* * Function literals can only appear once, so if this * appearance was scoped, there cannot be any others. */ if (arg.op == TOKfunction) { FuncExp fe = (FuncExp) arg; fe.fd.tookAddressOf = 0; } /* * For passing a delegate to a scoped parameter, this * doesn't count as taking the address of it. We only * worry about 'escaping' references to the function. */ else if (arg.op == TOKdelegate) { DelegateExp de = (DelegateExp) arg; if (de.e1.op == TOKvar) { VarExp ve = (VarExp) de.e1; FuncDeclaration f = ve.var.isFuncDeclaration(); if (f != null) { f.tookAddressOf--; // printf("tookAddressOf = %d\n", // f.tookAddressOf); } } } } } else { if (!((p.storageClass & STClazy) != 0 && p.type.ty == Tvoid)) { arg = arg.implicitCastTo(sc, p.type, context); } if ((p.storageClass & (STCout | STCref)) != 0) { // BUG: should check that argument to inout is type // 'invariant' // BUG: assignments to inout should also be type 'invariant' arg = arg.modifiableLvalue(sc, arg, context); // if (arg.op == TOKslice) // arg.error("cannot modify slice %s", arg.toChars()); // Don't have a way yet to do a pointer to a bit in array if (arg.op == TOKarray && arg.type.toBasetype(context).ty == Tbit) { if (context.acceptsErrors()) { context.acceptProblem(Problem.newSemanticTypeError( IProblem.CannotHaveOutOrInoutArgumentOfBitInArray, this)); } } } // Convert static arrays to pointers tb = arg.type.toBasetype(context); if (tb.ty == Tsarray) { arg = arg.checkToPointer(context); } } // Convert lazy argument to a delegate if ((p.storageClass & STClazy) != 0) { arg = arg.toDelegate(sc, p.type, context); } } else { // If not D linkage, do promotions if (tf.linkage != LINKd) { // Promote bytes, words, etc., to ints arg = arg.integralPromotions(sc, context); // Promote floats to doubles switch (arg.type.ty) { case Tfloat32: arg = arg.castTo(sc, Type.tfloat64, context); break; case Timaginary32: arg = arg.castTo(sc, Type.timaginary64, context); break; } } // Convert static arrays to dynamic arrays tb = arg.type.toBasetype(context); if (tb.ty == Tsarray) { TypeSArray ts = (TypeSArray) tb; Type ta = ts.next.arrayOf(context); if (ts.size(arg.filename, arg.lineNumber, context) == 0) { arg = new NullExp(arg.filename, arg.lineNumber); arg.type = ta; } else { arg = arg.castTo(sc, ta, context); } } if (tb.ty == Tstruct) { arg = callCpCtor(filename, lineNumber, sc, arg, context); } // Give error for overloaded function addresses if (arg.op == TOKsymoff) { SymOffExp se = (SymOffExp) arg; if (se.hasOverloads && null == se.var.isFuncDeclaration().isUnique( context)) { if (context.acceptsErrors()) { context.acceptProblem(Problem.newSemanticTypeError(IProblem.FunctionIsOverloaded, arg, arg.toChars(context))); } } } arg.rvalue(context); } arg = arg.optimize(WANTvalue, context); arguments.set(i, arg); if (done != 0) { break; } } // If D linkage and variadic, add _arguments[] as first argument if (tf.linkage == LINKd && tf.varargs == 1) { Expression e; e = createTypeInfoArray(sc, arguments.subList(nparams, arguments.size()), arguments.size() - nparams); arguments.add(0, e); } } private Expression callCpCtor(char[] filename, int lineNumber, Scope sc, Expression e, SemanticContext context) { Type tb = e.type.toBasetype(context); assert (tb.ty == Tstruct); StructDeclaration sd = ((TypeStruct) tb).sym; if (sd.cpctor != null) { /* * Create a variable tmp, and replace the argument e with: (tmp = * e),tmp and let AssignExp() handle the construction. This is not * the most efficent, ideally tmp would be constructed directly onto * the stack. */ IdentifierExp idtmp = context.uniqueId("__tmp"); VarDeclaration tmp = new VarDeclaration(filename, lineNumber, tb, idtmp, new ExpInitializer(null, 0, e)); Expression ae = new DeclarationExp(filename, lineNumber, tmp); e = new CommaExp(filename, lineNumber, ae, new VarExp(filename, lineNumber, tmp)); e = e.semantic(sc, context); } return e; } public abstract int getNodeType(); /*************************************************************************** * Determine if scope sc has package level access to s. */ public static boolean hasPackageAccess(Scope sc, Dsymbol s) { for (; s != null; s = s.parent) { if (s.isPackage() != null && s.isModule() == null) { break; } } if (s != null && s == sc.module.parent) { return true; } return false; } /** * Determine if 'this' is available. If it is, return the FuncDeclaration * that has it. */ public FuncDeclaration hasThis(Scope sc) { FuncDeclaration fd; FuncDeclaration fdthis; fdthis = sc.parent.isFuncDeclaration(); // Go upwards until we find the enclosing member function fd = fdthis; while (true) { if (fd == null) { // goto Lno; return null; // don't have 'this' available } if (!fd.isNested()) { break; } Dsymbol parent = fd.parent; while (parent != null) { TemplateInstance ti = parent.isTemplateInstance(); if (ti != null) { parent = ti.parent; } else { break; } } fd = fd.parent.isFuncDeclaration(); } if (fd.isThis() == null) { // goto Lno; return null; // don't have 'this' available } Assert.isNotNull(fd.vthis()); return fd; } public void preFunctionArguments(char[] filename, int lineNumber, Scope sc, Expressions exps, SemanticContext context) { if (exps != null) { expandTuples(exps, context); for (int i = 0; i < exps.size(); i++) { Expression arg = exps.get(i); if (arg.type == null) { if (context.acceptsWarnings()) { context.acceptProblem(Problem.newSemanticTypeWarning( IProblem.SymbolNotAnExpression, 0, arg.start, arg.length, arg.toChars(context))); } arg = new IntegerExp(arg.filename, arg.lineNumber, 0, Type.tint32); } arg = resolveProperties(sc, arg, context); exps.set(i, arg); } } } public boolean RealEquals(real_t r1, real_t r2) { return r1.equals(r2); } public String toChars(SemanticContext context) { throw new IllegalStateException( "This is an abstract method in DMD an should be implemented"); } protected String toPrettyChars(SemanticContext context) { throw new IllegalStateException("Problem reporting not implemented"); } public final int getElementType() { return getNodeType(); } /************************************* * If variable has a const initializer, * return that initializer. */ public static Expression expandVar(int result, VarDeclaration v, SemanticContext context) { Expression e = null; if (v != null && (v.isConst() || v.isInvariant(context) || (v.storage_class & STCmanifest) != 0)) { Type tb = v.type.toBasetype(context); if ((result & WANTinterpret) != 0 || (v.storage_class & STCmanifest) != 0 || (tb.ty != Tsarray && tb.ty != Tstruct)) { if (v.init != null) { if (v.inuse != 0) { // goto L1; return e; } Expression ei = v.init.toExpression(context); if (null == ei) { // goto L1; return e; } if (ei.op == TOKconstruct || ei.op == TOKblit) { AssignExp ae = (AssignExp) ei; ei = ae.e2; if (ei.isConst() != true && ei.op != TOKstring) { // goto L1; return e; } if (ei.type != v.type) { // goto L1; return e; } } if (v.scope != null) { v.inuse++; e = ei.syntaxCopy(context); e = e.semantic(v.scope, context); e = e.implicitCastTo(v.scope, v.type, context); v.scope = null; v.inuse--; } else if (null == ei.type) { // goto L1; return e; } else { // Should remove the copy() operation by // making all mods to expressions copy-on-write e = ei.copy(); } } else { // goto L1; return e; } if (e.type != v.type) { e = e.castTo(null, v.type, context); } e = e.optimize(result, context); } } //L1: return e; } /************************************* * If expression is a variable with a const initializer, * return that initializer. */ public static Expression fromConstInitializer(Expression e1, SemanticContext context) { return fromConstInitializer(0, e1, context); } public static Expression fromConstInitializer(int result, Expression e1, SemanticContext context) { if (context.isD2()) { Expression e = e1; if (e1.op == TOKvar) { VarExp ve = (VarExp) e1; VarDeclaration v = ve.var.isVarDeclaration(); e = expandVar(result, v, context); if (e != null) { if (e.type != e1.type) { // Type 'paint' operation e = e.copy(); e.type = e1.type; } } else e = e1; } return e; } else { if (e1.op == TOKvar) { VarExp ve = (VarExp) e1; VarDeclaration v = ve.var.isVarDeclaration(); if (v != null && v.isConst() && v.init() != null) { Expression ei = v.init().toExpression(context); if (ei != null && ei.type != null) { e1 = ei; } } } } return e1; } public static void arrayExpressionScanForNestedRef(Scope sc, Expressions a, SemanticContext context) { if (null != a) { for (int i = 0; i < a.size(); i++) { Expression e = a.get(i); if (null != e) { e.scanForNestedRef(sc, context); } } } } public static String mangle(Declaration sthis) { OutBuffer buf = new OutBuffer(); String id; Dsymbol s; s = sthis; do { if (s.ident != null) { FuncDeclaration fd = s.isFuncDeclaration(); if (s != sthis && fd != null) { id = mangle(fd); buf.prependstring(id); // goto L1; break; } else { id = s.ident.toChars(); int len = id.length(); buf.prependstring(id); buf.prependstring(len); } } else { buf.prependstring("0"); } s = s.parent; } while (s != null); // L1: FuncDeclaration fd = sthis.isFuncDeclaration(); if (fd != null && (fd.needThis() || fd.isNested())) { buf.writeByte(Type.needThisPrefix()); } if (sthis.type.deco != null) { buf.writestring(sthis.type.deco); } else { if (!fd.inferRetType()) { throw new IllegalStateException("assert (fd.inferRetType);"); } } id = buf.toChars(); buf.data = null; return id; } public static Dsymbol getDsymbol(ASTDmdNode oarg, SemanticContext context) { Dsymbol sa; Expression ea = isExpression(oarg); if (ea != null) { // Try to convert Expression to symbol if (ea.op == TOKvar) { sa = ((VarExp) ea).var; } else if (ea.op == TOKfunction) { sa = ((FuncExp) ea).fd; } else { sa = null; } } else { // Try to convert Type to symbol Type ta = isType(oarg); if (ta != null) { sa = ta.toDsymbol(null, context); } else { sa = isDsymbol(oarg); // if already a symbol } } return sa; } public static Type getType(ASTDmdNode o) { Type t = isType(o); if (null == t) { Expression e = isExpression(o); if (e != null) { t = e.type; } } return t; } public static Dsymbol isDsymbol(ASTDmdNode o) { //return dynamic_cast<Dsymbol >(o); if (null == o || o.dyncast() != DYNCAST_DSYMBOL) { return null; } return (Dsymbol) o; } public static Expression isExpression(ASTDmdNode o) { //return dynamic_cast<Expression >(o); if (null == o || o.dyncast() != DYNCAST_EXPRESSION) { return null; } return (Expression) o; } public static Tuple isTuple(ASTDmdNode o) { //return dynamic_cast<Tuple >(o); if (null == o || o.dyncast() != DYNCAST_TUPLE) { return null; } return (Tuple) o; } public static Type isType(ASTDmdNode o) { //return dynamic_cast<Type >(o); if (null == o || o.dyncast() != DYNCAST_TYPE) { return null; } return (Type) o; } public static Expression semanticLength(Scope sc, Type t, Expression exp, SemanticContext context) { if (t.ty == Ttuple) { ScopeDsymbol sym = new ArrayScopeSymbol(sc, (TypeTuple) t); sym.parent = sc.scopesym; sc = sc.push(sym); exp = exp.semantic(sc, context); sc.pop(); } else { exp = exp.semantic(sc, context); } return exp; } public static Expression semanticLength(Scope sc, TupleDeclaration s, Expression exp, SemanticContext context) { ScopeDsymbol sym = new ArrayScopeSymbol(sc, s); sym.parent = sc.scopesym; sc = sc.push(sym); exp = exp.semantic(sc, context); sc.pop(); return exp; } public static void overloadResolveX(Match m, FuncDeclaration fstart, Expression ethis, Expressions arguments, SemanticContext context) { Param2 p = new Param2(); p.m = m; p.ethis = ethis; p.arguments = arguments; overloadApply(fstart, fp2, p, context); } public static interface OverloadApply_fp { int call(Object param, FuncDeclaration f, SemanticContext context); } public final static OverloadApply_fp fp1 = new OverloadApply_fp() { public int call(Object param, FuncDeclaration f, SemanticContext context) { Param1 p = (Param1) param; Type t = p.t; if (t.equals(f.type)) { p.f = f; return 1; } if (context.isD2()) { /* * Allow covariant matches, if it's just a const conversion of * the return type */ if (t.ty == Tfunction) { TypeFunction tf = (TypeFunction) f.type; if (tf.covariant(t, context) == 1 && tf.nextOf().implicitConvTo(t.nextOf(), context) .ordinal() >= MATCHconst.ordinal()) { p.f = f; return 1; } } } return 0; } }; public final static OverloadApply_fp fp2 = new OverloadApply_fp() { public int call(Object param, FuncDeclaration f, SemanticContext context) { Param2 p = (Param2) param; Match m = p.m; Expressions arguments = p.arguments; MATCH match; if (f != m.lastf) // skip duplicates { TypeFunction tf; m.anyf = f; tf = (TypeFunction) f.type; match = tf.callMatch(f.needThis() ? p.ethis : null, arguments, context); if (match != MATCHnomatch) { if (match.ordinal() > m.last.ordinal()) { // goto LfIsBetter; m.last = match; m.lastf = f; m.count = 1; return 0; } if (match.ordinal() < m.last.ordinal()) { // goto LlastIsBetter; return 0; } /* See if one of the matches overrides the other. */ if (m.lastf.overrides(f, context)) { // goto LlastIsBetter; return 0; } else if (f.overrides(m.lastf, context)) { // goto LfIsBetter; m.last = match; m.lastf = f; m.count = 1; return 0; } /* Try to disambiguate using template-style partial ordering rules. * In essence, if f() and g() are ambiguous, if f() can call g(), * but g() cannot call f(), then pick f(). * This is because f() is "more specialized." */ { MATCH c1 = f.leastAsSpecialized(m.lastf, context); MATCH c2 = m.lastf.leastAsSpecialized(f, context); if (c1.ordinal() > c2.ordinal()) { // goto LfIsBetter; m.last = match; m.lastf = f; m.count = 1; return 0; } if (c1.ordinal() < c2.ordinal()) { // goto LlastIsBetter; return 0; } } // Lambiguous: m.nextf = f; m.count++; return 0; } } return 0; } }; /*************************************************** * Visit each overloaded function in turn, and call * (*fp)(param, f) on it. * Exit when no more, or (*fp)(param, f) returns 1. * Returns: * 0 continue * 1 done */ public static boolean overloadApply(FuncDeclaration fstart, OverloadApply_fp fp, Object param, SemanticContext context) { FuncDeclaration f; Declaration d; Declaration next; for (d = fstart; d != null; d = next) { FuncAliasDeclaration fa = d.isFuncAliasDeclaration(); if (fa != null) { if (overloadApply(fa.funcalias, fp, param, context)) { return false; } next = fa.overnext; } else { AliasDeclaration a = d.isAliasDeclaration(); if (a != null) { Dsymbol s = a.toAlias(context); next = s.isDeclaration(); if (next == a) { break; } if (next == fstart) { break; } } else { f = d.isFuncDeclaration(); if (null == f) { if (context.acceptsErrors()) { context.acceptProblem(Problem.newSemanticTypeError( IProblem.SymbolIsAliasedToAFunction, a, a.toChars(context))); } break; // BUG: should print error message? } if (fp.call(param, f, context) != 0) { return true; } next = f.overnext; } } } return false; } public static Expression interpret_aaLen(InterState istate, Expressions arguments, SemanticContext context) { if (null == arguments || arguments.size() != 1) { return null; } Expression earg = arguments.get(0); earg = earg.interpret(istate, context); if (earg == EXP_CANT_INTERPRET) { return null; } if (earg.op != TOKassocarrayliteral) { return null; } AssocArrayLiteralExp aae = (AssocArrayLiteralExp) earg; Expression e = new IntegerExp(aae.filename, aae.lineNumber, aae.keys.size(), Type.tsize_t); return e; } public static Expression interpret_aaKeys(InterState istate, Expressions arguments, SemanticContext context) { if (null == arguments || arguments.size() != 2) { return null; } Expression earg = arguments.get(0); earg = earg.interpret(istate, context); if (earg == EXP_CANT_INTERPRET) { return null; } if (earg.op != TOKassocarrayliteral) { return null; } AssocArrayLiteralExp aae = (AssocArrayLiteralExp) earg; Expression e = new ArrayLiteralExp(aae.filename, aae.lineNumber, aae.keys); return e; } public static Expression interpret_aaValues(InterState istate, Expressions arguments, SemanticContext context) { if (null == arguments || arguments.size() != 3) { return null; } Expression earg = arguments.get(0); earg = earg.interpret(istate, context); if (earg == EXP_CANT_INTERPRET) { return null; } if (earg.op != TOKassocarrayliteral) { return null; } AssocArrayLiteralExp aae = (AssocArrayLiteralExp) earg; Expression e = new ArrayLiteralExp(aae.filename, aae.lineNumber, aae.values); return e; } public void expandTuples(Expressions exps, SemanticContext context) { if (exps != null) { for (int i = 0; i < exps.size(); i++) { Expression arg = exps.get(i); if (null == arg) { continue; } // Look for tuple with 0 members if (arg.op == TOKtype) { TypeExp e = (TypeExp) arg; if (e.type.toBasetype(context).ty == Ttuple) { TypeTuple tt = (TypeTuple) e.type.toBasetype(context); if (null == tt.arguments || tt.arguments.size() == 0) { exps.remove(i); if (i == exps.size()) { return; } i--; continue; } } } // Inline expand all the tuples while (arg.op == TOKtuple) { TupleExp te = (TupleExp) arg; exps.remove(i); // remove arg exps.addAll(i, te.exps); // replace with tuple contents if (i == exps.size()) { return; // empty tuple, no more arguments } arg = exps.get(i); } } } } public static Expression expType(Type type, Expression e, SemanticContext context) { if (!same(type, e.type, context)) { e = e.copy(); e.type = type; } return e; } public static final Expression getVarExp(char[] filename, int lineNumber, InterState istate, Declaration d, SemanticContext context) { Expression e = EXP_CANT_INTERPRET; VarDeclaration v = d.isVarDeclaration(); SymbolDeclaration s = d.isSymbolDeclaration(); if (null != v) { boolean condition; if (context.isD2()) { condition = (v.isConst() || v.isInvariant(context)) && v.init != null && null == v.value; } else { condition = v.isConst() && null != v.init(); } if (condition) { e = v.init().toExpression(context); if (e != null && null == e.type) { e.type = v.type; } } else { e = v.value(); if (null == e) { if (context.acceptsErrors()) { context.acceptProblem(Problem.newSemanticTypeError( IProblem.VariableIsUsedBeforeInitialization, v, v.toChars(context))); } } else if (e != EXP_CANT_INTERPRET) { e = e.interpret(istate, context); } } if (null == e) { e = EXP_CANT_INTERPRET; } } else if (null != s) { if (s.dsym().toInitializer() == s.sym()) { Expressions exps = new Expressions(0); e = new StructLiteralExp(null, 0, s.dsym(), exps); e = e.semantic(null, context); } } return e; } public static void ObjectToCBuffer(OutBuffer buf, HdrGenState hgs, ASTDmdNode oarg, SemanticContext context) { Type t = isType(oarg); Expression e = isExpression(oarg); Dsymbol s = isDsymbol(oarg); Tuple v = isTuple(oarg); if (null != t) { t.toCBuffer(buf, null, hgs, context); } else if (null != e) { e.toCBuffer(buf, hgs, context); } else if (null != s) { String p = null != s.ident ? s.ident.toChars() : s.toChars(context); buf.writestring(p); } else if (null != v) { Objects args = v.objects; for (int i = 0; i < args.size(); i++) { if (i > 0) { buf.writeByte(','); } ASTDmdNode o = args.get(i); ObjectToCBuffer(buf, hgs, o, context); } } else if (null == oarg) { buf.writestring("null"); } else { assert (false); } } public static void templateResolve(Match m, TemplateDeclaration td, Scope sc, char[] filename, int lineNumber, Objects targsi, Expression ethis, Expressions arguments, SemanticContext context) { FuncDeclaration fd; assert (td != null); fd = td.deduceFunctionTemplate(sc, filename, lineNumber, targsi, ethis, arguments, context); if (null == fd) { return; } m.anyf = fd; if (m.last.ordinal() >= MATCHexact.ordinal()) { m.nextf = fd; m.count++; } else { m.last = MATCHexact; m.lastf = fd; m.count = 1; } } public static boolean match(ASTDmdNode o1, ASTDmdNode o2, TemplateDeclaration tempdecl, Scope sc, SemanticContext context) { Type t1 = isType(o1); Type t2 = isType(o2); Expression e1 = isExpression(o1); Expression e2 = isExpression(o2); Dsymbol s1 = isDsymbol(o1); Dsymbol s2 = isDsymbol(o2); Tuple v1 = isTuple(o1); Tuple v2 = isTuple(o2); /* A proper implementation of the various equals() overrides * should make it possible to just do o1.equals(o2), but * we'll do that another day. */ if (t1 != null) { /* if t1 is an instance of ti, then give error * about recursive expansions. */ Dsymbol s = t1.toDsymbol(sc, context); if (s != null && s.parent != null) { TemplateInstance ti1 = s.parent.isTemplateInstance(); if (ti1 != null && ti1.tempdecl == tempdecl) { for (Scope sc1 = sc; sc1 != null; sc1 = sc1.enclosing) { if (sc1.scopesym == ti1) { if (context.acceptsErrors()) { context.acceptProblem(Problem.newSemanticTypeError( IProblem.RecursiveTemplateExpansionForTemplateArgument, t1, t1.toChars(context))); } return true; // fake a match } } } } if (null == t2 || !t1.equals(t2)) { // goto Lnomatch; return false; } } else if (e1 != null) { if (null == e2) { // goto Lnomatch; return false; } if (!e1.equals(e2, context)) { // goto Lnomatch; return false; } } else if (s1 != null) { if (null == s2 || !s1.equals(s2) || s1.parent != s2.parent) { // goto Lnomatch; return false; } if (context.isD2()) { VarDeclaration _v1 = s1.isVarDeclaration(); VarDeclaration _v2 = s2.isVarDeclaration(); if (_v1 != null && _v2 != null && (_v1.storage_class & _v2.storage_class & STCmanifest) != 0) { ExpInitializer ei1 = _v1.init.isExpInitializer(); ExpInitializer ei2 = _v2.init.isExpInitializer(); if (ei1 != null && ei2 != null && !ei1.exp.equals(ei2.exp)) { // goto Lnomatch; return false; } } } } else if (v1 != null) { if (null == v2) { // goto Lnomatch; return false; } if (size(v1.objects) != size(v2.objects)) { // goto Lnomatch; return false; } for (int i = 0; i < size(v1.objects); i++) { if (!match(v1.objects.get(i), v2.objects.get(i), tempdecl, sc, context)) { // goto Lnomatch; return false; } } } return true; // match // Lnomatch: // return 0; // nomatch; } /** * Returns the size of a list which may ne <code>null</code>. * In such case, 0 is returned. */ public static int size(List list) { return list == null ? 0 : list.size(); } /** * If an error has to be marked in this node, returns * the start position to mark this error. For example, * if this is a ClassDeclaration, it returns the position * where it's name starts. If this is an anonymous EnumDeclaration, * the start of the "enum" keyword is returned. * * By default, the start of this node is returned. Subclasses * may override. * * The length can be obtained with {@link #getErrorLength()}. */ public int getErrorStart() { return start; } /** * By default, the length of this node is returned. Subclasses * may override. * * @see #getErrorStart() */ public int getErrorLength() { return length; } public final void copySourceRange(ASTDmdNode other) { this.start = other.start; this.length = other.length; } public final void copySourceRange(ASTDmdNode first, ASTDmdNode last) { int newLength = last.start + last.length - first.start; if (newLength <= 0) { return; } this.start = first.start; this.length = last.start + last.length - first.start; } public void copySourceRange(List<? extends ASTDmdNode> a) { if (a.isEmpty()) { return; } else { copySourceRange(a.get(0), a.get(a.size() - 1)); } } protected char[] getFQN(Identifiers packages, IdentifierExp id) { // TODO Descent char[] optimize, don't use StringBuilder StringBuilder sb = new StringBuilder(); if (packages != null) { for(int i = 0; i < packages.size(); i++) { sb.append(packages.get(i).toCharArray()); sb.append('.'); } } if (id != null) { sb.append(id.toCharArray()); } char[] ret = new char[sb.length()]; sb.getChars(0, sb.length(), ret, 0); return ret; } public static void realToMangleBuffer(OutBuffer buf, real_t value) { /* Rely on %A to get portable mangling. * Must munge result to get only identifier characters. * * Possible values from %A => mangled result * NAN => NAN * -INF => NINF * INF => INF * -0X1.1BC18BA997B95P+79 => N11BC18BA997B95P79 * 0X1.9P+2 => 19P2 */ if (value.isNaN()) { buf.writestring("NAN"); // no -NAN bugs } else { char[] buffer = value.toString().toCharArray(); for (int i = 0; i < buffer.length; i++) { char c = buffer[i]; switch (c) { case '-': buf.writeByte('N'); break; case '+': case 'X': case '.': break; case '0': if (i < 2) { break; // skip leading 0X } default: buf.writeByte(c); break; } } } } public int getLineNumber() { return -1; } public void setLineNumber(int lineNumber) { // empty } public static final boolean equals(IdentifierExp e1, IdentifierExp e2) { if (e1 == null && e2 == null) { return true; } if ((e1 == null) != (e2 == null)) { return false; } return equals(e1.ident, e2.ident); } public static final boolean equals(char[] e1, char[] e2) { return CharOperation.equals(e1, e2); } public static final boolean equals(char[] e1, IdentifierExp e2) { if (e2 == null) { return false; } return CharOperation.equals(e1, e2.ident); } public static final boolean equals(IdentifierExp e1, char[] e2) { if (e1 == null) { return false; } return CharOperation.equals(e1.ident, e2); } public static final boolean same(Type t1, Type t2, SemanticContext context) { if (t1 == null && t2 == null) { return true; } if ((t1 == null) != (t2 == null)) { return false; } return t1.same(t2); } public static int templateIdentifierLookup(IdentifierExp id, TemplateParameters parameters) { for (int i = 0; i < size(parameters); i++) { TemplateParameter tp = parameters.get(i); if (equals(tp.ident, id)) { return i; } } return -1; } public static int templateParameterLookup(Type tparam, TemplateParameters parameters) { if (tparam.ty != Tident) { throw new IllegalStateException("assert(tparam.ty == Tident);"); } TypeIdentifier tident = (TypeIdentifier) tparam; if (size(tident.idents) == 0) { return templateIdentifierLookup(tident.ident, parameters); } return -1; } public static Expression eval_builtin(BUILTIN builtin, Expressions arguments, SemanticContext context) { if (size(arguments) == 0) { return null; } Expression arg0 = arguments.get(0); Expression e = null; switch (builtin) { case BUILTINsin: if (arg0.op == TOKfloat64) { e = new RealExp(null, 0, arg0.toReal(context).sin(), context.isD2() ? arg0.type : Type.tfloat80); } break; case BUILTINcos: if (arg0.op == TOKfloat64) { e = new RealExp(null, 0, arg0.toReal(context).cos(), context.isD2() ? arg0.type : Type.tfloat80); } break; case BUILTINtan: if (arg0.op == TOKfloat64) { e = new RealExp(null, 0, arg0.toReal(context).tan(), context.isD2() ? arg0.type : Type.tfloat80); } break; case BUILTINsqrt: if (arg0.op == TOKfloat64) { e = new RealExp(null, 0, arg0.toReal(context).sqrt(), context.isD2() ? arg0.type : Type.tfloat80); } break; case BUILTINfabs: if (arg0.op == TOKfloat64) { e = new RealExp(null, 0, arg0.toReal(context).abs(), context.isD2() ? arg0.type : Type.tfloat80); } break; } return e; } /************************************************************* * Now that we have the right function f, we need to get the * right 'this' pointer if f is in an outer class, but our * existing 'this' pointer is in an inner class. * This code is analogous to that used for variables * in DotVarExp::semantic(). */ public static Expression getRightThis(char[] filename, int lineNumber, Scope sc, AggregateDeclaration ad, Expression e1, Declaration var, SemanticContext context) { boolean gotoL1 = true; L1: while(gotoL1) { gotoL1 = false; Type t = e1.type.toBasetype(context); if (ad != null && !(t.ty == Tpointer && t.nextOf().ty == Tstruct && ((TypeStruct) t.nextOf()).sym == ad) && !(t.ty == Tstruct && ((TypeStruct) t).sym == ad)) { ClassDeclaration cd = ad.isClassDeclaration(); ClassDeclaration tcd = t.isClassHandle(); if (null == cd || null == tcd || !(tcd == cd || cd.isBaseOf(tcd, null, context))) { if (tcd != null && tcd.isNested()) { // Try again with outer scope e1 = new DotVarExp(filename, lineNumber, e1, tcd.vthis); e1.type = tcd.vthis.type; // e1 = e1.semantic(sc, context); // Skip over nested functions, and get the enclosing // class type. int n = 0; Dsymbol s; for(s = tcd.toParent(); s != null && s.isFuncDeclaration() != null; s = s.toParent()) { FuncDeclaration f = s.isFuncDeclaration(); if (f.vthis != null) { n++; e1 = new VarExp(filename, lineNumber, f.vthis); } s = s.toParent(); } if (s != null && s.isClassDeclaration() != null) { e1.type = s.isClassDeclaration().type; if (n > 1) { e1 = e1.semantic(sc, context); } } else { e1 = e1.semantic(sc, context); } // goto L1; gotoL1 = true; continue L1; } if (context.acceptsErrors()) { context.acceptProblem(Problem.newSemanticTypeError(IProblem.ThisForSymbolNeedsToBeType, var, var .toChars(context), ad.toChars(context), t.toChars(context))); } } } } return e1; } public void errorOnModifier(int problemId, TOK tok, SemanticContext context) { boolean reported = false; List<Modifier> modifiers; if ((modifiers = context.Module_rootModule.getModifiers(this)) != null) { for (Modifier modifier : modifiers) { if (modifier.tok == tok) { if (context.acceptsErrors()) { context.acceptProblem(Problem.newSemanticTypeError( problemId, modifier)); } reported = true; } } } List<Modifier> extraModifiers; if ((extraModifiers = context.getExtraModifiers(this)) != null) { for (Modifier modifier : extraModifiers) { if (modifier.tok == tok) { if (context.acceptsErrors()) { context.acceptProblem(Problem.newSemanticTypeError( problemId, modifier)); } reported = true; } } } if (!reported) { if (context.acceptsErrors()) { context.acceptProblem(Problem.newSemanticTypeErrorLoc( problemId, this)); } } } /************************************** * Combine types. * Output: * *pt merged type, if *pt is not NULL * *pe1 rewritten e1 * *pe2 rewritten e2 * Returns: * !=0 success * 0 failed */ public static boolean typeMerge(Scope sc, Expression e, Type[] pt, Expression[] pe1, Expression[] pe2, SemanticContext context) { Expression e1 = pe1[0].integralPromotions(sc, context); Expression e2 = pe2[0].integralPromotions(sc, context); Type t1 = e1.type; Type t2 = e2.type; assert (t1 != null); Type t = t1; assert (t2 != null); Type t1b = t1.toBasetype(context); Type t2b = t2.toBasetype(context); TY ty = (TY) Type.impcnvResult[t1b.ty.ordinal()][t2b.ty.ordinal()]; if (ty != Terror) { TY ty1; TY ty2; ty1 = (TY) Type.impcnvType1[t1b.ty.ordinal()][t2b.ty.ordinal()]; ty2 = (TY) Type.impcnvType2[t1b.ty.ordinal()][t2b.ty.ordinal()]; if (t1b.ty == ty1) // if no promotions { if (t1 == t2) { t = t1; // goto Lret; return typeMerge_Lret(pt, pe1, pe2, t2b, e1, e2); } if (t1b == t2b) { t = t1b; // goto Lret; return typeMerge_Lret(pt, pe1, pe2, t2b, e1, e2); } } t = Type.basic[ty.ordinal()]; t1 = Type.basic[ty1.ordinal()]; t2 = Type.basic[ty2.ordinal()]; e1 = e1.castTo(sc, t1, context); e2 = e2.castTo(sc, t2, context); // goto Lret; return typeMerge_Lret(pt, pe1, pe2, t2b, e1, e2); } t1 = t1b; t2 = t2b; boolean repeat = true; Lagain: while (repeat) { repeat = false; if (same(t1, t2, context)) { } else if (t1.ty == Tpointer && t2.ty == Tpointer) { // Bring pointers to compatible type Type t1n = t1.nextOf(); Type t2n = t2.nextOf(); if (same(t1n, t2n, context)) ; else if (t1n.ty == Tvoid) // pointers to void are always // compatible t = t2; else if (t2n.ty == Tvoid) ; else if (t1n.mod != t2n.mod) { t1 = t1n.mutableOf(context).constOf(context).pointerTo( context); t2 = t2n.mutableOf(context).constOf(context).pointerTo( context); t = t1; // goto Lagain; repeat = true; continue Lagain; } else if (t1n.ty == Tclass && t2n.ty == Tclass) { ClassDeclaration cd1 = t1n.isClassHandle(); ClassDeclaration cd2 = t2n.isClassHandle(); int[] offset = { 0 }; if (cd1.isBaseOf(cd2, offset, context)) { if (offset[0] != 0) e2 = e2.castTo(sc, t, context); } else if (cd2.isBaseOf(cd1, offset, context)) { t = t2; if (offset[0] != 0) e1 = e1.castTo(sc, t, context); } else { // goto Lincompatible; return false; } } else { // goto Lincompatible; return false; } } else if ((t1.ty == Tsarray || t1.ty == Tarray) && e2.op == TOKnull && t2.ty == Tpointer && t2.nextOf().ty == Tvoid) { /* * (T[n] op void) (T[] op void) */ // goto Lx1; return typeMerge_Lx1(pt, pe1, pe2, t2b, e1, e2, t1b, sc, context); } else if ((t2.ty == Tsarray || t2.ty == Tarray) && e1.op == TOKnull && t1.ty == Tpointer && t1.nextOf().ty == Tvoid) { /* * (void op T[n]) (void op T[]) */ // goto Lx2; return typeMerge_Lx2(pt, pe1, pe2, t1b, e1, e2, t2b, sc, context); } else if ((t1.ty == Tsarray || t1.ty == Tarray) && t1.implicitConvTo(t2, context) != MATCHnomatch) { // goto Lt2; return typeMerge_Lt2(pt, pe1, pe2, t1b, e1, e2, sc, t2b, context); } else if ((t2.ty == Tsarray || t2.ty == Tarray) && t2.implicitConvTo(t1, context) != MATCHnomatch) { // goto Lt1; return typeMerge_Lt1(pt, pe1, pe2, t2b, e1, e2, sc, t1b, context); } /* * If one is mutable and the other invariant, then retry with both * of them as const */ else if ((t1.ty == Tsarray || t1.ty == Tarray || t1.ty == Tpointer) && (t2.ty == Tsarray || t2.ty == Tarray || t2.ty == Tpointer) && t1.nextOf().mod != t2.nextOf().mod) { if (t1.ty == Tpointer) t1 = t1.nextOf().mutableOf(context).constOf(context) .pointerTo(context); else t1 = t1.nextOf().mutableOf(context).constOf(context) .arrayOf(context); if (t2.ty == Tpointer) t2 = t2.nextOf().mutableOf(context).constOf(context) .pointerTo(context); else t2 = t2.nextOf().mutableOf(context).constOf(context) .arrayOf(context); t = t1; // goto Lagain; repeat = true; continue Lagain; } else if (t1.ty == Tclass || t2.ty == Tclass) { while (true) { int i1 = e2.implicitConvTo(t1, context).ordinal(); int i2 = e1.implicitConvTo(t2, context).ordinal(); if (i1 != 0 && i2 != 0) { // We have the case of class vs. void*, so pick class if (t1.ty == Tpointer) i1 = 0; else if (t2.ty == Tpointer) i2 = 0; } if (i2 != 0) { // goto Lt2; return typeMerge_Lt2(pt, pe1, pe2, t1b, e1, e2, sc, t2b, context); } else if (i1 != 0) { // goto Lt1; return typeMerge_Lt1(pt, pe1, pe2, t2b, e1, e2, sc, t1b, context); } else if (t1.ty == Tclass && t2.ty == Tclass) { TypeClass tc1 = (TypeClass) t1; TypeClass tc2 = (TypeClass) t2; /* * Pick 'tightest' type */ ClassDeclaration cd1 = tc1.sym.baseClass; ClassDeclaration cd2 = tc2.sym.baseClass; if (cd1 != null && cd2 != null) { t1 = cd1.type; t2 = cd2.type; } else if (cd1 != null) t1 = cd1.type; else if (cd2 != null) t2 = cd2.type; else { // goto Lincompatible; return false; } } else { // goto Lincompatible; return false; } } } else if (t1.ty == Tstruct && t2.ty == Tstruct) { if (((TypeStruct) t1).sym != ((TypeStruct) t2).sym) { // goto Lincompatible; return false; } } else if ((e1.op == TOKstring || e1.op == TOKnull) && e1.implicitConvTo(t2, context) != MATCHnomatch) { // goto Lt2; return typeMerge_Lt2(pt, pe1, pe2, t1b, e1, e2, sc, t2b, context); } else if ((e2.op == TOKstring || e2.op == TOKnull) && e2.implicitConvTo(t1, context) != MATCHnomatch) { // goto Lt1; return typeMerge_Lt1(pt, pe1, pe2, t2b, e1, e2, sc, t1b, context); } else if (t1.ty == Tsarray && t2.ty == Tsarray && e2.implicitConvTo(t1.nextOf().arrayOf(context), context) != MATCHnomatch) { // Lx1: return typeMerge_Lx1(pt, pe1, pe2, t2b, e1, e2, t1b, sc, context); } else if (t1.ty == Tsarray && t2.ty == Tsarray && e1.implicitConvTo(t2.nextOf().arrayOf(context), context) != MATCHnomatch) { // Lx2: return typeMerge_Lx2(pt, pe1, pe2, t1b, e1, e2, t2b, sc, context); } else if (t1.isintegral() && t2.isintegral()) { throw new IllegalStateException(); } else if (e1.op == TOKslice && t1.ty == Tarray && e2.implicitConvTo(t1.nextOf(), context) != MATCHnomatch) { // T[] op T e2 = e2.castTo(sc, t1.nextOf(), context); t = t1.nextOf().arrayOf(context); } else if (e2.op == TOKslice && t2.ty == Tarray && e1.implicitConvTo(t2.nextOf(), context) != MATCHnomatch) { // T op T[] e1 = e1.castTo(sc, t2.nextOf(), context); t = t2.nextOf().arrayOf(context); e1 = e1.optimize(WANTvalue, context); if (e != null && e.isCommutative() && e1.isConst()) { /* * Swap operands to minimize number of functions generated */ Expression tmp = e1; e1 = e2; e2 = tmp; } } else { // Lincompatible: return false; } } return typeMerge_Lret(pt, pe1, pe2, t2b, e1, e2); } private static boolean typeMerge_Lt1(Type[] pt, Expression[] pe1, Expression[] pe2, Type t, Expression e1, Expression e2, Scope sc, Type t1, SemanticContext context) { e2 = e2.castTo(sc, t1, context); t = t1; return typeMerge_Lret(pt, pe1, pe2, t, e1, e2); } private static boolean typeMerge_Lt2(Type[] pt, Expression[] pe1, Expression[] pe2, Type t, Expression e1, Expression e2, Scope sc, Type t2, SemanticContext context) { e1 = e1.castTo(sc, t2, context); t = t2; return typeMerge_Lret(pt, pe1, pe2, t, e1, e2); } private static boolean typeMerge_Lx1(Type[] pt, Expression[] pe1, Expression[] pe2, Type t, Expression e1, Expression e2, Type t1, Scope sc, SemanticContext context) { t = t1.nextOf().arrayOf(context); e1 = e1.castTo(sc, t, context); e2 = e2.castTo(sc, t, context); return typeMerge_Lret(pt, pe1, pe2, t, e1, e2); } private static boolean typeMerge_Lx2(Type[] pt, Expression[] pe1, Expression[] pe2, Type t, Expression e1, Expression e2, Type t2, Scope sc, SemanticContext context) { t = t2.nextOf().arrayOf(context); e1 = e1.castTo(sc, t, context); e2 = e2.castTo(sc, t, context); return typeMerge_Lret(pt, pe1, pe2, t, e1, e2); } private static boolean typeMerge_Lret(Type[] pt, Expression[] pe1, Expression[] pe2, Type t, Expression e1, Expression e2) { - if (pt[0] != null) { + if (pt[0] == null) { pt[0] = t; } pe1[0] = e1; pe2[0] = e2; return true; } /*********************************** * See if both types are arrays that can be compared * for equality. Return !=0 if so. * If they are arrays, but incompatible, issue error. * This is to enable comparing things like an immutable * array with a mutable one. */ public boolean arrayTypeCompatible(char[] filename, int lineNumber, Type t1, Type t2, SemanticContext context) { t1 = t1.toBasetype(context); t2 = t2.toBasetype(context); if ((t1.ty == Tarray || t1.ty == Tsarray || t1.ty == Tpointer) && (t2.ty == Tarray || t2.ty == Tsarray || t2.ty == Tpointer)) { if (t1.nextOf().implicitConvTo(t2.nextOf(), context).ordinal() < MATCHconst .ordinal() && t2.nextOf().implicitConvTo(t1.nextOf(), context) .ordinal() < MATCHconst.ordinal() && (t1.nextOf().ty != Tvoid && t2.nextOf().ty != Tvoid)) { if (context.acceptsErrors()) { // SEMANTIC missing ok location context.acceptProblem(Problem.newSemanticTypeError(IProblem.ArrayEqualityComparisonTypeMismatch, t1, t1.toChars(context), t2.toChars(context))); } } return true; } return false; } /******************************************* * Given a symbol that could be either a FuncDeclaration or * a function template, resolve it to a function symbol. * sc instantiation scope * loc instantiation location * targsi initial list of template arguments * ethis if !NULL, the 'this' pointer argument * fargs arguments to function * flags 1: do not issue error message on no match, just return NULL */ public static FuncDeclaration resolveFuncCall(Scope sc, char[] filename, int lineNumber, Dsymbol s, Objects tiargs, Expression ethis, Expressions arguments, int flags, SemanticContext context) { if (null == s) return null; // no match FuncDeclaration f = s.isFuncDeclaration(); if (f != null) f = f.overloadResolve(filename, lineNumber, ethis, arguments, context, ethis); // SEMANTIC ethis is caller? else { TemplateDeclaration td = s.isTemplateDeclaration(); f = td.deduceFunctionTemplate(sc, filename, lineNumber, tiargs, null, arguments, flags, context); } return f; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } }
true
false
null
null
diff --git a/restconfig/src/main/java/org/geoserver/catalog/rest/FeatureTypeListResource.java b/restconfig/src/main/java/org/geoserver/catalog/rest/FeatureTypeListResource.java index 798db4d11..f69f6791d 100644 --- a/restconfig/src/main/java/org/geoserver/catalog/rest/FeatureTypeListResource.java +++ b/restconfig/src/main/java/org/geoserver/catalog/rest/FeatureTypeListResource.java @@ -1,38 +1,38 @@ /* Copyright (c) 2001 - 2009 TOPP - www.openplans.org. All rights reserved. * This code is licensed under the GPL 2.0 license, availible at the root * application directory. */ package org.geoserver.catalog.rest; import java.util.List; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.DataStoreInfo; import org.geoserver.catalog.FeatureTypeInfo; import org.geoserver.catalog.NamespaceInfo; import org.restlet.Context; import org.restlet.data.Request; import org.restlet.data.Response; public class FeatureTypeListResource extends AbstractCatalogListResource { public FeatureTypeListResource(Context context, Request request, Response response, Catalog catalog) { super(context, request, response, FeatureTypeInfo.class, catalog); } @Override protected List handleListGet() throws Exception { String ws = getAttribute( "workspace" ); String ds = getAttribute("datastore"); if ( ds != null ) { - DataStoreInfo dataStore = catalog.getDataStoreByName( ds ); + DataStoreInfo dataStore = catalog.getDataStoreByName(ws, ds); return catalog.getFeatureTypesByDataStore(dataStore); } NamespaceInfo ns = catalog.getNamespaceByPrefix( ws ); return catalog.getFeatureTypesByNamespace( ns ); } }
true
true
protected List handleListGet() throws Exception { String ws = getAttribute( "workspace" ); String ds = getAttribute("datastore"); if ( ds != null ) { DataStoreInfo dataStore = catalog.getDataStoreByName( ds ); return catalog.getFeatureTypesByDataStore(dataStore); } NamespaceInfo ns = catalog.getNamespaceByPrefix( ws ); return catalog.getFeatureTypesByNamespace( ns ); }
protected List handleListGet() throws Exception { String ws = getAttribute( "workspace" ); String ds = getAttribute("datastore"); if ( ds != null ) { DataStoreInfo dataStore = catalog.getDataStoreByName(ws, ds); return catalog.getFeatureTypesByDataStore(dataStore); } NamespaceInfo ns = catalog.getNamespaceByPrefix( ws ); return catalog.getFeatureTypesByNamespace( ns ); }
diff --git a/fingerpaint/src/nl/tue/fingerpaint/client/model/drawingtool/CircleDrawingTool.java b/fingerpaint/src/nl/tue/fingerpaint/client/model/drawingtool/CircleDrawingTool.java index 2245d23..d97f0f8 100644 --- a/fingerpaint/src/nl/tue/fingerpaint/client/model/drawingtool/CircleDrawingTool.java +++ b/fingerpaint/src/nl/tue/fingerpaint/client/model/drawingtool/CircleDrawingTool.java @@ -1,76 +1,76 @@ package nl.tue.fingerpaint.client.model.drawingtool; import nl.tue.fingerpaint.shared.utils.Colour; import com.google.gwt.canvas.dom.client.CanvasPixelArray; import com.google.gwt.canvas.dom.client.ImageData; /** * A {@code CircleDrawingTool} is a {@link DrawingTool} with a circular shape. * Users can thus use this drawing tool to draw circles on the canvas. * * @author Group Fingerpaint */ public class CircleDrawingTool extends DrawingTool { // --Constructors------------------------------------------- /** * Constructs a circle drawing tool with radius r * * @param r * The radius of the drawing tool */ public CircleDrawingTool(int r) { super(r); } // --Public methods for general use-------------------------- /** * Returns an ImageData object representing the circle drawing tool. * * @param img * The ImageData object to draw the drawing tool on * @param colour * The colour to create the drawing tool with */ @Override public ImageData getTool(ImageData img, Colour colour) { int width = img.getWidth(); - int radius = (int) Math.floor(width / 2.0); + int radius = (width - 1) / 2; int x = radius; int y = radius; CanvasPixelArray data = img.getData(); int col = colour.getRed(); int i = 0, j = radius; int index; while (i <= j) { for (int w = x - j; w <= x + j; w++) { index = ((y + i) * width + w) * 4; fillPixel(data, index, col, 255); } for (int w = x - j; w <= x + j; w++) { index = ((y - i) * width + w) * 4; fillPixel(data, index, col, 255); } for (int w = x - i; w <= x + i; w++) { index = ((y + j) * width + w) * 4; fillPixel(data, index, col, 255); } for (int w = x - i; w <= x + i; w++) { index = ((y - j) * width + w) * 4; fillPixel(data, index, col, 255); } i++; j = (int) (Math.sqrt(radius * radius - i * i) + 0.5); } return img; } } \ No newline at end of file
true
false
null
null
diff --git a/eclipse/plugins/net.sf.orc2hdl/src/net/sf/orc2hdl/design/DesignActorVisitor.java b/eclipse/plugins/net.sf.orc2hdl/src/net/sf/orc2hdl/design/DesignActorVisitor.java index f4c0f89..fffff37 100644 --- a/eclipse/plugins/net.sf.orc2hdl/src/net/sf/orc2hdl/design/DesignActorVisitor.java +++ b/eclipse/plugins/net.sf.orc2hdl/src/net/sf/orc2hdl/design/DesignActorVisitor.java @@ -1,977 +1,980 @@ /* * Copyright (c) 2012, Ecole Polytechnique Fédérale de Lausanne * 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 Polytechnique Fédérale de Lausanne 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 COPYRIGHT HOLDERS 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 COPYRIGHT OWNER OR 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 net.sf.orc2hdl.design; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.sf.openforge.frontend.slim.builder.ActionIOHandler; import net.sf.openforge.frontend.slim.builder.ActionIOHandler.FifoIOHandler; import net.sf.openforge.frontend.slim.builder.ActionIOHandler.NativeIOHandler; import net.sf.openforge.lim.And; import net.sf.openforge.lim.Block; import net.sf.openforge.lim.Branch; import net.sf.openforge.lim.Bus; import net.sf.openforge.lim.Call; import net.sf.openforge.lim.ClockDependency; import net.sf.openforge.lim.Component; import net.sf.openforge.lim.ControlDependency; import net.sf.openforge.lim.DataDependency; import net.sf.openforge.lim.Decision; import net.sf.openforge.lim.Dependency; import net.sf.openforge.lim.Design; import net.sf.openforge.lim.Entry; import net.sf.openforge.lim.Exit; import net.sf.openforge.lim.InBuf; import net.sf.openforge.lim.Module; import net.sf.openforge.lim.Or; import net.sf.openforge.lim.OutBuf; import net.sf.openforge.lim.Port; import net.sf.openforge.lim.ResetDependency; import net.sf.openforge.lim.Task; import net.sf.openforge.lim.TaskCall; import net.sf.openforge.lim.memory.AddressStridePolicy; import net.sf.openforge.lim.memory.AddressableUnit; import net.sf.openforge.lim.memory.Allocation; import net.sf.openforge.lim.memory.LogicalMemory; import net.sf.openforge.lim.memory.LogicalValue; import net.sf.openforge.lim.memory.Record; import net.sf.openforge.lim.memory.Scalar; import net.sf.openforge.lim.op.AddOp; import net.sf.openforge.lim.op.AndOp; import net.sf.openforge.lim.op.ComplementOp; import net.sf.openforge.lim.op.DivideOp; import net.sf.openforge.lim.op.EqualsOp; import net.sf.openforge.lim.op.GreaterThanEqualToOp; import net.sf.openforge.lim.op.GreaterThanOp; import net.sf.openforge.lim.op.LeftShiftOp; import net.sf.openforge.lim.op.LessThanEqualToOp; import net.sf.openforge.lim.op.LessThanOp; import net.sf.openforge.lim.op.MinusOp; import net.sf.openforge.lim.op.ModuloOp; import net.sf.openforge.lim.op.MultiplyOp; import net.sf.openforge.lim.op.NoOp; import net.sf.openforge.lim.op.NotEqualsOp; import net.sf.openforge.lim.op.NotOp; import net.sf.openforge.lim.op.OrOp; import net.sf.openforge.lim.op.RightShiftOp; import net.sf.openforge.lim.op.SimpleConstant; import net.sf.openforge.lim.op.SubtractOp; import net.sf.openforge.lim.op.XorOp; import net.sf.openforge.util.MathStuff; import net.sf.openforge.util.naming.ID; import net.sf.openforge.util.naming.IDSourceInfo; import net.sf.orcc.df.Action; import net.sf.orcc.df.Actor; import net.sf.orcc.df.Instance; import net.sf.orcc.df.util.DfVisitor; import net.sf.orcc.ir.BlockIf; import net.sf.orcc.ir.BlockWhile; import net.sf.orcc.ir.ExprBinary; import net.sf.orcc.ir.ExprBool; import net.sf.orcc.ir.ExprInt; import net.sf.orcc.ir.ExprUnary; import net.sf.orcc.ir.ExprVar; import net.sf.orcc.ir.InstAssign; import net.sf.orcc.ir.InstCall; import net.sf.orcc.ir.InstLoad; import net.sf.orcc.ir.IrFactory; import net.sf.orcc.ir.OpBinary; import net.sf.orcc.ir.OpUnary; import net.sf.orcc.ir.Procedure; import net.sf.orcc.ir.Type; import net.sf.orcc.ir.TypeList; import net.sf.orcc.ir.Var; import net.sf.orcc.ir.util.AbstractIrVisitor; import net.sf.orcc.ir.util.ValueUtil; import org.eclipse.emf.common.util.EList; /** * The DesignActorVisitor class transforms an Orcc Actor to an OpenForge Design * * @author Endri Bezati * */ public class DesignActorVisitor extends DfVisitor<Object> { /** List which associates each action with its components **/ private final Map<Action, List<Component>> actionComponents = new HashMap<Action, List<Component>>(); /** Map of action associated to its Task **/ private final Map<Action, Task> actorsTasks = new HashMap<Action, Task>(); /** Action component Counter **/ protected Integer componentCounter; /** Dependency between Components and Port-Var **/ protected Map<Component, Map<Port, Var>> componentPortDependency = new HashMap<Component, Map<Port, Var>>(); /** Dependency between Components and Bus-Var **/ protected Map<Component, Map<Bus, Var>> componentBusDependency = new HashMap<Component, Map<Bus, Var>>(); /** Dependency between Components and Done Bus **/ protected Map<Component, Bus> componentDoneBusDependency = new HashMap<Component, Bus>(); /** Dependency between Module Ports and its associated Var **/ protected Map<Module, Map<Port, Var>> modulePortDependency = new HashMap<Module, Map<Port, Var>>(); /** Current visited action **/ protected Action currentAction = null; /** Current Component **/ protected Component currentComponent = null; /** Current Exit **/ protected Exit.Type currentExit; /** Current List Component **/ protected List<Component> currentListComponent; /** The current module which represents the Action **/ protected Module currentModule; /** Design to be build **/ protected Design design; /** Port Cache **/ protected PortCache portCache = new PortCache(); /** Design Resources **/ protected ResourceCache resources; /** Design stateVars **/ protected Map<LogicalValue, Var> stateVars; /** Instance **/ Instance instance; public DesignActorVisitor(Instance instance, Design design, ResourceCache resources) { this.instance = instance; this.design = design; this.resources = resources; irVisitor = new InnerIrVisitor(); } protected class InnerIrVisitor extends AbstractIrVisitor<Object> { public InnerIrVisitor() { super(true); } @Override public Object caseExprBinary(ExprBinary expr) { if (expr.getOp() == OpBinary.BITAND) { currentComponent = new AndOp(); } else if (expr.getOp() == OpBinary.BITOR) { currentComponent = new OrOp(); } else if (expr.getOp() == OpBinary.BITXOR) { currentComponent = new XorOp(); } else if (expr.getOp() == OpBinary.DIV) { currentComponent = new DivideOp(expr.getType().getSizeInBits()); } else if (expr.getOp() == OpBinary.DIV_INT) { currentComponent = new DivideOp(expr.getType().getSizeInBits()); } else if (expr.getOp() == OpBinary.EQ) { currentComponent = new EqualsOp(); } else if (expr.getOp() == OpBinary.GE) { currentComponent = new GreaterThanEqualToOp(); } else if (expr.getOp() == OpBinary.GT) { currentComponent = new GreaterThanOp(); } else if (expr.getOp() == OpBinary.LE) { currentComponent = new LessThanEqualToOp(); } else if (expr.getOp() == OpBinary.LOGIC_AND) { currentComponent = new And(2); } else if (expr.getOp() == OpBinary.LOGIC_OR) { currentComponent = new Or(2); } else if (expr.getOp() == OpBinary.LT) { currentComponent = new LessThanOp(); } else if (expr.getOp() == OpBinary.MINUS) { currentComponent = new SubtractOp(); } else if (expr.getOp() == OpBinary.MOD) { currentComponent = new ModuloOp(); } else if (expr.getOp() == OpBinary.NE) { currentComponent = new NotEqualsOp(); } else if (expr.getOp() == OpBinary.PLUS) { currentComponent = new AddOp(); } else if (expr.getOp() == OpBinary.SHIFT_LEFT) { int log2N = MathStuff.log2(expr.getType().getSizeInBits()); currentComponent = new LeftShiftOp(log2N); } else if (expr.getOp() == OpBinary.SHIFT_RIGHT) { int log2N = MathStuff.log2(expr.getType().getSizeInBits()); currentComponent = new RightShiftOp(log2N); } else if (expr.getOp() == OpBinary.TIMES) { currentComponent = new MultiplyOp(expr.getType() .getSizeInBits()); } // Three address code obligated, a binary expression // can not contain another binary expression // Get variables for E1 and E2 Var e1 = ((ExprVar) expr.getE1()).getUse().getVariable(); Var e2 = ((ExprVar) expr.getE2()).getUse().getVariable(); mapInPorts(new ArrayList<Var>(Arrays.asList(e1, e2)), currentComponent); currentListComponent.add(currentComponent); return null; } @Override public Object caseExprBool(ExprBool expr) { final long value = expr.isValue() ? 1 : 0; currentComponent = new SimpleConstant(value, 1, true); return null; } @Override public Object caseExprInt(ExprInt expr) { final long value = expr.getIntValue(); currentComponent = new SimpleConstant(value, expr.getType() .getSizeInBits(), expr.getType().isInt()); return null; } @Override public Object caseExprUnary(ExprUnary expr) { if (expr.getOp() == OpUnary.BITNOT) { currentComponent = new ComplementOp(); } else if (expr.getOp() == OpUnary.LOGIC_NOT) { currentComponent = new NotOp(); } else if (expr.getOp() == OpUnary.MINUS) { currentComponent = new MinusOp(); } return null; } @Override public Object caseExprVar(ExprVar var) { // TODO: See if NoOP can have more than one inputs after all actors // Transformations currentComponent = new NoOp(1, Exit.DONE); mapInPorts( new ArrayList<Var>( Arrays.asList(var.getUse().getVariable())), currentComponent); return null; } @Override public Object caseInstAssign(InstAssign assign) { super.caseInstAssign(assign); if (currentComponent != null) { currentListComponent.add(currentComponent); mapOutPorts(assign.getTarget().getVariable()); } return null; } @Override public Object caseInstCall(InstCall call) { currentComponent = new TaskCall(); resources.addTaskCall(call, (TaskCall) currentComponent); return null; } @Override public Object caseInstLoad(InstLoad load) { if (load.getSource().getVariable().getType().isList()) { // TODO: Load index of the List } else { currentComponent = new NoOp(1, Exit.DONE); } return null; } @Override public Object caseBlockIf(BlockIf blockIf) { return null; } @Override public Object caseBlockWhile(BlockWhile blockWhile) { return null; } @Override public Object caseVar(Var var) { if (var.isGlobal()) { stateVars.put(makeLogicalValue(var), var); } return null; } } protected Decision buildDecision(Var inputDecision, String resultName) { Decision decision = null; // Create the decision variable and assign the inputDecision to it Type type = IrFactory.eINSTANCE.createTypeBool(); Var decisionVar = IrFactory.eINSTANCE.createVar(0, type, resultName, false, 0); InstAssign assign = IrFactory.eINSTANCE.createInstAssign(decisionVar, IrFactory.eINSTANCE.createExprVar(inputDecision)); // Visit assignSched doSwitch(assign); currentModule = (Module) buildModule(Arrays.asList(currentComponent), Arrays.asList(inputDecision), Collections.<Var> emptyList(), "decisionBlock", null); // Add done dependency mapOutControlPort(currentModule); // Create the decision decision = new Decision((Block) currentModule, currentComponent); // Any data inputs to the decision need to be propagated from // the block to the decision. There should be no output ports // to propagate. They are inferred true/false. propagateInputs(decision, (Block) currentModule); // Build option scope currentModule.specifySearchScope("moduleDecision"); return decision; } protected Component buildBranch(Decision decision, Block thenBlock, Block elseBlock, List<Var> inVars, List<Var> outVars, String searchScope, Exit.Type exitType) { Branch branch = null; portCache.publish(decision); portCache.publish(thenBlock); if (elseBlock == null) { branch = new Branch(decision, thenBlock); } else { branch = new Branch(decision, thenBlock, elseBlock); portCache.publish(elseBlock); } createModuleInterface(branch, inVars, outVars, exitType); // Map In/Out port of branch mapInPorts(inVars, branch, branch.showIDLogical()); mapOutControlPort(branch); operationDependencies(branch, Arrays.asList((Component) branch), componentPortDependency, branch.getExit(Exit.DONE)); // Give the name of the searchScope branch.specifySearchScope(searchScope); return branch; } protected Component buildModule(List<Component> components, List<Var> inVars, List<Var> outVars, String searchScope, Exit.Type exitType) { // Create an Empty Block Module module = new Block(false); // Add Input and Output Port for the Module createModuleInterface(module, inVars, outVars, exitType); // Put all the components to the Module populateModule(module, components); // Set all the dependencies operationDependencies(module, components, componentPortDependency, module.getExit(exitType)); // Give the name of the searchScope module.specifySearchScope(searchScope); return module; } @Override public Object caseAction(Action action) { currentAction = action; componentCounter = 0; currentListComponent = new ArrayList<Component>(); // Initialize currentModule and its exit Type // currentModule = new Block(false); // Make Action module exit currentExit = Exit.RETURN; // Get pinRead Operation(s) for (net.sf.orcc.df.Port port : action.getInputPattern().getPorts()) { makePinReadOperation(port, portCache); currentListComponent.add(currentComponent); } // Visit the rest of the action super.doSwitch(action.getBody()); // Get pinWrite Operation(s) for (net.sf.orcc.df.Port port : action.getOutputPattern().getPorts()) { makePinWriteOperation(port, portCache); currentListComponent.add(currentComponent); } // Create the task Task task = createTask(currentAction.getName()); actorsTasks.put(action, task); // Add it to the design design.addTask(task); // TODO: To be deleted actionComponents.put(currentAction, currentListComponent); return null; } @Override public Object caseActor(Actor actor) { // Get Actors Input(s) Port getActorsPorts(actor.getInputs(), "in", resources); // Get Actors Output(s) Port getActorsPorts(actor.getOutputs(), "out", resources); // TODO: Get the values of the parameters before visiting for (Var parameter : actor.getParameters()) { doSwitch(parameter); } stateVars = new HashMap<LogicalValue, Var>(); // Visit stateVars for (Var stateVar : actor.getStateVars()) { doSwitch(stateVar); } // Allocate each LogicalValue (State Variable) in a memory // with a matching address stride. This provides consistency // in the memories and allows for state vars to be co-located // if area is of concern. Map<Integer, LogicalMemory> memories = new HashMap<Integer, LogicalMemory>(); for (LogicalValue lvalue : stateVars.keySet()) { int stride = lvalue.getAddressStridePolicy().getStride(); LogicalMemory mem = memories.get(stride); if (mem == null) { // 32 should be more than enough for max address // width mem = new LogicalMemory(32); mem.createLogicalMemoryPort(); design.addMemory(mem); } // Create a 'location' for the stateVar that is // appropriate for its type/size. Allocation location = mem.allocate(lvalue); Var stateVar = stateVars.get(lvalue); setAttributes(stateVar, location); resources.addLocation(stateVar, location); } // TODO: Create Task for procedures for (Procedure procedure : actor.getProcs()) { doSwitch(procedure); } // Create a Task for each action in the actor for (Action action : actor.getActions()) { doSwitch(action); } // TODO: Do not know what to do for the moment with this one for (Action initialize : actor.getInitializes()) { doSwitch(initialize); } // Create a task for the scheduler and add it directly to the design DesignActorSchedulerVisitor schedulerVisitor = new DesignActorSchedulerVisitor( instance, design, actorsTasks, resources); schedulerVisitor.doSwitch(actor); return null; } protected void componentAddEntry(Component comp, Exit drivingExit, Bus clockBus, Bus resetBus, Bus goBus) { Entry entry = comp.makeEntry(drivingExit); // Even though most components do not use the clock, reset and // go ports we set up the dependencies for consistency. entry.addDependency(comp.getClockPort(), new ClockDependency(clockBus)); entry.addDependency(comp.getResetPort(), new ResetDependency(resetBus)); entry.addDependency(comp.getGoPort(), new ControlDependency(goBus)); } protected Call createCall(String name, Module module) { Block procedureBlock = (Block) module; net.sf.openforge.lim.Procedure proc = new net.sf.openforge.lim.Procedure( procedureBlock); Call call = proc.makeCall(); proc.setIDSourceInfo(deriveIDSourceInfo(name)); for (Port blockPort : procedureBlock.getPorts()) { Port callPort = call.getPortFromProcedurePort(blockPort); portCache.replaceTarget(blockPort, callPort); } for (Exit exit : procedureBlock.getExits()) { for (Bus blockBus : exit.getBuses()) { Bus callBus = call.getBusFromProcedureBus(blockBus); portCache.replaceSource(blockBus, callBus); } } return call; } protected void createModuleInterface(Module module, List<Var> inVars, List<Var> outVars, Exit.Type exitType) { if (inVars != null) { Map<Port, Var> portDep = new HashMap<Port, Var>(); for (Var var : inVars) { Port port = module.makeDataPort(); port.setIDLogical(var.getIndexedName()); portDep.put(port, var); // portCache.putTarget(var, port); // portCache.putSource(var, port.getPeer()); } modulePortDependency.put(module, portDep); } // TODO: outVars for PHI // Create modules exit if (module.getExit(Exit.DONE) == null) { if ((exitType != null) && (exitType != Exit.DONE)) { module.makeExit(0, exitType); } else { module.makeExit(0); } } } protected Task createTask(String name) { Task task = null; currentModule = (Module) buildModule(currentListComponent, Collections.<Var> emptyList(), Collections.<Var> emptyList(), name, currentExit); // create Call Call call = createCall(name, currentModule); topLevelInit(call); // Create task task = new Task(call); task.setKickerRequired(false); task.setSourceName(name); return task; } // TODO: set all the necessary information here protected IDSourceInfo deriveIDSourceInfo(String name) { String fileName = null; String packageName = null; String className = name; String methodName = name; String signature = null; int line = 0; int cpos = 0; return new IDSourceInfo(fileName, packageName, className, methodName, signature, line, cpos); } /** * This method get the I/O ports of the actor and it adds in {@link Design} * the actors ports * * @param ports * the list of the Ports * @param direction * the direction of the port, "in" for input / "out" for output * @param resources * the cache resource */ private void getActorsPorts(EList<net.sf.orcc.df.Port> ports, String direction, ResourceCache resources) { for (net.sf.orcc.df.Port port : ports) { if (port.isNative()) { NativeIOHandler ioHandler = new ActionIOHandler.NativeIOHandler( direction, port.getName(), Integer.toString(port .getType().getSizeInBits())); ioHandler.build(design); resources.addIOHandler(port, ioHandler); } else { FifoIOHandler ioHandler = new ActionIOHandler.FifoIOHandler( direction, port.getName(), Integer.toString(port .getType().getSizeInBits())); ioHandler.build(design); resources.addIOHandler(port, ioHandler); } } } /** * Constructs a LogicalValue from a String value given its type * * @param stringValue * the numerical value * @param type * the type of the numerical value * @return */ private LogicalValue makeLogicalValue(String stringValue, Type type) { LogicalValue logicalValue = null; final BigInteger value; Integer bitSize = type.getSizeInBits(); if (stringValue.trim().toUpperCase().startsWith("0X")) { value = new BigInteger(stringValue.trim().substring(2), 16); } else { value = new BigInteger(stringValue); } AddressStridePolicy addrPolicy = new AddressStridePolicy(bitSize); logicalValue = new Scalar(new AddressableUnit(value), addrPolicy); return logicalValue; } /** * Constructs a LogicalValue from a Variable * * @param var * the variable * @return */ private LogicalValue makeLogicalValue(Var var) { LogicalValue logicalValue = null; if (var.getType().isList()) { TypeList typeList = (TypeList) var.getType(); Type type = typeList.getInnermostType(); List<Integer> listDimension = typeList.getDimensions(); Object varValue = var.getValue(); logicalValue = makeLogicalValueObject(varValue, listDimension, type); } else { Type type = var.getType(); if (var.isInitialized()) { String valueString = Integer.toString(((ExprInt) var .getInitialValue()).getIntValue()); logicalValue = makeLogicalValue(valueString, type); } else { logicalValue = makeLogicalValue("0", type); } } return logicalValue; } /** * Constructs a LogicalValue from a uni or multi-dim Object Value * * @param obj * the object value * @param dimension * the dimension of the object value * @param type * the type of the object value * @return */ private LogicalValue makeLogicalValueObject(Object obj, List<Integer> dimension, Type type) { LogicalValue logicalValue = null; if (dimension.size() > 1) { List<LogicalValue> subElements = new ArrayList<LogicalValue>( dimension.get(0)); List<Integer> newListDimension = dimension; newListDimension.remove(0); for (int i = 0; i < dimension.get(0); i++) { subElements.add(makeLogicalValueObject(Array.get(obj, i), newListDimension, type)); } logicalValue = new Record(subElements); } else { if (dimension.get(0).equals(1)) { BigInteger value = (BigInteger) ValueUtil.get(type, obj, 0); String valueString = value.toString(); logicalValue = makeLogicalValue(valueString, type); } else { List<LogicalValue> subElements = new ArrayList<LogicalValue>( dimension.get(0)); for (int i = 0; i < dimension.get(0); i++) { BigInteger value = (BigInteger) ValueUtil.get(type, obj, i); String valueString = value.toString(); subElements.add(makeLogicalValue(valueString, type)); } logicalValue = new Record(subElements); } } return logicalValue; } private void makePinReadOperation(net.sf.orcc.df.Port port, PortCache portCache) { ActionIOHandler ioHandler = resources.getIOHandler(port); currentComponent = ioHandler.getReadAccess(); setAttributes( "pinRead_" + port.getName() + "_" + Integer.toString(componentCounter), currentComponent); Var pinReadVar = currentAction.getInputPattern().getPortToVarMap() .get(port); for (Bus dataBus : currentComponent.getExit(Exit.DONE).getDataBuses()) { if (dataBus.getValue() == null) { dataBus.setSize(port.getType().getSizeInBits(), port.getType() .isInt() || port.getType().isBool()); } portCache.putSource(pinReadVar, dataBus); } mapOutPorts(pinReadVar); componentCounter++; } private void makePinWriteOperation(net.sf.orcc.df.Port port, PortCache portCache) { ActionIOHandler ioHandler = resources.getIOHandler(port); currentComponent = ioHandler.getWriteAccess(); setAttributes( "pinWrite_" + port.getName() + "_" + Integer.toString(componentCounter), currentComponent); Var pinWriteVar = currentAction.getOutputPattern().getPortToVarMap() .get(port); mapInPorts(new ArrayList<Var>(Arrays.asList(pinWriteVar)), currentComponent); // Add done dependency for this operation to the current module exit Bus doneBus = currentComponent.getExit(Exit.DONE).getDoneBus(); portCache.putDoneBus(currentComponent, doneBus); componentCounter++; } protected void mapInPorts(List<Var> inVars, Component component) { Iterator<Port> portIter = component.getDataPorts().iterator(); Map<Port, Var> portDep = new HashMap<Port, Var>(); for (Var var : inVars) { Port dataPort = portIter.next(); dataPort.setIDLogical(var.getIndexedName()); dataPort.setSize(var.getType().getSizeInBits(), var.getType() .isInt() || var.getType().isBool()); portDep.put(dataPort, var); // portCache.putTarget(var, dataPort); } // Put Input dependency componentPortDependency.put(component, portDep); } protected void mapInPorts(List<Var> inVars, Component component, String prefix) { List<Var> changedVar = new ArrayList<Var>(); Iterator<Port> portIter = component.getDataPorts().iterator(); Map<Port, Var> portDep = new HashMap<Port, Var>(); for (Var var : inVars) { Var varDep = IrFactory.eINSTANCE.createVar(0, var.getType(), var.getIndexedName() + "_" + prefix, false, 0); Port dataPort = portIter.next(); dataPort.setIDLogical(varDep.getIndexedName()); dataPort.setSize(varDep.getType().getSizeInBits(), varDep.getType() .isInt() || varDep.getType().isBool()); portDep.put(dataPort, varDep); // portCache.putTarget(varDep, dataPort); changedVar.add(varDep); } // Put Input dependency componentPortDependency.put(component, portDep); } protected void mapOutPorts(Var var) { Bus dataBus = currentComponent.getExit(Exit.DONE).getDataBuses().get(0); Map<Bus, Var> busDep = new HashMap<Bus, Var>(); + Map<Port, Var> portDep = new HashMap<Port, Var>(); if (dataBus.getValue() == null) { dataBus.setSize(var.getType().getSizeInBits(), var.getType() .isInt() || var.getType().isBool()); } dataBus.setIDLogical(var.getIndexedName()); busDep.put(dataBus, var); + portDep.put(dataBus.getPeer(), var); + componentPortDependency.put(currentComponent, portDep); componentBusDependency.put(currentComponent, busDep); // portCache.putSource(var, dataBus); mapOutControlPort(currentComponent); } protected void mapOutControlPort(Component component) { Bus doneBus = component.getExit(Exit.DONE).getDoneBus(); componentDoneBusDependency.put(component, doneBus); // portCache.putDoneBus(component, doneBus); } protected void operationDependencies(Module module, List<Component> components, Map<Component, Map<Port, Var>> dependecies, Exit exit) { // Build Data Dependencies for (Component component : components) { for (Port port : component.getDataPorts()) { Var var = componentPortDependency.get(component).get(port); if (dependencyOnModulePort(module, var)) { Bus sourceBus = getModulePortPeer(module, var); List<Entry> entries = port.getOwner().getEntries(); Entry entry = entries.get(0); Dependency dep = new DataDependency(sourceBus); entry.addDependency(port, dep); } else { Bus sourceBus = getModuleComponentPortPeer(module, var); List<Entry> entries = port.getOwner().getEntries(); Entry entry = entries.get(0); Dependency dep = new DataDependency(sourceBus); entry.addDependency(port, dep); } } } // Build control Dependencies for (Component component : components) { Bus busDone = componentDoneBusDependency.get(component); if (busDone != null) { Port donePort = exit.getDoneBus().getPeer(); List<Entry> entries = donePort.getOwner().getEntries(); Entry entry = entries.get(0); Dependency dep = new ControlDependency(busDone); entry.addDependency(donePort, dep); } } } protected Bus getModulePortPeer(Module module, Var var) { Bus bus = null; Map<Port, Var> portVar = modulePortDependency.get(module); for (Port port : portVar.keySet()) { if (var == portVar.get(port)) { bus = port.getPeer(); } } return bus; } protected Bus getModuleComponentPortPeer(Module module, Var var) { Bus bus = null; for (Component component : module.getComponents()) { Map<Port, Var> portVar = componentPortDependency.get(component); if (portVar != null) { for (Port port : portVar.keySet()) { if (var == portVar.get(port)) { return port.getPeer(); } } } } return bus; } protected Boolean dependencyOnModulePort(Module module, Var var) { Map<Port, Var> portVar = modulePortDependency.get(module); for (Port port : portVar.keySet()) { if (portVar.get(port) == var) { return true; } } return false; } /** * Takes care of the busy work of putting the components into the module (in * order) and ensuring appropriate clock, reset, and go dependencies (which * ALL components must have) * * @param components * a List of {@link Component} objects */ protected void populateModule(Module module, List<Component> components) { final InBuf inBuf = module.getInBuf(); final Bus clockBus = inBuf.getClockBus(); final Bus resetBus = inBuf.getResetBus(); final Bus goBus = inBuf.getGoBus(); // I believe that the drivingExit no longer relevant Exit drivingExit = inBuf.getExit(Exit.DONE); int index = 0; for (Component comp : components) { if (module instanceof Block) { ((Block) module).insertComponent(comp, index++); } else { module.addComponent(comp); } componentAddEntry(comp, drivingExit, clockBus, resetBus, goBus); drivingExit = comp.getExit(Exit.DONE); } // Ensure that the outbufs of the module have an entry for (OutBuf outbuf : module.getOutBufs()) { componentAddEntry(outbuf, drivingExit, clockBus, resetBus, goBus); } } protected void propagateInputs(Decision decision, Block testBlock) { for (Port port : testBlock.getDataPorts()) { Port decisionPort = decision.makeDataPort(); Entry entry = port.getOwner().getEntries().get(0); entry.addDependency(port, new DataDependency(decisionPort.getPeer())); portCache.replaceTarget(port, decisionPort); } } protected void setAttributes(String tag, Component comp) { setAttributes(tag, comp, false); } protected void setAttributes(String tag, Component comp, Boolean Removable) { comp.setSourceName(tag); if (!Removable) { comp.setNonRemovable(); } } /** * Set the name of an LIM component by the name of an Orcc variable * * @param var * a Orcc IR variable element * @param comp * a LIM ID component */ protected void setAttributes(Var var, ID comp) { comp.setSourceName(var.getName()); } protected void topLevelInit(Call call) { call.getClockPort().setSize(1, false); call.getResetPort().setSize(1, false); call.getGoPort().setSize(1, false); } }
false
false
null
null
diff --git a/dbflute/src/main/java/org/seasar/dbflute/logic/dumpdata/DfDumpDataExtractor.java b/dbflute/src/main/java/org/seasar/dbflute/logic/dumpdata/DfDumpDataExtractor.java index 25e9d5068..6b83e821f 100644 --- a/dbflute/src/main/java/org/seasar/dbflute/logic/dumpdata/DfDumpDataExtractor.java +++ b/dbflute/src/main/java/org/seasar/dbflute/logic/dumpdata/DfDumpDataExtractor.java @@ -1,104 +1,117 @@ package org.seasar.dbflute.logic.dumpdata; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.seasar.dbflute.properties.DfAbstractHelperProperties; /** * @author jflute * @since 0.8.3 (2008/10/28 Tuesday) */ public class DfDumpDataExtractor { // =============================================================================== // Definition // ========== /** Log-instance */ private static final Log _log = LogFactory.getLog(DfAbstractHelperProperties.class); // =================================================================================== // Attribute // ========= protected DataSource _dataSource; // =================================================================================== // Constructor // =========== public DfDumpDataExtractor(DataSource dataSource) { _dataSource = dataSource; } // =================================================================================== // Extract // ======= /** * Extract data. * @param tableColumnMap The map of table and column. (NotNull) * @param limit The limit of records. (If it's minus value, extracts all records.) */ public Map<String, List<Map<String, String>>> extractData(Map<String, List<String>> tableColumnMap, int limit) { final Map<String, List<Map<String, String>>> dumpDataMap = new LinkedHashMap<String, List<Map<String, String>>>(); + Connection conn = null; try { + conn = _dataSource.getConnection(); final Set<String> tableNameSet = tableColumnMap.keySet(); for (String tableName : tableNameSet) { final List<String> columnNameList = tableColumnMap.get(tableName); - final Connection conn = _dataSource.getConnection(); - final Statement statement = conn.createStatement(); final String selectClause = buildSelectClause(columnNameList); final String fromClause = buildFromClause(tableName); final List<Map<String, String>> recordList = new ArrayList<Map<String, String>>(); + Statement statement = null; try { + statement = conn.createStatement(); final String sql = selectClause + " " + fromClause; final ResultSet rs = statement.executeQuery(sql); int count = 0; while (rs.next()) { if (limit >= 0 && limit <= count) { break; } final LinkedHashMap<String, String> recordMap = new LinkedHashMap<String, String>(); for (String columnName : columnNameList) { final String columnValue = rs.getString(columnName); recordMap.put(columnName, columnValue); } recordList.add(recordMap); ++count; } _log.info(" " + tableName + "(" + recordList.size() + ")"); } catch (SQLException ignored) { _log.info("Failed to extract data of " + tableName + ": " + ignored.getMessage()); + } finally { + if (statement != null) { + statement.close(); + } } dumpDataMap.put(tableName, recordList); } } catch (SQLException e) { throw new IllegalStateException(e); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException ignored) { + } + } } return dumpDataMap; } protected String buildSelectClause(List<String> columnNameList) { final StringBuilder sb = new StringBuilder(); for (String columnName : columnNameList) { if (sb.length() > 0) { sb.append(", "); } sb.append(columnName); } return sb.insert(0, "select ").toString(); } protected String buildFromClause(String tableName) { return "from " + tableName; } }
false
true
public Map<String, List<Map<String, String>>> extractData(Map<String, List<String>> tableColumnMap, int limit) { final Map<String, List<Map<String, String>>> dumpDataMap = new LinkedHashMap<String, List<Map<String, String>>>(); try { final Set<String> tableNameSet = tableColumnMap.keySet(); for (String tableName : tableNameSet) { final List<String> columnNameList = tableColumnMap.get(tableName); final Connection conn = _dataSource.getConnection(); final Statement statement = conn.createStatement(); final String selectClause = buildSelectClause(columnNameList); final String fromClause = buildFromClause(tableName); final List<Map<String, String>> recordList = new ArrayList<Map<String, String>>(); try { final String sql = selectClause + " " + fromClause; final ResultSet rs = statement.executeQuery(sql); int count = 0; while (rs.next()) { if (limit >= 0 && limit <= count) { break; } final LinkedHashMap<String, String> recordMap = new LinkedHashMap<String, String>(); for (String columnName : columnNameList) { final String columnValue = rs.getString(columnName); recordMap.put(columnName, columnValue); } recordList.add(recordMap); ++count; } _log.info(" " + tableName + "(" + recordList.size() + ")"); } catch (SQLException ignored) { _log.info("Failed to extract data of " + tableName + ": " + ignored.getMessage()); } dumpDataMap.put(tableName, recordList); } } catch (SQLException e) { throw new IllegalStateException(e); } return dumpDataMap; }
public Map<String, List<Map<String, String>>> extractData(Map<String, List<String>> tableColumnMap, int limit) { final Map<String, List<Map<String, String>>> dumpDataMap = new LinkedHashMap<String, List<Map<String, String>>>(); Connection conn = null; try { conn = _dataSource.getConnection(); final Set<String> tableNameSet = tableColumnMap.keySet(); for (String tableName : tableNameSet) { final List<String> columnNameList = tableColumnMap.get(tableName); final String selectClause = buildSelectClause(columnNameList); final String fromClause = buildFromClause(tableName); final List<Map<String, String>> recordList = new ArrayList<Map<String, String>>(); Statement statement = null; try { statement = conn.createStatement(); final String sql = selectClause + " " + fromClause; final ResultSet rs = statement.executeQuery(sql); int count = 0; while (rs.next()) { if (limit >= 0 && limit <= count) { break; } final LinkedHashMap<String, String> recordMap = new LinkedHashMap<String, String>(); for (String columnName : columnNameList) { final String columnValue = rs.getString(columnName); recordMap.put(columnName, columnValue); } recordList.add(recordMap); ++count; } _log.info(" " + tableName + "(" + recordList.size() + ")"); } catch (SQLException ignored) { _log.info("Failed to extract data of " + tableName + ": " + ignored.getMessage()); } finally { if (statement != null) { statement.close(); } } dumpDataMap.put(tableName, recordList); } } catch (SQLException e) { throw new IllegalStateException(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException ignored) { } } } return dumpDataMap; }
diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/LocalHistoryPage.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/LocalHistoryPage.java index eb999da99..d5c1a44d0 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/LocalHistoryPage.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/LocalHistoryPage.java @@ -1,576 +1,575 @@ /******************************************************************************* * Copyright (c) 2006 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 org.eclipse.team.internal.ui.history; import java.util.ArrayList; import java.util.HashMap; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.action.*; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.IOpenEventListener; import org.eclipse.jface.util.OpenStrategy; import org.eclipse.jface.viewers.*; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.*; import org.eclipse.team.core.RepositoryProvider; import org.eclipse.team.core.TeamStatus; import org.eclipse.team.core.history.IFileHistory; import org.eclipse.team.core.history.IFileRevision; import org.eclipse.team.internal.core.history.LocalFileHistory; import org.eclipse.team.internal.core.history.LocalFileRevision; import org.eclipse.team.internal.ui.*; import org.eclipse.team.internal.ui.actions.CompareRevisionAction; import org.eclipse.team.internal.ui.actions.OpenRevisionAction; import org.eclipse.team.ui.history.HistoryPage; import org.eclipse.team.ui.history.IHistoryPageSite; import org.eclipse.ui.*; import org.eclipse.ui.progress.IProgressConstants; import com.ibm.icu.util.Calendar; public class LocalHistoryPage extends HistoryPage { /* private */ IFile file; /* private */ IFileRevision currentFileRevision; // cached for efficiency /* private */ LocalFileHistory localFileHistory; /* private */IFileRevision[] entries; /* private */ TreeViewer treeViewer; /* private */boolean shutdown = false; //grouping on private boolean groupingOn; //toggle constants for default click action private boolean compareMode = false; protected LocalHistoryTableProvider historyTableProvider; private RefreshFileHistory refreshFileHistoryJob; private Composite localComposite; private Action groupByDateMode; private Action collapseAll; private Action compareModeAction; private CompareRevisionAction compareAction; private OpenRevisionAction openAction; private HistoryResourceListener resourceListener; public boolean inputSet() { currentFileRevision = null; IFile tempFile = getFile(); this.file = tempFile; if (tempFile == null) return false; //blank current input only after we're sure that we have a file //to fetch history for this.treeViewer.setInput(null); localFileHistory = new LocalFileHistory(file); if (refreshFileHistoryJob == null) refreshFileHistoryJob = new RefreshFileHistory(); //always refresh the history if the input gets set refreshHistory(true); return true; } private IFile getFile() { Object obj = getInput(); if (obj instanceof IFile) return (IFile) obj; return null; } private void refreshHistory(boolean refetch) { if (refreshFileHistoryJob.getState() != Job.NONE){ refreshFileHistoryJob.cancel(); } refreshFileHistoryJob.setFileHistory(localFileHistory); refreshFileHistoryJob.setGrouping(groupingOn); IHistoryPageSite parentSite = getHistoryPageSite(); Utils.schedule(refreshFileHistoryJob, getWorkbenchSite(parentSite)); } private IWorkbenchPartSite getWorkbenchSite(IHistoryPageSite parentSite) { IWorkbenchPart part = parentSite.getPart(); if (part != null) return part.getSite(); return null; } public void createControl(Composite parent) { localComposite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.marginHeight = 0; layout.marginWidth = 0; localComposite.setLayout(layout); GridData data = new GridData(GridData.FILL_BOTH); data.grabExcessVerticalSpace = true; localComposite.setLayoutData(data); treeViewer = createTree(localComposite); contributeActions(); IHistoryPageSite parentSite = getHistoryPageSite(); if (parentSite != null && parentSite instanceof DialogHistoryPageSite && treeViewer != null) parentSite.setSelectionProvider(treeViewer); resourceListener = new HistoryResourceListener(); ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceListener, IResourceChangeEvent.POST_CHANGE); } private void contributeActions() { final IPreferenceStore store = TeamUIPlugin.getPlugin().getPreferenceStore(); //Group by Date groupByDateMode = new Action(TeamUIMessages.LocalHistoryPage_GroupRevisionsByDateAction, TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_DATES_CATEGORY)){ public void run() { groupingOn = !groupingOn; - compareModeAction.setChecked(groupingOn); store.setValue(IPreferenceIds.PREF_GROUPBYDATE_MODE, groupingOn); refreshHistory(false); } }; groupingOn = store.getBoolean(IPreferenceIds.PREF_GROUPBYDATE_MODE); groupByDateMode.setChecked(groupingOn); groupByDateMode.setToolTipText(TeamUIMessages.LocalHistoryPage_GroupRevisionsByDateTip); groupByDateMode.setDisabledImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_DATES_CATEGORY)); groupByDateMode.setHoverImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_DATES_CATEGORY)); //Collapse All collapseAll = new Action(TeamUIMessages.LocalHistoryPage_CollapseAllAction, TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COLLAPSE_ALL)) { public void run() { treeViewer.collapseAll(); } }; collapseAll.setToolTipText(TeamUIMessages.LocalHistoryPage_CollapseAllTip); collapseAll.setDisabledImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COLLAPSE_ALL)); collapseAll.setHoverImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COLLAPSE_ALL)); //Compare Mode Action compareModeAction = new Action(TeamUIMessages.LocalHistoryPage_CompareModeAction,TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPARE_VIEW)) { public void run() { compareMode = !compareMode; compareModeAction.setChecked(compareMode); } }; compareModeAction.setToolTipText(TeamUIMessages.LocalHistoryPage_CompareModeTip); compareModeAction.setDisabledImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPARE_VIEW)); compareModeAction.setHoverImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPARE_VIEW)); compareModeAction.setChecked(false); // Click Compare action compareAction = new CompareRevisionAction(TeamUIMessages.LocalHistoryPage_CompareAction); treeViewer.getTree().addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e) { compareAction.setCurrentFileRevision(getCurrentFileRevision()); compareAction.selectionChanged((IStructuredSelection) treeViewer.getSelection()); } }); compareAction.setPage(this); openAction = new OpenRevisionAction(TeamUIMessages.LocalHistoryPage_OpenAction); treeViewer.getTree().addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e) { openAction.selectionChanged((IStructuredSelection) treeViewer.getSelection()); } }); openAction.setPage(this); OpenStrategy handler = new OpenStrategy(treeViewer.getTree()); handler.addOpenListener(new IOpenEventListener() { public void handleOpen(SelectionEvent e) { StructuredSelection tableStructuredSelection = (StructuredSelection) treeViewer.getSelection(); if (compareMode){ StructuredSelection sel = new StructuredSelection(new Object[] {getCurrentFileRevision(), tableStructuredSelection.getFirstElement()}); compareAction.selectionChanged(sel); compareAction.run(); } else { //Pass in the entire structured selection to allow for multiple editor openings StructuredSelection sel = tableStructuredSelection; openAction.selectionChanged(sel); openAction.run(); } } }); //Contribute actions to popup menu MenuManager menuMgr = new MenuManager(); Menu menu = menuMgr.createContextMenu(treeViewer.getTree()); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager menuMgr) { fillTableMenu(menuMgr); } }); menuMgr.setRemoveAllWhenShown(true); treeViewer.getTree().setMenu(menu); //Don't add the object contribution menu items if this page is hosted in a dialog IHistoryPageSite parentSite = getHistoryPageSite(); /*if (!parentSite.isModal()) { IWorkbenchPart part = parentSite.getPart(); if (part != null) { IWorkbenchPartSite workbenchPartSite = part.getSite(); workbenchPartSite.registerContextMenu(menuMgr, treeViewer); } IPageSite pageSite = parentSite.getWorkbenchPageSite(); if (pageSite != null) { IActionBars actionBars = pageSite.getActionBars(); // Contribute toggle text visible to the toolbar drop-down IMenuManager actionBarsMenu = actionBars.getMenuManager(); if (actionBarsMenu != null){ actionBarsMenu.add(toggleTextWrapAction); actionBarsMenu.add(new Separator()); actionBarsMenu.add(toggleTextAction); actionBarsMenu.add(toggleListAction); actionBarsMenu.add(new Separator()); actionBarsMenu.add(cvsHistoryFilter); actionBarsMenu.add(toggleFilterAction); } actionBars.updateActionBars(); } }*/ //Create the local tool bar IToolBarManager tbm = parentSite.getToolBarManager(); if (tbm != null) { //Add groups tbm.add(new Separator("grouping")); //$NON-NLS-1$ tbm.appendToGroup("grouping", groupByDateMode); //$NON-NLS-1$ tbm.add(new Separator("modes")); //$NON-NLS-1$ tbm.add(new Separator("collapse")); //$NON-NLS-1$ tbm.appendToGroup("collapse", collapseAll); //$NON-NLS-1$ tbm.appendToGroup("collapse", compareModeAction); //$NON-NLS-1$ tbm.update(false); } } protected void fillTableMenu(IMenuManager manager) { // file actions go first (view file) IHistoryPageSite parentSite = getHistoryPageSite(); manager.add(new Separator(IWorkbenchActionConstants.GROUP_FILE)); if (file != null && !parentSite.isModal()){ manager.add(openAction); manager.add(compareAction); } } /** * Creates the tree that displays the local file revisions * * @param the parent composite to contain the group * @return the group control */ protected TreeViewer createTree(Composite parent) { historyTableProvider = new LocalHistoryTableProvider(); TreeViewer viewer = historyTableProvider.createTree(parent); viewer.setContentProvider(new ITreeContentProvider() { public Object[] getElements(Object inputElement) { // The entries of already been fetch so return them if (entries != null) return entries; if (!(inputElement instanceof IFileHistory) && !(inputElement instanceof AbstractHistoryCategory[])) return new Object[0]; if (inputElement instanceof AbstractHistoryCategory[]){ return (AbstractHistoryCategory[]) inputElement; } final IFileHistory fileHistory = (IFileHistory) inputElement; entries = fileHistory.getFileRevisions(); return entries; } public void dispose() { } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { entries = null; } public Object[] getChildren(Object parentElement) { if (parentElement instanceof AbstractHistoryCategory){ return ((AbstractHistoryCategory) parentElement).getRevisions(); } return null; } public Object getParent(Object element) { return null; } public boolean hasChildren(Object element) { if (element instanceof AbstractHistoryCategory){ return ((AbstractHistoryCategory) element).hasRevisions(); } return false; } }); return viewer; } public Control getControl() { return localComposite; } public void setFocus() { localComposite.setFocus(); } public String getDescription() { if (file != null) return file.getFullPath().toString(); return null; } public String getName() { if (file != null) return file.getName(); return ""; //$NON-NLS-1$ } public boolean isValidInput(Object object) { //true if object is an unshared file if (object instanceof IFile) { if (!RepositoryProvider.isShared(((IFile) object).getProject())) return true; } return false; } public void refresh() { refreshHistory(true); } public Object getAdapter(Class adapter) { // TODO Auto-generated method stub return null; } public void dispose() { shutdown = true; if (resourceListener != null){ ResourcesPlugin.getWorkspace().removeResourceChangeListener(resourceListener); resourceListener = null; } //Cancel any incoming if (refreshFileHistoryJob != null) { if (refreshFileHistoryJob.getState() != Job.NONE) { refreshFileHistoryJob.cancel(); } } } public IFileRevision getCurrentFileRevision() { if (currentFileRevision != null) return currentFileRevision; if (file != null) currentFileRevision = new LocalFileRevision(file); return currentFileRevision; } private class RefreshFileHistory extends Job { private final static int NUMBER_OF_CATEGORIES = 4; private LocalFileHistory fileHistory; private AbstractHistoryCategory[] categories; private boolean grouping; private Object[] elementsToExpand; public RefreshFileHistory() { super(TeamUIMessages.LocalHistoryPage_FetchLocalHistoryMessage); } public void setFileHistory(LocalFileHistory fileHistory) { this.fileHistory = fileHistory; } public void setGrouping (boolean value){ this.grouping = value; } public IStatus run(IProgressMonitor monitor) { IStatus status = Status.OK_STATUS; if (fileHistory != null && !shutdown) { //If fileHistory termintates in a bad way, try to fetch the local //revisions only try { fileHistory.refresh(monitor); } catch (CoreException ex) { status = new TeamStatus(ex.getStatus().getSeverity(), TeamUIPlugin.ID, ex.getStatus().getCode(), ex.getMessage(), ex, file); } if (grouping) sortRevisions(); Utils.asyncExec(new Runnable() { public void run() { historyTableProvider.setFile(file); if (grouping) { mapExpandedElements(treeViewer.getExpandedElements()); treeViewer.getTree().setRedraw(false); treeViewer.setInput(categories); //if user is switching modes and already has expanded elements //selected try to expand those, else expand all if (elementsToExpand.length > 0) treeViewer.setExpandedElements(elementsToExpand); else { treeViewer.expandAll(); Object[] el = treeViewer.getExpandedElements(); if (el != null && el.length > 0) { treeViewer.setSelection(new StructuredSelection(el[0])); treeViewer.getTree().deselectAll(); } } treeViewer.getTree().setRedraw(true); } else { if (fileHistory.getFileRevisions().length > 0) { treeViewer.setInput(fileHistory); } else { categories = new AbstractHistoryCategory[] {getErrorMessage()}; treeViewer.setInput(categories); } } } }, treeViewer); } if (status != Status.OK_STATUS ) { this.setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); this.setProperty(IProgressConstants.NO_IMMEDIATE_ERROR_PROMPT_PROPERTY, Boolean.TRUE); } return status; } private void mapExpandedElements(Object[] expandedElements) { //store the names of the currently expanded categories in a map HashMap elementMap = new HashMap(); for (int i=0; i<expandedElements.length; i++){ elementMap.put(((DateHistoryCategory)expandedElements[i]).getName(), null); } //Go through the new categories and keep track of the previously expanded ones ArrayList expandable = new ArrayList(); for (int i = 0; i<categories.length; i++){ //check to see if this category is currently expanded if (elementMap.containsKey(categories[i].getName())){ expandable.add(categories[i]); } } elementsToExpand = new Object[expandable.size()]; elementsToExpand = (Object[]) expandable.toArray(new Object[expandable.size()]); } private boolean sortRevisions() { IFileRevision[] fileRevision = fileHistory.getFileRevisions(); //Create the 4 categories DateHistoryCategory[] tempCategories = new DateHistoryCategory[NUMBER_OF_CATEGORIES]; //Get a calendar instance initialized to the current time Calendar currentCal = Calendar.getInstance(); tempCategories[0] = new DateHistoryCategory(TeamUIMessages.HistoryPage_Today, currentCal, null); //Get yesterday Calendar yesterdayCal = Calendar.getInstance(); yesterdayCal.roll(Calendar.DAY_OF_YEAR, -1); tempCategories[1] = new DateHistoryCategory(TeamUIMessages.HistoryPage_Yesterday, yesterdayCal, null); //Get this month Calendar monthCal = Calendar.getInstance(); monthCal.set(Calendar.DAY_OF_MONTH, 1); tempCategories[2] = new DateHistoryCategory(TeamUIMessages.HistoryPage_ThisMonth, monthCal, yesterdayCal); //Everything before after week is previous tempCategories[3] = new DateHistoryCategory(TeamUIMessages.HistoryPage_Previous, null, monthCal); ArrayList finalCategories = new ArrayList(); for (int i = 0; i<NUMBER_OF_CATEGORIES; i++){ tempCategories[i].collectFileRevisions(fileRevision, false); if (tempCategories[i].hasRevisions()) finalCategories.add(tempCategories[i]); } //Assume that some revisions have been found boolean revisionsFound = true; if (finalCategories.size() == 0){ //no revisions found for the current mode, so add a message category finalCategories.add(getErrorMessage()); revisionsFound = false; } categories = (AbstractHistoryCategory[])finalCategories.toArray(new AbstractHistoryCategory[finalCategories.size()]); return revisionsFound; } private MessageHistoryCategory getErrorMessage(){ MessageHistoryCategory messageCategory = new MessageHistoryCategory(TeamUIMessages.LocalHistoryPage_NoRevisionsFound); return messageCategory; } } private class HistoryResourceListener implements IResourceChangeListener { /** * @see IResourceChangeListener#resourceChanged(IResourceChangeEvent) */ public void resourceChanged(IResourceChangeEvent event) { IResourceDelta root = event.getDelta(); if (file == null) return; IResourceDelta resourceDelta = root.findMember(file.getFullPath()); if (resourceDelta != null){ Display.getDefault().asyncExec(new Runnable() { public void run() { refresh(); } }); } } } }
true
true
private void contributeActions() { final IPreferenceStore store = TeamUIPlugin.getPlugin().getPreferenceStore(); //Group by Date groupByDateMode = new Action(TeamUIMessages.LocalHistoryPage_GroupRevisionsByDateAction, TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_DATES_CATEGORY)){ public void run() { groupingOn = !groupingOn; compareModeAction.setChecked(groupingOn); store.setValue(IPreferenceIds.PREF_GROUPBYDATE_MODE, groupingOn); refreshHistory(false); } }; groupingOn = store.getBoolean(IPreferenceIds.PREF_GROUPBYDATE_MODE); groupByDateMode.setChecked(groupingOn); groupByDateMode.setToolTipText(TeamUIMessages.LocalHistoryPage_GroupRevisionsByDateTip); groupByDateMode.setDisabledImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_DATES_CATEGORY)); groupByDateMode.setHoverImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_DATES_CATEGORY)); //Collapse All collapseAll = new Action(TeamUIMessages.LocalHistoryPage_CollapseAllAction, TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COLLAPSE_ALL)) { public void run() { treeViewer.collapseAll(); } }; collapseAll.setToolTipText(TeamUIMessages.LocalHistoryPage_CollapseAllTip); collapseAll.setDisabledImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COLLAPSE_ALL)); collapseAll.setHoverImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COLLAPSE_ALL)); //Compare Mode Action compareModeAction = new Action(TeamUIMessages.LocalHistoryPage_CompareModeAction,TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPARE_VIEW)) { public void run() { compareMode = !compareMode; compareModeAction.setChecked(compareMode); } }; compareModeAction.setToolTipText(TeamUIMessages.LocalHistoryPage_CompareModeTip); compareModeAction.setDisabledImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPARE_VIEW)); compareModeAction.setHoverImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPARE_VIEW)); compareModeAction.setChecked(false); // Click Compare action compareAction = new CompareRevisionAction(TeamUIMessages.LocalHistoryPage_CompareAction); treeViewer.getTree().addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e) { compareAction.setCurrentFileRevision(getCurrentFileRevision()); compareAction.selectionChanged((IStructuredSelection) treeViewer.getSelection()); } }); compareAction.setPage(this); openAction = new OpenRevisionAction(TeamUIMessages.LocalHistoryPage_OpenAction); treeViewer.getTree().addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e) { openAction.selectionChanged((IStructuredSelection) treeViewer.getSelection()); } }); openAction.setPage(this); OpenStrategy handler = new OpenStrategy(treeViewer.getTree()); handler.addOpenListener(new IOpenEventListener() { public void handleOpen(SelectionEvent e) { StructuredSelection tableStructuredSelection = (StructuredSelection) treeViewer.getSelection(); if (compareMode){ StructuredSelection sel = new StructuredSelection(new Object[] {getCurrentFileRevision(), tableStructuredSelection.getFirstElement()}); compareAction.selectionChanged(sel); compareAction.run(); } else { //Pass in the entire structured selection to allow for multiple editor openings StructuredSelection sel = tableStructuredSelection; openAction.selectionChanged(sel); openAction.run(); } } }); //Contribute actions to popup menu MenuManager menuMgr = new MenuManager(); Menu menu = menuMgr.createContextMenu(treeViewer.getTree()); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager menuMgr) { fillTableMenu(menuMgr); } }); menuMgr.setRemoveAllWhenShown(true); treeViewer.getTree().setMenu(menu); //Don't add the object contribution menu items if this page is hosted in a dialog IHistoryPageSite parentSite = getHistoryPageSite(); /*if (!parentSite.isModal()) { IWorkbenchPart part = parentSite.getPart(); if (part != null) { IWorkbenchPartSite workbenchPartSite = part.getSite(); workbenchPartSite.registerContextMenu(menuMgr, treeViewer); } IPageSite pageSite = parentSite.getWorkbenchPageSite(); if (pageSite != null) { IActionBars actionBars = pageSite.getActionBars(); // Contribute toggle text visible to the toolbar drop-down IMenuManager actionBarsMenu = actionBars.getMenuManager(); if (actionBarsMenu != null){ actionBarsMenu.add(toggleTextWrapAction); actionBarsMenu.add(new Separator()); actionBarsMenu.add(toggleTextAction); actionBarsMenu.add(toggleListAction); actionBarsMenu.add(new Separator()); actionBarsMenu.add(cvsHistoryFilter); actionBarsMenu.add(toggleFilterAction); } actionBars.updateActionBars(); } }*/
private void contributeActions() { final IPreferenceStore store = TeamUIPlugin.getPlugin().getPreferenceStore(); //Group by Date groupByDateMode = new Action(TeamUIMessages.LocalHistoryPage_GroupRevisionsByDateAction, TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_DATES_CATEGORY)){ public void run() { groupingOn = !groupingOn; store.setValue(IPreferenceIds.PREF_GROUPBYDATE_MODE, groupingOn); refreshHistory(false); } }; groupingOn = store.getBoolean(IPreferenceIds.PREF_GROUPBYDATE_MODE); groupByDateMode.setChecked(groupingOn); groupByDateMode.setToolTipText(TeamUIMessages.LocalHistoryPage_GroupRevisionsByDateTip); groupByDateMode.setDisabledImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_DATES_CATEGORY)); groupByDateMode.setHoverImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_DATES_CATEGORY)); //Collapse All collapseAll = new Action(TeamUIMessages.LocalHistoryPage_CollapseAllAction, TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COLLAPSE_ALL)) { public void run() { treeViewer.collapseAll(); } }; collapseAll.setToolTipText(TeamUIMessages.LocalHistoryPage_CollapseAllTip); collapseAll.setDisabledImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COLLAPSE_ALL)); collapseAll.setHoverImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COLLAPSE_ALL)); //Compare Mode Action compareModeAction = new Action(TeamUIMessages.LocalHistoryPage_CompareModeAction,TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPARE_VIEW)) { public void run() { compareMode = !compareMode; compareModeAction.setChecked(compareMode); } }; compareModeAction.setToolTipText(TeamUIMessages.LocalHistoryPage_CompareModeTip); compareModeAction.setDisabledImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPARE_VIEW)); compareModeAction.setHoverImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPARE_VIEW)); compareModeAction.setChecked(false); // Click Compare action compareAction = new CompareRevisionAction(TeamUIMessages.LocalHistoryPage_CompareAction); treeViewer.getTree().addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e) { compareAction.setCurrentFileRevision(getCurrentFileRevision()); compareAction.selectionChanged((IStructuredSelection) treeViewer.getSelection()); } }); compareAction.setPage(this); openAction = new OpenRevisionAction(TeamUIMessages.LocalHistoryPage_OpenAction); treeViewer.getTree().addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e) { openAction.selectionChanged((IStructuredSelection) treeViewer.getSelection()); } }); openAction.setPage(this); OpenStrategy handler = new OpenStrategy(treeViewer.getTree()); handler.addOpenListener(new IOpenEventListener() { public void handleOpen(SelectionEvent e) { StructuredSelection tableStructuredSelection = (StructuredSelection) treeViewer.getSelection(); if (compareMode){ StructuredSelection sel = new StructuredSelection(new Object[] {getCurrentFileRevision(), tableStructuredSelection.getFirstElement()}); compareAction.selectionChanged(sel); compareAction.run(); } else { //Pass in the entire structured selection to allow for multiple editor openings StructuredSelection sel = tableStructuredSelection; openAction.selectionChanged(sel); openAction.run(); } } }); //Contribute actions to popup menu MenuManager menuMgr = new MenuManager(); Menu menu = menuMgr.createContextMenu(treeViewer.getTree()); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager menuMgr) { fillTableMenu(menuMgr); } }); menuMgr.setRemoveAllWhenShown(true); treeViewer.getTree().setMenu(menu); //Don't add the object contribution menu items if this page is hosted in a dialog IHistoryPageSite parentSite = getHistoryPageSite(); /*if (!parentSite.isModal()) { IWorkbenchPart part = parentSite.getPart(); if (part != null) { IWorkbenchPartSite workbenchPartSite = part.getSite(); workbenchPartSite.registerContextMenu(menuMgr, treeViewer); } IPageSite pageSite = parentSite.getWorkbenchPageSite(); if (pageSite != null) { IActionBars actionBars = pageSite.getActionBars(); // Contribute toggle text visible to the toolbar drop-down IMenuManager actionBarsMenu = actionBars.getMenuManager(); if (actionBarsMenu != null){ actionBarsMenu.add(toggleTextWrapAction); actionBarsMenu.add(new Separator()); actionBarsMenu.add(toggleTextAction); actionBarsMenu.add(toggleListAction); actionBarsMenu.add(new Separator()); actionBarsMenu.add(cvsHistoryFilter); actionBarsMenu.add(toggleFilterAction); } actionBars.updateActionBars(); } }*/
diff --git a/src/edu/calpoly/csc/pulseman/gameobject/Goal.java b/src/edu/calpoly/csc/pulseman/gameobject/Goal.java index 9ad8dae..4b1b4ae 100644 --- a/src/edu/calpoly/csc/pulseman/gameobject/Goal.java +++ b/src/edu/calpoly/csc/pulseman/gameobject/Goal.java @@ -1,29 +1,38 @@ package edu.calpoly.csc.pulseman.gameobject; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; +import org.newdawn.slick.SlickException; import org.newdawn.slick.geom.Rectangle; +import org.newdawn.slick.particles.ParticleEmitter; +import org.newdawn.slick.particles.ParticleSystem; +import org.newdawn.slick.particles.effects.FireEmitter; public class Goal extends Collidable { - public static Image image; + private static Image image; + private ParticleSystem ps; - public Goal(int x, int y) { + public Goal(int x, int y) throws SlickException { super(new Rectangle(x, y, image.getWidth(), image.getHeight())); + ps = new ParticleSystem(new Image("res/orb.png")); + ps.addEmitter(new FireEmitter()); } public static void init(Image image) { Goal.image = image; } @Override public void render(GameContainer gc, Graphics g) { - g.drawImage(image, getHitBox().getX(), getHitBox().getY()); + //g.drawImage(image, getHitBox().getX(), getHitBox().getY()); + ps.render(getHitBox().getX() + getHitBox().getWidth() / 2.0f, + getHitBox().getY() + getHitBox().getHeight() / 2.0f); } @Override public void update(GameContainer gc, int delta) { - + ps.update(delta); } }
false
false
null
null
diff --git a/nuxeo-webengine-core/src/main/java/org/nuxeo/ecm/webengine/login/WebEngineSessionManager.java b/nuxeo-webengine-core/src/main/java/org/nuxeo/ecm/webengine/login/WebEngineSessionManager.java index 5b3a6546..95d17b13 100644 --- a/nuxeo-webengine-core/src/main/java/org/nuxeo/ecm/webengine/login/WebEngineSessionManager.java +++ b/nuxeo-webengine-core/src/main/java/org/nuxeo/ecm/webengine/login/WebEngineSessionManager.java @@ -1,59 +1,63 @@ package org.nuxeo.ecm.webengine.login; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.ecm.core.api.NuxeoPrincipal; import org.nuxeo.ecm.platform.ui.web.auth.CachableUserIdentificationInfo; import org.nuxeo.ecm.platform.ui.web.auth.plugins.DefaultSessionManager; import org.nuxeo.ecm.platform.usermanager.UserManager; import org.nuxeo.ecm.webengine.session.UserSession; import org.nuxeo.runtime.api.Framework; public class WebEngineSessionManager extends DefaultSessionManager { //TODO work on skin request to avoid hardcoding paths private static final String RESOURCES_PATH = "/nuxeo/site/files/"; private static final Log log = LogFactory.getLog(WebEngineSessionManager.class); private static boolean useSharedAnonymousSession = false; @Override public boolean canBypassRequest(ServletRequest request) { // static resources don't require Authentication return ((HttpServletRequest) request).getRequestURI().startsWith(RESOURCES_PATH); } @Override public void onAuthenticatedSessionCreated(ServletRequest request, HttpSession httpSession, CachableUserIdentificationInfo cachebleUserInfo) { UserSession userSession = null; if (useSharedAnonymousSession && ((NuxeoPrincipal) cachebleUserInfo.getPrincipal()).isAnonymous()) { try { UserManager um = Framework.getService(UserManager.class); userSession = UserSession.getAnonymousSession(um); } catch (Exception e) { log.error("Error during Anonymous session creation", e); log.warn("Std UserSession will be used instead"); // fall back to default session } } if (userSession == null) { // create WE custom UserSession userSession = new UserSession(cachebleUserInfo.getPrincipal(), cachebleUserInfo.getUserInfo().getPassword()); } + // check for a valid session + if (httpSession == null) { + httpSession = ((HttpServletRequest)request).getSession(); + } UserSession.setCurrentSession(httpSession, userSession); } @Override public boolean needResetLogin(ServletRequest req) { String p = ((HttpServletRequest) req).getPathInfo(); return p != null && p.startsWith("/login"); } } diff --git a/nuxeo-webengine-core/src/main/java/org/nuxeo/ecm/webengine/session/UserSession.java b/nuxeo-webengine-core/src/main/java/org/nuxeo/ecm/webengine/session/UserSession.java index a31d4b4b..040094b5 100644 --- a/nuxeo-webengine-core/src/main/java/org/nuxeo/ecm/webengine/session/UserSession.java +++ b/nuxeo-webengine-core/src/main/java/org/nuxeo/ecm/webengine/session/UserSession.java @@ -1,343 +1,348 @@ /* * (C) Copyright 2006-2008 Nuxeo SAS (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * 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. * * Contributors: * bstefanescu * * $Id$ */ package org.nuxeo.ecm.webengine.session; import java.security.Principal; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.security.auth.Subject; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionBindingListener; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.ecm.core.api.ClientException; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.repository.Repository; import org.nuxeo.ecm.core.api.repository.RepositoryManager; import org.nuxeo.ecm.platform.usermanager.UserManager; import org.nuxeo.runtime.api.Framework; /** * Used to store user session. This object is cached in a the HTTP session * Principal, subject and credentials are immutable per user session * * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> */ // TODO: should be synchronized? concurrent access may happen for the same session public class UserSession extends HashMap<String, Object> implements HttpSessionBindingListener { private static final long serialVersionUID = 260562970988817064L; private static final Log log = LogFactory.getLog(UserSession.class); protected static UserSession anonymous; protected Map<Class<?>, ComponentMap<?>> comps = new HashMap<Class<?>, ComponentMap<?>>(); public static UserSession getCurrentSession(HttpSession session) { + if (session == null) { + return null; + } return (UserSession) session.getAttribute("nuxeo.webengine.user_session"); } public static void setCurrentSession(HttpSession session, UserSession us) { // UserSession currentUs = (UserSession)session.getAttribute("nuxeo.webengine.user_session"); // if (currentUs != null) { // // } - session.setAttribute("nuxeo.webengine.user_session", us); + if (session != null) { + session.setAttribute("nuxeo.webengine.user_session", us); + } } public static UserSession getAnonymousSession(UserManager mgr) throws ClientException { if (anonymous == null) { anonymous = createAnonymousSession(mgr); } return anonymous; } public static UserSession createAnonymousSession(UserManager mgr) throws ClientException { String userId = mgr.getAnonymousUserId(); if (userId == null) { throw new IllegalStateException("User anonymous cannot be created"); } return new UserSession(mgr.getPrincipal(userId), userId); } public static void destroyAnonynousSession() { if (anonymous != null && anonymous.coreSession != null) { anonymous.coreSession.destroy(); } anonymous.coreSession = null; } protected final Subject subject; protected final Principal principal; protected final Object credentials; protected transient CoreSession coreSession; public UserSession(Principal principal) { this(principal, null); } public UserSession(Principal principal, String password) { this(principal, password == null ? new char[0] : password.toCharArray()); } public UserSession(Principal principal, Object credentials) { this.principal = principal; this.credentials = credentials; Set<Principal> principals = new HashSet<Principal>(); Set<Object> publicCredentials = new HashSet<Object>(); Set<Object> privateCredentials = new HashSet<Object>(); principals.add(principal); publicCredentials.add(credentials); subject = new Subject(true, principals, publicCredentials, privateCredentials); } public void setCoreSession(CoreSession coreSession) { this.coreSession = coreSession; } /** * Gets a core session. * <p> * If it does not already exist, it will be opened against the * given repository. * * @param repoName * @return the core session */ public CoreSession getCoreSession(String repoName) { if (coreSession == null) { synchronized (this) { if (coreSession == null) { try { coreSession = openSession(repoName); } catch (Exception e) { e.printStackTrace(); //TODO } } } } return coreSession; } /** * Gets a core session. * <p> * If not already opened, opens a new core session against the default * repository. * * @return */ public CoreSession getCoreSession() { return getCoreSession(null); } /** * Whether or not this is the shared anonymous session. */ public boolean isAnonymous() { return this == anonymous; } public Principal getPrincipal() { return principal; } public Object getCredentials() { return credentials; } public Subject getSubject() { return subject; } public static CoreSession openSession(String repoName) throws Exception { RepositoryManager rm = Framework.getService(RepositoryManager.class); Repository repo = null; if (repoName== null) { repo = rm.getDefaultRepository(); } else { repo = rm.getRepository(repoName); } if (repo == null) { throw new SessionException("Unable to get " + repoName + " repository"); } return repo.open(); } public void valueBound(HttpSessionBindingEvent event) { // the user session was bound to the HTTP session install(event.getSession()); } public void valueUnbound(HttpSessionBindingEvent event) { // the user session was removed from the HTTP session uninstall(event.getSession()); // System.out.println("unbound: "+event.getName() + " = " +event.getValue()); //HttpSess // CoreSession cs = (CoreSession)session.getAttribute(DefaultWebContext.CORESESSION_KEY); // if (cs != null) { // if (!DefaultWebContext.isAnonymousSession(cs)) { // propagate(currentIdentity); // cs.destroy(); // } // } } protected void install(HttpSession session) { if (log.isDebugEnabled()) { log.debug("Installing user session"); } } protected synchronized void uninstall(HttpSession session) { if (log.isDebugEnabled()) { log.debug("Uninstalling user session"); } // destroy all components for (Map.Entry<Class<?>,ComponentMap<?>> entry : comps.entrySet()) { try { entry.getValue().destroy(this); } catch (SessionException e) { log.error("Failed to destroy component: "+entry.getKey(), e); } } comps = new HashMap<Class<?>, ComponentMap<?>>(); // destroy core session if (coreSession != null) { coreSession.destroy(); coreSession = null; } } /** * Finds an existing component. * <p> * The component state will not be modified before being returned * as in {@link #getComponent(Class, String)}. * <p> * If the component was not found in that session, returns null. * * @param <T> * @param type * @param name * @return */ @SuppressWarnings("unchecked") public synchronized <T extends Component> T findComponent(Class<T> type, String name) { ComponentMap<T> map = (ComponentMap<T>)comps.get(type); if (map == null) { return null; } if (name == null) { return map.getComponent(); } else { return type.cast(map.get(name)); } } /** * Gets a component given its class and an optional name. * <p> * If the component was not yet created in this session, it will * be created and registered against the session. * * @param <T> * @param type * @param name * @return * @throws SessionException */ @SuppressWarnings("unchecked") public synchronized <T extends Component> T getComponent(Class<T> type, String name) throws SessionException { ComponentMap<T> map = (ComponentMap<T>) comps.get(type); T comp = null; if (map == null) { map = new ComponentMap<T>(); comps.put(type, map); } else { if (name == null) { comp = map.getComponent(); } else { comp = type.cast(map.get(name)); } if (comp != null) { return comp; } } // component not found try { comp = type.newInstance(); } catch (Exception e) { throw new SessionException("Failed to instantiate component: "+type, e); } comp.initialize(this, name); if (name == null) { map.setComponent(comp); } else { map.put(name, comp); } return type.cast(comp); } public <T extends Component> T getComponent(Class<T> type) throws SessionException { return getComponent(type, null); } @SuppressWarnings("unchecked") public <T extends Component> T getComponent(String typeName, String name) throws SessionException { try { Class<T> type = (Class<T>) Class.forName(typeName); return getComponent(type, name); } catch (ClassNotFoundException e) { throw new SessionException("Could not find component class: " + typeName, e); } } /** * Gets component by ID. * <p> * The ID is of the form <code>type#name</code> for non-null names * and <code>type</code> for null names. * * @param <T> * @param id * @return */ @SuppressWarnings("unchecked") public <T extends Component> T getComponent(String id) throws SessionException { int p = id.lastIndexOf('#'); if (p > -1) { return (T) getComponent(id.substring(0, p), id.substring(p + 1)); } else { return (T) getComponent(id, null); } } }
false
false
null
null
diff --git a/src/main/java/de/krkm/trex/inference/concept/ConceptDisjointnessInferenceStepProvider.java b/src/main/java/de/krkm/trex/inference/concept/ConceptDisjointnessInferenceStepProvider.java index 70bf960..c5157e1 100644 --- a/src/main/java/de/krkm/trex/inference/concept/ConceptDisjointnessInferenceStepProvider.java +++ b/src/main/java/de/krkm/trex/inference/concept/ConceptDisjointnessInferenceStepProvider.java @@ -1,195 +1,194 @@ package de.krkm.trex.inference.concept; import de.krkm.trex.booleanexpressions.ExpressionMinimizer; import de.krkm.trex.booleanexpressions.OrExpression; import de.krkm.trex.inference.InferenceStepProvider; import de.krkm.trex.inference.Matrix; import de.krkm.trex.reasoner.TRexReasoner; import de.krkm.trex.util.Util; import org.semanticweb.owlapi.model.*; import java.util.HashSet; import java.util.Set; import static de.krkm.trex.booleanexpressions.ExpressionMinimizer.*; public class ConceptDisjointnessInferenceStepProvider extends InferenceStepProvider { private TRexReasoner reasoner; private OWLDataFactory factory; private Matrix matrix; @Override public void initMatrix(OWLOntology ontology, TRexReasoner reasoner, Matrix matrix) { this.reasoner = reasoner; this.matrix = matrix; this.factory = ontology.getOWLOntologyManager().getOWLDataFactory(); int dimension = matrix.getNamingManager().getNumberOfConcepts(); matrix.setMatrix(new boolean[dimension][dimension]); matrix.setExplanations(new OrExpression[dimension][dimension]); Set<OWLDisjointClassesAxiom> disjointClassesAxiomSet = ontology.getAxioms(AxiomType.DISJOINT_CLASSES); for (OWLDisjointClassesAxiom a : disjointClassesAxiomSet) { for (OWLDisjointClassesAxiom p : a.asPairwiseAxioms()) { Set<OWLClass> disjointClassesSet = a.getClassesInSignature(); OWLClass[] disjointClasses = disjointClassesSet.toArray(new OWLClass[disjointClassesSet.size()]); for (int i = 0; i < disjointClasses.length; i++) { for (int j = 0; j < i; j++) { if (i == j) { continue; } if (!disjointClasses[i].isAnonymous() && !disjointClasses[j].isAnonymous()) { String iriI = Util.getFragment(disjointClasses[i].asOWLClass().getIRI().toString()); String iriJ = Util.getFragment(disjointClasses[j].asOWLClass().getIRI().toString()); matrix.set(iriI, iriJ, true); int idI = matrix.getNamingManager().getConceptId(iriI); int idJ = matrix.getNamingManager().getConceptId(iriJ); matrix.set(iriI, iriJ, true); matrix.addExplanation(idI, idJ, or(and(literal(p.getAxiomWithoutAnnotations())))); } } } } } } @Override public boolean infer(Matrix matrix, int row, int col) { boolean mod = false; for (int i = 0; i < matrix.dimensionRow; i++) { if (reasoner.conceptSubsumption.matrix[row][i] && matrix.get(col, i)) { matrix.set(row, col, true); mod = matrix.addExplanation(row, col, ExpressionMinimizer.flatten(reasoner.getConceptSubsumption().getExplanation(row, i), matrix.getExplanation(i, col))) || mod; } } return mod; } @Override public String getAxiomRepresentation(Matrix matrix, int row, int col) { if (matrix.get(row, col)) { return String.format("DisjointWith(%s, %s)", matrix.getNamingManager().getConceptIRI(row), matrix.getNamingManager().getConceptIRI(col)); } return null; } @Override public OWLAxiom getAxiom(Matrix matrix, int row, int col) { if (matrix.get(row, col)) { HashSet<OWLClass> concepts = new HashSet<OWLClass>(); concepts.add(factory.getOWLClass(IRI.create(getIRIWithNamespace( matrix.getNamingManager().getConceptIRI(row))))); concepts.add(factory.getOWLClass(IRI.create(getIRIWithNamespace( matrix.getNamingManager().getConceptIRI(col))))); return factory.getOWLDisjointClassesAxiom(concepts); } return null; } @Override public String getIdentifier() { return "DisjointWith"; } @Override public boolean isSymmetric() { return true; } @Override public int resolveRowIRI(String iri) { return reasoner.getNamingManager().getConceptId(iri); } @Override public String resolveRowID(int id) { return reasoner.getNamingManager().getConceptIRI(id); } @Override public AxiomType getAxiomType() { return AxiomType.DISJOINT_CLASSES; } @Override public boolean isEntailed(OWLAxiom axiom) { isProcessable(axiom); boolean res = false; Set<OWLClass> disjointClassesSet = axiom.getClassesInSignature(); OWLClass[] disjointClasses = disjointClassesSet.toArray(new OWLClass[disjointClassesSet.size()]); for (int i = 0; i < disjointClasses.length; i++) { for (int j = 0; j < i; j++) { if (i == j) { continue; } String iriI = Util.getFragment(disjointClasses[i].asOWLClass().getIRI().toString()); String iriJ = Util.getFragment(disjointClasses[j].asOWLClass().getIRI().toString()); res = matrix.get(iriI, iriJ) || res; // if entailed: stop processing if (res) { return true; } } } return res; } @Override public OrExpression getExplanation(OWLAxiom axiom) { isProcessable(axiom); OrExpression overall = null; Set<OWLClass> disjointClassesSet = axiom.getClassesInSignature(); OWLClass[] disjointClasses = disjointClassesSet.toArray(new OWLClass[disjointClassesSet.size()]); for (int i = 0; i < disjointClasses.length; i++) { - for (int j = 0; j < i; j++) { - if (i == j) { - continue; - } + for (int j = 0; j <= i; j++) { int idI = resolveRowIRI(Util.getFragment(disjointClasses[i].asOWLClass().getIRI().toString())); int idJ = resolveColIRI(Util.getFragment(disjointClasses[j].asOWLClass().getIRI().toString())); if (matrix.get(idI, idJ)) { if (overall == null) { overall = matrix.getExplanation(idI, idJ); } else { System.out.println("Adding to overall: " + overall.toString()); overall = ExpressionMinimizer.flatten(overall, matrix.getExplanation(idI, idJ)); System.out.println("Adding to overall: " + overall.toString()); } } } } - ExpressionMinimizer.minimize(overall); + if (overall != null) { + ExpressionMinimizer.minimize(overall); + } return overall; } @Override public void addAxiom(OWLAxiom axiom) { isProcessable(axiom); Set<OWLClass> disjointClassesSet = axiom.getClassesInSignature(); OWLClass[] disjointClasses = disjointClassesSet.toArray(new OWLClass[disjointClassesSet.size()]); for (int i = 0; i < disjointClasses.length; i++) { for (int j = 0; j < i; j++) { if (i == j) { continue; } String iriI = Util.getFragment(disjointClasses[i].asOWLClass().getIRI().toString()); String iriJ = Util.getFragment(disjointClasses[j].asOWLClass().getIRI().toString()); matrix.set(iriI, iriJ, true); int indexA = resolveRowIRI(iriI); int indexB = resolveColIRI(iriJ); matrix.addExplanation(indexA, indexB, or(and(literal(axiom)))); } } } } diff --git a/src/main/java/de/krkm/trex/inference/property/PropertyDisjointnessInferenceStepProvider.java b/src/main/java/de/krkm/trex/inference/property/PropertyDisjointnessInferenceStepProvider.java index 0eddf62..8189da8 100644 --- a/src/main/java/de/krkm/trex/inference/property/PropertyDisjointnessInferenceStepProvider.java +++ b/src/main/java/de/krkm/trex/inference/property/PropertyDisjointnessInferenceStepProvider.java @@ -1,197 +1,196 @@ package de.krkm.trex.inference.property; import de.krkm.trex.booleanexpressions.ExpressionMinimizer; import de.krkm.trex.booleanexpressions.OrExpression; import de.krkm.trex.inference.InferenceStepProvider; import de.krkm.trex.inference.Matrix; import de.krkm.trex.reasoner.TRexReasoner; import de.krkm.trex.util.Util; import org.semanticweb.owlapi.model.*; import java.util.HashSet; import java.util.Set; import static de.krkm.trex.booleanexpressions.ExpressionMinimizer.*; public class PropertyDisjointnessInferenceStepProvider extends InferenceStepProvider { private TRexReasoner reasoner; private OWLDataFactory factory; private Matrix matrix; @Override public void initMatrix(OWLOntology ontology, TRexReasoner reasoner, Matrix matrix) { this.matrix = matrix; int dimension = matrix.getNamingManager().getNumberOfProperties(); matrix.setMatrix(new boolean[dimension][dimension]); matrix.setExplanations(new OrExpression[dimension][dimension]); this.reasoner = reasoner; this.factory = ontology.getOWLOntologyManager().getOWLDataFactory(); Set<OWLDisjointObjectPropertiesAxiom> disjointPropertyAxiomSet = ontology.getAxioms( AxiomType.DISJOINT_OBJECT_PROPERTIES); for (OWLDisjointObjectPropertiesAxiom a : disjointPropertyAxiomSet) { Set<OWLObjectProperty> disjointPropertySet = a.getObjectPropertiesInSignature(); OWLObjectProperty[] disjointProperties = disjointPropertySet.toArray( new OWLObjectProperty[disjointPropertySet.size()]); for (int i = 0; i < disjointProperties.length; i++) { for (int j = 0; j < disjointProperties.length; j++) { if (i == j) { continue; } if (!disjointProperties[i].isAnonymous() && !disjointProperties[j].isAnonymous()) { String iriI = Util.getFragment(disjointProperties[i].asOWLObjectProperty().getIRI().toString()); String iriJ = Util.getFragment(disjointProperties[j].asOWLObjectProperty().getIRI().toString()); matrix.set(iriI, iriJ, true); int idI = matrix.getNamingManager().getPropertyId(iriI); int idJ = matrix.getNamingManager().getPropertyId(iriJ); matrix.set(iriI, iriJ, true); matrix.addExplanation(idI, idJ, or(and(literal(a.getAxiomWithoutAnnotations())))); } } } } } @Override public boolean infer(Matrix matrix, int row, int col) { boolean mod = false; for (int i = 0; i < reasoner.getPropertySubsumption().dimensionRow; i++) { if (reasoner.propertySubsumption.matrix[row][i] && matrix.get(i, col)) { matrix.set(row, col, true); mod = matrix.addExplanation(row, col, ExpressionMinimizer.flatten(reasoner.getPropertySubsumption().getExplanation(row, i), matrix.getExplanation(i, col))) || mod; } } return mod; } @Override public String getAxiomRepresentation(Matrix matrix, int row, int col) { if (matrix.get(row, col)) { return String.format("DisjointObjectProperty(%s, %s)", matrix.getNamingManager().getConceptIRI(row), matrix.getNamingManager().getConceptIRI(col)); } return null; } public OWLAxiom getAxiom(Matrix matrix, int row, int col) { if (matrix.get(row, col)) { HashSet<OWLObjectProperty> props = new HashSet<OWLObjectProperty>(); props.add(factory.getOWLObjectProperty(IRI.create(getIRIWithNamespace( matrix.getNamingManager().getPropertyIRI(row))))); props.add(factory.getOWLObjectProperty(IRI.create(getIRIWithNamespace( matrix.getNamingManager().getPropertyIRI(col))))); return factory.getOWLDisjointObjectPropertiesAxiom(props); } return null; } @Override public String getIdentifier() { return "DisjointObjectProperty"; } @Override public boolean isSymmetric() { return true; } @Override public int resolveRowIRI(String iri) { return reasoner.getNamingManager().getPropertyId(iri); } @Override public String resolveRowID(int id) { return reasoner.getNamingManager().getPropertyIRI(id); } @Override public AxiomType getAxiomType() { return AxiomType.DISJOINT_OBJECT_PROPERTIES; } @Override public boolean isEntailed(OWLAxiom axiom) { isProcessable(axiom); boolean res = false; Set<OWLObjectProperty> disjointPropertySet = axiom.getObjectPropertiesInSignature(); OWLObjectProperty[] disjointClasses = disjointPropertySet.toArray( new OWLObjectProperty[disjointPropertySet.size()]); for (int i = 0; i < disjointClasses.length; i++) { for (int j = 0; j < i; j++) { if (i == j) { continue; } String iriI = Util.getFragment(disjointClasses[i].asOWLObjectProperty().getIRI().toString()); String iriJ = Util.getFragment(disjointClasses[j].asOWLObjectProperty().getIRI().toString()); res = matrix.get(iriI, iriJ) || res; if (res) { return true; } } } return res; } @Override public OrExpression getExplanation(OWLAxiom axiom) { isProcessable(axiom); OrExpression overall = null; Set<OWLObjectProperty> disjointPropertySet = axiom.getObjectPropertiesInSignature(); OWLObjectProperty[] disjointClasses = disjointPropertySet.toArray( new OWLObjectProperty[disjointPropertySet.size()]); for (int i = 0; i < disjointClasses.length; i++) { - for (int j = 0; j < i; j++) { - if (i == j) { - continue; - } + for (int j = 0; j <= i; j++) { int idI = resolveRowIRI(Util.getFragment(disjointClasses[i].asOWLObjectProperty().getIRI().toString())); int idJ = resolveColIRI(Util.getFragment(disjointClasses[j].asOWLObjectProperty().getIRI().toString())); if (matrix.get(idI, idJ)) { if (overall == null) { overall = matrix.getExplanation(idI, idJ); } else { System.out.println("Adding to overall: " + overall.toString()); overall = ExpressionMinimizer.flatten(overall, matrix.getExplanation(idI, idJ)); System.out.println("Adding to overall: " + overall.toString()); } } } } - ExpressionMinimizer.minimize(overall); + if (overall != null) { + ExpressionMinimizer.minimize(overall); + } return overall; } @Override public void addAxiom(OWLAxiom axiom) { isProcessable(axiom); Set<OWLObjectProperty> disjointPropertySet = axiom.getObjectPropertiesInSignature(); OWLObjectProperty[] disjointClasses = disjointPropertySet.toArray( new OWLObjectProperty[disjointPropertySet.size()]); for (int i = 0; i < disjointClasses.length; i++) { for (int j = 0; j < i; j++) { if (i == j) { continue; } String iriI = Util.getFragment(disjointClasses[i].asOWLObjectProperty().getIRI().toString()); String iriJ = Util.getFragment(disjointClasses[j].asOWLObjectProperty().getIRI().toString()); matrix.set(iriI, iriJ, true); int indexA = resolveRowIRI(iriI); int indexB = resolveColIRI(iriJ); matrix.addExplanation(indexA, indexB, or(and(literal(axiom)))); } } } } diff --git a/src/main/java/de/krkm/trex/reasoner/TRexReasoner.java b/src/main/java/de/krkm/trex/reasoner/TRexReasoner.java index 1212bb3..96d127b 100644 --- a/src/main/java/de/krkm/trex/reasoner/TRexReasoner.java +++ b/src/main/java/de/krkm/trex/reasoner/TRexReasoner.java @@ -1,451 +1,455 @@ package de.krkm.trex.reasoner; import de.krkm.trex.booleanexpressions.ExpressionMinimizer; import de.krkm.trex.booleanexpressions.OrExpression; import de.krkm.trex.inference.Matrix; import de.krkm.trex.inference.concept.ConceptDisjointnessInferenceStepProvider; import de.krkm.trex.inference.concept.SubClassOfInferenceStepProvider; import de.krkm.trex.inference.property.*; import org.semanticweb.owlapi.model.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Set; /** * Encapsulates the reasoning service * * @author Daniel Fleischhacker <daniel@informatik.uni-mannheim.de> */ public class TRexReasoner { private OWLOntology ontology; private OntologyNamingManager namingManager; private Logger log = LoggerFactory.getLogger(TRexReasoner.class); public Matrix conceptSubsumption; public Matrix conceptDisjointness; public Matrix propertySubsumption; public Matrix propertyDisjointness; public Matrix propertyDomain; public Matrix propertyRange; public Matrix propertyUnsatisfiability; private boolean conceptOnly; private HashMap<AxiomType, ArrayList<Matrix>> typeToMatrix = new HashMap<AxiomType, ArrayList<Matrix>>(); private OWLDataFactory dataFactory; public TRexReasoner(OWLOntology ontology) { this(ontology, false); } /** * Initializes the reasoner to perform inference on the given ontology. * * @param ontology ontology to perform inference on */ public TRexReasoner(OWLOntology ontology, boolean conceptOnly) { this.conceptOnly = conceptOnly; this.ontology = ontology; dataFactory = ontology.getOWLOntologyManager().getOWLDataFactory(); namingManager = new OntologyNamingManager(ontology); conceptSubsumption = new Matrix(ontology, this, namingManager, new SubClassOfInferenceStepProvider()); registerType(conceptSubsumption); materializeConceptSubsumption(); conceptDisjointness = new Matrix(ontology, this, namingManager, new ConceptDisjointnessInferenceStepProvider()); registerType(conceptDisjointness); materializeConceptDisjointness(); if (!conceptOnly) { propertySubsumption = new Matrix(ontology, this, namingManager, new SubPropertyOfInferenceStepProvider()); registerType(propertySubsumption); materializePropertySubsumption(); propertyDisjointness = new Matrix(ontology, this, namingManager, new PropertyDisjointnessInferenceStepProvider()); registerType(propertyDisjointness); materializePropertyDisjointness(); propertyDomain = new Matrix(ontology, this, namingManager, new PropertyDomainInferenceStepProvider()); registerType(propertyDomain); materializePropertyDomain(); propertyRange = new Matrix(ontology, this, namingManager, new PropertyRangeInferenceStepProvider()); registerType(propertyRange); materializePropertyRange(); propertyUnsatisfiability = new Matrix(ontology, this, namingManager, new PropertyUnsatisfiabilityInferenceProvider()); registerType(propertyUnsatisfiability); materializePropertyUnsatisfiability(); } } /** * Re-runs the materialization step for this reasoner. In this process only new axioms are considered which do not * introduce new properties or concepts. */ public void rematerialize() { for (ArrayList<Matrix> matrices : typeToMatrix.values()) { for (Matrix m : matrices) { m.materialize(); } } } /** * Registers the given matrix to the reasoner system. * * @param matrix matrix to register in reasoner */ public void registerType(Matrix matrix) { if (!typeToMatrix.containsKey(matrix.getAxiomType())) { typeToMatrix.put(matrix.getAxiomType(), new ArrayList<Matrix>()); } typeToMatrix.get(matrix.getAxiomType()).add(matrix); } /** * Returns the naming manager used by this reasoner * * @return naming manager of this reasoner */ public OntologyNamingManager getNamingManager() { return namingManager; } /** * Returns the matrix used for concept subsumption * * @return matrix used for concept subsumption */ public Matrix getConceptSubsumption() { return conceptSubsumption; } /** * Returns the matrix used for concept disjointness * * @return matrix used for concept disjointness */ public Matrix getConceptDisjointness() { return conceptDisjointness; } /** * Returns the matrix used for property subsumption * * @return matrix used for property subsumption */ public Matrix getPropertySubsumption() { return propertySubsumption; } /** * Returns the matrix used for property disjointness * * @return matrix used for property disjointness */ public Matrix getPropertyDisjointness() { return propertyDisjointness; } /** * Returns the matrix used for property domains * * @return matrix used for property domains */ public Matrix getPropertyDomain() { return propertyDomain; } /** * Returns the matrix used for property ranges * * @return matrix used for property ranges */ public Matrix getPropertyRange() { return propertyRange; } /** * Starts materialization of derivable concept-subsumption axioms */ public void materializeConceptSubsumption() { conceptSubsumption.materialize(); } /** * Starts materializing of derivable concept disjointness axioms */ public void materializeConceptDisjointness() { conceptDisjointness.materialize(); } /** * Starts materialization of derivable property-subsumption axioms */ public void materializePropertySubsumption() { propertySubsumption.materialize(); } /** * Starts materializing of derivable property disjointness axioms */ public void materializePropertyDisjointness() { propertyDisjointness.materialize(); } /** * Starts materializing of derivable property disjointness axioms */ public void materializePropertyDomain() { propertyDomain.materialize(); } /** * Starts materializing of derivable property disjointness axioms */ public void materializePropertyRange() { propertyRange.materialize(); } private void materializePropertyUnsatisfiability() { propertyUnsatisfiability.materialize(); } /** * Returns all axioms supported by this reasoner and entailed by the ontology. * * @return all axioms supported by this reasoner and entailed by the ontology */ public Set<OWLAxiom> getAxioms() { HashSet<OWLAxiom> res = new HashSet<OWLAxiom>(); res.addAll(conceptSubsumption.getOWLAxioms()); res.addAll(conceptDisjointness.getOWLAxioms()); if (!conceptOnly) { res.addAll(propertySubsumption.getOWLAxioms()); res.addAll(propertyDomain.getOWLAxioms()); res.addAll(propertyDisjointness.getOWLAxioms()); res.addAll(propertyRange.getOWLAxioms()); } return res; } /** * Adds the given axiom into the ontology which is managed by this reasoner instance. Afterwards, a * rematerialization using {@link #rematerialize()} might be required. * * @param axiom axiom to add into ontology */ public void addAxiom(OWLAxiom axiom) { for (Matrix relevantMatrix : typeToMatrix.get(axiom.getAxiomType())) { relevantMatrix.addAxiom(axiom); } ontology.getOWLOntologyManager().addAxiom(ontology, axiom); } /** * Determines whether the given axiom is entailed by the ontology. * * @param axiom axiom to check entailment for * @return true if the axiom is entailed by the ontology, false otherwise */ public boolean isEntailed(OWLAxiom axiom) { if (!typeToMatrix.containsKey(axiom.getAxiomType())) { throw new UnsupportedOperationException( "Reasoner unable to handle axiom type: " + axiom.getAxiomType()); } for (Matrix relevantMatrix : typeToMatrix.get(axiom.getAxiomType())) { if (relevantMatrix.isEntailed(axiom)) { return true; } } return false; } /** * Returns the explanation for the given axiom or null if the axiom is not entailed. * * @param axiom axiom to return explanation for * @return explanation for given axiom if axiom is entailed, otherwise null */ public OrExpression getExplanation(OWLAxiom axiom) { if (!typeToMatrix.containsKey(axiom.getAxiomType())) { throw new UnsupportedOperationException( "Reasoner unable to handle axiom type: " + axiom.getAxiomType()); } OrExpression explanation = null; for (Matrix relevantMatrix : typeToMatrix.get(axiom.getAxiomType())) { + OrExpression newExplanation = relevantMatrix.getExplanation(axiom); + if (newExplanation == null) { + continue; + } if (explanation == null) { - explanation = relevantMatrix.getExplanation(axiom).copy(); + explanation = newExplanation.copy(); } else { - explanation = ExpressionMinimizer.flatten(explanation, relevantMatrix.getExplanation(axiom)); + explanation = ExpressionMinimizer.flatten(explanation, newExplanation); } ExpressionMinimizer.minimize(explanation); } return explanation; } /** * Returns true if the concept identified by the IRI <code>subClass</code> is a subconcept of the concept identified * by the IRI <code>superClass</code>. * * @param subClass IRI of potential subconcept * @param superClass IRI of potential superconcept * @return true if subClass is subconcept of superClass */ public boolean isSubClassOf(String subClass, String superClass) { return conceptSubsumption.get(subClass, superClass); } /** * Returns true if the concept identified by the id <code>subClass</code> is a subconcept of the concept identified * by the id <code>superClass</code>. * * @param subClass ID of potential subconcept * @param superClass ID of potential superconcept * @return true if subClass is subconcept of superClass */ public boolean isSubClassOf(int subClass, int superClass) { return conceptSubsumption.get(subClass, superClass); } /** * Returns true if the concept identified by the IRI <code>subProperty</code> is a subproperty of the property * identified by the IRI <code>superProperty</code>. * * @param subProperty IRI of potential subproperty * @param superProperty IRI of potential superproperty * @return true if subProperty is subproperty of superProperty */ public boolean isSubPropertyOf(String subProperty, String superProperty) { return propertySubsumption.get(subProperty, superProperty); } /** * Returns true if the concept identified by the id <code>subProperty</code> is a subproperty of the property * identified by the id <code>superProperty</code>. * * @param subProperty ID of potential subproperty * @param superProperty ID of potential superproperty * @return true if subProperty is subproperty of superProperty */ public boolean isSubPropertyOf(int subProperty, int superProperty) { return propertySubsumption.get(subProperty, superProperty); } /** * Determines whether both classes are disjoint. * * @param class1 first class * @param class2 second class * @return true if both classes are disjoint, otherwise false */ public boolean areDisjointClasses(String class1, String class2) { return conceptDisjointness.get(class1, class2); } /** * Determines whether both classes are disjoint. * * @param class1 first class * @param class2 second class * @return true if both classes are disjoint, otherwise false */ public boolean areDisjointClasses(int class1, int class2) { return conceptDisjointness.get(class1, class2); } /** * Determines whether both properties are disjoint. * * @param property1 first property * @param property2 second property * @return true if both classes are disjoint, otherwise false */ public boolean areDisjointProperties(String property1, String property2) { return propertyDisjointness.get(property1, property2); } /** * Determines whether both properties are disjoint. * * @param property1 first property * @param property2 second property * @return true if both classes are disjoint, otherwise false */ public boolean areDisjointProperties(int property1, int property2) { return propertyDisjointness.get(property1, property2); } /** * Returns the set of all classes which are unsatisfiable in the ontology. * * @return set of all unsatisfiable classes */ public Set<OWLClass> getIncoherentClasses() { Set<OWLClass> res = new HashSet<OWLClass>(); for (int i = 0; i < conceptDisjointness.dimensionCol; i++) { if (conceptDisjointness.get(i, i)) { res.add(dataFactory.getOWLClass(IRI.create(namingManager.getConceptIRI(i)))); } } return res; } /** * Returns the set of all unsatisfiable properties, i.e., properties whose extension must be empty. * * @return set of all unsatisfiable properties */ public Set<OWLObjectProperty> getIncoherentProperties() { Set<OWLObjectProperty> res = new HashSet<OWLObjectProperty>(); for (int i = 0; i < propertyDisjointness.dimensionCol; i++) { if (propertyDisjointness.get(i, i)) { res.add(dataFactory.getOWLObjectProperty(IRI.create(namingManager.getPropertyIRI(i)))); } } for (int i = 0; i < propertyUnsatisfiability.dimensionCol; i++) { if (propertyUnsatisfiability.get(0, i)) { res.add(dataFactory.getOWLObjectProperty(IRI.create(namingManager.getPropertyIRI(i)))); } } return res; } public Set<OWLClass> getConceptCycles() { Set<OWLClass> res = new HashSet<OWLClass>(); for (int i = 0; i < conceptSubsumption.dimensionCol; i++) { if (conceptSubsumption.get(i, i)) { res.add(dataFactory.getOWLClass(IRI.create(namingManager.getConceptIRI(i)))); } } return res; } public Set<OWLObjectProperty> getPropertyCycles() { Set<OWLObjectProperty> res = new HashSet<OWLObjectProperty>(); for (int i = 0; i < conceptSubsumption.dimensionCol; i++) { if (conceptSubsumption.get(i, i)) { res.add(dataFactory.getOWLObjectProperty(IRI.create(namingManager.getPropertyIRI(i)))); } } return res; } }
false
false
null
null
diff --git a/src/com/atech/mpso/MPsoActivity.java b/src/com/atech/mpso/MPsoActivity.java index d2aa76f..9d36933 100644 --- a/src/com/atech/mpso/MPsoActivity.java +++ b/src/com/atech/mpso/MPsoActivity.java @@ -1,76 +1,77 @@ package com.atech.mpso; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MPsoActivity extends Activity implements ResponseCallback{ private EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.title); setContentView(R.layout.activity_mpso); editText = (EditText)findViewById(R.id.editTUC); editText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { search(); return true; } return false; } }); findViewById(R.id.search).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { search(); } }); if (BuildConfig.DEBUG) editText.setText("00442039"); } private void search() { String tarjetaTUC = editText.getText().toString(); if (valid(tarjetaTUC)) new MPesoCaller(getBaseContext()).consultarSaldo(tarjetaTUC, MPsoActivity.this); - + else + editText.setError(getString(R.string.validation_error)); } private boolean valid(String tarjetaTUC) { try { Integer.parseInt(tarjetaTUC); } catch(NumberFormatException ex) { return false; } return tarjetaTUC.length() == 8; } @Override public void response(String saldo) { Toast.makeText(this, "saldo is " + saldo, Toast.LENGTH_LONG).show();; } @Override public void error(String message) { Toast.makeText(this, "saldo is " + message, Toast.LENGTH_LONG).show(); } }
true
false
null
null
diff --git a/src/main/java/com/vonhof/babelshark/impl/DefaultNodeMapper.java b/src/main/java/com/vonhof/babelshark/impl/DefaultNodeMapper.java index 71af57c..ed8fb3c 100644 --- a/src/main/java/com/vonhof/babelshark/impl/DefaultNodeMapper.java +++ b/src/main/java/com/vonhof/babelshark/impl/DefaultNodeMapper.java @@ -1,236 +1,245 @@ package com.vonhof.babelshark.impl; import com.vonhof.babelshark.MappedBean.ObjectField; import com.vonhof.babelshark.*; import com.vonhof.babelshark.exception.MappingException; import com.vonhof.babelshark.node.SharkNode.NodeType; import com.vonhof.babelshark.node.*; +import java.lang.reflect.Array; import java.text.DateFormat; import java.text.ParseException; import java.util.Map.Entry; import java.util.*; /** * Default mapper for nodes to values and values to nodes * @author Henrik Hofmeister <@vonhofdk> */ public class DefaultNodeMapper implements NodeMapper { private final BeanMapper beanMapper; public DefaultNodeMapper() { this(new DefaultBeanMapper()); } public DefaultNodeMapper(BeanMapper beanMapper) { this.beanMapper = beanMapper; } public <T> T readAs(SharkNode node, Class<T> type) throws MappingException { return (T) readAs(node, SharkType.get(type)); } public <T,U> T readAs(SharkNode node, SharkType<T,U> type) throws MappingException { if (type == null) type = (SharkType<T, U>) SharkType.forSimple(Object.class); if (SharkNode.class.isAssignableFrom(type.getType())) return (T) node; if (ReflectUtils.isPrimitive(type.getType())) { if (!node.is(NodeType.VALUE)) throw new MappingException(String.format("Could not convert %s to %s",node,type)); ValueNode valueNode = (ValueNode) node; return readPrimitive(valueNode.getValue(),type.getType()); } if (ReflectUtils.isMappable(type.getType())) { if (!node.is(NodeType.MAP)) throw new MappingException(String.format("Could not convert %s to %s",node,type)); //If type is map if (type.isMap() || type.getType().equals(Object.class)) return readMap((ObjectNode)node, type); return readBean((ObjectNode)node, type); } if (type.isCollection()) { if (!node.is(NodeType.LIST)) throw new MappingException(String.format("Could not convert %s to %s",node,type)); return readCollection((ArrayNode)node, type); } throw new MappingException(String.format("Could not convert %s to %s",node,type)); } protected <T,U> T readMap(ObjectNode node,SharkType<T,U> type) throws MappingException { Map<String,U> out = null; try { Class clz = type.getType(); if (!ReflectUtils.isInstantiatable(clz)) { if (Map.class.isAssignableFrom(clz) || Object.class.equals(clz)) clz = LinkedHashMap.class; else throw new MappingException(String.format("Unknown map type: %s",type)); } out = (Map<String, U>) clz.newInstance(); } catch (Exception ex) { throw new MappingException(ex); } for(String field:node.getFields()) { out.put(field, readAs(node.get(field),type.getValueType())); } return (T) out; } protected <T> T readBean(ObjectNode node,SharkType<T,?> type) throws MappingException { final MappedBean<T> map = beanMapper.getMap(type.getType()); final T out = map.newInstance(node); for(String field:node.getFields()) { final ObjectField oField = map.getField(field); if (!oField.hasSetter()) continue; Object value = readAs(node.get(field),oField.getType()); oField.set(out,value); } return out; } protected <T,V> T readCollection(ArrayNode node,SharkType<T,V> type) throws MappingException { Collection<V> out = null; try { Class clz = type.getType(); - if (!ReflectUtils.isInstantiatable(clz)) { + if (clz.isArray()) { + Object array = Array.newInstance(clz.getComponentType(), node.size()); + for(int i = 0; i < node.size();i++) { + Object value = readAs(node.get(i),clz.getComponentType()); + Array.set(array, i, value); + } + return (T) array; + } else if (!ReflectUtils.isInstantiatable(clz)) { if (Set.class.isAssignableFrom(clz)) clz = HashSet.class; else if (List.class.isAssignableFrom(clz)) clz = ArrayList.class; else throw new MappingException(String.format("Unknown collection type: %s",type)); } out = (Collection) clz.newInstance(); } catch (Exception ex) { throw new MappingException(ex); } for(SharkNode childNode:node) { out.add(readAs(childNode,type.getValueType())); } return (T) out; } protected <T> T readPrimitive(Object o,Class<T> type) throws MappingException { if (type.isInstance(o)) return (T)o; if (String.class.equals(o)) { try { return ConvertUtils.convert((String)o, type); } catch(RuntimeException ex) { throw new MappingException(ex); } } if (o instanceof Number) { Number number = (Number) o; if (Integer.class.equals(type) || int.class.equals(type)) return (T) new Integer(number.intValue()); if (Float.class.equals(type) || float.class.equals(type)) return (T) new Float(number.floatValue()); if (Double.class.equals(type) || double.class.equals(type)) return (T) new Double(number.doubleValue()); if (Long.class.equals(type) || long.class.equals(type)) return (T) new Long(number.longValue()); if (Date.class.equals(type)) return (T) new Date(number.longValue()); } throw new MappingException(String.format("Could not convert %s to %s",o,type.getName())); } protected <T> T stringToPrimitive(String str,Class<T> type) throws MappingException { if (str == null) return null; if (!ReflectUtils.isPrimitive(type)) throw new MappingException(String.format("Not a primitive: %s",type.getName())); if (String.class.equals(type)) return (T) str; if (Boolean.class.equals(type)) return (T) Boolean.valueOf(str); if (Integer.class.equals(type)) return (T) Integer.valueOf(str); if (Float.class.equals(type)) return (T) Float.valueOf(str); if (Double.class.equals(type)) return (T) Double.valueOf(str); if (Long.class.equals(type)) return (T) Long.valueOf(str); if (Enum.class.equals(type)) { try { return (T) type.getMethod("valueOf",String.class).invoke(null,str); } catch (Exception ex) { throw new MappingException(String.format("Could not read enum value in %s: %s",type.getName(),str), ex); } } if (Date.class.equals(type)) { try { return (T) DateFormat.getDateTimeInstance().parse(str); } catch (ParseException ex) { throw new MappingException(String.format("Could not read date string: %s",str), ex); } } throw new MappingException(String.format("Unhandled primitive: %s",type.getName())); } public SharkNode toNode(Object instance) throws MappingException { if (instance instanceof SharkNode) return (SharkNode) instance; if (instance == null) return new ValueNode(null); SharkType type = SharkType.get(instance.getClass()); if (ReflectUtils.isPrimitive(type.getType())) { return new ValueNode(instance); } if (ReflectUtils.isMappable(type.getType())) { ObjectNode node = new ObjectNode(); if (type.isMap()) { Map<Object,Object> map = (Map<Object,Object>)instance; for (Entry<Object,Object> entry:map.entrySet()) { node.put(String.valueOf(entry.getKey()),toNode(entry.getValue())); } } else { MappedBean<Object> map = beanMapper.getMap(type.getType()); for (String field:map.getFieldList()) { ObjectField oField = map.getField(field); if (!oField.hasGetter()) continue; Object value = oField.get(instance); node.put(field,toNode(value)); } } return node; } if (type.isCollection()) { ArrayNode node = new ArrayNode(); if (instance.getClass().isArray()) { - Object[] list = (Object[]) instance; - for (Object value:list) { + int length = Array.getLength(instance); + for(int i = 0; i < length;i++) { + Object value = Array.get(instance, i); node.add(toNode(value)); } } else { Collection list = (Collection) instance; for (Object value:list) { node.add(toNode(value)); } } return node; } throw new MappingException(String.format("Could not convert %s to node",type)); } } diff --git a/src/main/java/com/vonhof/babelshark/node/ArrayNode.java b/src/main/java/com/vonhof/babelshark/node/ArrayNode.java index c5a9ad9..783081f 100644 --- a/src/main/java/com/vonhof/babelshark/node/ArrayNode.java +++ b/src/main/java/com/vonhof/babelshark/node/ArrayNode.java @@ -1,119 +1,121 @@ package com.vonhof.babelshark.node; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; /** * * @author Henrik Hofmeister <@vonhofdk> */ public final class ArrayNode extends SharkNode implements Iterable<SharkNode> { private final List<SharkNode> children = new ArrayList<SharkNode>(); public ArrayNode() { super(NodeType.LIST); } public <T extends SharkNode> T add(T node) { children.add(node); return node; } - + public int size() { + return children.size(); + } public SharkNode get(int i) { if (children.size() <= i) return null; return children.get(i); } public Iterator<SharkNode> iterator() { return children.iterator(); } public ObjectNode addObject() { return add(new ObjectNode()); } public ArrayNode addArray() { return add(new ArrayNode()); } public void add(String ... values) { for(String value:values) add(new ValueNode(value)); } public void add(int ... values) { for(int value:values) add(new ValueNode(value)); } public void add(float ... values) { for(float value:values) add(new ValueNode(value)); } public void add(double ... values) { for(double value:values) add(new ValueNode(value)); } public void add(long... values) { for(long value:values) add(new ValueNode(value)); } public void add(Date ... values) { for(Date value:values) add(new ValueNode(value)); } public void add(boolean ... values) { for(boolean value:values) add(new ValueNode(value)); } public void add(Enum ... values) { for(Enum value:values) add(new ValueNode(value)); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); boolean first = true; for(SharkNode child:children) { if(first) first = false; else sb.append(","); sb.append(child); } sb.append("]"); return sb.toString(); } @Override public boolean equals(Object obj) { if (!super.equals(obj)) { return false; } final ArrayNode other = (ArrayNode) obj; if (this.children != other.children && (this.children == null || !this.children.equals(other.children))) { return false; } return true; } @Override public int hashCode() { int hash = super.hashCode(); hash = 79 * hash + (this.children != null ? this.children.hashCode() : 0); return hash; } }
false
false
null
null
diff --git a/src/org/biomart/queryEngine/queryCompiler/QueryCompiler.java b/src/org/biomart/queryEngine/queryCompiler/QueryCompiler.java index fd42fc3..99ef006 100644 --- a/src/org/biomart/queryEngine/queryCompiler/QueryCompiler.java +++ b/src/org/biomart/queryEngine/queryCompiler/QueryCompiler.java @@ -1,981 +1,981 @@ package org.biomart.queryEngine.queryCompiler; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import org.biomart.common.resources.Log; import org.biomart.configurator.utils.McUtils; import org.biomart.configurator.utils.type.DatasetTableType; import org.biomart.objects.enums.FilterType; import org.biomart.objects.objects.Attribute; import org.biomart.objects.objects.Column; import org.biomart.objects.objects.Dataset; import org.biomart.objects.objects.DatasetColumn; import org.biomart.objects.objects.DatasetTable; import org.biomart.objects.objects.Element; import org.biomart.objects.objects.Filter; import org.biomart.objects.objects.Key; import org.biomart.objects.objects.Relation; import org.biomart.objects.objects.Table; import org.biomart.queryEngine.DBType; import org.biomart.queryEngine.OperatorType; import org.biomart.queryEngine.QueryElement; import org.biomart.queryEngine.SubQuery; import org.jdom.Document; import org.jdom.output.XMLOutputter; /** * * @author Jonathan Guberman, Arek Kasprzyk * * This class prepares SQL query for both Source schema (Virtual Mart) * based querying as well as Materialised schemas (Marts). * A vital component of query compilation which is used for ON THE FLY * extension of WHERE clause for dataset joining, sits in the SubQuery object. */ public class QueryCompiler { //added by Yong for QC testing /** * qcPath is a list of * org.biomart.builder.model.Table * org.biomart.builder.model.Relation * * methods may be used by QC * Table.getName() * Table.getColumns() * Relation.getFirstKey.getName() * Relation.getSecondKey.getName() */ // private List<Object> qcPath; private Map<DatasetTable, List<Object>> qcPathMap; private List<Attribute> selectedAttributes; private Map<Filter,String> selectedFilters; @SuppressWarnings("unused") private Boolean leftFlag; private final String only = "NOT NULL"; private final String excluded = "NULL"; private String quoteChar = ""; /** * * @param dbName * @param ds * @return */ public String searchMaterilizedSchema(String dbName, Dataset ds){ boolean leftFlag = false; //Hard-coded for now, will be retrieved from properties List<String> dss = new ArrayList<String>(); dss.add(ds.getName()); // Create list of all main tables List<DatasetTable> allTmpMainTables = selectedAttributes.iterator().next().getDatasetTable().getMart().getOrderedMainTableList(); List<DatasetTable> allMainTables = new ArrayList<DatasetTable>(); //if datasettable is partitioned, replace it to a real datasettable for(DatasetTable tmpDst: allTmpMainTables) { allMainTables.add(tmpDst); } /*for(Table table : mart.getTableList()){ if(table.getMain()){ allMainTables.add(table); } }*/ HashSet<Column> columnsToCheck = new HashSet<Column>(); HashSet<DatasetTable> mainTables = new HashSet<DatasetTable>(); HashSet<DatasetTable> dmTables = new HashSet<DatasetTable>(); StringBuilder querySQL = new StringBuilder("SELECT "); //TODO: use newly created (DatabaseDialect.SELECT + " ") instead of hardcoded (likewise for other SQL keywords in this class) /* Loop through all the attributes, adding them to * either the list of main tables or the list of dm * tables */ for(Attribute attribute:selectedAttributes){ DatasetTable table = attribute.getDatasetTable(); if (table.getType().equals(DatasetTableType.DIMENSION)) { dmTables.add(table); for(Column dsc: table.getRelations().iterator().next().getOtherKey(table.getForeignKeys().iterator().next()).getColumns()) { columnsToCheck.add(dsc); } } else { mainTables.add(table); columnsToCheck.add(attribute.getDataSetColumn()); } } /* Loop through all the filters, finding their * corresponding attributes, and then adding those * to either the list of main tables or the list of * dm tables */ for(Filter filter:selectedFilters.keySet()){ if(filter.isFilterList()){ for(Filter subFilter : filter.getFilterList(dss)){ findTableType(columnsToCheck, mainTables, dmTables, subFilter,ds); } } else { findTableType(columnsToCheck, mainTables, dmTables, filter,ds); } } /* Figure out what table should be the main table by * checking if it contains any of the necessary keys. * If it doesn't contain any, move to the next smaller * main table. Otherwise, it is our main. */ //TODO fix this: ordering of main tables must be guaranteed String mainTableName = null; outer: for(DatasetTable table:allMainTables){ if(table.getColumnList(ds.getName()).containsAll(columnsToCheck)){ mainTableName = table.getSubPartitionCommaList(ds.getName()); //get real table name if(McUtils.hasPartitionBinding(mainTableName)) mainTableName = McUtils.getRealName(mainTableName, ds); break outer; } /*for (Column column : columnsToCheck) { if (table.getColumnList().contains(column)) { System.err.println(column.getName()); mainTableName = table.getName();//table.getMaterializedName(); break outer; } }*/ } // For getting totals String totalMainTableName = null; for (DatasetTable table : allMainTables) { if (table.getType().equals(DatasetTableType.MAIN)) { totalMainTableName = table.getName(ds.getName()); } } Log.info("Using main table: " + mainTableName); if (isCountQuery) { querySQL.append(" COUNT(*) AS count "); } else { /* * Loop through the attributes, adding them to the * SELECT clause of the query */ for(Attribute attribute:selectedAttributes){ DatasetColumn column = attribute.getDataSetColumn(); //String tableName = column.getTable().getName(); DatasetTable table = attribute.getDatasetTable(); String tableName = table.getSubPartitionCommaList(ds.getName()); if(McUtils.hasPartitionBinding(tableName)) { tableName = McUtils.getRealName(tableName, ds); } if (table.isMain()) { querySQL.append("main."); } else { querySQL.append(dbName + "." + quoteChar + tableName + quoteChar + "."); } querySQL.append(quoteChar + column.getName() + quoteChar); querySQL.append(", "); } // for // Clean up the final comma if necessary if(selectedAttributes.size()>0){ querySQL.deleteCharAt(querySQL.length()-2); } } // Add all of the dm tables and the main table to the FROM clause querySQL.append(" FROM "); if(leftFlag){ querySQL.append(dbName + "." + quoteChar + mainTableName + quoteChar + " main "); for (DatasetTable table : dmTables){ Key key = table.getForeignKeys().iterator().next(); for (Column column : key.getColumns()){ String keyName = column.getName(); //mart.getTable(table).getKey().getName(); String tableName = table.getName(); if(McUtils.hasPartitionBinding(tableName)) tableName = McUtils.getRealName(tableName, ds); String fullTable = dbName + "."+ quoteChar + tableName+ quoteChar; querySQL.append(" LEFT JOIN " + fullTable + " on main." + quoteChar+ keyName + quoteChar+ "=" + fullTable + "." + quoteChar+ keyName+ quoteChar); } } }else{ HashSet<String> tableNames = new HashSet<String>(); for (DatasetTable table : dmTables){ String tableName = table.getSubPartitionCommaList(ds.getName()); if(McUtils.hasPartitionBinding(tableName)) tableName = McUtils.getRealName(tableName, ds); if(!tableNames.contains(tableName)){ querySQL.append(dbName + "." + quoteChar+ tableName + quoteChar+ ", "); tableNames.add(tableName); } } querySQL.append(dbName + "." + quoteChar+ mainTableName + quoteChar+ " main "); } // if /* * Loop through the filters, adding them to the WHERE clause */ if(selectedFilters.size()>0 || (!leftFlag && dmTables.size()>0)){ querySQL.append(" WHERE "); } for(Filter filter:selectedFilters.keySet()){ // If we're doing a count query then only add filters from main table if(filter.isFilterList()){ querySQL.append("("); for(String value : selectedFilters.get(filter).split("[,\\n\\r]")){ String[] splitValue = value.split(filter.getSplitOnValue(),-1); querySQL.append("("); String currentValue = null; for(int i = 0; i < filter.getFilterList(dss).size(); ++i){ if(filter.getSplitOnValue().equals("") || splitValue.length==1){ currentValue = value; } else if (splitValue.length==filter.getFilterList(dss).size()){ currentValue = splitValue[i]; } else { Log.error("Invalid number of filterlist arguments! Filter " + filter.getName() + " is being ignored."); } Filter subFilter = filter.getFilterList(dss).get(i); DatasetTable table = subFilter.getDatasetTable(); DatasetTableType tableType = table.getType(); String tableName = subFilter.getDatasetTable().getSubPartitionCommaList(ds.getName()); if(McUtils.hasPartitionBinding(tableName)) tableName = McUtils.getRealName(tableName, ds); if (subFilter.getQualifier() == OperatorType.RANGE) { querySQL.append("("); String operation1 = " >= "; String operation2 = " <= "; String originalValue = selectedFilters.get(subFilter); String[] values = originalValue.split(subFilter.getSplitOnValue()); if(values.length == 1){ values = new String[2]; if(originalValue.startsWith(">=")){ - values[0] = originalValue.substring(1); + values[0] = originalValue.substring(2); values[1] = null; operation1 = " >= "; } else if (originalValue.startsWith("=<")){ values[0] = null; - values[1] = originalValue.substring(1); + values[1] = originalValue.substring(2); operation2 = " <= "; } else if(originalValue.startsWith(">")){ values[0] = originalValue.substring(1); values[1] = null; operation1 = " > "; } else if (originalValue.startsWith("<")){ values[0] = null; values[1] = originalValue.substring(1); operation2 = " < "; } else { values[0] = originalValue; values[1] = null; operation1 = " = "; } } if (values[0]!=null){ if(tableType.equals(DatasetTableType.MAIN) || tableType.equals(DatasetTableType.MAIN_SUBCLASS) || tableName.endsWith("main") || tableName.endsWith("main||")){ querySQL.append("main."); } else { querySQL.append(dbName + "." + quoteChar+ tableName + quoteChar+ "."); } querySQL.append(quoteChar+subFilter.getDatasetColumn().getName()+ quoteChar); querySQL.append(operation1 + values[0]); } if(values[0]!=null && values[1]!=null) querySQL.append(" AND "); if(values[1]!=null){ if(tableType.equals(DatasetTableType.MAIN) || tableType.equals(DatasetTableType.MAIN_SUBCLASS) || tableName.endsWith("main") || tableName.endsWith("main||")){ querySQL.append("main."); } else { querySQL.append(dbName + "." + quoteChar+ tableName + quoteChar+ "."); } querySQL.append( quoteChar+subFilter.getDatasetColumn().getName()+ quoteChar); querySQL.append(operation2 + values[1] + " " ); } querySQL.append(") "); } else if(subFilter.getQualifier()!=OperatorType.IS){ if (table.isMain()) { querySQL.append("main."); } else { querySQL.append(dbName + "." + quoteChar+ tableName + quoteChar+ "."); } querySQL.append( quoteChar+subFilter.getDatasetColumn().getName()+ quoteChar); querySQL.append(" " + subFilter.getQualifier() + " "); querySQL.append("'" + currentValue + "' "); } else { if (table.isMain()) { querySQL.append("main."); } else { querySQL.append(dbName + "." + quoteChar+ tableName + quoteChar+ "."); } querySQL.append(quoteChar+subFilter.getDatasetColumn().getName()+ quoteChar); querySQL.append(" " + subFilter.getQualifier() + " "); querySQL.append("'"+currentValue + "' "); } if(filter.getFilterOperation()!=null) querySQL.append(filter.getFilterOperation() + " "); else querySQL.append("AND "); } if(filter.getFilterOperation()!=null) querySQL.delete(querySQL.length()-(filter.getFilterOperation().toString().length()+1), querySQL.length()); else querySQL.delete(querySQL.length()-4, querySQL.length()); querySQL.append(") OR "); } querySQL.delete(querySQL.length()-3, querySQL.length()); querySQL.append(") AND "); } else { String tableName = filter.getDatasetTable().getSubPartitionCommaList(ds.getName()); if(McUtils.hasPartitionBinding(tableName)) tableName = McUtils.getRealName(tableName, ds); querySQL.append("("); String[] splitFilter = selectedFilters.get(filter).split("[,\\n\\r]"); DatasetTable table = filter.getDatasetTable(); DatasetTableType tableType = table.getType(); if(filter.getQualifier()==OperatorType.E && splitFilter.length > 1){ if (table.isMain()) { querySQL.append("main."); } else { querySQL.append(dbName + "." + quoteChar+ tableName + quoteChar+ "."); } querySQL.append(quoteChar+filter.getDatasetColumn().getName()+ quoteChar); querySQL.append(" IN ("); for(String value : splitFilter){ querySQL.append("'" + value.trim() + "',"); } querySQL.deleteCharAt(querySQL.length()-1); querySQL.append(")"); } else if (filter.getQualifier() == OperatorType.RANGE) { String operation1 = " >= "; String operation2 = " <= "; String originalValue = selectedFilters.get(filter); String[] values = originalValue.split(filter.getSplitOnValue()); if(values.length == 1){ values = new String[2]; if(originalValue.startsWith(">=")){ - values[0] = originalValue.substring(1); + values[0] = originalValue.substring(2); values[1] = null; operation1 = " >= "; } else if (originalValue.startsWith("=<")){ values[0] = null; - values[1] = originalValue.substring(1); + values[1] = originalValue.substring(2); operation2 = " <= "; } else if(originalValue.startsWith(">")){ values[0] = originalValue.substring(1); values[1] = null; operation1 = " > "; } else if (originalValue.startsWith("<")){ values[0] = null; values[1] = originalValue.substring(1); operation2 = " < "; } else { values[0] = originalValue; values[1] = null; operation1 = " = "; } } if (values[0]!=null){ if(tableType.equals(DatasetTableType.MAIN) || tableType.equals(DatasetTableType.MAIN_SUBCLASS) || tableName.endsWith("main") || tableName.endsWith("main||")){ querySQL.append("main."); } else { querySQL.append(dbName + "." + quoteChar+ tableName + quoteChar+ "."); } querySQL.append(quoteChar+filter.getDatasetColumn().getName()+ quoteChar); querySQL.append(operation1 + values[0]); } if(values[0]!=null && values[1]!=null) querySQL.append(" AND "); if(values[1]!=null){ if(tableType.equals(DatasetTableType.MAIN) || tableType.equals(DatasetTableType.MAIN_SUBCLASS) || tableName.endsWith("main") || tableName.endsWith("main||")){ querySQL.append("main."); } else { querySQL.append(dbName + "." + quoteChar+ tableName + quoteChar+ "."); } querySQL.append( quoteChar+filter.getDatasetColumn().getName()+ quoteChar); querySQL.append(operation2 + values[1] + " " ); } } else{ for(String value : splitFilter){ if (table.isMain()) { querySQL.append("main."); } else { querySQL.append(dbName + "." + quoteChar+ tableName + quoteChar+ "."); } querySQL.append( quoteChar+filter.getDatasetColumn().getName()+ quoteChar); querySQL.append(" " + filter.getQualifier() + " "); if(filter.getQualifier()!=OperatorType.IS) querySQL.append("'" + value.trim() + "' OR "); else querySQL.append(value.trim() + " OR "); } querySQL.delete(querySQL.length()-3, querySQL.length()); } querySQL.append(") AND "); } } // Clean up the last bracket and AND if necessary if(selectedFilters.size()>0 && (dmTables.size()==0 || leftFlag)){ querySQL.delete(querySQL.length()-4, querySQL.length()); } // Add in the join relations if(!leftFlag){ for(DatasetTable table : dmTables){ Key key = table.getForeignKeys().iterator().next(); for (Column column : key.getColumns()){ String keyName = column.getName(); String tableName = table.getSubPartitionCommaList(ds.getName()); if(McUtils.hasPartitionBinding(tableName)) tableName = McUtils.getRealName(tableName, ds); querySQL.append(" main." + quoteChar+ keyName+ quoteChar + "=" + dbName + "." + quoteChar+ tableName + quoteChar+ "." + quoteChar+ keyName+ quoteChar + " AND"); } } if(dmTables.size()>0){ querySQL.delete(querySQL.length()-4, querySQL.length()); } } return querySQL.toString(); } private void findTableType(HashSet<Column> columnsToCheck, HashSet<DatasetTable> mainTables, HashSet<DatasetTable> dmTables, Filter filter, Dataset ds) { DatasetTable tableName = filter.getDatasetTable(); if (tableName.getType().equals(DatasetTableType.DIMENSION)) { dmTables.add(tableName); for(Column cc: tableName.getRelations().iterator().next().getOtherKey(tableName.getForeignKeys().iterator().next()).getColumns()) { columnsToCheck.add(cc); } } else { mainTables.add(tableName); columnsToCheck.add(filter.getDatasetColumn()); } } /** * * @param dbName * @return */ public String searchSourceSchema(String dbName){ // searchMaterilizedSchema(); // System.out.println("----"); dbName = dbName + "."; // Create list of all main tables List<DatasetTable> allMainTables = selectedAttributes.iterator().next().getDatasetTable().getMart().getOrderedMainTableList(); Set<Column> columnsToCheck = new HashSet<Column>(); /* Loop through all the attributes, adding them to * the list of columns to check the main table */ for(Attribute attribute:selectedAttributes){ DatasetTable table = attribute.getDatasetTable(); if (table.getType().equals(DatasetTableType.DIMENSION)) { for(Column column: table.getRelations().iterator().next().getOtherKey(table.getForeignKeys().iterator().next()).getColumns()) columnsToCheck.add(column); } else { columnsToCheck.add(attribute.getDataSetColumn()); } } /* Loop through all the filters, finding their * corresponding attributes, and then adding those * to the list of columns to check for the main table */ for(Filter filter:selectedFilters.keySet()){ DatasetTable tableName = filter.getDatasetTable(); if (tableName.getType().equals(DatasetTableType.DIMENSION)) { for(Column column: tableName.getRelations().iterator().next().getOtherKey(tableName.getForeignKeys().iterator().next()).getColumns()) columnsToCheck.add(column); } else { columnsToCheck.add(filter.getDatasetColumn()); } } /* Figure out what table should be the main table by * checking if it contains any of the necessary keys. * If it doesn't contain any, move to the next smaller * main table. Otherwise, it is our main. */ DatasetTable mainTable = allMainTables.get(allMainTables.size()-1);//null; /* outer: for(DatasetTable table:allMainTables){ //for (Column column : columnsToCheck) { //if (table.getColumnList().contains(column)) { if (table.getColumnList().containsAll(columnsToCheck)) { mainTable = table; break outer; } //} }*/ // This map will keep track of all the sourcecolumns for each datasettable Map<DatasetTable, Set<Table>> sourceTablesByDataSetTable = new HashMap<DatasetTable,Set<Table>>(); // First we keep track of all the source tables for the selected attributes Set<Table> tempSet = null; for (Attribute attribute:selectedAttributes){ DatasetColumn curColumn = attribute.getDataSetColumn(); DatasetTable curDataSetTable = curColumn.getDatasetTable(); // if(curDataSetTable.getType().equals(DatasetTableType.MAIN) || curDataSetTable.getType().equals( DatasetTableType.MAIN_SUBCLASS)) if (curDataSetTable.isMain()) curDataSetTable = mainTable; Table curSourceTable = curColumn.getSourceColumn().getTable(); tempSet = sourceTablesByDataSetTable.get(curDataSetTable); if (null==tempSet) { tempSet = new HashSet<Table>(); } tempSet.add(curSourceTable); sourceTablesByDataSetTable.put(curDataSetTable, tempSet); } // And the same for filters if(!(selectedFilters==null)){ for(Filter filter:selectedFilters.keySet()){ DatasetColumn curColumn = filter.getDatasetColumn(); DatasetTable curDataSetTable = curColumn.getDatasetTable(); // if(curDataSetTable.getType().equals(DatasetTableType.MAIN) || curDataSetTable.getType().equals( DatasetTableType.MAIN_SUBCLASS)) if (curDataSetTable.isMain()) curDataSetTable = mainTable; Table curSourceTable = curColumn.getSourceColumn().getTable(); tempSet = sourceTablesByDataSetTable.get(curDataSetTable); if (null==tempSet) { tempSet = new HashSet<Table>(); } tempSet.add(curSourceTable); sourceTablesByDataSetTable.put(curDataSetTable, tempSet); } } else { System.err.println("Empty filterset!"); } // Next we make sure that we have the Source keys and Source tables for joining the main to the DMs, but only if we have more than one table if(sourceTablesByDataSetTable.keySet().size() > 1){ Map<DatasetTable, Set<Table>> tempMap = new HashMap<DatasetTable,Set<Table>>(); for (DatasetTable curDSTable: sourceTablesByDataSetTable.keySet()){ if (curDSTable.getType().equals(DatasetTableType.DIMENSION)){ Relation relation = curDSTable.getRelations().iterator().next(); Key curDSKey = relation.getKeyForTable(curDSTable); Key curMainKey = relation.getOtherKey(curDSKey); DatasetTable curMainTable = mainTable;//(DatasetTable) curMainKey.getTable(); // Make sure the DM table's key's source table is included tempSet = sourceTablesByDataSetTable.get(curDSTable); if (null==tempSet) { tempSet = new HashSet<Table>(); } tempSet.add(((DatasetColumn) curDSKey.getColumns().get(0)).getTable()); tempMap.put(curDSTable, tempSet); // And the inverse: Make sure the Main table's key's source table is included; // This will need to resolve to a single main eventually, but for now this is OK tempSet = sourceTablesByDataSetTable.get(curMainTable); if (null==tempSet) { tempSet = new HashSet<Table>(); } tempSet.add(((DatasetColumn) curMainKey.getColumns().get(0)).getTable()); tempMap.put(mainTable/*curMainTable*/, tempSet); } } sourceTablesByDataSetTable.putAll(tempMap); } /* * Loop through the attributes, adding them to the * SELECT clause of the query */ StringBuilder querySQL = new StringBuilder(); if (isCountQuery) { querySQL.append("SELECT COUNT(*) FROM ").append(mainTable.getName()); } else { querySQL.append("SELECT "); for(Attribute attribute:selectedAttributes){ querySQL.append(dbName); String tableName = attribute.getDataSetColumn().getSourceColumn().getTable().getName(); querySQL.append(quoteChar + tableName + quoteChar); querySQL.append("."); querySQL.append(quoteChar+attribute.getDataSetColumn().getSourceColumn().getName()+quoteChar); querySQL.append(", "); } // Clean up the final comma if necessary if(selectedAttributes.size()>0){ querySQL.deleteCharAt(querySQL.length()-2); } } querySQL.append("FROM "); int insertParenthesisPoint = querySQL.length(); //Keep track of where to insert opening parentheses int openParenthesisCount = 0; LinkedHashMap<Table, Relation> orderedSourceTables = new LinkedHashMap<Table, Relation>(); List<Object> mainSourceList = qcPathMap.get(mainTable); for (int i = 0; i <= getLastIndex(sourceTablesByDataSetTable.get(mainTable), mainSourceList); i+=2){ if(orderedSourceTables.get((Table) mainSourceList.get(i)) == null) if (i==0){ orderedSourceTables.put((Table) mainSourceList.get(i), null); } else { orderedSourceTables.put((Table) mainSourceList.get(i), (Relation) mainSourceList.get(i-1)); } } for (DatasetTable table: sourceTablesByDataSetTable.keySet()){ List<Object> sourceList = qcPathMap.get(table); for (int i = 0; i <= getLastIndex(sourceTablesByDataSetTable.get(table), sourceList); i+=2){ if(orderedSourceTables.get((Table) sourceList.get(i)) == null) if (i==0){ /* Don't do anything, because this is a dm table. May need revision */ //orderedSourceTables.put((Table) sourceList.get(i), null); } else { orderedSourceTables.put((Table) sourceList.get(i), (Relation) sourceList.get(i-1)); } } } List<Table> reorderedTableList = getReorderedJoinTableList(orderedSourceTables); for (Table sourceTable: reorderedTableList){ Relation relation = orderedSourceTables.get(sourceTable); if (null == relation){ querySQL.append(dbName + quoteChar + sourceTable.getName() + quoteChar); } else { querySQL.append(" LEFT JOIN "); querySQL.append(dbName + quoteChar+ sourceTable.getName()+quoteChar + " ON "); querySQL.append(dbName + quoteChar + sourceTable.getName()+quoteChar + "." + quoteChar+relation.getFirstKeyColumnForTable(sourceTable).getName()+quoteChar + "=" + dbName + quoteChar + relation.getFirstKeyColumnForOtherTable(sourceTable).getTable().getName() + quoteChar + "." + quoteChar + relation.getFirstKeyColumnForOtherTable(sourceTable).getName() + quoteChar + ")"); openParenthesisCount++; } } for(int i = 0; i < openParenthesisCount; ++i){ querySQL.insert(insertParenthesisPoint, '('); } if(selectedFilters.size() > 0){ querySQL.append(" WHERE "); for(Filter filter:selectedFilters.keySet()){ String values[] = selectedFilters.get(filter).split("[,\\n\\r]"); String tableName = filter.getDatasetColumn().getSourceColumn().getTable().getName(); querySQL.append(dbName + quoteChar + tableName + quoteChar); querySQL.append("."); querySQL.append(quoteChar + filter.getDatasetColumn().getSourceColumn().getName() + quoteChar); if(values.length==1){ querySQL.append(filter.getQualifier()); querySQL.append("'" + selectedFilters.get(filter) + "'"); } else { if(filter.getQualifier().equals(OperatorType.E)){ querySQL.append(" IN ("); for(String value : values){ querySQL.append("'" + value.trim() + "',"); } querySQL.deleteCharAt(querySQL.length()-1); querySQL.append(")"); } } querySQL.append(" AND "); } querySQL.delete(querySQL.length()-4, querySQL.length()); } // System.out.print("Source: "); // System.out.println(querySQL); return querySQL.toString(); } /** * Returns an RDBMS/case-independent deterministic ordering of tables (for join) */ private List<Table> getReorderedJoinTableList(LinkedHashMap<Table, Relation> orderedSourceTables) { Map<Table,List<Table>> dependenceMap = new TreeMap<Table, List<Table>>(); boolean first = true; for (Table sourceTable : orderedSourceTables.keySet()) { if (first) { // skip first table (must be first anyway) first = false; } else { Relation relation = orderedSourceTables.get(sourceTable); Table referencedTable = relation.getFirstKeyColumnForOtherTable(sourceTable).getTable(); assert null!=referencedTable; List<Table> referencingTableList = dependenceMap.get(referencedTable); if (null==referencingTableList) { referencingTableList = new ArrayList<Table>(); dependenceMap.put(referencedTable, referencingTableList); } assert !referencingTableList.contains(sourceTable); referencingTableList.add(sourceTable); } } assert orderedSourceTables.isEmpty() || !dependenceMap.isEmpty() : dependenceMap; List<Table> reorderedJoinTableList = new ArrayList<Table>(); if (!orderedSourceTables.isEmpty()) { Table firstSourceTable = orderedSourceTables.keySet().iterator().next(); assert firstSourceTable.getRelations()==null; // first table has no relation by design reorderedJoinTableList.add(firstSourceTable); recursiveTableAddition(dependenceMap, reorderedJoinTableList, firstSourceTable); } String debugString = McUtils.NEW_LINE + "dependenceMap = " + dependenceMap + McUtils.NEW_LINE + McUtils.NEW_LINE + "joinTableList = " + reorderedJoinTableList + McUtils.NEW_LINE; assert reorderedJoinTableList.size()==orderedSourceTables.size() && new TreeSet<Table>(reorderedJoinTableList).size()==orderedSourceTables.size() : debugString; Log.debug(debugString); return reorderedJoinTableList; } private void recursiveTableAddition(Map<Table,List<Table>> dependenceMap, List<Table> reorderedJoinTableList, Table referencedTable) { List<Table> referencingTableList = dependenceMap.get(referencedTable); if (null!=referencingTableList) { assert !referencingTableList.isEmpty(); Collections.sort(referencingTableList); for (Table referencingTable : referencingTableList) { reorderedJoinTableList.add(referencingTable); recursiveTableAddition(dependenceMap, reorderedJoinTableList, referencingTable); } } } /** * * @param value */ public void setQcPathMap(Map<DatasetTable,List<Object>> value) { this.qcPathMap = value; } /** * * @param value */ public void setSelectedAttributes(List<Attribute> value) { this.selectedAttributes = value; } /** * * @param value */ public void setSelectedFilters(Map<Filter,String> value) { this.selectedFilters = value; } /** * */ private final boolean isCountQuery; public QueryCompiler(boolean isCountQuery) { this.isCountQuery = isCountQuery; this.selectedAttributes = new ArrayList<Attribute>(); this.selectedFilters = new HashMap<Filter, String>(); } /** * Generates the SQL query corresponding to the SubQuery object specified * * @param subQuery * @param forceSource * @return */ public String generateQuery(SubQuery subQuery, boolean forceSource) { // If forcing it to use the source schema or that the schema is not materialized //if (forceSource /*|| // !subQuery.getConfig().getMart().getMaterialized()*/) { // return searchSourceSchema(); //} // Use the materialized schema //else { ArrayList<Attribute> portables = new ArrayList<Attribute>(); List<String> datasets = new ArrayList<String>(); datasets.add(subQuery.getDataset().getInternalName()); for(QueryElement queryElement : subQuery.getQueryAttributeList()){ Attribute attribute; switch(queryElement.getType()){ case ATTRIBUTE: attribute = (Attribute) queryElement.getElement(); List<Attribute> attributeList = attribute.getAttributeList(datasets,true); if(attributeList.isEmpty()){ attributeList = new ArrayList<Attribute>(); attributeList.add(attribute); } for(Attribute subAttribute : attributeList){ if(subAttribute==null) Log.error("ATTRIBUTE is NULL"); if(subAttribute.getValue() == null || subAttribute.getValue().equals("")) this.selectedAttributes.add(subAttribute); } break; case EXPORTABLE_ATTRIBUTE: for(Element element : queryElement.getElementList()){ attribute = (Attribute) element; if(attribute==null) Log.error("EXPORTABLE ATTRIBUTE is NULL"); portables.add(attribute); if(queryElement.getPortablePosition()==null){ queryElement.setPortablePosition(portables.size()-1); } } break; } } for(QueryElement queryElement : subQuery.getQueryFilterList()){ Filter filter; switch(queryElement.getType()){ case FILTER: filter = (Filter) queryElement.getElement(); if(subQuery.isDatabase() || subQuery.getVersion().equals("0.7")){ if(filter.isFilterList()){ for(Filter subFilter : filter.getFilterList(datasets)){ if(subFilter.getFilterType()==FilterType.BOOLEAN){ if(queryElement.getFilterValues().equals("only")){ subFilter.setQualifier(OperatorType.IS); queryElement.setFilterValues(this.only); } else if(queryElement.getFilterValues().equals("excluded")){ subFilter.setQualifier(OperatorType.IS); queryElement.setFilterValues(this.excluded); } } } } } this.selectedFilters.put(filter,queryElement.getFilterValues()); if(subQuery.isDatabase() || subQuery.getVersion().equals("0.7")){ if(filter.getFilterType()==FilterType.BOOLEAN){ if(queryElement.getFilterValues().equals("only")){ filter.setQualifier(OperatorType.IS); this.selectedFilters.put(filter,this.only); } else if(queryElement.getFilterValues().equals("excluded")){ filter.setQualifier(OperatorType.IS); this.selectedFilters.put(filter,this.excluded); } } } break; case IMPORTABLE_FILTER: for(Element element : queryElement.getElementList()){ filter = (Filter) element; if(filter.getAttribute()==null) Log.error("IMPORTABLE FILTER's attribute is NULL"); portables.add(filter.getAttribute()); if(queryElement.getPortablePosition()==null){ queryElement.setPortablePosition(portables.size()-1); } } break; } } this.selectedAttributes.addAll(0, portables); subQuery.setTotalCols(this.selectedAttributes.size()); if(subQuery.isDatabase()){ String prefix = ""; if (subQuery.getDbType() == DBType.ORACLE || subQuery.getDbType() == DBType.POSTGRES || subQuery.getDbType() == DBType.DB2) quoteChar = "\""; if(subQuery.useDbName() && subQuery.useSchema()) prefix = quoteChar + subQuery.getDatabaseName() + quoteChar + "." + quoteChar + subQuery.getSchemaName() + quoteChar; else if(subQuery.useDbName()) prefix = quoteChar + subQuery.getDatabaseName() + quoteChar; else if(subQuery.useSchema()) prefix = quoteChar + subQuery.getSchemaName() + quoteChar; return searchSchema(prefix, subQuery.getDataset(), forceSource); } else { return searchWebServices(subQuery); } //} } private String searchSchema(String dbName, Dataset ds, boolean forceSource){ if(forceSource){ this.qcPathMap = McUtils.getQcPathMap(ds); return searchSourceSchema(dbName); } else { return searchMaterilizedSchema(dbName, ds); } } // Allow filters to be excluded in count queries so we can get a total # private String searchWebServices(SubQuery subQuery) { org.jdom.Element queryElement = new org.jdom.Element("Query"); Document queryDocument = new Document(queryElement); // queryElement.setAttribute("processor", subQuery.getProcessor()); // queryElement.setAttribute("limit", Integer.toString(subQuery.getLimit())); queryElement.setAttribute("client", subQuery.getClient()); String virtualSchema = subQuery.getDataset().getValueForColumn(11); if(virtualSchema != null && !virtualSchema.equals("")) queryElement.setAttribute("virtualSchemaName",virtualSchema); org.jdom.Element datasetElement = new org.jdom.Element("Dataset"); datasetElement.setAttribute("name", subQuery.getDataset().getName()); if(subQuery.getConfig().getName()==null) datasetElement.setAttribute("config", subQuery.getDataset().getParentMart().getDefaultConfig().getName()); else datasetElement.setAttribute("config", subQuery.getConfig().getName()); if (isCountQuery) { queryElement.setAttribute("count", "1"); } queryElement.addContent(datasetElement); for(Attribute attribute : this.selectedAttributes){ org.jdom.Element attributeElement = new org.jdom.Element("Attribute"); attributeElement.setAttribute("name", attribute.getInternalName()); datasetElement.addContent(attributeElement); } for(Filter filter : this.selectedFilters.keySet()){ org.jdom.Element filterElement = new org.jdom.Element("Filter"); filterElement.setAttribute("name", filter.getInternalName()); System.err.println(filter.getFilterType()); if(subQuery.getVersion().equals("0.7") && filter.getFilterType()==FilterType.BOOLEAN){ if(this.selectedFilters.get(filter).equals(this.only)){ this.selectedFilters.put(filter,"only"); filterElement.setAttribute("excluded","0"); } else if(this.selectedFilters.get(filter).equals(this.excluded)){ this.selectedFilters.put(filter,"excluded"); filterElement.setAttribute("excluded","1"); } } else { filterElement.setAttribute("value", this.selectedFilters.get(filter)); } datasetElement.addContent(filterElement); } XMLOutputter outputter = new XMLOutputter(); return outputter.outputString(queryDocument); } private int getLastIndex(Set<Table> set, List<Object> list){ int i = 0; if(set!=null && list!=null){ for(Table item : set){ if (list.lastIndexOf(item) > i) i = list.lastIndexOf(item); } } return i; } }
false
false
null
null
diff --git a/flexodesktop/GUI/flexointerfacebuilder/src/main/java/org/openflexo/fib/view/widget/FIBDropDownWidget.java b/flexodesktop/GUI/flexointerfacebuilder/src/main/java/org/openflexo/fib/view/widget/FIBDropDownWidget.java index 5ba7af822..b3634806f 100644 --- a/flexodesktop/GUI/flexointerfacebuilder/src/main/java/org/openflexo/fib/view/widget/FIBDropDownWidget.java +++ b/flexodesktop/GUI/flexointerfacebuilder/src/main/java/org/openflexo/fib/view/widget/FIBDropDownWidget.java @@ -1,258 +1,261 @@ /* * (c) Copyright 2010-2011 AgileBirds * * This file is part of OpenFlexo. * * OpenFlexo 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. * * OpenFlexo 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 OpenFlexo. If not, see <http://www.gnu.org/licenses/>. * */ package org.openflexo.fib.view.widget; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.BorderFactory; import javax.swing.ComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JPanel; import org.openflexo.fib.controller.FIBController; import org.openflexo.fib.model.FIBDropDown; import org.openflexo.fib.model.FIBModelObject; import org.openflexo.localization.FlexoLocalization; import org.openflexo.toolbox.ToolBox; public class FIBDropDownWidget extends FIBMultipleValueWidget<FIBDropDown, JComboBox, Object> { static final Logger logger = Logger.getLogger(FIBDropDownWidget.class.getPackage().getName()); private final JButton resetButton; private final JPanel dropdownPanel; protected JComboBox jComboBox; public FIBDropDownWidget(FIBDropDown model, FIBController controller) { super(model, controller); initJComboBox(); dropdownPanel = new JPanel(new BorderLayout()); resetButton = new JButton(); resetButton.setText(FlexoLocalization.localizedForKey(FIBModelObject.LOCALIZATION, "reset", resetButton)); resetButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { jComboBox.getModel().setSelectedItem(null); setValue(null); } }); if (ToolBox.getPLATFORM() != ToolBox.MACOS) { dropdownPanel.setBorder(BorderFactory.createEmptyBorder(TOP_COMPENSATING_BORDER, LEFT_COMPENSATING_BORDER, BOTTOM_COMPENSATING_BORDER, RIGHT_COMPENSATING_BORDER)); } dropdownPanel.add(jComboBox, BorderLayout.CENTER); if (model.showReset) { dropdownPanel.add(resetButton, BorderLayout.EAST); } dropdownPanel.setOpaque(false); dropdownPanel.addFocusListener(this); updateFont(); } protected void initJComboBox() { if (logger.isLoggable(Level.FINE)) { logger.fine("initJComboBox()"); } Dimension dimTemp = null; Point locTemp = null; Container parentTemp = null; if (jComboBox != null && jComboBox.getParent() != null) { dimTemp = jComboBox.getSize(); locTemp = jComboBox.getLocation(); parentTemp = jComboBox.getParent(); parentTemp.remove(jComboBox); parentTemp.remove(resetButton); } listModel = null; jComboBox = new JComboBox(getListModel()); /*if (getDataObject() == null) { Vector<Object> defaultValue = new Vector<Object>(); defaultValue.add(FlexoLocalization.localizedForKey("no_selection")); _jComboBox = new JComboBox(defaultValue); } else { // TODO: Verify that there is no reason for this comboBoxModel to be cached. listModel=null; _jComboBox = new JComboBox(getListModel()); }*/ jComboBox.setFont(getFont()); jComboBox.setRenderer(getListCellRenderer()); jComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (logger.isLoggable(Level.FINE)) { logger.fine("Action performed in " + this.getClass().getName()); } updateModelFromWidget(); } }); if (parentTemp != null) { // _jComboBox.setSize(dimTemp); jComboBox.setLocation(locTemp); ((JPanel) parentTemp).add(jComboBox, BorderLayout.CENTER); if (getWidget().showReset) { ((JPanel) parentTemp).add(resetButton, BorderLayout.EAST); } } // Important: otherwise might be desynchronized jComboBox.revalidate(); if ((getWidget().getData() == null || !getWidget().getData().isValid()) && getWidget().getAutoSelectFirstRow() && getListModel().getSize() > 0) { jComboBox.setSelectedIndex(0); } jComboBox.setEnabled(isComponentEnabled()); } @Override public synchronized boolean updateWidgetFromModel() { if (notEquals(getValue(), jComboBox.getSelectedItem()) || listModelRequireChange()) { if (logger.isLoggable(Level.FINE)) { logger.fine("updateWidgetFromModel()"); } widgetUpdating = true; initJComboBox(); jComboBox.setSelectedItem(getValue()); widgetUpdating = false; if (getValue() == null && getWidget().getAutoSelectFirstRow() && getListModel().getSize() > 0) { jComboBox.setSelectedIndex(0); } return true; } return false; } /** * Update the model given the actual state of the widget */ @Override public synchronized boolean updateModelFromWidget() { if (widgetUpdating) { return false; } if (notEquals(getValue(), jComboBox.getSelectedItem())) { modelUpdating = true; if (logger.isLoggable(Level.FINE)) { logger.fine("updateModelFromWidget with " + jComboBox.getSelectedItem()); } if (jComboBox.getSelectedItem() != null && !widgetUpdating) { setValue(jComboBox.getSelectedItem()); } modelUpdating = false; return true; } return false; } @Override public MyComboBoxModel getListModel() { return (MyComboBoxModel) super.getListModel(); } @Override protected MyComboBoxModel updateListModelWhenRequired() { if (listModel == null) { listModel = new MyComboBoxModel(getValue()); if (jComboBox != null) { jComboBox.setModel((MyComboBoxModel) listModel); } } else { MyComboBoxModel aNewMyComboBoxModel = new MyComboBoxModel(getValue()); if (!aNewMyComboBoxModel.equals(listModel)) { listModel = aNewMyComboBoxModel; jComboBox.setModel((MyComboBoxModel) listModel); + // This next line should trigger the invalidation of the cached + // preferred size of the combo box + jComboBox.setPrototypeDisplayValue(null); } } return (MyComboBoxModel) listModel; } protected class MyComboBoxModel extends FIBMultipleValueModel implements ComboBoxModel { protected Object selectedItem = null; public MyComboBoxModel(Object selectedObject) { super(); } @Override public void setSelectedItem(Object anItem) { if (selectedItem != anItem) { widgetUpdating = true; selectedItem = anItem; // logger.info("setSelectedItem() with " + anItem + " widgetUpdating=" + widgetUpdating + " modelUpdating=" + // modelUpdating); getDynamicModel().selected = anItem; getDynamicModel().selectedIndex = indexOf(anItem); if (!widgetUpdating && !modelUpdating) { notifyDynamicModelChanged(); } widgetUpdating = false; } } @Override public Object getSelectedItem() { return selectedItem; } @Override public boolean equals(Object object) { if (object instanceof MyComboBoxModel) { if (selectedItem != ((MyComboBoxModel) object).selectedItem) { return false; } } return super.equals(object); } } @Override public JPanel getJComponent() { return dropdownPanel; } @Override public JComboBox getDynamicJComponent() { return jComboBox; } @Override public void updateFont() { super.updateFont(); jComboBox.setFont(getFont()); } }
true
false
null
null
diff --git a/deegree-core/deegree-core-base/src/main/java/org/deegree/feature/xpath/GMLObjectNavigator.java b/deegree-core/deegree-core-base/src/main/java/org/deegree/feature/xpath/GMLObjectNavigator.java index e6b87fd6d2..3c32a274b1 100644 --- a/deegree-core/deegree-core-base/src/main/java/org/deegree/feature/xpath/GMLObjectNavigator.java +++ b/deegree-core/deegree-core-base/src/main/java/org/deegree/feature/xpath/GMLObjectNavigator.java @@ -1,496 +1,494 @@ //$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2009 by: Department of Geography, University of Bonn and lat/lon GmbH This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: info@deegree.org ----------------------------------------------------------------------------*/ package org.deegree.feature.xpath; -import static java.util.Collections.emptyIterator; import static org.deegree.commons.xml.CommonNamespaces.GML3_2_NS; import static org.deegree.commons.xml.CommonNamespaces.GMLNS; import static org.jaxen.JaxenConstants.EMPTY_ITERATOR; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.xml.namespace.QName; import org.deegree.commons.tom.TypedObjectNode; import org.deegree.commons.tom.genericxml.GenericXMLElement; import org.deegree.commons.tom.gml.GMLObject; import org.deegree.commons.tom.gml.property.Property; import org.deegree.commons.tom.ows.CodeType; import org.deegree.commons.tom.primitive.PrimitiveValue; import org.deegree.commons.uom.Measure; import org.deegree.feature.Feature; import org.deegree.feature.xpath.node.AttributeNode; import org.deegree.feature.xpath.node.DocumentNode; import org.deegree.feature.xpath.node.ElementNode; import org.deegree.feature.xpath.node.GMLObjectNode; import org.deegree.feature.xpath.node.PrimitiveNode; import org.deegree.feature.xpath.node.PropertyNode; import org.deegree.feature.xpath.node.XMLElementNode; import org.deegree.feature.xpath.node.XPathNode; import org.jaxen.DefaultNavigator; -import org.jaxen.JaxenConstants; import org.jaxen.XPath; import org.jaxen.saxpath.SAXPathException; import org.jaxen.util.SingleObjectIterator; /** * <a href="http://jaxen.codehaus.org/">Jaxen</a> {@link DefaultNavigator} implementation for {@link GMLObject} objects. * * @author <a href="mailto:schneider@lat-lon.de">Markus Schneider </a> * @author last edited by: $Author:$ * * @version $Revision:$, $Date:$ */ class GMLObjectNavigator extends DefaultNavigator { private static final long serialVersionUID = 5684363154723828577L; private DocumentNode documentNode; /** * Creates a new {@link GMLObjectNavigator} instance with a {@link Feature} that acts as the root of the navigation * hierarchy. * * @param root * root of the navigation hierarchy (child of the document node), can be <code>null</code> */ GMLObjectNavigator( GMLObject root ) { if ( root != null ) { this.documentNode = new DocumentNode( new GMLObjectNode<GMLObject, GMLObject>( null, root ) ); } } /** * Returns an iterator over the attributes of an {@link ElementNode}. * * @param node * the context node for the attribute axis (an {@link ElementNode}, otherwise returns emtpy iterator) * @return a possibly empty iterator (never <code>null</code>) */ @SuppressWarnings("unchecked") @Override public Iterator<AttributeNode<? extends TypedObjectNode>> getAttributeAxisIterator( Object node ) { if ( node instanceof GMLObjectNode<?, ?> ) { GMLObjectNode<GMLObject, ?> gmlObjectNode = (GMLObjectNode<GMLObject, ?>) node; GMLObject object = gmlObjectNode.getValue(); if ( object.getId() != null ) { List<AttributeNode<?>> idAttrs = new ArrayList<AttributeNode<?>>( 4 ); PrimitiveValue id = new PrimitiveValue( object.getId() ); idAttrs.add( new AttributeNode<GMLObject>( gmlObjectNode, new QName( "fid" ), id ) ); idAttrs.add( new AttributeNode<GMLObject>( gmlObjectNode, new QName( "gid" ), id ) ); idAttrs.add( new AttributeNode<GMLObject>( gmlObjectNode, new QName( GMLNS, "id" ), id ) ); idAttrs.add( new AttributeNode<GMLObject>( gmlObjectNode, new QName( GML3_2_NS, "id" ), id ) ); return idAttrs.iterator(); } } else if ( node instanceof PropertyNode ) { Object value = ( (PropertyNode) node ).getValue().getValue(); if ( value instanceof Measure && ( (Measure) value ).getUomUri() != null ) { PrimitiveValue uom = new PrimitiveValue( ( (Measure) value ).getUomUri() ); return new SingleObjectIterator( new AttributeNode<Property>( (PropertyNode) node, new QName( "uom" ), uom ) ); } else if ( value instanceof CodeType && ( (CodeType) value ).getCodeSpace() != null ) { PrimitiveValue codeSpace = new PrimitiveValue( ( (CodeType) value ).getCodeSpace() ); return new SingleObjectIterator( new AttributeNode<Property>( (PropertyNode) node, new QName( "codeSpace" ), codeSpace ) ); } else if ( value instanceof GenericXMLElement ) { XMLElementNode<Property> n = new XMLElementNode<Property>( (PropertyNode) node, (GenericXMLElement) value ); return getAttributeAxisIterator( n ); } } else if ( node instanceof XMLElementNode<?> ) { org.deegree.commons.tom.ElementNode value = ( (XMLElementNode<?>) node ).getValue(); Map<QName, PrimitiveValue> attributes = value.getAttributes(); if ( attributes != null ) { List<AttributeNode<?>> attrNodes = new ArrayList<AttributeNode<?>>( attributes.size() ); for ( Entry<QName, PrimitiveValue> attribute : attributes.entrySet() ) { attrNodes.add( new AttributeNode<org.deegree.commons.tom.ElementNode>( (XMLElementNode<?>) node, attribute.getKey(), attribute.getValue() ) ); } return attrNodes.iterator(); } } - return JaxenConstants.EMPTY_ITERATOR; + return EMPTY_ITERATOR; } /** * Returns the local name of an attribute node. * * @param node * attribute node, must not be null * @return a string representing the unqualified local name if the node is an attribute, or <code>null</code> * otherwise */ @Override public String getAttributeName( Object node ) { String name = null; if ( isAttribute( node ) ) { AttributeNode<?> attr = (AttributeNode<?>) node; name = attr.getLocalName(); } return name; } /** * Returns the namespace URI of an attribute node. * * @param node * attribute node, must not be null * @return namespace if the argument is an attribute, or <code>null</code> otherwise */ @Override public String getAttributeNamespaceUri( Object node ) { String ns = null; if ( isAttribute( node ) ) { AttributeNode<?> attr = (AttributeNode<?>) node; ns = attr.getNamespaceUri(); } return ns; } /** * Returns the qualified (=prefixed) name of an attribute node. * * @param node * attribute node, must not be null * @return a string representing the qualified (i.e. possibly prefixed) name if the argument is an attribute, or * <code>null</code> otherwise */ @Override public String getAttributeQName( Object node ) { String name = null; if ( isAttribute( node ) ) { AttributeNode<?> attr = (AttributeNode<?>) node; name = attr.getPrefixedName(); } return name; } /** * Returns the string value of an attribute node. * * @param node * attribute node, must not be null * @return the text of the attribute value if the node is an attribute, <code>null</code> otherwise */ @Override public String getAttributeStringValue( Object node ) { String value = null; if ( isAttribute( node ) ) { value = ( (AttributeNode<?>) node ).getValue().getAsText(); } return value; } /** * Returns an iterator over all children of the given node. * * @param node * the context node for the child axis, never <code>null</code> * @return a possibly empty iterator, never <code>null</code> */ @Override public Iterator<?> getChildAxisIterator( Object node ) { Iterator<?> iter = EMPTY_ITERATOR; if ( node instanceof GMLObjectNode<?, ?> ) { GMLObjectNode<GMLObject, GMLObject> gmlObjectNode = (GMLObjectNode<GMLObject, GMLObject>) node; if ( gmlObjectNode.getValue() != null ) { iter = new PropertyNodeIterator( gmlObjectNode ); } } else if ( node instanceof DocumentNode ) { iter = new SingleObjectIterator( ( (DocumentNode) node ).getRootNode() ); } else if ( node instanceof PropertyNode ) { PropertyNode propNode = (PropertyNode) node; Property prop = propNode.getValue(); if ( !prop.getChildren().isEmpty() ) { List<XPathNode> xpathNodes = new ArrayList<XPathNode>( prop.getChildren().size() ); for ( TypedObjectNode xmlNode : prop.getChildren() ) { if ( xmlNode instanceof org.deegree.commons.tom.ElementNode ) { xpathNodes.add( new XMLElementNode<Property>( propNode, (org.deegree.commons.tom.ElementNode) xmlNode ) ); } else if ( xmlNode instanceof GMLObject ) { xpathNodes.add( new GMLObjectNode<GMLObject, Property>( propNode, (GMLObject) xmlNode ) ); } else if ( xmlNode instanceof PrimitiveValue ) { xpathNodes.add( new PrimitiveNode<Property>( propNode, (PrimitiveValue) xmlNode ) ); } } iter = xpathNodes.iterator(); } else { final Object propValue = prop.getValue(); if ( propValue instanceof GMLObject ) { GMLObject castNode = (GMLObject) propValue; iter = new SingleObjectIterator( new GMLObjectNode<GMLObject, Property>( propNode, castNode ) ); } else if ( propValue instanceof PrimitiveValue ) { iter = new SingleObjectIterator( new PrimitiveNode<Property>( (PropertyNode) node, (PrimitiveValue) propValue ) ); } else if ( propValue == null ) { - iter = emptyIterator(); + iter = EMPTY_ITERATOR; } else { // TODO remove this case iter = new SingleObjectIterator( new PrimitiveNode<Property>( (PropertyNode) node, new PrimitiveValue( propValue.toString() ) ) ); } } } else if ( node instanceof XMLElementNode<?> ) { XMLElementNode<?> xmlElementNode = (XMLElementNode<?>) node; List<TypedObjectNode> xmlNodes = xmlElementNode.getValue().getChildren(); List<XPathNode<?>> xpathNodes = new ArrayList<XPathNode<?>>( xmlNodes.size() ); for ( TypedObjectNode xmlNode : xmlNodes ) { if ( xmlNode instanceof org.deegree.commons.tom.ElementNode ) { xpathNodes.add( new XMLElementNode<org.deegree.commons.tom.ElementNode>( xmlElementNode, (org.deegree.commons.tom.ElementNode) xmlNode ) ); } else if ( xmlNode instanceof GMLObject ) { xpathNodes.add( new GMLObjectNode<GMLObject, org.deegree.commons.tom.ElementNode>( xmlElementNode, (GMLObject) xmlNode ) ); } else if ( xmlNode instanceof PrimitiveValue ) { xpathNodes.add( new PrimitiveNode<org.deegree.commons.tom.ElementNode>( xmlElementNode, (PrimitiveValue) xmlNode ) ); } } iter = xpathNodes.iterator(); } return iter; } @Override public String getCommentStringValue( Object contextNode ) { String msg = "getCommentStringValue(Object) called with argument (" + contextNode + "), but method not implemented"; throw new UnsupportedOperationException( msg ); } /** * Returns the top-level document node. * * @param contextNode * any node in the document * @return the root node */ @Override public Object getDocumentNode( Object contextNode ) { if ( documentNode == null ) { String msg = "getDocumentNode(Object) not possible, no document node provided"; throw new UnsupportedOperationException( msg ); } return documentNode; } /** * Returns the local name of an element node. * * @param node * the element node * @return a string representing the unqualified local name if the node is an element, or null otherwise */ @Override public String getElementName( Object node ) { String name = null; if ( isElement( node ) ) { ElementNode<?> el = (ElementNode<?>) node; name = el.getLocalName(); } return name; } /** * Returns the namespace URI of an element node. * * @param node * the element node * @return the namespace if the argument is an element, or null otherwise */ @Override public String getElementNamespaceUri( Object node ) { String ns = null; if ( isElement( node ) ) { ElementNode<?> el = (ElementNode<?>) node; ns = el.getNamespaceUri(); } return ns; } /** * Returns the qualified (=prefixed) name of an element node. * * @param node * the element node * @return a string representing the qualified (i.e. possibly prefixed) name if the argument is an element, or null * otherwise */ @Override public String getElementQName( Object node ) { String name = null; if ( isElement( node ) ) { ElementNode<?> el = (ElementNode<?>) node; name = el.getPrefixedName(); } return name; } /** * Returns the string value of an element node. * * @param node * the target node * @return the text inside the node and its descendants if the node is an element, null otherwise */ @Override public String getElementStringValue( Object node ) { String value = null; if ( node instanceof PropertyNode ) { Property prop = ( (PropertyNode) node ).getValue(); Object propValue = prop.getValue(); // TODO check if conversion is feasible (e.g. Geometry.toString() may be expensive) value = propValue.toString(); } return value; } @Override public String getNamespacePrefix( Object contextNode ) { String msg = "getNamespacePrefix(Object) called with argument (" + contextNode + "), but method not implemented"; throw new UnsupportedOperationException( msg ); } @Override public String getNamespaceStringValue( Object contextNode ) { String msg = "getNamespaceStringValue(Object) called with argument (" + contextNode + "), but method not implemented"; throw new UnsupportedOperationException( msg ); } /** * Returns a (single-member) iterator over this node's parent. * * @param contextNode * the context node for the parent axis * @return a possibly-empty iterator (not null) */ @SuppressWarnings("unchecked") @Override public Iterator<XPathNode<?>> getParentAxisIterator( Object contextNode ) { return new SingleObjectIterator( ( (XPathNode<?>) contextNode ).getParent() ); } @Override public String getTextStringValue( Object obj ) { String value = null; if ( obj instanceof PrimitiveNode<?> ) { value = ( (PrimitiveNode<?>) obj ).getValue().getAsText(); } return value; } @Override public boolean isAttribute( Object obj ) { return obj instanceof AttributeNode<?>; } @Override public boolean isComment( Object obj ) { // TODO Auto-generated method stub return false; } @Override public boolean isDocument( Object obj ) { // TODO Auto-generated method stub return false; } @Override public boolean isElement( Object obj ) { return obj instanceof ElementNode<?>; } @Override public boolean isNamespace( Object obj ) { return false; } @Override public boolean isProcessingInstruction( Object obj ) { return false; } @Override public boolean isText( Object obj ) { return obj instanceof PrimitiveNode<?>; } /** * Returns a parsed form of the given XPath string, which will be suitable for queries on <code>Feature</code> * objects. * * @param xpath * the XPath expression * @return a parsed form of the given XPath string * @throws SAXPathException * if the string is syntactically incorrect */ @Override public XPath parseXPath( String xpath ) throws SAXPathException { return new GMLObjectXPath( xpath, null ); } /** * Translates a namespace prefix to a URI. * * @param prefix * the namespace prefix * @param element * the namespace context * @return the namespace URI bound to the prefix in the scope of <code>element</code>; null if the prefix is not * bound */ @Override public String translateNamespacePrefixToUri( String prefix, Object element ) { String msg = "translateNamespacePrefixToUri(String,Object) called with arguments (" + prefix + "," + element + "), but method not implemented"; throw new UnsupportedOperationException( msg ); } }
false
false
null
null
diff --git a/src/com/reelfx/Applet.java b/src/com/reelfx/Applet.java index 79b5318..79f76bc 100644 --- a/src/com/reelfx/Applet.java +++ b/src/com/reelfx/Applet.java @@ -1,661 +1,661 @@ package com.reelfx; import java.awt.Dimension; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Window; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.JarURLConnection; import java.net.URISyntaxException; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Enumeration; import java.util.Properties; import java.util.Vector; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import javax.swing.JApplet; import javax.swing.SwingUtilities; import netscape.javascript.JSException; import netscape.javascript.JSObject; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import com.reelfx.controller.AbstractController; import com.reelfx.controller.LinuxController; import com.reelfx.controller.MacController; import com.reelfx.controller.WindowsController; import com.reelfx.model.AttributesManager; import com.reelfx.model.CaptureViewport; import com.reelfx.view.util.ViewListener; import com.reelfx.view.util.ViewNotifications; import com.sun.JarClassLoader; /** * * The applet initializer class. It adheres to the standard Java applet, setups all a series of * global variables used throughout the applet, acts as a middle man for the Java/Javascript * communication, and provides a series of auxilary methods for unpacking JAR files, etc. * * @author Daniel Dixon (http://www.danieldixon.com) * * * Copyright (C) 2010 ReelFX Creative Studios (http://www.reelfx.com) * * 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/> * * * SPECIAL NOTE ON JSObject on Mac (Used for communicating with Javascript) * In Eclipse, initially couldn't find the class. This guy said to add a reference to 'plugin.jar' * (http://stackoverflow.com/questions/1664604/jsobject-download-it-or-available-in-jre-1-6) however * the only plugin.jar's I found for Java via the 'locate plugin.jar' command were either bad symlinks or inside * .bundle so I had to create a good symlink called plugin-daniel.jar in /System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Home/lib * that pointed to /System/Library/Frameworks/JavaVM.framework/Versions/A/Resources/Deploy.bundle/Contents/Resources/Java/plugin.jar * I had no issue adding it on Windows or Linux. * * Further information: http://java.sun.com/j2se/1.5.0/docs/guide/plugin/developer_guide/java_js.html */ public class Applet extends JApplet { private static final long serialVersionUID = 4544354980928245103L; public static File BASE_FOLDER, BIN_FOLDER, DESKTOP_FOLDER; public static URL DOCUMENT_BASE, CODE_BASE; public static JApplet APPLET; public static JSObject JS_BRIDGE; public static String POST_URL = null, SCREEN_CAPTURE_NAME = null, API_KEY, HOST_URL; public static boolean HEADLESS = false; public static boolean IS_MAC = System.getProperty("os.name").toLowerCase().contains("mac"); public static boolean IS_LINUX = System.getProperty("os.name").toLowerCase().contains("linux"); public static boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().contains("windows"); public static boolean DEV_MODE = false; public final static Dimension SCREEN = new Dimension( // for the primary monitor only GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode().getWidth(), GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode().getHeight()); public final static CaptureViewport CAPTURE_VIEWPORT = new CaptureViewport(); public static Vector<Window> APPLET_WINDOWS = new Vector<Window>(); // didn't want to manually manage windows, but Safari would only return a Frame through Window.getWindows() on commands called via JS private AbstractController controller = null; private static Logger logger = Logger.getLogger(Applet.class); public static Properties PROPERTIES = new Properties(); // TODO move some of these static variables into the Properties obj? clean up properties in general? /** * The init method is called when this applet is loaded into the browser. It is used to initialize * finish initializing all static variables used for state. */ @Override public void init() { try { if(getParameter("dev_mode") != null) - DEV_MODE = true; + DEV_MODE = getParameter("dev_mode").equals("true"); // setup properties configuration (should before base folder) if(Applet.DEV_MODE) { PROPERTIES.load(new FileInputStream("../config.properties")); } else { PROPERTIES.load(this.getClass().getClassLoader().getResourceAsStream("config.properties")); } BASE_FOLDER = new File(getBaseFolderPath()); // should be next, after property loading BIN_FOLDER = new File(getBinFolderPath()); DESKTOP_FOLDER = new File(getDesktopFolderPath()); // setup logging (http://www.theserverside.com/discussions/thread.tss?thread_id=42709) if(Applet.DEV_MODE) { System.setProperty("log.file.path", "../logs/development.log"); PropertyConfigurator.configure("../logs/log4j.properties"); } else { System.setProperty("log.file.path", BASE_FOLDER.getAbsolutePath()+File.separator+"production.log"); PropertyConfigurator.configure(this.getClass().getClassLoader().getResource("log4j.properties")); } // setup the javascript API try { JS_BRIDGE = JSObject.getWindow(this); } catch(JSException e) { logger.error("Could not create JSObject. Probably in development mode."); } DOCUMENT_BASE = getDocumentBase(); CODE_BASE = getCodeBase(); APPLET = this; // breaking OOP so I can have a "root" POST_URL = getParameter("post_url"); API_KEY = getParameter("api_key"); SCREEN_CAPTURE_NAME = getParameter("screen_capture_name"); HOST_URL = DOCUMENT_BASE.getProtocol() + "://" + DOCUMENT_BASE.getHost(); // verify that we have what we need if(getParameter("headless") != null) HEADLESS = !getParameter("headless").isEmpty() && getParameter("headless").equals("true"); // Boolean.getBoolean(string) didn't work if( BASE_FOLDER.exists() && !BASE_FOLDER.isDirectory() && !BASE_FOLDER.delete() ) throw new IOException("Could not delete file for folder: " + BASE_FOLDER.getAbsolutePath()); if( !BASE_FOLDER.exists() && !BASE_FOLDER.mkdir() ) throw new IOException("Could not create folder: " + BASE_FOLDER.getAbsolutePath()); // print information to console logger.info(getAppletInfo()); // execute a job on the event-dispatching thread; creating this applet's GUI SwingUtilities.invokeAndWait(new Runnable() { public void run() { // start up the os-specific controller if(IS_MAC) controller = new MacController(); else if(IS_LINUX) controller = new LinuxController(); else if(IS_WINDOWS) controller = new WindowsController(); else System.err.println("Want to launch controller but don't which operating system this is!"); } }); SwingUtilities.invokeLater(new Runnable() { public void run() { if(controller != null) controller.setupExtensions(); } }); } catch (Exception e) { logger.error("Could not create GUI!",e); } } /** * Sends a notification to all the views and each can update itself accordingly. * * @param notification * @param body */ public static void sendViewNotification(ViewNotifications notification,Object body) { // applet is a special case (see ApplicationController constructor) if(APPLET.getContentPane().getComponents().length > 0) ((ViewListener) APPLET.getContentPane().getComponent(0)).receiveViewNotification(notification, body); // another special case where the capture viewport is a pseudo-model CAPTURE_VIEWPORT.receiveViewNotification(notification, body); // notify all the open windows (tried Window.getWindows() but had issues) for(Window win : Applet.APPLET_WINDOWS) { if(win instanceof ViewListener) { ((ViewListener) win).receiveViewNotification(notification, body); } } } public static void sendViewNotification(ViewNotifications notification) { sendViewNotification(notification, null); } // ---------- BEGIN INCOMING JAVASCRIPT API ---------- /** * Allow an external interface trigger the count-down and subsequent recording */ public void prepareAndRecord() { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { try { controller.recordGUI.prepareForRecording(); } catch (Exception e) { logger.error("Can't prepare and start the recording!",e); } return null; } }); } /** * Allow an external interface top the recording */ public void stopRecording() { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { try { controller.recordGUI.stopRecording(); } catch (Exception e) { logger.error("Can't stop the recording!",e); } return null; } }); } /** * Allow an external interface to open the preview player */ public void previewRecording() { controller.previewRecording(); } /** * Allow an external interface change where the final movie file is posted to */ public void changePostUrl(final String url) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { try { POST_URL = url; logger.info("Changed post URL to "+url); } catch (Exception e) { logger.error("Can't change the post URL!",e); } return null; } }); } /** * Allow an external interface to post process and upload the recording */ public void postRecording() { controller.postRecording(); } /** * Allow an external interface to show the recording interface */ public void showRecordingInterface() { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { try { SwingUtilities.invokeLater(new Runnable() { public void run() { if(controller != null) { if (AttributesManager.OUTPUT_FILE.exists()) { handleExistingRecording(); logger.info("Outside call to show recording interface, but prior review exists..."); } else { controller.showRecordingInterface(); logger.info("Outside call to show recording interface. Showing recording tools..."); } } else { logger.error("No controller exists!"); } } }); } catch (Exception e) { logger.error("Can't show the recording interface!",e); } return null; } }); } /** * Allow an external interface to hide the recording interface */ public void hideRecordingInterface() { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { try { SwingUtilities.invokeLater(new Runnable() { public void run() { if(controller != null) controller.hideRecordingInterface(); } }); } catch (Exception e) { logger.error("Can't hide the recording interface!",e); } return null; } }); } // ---------- END INCOMING / BEGIN OUTGOING JAVASCRIPT API ---------- public static void handleRecordingUpdate(ViewNotifications state,String status) { if(status == null) status = ""; jsCall("sct_handle_recording_update(\""+state+"\",\""+status+"\");"); } public static void handleRecordingUIHide() { jsCall("sct_handle_recording_ui_hide();"); } public static void handleExistingRecording() { jsCall("sct_handle_existing_recording()"); } public static void handleFreshRecording() { jsCall("sct_handle_fresh_recording()"); } public static void handleUploadedRecording() { jsCall("sct_handle_uploaded_recording()"); } public static void handleDeletedRecording() { jsCall("sct_handle_deleted_recording()"); } public static void redirectWebPage(String url) { jsCall("sct_redirect_page(\""+url+"\");"); } public static void sendShowStatus(String message) { jsCall("sct_show_status(\""+message+"\");"); } public static void sendHideStatus() { jsCall("sct_hide_status();"); } public static void sendInfo(String message) { jsCall("sct_info(\""+message+"\");"); } public static void sendError(String message) { jsCall("sct_error(\""+message+"\");"); } private static void jsCall(String method) { if(JS_BRIDGE == null) { logger.error("Call to "+method+" but no JS Bridge exists. Probably in development mode..."); } else { //System.out.println("Sending javascript call: "+method); //JSObject doc = (JSObject) JS_BRIDGE.getMember("document"); //doc.eval(method); JS_BRIDGE.eval(method); } } // ---------- END OUTGOING JAVASCRIPT API ---------- /** * Copies an entire folder out of a jar to a physical location. * * Base code: http://forums.sun.com/thread.jspa?threadID=5154854 * Helpful: http://mindprod.com/jgloss/getresourceasstream.html * Helpful: http://stackoverflow.com/questions/810284/putting-bat-file-inside-a-jar-file * * @param jarName Path and name of the jar to extract from * @param folderName Single name, not path, of the folder to pull from the root of the jar. */ public static void copyFolderFromCurrentJar(String jarName, String folderName) { if(jarName == null || folderName == null) return; try { ZipFile z = new ZipFile(jarName); Enumeration<? extends ZipEntry> entries = z.entries(); // make the folder first //File folder = new File(RFX_FOLDER.getAbsolutePath()+File.separator+folderName); //if( !folder.exists() ) folder.mkdir(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry)entries.nextElement(); if (entry.getName().contains(folderName)) { File f = new File(BASE_FOLDER.getAbsolutePath()+File.separator+entry.getName()); if (entry.isDirectory() && f.mkdir()) { logger.info("Created folder "+f.getAbsolutePath()+" for "+entry.getName()); } else if (!f.exists()) { if (copyFileFromJar(entry.getName(), f)) { logger.info("Copied file: " + entry.getName()); } else { logger.error("Could not copy file: "+entry.getName()); } } } } } catch (IOException e) { e.printStackTrace(); } } /** * Use this one or loading from a remote jar and extracting it. * * @param jar * @param folderName */ public static void copyFolderFromRemoteJar(URL jar, String folderName) { if(jar == null || folderName == null) return; try { JarClassLoader jarLoader = new JarClassLoader(jar); URL u = new URL("jar", "", jar + "!/"); JarURLConnection uc = (JarURLConnection)u.openConnection(); JarFile jarFile = uc.getJarFile(); Enumeration<? extends JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry)entries.nextElement(); if (entry.getName().contains(folderName)) { File f = new File(BASE_FOLDER.getAbsolutePath()+File.separator+entry.getName()); if (entry.isDirectory() && f.mkdir()) { logger.info("Created folder "+f.getAbsolutePath()+" for "+entry.getName()); } else if (!f.exists()) { if (copyFileFromJar(entry.getName(), f, jarLoader)) { logger.info("Copied file: " + entry.getName()); } else { logger.error("Could not copy file: "+entry.getName()); } } } } } catch (IOException e) { e.printStackTrace(); } } protected static boolean copyFileFromJar(String sResource, File fDest) { return copyFileFromJar(sResource, fDest, Applet.class.getClassLoader()); } /** * Copies a file out of the jar to a physical location. * Doesn't need to be private, uses a resource stream, so may have * security errors if run from webstart application * * Base code: http://forums.sun.com/thread.jspa?threadID=5154854 * Helpful: http://mindprod.com/jgloss/getresourceasstream.html * Helpful: http://stackoverflow.com/questions/810284/putting-bat-file-inside-a-jar-file */ protected static boolean copyFileFromJar(String sResource, File fDest, ClassLoader loader) { if (sResource == null || fDest == null) return false; InputStream sIn = null; OutputStream sOut = null; File sFile = null; try { fDest.getParentFile().mkdirs(); sFile = new File(sResource); } catch(Exception e) { e.printStackTrace(); } try { int nLen = 0; sIn = loader.getResourceAsStream(sResource); if (sIn == null) throw new IOException("Could not get resource as stream to copy " + sResource + " from the jar to " + fDest.getAbsolutePath() + ")"); sOut = new FileOutputStream(fDest); byte[] bBuffer = new byte[1024]; while ((nLen = sIn.read(bBuffer)) > 0) sOut.write(bBuffer, 0, nLen); sOut.flush(); } catch(IOException ex) { ex.printStackTrace(); } finally { try { if (sIn != null) sIn.close(); if (sOut != null) sOut.close(); } catch (IOException eError) { eError.printStackTrace(); } } return fDest.exists(); } /** * Print out information the configuration the Applet is running under. * * base code: http://stackoverflow.com/questions/2234476/how-to-detect-the-current-display-with-java */ @Override public String getAppletInfo() { // screen the Applet is on GraphicsDevice myScreen = getGraphicsConfiguration().getDevice(); // screen the start bar, OS bar, whatever is on GraphicsDevice primaryScreen = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); // all screens GraphicsDevice[] allScreens = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); int myScreenIndex = -1, primaryScreenIndex = -1; for (int i = 0; i < allScreens.length; i++) { if (allScreens[i].equals(myScreen)) { myScreenIndex = i; } if (allScreens[i].equals(primaryScreen)) { primaryScreenIndex = i; } } try { return "\n\n\n\nAPPLET PROPERLY INITIALIZED WITH THIS VARIABLES:\n"+ "Java Version: \t"+System.getProperty("java.version")+"\n"+ "OS Name: \t"+System.getProperty("os.name")+"\n"+ "OS Version: \t"+System.getProperty("os.version")+"\n"+ "Dev Mode? \t"+DEV_MODE+"\n"+ "Run Directory: \t"+System.getProperty("user.dir")+"\n"+ "User Home: \t"+System.getProperty("user.home")+"\n"+ "User Name: \t"+System.getProperty("user.name")+"\n"+ "Base Folder: \t"+BASE_FOLDER.getPath()+"\n"+ "Bin Folder: \t"+BIN_FOLDER.getPath()+"\n"+ "User Desktop: \t"+DESKTOP_FOLDER.getPath()+"\n"+ "Host URL:\t"+HOST_URL+"\n"+ "Code Base: \t"+getCodeBase()+"\n"+ "Document Base: \t"+getDocumentBase()+"\n"+ "Execution URL: \t"+Applet.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()+"\n"+ "Multiple Monitors: \t"+(allScreens.length > 1)+"\n"+ "Applet window is on screen " + myScreenIndex+"\n"+ "Primary screen is index " + primaryScreenIndex+"\n"+ "Primary screen resolution: "+SCREEN+"\n"+ "Headless: \t"+HEADLESS; } catch (URISyntaxException e) { e.printStackTrace(); return "Error"; } /* System.out.println("Have these system variables:"); Map<String, String> sysEnv = System.getenv(); for (String envName : sysEnv.keySet()) { System.out.format("%s=%s%n", envName, sysEnv.get(envName)); } */ //System.out.println("Free space: \n"+TEMP_FOLDER.getFreeSpace()+" GBs"); // Java 1.6 only //System.out.println("Total space: \n"+TEMP_FOLDER.getTotalSpace()+" GBs"); } /** * The "base" folder is where all preference files and media files are recorded. * * @return * @throws IOException */ public static String getBaseFolderPath() throws IOException { if(IS_MAC) return System.getProperty("user.home")+File.separator+"Library"+File.separator+PROPERTIES.getProperty("base.folder"); else if(IS_LINUX) return System.getProperty("user.home")+File.separator+"."+PROPERTIES.getProperty("base.folder"); else if(IS_WINDOWS) return System.getenv("TEMP")+File.separator+PROPERTIES.getProperty("base.folder"); else throw new IOException("I don't know where to find the native extensions!"); } /** * The "bin" folder is where the binaries are downloaded to and execute from. * * @return * @throws IOException */ public static String getBinFolderPath() throws IOException { return BASE_FOLDER.getAbsolutePath()+File.separator+getBinFolderName(); } /** * These must start with "bin". * * @return Name of folder and JAR with folder of same name for holding native extensions. * @throws IOException */ public static String getBinFolderName() throws IOException { if(IS_MAC) return "bin-mac"; else if(IS_LINUX) return "bin-linux"; else if(IS_WINDOWS) return "bin-windows-v1.2"; else throw new IOException("I don't know what bin folder to use!"); } /** * Determines the desktop folder for the machine that the Java applet is running on. Not tested, and not used. * @return * @throws IOException */ public static String getDesktopFolderPath() throws IOException { if(IS_MAC || IS_LINUX || IS_WINDOWS) return System.getProperty("user.home")+File.separator+"Desktop"; else throw new IOException("I don't know where to find the user's desktop!"); } /** * Called when the browser closes the web page. * * NOTE: A bug in Mac OS X may prevent this from being called: http://lists.apple.com/archives/java-dev///2009/Oct/msg00042.html */ @Override public void destroy() { System.out.println("Closing down..."); if(controller != null) controller.closeDown(); controller = null; } }
true
true
public void init() { try { if(getParameter("dev_mode") != null) DEV_MODE = true; // setup properties configuration (should before base folder) if(Applet.DEV_MODE) { PROPERTIES.load(new FileInputStream("../config.properties")); } else { PROPERTIES.load(this.getClass().getClassLoader().getResourceAsStream("config.properties")); } BASE_FOLDER = new File(getBaseFolderPath()); // should be next, after property loading BIN_FOLDER = new File(getBinFolderPath()); DESKTOP_FOLDER = new File(getDesktopFolderPath()); // setup logging (http://www.theserverside.com/discussions/thread.tss?thread_id=42709) if(Applet.DEV_MODE) { System.setProperty("log.file.path", "../logs/development.log"); PropertyConfigurator.configure("../logs/log4j.properties"); } else { System.setProperty("log.file.path", BASE_FOLDER.getAbsolutePath()+File.separator+"production.log"); PropertyConfigurator.configure(this.getClass().getClassLoader().getResource("log4j.properties")); } // setup the javascript API try { JS_BRIDGE = JSObject.getWindow(this); } catch(JSException e) { logger.error("Could not create JSObject. Probably in development mode."); } DOCUMENT_BASE = getDocumentBase(); CODE_BASE = getCodeBase(); APPLET = this; // breaking OOP so I can have a "root" POST_URL = getParameter("post_url"); API_KEY = getParameter("api_key"); SCREEN_CAPTURE_NAME = getParameter("screen_capture_name"); HOST_URL = DOCUMENT_BASE.getProtocol() + "://" + DOCUMENT_BASE.getHost(); // verify that we have what we need if(getParameter("headless") != null) HEADLESS = !getParameter("headless").isEmpty() && getParameter("headless").equals("true"); // Boolean.getBoolean(string) didn't work if( BASE_FOLDER.exists() && !BASE_FOLDER.isDirectory() && !BASE_FOLDER.delete() ) throw new IOException("Could not delete file for folder: " + BASE_FOLDER.getAbsolutePath()); if( !BASE_FOLDER.exists() && !BASE_FOLDER.mkdir() ) throw new IOException("Could not create folder: " + BASE_FOLDER.getAbsolutePath()); // print information to console logger.info(getAppletInfo()); // execute a job on the event-dispatching thread; creating this applet's GUI SwingUtilities.invokeAndWait(new Runnable() { public void run() { // start up the os-specific controller if(IS_MAC) controller = new MacController(); else if(IS_LINUX) controller = new LinuxController(); else if(IS_WINDOWS) controller = new WindowsController(); else System.err.println("Want to launch controller but don't which operating system this is!"); } }); SwingUtilities.invokeLater(new Runnable() { public void run() { if(controller != null) controller.setupExtensions(); } }); } catch (Exception e) { logger.error("Could not create GUI!",e); } }
public void init() { try { if(getParameter("dev_mode") != null) DEV_MODE = getParameter("dev_mode").equals("true"); // setup properties configuration (should before base folder) if(Applet.DEV_MODE) { PROPERTIES.load(new FileInputStream("../config.properties")); } else { PROPERTIES.load(this.getClass().getClassLoader().getResourceAsStream("config.properties")); } BASE_FOLDER = new File(getBaseFolderPath()); // should be next, after property loading BIN_FOLDER = new File(getBinFolderPath()); DESKTOP_FOLDER = new File(getDesktopFolderPath()); // setup logging (http://www.theserverside.com/discussions/thread.tss?thread_id=42709) if(Applet.DEV_MODE) { System.setProperty("log.file.path", "../logs/development.log"); PropertyConfigurator.configure("../logs/log4j.properties"); } else { System.setProperty("log.file.path", BASE_FOLDER.getAbsolutePath()+File.separator+"production.log"); PropertyConfigurator.configure(this.getClass().getClassLoader().getResource("log4j.properties")); } // setup the javascript API try { JS_BRIDGE = JSObject.getWindow(this); } catch(JSException e) { logger.error("Could not create JSObject. Probably in development mode."); } DOCUMENT_BASE = getDocumentBase(); CODE_BASE = getCodeBase(); APPLET = this; // breaking OOP so I can have a "root" POST_URL = getParameter("post_url"); API_KEY = getParameter("api_key"); SCREEN_CAPTURE_NAME = getParameter("screen_capture_name"); HOST_URL = DOCUMENT_BASE.getProtocol() + "://" + DOCUMENT_BASE.getHost(); // verify that we have what we need if(getParameter("headless") != null) HEADLESS = !getParameter("headless").isEmpty() && getParameter("headless").equals("true"); // Boolean.getBoolean(string) didn't work if( BASE_FOLDER.exists() && !BASE_FOLDER.isDirectory() && !BASE_FOLDER.delete() ) throw new IOException("Could not delete file for folder: " + BASE_FOLDER.getAbsolutePath()); if( !BASE_FOLDER.exists() && !BASE_FOLDER.mkdir() ) throw new IOException("Could not create folder: " + BASE_FOLDER.getAbsolutePath()); // print information to console logger.info(getAppletInfo()); // execute a job on the event-dispatching thread; creating this applet's GUI SwingUtilities.invokeAndWait(new Runnable() { public void run() { // start up the os-specific controller if(IS_MAC) controller = new MacController(); else if(IS_LINUX) controller = new LinuxController(); else if(IS_WINDOWS) controller = new WindowsController(); else System.err.println("Want to launch controller but don't which operating system this is!"); } }); SwingUtilities.invokeLater(new Runnable() { public void run() { if(controller != null) controller.setupExtensions(); } }); } catch (Exception e) { logger.error("Could not create GUI!",e); } }
diff --git a/src/main/java/net/nightwhistler/pageturner/activity/LibraryActivity.java b/src/main/java/net/nightwhistler/pageturner/activity/LibraryActivity.java index 99858ac..fe2d14c 100644 --- a/src/main/java/net/nightwhistler/pageturner/activity/LibraryActivity.java +++ b/src/main/java/net/nightwhistler/pageturner/activity/LibraryActivity.java @@ -1,1075 +1,1075 @@ /* * Copyright (C) 2011 Alex Kuiper * * This file is part of PageTurner * * PageTurner 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. * * PageTurner 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 PageTurner. If not, see <http://www.gnu.org/licenses/>.* */ package net.nightwhistler.pageturner.activity; import java.io.File; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import net.nightwhistler.htmlspanner.HtmlSpanner; import net.nightwhistler.pageturner.Configuration; import net.nightwhistler.pageturner.Configuration.LibrarySelection; import net.nightwhistler.pageturner.Configuration.LibraryView; import net.nightwhistler.pageturner.R; import net.nightwhistler.pageturner.library.ImportCallback; import net.nightwhistler.pageturner.library.ImportTask; import net.nightwhistler.pageturner.library.KeyedQueryResult; import net.nightwhistler.pageturner.library.KeyedResultAdapter; import net.nightwhistler.pageturner.library.LibraryBook; import net.nightwhistler.pageturner.library.LibraryService; import net.nightwhistler.pageturner.library.QueryResult; import net.nightwhistler.pageturner.view.BookCaseView; import net.nightwhistler.pageturner.view.FastBitmapDrawable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import roboguice.activity.RoboActivity; import roboguice.inject.InjectView; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.database.sqlite.SQLiteException; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.ListView; import android.widget.RadioButton; import android.widget.Spinner; import android.widget.TextView; import android.widget.ViewSwitcher; import com.google.inject.Inject; public class LibraryActivity extends RoboActivity implements ImportCallback, OnItemClickListener { @Inject private LibraryService libraryService; @InjectView(R.id.librarySpinner) private Spinner spinner; @InjectView(R.id.libraryList) private ListView listView; @InjectView(R.id.bookCaseView) private BookCaseView bookCaseView; @InjectView(R.id.alphabetList) private ListView alphabetBar; private AlphabetAdapter alphabetAdapter; @InjectView(R.id.alphabetDivider) private ImageView alphabetDivider; @InjectView(R.id.libHolder) private ViewSwitcher switcher; @Inject private Configuration config; private Drawable backupCover; private Handler handler; private static final int[] ICONS = { R.drawable.book_binoculars, R.drawable.book_add, R.drawable.book_star, R.drawable.book, R.drawable.user }; private KeyedResultAdapter bookAdapter; private static final DateFormat DATE_FORMAT = DateFormat.getDateInstance(DateFormat.LONG); private static final int ALPHABET_THRESHOLD = 20; private ProgressDialog waitDialog; private ProgressDialog importDialog; private AlertDialog importQuestion; private boolean askedUserToImport; private boolean oldKeepScreenOn; private static final Logger LOG = LoggerFactory.getLogger(LibraryActivity.class); private IntentCallBack intentCallBack; private List<CoverCallback> callbacks = new ArrayList<CoverCallback>(); private Map<String, Drawable> coverCache = new HashMap<String, Drawable>(); private interface IntentCallBack { void onResult( int resultCode, Intent data ); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.library_menu); Bitmap backupBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.unknown_cover ); this.backupCover = new FastBitmapDrawable(backupBitmap); this.handler = new Handler(); if ( savedInstanceState != null ) { this.askedUserToImport = savedInstanceState.getBoolean("import_q", false); } this.bookCaseView.setOnScrollListener( new CoverScrollListener() ); this.listView.setOnScrollListener( new CoverScrollListener() ); if ( config.getLibraryView() == LibraryView.BOOKCASE ) { this.bookAdapter = new BookCaseAdapter(this); this.bookCaseView.setAdapter(bookAdapter); if ( switcher.getDisplayedChild() == 0 ) { switcher.showNext(); } } else { this.bookAdapter = new BookListAdapter(this); this.listView.setAdapter(bookAdapter); } ArrayAdapter<String> adapter = new QueryMenuAdapter(this, getResources().getStringArray(R.array.libraryQueries)); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new MenuSelectionListener()); this.waitDialog = new ProgressDialog(this); this.waitDialog.setOwnerActivity(this); this.importDialog = new ProgressDialog(this); this.importDialog.setOwnerActivity(this); importDialog.setTitle(R.string.importing_books); importDialog.setMessage(getString(R.string.scanning_epub)); registerForContextMenu(this.listView); this.listView.setOnItemClickListener(this); setAlphabetBarVisible(false); } private void onBookClicked( LibraryBook book ) { showBookDetails(book); } @Override public void onItemClick(AdapterView<?> parent, View view, int pos, long id) { onBookClicked(this.bookAdapter.getResultAt(pos)); } private Bitmap getCover( LibraryBook book ) { return BitmapFactory.decodeByteArray(book.getCoverImage(), 0, book.getCoverImage().length ); } private void showBookDetails( final LibraryBook libraryBook ) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.book_details); LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.book_details, null); builder.setView( layout ); ImageView coverView = (ImageView) layout.findViewById(R.id.coverImage ); if ( libraryBook.getCoverImage() != null ) { coverView.setImageBitmap( getCover(libraryBook) ); } else { coverView.setImageDrawable( getResources().getDrawable(R.drawable.unknown_cover)); } TextView titleView = (TextView) layout.findViewById(R.id.titleField); TextView authorView = (TextView) layout.findViewById(R.id.authorField); TextView lastRead = (TextView) layout.findViewById(R.id.lastRead); TextView added = (TextView) layout.findViewById(R.id.addedToLibrary); TextView descriptionView = (TextView) layout.findViewById(R.id.bookDescription); TextView fileName = (TextView) layout.findViewById(R.id.fileName); titleView.setText(libraryBook.getTitle()); String authorText = String.format( getString(R.string.book_by), libraryBook.getAuthor().getFirstName() + " " + libraryBook.getAuthor().getLastName() ); authorView.setText( authorText ); fileName.setText( libraryBook.getFileName() ); if (libraryBook.getLastRead() != null && ! libraryBook.getLastRead().equals(new Date(0))) { String lastReadText = String.format(getString(R.string.last_read), DATE_FORMAT.format(libraryBook.getLastRead())); lastRead.setText( lastReadText ); } else { String lastReadText = String.format(getString(R.string.last_read), getString(R.string.never_read)); lastRead.setText( lastReadText ); } String addedText = String.format( getString(R.string.added_to_lib), DATE_FORMAT.format(libraryBook.getAddedToLibrary())); added.setText( addedText ); descriptionView.setText(new HtmlSpanner().fromHtml( libraryBook.getDescription())); builder.setNeutralButton(R.string.delete, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { libraryService.deleteBook( libraryBook.getFileName() ); new LoadBooksTask().execute(config.getLastLibraryQuery()); dialog.dismiss(); } }); builder.setNegativeButton(android.R.string.cancel, null); builder.setPositiveButton(R.string.read, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(LibraryActivity.this, ReadingActivity.class); intent.setData( Uri.parse(libraryBook.getFileName())); setResult(RESULT_OK, intent); startActivityIfNeeded(intent, 99); } }); builder.show(); } private void showDownloadDialog() { final List<String> names = new ArrayList<String>(){{ add("Feedbooks"); add("Manybooks.net"); add("Gutenberg.org"); }}; final List<String> addresses = new ArrayList<String>(){{ add("http://www.feedbooks.com/site/free_books.atom"); add("http://www.manybooks.net/opds/index.php"); //"http://www.allromanceebooks.com/epub-feed.xml", //"http://bookserver.archive.org/catalog/", add("http://m.gutenberg.org/ebooks/?format=opds"); }}; if ( config.getCalibreServer().length() != 0 ) { names.add("Calibre server"); addresses.add(config.getCalibreServer()); } AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.download); builder.setItems(names.toArray(new String[names.size()]), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { Intent intent = new Intent(LibraryActivity.this, CatalogActivity.class); intent.putExtra("url", addresses.get(item)); startActivityIfNeeded(intent, 99); } }); builder.show(); } private void startImport(File startFolder, boolean copy) { ImportTask importTask = new ImportTask(this, libraryService, this, copy); importDialog.setOnCancelListener(importTask); importDialog.show(); this.oldKeepScreenOn = listView.getKeepScreenOn(); listView.setKeepScreenOn(true); importTask.execute(startFolder); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if ( this.intentCallBack != null ) { this.intentCallBack.onResult(resultCode, data); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.library_menu, menu); OnMenuItemClickListener toggleListener = new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { if ( switcher.getDisplayedChild() == 0 ) { bookAdapter = new BookCaseAdapter(LibraryActivity.this); bookCaseView.setAdapter(bookAdapter); config.setLibraryView(LibraryView.BOOKCASE); } else { bookAdapter = new BookListAdapter(LibraryActivity.this); listView.setAdapter(bookAdapter); config.setLibraryView(LibraryView.LIST); } switcher.showNext(); new LoadBooksTask().execute(config.getLastLibraryQuery()); return true; } }; MenuItem shelves = menu.findItem(R.id.shelves_view); shelves.setOnMenuItemClickListener(toggleListener); MenuItem list = menu.findItem(R.id.list_view); list.setOnMenuItemClickListener(toggleListener); MenuItem prefs = menu.findItem(R.id.preferences); prefs.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { Intent intent = new Intent(LibraryActivity.this, PageTurnerPrefsActivity.class); startActivity(intent); return true; } }); MenuItem scan = menu.findItem(R.id.scan_books); scan.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { showImportDialog(); return true; } }); MenuItem about = menu.findItem(R.id.about); about.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { Dialogs.showAboutDialog(LibraryActivity.this); return true; } }); MenuItem download = menu.findItem(R.id.download); download.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { showDownloadDialog(); return true; } }); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean bookCaseActive = switcher.getDisplayedChild() != 0; menu.findItem(R.id.shelves_view).setVisible(! bookCaseActive); menu.findItem(R.id.list_view).setVisible(bookCaseActive); return true; } private void showImportDialog() { AlertDialog.Builder builder; LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); final View layout = inflater.inflate(R.layout.import_dialog, null); final RadioButton scanSpecific = (RadioButton) layout.findViewById(R.id.radioScanFolder); final TextView folder = (TextView) layout.findViewById(R.id.folderToScan); final CheckBox copyToLibrary = (CheckBox) layout.findViewById(R.id.copyToLib); final Button browseButton = (Button) layout.findViewById(R.id.browseButton); folder.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { scanSpecific.setChecked(true); } }); //Copy default setting from the prefs copyToLibrary.setChecked( config.isCopyToLibrayEnabled() ); builder = new AlertDialog.Builder(this); builder.setView(layout); OnClickListener okListener = new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if ( scanSpecific.isChecked() ) { startImport(new File(folder.getText().toString()), copyToLibrary.isChecked() ); } else { startImport(new File("/sdcard"), copyToLibrary.isChecked()); } } }; View.OnClickListener browseListener = new View.OnClickListener() { @Override public void onClick(View v) { scanSpecific.setChecked(true); Intent intent = new Intent(LibraryActivity.this, FileBrowseActivity.class); intent.setData( Uri.parse(folder.getText().toString() )); startActivityForResult(intent, 0); } }; this.intentCallBack = new IntentCallBack() { @Override public void onResult(int resultCode, Intent data) { if ( resultCode == RESULT_OK && data != null ) { folder.setText(data.getData().getPath()); } } }; browseButton.setOnClickListener(browseListener); builder.setTitle(R.string.import_books); builder.setPositiveButton(android.R.string.ok, okListener ); builder.setNegativeButton(android.R.string.cancel, null ); builder.show(); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putBoolean("import_q", askedUserToImport); } @Override protected void onStop() { this.libraryService.close(); this.waitDialog.dismiss(); this.importDialog.dismiss(); super.onStop(); } @Override public void onBackPressed() { finish(); } @Override protected void onPause() { this.bookAdapter.clear(); this.libraryService.close(); //We clear the list to free up memory. super.onPause(); } @Override protected void onResume() { super.onResume(); LibrarySelection lastSelection = config.getLastLibraryQuery(); if ( spinner.getSelectedItemPosition() != lastSelection.ordinal() ) { spinner.setSelection(lastSelection.ordinal()); } else { new LoadBooksTask().execute(lastSelection); } } @Override public void importCancelled() { listView.setKeepScreenOn(oldKeepScreenOn); //Switch to the "recently added" view. if ( spinner.getSelectedItemPosition() == LibrarySelection.LAST_ADDED.ordinal() ) { new LoadBooksTask().execute(LibrarySelection.LAST_ADDED); } else { spinner.setSelection(LibrarySelection.LAST_ADDED.ordinal()); } } @Override public void importComplete(int booksImported, List<String> errors) { importDialog.hide(); OnClickListener dismiss = new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }; //If the user cancelled the import, don't bug him/her with alerts. if ( (! errors.isEmpty()) ) { AlertDialog.Builder builder = new AlertDialog.Builder(LibraryActivity.this); builder.setTitle(R.string.import_errors); builder.setItems( errors.toArray(new String[errors.size()]), null ); builder.setNeutralButton(android.R.string.ok, dismiss ); builder.show(); } listView.setKeepScreenOn(oldKeepScreenOn); if ( booksImported > 0 ) { //Switch to the "recently added" view. if ( spinner.getSelectedItemPosition() == LibrarySelection.LAST_ADDED.ordinal() ) { new LoadBooksTask().execute(LibrarySelection.LAST_ADDED); } else { spinner.setSelection(LibrarySelection.LAST_ADDED.ordinal()); } } else { AlertDialog.Builder builder = new AlertDialog.Builder(LibraryActivity.this); builder.setTitle(R.string.no_books_found); builder.setMessage( getString(R.string.no_bks_fnd_text) ); builder.setNeutralButton(android.R.string.ok, dismiss); builder.show(); } } @Override public void importFailed(String reason) { importDialog.hide(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.import_failed); builder.setMessage(reason); builder.setNeutralButton(android.R.string.ok, null); builder.show(); } @Override public void importStatusUpdate(String update) { importDialog.setMessage(update); } public void onAlphabetBarClick( KeyedQueryResult<LibraryBook> result, Character c ) { int index = result.getOffsetFor(Character.toUpperCase(c)); if ( index == -1 ) { return; } if ( alphabetAdapter != null ) { alphabetAdapter.setHighlightChar(c); } if ( config.getLibraryView() == LibraryView.BOOKCASE ) { this.bookCaseView.setSelection(index); } else { this.listView.setSelection(index); } } /** * Based on example found here: * http://www.vogella.de/articles/AndroidListView/article.html * * @author work * */ private class BookListAdapter extends KeyedResultAdapter { private Context context; public BookListAdapter(Context context) { this.context = context; } @Override public View getView(int index, final LibraryBook book, View convertView, ViewGroup parent) { View rowView; if ( convertView == null ) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = inflater.inflate(R.layout.book_row, parent, false); } else { rowView = convertView; } TextView titleView = (TextView) rowView.findViewById(R.id.bookTitle); TextView authorView = (TextView) rowView.findViewById(R.id.bookAuthor); TextView dateView = (TextView) rowView.findViewById(R.id.addedToLibrary); TextView progressView = (TextView) rowView.findViewById(R.id.readingProgress); final ImageView imageView = (ImageView) rowView.findViewById(R.id.bookCover); String authorText = String.format(getString(R.string.book_by), book.getAuthor().getFirstName() + " " + book.getAuthor().getLastName() ); authorView.setText(authorText); titleView.setText(book.getTitle()); if ( book.getProgress() > 0 ) { progressView.setText( "" + book.getProgress() + "%"); } else { progressView.setText(""); } String dateText = String.format(getString(R.string.added_to_lib), DATE_FORMAT.format(book.getAddedToLibrary())); dateView.setText( dateText ); loadCover(imageView, book, index); return rowView; } } private void loadCover( ImageView imageView, LibraryBook book, int index ) { Drawable draw = coverCache.get(book.getFileName()); if ( draw != null ) { imageView.setImageDrawable(draw); } else { imageView.setImageDrawable(backupCover); if ( book.getCoverImage() != null ) { callbacks.add( new CoverCallback(book, index, imageView ) ); } } } private class CoverScrollListener implements AbsListView.OnScrollListener { private Runnable lastRunnable; private Character lastCharacter; @Override public void onScroll(AbsListView view, final int firstVisibleItem, final int visibleItemCount, final int totalItemCount) { if ( visibleItemCount == 0 ) { return; } if ( this.lastRunnable != null ) { handler.removeCallbacks(lastRunnable); } this.lastRunnable = new Runnable() { @Override public void run() { if ( bookAdapter.isKeyed() ) { String key = bookAdapter.getKey( firstVisibleItem ); Character keyChar = null; if ( key.length() > 0 ) { keyChar = Character.toUpperCase( key.charAt(0) ); } if (keyChar != null && ! keyChar.equals(lastCharacter)) { lastCharacter = keyChar; List<Character> alphabet = bookAdapter.getAlphabet(); //If the highlight-char is already set, this means the //user clicked the bar, so don't scroll it. if (alphabetAdapter != null && ! keyChar.equals( alphabetAdapter.getHighlightChar() ) ) { alphabetAdapter.setHighlightChar(keyChar); alphabetBar.setSelection( alphabet.indexOf(keyChar) ); } for ( int i=0; i < alphabetBar.getChildCount(); i++ ) { View child = alphabetBar.getChildAt(i); if ( child.getTag().equals(keyChar) ) { child.setBackgroundColor(Color.BLUE); - } else { - child.setBackgroundColor(android.R.color.background_dark); + } else { + child.setBackgroundColor(getResources().getColor(android.R.color.background_dark)); } } } } List<CoverCallback> localList = new ArrayList<CoverCallback>( callbacks ); callbacks.clear(); int lastVisibleItem = firstVisibleItem + visibleItemCount - 1; LOG.debug( "Loading items " + firstVisibleItem + " to " + lastVisibleItem + " of " + totalItemCount ); for ( CoverCallback callback: localList ) { if ( callback.viewIndex >= firstVisibleItem && callback.viewIndex <= lastVisibleItem ) { callback.run(); } } } }; handler.postDelayed(lastRunnable, 550); } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } } private class CoverCallback { protected LibraryBook book; protected int viewIndex; protected ImageView view; public CoverCallback(LibraryBook book, int viewIndex, ImageView view) { this.book = book; this.view = view; this.viewIndex = viewIndex; } public void run() { try { FastBitmapDrawable drawable = new FastBitmapDrawable(getCover(book)); view.setImageDrawable(drawable); coverCache.put(book.getFileName(), drawable); } catch (OutOfMemoryError err) { coverCache.clear(); } } } private class BookCaseAdapter extends KeyedResultAdapter { private Context context; public BookCaseAdapter(Context context) { this.context = context; } @Override public View getView(final int index, final LibraryBook object, View convertView, ViewGroup parent) { View result; if ( convertView == null ) { LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); result = inflater.inflate(R.layout.bookcase_row, parent, false); } else { result = convertView; } result.setTag(index); result.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { onBookClicked(object); } }); final ImageView image = (ImageView) result.findViewById(R.id.bookCover); image.setImageDrawable(backupCover); TextView text = (TextView) result.findViewById(R.id.bookLabel); text.setText( object.getTitle() ); text.setBackgroundResource(R.drawable.alphabet_bar_bg_dark); loadCover(image, object, index); return result; } } private class QueryMenuAdapter extends ArrayAdapter<String> { String[] strings; public QueryMenuAdapter(Context context, String[] strings) { super(context, android.R.layout.simple_spinner_item, strings); this.strings = strings; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View rowView; if ( convertView == null ) { LayoutInflater inflater = (LayoutInflater) getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = inflater.inflate(R.layout.menu_row, parent, false); } else { rowView = convertView; } TextView textView = (TextView) rowView.findViewById(R.id.menuText); textView.setText(strings[position]); textView.setTextColor(Color.BLACK); ImageView img = (ImageView) rowView.findViewById(R.id.icon); img.setImageResource(ICONS[position]); return rowView; } } private void buildImportQuestionDialog() { if ( importQuestion != null ) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(LibraryActivity.this); builder.setTitle(R.string.no_books_found); builder.setMessage( getString(R.string.scan_bks_question) ); builder.setPositiveButton(android.R.string.yes, new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); //startImport(new File("/sdcard"), config.isCopyToLibrayEnabled()); showImportDialog(); } }); builder.setNegativeButton(android.R.string.no, new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); importQuestion = null; } }); this.importQuestion = builder.create(); } private void setAlphabetBarVisible( boolean visible ) { int vis = visible ? View.VISIBLE : View.GONE; alphabetBar.setVisibility(vis); alphabetDivider.setVisibility(vis); listView.setFastScrollEnabled(visible); } private class MenuSelectionListener implements OnItemSelectedListener { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long arg3) { LibrarySelection newSelections = LibrarySelection.values()[pos]; config.setLastLibraryQuery(newSelections); bookAdapter.clear(); new LoadBooksTask().execute(newSelections); } @Override public void onNothingSelected(AdapterView<?> arg0) { } } private class AlphabetAdapter extends ArrayAdapter<Character> { private List<Character> data; private Character highlightChar; public AlphabetAdapter(Context context, int layout, int view, List<Character> input ) { super(context, layout, view, input); this.data = input; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); Character tag = data.get(position); view.setTag( tag ); if ( tag.equals(highlightChar) ) { view.setBackgroundColor(Color.BLUE); } else { - view.setBackgroundColor(android.R.color.background_dark); + view.setBackgroundColor(getResources().getColor(android.R.color.background_dark)); } return view; } public void setHighlightChar(Character highlightChar) { this.highlightChar = highlightChar; } public Character getHighlightChar() { return highlightChar; } } private class LoadBooksTask extends AsyncTask<Configuration.LibrarySelection, Integer, QueryResult<LibraryBook>> { private Configuration.LibrarySelection sel; @Override protected void onPreExecute() { waitDialog.setTitle(R.string.loading_library); waitDialog.show(); coverCache.clear(); } @Override protected QueryResult<LibraryBook> doInBackground(Configuration.LibrarySelection... params) { Exception storedException = null; for ( int i=0; i < 3; i++ ) { try { this.sel = params[0]; switch ( sel ) { case LAST_ADDED: return libraryService.findAllByLastAdded(); case UNREAD: return libraryService.findUnread(); case BY_TITLE: return libraryService.findAllByTitle(); case BY_AUTHOR: return libraryService.findAllByAuthor(); default: return libraryService.findAllByLastRead(); } } catch (SQLiteException sql) { storedException = sql; try { //Sometimes the database is still locked. Thread.sleep(1000); } catch (InterruptedException in) {} } } throw new RuntimeException( "Failed after 3 attempts", storedException ); } @Override protected void onPostExecute(QueryResult<LibraryBook> result) { bookAdapter.setResult(result); if ( result instanceof KeyedQueryResult && result.getSize() >= ALPHABET_THRESHOLD ) { final KeyedQueryResult<LibraryBook> keyedResult = (KeyedQueryResult<LibraryBook>) result; alphabetAdapter = new AlphabetAdapter(LibraryActivity.this, R.layout.alphabet_line, R.id.alphabetLabel, keyedResult.getAlphabet() ); alphabetBar.setAdapter(alphabetAdapter); alphabetBar.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Character c = keyedResult.getAlphabet().get(arg2); onAlphabetBarClick(keyedResult, c); } }); setAlphabetBarVisible(true); } else { alphabetAdapter = null; setAlphabetBarVisible(false); } waitDialog.hide(); if ( sel == Configuration.LibrarySelection.LAST_ADDED && result.getSize() == 0 && ! askedUserToImport ) { askedUserToImport = true; buildImportQuestionDialog(); importQuestion.show(); } } } }
false
false
null
null
diff --git a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/QueryExecutor.java b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/QueryExecutor.java index 3cf352611..7d433e915 100644 --- a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/QueryExecutor.java +++ b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/QueryExecutor.java @@ -1,1139 +1,1141 @@ /******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * 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: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.data.engine.impl; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.birt.core.data.DataType; import org.eclipse.birt.core.data.ExpressionUtil; import org.eclipse.birt.data.engine.api.IBaseExpression; import org.eclipse.birt.data.engine.api.IBaseQueryDefinition; import org.eclipse.birt.data.engine.api.IBaseQueryResults; import org.eclipse.birt.data.engine.api.IBinding; import org.eclipse.birt.data.engine.api.IComputedColumn; import org.eclipse.birt.data.engine.api.IConditionalExpression; import org.eclipse.birt.data.engine.api.IFilterDefinition; import org.eclipse.birt.data.engine.api.IGroupDefinition; import org.eclipse.birt.data.engine.api.IQueryDefinition; import org.eclipse.birt.data.engine.api.IResultMetaData; import org.eclipse.birt.data.engine.api.ISortDefinition; import org.eclipse.birt.data.engine.api.querydefn.ComputedColumn; import org.eclipse.birt.data.engine.api.querydefn.ConditionalExpression; import org.eclipse.birt.data.engine.api.querydefn.FilterDefinition; import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression; import org.eclipse.birt.data.engine.api.script.IDataSourceInstanceHandle; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.data.engine.executor.BaseQuery; import org.eclipse.birt.data.engine.executor.JointDataSetQuery; import org.eclipse.birt.data.engine.expression.ExpressionCompilerUtil; import org.eclipse.birt.data.engine.expression.ExpressionProcessor; import org.eclipse.birt.data.engine.i18n.ResourceConstants; import org.eclipse.birt.data.engine.impl.aggregation.AggregateTable; import org.eclipse.birt.data.engine.impl.group.GroupCalculatorFactory; import org.eclipse.birt.data.engine.odi.ICandidateQuery; import org.eclipse.birt.data.engine.odi.IDataSource; import org.eclipse.birt.data.engine.odi.IEventHandler; import org.eclipse.birt.data.engine.odi.IPreparedDSQuery; import org.eclipse.birt.data.engine.odi.IQuery; import org.eclipse.birt.data.engine.odi.IResultIterator; import org.eclipse.birt.data.engine.odi.IResultObjectEvent; import org.eclipse.birt.data.engine.olap.api.ICubeQueryResults; import org.eclipse.birt.data.engine.olap.script.JSCubeBindingObject; import org.eclipse.birt.data.engine.script.OnFetchScriptHelper; import org.eclipse.birt.data.engine.script.ScriptConstants; import org.mozilla.javascript.Context; import org.mozilla.javascript.Scriptable; import com.ibm.icu.text.Collator; /** * */ public abstract class QueryExecutor implements IQueryExecutor { private IBaseQueryDefinition baseQueryDefn; private AggregateTable aggrTable; // from PreparedQuery->PreparedDataSourceQuery->DataEngineImpl private Scriptable sharedScope; /** Externally provided query scope; can be null */ // from PreparedQuery->PreparedDataSourceQuery private Scriptable parentScope; // for query execution private Scriptable queryScope; private boolean isPrepared = false; private boolean isExecuted = false; private boolean loadFromCache; private Map queryAppContext; /** Query nesting level, 1 - outermost query */ private int nestedLevel = 1; /** Runtime data source and data set used by this instance of executor */ protected DataSourceRuntime dataSource; protected DataSetRuntime dataSet; protected IDataSource odiDataSource; protected IQuery odiQuery; /** Outer query's results; null if this query is not nested */ protected IQueryService tabularOuterResults; private IResultIterator odiResult; private IExecutorHelper parentHelper; private DataEngineSession session; protected List temporaryComputedColumns = new ArrayList( ); private static Logger logger = Logger.getLogger( QueryExecutor.class.getName( ) ); /** * @param sharedScope * @param baseQueryDefn * @param aggrTable */ QueryExecutor( Scriptable sharedScope, IBaseQueryDefinition baseQueryDefn, AggregateTable aggrTable, DataEngineSession session ) { Object[] params = { sharedScope, baseQueryDefn, aggrTable, session }; logger.entering( QueryExecutor.class.getName( ), "QueryExecutor", params ); this.sharedScope = sharedScope; this.baseQueryDefn = baseQueryDefn; this.aggrTable = aggrTable; this.session = session; logger.exiting( QueryExecutor.class.getName( ), "QueryExecutor" ); } /** * Provide the actual DataSourceRuntime used for the query. * * @return */ abstract protected DataSourceRuntime findDataSource( ) throws DataException; /** * Create a new instance of data set runtime * * @return */ abstract protected DataSetRuntime newDataSetRuntime( ) throws DataException; /** * Create a new unopened odiDataSource given the data source runtime * definition * * @return */ abstract protected IDataSource createOdiDataSource( ) throws DataException; /** * Create an empty instance of odi query * * @return */ abstract protected IQuery createOdiQuery( ) throws DataException; /** * Prepares the ODI query */ protected void prepareOdiQuery( ) throws DataException { } /** * * @throws DataException */ protected void dataSourceBeforeOpen( ) throws DataException { if ( !this.loadFromCache ) { this.dataSource.beforeOpen( ); } } /** * * @throws DataException */ protected void dataSourceAfterOpen( ) throws DataException { if ( !this.loadFromCache ) { this.dataSource.afterOpen( ); } } /** * * @throws DataException */ protected void dataSetBeforeOpen( ) throws DataException { if ( !this.loadFromCache ) { this.dataSet.beforeOpen( ); } } /** * * @throws DataException */ protected void dataSetAfterOpen( ) throws DataException { if ( !this.loadFromCache ) { this.dataSet.afterOpen( ); } } /** * * @throws DataException */ protected void dataSetBeforeClose( ) throws DataException { if ( !this.loadFromCache ) { dataSet.beforeClose( ); } } /** * * @throws DataException */ protected void dataSetAfterClose( ) throws DataException { if ( !this.loadFromCache ) { this.dataSet.afterClose( ); } } /** * Executes the ODI query to reproduce a ODI result set * @param eventHandler * @param stopSign * @return */ abstract protected IResultIterator executeOdiQuery( IEventHandler eventHandler, StopSign stopSign ) throws DataException; /** * @param context */ void setAppContext( Map context ) { queryAppContext = context; } /** * Prepare Executor so that it is ready to execute the query * * @param outerRts * @param targetScope * @throws DataException */ void prepareExecution( IBaseQueryResults outerRts, Scriptable targetScope ) throws DataException { if ( isPrepared ) return; this.parentScope = targetScope; dataSource = findDataSource( ); if ( outerRts != null && ( outerRts instanceof IQueryService || outerRts instanceof ICubeQueryResults )) { if ( outerRts instanceof IQueryService ) { tabularOuterResults = ( (IQueryService) outerRts ); if ( tabularOuterResults.isClosed( ) ) { // Outer result is closed; invalid throw new DataException( ResourceConstants.RESULT_CLOSED ); } this.nestedLevel = tabularOuterResults.getNestedLevel( ); // TODO: check helper is null IExecutorHelper helper = tabularOuterResults.getExecutorHelper( ); this.setParentExecutorHelper( helper ); } else if( outerRts instanceof ICubeQueryResults ) { ExecutorHelper helper = new ExecutorHelper( null ); helper.setScriptable( new JSCubeBindingObject( ( (ICubeQueryResults) outerRts ).getCubeCursor( ) ) ); this.setParentExecutorHelper( helper ); } } // Create the data set runtime // Since data set runtime contains the execution result, a new data set // runtime is needed for each execute dataSet = newDataSetRuntime( ); assert dataSet != null; //For cached data set, we need not execute any scripts. loadFromCache = loadFromCache( ); openDataSource( ); // Run beforeOpen script now so the script can modify the // DataSetRuntime properties dataSetBeforeOpen( ); // Let subclass create a new and empty intance of the appropriate // odi IQuery odiQuery = createOdiQuery( ); odiQuery.setDistinctValueFlag( dataSet.needDistinctValue( ) ); odiQuery.setQueryDefinition( this.baseQueryDefn ); odiQuery.setExprProcessor( new ExpressionProcessor( dataSet ) ); //Set the row fetch limit for the IQuery instance.The row fetch limit //is the number of rows that a data set can fetch from data source. if( dataSet.getDesign( ) != null ) { //When it is not a subquery, the property "row fetch limit" should be applied //to the query. odiQuery.setRowFetchLimit( dataSet.getDesign( ).getRowFetchLimit( ) ); } populateOdiQuery( ); prepareOdiQuery( ); isPrepared = true; } /** * * @return * @throws DataException */ private boolean loadFromCache( ) throws DataException { + if( this.dataSource == null ) + return false; if ( !( this.baseQueryDefn instanceof IQueryDefinition ) ) return false; return this.session.getDataSetCacheManager( ) .doesLoadFromCache( this.dataSource.getDesign( ), this.dataSet.getDesign( ), new ParameterUtil( this.tabularOuterResults == null ? null : this.tabularOuterResults.getQueryScope( ), this.dataSet, ( IQueryDefinition )this.baseQueryDefn, this.getQueryScope( ) ).resolveDataSetParameters( true ), this.queryAppContext ); } /** * Open the required DataSource. This method should be called after * "dataSource" is initialized by findDataSource() method. * * @throws DataException */ protected void openDataSource( ) throws DataException { assert odiDataSource == null; // Open the underlying data source // dataSource = findDataSource( ); if ( dataSource != null ) { // TODO: potential bug if ( !dataSource.isOpen( ) || session.getDataSetCacheManager( ).needsToCache( )) { // Data source is not open; create an Odi Data Source and open it // We should run the beforeOpen script now to give it a chance to modify // runtime data source properties dataSourceBeforeOpen( ); // Let subclass create a new unopened odi data source odiDataSource = createOdiDataSource( ); // Passes thru the prepared query executor's // context to the new odi data source odiDataSource.setAppContext( queryAppContext ); // Open the odi data source dataSource.openOdiDataSource( odiDataSource ); dataSourceAfterOpen( ); } else { // Use existing odiDataSource created for the data source runtime odiDataSource = dataSource.getOdiDataSource( ); // Passes thru the prepared query executor's // current context to existing data source odiDataSource.setAppContext( queryAppContext ); } } } /** * Populates odiQuery with this query's definitions * * @throws DataException */ protected void populateOdiQuery( ) throws DataException { assert odiQuery != null; assert this.baseQueryDefn != null; Context cx = Context.enter( ); try { // Set grouping populateGrouping( cx ); // Set sorting populateSorting( ); // set fetch event populateFetchEvent( cx ); // specify max rows the query should fetch odiQuery.setMaxRows( this.baseQueryDefn.getMaxRows( ) ); prepareCacheQuery( this.odiQuery ); } finally { Context.exit( ); } } /** * TODO: enhance me, this is only a temp logic * Set temporary computed columns to DataSourceQuery where cache is used */ protected void prepareCacheQuery( IQuery odiQuery ) { if ( temporaryComputedColumns != null && temporaryComputedColumns.size( ) > 0 ) { if ( odiQuery instanceof org.eclipse.birt.data.engine.executor.dscache.DataSourceQuery ) { ( (org.eclipse.birt.data.engine.executor.dscache.DataSourceQuery) odiQuery ).setTempComputedColumn( this.temporaryComputedColumns ); } else if ( odiQuery instanceof org.eclipse.birt.data.engine.executor.dscache.CandidateQuery ) { ( (org.eclipse.birt.data.engine.executor.dscache.CandidateQuery) odiQuery ).setTempComputedColumn( this.temporaryComputedColumns ); } } } /** * Populate grouping to the query. * * @param cx * @throws DataException */ private void populateGrouping( Context cx ) throws DataException { List groups = this.baseQueryDefn.getGroups( ); if ( groups != null && !groups.isEmpty( ) ) { IQuery.GroupSpec[] groupSpecs = new IQuery.GroupSpec[groups.size( )]; Iterator it = groups.iterator( ); for ( int i = 0; it.hasNext( ); i++ ) { IGroupDefinition src = (IGroupDefinition) it.next( ); validateGroupExpression( src ); String expr = getGroupKeyExpression( src ); String groupName = populateGroupName( i, expr ); IQuery.GroupSpec dest = QueryExecutorUtil.groupDefnToSpec( cx, src, expr, groupName, -1, this.baseQueryDefn.getQueryExecutionHints( ) == null ? true : this.baseQueryDefn.getQueryExecutionHints( ) .doSortBeforeGrouping( ) ); int dataType = getColumnDataType( cx, expr ); groupSpecs[i] = dest; this.temporaryComputedColumns.add( getComputedColumnInstance( cx, groupSpecs[i].getInterval( ), src, expr, groupName, dest, dataType) ); } odiQuery.setGrouping( Arrays.asList( groupSpecs ) ); } } /** * Validating the group expression. * * @param src * @throws DataException */ private void validateGroupExpression( IGroupDefinition src ) throws DataException { if ( ( src.getKeyColumn( ) == null || src.getKeyColumn( ) .trim( ) .length( ) == 0 ) && ( src.getKeyExpression( ) == null || src.getKeyExpression( ) .trim( ) .length( ) == 0 ) ) throw new DataException( ResourceConstants.BAD_GROUP_EXPRESSION ); } /** * Populate the group name according to the given expression. * * @param i * @param expr * @return */ private String populateGroupName( int i, String expr ) { String groupName; if ( expr.trim( ).equalsIgnoreCase( "row[0]" ) || expr.trim( ).equalsIgnoreCase( "row._rowPosition" ) || expr.trim( ).equalsIgnoreCase( "dataSetRow[0]" ) || expr.trim( ) .equalsIgnoreCase( "dataSetRow._rowPosition" ) ) { groupName = "_{$TEMP_GROUP_" + i + "ROWID$}_"; } else { groupName = "_{$TEMP_GROUP_" + i + "$}_"; } return groupName; } /** * Get the computed column instance according to the group type.If group has * interval, return GroupComputedColumn, otherwise return normal computed * column. * * @param cx * @param groupSpecs * @param i * @param src * @param expr * @param groupName * @param dest * @return * @throws DataException */ private IComputedColumn getComputedColumnInstance( Context cx, int interval, IGroupDefinition src, String expr, String groupName, IQuery.GroupSpec dest, int dataType) throws DataException { if ( dest.getInterval( ) != IGroupDefinition.NO_INTERVAL ) { return new GroupComputedColumn( groupName, expr, QueryExecutorUtil.getTempComputedColumnType( interval ), GroupCalculatorFactory.getGroupCalculator( src.getInterval( ), src.getIntervalStart( ), src.getIntervalRange( ), dataType) ); } else { return new ComputedColumn( groupName, expr, QueryExecutorUtil.getTempComputedColumnType( interval ) ); } } /** * Populate the sortings in a query. * * @throws DataException */ private void populateSorting( ) throws DataException { List sorts = this.baseQueryDefn.getSorts( ); if ( sorts != null && !sorts.isEmpty( ) ) { IQuery.SortSpec[] sortSpecs = new IQuery.SortSpec[sorts.size( )]; Iterator it = sorts.iterator( ); for ( int i = 0; it.hasNext( ); i++ ) { ISortDefinition src = (ISortDefinition) it.next( ); int sortIndex = -1; String sortKey = src.getColumn( ); if ( sortKey == null ) sortKey = src.getExpression( ).getText( ); else { sortKey = getColumnRefExpression( sortKey ); } temporaryComputedColumns.add( new ComputedColumn( "_{$TEMP_SORT_" + i + "$}_", sortKey, DataType.ANY_TYPE ) ); sortIndex = -1; sortKey = String.valueOf( "_{$TEMP_SORT_" + i + "$}_"); IQuery.SortSpec dest = new IQuery.SortSpec( sortIndex, sortKey, src.getSortDirection( ) == ISortDefinition.SORT_ASC, src.getSortStrength( ) == -1? null:Collator.getInstance( )); sortSpecs[i] = dest; } odiQuery.setOrdering( Arrays.asList( sortSpecs ) ); } } /** * * @param cx * @throws DataException */ private void populateFetchEvent( Context cx ) throws DataException { List dataSetFilters = new ArrayList( ); List queryFilters = new ArrayList( ); List aggrFilters = new ArrayList( ); if ( dataSet.getFilters( ) != null ) { dataSetFilters = dataSet.getFilters( ); } if ( this.baseQueryDefn.getFilters( ) != null ) { for ( int i = 0; i < this.baseQueryDefn.getFilters( ).size( ); i++ ) { if ( QueryExecutorUtil.isAggrFilter( (IFilterDefinition) this.baseQueryDefn.getFilters( ) .get( i ), this.baseQueryDefn.getBindings( ) ) ) { aggrFilters.add( this.baseQueryDefn.getFilters( ).get( i ) ); } else { queryFilters.add( this.baseQueryDefn.getFilters( ).get( i ) ); } } } //When prepare filters, the temporaryComputedColumns would also be effect. List multipassFilters = prepareFilters( cx, dataSetFilters, queryFilters, temporaryComputedColumns ); //******************populate the onFetchEvent below**********************/ List computedColumns = null; // set computed column event computedColumns = this.dataSet.getComputedColumns( ); if ( computedColumns == null ) computedColumns = new ArrayList( ); if ( computedColumns.size( ) > 0 || temporaryComputedColumns.size( ) > 0 ) { IResultObjectEvent objectEvent = new ComputedColumnHelper( this.dataSet, computedColumns, temporaryComputedColumns ); odiQuery.addOnFetchEvent( objectEvent ); this.dataSet.getComputedColumns( ) .addAll( temporaryComputedColumns ); } if ( dataSet.getEventHandler( ) != null ) { OnFetchScriptHelper event = new OnFetchScriptHelper( dataSet ); odiQuery.addOnFetchEvent( event ); } if ( dataSetFilters.size( ) + queryFilters.size( ) + multipassFilters.size( ) + aggrFilters.size( ) > 0 ) { IResultObjectEvent objectEvent = new FilterByRow( dataSetFilters, queryFilters, multipassFilters, aggrFilters, dataSet ); odiQuery.addOnFetchEvent( objectEvent ); } } /** * get the data type of a expression * @param cx * @param expr * @return * @throws DataException */ private int getColumnDataType( Context cx, String expr ) throws DataException { String columnName = QueryExecutorUtil.getColInfoFromJSExpr( cx, expr ) .getColumnName( ); if ( columnName == null ) { return DataType.UNKNOWN_TYPE; } if ( columnName.equals( ScriptConstants.ROW_NUM_KEYWORD ) ) { return DataType.INTEGER_TYPE; } Object baseExpr = ( this.baseQueryDefn.getBindings( ).get( columnName ) ); if ( baseExpr == null ) { return DataType.UNKNOWN_TYPE; } return ( (IBinding) baseExpr ).getExpression( ).getDataType( ); } /** * @param src * @return */ private String getGroupKeyExpression( IGroupDefinition src ) { String expr = src.getKeyColumn( ); if ( expr == null ) { expr = src.getKeyExpression( ); } else { expr = getColumnRefExpression( expr ); } return expr; } /** * * @param expr * @return */ private String getColumnRefExpression( String expr ) { return ExpressionUtil.createJSRowExpression( expr ); } void setParentExecutorHelper( IExecutorHelper helper ) { this.parentHelper = helper; } /** * * @param cx * @param dataSetFilters * @param queryFilters * @param temporaryComputedColumns * @return * @throws DataException */ private List prepareFilters( Context cx, List dataSetFilters, List queryFilters, List temporaryComputedColumns ) throws DataException { List result = new ArrayList( ); prepareFilter( cx, dataSetFilters, temporaryComputedColumns, result ); prepareFilter( cx, queryFilters, temporaryComputedColumns, result ); return result; } /** * * @param cx * @param dataSetFilters * @param temporaryComputedColumns * @param result * @throws DataException */ private void prepareFilter( Context cx, List dataSetFilters, List temporaryComputedColumns, List result ) throws DataException { if ( dataSetFilters != null && !dataSetFilters.isEmpty( ) ) { Iterator it = dataSetFilters.iterator( ); for ( int i = 0; it.hasNext( ); i++ ) { IFilterDefinition src = (IFilterDefinition) it.next( ); IBaseExpression expr = src.getExpression( ); if ( isGroupFilter( src ) ) { ConditionalExpression ce = ( (ConditionalExpression) expr ); String exprText = ce.getExpression( ).getText( ); ColumnInfo columnInfo = QueryExecutorUtil.getColInfoFromJSExpr( cx, exprText ); int index = columnInfo.getColumnIndex( ); String name = columnInfo.getColumnName( ); if ( name == null && index < 0 ) { // If failed to treate filter key as a column reference // expression // then treat it as a computed column expression temporaryComputedColumns.add( new ComputedColumn( "_{$TEMP_FILTER_" + i + "$}_", exprText, DataType.ANY_TYPE ) ); it.remove( ); result.add( new FilterDefinition( new ConditionalExpression( new ScriptExpression( String.valueOf( "dataSetRow[\"_{$TEMP_FILTER_" + i + "$}_\"]" ) ), ce.getOperator( ), ce.getOperand1( ), ce.getOperand2( ) ) ) ); } } } } } /** * * @param filter * @return * @throws DataException */ private boolean isGroupFilter( IFilterDefinition filter ) throws DataException { IBaseExpression expr = filter.getExpression( ); if ( expr instanceof IConditionalExpression ) { if ( !ExpressionCompilerUtil.isValidExpressionInQueryFilter( expr ) ) throw new DataException( ResourceConstants.INVALID_DEFINITION_IN_FILTER, new Object[]{ ( (IConditionalExpression) expr ).getExpression( ).getText( ) } ); try { if ( odiQuery instanceof BaseQuery ) { return ( (BaseQuery) odiQuery ).getExprProcessor( ) .hasAggregation( expr ); } } catch ( DataException e ) { return true; } } return false; } /* * @see org.eclipse.birt.data.engine.impl.IQueryExecutor#getResultMetaData() */ public IResultMetaData getResultMetaData( ) throws DataException { assert odiQuery instanceof IPreparedDSQuery || odiQuery instanceof ICandidateQuery || odiQuery instanceof JointDataSetQuery; if ( odiQuery instanceof IPreparedDSQuery ) { if ( ( (IPreparedDSQuery) odiQuery ).getResultClass( ) != null ) return new ResultMetaData( ( (IPreparedDSQuery) odiQuery ).getResultClass( ) ); else return null; } else if ( odiQuery instanceof JointDataSetQuery ) { return new ResultMetaData( ( (JointDataSetQuery) odiQuery ).getResultClass( ) ); } else { return new ResultMetaData( ( (ICandidateQuery) odiQuery ).getResultClass( ) ); } } /* * @see org.eclipse.birt.data.engine.impl.IQueryExecutor#execute() */ public void execute( IEventHandler eventHandler, StopSign stopSign ) throws DataException { logger.logp( Level.FINER, QueryExecutor.class.getName( ), "execute", "Start to execute" ); if ( this.isExecuted ) return; ExecutorHelper helper = new ExecutorHelper( this.parentHelper ); eventHandler.setExecutorHelper( helper ); // Execute the query odiResult = executeOdiQuery( eventHandler, stopSign ); helper.setScriptable( this.dataSet.getJSResultRowObject( ) ); resetComputedColumns( ); // Bind the row object to the odi result set this.dataSet.setResultSet( odiResult, false ); // Calculate aggregate values //this.aggrTable.calculate( odiResult, getQueryScope( ) ); this.isExecuted = true; logger.logp( Level.FINER, QueryExecutor.class.getName( ), "execute", "Finish executing" ); } /** * reset computed columns */ private void resetComputedColumns( ) { List l = this.getDataSet( ).getComputedColumns( ); if ( l != null ) l.removeAll( this.temporaryComputedColumns ); } /* * Closes the executor; release all odi resources * * @see org.eclipse.birt.data.engine.impl.IQueryExecutor#close() */ public void close( ) { if ( odiQuery == null ) { // already closed logger.logp( Level.FINER, QueryExecutor.class.getName( ), "close", "executor closed " ); return; } // Close the data set and associated odi query try { dataSetBeforeClose( ); } catch ( DataException e ) { logger.logp( Level.FINE, QueryExecutor.class.getName( ), "close", e.getMessage( ), e ); } if ( odiResult != null ) { try { odiResult.close( ); } catch ( DataException e1 ) { // TODO Auto-generated catch block e1.printStackTrace( ); } } odiQuery.close( ); try { dataSet.close( ); } catch ( DataException e ) { logger.logp( Level.FINE, QueryExecutor.class.getName( ), "close", e.getMessage( ), e ); } odiQuery = null; odiDataSource = null; odiResult = null; queryScope = null; isPrepared = false; isExecuted = false; // Note: reset dataSet and dataSource only after afterClose() is executed, since // the script may access these two objects try { dataSetAfterClose( ); } catch ( DataException e ) { logger.logp( Level.FINE, QueryExecutor.class.getName( ), "close", e.getMessage( ), e ); } dataSet = null; dataSource = null; logger.logp( Level.FINER, QueryExecutor.class.getName( ), "close", "executor closed " ); } /* * @see org.eclipse.birt.data.engine.impl.IQueryExecutor#getDataSet() */ public DataSetRuntime getDataSet( ) { return dataSet; } /* * @see org.eclipse.birt.data.engine.impl.IQueryExecutor#getSharedScope() */ public Scriptable getSharedScope( ) { return this.sharedScope; } /** * Gets the Javascript scope for evaluating expressions for this query * * @return */ public Scriptable getQueryScope( ) { if ( queryScope == null ) { // Set up a query scope. All expressions are evaluated against the // Data set JS object as the prototype (so that it has access to all // data set properties). It uses a subscope of the externally provided // parent scope, or the global shared scope queryScope = newSubScope( parentScope ); queryScope.setPrototype( dataSet.getJSDataSetObject( ) ); } return queryScope; } /** * Creates a subscope within parent scope * @param parentAndProtoScope parent scope. If null, the shared top-level scope is used as parent */ private Scriptable newSubScope( Scriptable parentAndProtoScope ) { if ( parentAndProtoScope == null ) parentAndProtoScope = sharedScope; Context cx = Context.enter( ); try { Scriptable scope = cx.newObject( parentAndProtoScope ); scope.setParentScope( parentAndProtoScope ); scope.setPrototype( parentAndProtoScope ); return scope; } finally { Context.exit( ); } } /* * @see org.eclipse.birt.data.engine.impl.IQueryExecutor#getNestedLevel() */ public int getNestedLevel( ) { return this.nestedLevel; } /* * @see org.eclipse.birt.data.engine.impl.IQueryExecutor#getDataSourceInstanceHandle() */ public IDataSourceInstanceHandle getDataSourceInstanceHandle( ) { return this.dataSource; } /* * @see org.eclipse.birt.data.engine.impl.IQueryExecutor#getJSAggrValueObject() */ public Scriptable getJSAggrValueObject( ) { return this.aggrTable.getJSAggrValueObject( ); } /* * @see org.eclipse.birt.data.engine.impl.IQueryExecutor#getNestedDataSets(int) */ public DataSetRuntime[] getNestedDataSets( int nestedCount ) { return tabularOuterResults == null ? null : tabularOuterResults.getDataSetRuntime( nestedCount ); } /* * @see org.eclipse.birt.data.engine.impl.IQueryExecutor#getOdiResultSet() */ public IResultIterator getOdiResultSet( ) { return this.odiResult; } /** * @param evaluateValue * @return * @throws DataException */ protected Collection resolveDataSetParameters( boolean evaluateValue ) throws DataException { return new ParameterUtil( this.tabularOuterResults == null ? null:this.tabularOuterResults.getQueryScope( ), this.getDataSet( ), (IQueryDefinition) this.baseQueryDefn, this.getQueryScope( ) ).resolveDataSetParameters( evaluateValue ); } /* * (non-Javadoc) * @see org.eclipse.birt.data.engine.impl.IQueryExecutor#getAppContext() */ public Map getAppContext() { return this.queryAppContext; } } \ No newline at end of file
true
false
null
null
diff --git a/integrationtest/src/test/java/org/openengsb/integrationtest/util/OpenEngSBBundles.java b/integrationtest/src/test/java/org/openengsb/integrationtest/util/OpenEngSBBundles.java index 9cdd4a44a..1a52b79a9 100644 --- a/integrationtest/src/test/java/org/openengsb/integrationtest/util/OpenEngSBBundles.java +++ b/integrationtest/src/test/java/org/openengsb/integrationtest/util/OpenEngSBBundles.java @@ -1,114 +1,114 @@ /** * Copyright 2010 OpenEngSB Division, Vienna University of Technology * * 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.openengsb.integrationtest.util; import org.ops4j.pax.exam.CoreOptions; import org.ops4j.pax.exam.options.MavenArtifactProvisionOption; import org.ops4j.pax.exam.options.MavenArtifactUrlReference; public final class OpenEngSBBundles { public static final MavenArtifactProvisionOption OPENENGSB_WRAPPED_WICKET = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.wrapped").artifactId( "org.apache.wicket-all")); public static final MavenArtifactProvisionOption OPENENGSB_WRAPPED_JAXB = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.wrapped").artifactId("javax.xml.jaxb-all")); public static final MavenArtifactProvisionOption OPENENGSB_WRAPPED_GUAVA = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.wrapped") .artifactId("com.google.guava-all")); public static final MavenArtifactProvisionOption OPENENGSB_WRAPPED_XMLRPC = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.wrapped") .artifactId("org.apache.xmlrpc-all")); public static final MavenArtifactProvisionOption OPENENGSB_WRAPPED_JSCH = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.wrapped") .artifactId("com.jcraft.jsch-all")); public static final MavenArtifactProvisionOption OPENENGSB_CONFIG_JETTY = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.config").artifactId( "openengsb-config-jetty")); public static final MavenArtifactProvisionOption OPENENGSB_CONFIG_WEBEXTENDER = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.config").artifactId( "openengsb-config-webextender")); public static final MavenArtifactProvisionOption OPENENGSB_CORE_COMMON = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.core").artifactId("openengsb-core-common")); public static final MavenArtifactProvisionOption OPENENGSB_CORE_EVENTS = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.core").artifactId("openengsb-core-events")); public static final MavenArtifactProvisionOption OPENENGSB_CORE_PERSISTENCE = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.core").artifactId( "openengsb-core-persistence")); public static final MavenArtifactProvisionOption OPENENGSB_CORE_WORKFLOW = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.core") .artifactId("openengsb-core-workflow")); public static final MavenArtifactProvisionOption OPENENGSB_DOMAINS_EXAMPLE_IMPLEMENTATION = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.domains.example").artifactId( "openengsb-domains-example-implementation")); public static final MavenArtifactProvisionOption OPENENGSB_DOMAINS_EXAMPLE_CONNECTOR = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.domains.example").artifactId( "openengsb-domains-example-connector")); public static final MavenArtifactProvisionOption OPENENGSB_DOMAINS_NOTIFICATION_IMPLEMENTATION = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.domains.notification").artifactId( "openengsb-domains-notification-implementation")); public static final MavenArtifactProvisionOption OPENENGSB_DOMAINS_NOTIFICATION_EMAIL = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.domains.notification").artifactId( "openengsb-domains-notification-email")); public static final MavenArtifactProvisionOption OPENENGSB_DOMAINS_REPORT_IMPLEMENTATION = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.domains.report").artifactId( "openengsb-domains-report-implementation")); public static final MavenArtifactProvisionOption OPENENGSB_DOMAINS_REPORT_PLAINTEXT = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.domains.report").artifactId( "openengsb-domains-report-plaintext")); public static final MavenArtifactProvisionOption OPENENGSB_DOMAINS_ISSUE_IMPLEMENTATION = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.domains.issue").artifactId( "openengsb-domains-issue-implementation")); public static final MavenArtifactProvisionOption OPENENGSB_DOMAINS_ISSUE_TRAC = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.domains.issue").artifactId( "openengsb-domains-issue-trac")); - public static final MavenArtifactProvisionOption OPENENGSB_DOMAINS_SCM_IMPLEMENTATION = CoreOptions + public static final MavenArtifactProvisionOption OPENENGSB_DOMAINS_SCM_IMPLEMENTATION = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.domains.scm").artifactId( "openengsb-domains-scm-implementation")); public static final MavenArtifactProvisionOption OPENENGSB_DOMAINS_SCM_GIT = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.domains.scm").artifactId( "openengsb-domains-scm-git")); public static final MavenArtifactProvisionOption OPENENGSB_UI_WEB = CoreOptions .mavenBundle(new MavenArtifactUrlReference().groupId("org.openengsb.ui").artifactId("openengsb-ui-web") .type("war")); private OpenEngSBBundles() { // should not be instanciable, but should be allowed to contain private // methods } }
true
false
null
null
diff --git a/src/com/android/quicksearchbox/QueryTask.java b/src/com/android/quicksearchbox/QueryTask.java index 904cc71..2b8c8f4 100644 --- a/src/com/android/quicksearchbox/QueryTask.java +++ b/src/com/android/quicksearchbox/QueryTask.java @@ -1,102 +1,97 @@ /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.quicksearchbox; import com.android.quicksearchbox.util.Consumer; import com.android.quicksearchbox.util.NamedTask; import com.android.quicksearchbox.util.NamedTaskExecutor; import android.os.Handler; import java.util.Iterator; /** * A task that gets suggestions from a corpus. */ public class QueryTask<C extends SuggestionCursor> implements NamedTask { private final String mQuery; private final int mQueryLimit; private final SuggestionCursorProvider<C> mProvider; private final Handler mHandler; private final Consumer<C> mConsumer; private final boolean mTheOnlyOne; /** * Creates a new query task. * * @param query Query to run. * @param queryLimit The number of suggestions to ask each provider for. * @param provider The provider to ask for suggestions. * @param handler Handler that {@link Consumer#consume} will * get called on. If null, the method is called on the query thread. * @param consumer Consumer to notify when the suggestions have been returned. * @param onlyTask Indicates if this is the only task within a batch. */ public QueryTask(String query, int queryLimit, SuggestionCursorProvider<C> provider, Handler handler, Consumer<C> consumer, boolean onlyTask) { mQuery = query; mQueryLimit = queryLimit; mProvider = provider; mHandler = handler; mConsumer = consumer; mTheOnlyOne = onlyTask; } public String getName() { return mProvider.getName(); } public void run() { final C cursor = mProvider.getSuggestions(mQuery, mQueryLimit, mTheOnlyOne); if (mHandler == null) { mConsumer.consume(cursor); } else { mHandler.post(new Runnable() { public void run() { boolean accepted = mConsumer.consume(cursor); if (!accepted) { cursor.close(); } } }); } } @Override public String toString() { return mProvider + "[" + mQuery + "]"; } public static <C extends SuggestionCursor> void startQueries(String query, int maxResultsPerProvider, Iterable<? extends SuggestionCursorProvider<C>> providers, NamedTaskExecutor executor, Handler handler, Consumer<C> consumer, boolean onlyOneProvider) { - boolean onlyOneProvider = true; - Iterator<?> it = providers.iterator(); - if (it.hasNext()) it.next(); - if (it.hasNext()) onlyOneProvider = false; - for (SuggestionCursorProvider<C> provider : providers) { QueryTask<C> task = new QueryTask<C>(query, maxResultsPerProvider, provider, handler, consumer, onlyOneProvider); executor.execute(task); } } }
true
false
null
null
diff --git a/app/controllers/DataHub.java b/app/controllers/DataHub.java index 61f165b..0db5023 100644 --- a/app/controllers/DataHub.java +++ b/app/controllers/DataHub.java @@ -1,315 +1,315 @@ package controllers; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import nl.bitwalker.useragentutils.UserAgent; import com.mongodb.MongoException; import models.RecordedLocation; import models.TrackSession; import models.TrackedAction; import models.User; import play.Play; import play.data.Form; import play.data.validation.Constraints.Required; import play.mvc.Controller; import play.mvc.Http; import play.mvc.Http.Context; import play.mvc.Http.Cookie; import play.mvc.Result; import utils.Base64; import utils.Tools; public class DataHub extends Controller { public static class TrackRequest { @Required public String d; @Required public String host; @Required public String key; } public static Result track() { response().setContentType( "image/png" ); InputStream outGifStream = Play.application().resourceAsStream("/public/images/site/blank.png"); Form<TrackRequest> req = form( TrackRequest.class ).bindFromRequest(); if( req.hasErrors() ) return badRequest( outGifStream ); TrackSession.Model trackSess = null; User.Model user = null; try { user = User.coll.findOneById( req.get().key ); } catch( MongoException e ) { e.printStackTrace(); return internalServerError("No User"); } if( user == null || user._id == null || user._id.isEmpty() ) return badRequest( outGifStream ); if( !User.isDomainTrackable( req.get().host, user ) ) { return forbidden( outGifStream ); } Long systemTs = new Date().getTime(); - if( session().containsKey(Tools.md5Encode( req.get().host )+"_tracked_session_ts") ) +// if( session().containsKey(Tools.md5Encode( req.get().host )+"_tracked_session_ts") ) if( session().containsKey(Tools.md5Encode( req.get().host )+"_tracked_session_ts") && ( systemTs < Integer.parseInt( session().get(Tools.md5Encode( req.get().host )+"_tracked_session_ts") ) ) && session().containsKey(Tools.md5Encode( req.get().host )+"_tracked_session") ) { trackSess = TrackSession.coll.findOneById( session().get( Tools.md5Encode( req.get().host )+"_tracked_session") ); } else { trackSess = new TrackSession.Model(); trackSess.startedAt = new Date(); if( Context.current().request().headers().containsKey("USER-AGENT") && Context.current().request().headers().get("USER-AGENT").length > 0 ) { trackSess.userAgent = Context.current().request().headers().get("USER-AGENT")[0]; UserAgent userAgent = UserAgent.parseUserAgentString( trackSess.userAgent ); trackSess.os = userAgent.getOperatingSystem().name(); trackSess.browser = userAgent.getBrowser().name(); } if( Context.current().request().headers().containsKey("ACCEPT-LANGUAGE") && Context.current().request().headers().get("ACCEPT-LANGUAGE").length > 0 ) { trackSess.language = Context.current().request().headers().get("ACCEPT-LANGUAGE")[0]; String[] languages = trackSess.language.split(","); if( languages.length > 1 ) trackSess.mainLanguage = languages[0]; else trackSess.mainLanguage = trackSess.language; } trackSess.host = req.get().host; trackSess.userId = user._id; trackSess._id = TrackSession.save(trackSess).getSavedId(); session().put( Tools.md5Encode( req.get().host )+"_tracked_session", trackSess._id); //TODO: get client IP using http proxy } RecordedLocation.Model loc = null; if( session().containsKey(Tools.md5Encode( req.get().host )+"_last_tracked_location") ) { loc = RecordedLocation.coll.findOneById( session().get(Tools.md5Encode( req.get().host )+"_last_tracked_location") ); } String actionsString = new String( Base64.decode( req.get().d ) ); String[] actions = actionsString.split("}"); Long lastTs = 0L; for(int i = 0; i < actions.length; i++) { String[] parts = actions[i].split("[|]"); if( parts.length < 1 ) continue; TrackedAction.Model action = null; try { switch( Byte.valueOf( parts[0] ) ) { case 0: if( parts.length != 7 ) continue; //TODO:Track domains and pageUrl action = new TrackedAction.Model(); action.e = 0; action.location = parts[1]; action.w = Short.valueOf( parts[2] ); action.h = Short.valueOf( parts[3] ); action.t = Short.valueOf( parts[4] ); action.l = Short.valueOf( parts[5] ); action.ts = Long.valueOf( parts[6] ); loc = new RecordedLocation.Model(); loc.sessionId = trackSess._id; loc.startedAt = new Date( action.ts ); loc.location = parts[1]; loc._id = RecordedLocation.save( loc ).getSavedId(); if( trackSess.firstActionAt == null ) { trackSess.firstActionAt = new Date( action.ts ); TrackSession.save(trackSess); } session().put(Tools.md5Encode( req.get().host )+"_last_tracked_location", loc._id); break; case 1: //mouse down if( parts.length != 6 ) continue; action = new TrackedAction.Model(); action.e = 1; action.x = Short.valueOf( parts[1] ); action.y = Short.valueOf( parts[2] ); action.w = Short.valueOf( parts[3] ); action.h = Short.valueOf( parts[4] ); action.ts = Long.valueOf( parts[5] ); break; case 2: //move if( parts.length != 6 ) continue; action = new TrackedAction.Model(); action.e = 2; action.x = Short.valueOf( parts[1] ); action.y = Short.valueOf( parts[2] ); action.w = Short.valueOf( parts[3] ); action.h = Short.valueOf( parts[4] ); action.ts = Long.valueOf( parts[5] ); break; case 3: //resize if( parts.length != 4 ) continue; action = new TrackedAction.Model(); action.e = 3; action.w = Short.valueOf( parts[1] ); action.h = Short.valueOf( parts[2] ); action.ts = Long.valueOf( parts[3] ); break; case 4: //scroll if( parts.length != 5 ) continue; action = new TrackedAction.Model(); action.e = 4; action.t = Short.valueOf( parts[1] ); action.l = Short.valueOf( parts[2] ); action.d = parts[3]; action.ts = Long.valueOf( parts[4] ); break; case 5: break; } } catch(NumberFormatException e) { continue; } if( action != null ) { action.recLocId = loc._id; TrackedAction.save(action); lastTs = action.ts; } } if( lastTs > 0 ) { loc.lastActionAt = new Date( lastTs ); trackSess.lastActionAt = new Date( lastTs ); TrackSession.save( trackSess ); } RecordedLocation.save( loc ); session().put(Tools.md5Encode( req.get().host )+"_tracked_session_ts", ( systemTs + 3600000 )+""); response().setContentType( "image/png" ); return ok( outGifStream ); } public static Result dummy() {/* Form<TrackRequest> req = form( TrackRequest.class ).bindFromRequest(); List<String> dummy = new ArrayList<String>(); dummy.add( "0|http://localhost/work/we3c/static/barebone.html#|1600|503|0|0|1339451636005}2|538|292|1339451636828}2|66|494|1339451638213}2|42|66|1339451638366}2|480|3|1339451638586}2|773|283|1339451638927}1|781|290|1339451639133}2|860|309|1339451639287}2|904|309|1339451639304}2|942|313|1339451639319}2|980|313|1339451639336}2|993|315|1339451639341}2|1350|261|1339451639607}1|1351|260|1339451639706}2|1346|260|1339451639874}2|1253|253|1339451639927}2|1230|255|1339451639935}2|881|246|1339451640021}2|860|249|1339451640033}2|762|247|1339451640078}2|691|275|1339451640209}2|680|275|1339451640225}2|654|278|1339451640271}4|2|0||1339451640322}4|128|0|d|1339451640701}2|563|384|1339451641061}2|532|382|1339451641156}2|523|383|1339451641227}2|485|375|1339451641382}2|398|467|1339451641476}2|369|467|1339451641586}2|340|471|1339451641820}1|339|471|1339451641849}2|336|470|1339451641976}2|227|464|1339451642029}2|198|466|1339451642038}2|0|295|1339451642186}2|218|241|1339451642505}2|470|277|1339451642569}2|503|277|1339451642577}2|532|279|1339451642585}2|557|279|1339451642591}2|744|310|1339451642663}2|759|310|1339451642672}2|783|315|1339451642686}2|796|315|1339451642694}2|807|320|1339451642701}2|816|320|1339451642712}2|979|398|1339451642935}2|1121|228|1339451643077}2|1121|205|1339451643085}2|1126|171|1339451643099}2|1126|136|1339451643123}2|715|236|1339451643381}2|574|233|1339451643405}2|523|235|1339451643413}2|443|232|1339451643427}2|408|234|1339451643435}2|314|201|1339451643529}2|316|186|1339451643537}" ); dummy.add( "2|318|165|1339451643554}2|438|60|1339451643664}2|902|266|1339451644115}2|1195|259|1339451644269}4|125|0||1339451645048}4|2|0|t|1339451645366}2|1191|266|1339451645385}4|0|0||1339451645386}2|1185|266|1339451645421}2|1075|263|1339451645460}2|1040|265|1339451645468}2|1007|265|1339451645476}2|974|267|1339451645483}2|861|261|1339451645508}2|746|268|1339451645530}2|680|268|1339451645552}2|603|276|1339451645570}2|580|276|1339451645578}2|525|288|1339451645600}2|514|288|1339451645608}2|503|291|1339451645616}2|494|291|1339451645624}2|389|352|1339451645906}2|376|352|1339451645922}2|362|355|1339451645944}2|340|355|1339451645976}2|331|356|1339451646008}1|331|357|1339451646055}2|328|351|1339451646202}2|200|77|1339451646319}2|216|67|1339451646397}2|479|265|1339451646693}1|482|265|1339451646765}2|758|418|1339451647091}2|795|418|1339451647115}2|888|436|1339451647366}2|925|436|1339451647390}2|936|439|1339451647397}2|1009|425|1339451647585}1|1014|423|1339451647643}2|1249|195|1339451648099}2|1249|185|1339451648132}1|1248|178|1339451648215}2|736|147|1339451648521}2|713|149|1339451648529}2|521|143|1339451648639}2|209|356|1339451648921}2|200|356|1339451648928}2|149|364|1339451648992}2|117|331|1339451649123}2|301|229|1339451649257}2|619|369|1339451649553}2|1093|172|1339451649873}2|1093|163|1339451649881}2|1098|151|1339451649889}2|1098|142|1339451649897}2|1116|120|1339451649959}2|1253|172|1339451650077}2|1014|246|1339451650311}2|989|246|1339451650319}" ); dummy.add( "2|945|243|1339451650336}2|497|134|1339451650521}2|488|136|1339451650529}2|479|136|1339451650537}2|470|138|1339451650545}2|459|138|1339451650561}2|405|174|1339451650663}2|386|174|1339451650717}2|291|306|1339451651099}2|349|353|1339451651397}2|367|353|1339451651413}2|379|357|1339451651421}2|398|357|1339451651427}2|468|370|1339451651459}2|487|370|1339451651474}2|529|375|1339451651483}2|569|375|1339451651499}2|588|378|1339451651505}2|609|378|1339451651513}2|653|383|1339451651529}2|699|383|1339451651545}2|722|385|1339451651553}2|743|385|1339451651561}2|766|387|1339451651574}2|1268|277|1339451651913}2|1253|174|1339451652007}2|1257|156|1339451652093}2|1042|407|1339451652295}2|301|238|1339451652671}2|709|177|1339451652857}2|718|180|1339451652865}2|727|180|1339451652874}2|1099|322|1339451653030}2|1130|322|1339451653037}2|1161|324|1339451653045}2|1324|277|1339451653139}2|1324|265|1339451653147}2|1326|253|1339451653155}2|1326|216|1339451653171}2|1328|203|1339451653177}2|1328|146|1339451653201}2|1332|128|1339451653217}2|1322|105|1339451653373}2|856|238|1339451653499}2|417|159|1339451653663}4|5|0||1339451653815}2|414|153|1339451653836}4|20|0||1339451653844}2|414|154|1339451653861}4|40|0||1339451653866}4|51|0|d|1339451653879}2|415|154|1339451653897}4|64|0||1339451653900}2|415|155|1339451653920}4|78|0||1339451653923}2|414|158|1339451653938}4|87|0||1339451653940}2|413|161|1339451653949}4|95|0||1339451653957}2|410|165|1339451653972}" ); dummy.add( "4|105|0||1339451653981}2|409|173|1339451653995}4|112|0||1339451654002}2|409|175|1339451654008}4|121|0||1339451654029}2|409|178|1339451654038}4|124|0||1339451654039}4|128|0|d|1339451654078}2|409|179|1339451654233}2|439|190|1339451654358}2|448|190|1339451654406}4|125|0||1339451654495}2|456|190|1339451654510}4|110|0||1339451654520}4|73|0|t|1339451654564}2|460|190|1339451654581}4|61|0||1339451654583}2|462|190|1339451654587}4|48|0||1339451654611}2|469|192|1339451654617}4|42|0||1339451654618}4|37|0|t|1339451654631}2|471|192|1339451654635}4|31|0||1339451654647}2|474|192|1339451654650}4|26|0||1339451654663}2|477|193|1339451654666}4|19|0||1339451654684}2|480|193|1339451654685}4|14|0||1339451654700}2|481|193|1339451654702}4|10|0||1339451654716}2|487|193|1339451654719}4|7|0||1339451654732}2|518|193|1339451654753}4|3|0||1339451654754}2|550|186|1339451654763}4|1|0||1339451654770}2|594|186|1339451654779}4|0|0||1339451654787}2|877|2|1339451654881}3|1541|496|1339451655809}2|932|14|1339451656029}2|934|26|1339451656037}2|934|41|1339451656045}2|1147|303|1339451656257}2|1192|303|1339451656327}2|1226|309|1339451656373}2|1268|309|1339451656421}2|1304|318|1339451656492}3|1163|496|1339451656805}2|862|313|1339451657217}2|871|313|1339451657398}3|1454|496|1339451657683}2|1210|291|1339451658091}2|948|222|1339451658427}4|2|0||1339451658434}2|947|222|1339451658439}4|9|0||1339451658456}4|27|0|d|1339451658485}" ); dummy.add( "2|945|222|1339451658516}4|61|0||1339451658524}4|114|0|d|1339451658638}2|943|222|1339451658652}4|121|0||1339451658655}4|135|0|d|1339451658730}4|43|0|t|1339451659112}2|946|223|1339451659116}4|30|0||1339451659136}2|948|227|1339451659144}4|23|0||1339451659151}2|951|229|1339451659163}4|17|0||1339451659166}2|953|230|1339451659179}4|12|0||1339451659181}2|957|231|1339451659185}4|7|0||1339451659197}2|963|234|1339451659201}2|972|240|1339451659213}4|3|0||1339451659214}2|1000|255|1339451659230}4|1|0||1339451659231}2|1029|272|1339451659241}4|0|0||1339451659247}2|1124|306|1339451659295}3|1012|496|1339451659696}2|584|277|1339451659897}2|555|273|1339451659999}4|2|0||1339451660501}4|135|0|d|1339451660783}2|552|272|1339451661062}4|134|0||1339451661182}4|20|0|t|1339451661378}2|555|271|1339451661398}4|14|0||1339451661400}2|559|272|1339451661405}4|10|0||1339451661417}2|572|275|1339451661419}4|7|0||1339451661433}2|588|279|1339451661435}2|604|282|1339451661443}4|4|0||1339451661449}2|633|285|1339451661459}4|2|0||1339451661466}2|663|293|1339451661475}4|0|0||1339451661482}2|774|335|1339451661655}3|1454|496|1339451661994}2|1250|340|1339451662349}2|572|191|1339451662607}2|532|195|1339451662624}2|496|195|1339451662639}2|421|228|1339451662749}4|3|0||1339451662793}2|423|234|1339451662796}4|18|0||1339451662820}4|47|0|d|1339451662853}2|425|238|1339451662869}4|62|0||1339451662877}2|427|239|1339451662891}" ); dummy.add( "4|78|0||1339451662900}2|428|241|1339451662914}4|88|0||1339451662922}2|430|244|1339451662937}4|103|0||1339451662948}2|431|245|1339451662955}4|119|0||1339451662996}2|435|253|1339451663017}4|128|0||1339451663021}4|135|0|d|1339451663069}2|436|253|1339451663258}4|129|0||1339451663270}2|437|253|1339451663279}4|117|0||1339451663289}2|440|254|1339451663298}4|102|0||1339451663305}2|445|255|1339451663316}4|89|0||1339451663321}2|450|255|1339451663327}4|65|0||1339451663355}2|457|256|1339451663373}4|52|0||1339451663379}2|462|256|1339451663395}4|42|0||1339451663399}2|466|256|1339451663415}4|34|0||1339451663417}2|474|256|1339451663425}4|30|0||1339451663430}2|482|255|1339451663440}4|26|0||1339451663442}2|489|255|1339451663449}4|22|0||1339451663455}2|496|252|1339451663460}2|510|240|1339451663484}4|14|0||1339451663489}2|525|224|1339451663503}4|8|0||1339451663506}2|538|205|1339451663513}4|6|0||1339451663518}2|552|180|1339451663530}4|4|0||1339451663532}2|562|150|1339451663545}4|2|0||1339451663547}2|572|123|1339451663564}4|0|0||1339451663565}2|580|63|1339451663591}2|580|50|1339451663599}2|609|5|1339451663718}3|1600|503|1339451664560}2|605|5|1339451664763}2|573|140|1339451664881}1|573|147|1339451664969}2|497|280|1339451665193}2|467|280|1339451665209}2|437|285|1339451665225}2|422|285|1339451665233}2|343|335|1339451665390}1|336|337|1339451665493}2|338|336|1339451665647}2|385|332|1339451665673}" ); // System.out.println( Context.current().request().headers().get("USER-AGENT")[0] ); // System.out.println( Context.current().request().headers().get("ACCEPT-LANGUAGE")[0] ); // System.out.println( Context.current().request().headers().get("CONNECTION")[0] ); // System.out.println( Context.current().request().headers().get("ACCEPT")[0] ); // System.out.println( Context.current().request().host() ); // System.out.println( Context.current().request().method() ); // System.out.println( Context.current().request().path() ); // System.out.println( Context.current().request().uri() ); // System.out.println( Context.current().request().acceptLanguages() ); // System.out.println( Context.current().request().queryString() ); TrackSession trackSess = null; //TODO:Track Api Keys && Domains if( session().containsKey("tracked_session") ) { trackSess = TrackSession.coll.findOneById( session().get("tracked_session") ); } else { trackSess = new TrackSession(); trackSess.startedAt = new Date(); if( Context.current().request().headers().containsKey("USER-AGENT") && Context.current().request().headers().get("USER-AGENT").length > 0 ) trackSess.userAgent = Context.current().request().headers().get("USER-AGENT")[0]; if( Context.current().request().headers().containsKey("ACCEPT-LANGUAGE") && Context.current().request().headers().get("ACCEPT-LANGUAGE").length > 0 ) trackSess.language = Context.current().request().headers().get("ACCEPT-LANGUAGE")[0]; trackSess.host = Context.current().request().host(); trackSess.userId = "4fdbb93244ae12efb6839f8d"; trackSess._id = trackSess.save().getSavedId(); session().put("tracked_session", trackSess._id); //TODO: get client IP using http proxy } RecordedLocation loc = null; if( session().containsKey("last_tracked_location") ) { loc = RecordedLocation.coll.findOneById( session().get("last_tracked_location") ); } for(int j = 0; j < dummy.size(); j++ ) { String[] actions = dummy.get(j).split("}"); Long lastTs = 0L; for(int i = 0; i < actions.length; i++) { String[] parts = actions[i].split("[|]"); if( parts.length < 1 ) continue; TrackedAction action = null; try { switch( Byte.valueOf( parts[0] ) ) { case 0: if( parts.length != 7 ) continue; //TODO:Track domains and pageUrl action = new TrackedAction(); action.e = 0; action.location = parts[1]; action.w = Short.valueOf( parts[2] ); action.h = Short.valueOf( parts[3] ); action.t = Short.valueOf( parts[4] ); action.l = Short.valueOf( parts[5] ); action.ts = Long.valueOf( parts[6] ); loc = new RecordedLocation(); loc.sessionId = trackSess._id; loc.startedAt = new Date( action.ts ); loc.location = parts[1]; loc._id = loc.save().getSavedId(); break; case 1: if( parts.length != 4 ) continue; action = new TrackedAction(); action.e = 1; action.x = Short.valueOf( parts[1] ); action.y = Short.valueOf( parts[2] ); action.ts = Long.valueOf( parts[3] ); break; case 2: if( parts.length != 4 ) continue; action = new TrackedAction(); action.e = 2; action.x = Short.valueOf( parts[1] ); action.y = Short.valueOf( parts[2] ); action.ts = Long.valueOf( parts[3] ); break; case 3: if( parts.length != 4 ) continue; action = new TrackedAction(); action.e = 3; action.w = Short.valueOf( parts[1] ); action.h = Short.valueOf( parts[2] ); action.ts = Long.valueOf( parts[3] ); break; case 4: if( parts.length != 5 ) continue; action = new TrackedAction(); action.e = 4; action.t = Short.valueOf( parts[1] ); action.l = Short.valueOf( parts[2] ); action.d = parts[3]; action.ts = Long.valueOf( parts[4] ); break; case 5: break; } } catch(NumberFormatException e) { continue; } if( action != null ) { action.recLocId = loc._id; action.save(); lastTs = action.ts; } } if( lastTs > 0 ) { loc.lastActionAt = new Date( lastTs ); trackSess.lastActionAt = new Date( lastTs ); trackSess.save(); } loc.save(); }*/ return ok(); } }
true
true
public static Result track() { response().setContentType( "image/png" ); InputStream outGifStream = Play.application().resourceAsStream("/public/images/site/blank.png"); Form<TrackRequest> req = form( TrackRequest.class ).bindFromRequest(); if( req.hasErrors() ) return badRequest( outGifStream ); TrackSession.Model trackSess = null; User.Model user = null; try { user = User.coll.findOneById( req.get().key ); } catch( MongoException e ) { e.printStackTrace(); return internalServerError("No User"); } if( user == null || user._id == null || user._id.isEmpty() ) return badRequest( outGifStream ); if( !User.isDomainTrackable( req.get().host, user ) ) { return forbidden( outGifStream ); } Long systemTs = new Date().getTime(); if( session().containsKey(Tools.md5Encode( req.get().host )+"_tracked_session_ts") ) if( session().containsKey(Tools.md5Encode( req.get().host )+"_tracked_session_ts") && ( systemTs < Integer.parseInt( session().get(Tools.md5Encode( req.get().host )+"_tracked_session_ts") ) ) && session().containsKey(Tools.md5Encode( req.get().host )+"_tracked_session") ) { trackSess = TrackSession.coll.findOneById( session().get( Tools.md5Encode( req.get().host )+"_tracked_session") ); } else { trackSess = new TrackSession.Model(); trackSess.startedAt = new Date(); if( Context.current().request().headers().containsKey("USER-AGENT") && Context.current().request().headers().get("USER-AGENT").length > 0 ) { trackSess.userAgent = Context.current().request().headers().get("USER-AGENT")[0]; UserAgent userAgent = UserAgent.parseUserAgentString( trackSess.userAgent ); trackSess.os = userAgent.getOperatingSystem().name(); trackSess.browser = userAgent.getBrowser().name(); } if( Context.current().request().headers().containsKey("ACCEPT-LANGUAGE") && Context.current().request().headers().get("ACCEPT-LANGUAGE").length > 0 ) { trackSess.language = Context.current().request().headers().get("ACCEPT-LANGUAGE")[0]; String[] languages = trackSess.language.split(","); if( languages.length > 1 ) trackSess.mainLanguage = languages[0]; else trackSess.mainLanguage = trackSess.language; } trackSess.host = req.get().host; trackSess.userId = user._id; trackSess._id = TrackSession.save(trackSess).getSavedId(); session().put( Tools.md5Encode( req.get().host )+"_tracked_session", trackSess._id); //TODO: get client IP using http proxy } RecordedLocation.Model loc = null; if( session().containsKey(Tools.md5Encode( req.get().host )+"_last_tracked_location") ) { loc = RecordedLocation.coll.findOneById( session().get(Tools.md5Encode( req.get().host )+"_last_tracked_location") ); } String actionsString = new String( Base64.decode( req.get().d ) ); String[] actions = actionsString.split("}"); Long lastTs = 0L; for(int i = 0; i < actions.length; i++) { String[] parts = actions[i].split("[|]"); if( parts.length < 1 ) continue; TrackedAction.Model action = null; try { switch( Byte.valueOf( parts[0] ) ) { case 0: if( parts.length != 7 ) continue; //TODO:Track domains and pageUrl action = new TrackedAction.Model(); action.e = 0; action.location = parts[1]; action.w = Short.valueOf( parts[2] ); action.h = Short.valueOf( parts[3] ); action.t = Short.valueOf( parts[4] ); action.l = Short.valueOf( parts[5] ); action.ts = Long.valueOf( parts[6] ); loc = new RecordedLocation.Model(); loc.sessionId = trackSess._id; loc.startedAt = new Date( action.ts ); loc.location = parts[1]; loc._id = RecordedLocation.save( loc ).getSavedId(); if( trackSess.firstActionAt == null ) { trackSess.firstActionAt = new Date( action.ts ); TrackSession.save(trackSess); } session().put(Tools.md5Encode( req.get().host )+"_last_tracked_location", loc._id); break; case 1: //mouse down if( parts.length != 6 ) continue; action = new TrackedAction.Model(); action.e = 1; action.x = Short.valueOf( parts[1] ); action.y = Short.valueOf( parts[2] ); action.w = Short.valueOf( parts[3] ); action.h = Short.valueOf( parts[4] ); action.ts = Long.valueOf( parts[5] ); break; case 2: //move if( parts.length != 6 ) continue; action = new TrackedAction.Model(); action.e = 2; action.x = Short.valueOf( parts[1] ); action.y = Short.valueOf( parts[2] ); action.w = Short.valueOf( parts[3] ); action.h = Short.valueOf( parts[4] ); action.ts = Long.valueOf( parts[5] ); break; case 3: //resize if( parts.length != 4 ) continue; action = new TrackedAction.Model(); action.e = 3; action.w = Short.valueOf( parts[1] ); action.h = Short.valueOf( parts[2] ); action.ts = Long.valueOf( parts[3] ); break; case 4: //scroll if( parts.length != 5 ) continue; action = new TrackedAction.Model(); action.e = 4; action.t = Short.valueOf( parts[1] ); action.l = Short.valueOf( parts[2] ); action.d = parts[3]; action.ts = Long.valueOf( parts[4] ); break; case 5: break; } } catch(NumberFormatException e) { continue; } if( action != null ) { action.recLocId = loc._id; TrackedAction.save(action); lastTs = action.ts; } } if( lastTs > 0 ) { loc.lastActionAt = new Date( lastTs ); trackSess.lastActionAt = new Date( lastTs ); TrackSession.save( trackSess ); } RecordedLocation.save( loc ); session().put(Tools.md5Encode( req.get().host )+"_tracked_session_ts", ( systemTs + 3600000 )+""); response().setContentType( "image/png" ); return ok( outGifStream ); }
public static Result track() { response().setContentType( "image/png" ); InputStream outGifStream = Play.application().resourceAsStream("/public/images/site/blank.png"); Form<TrackRequest> req = form( TrackRequest.class ).bindFromRequest(); if( req.hasErrors() ) return badRequest( outGifStream ); TrackSession.Model trackSess = null; User.Model user = null; try { user = User.coll.findOneById( req.get().key ); } catch( MongoException e ) { e.printStackTrace(); return internalServerError("No User"); } if( user == null || user._id == null || user._id.isEmpty() ) return badRequest( outGifStream ); if( !User.isDomainTrackable( req.get().host, user ) ) { return forbidden( outGifStream ); } Long systemTs = new Date().getTime(); // if( session().containsKey(Tools.md5Encode( req.get().host )+"_tracked_session_ts") ) if( session().containsKey(Tools.md5Encode( req.get().host )+"_tracked_session_ts") && ( systemTs < Integer.parseInt( session().get(Tools.md5Encode( req.get().host )+"_tracked_session_ts") ) ) && session().containsKey(Tools.md5Encode( req.get().host )+"_tracked_session") ) { trackSess = TrackSession.coll.findOneById( session().get( Tools.md5Encode( req.get().host )+"_tracked_session") ); } else { trackSess = new TrackSession.Model(); trackSess.startedAt = new Date(); if( Context.current().request().headers().containsKey("USER-AGENT") && Context.current().request().headers().get("USER-AGENT").length > 0 ) { trackSess.userAgent = Context.current().request().headers().get("USER-AGENT")[0]; UserAgent userAgent = UserAgent.parseUserAgentString( trackSess.userAgent ); trackSess.os = userAgent.getOperatingSystem().name(); trackSess.browser = userAgent.getBrowser().name(); } if( Context.current().request().headers().containsKey("ACCEPT-LANGUAGE") && Context.current().request().headers().get("ACCEPT-LANGUAGE").length > 0 ) { trackSess.language = Context.current().request().headers().get("ACCEPT-LANGUAGE")[0]; String[] languages = trackSess.language.split(","); if( languages.length > 1 ) trackSess.mainLanguage = languages[0]; else trackSess.mainLanguage = trackSess.language; } trackSess.host = req.get().host; trackSess.userId = user._id; trackSess._id = TrackSession.save(trackSess).getSavedId(); session().put( Tools.md5Encode( req.get().host )+"_tracked_session", trackSess._id); //TODO: get client IP using http proxy } RecordedLocation.Model loc = null; if( session().containsKey(Tools.md5Encode( req.get().host )+"_last_tracked_location") ) { loc = RecordedLocation.coll.findOneById( session().get(Tools.md5Encode( req.get().host )+"_last_tracked_location") ); } String actionsString = new String( Base64.decode( req.get().d ) ); String[] actions = actionsString.split("}"); Long lastTs = 0L; for(int i = 0; i < actions.length; i++) { String[] parts = actions[i].split("[|]"); if( parts.length < 1 ) continue; TrackedAction.Model action = null; try { switch( Byte.valueOf( parts[0] ) ) { case 0: if( parts.length != 7 ) continue; //TODO:Track domains and pageUrl action = new TrackedAction.Model(); action.e = 0; action.location = parts[1]; action.w = Short.valueOf( parts[2] ); action.h = Short.valueOf( parts[3] ); action.t = Short.valueOf( parts[4] ); action.l = Short.valueOf( parts[5] ); action.ts = Long.valueOf( parts[6] ); loc = new RecordedLocation.Model(); loc.sessionId = trackSess._id; loc.startedAt = new Date( action.ts ); loc.location = parts[1]; loc._id = RecordedLocation.save( loc ).getSavedId(); if( trackSess.firstActionAt == null ) { trackSess.firstActionAt = new Date( action.ts ); TrackSession.save(trackSess); } session().put(Tools.md5Encode( req.get().host )+"_last_tracked_location", loc._id); break; case 1: //mouse down if( parts.length != 6 ) continue; action = new TrackedAction.Model(); action.e = 1; action.x = Short.valueOf( parts[1] ); action.y = Short.valueOf( parts[2] ); action.w = Short.valueOf( parts[3] ); action.h = Short.valueOf( parts[4] ); action.ts = Long.valueOf( parts[5] ); break; case 2: //move if( parts.length != 6 ) continue; action = new TrackedAction.Model(); action.e = 2; action.x = Short.valueOf( parts[1] ); action.y = Short.valueOf( parts[2] ); action.w = Short.valueOf( parts[3] ); action.h = Short.valueOf( parts[4] ); action.ts = Long.valueOf( parts[5] ); break; case 3: //resize if( parts.length != 4 ) continue; action = new TrackedAction.Model(); action.e = 3; action.w = Short.valueOf( parts[1] ); action.h = Short.valueOf( parts[2] ); action.ts = Long.valueOf( parts[3] ); break; case 4: //scroll if( parts.length != 5 ) continue; action = new TrackedAction.Model(); action.e = 4; action.t = Short.valueOf( parts[1] ); action.l = Short.valueOf( parts[2] ); action.d = parts[3]; action.ts = Long.valueOf( parts[4] ); break; case 5: break; } } catch(NumberFormatException e) { continue; } if( action != null ) { action.recLocId = loc._id; TrackedAction.save(action); lastTs = action.ts; } } if( lastTs > 0 ) { loc.lastActionAt = new Date( lastTs ); trackSess.lastActionAt = new Date( lastTs ); TrackSession.save( trackSess ); } RecordedLocation.save( loc ); session().put(Tools.md5Encode( req.get().host )+"_tracked_session_ts", ( systemTs + 3600000 )+""); response().setContentType( "image/png" ); return ok( outGifStream ); }
diff --git a/interfaces/test/swp_compiler_ss13/common/lexer/LexerContractTest.java b/interfaces/test/swp_compiler_ss13/common/lexer/LexerContractTest.java index 500a414..1069a04 100644 --- a/interfaces/test/swp_compiler_ss13/common/lexer/LexerContractTest.java +++ b/interfaces/test/swp_compiler_ss13/common/lexer/LexerContractTest.java @@ -1,510 +1,496 @@ package swp_compiler_ss13.common.lexer; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import org.junit.Before; import org.junit.Test; public abstract class LexerContractTest<L extends Lexer> { public L lexer; @Before public final void setup() { lexer = getLexerInstance(); } protected abstract L getLexerInstance(); @Test public void nonInitializedLexerReturnsEofToken() { assertEquals(TokenType.EOF, lexer.getNextToken().getTokenType()); assertEquals("EOF should be returns till reinitialization", TokenType.EOF, lexer.getNextToken().getTokenType()); } @Test public void withNullInitializedLexerBehavesAsIfNotInitialized() { lexer.setSourceStream(null); assertEquals(TokenType.EOF, lexer.getNextToken().getTokenType()); assertEquals("EOF should be returns till reinitialization", TokenType.EOF, lexer.getNextToken().getTokenType()); } @Test public void emptyStreamInitializedLexerReturnsEofToken() { prepareLexer(""); assertEquals(TokenType.EOF, lexer.getNextToken().getTokenType()); assertEquals("EOF should be returns till reinitialization", TokenType.EOF, lexer.getNextToken().getTokenType()); } @Test public void lexerReturnsExpectedTokenAfterInitialization() { prepareLexer("testIdToken"); assertEquals(TokenType.ID, lexer.getNextToken().getTokenType()); } @Test public void lexerReturnsEofTokenAtEndOfInput() { prepareLexer("testIdToken"); assertEquals(TokenType.ID, lexer.getNextToken().getTokenType()); assertEquals(TokenType.EOF, lexer.getNextToken().getTokenType()); assertEquals("EOF should be returns till reinitialization", TokenType.EOF, lexer.getNextToken().getTokenType()); } @Test public void lexerIsReinitializable() { prepareLexer("testIdToken"); assertEquals(TokenType.ID, lexer.getNextToken().getTokenType()); assertEquals(TokenType.EOF, lexer.getNextToken().getTokenType()); prepareLexer("2535"); assertEquals(TokenType.NUM, lexer.getNextToken().getTokenType()); assertEquals(TokenType.EOF, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenNum() { Token token = null; prepareLexer("12312"); assertEquals(TokenType.NUM, (token = lexer.getNextToken()).getTokenType()); assertTrue(token instanceof NumToken); assertThat(((NumToken) token).getLongValue(), is(12312L)); prepareLexer("12312e11"); assertEquals(TokenType.NUM, (token = lexer.getNextToken()).getTokenType()); assertTrue(token instanceof NumToken); assertThat(((NumToken) token).getLongValue(), is(1231200000000000L)); prepareLexer("12312E10"); assertEquals(TokenType.NUM, (token = lexer.getNextToken()).getTokenType()); assertTrue(token instanceof NumToken); assertThat(((NumToken) token).getLongValue(), is(123120000000000L)); } @Test public void lexerHandlesMultipleMinusInNumAsNotAToken() { prepareLexer("1e--1"); assertEquals(TokenType.NOT_A_TOKEN, (lexer.getNextToken()).getTokenType()); } @Test public void lexerHandlesMultipleMinusInRealAsNotAToken() { prepareLexer("1.0e--1"); assertEquals(TokenType.NOT_A_TOKEN, (lexer.getNextToken()).getTokenType()); } @Test - public void lexerHandlesMultiplePlusInNumAsNotAToken() { - prepareLexer("17e++12"); - assertEquals(TokenType.NOT_A_TOKEN, - (lexer.getNextToken()).getTokenType()); - } - - @Test - public void lexerHandlesMultiplePlusInRealAsNotAToken() { - prepareLexer("1.4e++12"); - assertEquals(TokenType.NOT_A_TOKEN, - (lexer.getNextToken()).getTokenType()); - } - - @Test public void lexerRecognizeTokenReal() { Token token = null; prepareLexer("12312.0"); assertEquals(TokenType.REAL, (token = lexer.getNextToken()).getTokenType()); assertTrue(token instanceof RealToken); assertThat(((RealToken) token).getDoubleValue(), is(12312.0)); prepareLexer("12312.0e1"); assertEquals(TokenType.REAL, (token = lexer.getNextToken()).getTokenType()); assertTrue(token instanceof RealToken); assertThat(((RealToken) token).getDoubleValue(), is(123120.0)); prepareLexer("12312.0E1"); assertEquals(TokenType.REAL, (token = lexer.getNextToken()).getTokenType()); assertTrue(token instanceof RealToken); assertThat(((RealToken) token).getDoubleValue(), is(123120.0)); } @Test public void lexerRecognizeTokenString() { Token token = null; prepareLexer("\"test-string$$\""); assertEquals(TokenType.STRING, (token = lexer.getNextToken()).getTokenType()); assertEquals("\"test-string$$\"", token.getValue()); } @Test public void lexerRecognizeTokenTrue() { Token token = null; prepareLexer("true"); assertEquals(TokenType.TRUE, (token = lexer.getNextToken()).getTokenType()); assertTrue(token instanceof BoolToken); assertTrue(((BoolToken) token).getBooleanValue()); } @Test public void lexerRecognizeTokenFalse() { Token token = null; prepareLexer("false"); assertEquals(TokenType.FALSE, (token = lexer.getNextToken()).getTokenType()); assertTrue(token instanceof BoolToken); assertFalse(((BoolToken) token).getBooleanValue()); } @Test public void lexerRecognizeStringsWithEscapedQuotes() { Token token = null; prepareLexer("\"test-string\\\"\""); assertEquals(TokenType.STRING, (token = lexer.getNextToken()).getTokenType()); assertEquals("\"test-string\\\"\"", token.getValue()); } @Test public void lexerEndsStringsWithCorrectEscapingAtCorrectPosition() { Token token = null; prepareLexer("\"test-string\\\"\"\"test\""); assertEquals(TokenType.STRING, (token = lexer.getNextToken()).getTokenType()); assertEquals("\"test-string\\\"\"", token.getValue()); assertEquals(TokenType.STRING, (token = lexer.getNextToken()).getTokenType()); assertEquals("\"test\"", token.getValue()); } @Test public void lexerRecognizeIdToken() { Token token = null; prepareLexer("a"); assertEquals(TokenType.ID, (token = lexer.getNextToken()).getTokenType()); assertEquals("a", token.getValue()); prepareLexer("and"); assertEquals(TokenType.ID, (token = lexer.getNextToken()).getTokenType()); assertEquals("and", token.getValue()); prepareLexer("aComplexIdTypeWith100Meanings"); assertEquals(TokenType.ID, (token = lexer.getNextToken()).getTokenType()); assertEquals("aComplexIdTypeWith100Meanings", token.getValue()); } @Test public void lexerRecognizeTokenMinus() { prepareLexer("-"); assertEquals(TokenType.MINUS, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenPlus() { prepareLexer("+"); assertEquals(TokenType.PLUS, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenTimes() { prepareLexer("*"); assertEquals(TokenType.TIMES, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenDivide() { prepareLexer("/"); assertEquals(TokenType.DIVIDE, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenAssign() { prepareLexer("="); assertEquals(TokenType.ASSIGNOP, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenEquals() { prepareLexer("=="); assertEquals(TokenType.EQUALS, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenGreater() { prepareLexer(">"); assertEquals(TokenType.GREATER, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenGreaterEqual() { prepareLexer(">="); assertEquals(TokenType.GREATER_EQUAL, lexer.getNextToken() .getTokenType()); } @Test public void lexerRecognizeTokenLess() { prepareLexer("<"); assertEquals(TokenType.LESS, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenLessOrEqual() { prepareLexer("<="); assertEquals(TokenType.LESS_OR_EQUAL, lexer.getNextToken() .getTokenType()); } @Test public void lexerRecognizeTokenNot() { prepareLexer("!"); assertEquals(TokenType.NOT, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenNotEquals() { prepareLexer("!="); assertEquals(TokenType.NOT_EQUALS, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenOr() { prepareLexer("||"); assertEquals(TokenType.OR, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenAnd() { prepareLexer("&&"); assertEquals(TokenType.AND, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenBreak() { prepareLexer("break"); assertEquals(TokenType.BREAK, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenDo() { prepareLexer("do"); assertEquals(TokenType.DO, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenIf() { prepareLexer("if"); assertEquals(TokenType.IF, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenElse() { prepareLexer("else"); assertEquals(TokenType.ELSE, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenWhile() { prepareLexer("while"); assertEquals(TokenType.WHILE, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenPrint() { prepareLexer("print"); assertEquals(TokenType.PRINT, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenLongSymbol() { prepareLexer("long"); assertEquals(TokenType.LONG_SYMBOL, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenDoubleSymbol() { prepareLexer("double"); assertEquals(TokenType.DOUBLE_SYMBOL, lexer.getNextToken() .getTokenType()); } @Test public void lexerRecognizeTokenBoolSymbol() { prepareLexer("bool"); assertEquals(TokenType.BOOL_SYMBOL, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenStringSymbol() { prepareLexer("string"); assertEquals(TokenType.STRING_SYMBOL, lexer.getNextToken() .getTokenType()); } @Test public void lexerRecognizeTokenLeftParan() { prepareLexer("("); assertEquals(TokenType.LEFT_PARAN, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenRightParan() { prepareLexer(")"); assertEquals(TokenType.RIGHT_PARAN, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenLeftBrace() { prepareLexer("{"); assertEquals(TokenType.LEFT_BRACE, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenRightBrace() { prepareLexer("}"); assertEquals(TokenType.RIGHT_BRACE, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenLeftBracket() { prepareLexer("["); assertEquals(TokenType.LEFT_BRACKET, lexer.getNextToken() .getTokenType()); } @Test public void lexerRecognizeTokenRightBracket() { prepareLexer("]"); assertEquals(TokenType.RIGHT_BRACKET, lexer.getNextToken() .getTokenType()); } @Test public void lexerRecognizeTokenSemicolon() { prepareLexer(";"); assertEquals(TokenType.SEMICOLON, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeTokenComment() { prepareLexer("#hello\n"); assertEquals(TokenType.COMMENT, lexer.getNextToken().getTokenType()); prepareLexer("#hello"); assertEquals("Comments at document end may have no newline-character", TokenType.COMMENT, lexer.getNextToken().getTokenType()); } @Test public void lexerIsCaseSensitive() { prepareLexer("True TRUE False FALse Do DO Break If iF IF ElSe"); for (int i = 0; i < 11; i++) assertEquals(TokenType.ID, lexer.getNextToken().getTokenType()); assertEquals(TokenType.EOF, lexer.getNextToken().getTokenType()); } @Test public void lexerReturnsForNonTokenizableCharactersNotAToken() { prepareLexer("not $ $ print"); assertEquals(TokenType.ID, lexer.getNextToken().getTokenType()); assertEquals(TokenType.NOT_A_TOKEN, lexer.getNextToken().getTokenType()); assertEquals(TokenType.PRINT, lexer.getNextToken().getTokenType()); assertEquals(TokenType.EOF, lexer.getNextToken().getTokenType()); } @Test public void lexerRecognizeNotATokenAlsoAtEndOfStream() { prepareLexer("not $ $"); assertEquals(TokenType.ID, lexer.getNextToken().getTokenType()); assertEquals(TokenType.NOT_A_TOKEN, lexer.getNextToken().getTokenType()); assertEquals(TokenType.EOF, lexer.getNextToken().getTokenType()); } @Test public void lexerDoesNotMisrecognizeIdsStartingLikeReservedWords() { prepareLexer("true88 printer"); assertEquals(TokenType.ID, lexer.getNextToken().getTokenType()); assertEquals(TokenType.ID, lexer.getNextToken().getTokenType()); assertEquals(TokenType.EOF, lexer.getNextToken().getTokenType()); } @Test public void lexerIgnoresAdditionalWhitespaces() { prepareLexer("ids \t\n = \t\r\n\t\t 42\n\n;"); assertEquals(TokenType.ID, lexer.getNextToken().getTokenType()); assertEquals(TokenType.ASSIGNOP, lexer.getNextToken().getTokenType()); assertEquals(TokenType.NUM, lexer.getNextToken().getTokenType()); assertEquals(TokenType.SEMICOLON, lexer.getNextToken().getTokenType()); assertEquals(TokenType.EOF, lexer.getNextToken().getTokenType()); } @Test public void lexerMatchLongerStatements() { prepareLexer("distance=a*b;\nstr=\"Hello World\";#same message as ever\nif(i<10){\n}gate[9] = 2.67;"); TokenType[] expectedTokens = { TokenType.ID, TokenType.ASSIGNOP, TokenType.ID, TokenType.TIMES, TokenType.ID, TokenType.SEMICOLON, TokenType.ID, TokenType.ASSIGNOP, TokenType.STRING, TokenType.SEMICOLON, TokenType.COMMENT, TokenType.IF, TokenType.LEFT_PARAN, TokenType.ID, TokenType.LESS, TokenType.NUM, TokenType.RIGHT_PARAN, TokenType.LEFT_BRACE, TokenType.RIGHT_BRACE, TokenType.ID, TokenType.LEFT_BRACKET, TokenType.NUM, TokenType.RIGHT_BRACKET, TokenType.ASSIGNOP, TokenType.REAL, TokenType.SEMICOLON, TokenType.EOF }; for (int i = 0; i < expectedTokens.length; i++) assertEquals("Token " + i, expectedTokens[i], lexer.getNextToken() .getTokenType()); } @Test public void lexerCountsColumnInLineCorrectly() { prepareLexer("ids \t = \t\r\t\t 42;"); assertThat(lexer.getNextToken().getColumn(), is(1)); assertThat(lexer.getNextToken().getColumn(), is(12)); assertThat(lexer.getNextToken().getColumn(), is(24)); assertThat(lexer.getNextToken().getColumn(), is(26)); } @Test public void lexerResetsColumnCounterAfterNewline() { prepareLexer("ids =\n 42\n;"); assertThat(lexer.getNextToken().getColumn(), is(1)); assertThat(lexer.getNextToken().getColumn(), is(5)); assertThat(lexer.getNextToken().getColumn(), is(3)); assertThat(lexer.getNextToken().getColumn(), is(1)); } @Test public void lexerCountsLinesCorrectly() { prepareLexer("id\r\n=42\r\n;"); assertThat(lexer.getNextToken().getLine(), is(1)); assertThat(lexer.getNextToken().getLine(), is(2)); assertThat(lexer.getNextToken().getLine(), is(2)); assertThat(lexer.getNextToken().getLine(), is(3)); } /** * set testString as input for the parser */ private void prepareLexer(String testString) { try { lexer.setSourceStream(new ByteArrayInputStream(testString .getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { fail("UTF-8 is unknown ?!"); } } }
true
false
null
null
diff --git a/src/main/java/ige/integration/router/IntegrationRouteBuilder.java b/src/main/java/ige/integration/router/IntegrationRouteBuilder.java index fe2d5ad..e0a3f97 100644 --- a/src/main/java/ige/integration/router/IntegrationRouteBuilder.java +++ b/src/main/java/ige/integration/router/IntegrationRouteBuilder.java @@ -1,90 +1,90 @@ package ige.integration.router; import ige.integration.processes.IntegrationProcessor; import ige.integration.processes.JMSProcessor; import ige.integration.processes.RestProcessor; import ige.integration.utils.DataBean; import org.apache.camel.CamelContext; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.impl.DefaultCamelContext; public class IntegrationRouteBuilder extends RouteBuilder { // create CamelContext CamelContext context = new DefaultCamelContext(); private final String HOSTNAME = "smtp.gmail.com"; private final String PORT = "587"; private final String PASSWORD = "PASSWORD"; private final String USERNAME = "USERNAME"; private final String FROM = "FROM"; private final String TO = "TO"; @Override public void configure() { igeInroomDiningFlow(); /* flow1(); jmsInFlow(); restLetInFlow(); */ } private void igeInroomDiningFlow() { from("restlet:/placeOrder?restletMethod=POST") .unmarshal().xmljson() - .process(new IntegrationProcessor()) + .beanRef("integrationProcessor") .choice() .when(simple("${in.body.tenant.outboundType} == '1'")) .setHeader("CamelHttpMethod").constant("POST") .setHeader("Content-Type").constant("application/x-www-form-urlencoded") .setBody(simple("payload=${in.body}")) - .to("${in.tenant.outboundUrl}") + .to("http://localhost:8080/RestfullConsumer/InRoomDinning") .when(simple("${in.body.tenant.outboundType} == '2'")) .setBody(this.body()) .to("jms:orders") .when(simple("${in.body.tenant.outboundType} == '3'")) .setHeader("subject", constant("TEST")) .to("smtp://" + HOSTNAME + ":" + PORT + "?password=" + PASSWORD + "&username=" + USERNAME + "&from=" + FROM + "&to=" + TO + "&mail.smtp.starttls.enable=true") .otherwise() .to("file://C://"); } private void restLetInFlow() { from("restlet:/postOrder?restletMethod=GET").process( new RestProcessor()); } private void jmsInFlow() { from("jms:orders").process(new JMSProcessor()); } private void flow1() { from("restlet:/createOrder?restletMethod=POST") .transform() .method(DataBean.class, "newData(${header[id]})") .pipeline("sql:{{sql.selectData}}") .beanRef("dataBean", "processOrder") .filter() .method(DataBean.class, "checkOrder") .process(new IntegrationProcessor()) .choice() .when() .xpath("/dataBean/id=1") .to("jms:orders") .when() .xpath("/dataBean/id=2") // .setBody(this.body()).to("restlet:/postOrder?restletMethod=GET") .setBody(this.body()) .to("restlet:/postOrder?restletMethod=GET") .otherwise() .setHeader("subject", constant("TEST")) .to("smtp://" + HOSTNAME + ":" + PORT + "?password=" + PASSWORD + "&username=" + USERNAME + "&from=" + FROM + "&to=" + TO + "&mail.smtp.starttls.enable=true"); } }
false
false
null
null
diff --git a/indexer/src/cz/incad/kramerius/indexer/FedoraOperations.java b/indexer/src/cz/incad/kramerius/indexer/FedoraOperations.java index 76ef2339c..43974aca8 100644 --- a/indexer/src/cz/incad/kramerius/indexer/FedoraOperations.java +++ b/indexer/src/cz/incad/kramerius/indexer/FedoraOperations.java @@ -1,459 +1,462 @@ package cz.incad.kramerius.indexer; import cz.incad.kramerius.FedoraAccess; import cz.incad.kramerius.impl.FedoraAccessImpl; import cz.incad.kramerius.utils.conf.KConfiguration; import dk.defxws.fedoragsearch.server.*; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; /* import fedora.client.FedoraClient; import fedora.server.access.FedoraAPIA; import fedora.server.management.FedoraAPIM; import fedora.server.types.gen.Datastream; import fedora.server.types.gen.MIMETypedStream; import java.util.Properties; import javax.xml.namespace.QName; import org.fedora.api.Datastream; import org.fedora.api.FedoraAPIMService; */ import java.util.ArrayList; import org.fedora.api.FedoraAPIA; import org.fedora.api.FedoraAPIM; import org.fedora.api.MIMETypedStream; /** * performs the generic parts of the operations * * @author gsp@dtv.dk * @version */ public class FedoraOperations { private static final Logger logger = Logger.getLogger(FedoraOperations.class); private static final Map fedoraClients = new HashMap(); protected String fgsUserName; protected String indexName; //public Properties config; public byte[] foxmlRecord; protected String dsID; protected byte[] ds; protected String dsText; protected String[] params = null; String foxmlFormat; FedoraAccess fa; public FedoraOperations() { fa = new FedoraAccessImpl(KConfiguration.getInstance()); } private static String getBaseURL(String fedoraSoap) throws Exception { final String end = "/services"; String baseURL = fedoraSoap; if (fedoraSoap.endsWith(end)) { return fedoraSoap.substring(0, fedoraSoap.length() - end.length()); } else { throw new Exception("Unable to determine baseURL from fedoraSoap" + " value (expected it to end with '" + end + "'): " + fedoraSoap); } } private FedoraAPIA getAPIA() throws Exception { try { return fa.getAPIA(); } catch (Exception e) { throw new Exception("Error getting API-A stub"); } } private FedoraAPIM getAPIM() throws Exception { return fa.getAPIM(); } public void init(String indexName/*, Properties currentConfig*/) { init(null, indexName/*, currentConfig*/); } public void init(String fgsUserName, String indexName/*, Properties currentConfig*/) { // config = currentConfig; foxmlFormat = KConfiguration.getInstance().getConfiguration().getString("FOXMLFormat"); this.fgsUserName = KConfiguration.getInstance().getConfiguration().getString("fgsUserName"); this.indexName = KConfiguration.getInstance().getConfiguration().getString("IndexName"); logger.info("Index name property is '"+this.indexName+"'"); if (null == this.fgsUserName || this.fgsUserName.length() == 0) { try { this.fgsUserName = KConfiguration.getInstance().getConfiguration().getString("fedoragsearch.testUserName"); } catch (Exception e) { this.fgsUserName = "fedoragsearch.testUserName"; } } } public void updateIndex( String action, String value, String indexNames, ArrayList<String> requestParams) throws java.rmi.RemoteException, Exception { logger.info("updateIndex" + " action=" + action + " value=" + value + " indexNames=" + indexNames); // String repositoryName = repositoryNameParam; // if (repositoryNameParam == null || repositoryNameParam.equals("")) { // repositoryName = KConfiguration.getInstance().getConfiguration().getString("RepositoryName"); // } SolrOperations ops = new SolrOperations(this); ops.updateIndex(action, value, indexName, requestParams); } public byte[] getAndReturnFoxmlFromPid( String pid) throws java.rmi.RemoteException, Exception { if (logger.isDebugEnabled()) { logger.debug("getAndReturnFoxmlFromPid pid=" + pid); } try { return fa.getAPIM().export(pid, foxmlFormat, "public"); } catch (Exception e) { throw new Exception("Fedora Object " + pid + " not found. ", e); } } public void getFoxmlFromPid( String pid) throws java.rmi.RemoteException, Exception { if (logger.isInfoEnabled()) { logger.info("getFoxmlFromPid" + " pid=" + pid); } String format = "info:fedora/fedora-system:FOXML-1.1"; try { foxmlRecord = fa.getAPIM().export(pid, format, "public"); } catch (Exception e) { e.printStackTrace(); throw new Exception("Fedora Object " + pid + " not found. ", e); } } public int getPdfPagesCount( String pid, String dsId) throws Exception { ds = null; if (dsId != null) { try { FedoraAPIA apia = fa.getAPIA(); MIMETypedStream mts = apia.getDatastreamDissemination(pid, dsId, null); if (mts == null) { return 1; } ds = mts.getStream(); return (new TransformerToText().getPdfPagesCount(ds) + 1); } catch (Exception e) { throw new Exception(e.getClass().getName() + ": " + e.toString()); } } return 1; } public String getDatastreamText( String pid, String repositoryName, String dsId, String docCount) throws Exception { return getDatastreamText(pid, repositoryName, dsId, KConfiguration.getInstance().getConfiguration().getString("FedoraSoap"), KConfiguration.getInstance().getConfiguration().getString("FedoraUser"), KConfiguration.getInstance().getConfiguration().getString("FedoraPass"), KConfiguration.getInstance().getConfiguration().getString("TrustStorePath"), KConfiguration.getInstance().getConfiguration().getString("TrustStorePass"),docCount); } public String getParents(String pid){ try{ String query = "$object * <info:fedora/" + pid + ">"; String urlStr = KConfiguration.getInstance().getConfiguration().getString("FedoraResourceIndex") + "?type=triples&flush=true&lang=spo&format=N-Triples&limit=&distinct=off&stream=off" + "&query=" + java.net.URLEncoder.encode(query, "UTF-8"); StringBuilder sb = new StringBuilder(); java.net.URL url = new java.net.URL(urlStr); java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(url.openStream())); String inputLine; + int end; while ((inputLine = in.readLine()) != null) { //<info:fedora/uuid:5fe0b160-62d5-11dd-bdc7-000d606f5dc6> <http://www.nsdl.org/ontologies/relationships#hasPage> <info:fedora/uuid:75fca1f0-64b2-11dd-9fd4-000d606f5dc6> . //<info:fedora/uuid:f0da6570-8f3b-11dd-b796-000d606f5dc6> <http://www.nsdl.org/ontologies/relationships#isOnPage> <info:fedora/uuid:75fca1f0-64b2-11dd-9fd4-000d606f5dc6> . - inputLine = inputLine.substring(18,54); + end = inputLine.indexOf(">"); +//18 je velikost <info:fedora/uuid: + inputLine = inputLine.substring(18,end); sb.append(inputLine); sb.append(";"); } in.close(); sb.delete(sb.length()-1, sb.length()); return sb.toString(); }catch(Exception ex){ ex.printStackTrace(); logger.error(ex); return ""; } } public String getDatastreamText( String pid, String repositoryName, String dsId, String fedoraSoap, String fedoraUser, String fedoraPass, String trustStorePath, String trustStorePass, String pageNum) throws Exception { if (logger.isDebugEnabled()) { logger.debug("getDatastreamText" + " pid=" + pid + " repositoryName=" + repositoryName + " dsId=" + dsId + " fedoraSoap=" + fedoraSoap + " fedoraUser=" + fedoraUser + " fedoraPass=" + fedoraPass + " trustStorePath=" + trustStorePath + " trustStorePass=" + trustStorePass); } StringBuffer dsBuffer = new StringBuffer(); String mimetype = ""; ds = null; if (dsId != null) { try { FedoraAPIA apia = fa.getAPIA(); MIMETypedStream mts = apia.getDatastreamDissemination(pid, dsId, null); if (mts == null) { return ""; } ds = mts.getStream(); mimetype = mts.getMIMEType(); } catch (Exception e) { throw new Exception(e.getClass().getName() + ": " + e.toString()); } } if (ds != null) { dsBuffer = (new TransformerToText().getText(ds, mimetype, pageNum)); } else { logger.debug("ds is null"); } if (logger.isDebugEnabled()) { logger.debug("getDatastreamText" + " pid=" + pid + " dsId=" + dsId + " mimetype=" + mimetype + " dsBuffer=" + dsBuffer.toString()); } return dsBuffer.toString(); } /* public StringBuffer getFirstDatastreamText( String pid, String repositoryName, String dsMimetypes) throws Exception, Exception { return getFirstDatastreamText(pid, repositoryName, dsMimetypes, config.getProperty("FedoraSoap"), config.getProperty("FedoraUser"), config.getProperty("FedoraPass"), config.getProperty("TrustStorePath"), config.getProperty("TrustStorePass")); } public StringBuffer getFirstDatastreamText( String pid, String repositoryName, String dsMimetypes, String fedoraSoap, String fedoraUser, String fedoraPass, String trustStorePath, String trustStorePass) throws Exception, Exception { if (logger.isInfoEnabled()) { logger.info("getFirstDatastreamText" + " pid=" + pid + " dsMimetypes=" + dsMimetypes + " fedoraSoap=" + fedoraSoap + " fedoraUser=" + fedoraUser + " fedoraPass=" + fedoraPass + " trustStorePath=" + trustStorePath + " trustStorePass=" + trustStorePass); } StringBuffer dsBuffer = new StringBuffer(); Datastream[] dsds = null; try { FedoraAPIM apim = getAPIM( repositoryName, fedoraSoap, fedoraUser, fedoraPass, trustStorePath, trustStorePass); dsds = apim.getDatastreams(pid, null, "A"); } catch (AxisFault e) { throw new Exception(e.getClass().getName() + ": " + e.toString()); } catch (RemoteException e) { throw new Exception(e.getClass().getName() + ": " + e.toString()); } // String mimetypes = "text/plain text/html application/pdf application/ps application/msword"; String mimetypes = config.getProperty("MimeTypes"); if (dsMimetypes != null && dsMimetypes.length() > 0) { mimetypes = dsMimetypes; } String mimetype = ""; dsID = null; if (dsds != null) { int best = 99999; for (int i = 0; i < dsds.length; i++) { int j = mimetypes.indexOf(dsds[i].getMIMEType()); if (j > -1 && best > j) { dsID = dsds[i].getID(); best = j; mimetype = dsds[i].getMIMEType(); } } } ds = null; if (dsID != null) { try { FedoraAPIA apia = getAPIA( repositoryName, fedoraSoap, fedoraUser, fedoraPass, trustStorePath, trustStorePass); MIMETypedStream mts = apia.getDatastreamDissemination(pid, dsID, null); ds = mts.getStream(); } catch (AxisFault e) { throw new Exception(e.getClass().getName() + ": " + e.toString()); } catch (RemoteException e) { throw new Exception(e.getClass().getName() + ": " + e.toString()); } } if (ds != null) { dsBuffer = (new TransformerToText().getText(ds, mimetype)); } if (logger.isDebugEnabled()) { logger.debug("getFirstDatastreamText" + " pid=" + pid + " dsID=" + dsID + " mimetype=" + mimetype + " dsBuffer=" + dsBuffer.toString()); } return dsBuffer; } public StringBuffer getDisseminationText( String pid, String repositoryName, String bDefPid, String methodName, String parameters, String asOfDateTime) throws Exception, Exception { return getDisseminationText(pid, repositoryName, bDefPid, methodName, parameters, asOfDateTime, config.getProperty("FedoraSoap"), config.getProperty("FedoraUser"), config.getProperty("FedoraPass"), config.getProperty("TrustStorePath"), config.getProperty("TrustStorePass")); } public StringBuffer getDisseminationText( String pid, String repositoryName, String bDefPid, String methodName, String parameters, String asOfDateTime, String fedoraSoap, String fedoraUser, String fedoraPass, String trustStorePath, String trustStorePass) throws Exception, Exception { if (logger.isInfoEnabled()) { logger.info("getDisseminationText" + " pid=" + pid + " bDefPid=" + bDefPid + " methodName=" + methodName + " parameters=" + parameters + " asOfDateTime=" + asOfDateTime + " fedoraSoap=" + fedoraSoap + " fedoraUser=" + fedoraUser + " fedoraPass=" + fedoraPass + " trustStorePath=" + trustStorePath + " trustStorePass=" + trustStorePass); } StringTokenizer st = new StringTokenizer(parameters); fedora.server.types.gen.Property[] params = new fedora.server.types.gen.Property[st.countTokens()]; for (int i = 0; i < st.countTokens(); i++) { String param = st.nextToken(); String[] nameAndValue = param.split("="); params[i] = new fedora.server.types.gen.Property(nameAndValue[0], nameAndValue[1]); } if (logger.isDebugEnabled()) { logger.debug("getDisseminationText" + " #parameters=" + params.length); } StringBuffer dsBuffer = new StringBuffer(); String mimetype = ""; ds = null; if (pid != null) { try { FedoraAPIA apia = getAPIA( repositoryName, fedoraSoap, fedoraUser, fedoraPass, trustStorePath, trustStorePass); MIMETypedStream mts = apia.getDissemination(pid, bDefPid, methodName, params, asOfDateTime); if (mts == null) { throw new Exception("getDissemination returned null"); } ds = mts.getStream(); mimetype = mts.getMIMEType(); if (logger.isDebugEnabled()) { logger.debug("getDisseminationText" + " mimetype=" + mimetype); } } catch (AxisFault e) { if (e.getFaultString().indexOf("DisseminatorNotFoundException") > -1) { return new StringBuffer(); } else { throw new Exception(e.getFaultString() + ": " + e.toString()); } } catch (RemoteException e) { throw new Exception(e.getClass().getName() + ": " + e.toString()); }catch (Exception e) { if (e.toString().indexOf("DisseminatorNotFoundException") > -1) { return new StringBuffer(); } else { throw new Exception(e.toString()); } } } if (ds != null) { dsBuffer = (new TransformerToText().getText(ds, mimetype)); } if (logger.isDebugEnabled()) { logger.debug("getDisseminationText" + " pid=" + pid + " bDefPid=" + bDefPid + " mimetype=" + mimetype + " dsBuffer=" + dsBuffer.toString()); } return dsBuffer; } */ }
false
false
null
null
diff --git a/src/com/android/contacts/list/CustomContactListFilterActivity.java b/src/com/android/contacts/list/CustomContactListFilterActivity.java index 638a28ebb..d5395bd21 100644 --- a/src/com/android/contacts/list/CustomContactListFilterActivity.java +++ b/src/com/android/contacts/list/CustomContactListFilterActivity.java @@ -1,916 +1,924 @@ /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.contacts.list; import com.android.contacts.ContactsActivity; import com.android.contacts.R; import com.android.contacts.model.AccountType; import com.android.contacts.model.AccountTypeManager; import com.android.contacts.model.AccountWithDataSet; import com.android.contacts.model.EntityDelta.ValuesDelta; import com.android.contacts.model.GoogleAccountType; import com.android.contacts.util.EmptyService; import com.android.contacts.util.LocalizedNameResolver; import com.android.contacts.util.WeakAsyncTask; import com.google.android.collect.Lists; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.app.LoaderManager.LoaderCallbacks; import android.app.ProgressDialog; import android.content.AsyncTaskLoader; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.EntityIterator; import android.content.Intent; import android.content.Loader; import android.content.OperationApplicationException; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.RemoteException; import android.preference.PreferenceManager; import android.provider.ContactsContract; import android.provider.ContactsContract.Groups; import android.provider.ContactsContract.Settings; import android.util.Log; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.CheckBox; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.ExpandableListView.ExpandableListContextMenuInfo; import android.widget.TextView; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; /** * Shows a list of all available {@link Groups} available, letting the user * select which ones they want to be visible. */ public class CustomContactListFilterActivity extends ContactsActivity implements View.OnClickListener, ExpandableListView.OnChildClickListener, LoaderCallbacks<CustomContactListFilterActivity.AccountSet> { private static final String TAG = "CustomContactListFilterActivity"; private static final int ACCOUNT_SET_LOADER_ID = 1; private ExpandableListView mList; private DisplayAdapter mAdapter; private SharedPreferences mPrefs; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.contact_list_filter_custom); mList = (ExpandableListView) findViewById(com.android.internal.R.id.list); mList.setOnChildClickListener(this); mList.setHeaderDividersEnabled(true); mPrefs = PreferenceManager.getDefaultSharedPreferences(this); mAdapter = new DisplayAdapter(this); final LayoutInflater inflater = getLayoutInflater(); findViewById(R.id.btn_done).setOnClickListener(this); findViewById(R.id.btn_discard).setOnClickListener(this); mList.setOnCreateContextMenuListener(this); mList.setAdapter(mAdapter); ActionBar actionBar = getActionBar(); if (actionBar != null) { // android.R.id.home will be triggered in onOptionsItemSelected() actionBar.setDisplayHomeAsUpEnabled(true); } } public static class CustomFilterConfigurationLoader extends AsyncTaskLoader<AccountSet> { private AccountSet mAccountSet; public CustomFilterConfigurationLoader(Context context) { super(context); } @Override public AccountSet loadInBackground() { Context context = getContext(); final AccountTypeManager accountTypes = AccountTypeManager.getInstance(context); final ContentResolver resolver = context.getContentResolver(); final AccountSet accounts = new AccountSet(); for (AccountWithDataSet account : accountTypes.getAccounts(false)) { final AccountType accountType = accountTypes.getAccountTypeForAccount(account); if (accountType.isExtension() && !account.hasData(context)) { // Extension with no data -- skip. continue; } AccountDisplay accountDisplay = new AccountDisplay(resolver, account.name, account.type, account.dataSet); final Uri.Builder groupsUri = Groups.CONTENT_URI.buildUpon() .appendQueryParameter(Groups.ACCOUNT_NAME, account.name) .appendQueryParameter(Groups.ACCOUNT_TYPE, account.type); if (account.dataSet != null) { groupsUri.appendQueryParameter(Groups.DATA_SET, account.dataSet).build(); } EntityIterator iterator = ContactsContract.Groups.newEntityIterator(resolver.query( groupsUri.build(), null, null, null, null)); try { boolean hasGroups = false; // Create entries for each known group while (iterator.hasNext()) { final ContentValues values = iterator.next().getEntityValues(); final GroupDelta group = GroupDelta.fromBefore(values); accountDisplay.addGroup(group); hasGroups = true; } // Create single entry handling ungrouped status accountDisplay.mUngrouped = GroupDelta.fromSettings(resolver, account.name, account.type, account.dataSet, hasGroups); accountDisplay.addGroup(accountDisplay.mUngrouped); } finally { iterator.close(); } accounts.add(accountDisplay); } return accounts; } @Override public void deliverResult(AccountSet cursor) { if (isReset()) { return; } mAccountSet = cursor; if (isStarted()) { super.deliverResult(cursor); } } @Override protected void onStartLoading() { if (mAccountSet != null) { deliverResult(mAccountSet); } if (takeContentChanged() || mAccountSet == null) { forceLoad(); } } @Override protected void onStopLoading() { cancelLoad(); } @Override protected void onReset() { super.onReset(); onStopLoading(); mAccountSet = null; } } @Override protected void onStart() { getLoaderManager().initLoader(ACCOUNT_SET_LOADER_ID, null, this); super.onStart(); } @Override public Loader<AccountSet> onCreateLoader(int id, Bundle args) { return new CustomFilterConfigurationLoader(this); } @Override public void onLoadFinished(Loader<AccountSet> loader, AccountSet data) { mAdapter.setAccounts(data); } @Override public void onLoaderReset(Loader<AccountSet> loader) { mAdapter.setAccounts(null); } private static final int DEFAULT_SHOULD_SYNC = 1; private static final int DEFAULT_VISIBLE = 0; /** * Entry holding any changes to {@link Groups} or {@link Settings} rows, * such as {@link Groups#SHOULD_SYNC} or {@link Groups#GROUP_VISIBLE}. */ protected static class GroupDelta extends ValuesDelta { private boolean mUngrouped = false; private boolean mAccountHasGroups; private GroupDelta() { super(); } /** * Build {@link GroupDelta} from the {@link Settings} row for the given * {@link Settings#ACCOUNT_NAME}, {@link Settings#ACCOUNT_TYPE}, and * {@link Settings#DATA_SET}. */ public static GroupDelta fromSettings(ContentResolver resolver, String accountName, String accountType, String dataSet, boolean accountHasGroups) { final Uri.Builder settingsUri = Settings.CONTENT_URI.buildUpon() .appendQueryParameter(Settings.ACCOUNT_NAME, accountName) .appendQueryParameter(Settings.ACCOUNT_TYPE, accountType); if (dataSet != null) { settingsUri.appendQueryParameter(Settings.DATA_SET, dataSet); } final Cursor cursor = resolver.query(settingsUri.build(), new String[] { Settings.SHOULD_SYNC, Settings.UNGROUPED_VISIBLE }, null, null, null); try { final ContentValues values = new ContentValues(); values.put(Settings.ACCOUNT_NAME, accountName); values.put(Settings.ACCOUNT_TYPE, accountType); values.put(Settings.DATA_SET, dataSet); if (cursor != null && cursor.moveToFirst()) { // Read existing values when present values.put(Settings.SHOULD_SYNC, cursor.getInt(0)); values.put(Settings.UNGROUPED_VISIBLE, cursor.getInt(1)); return fromBefore(values).setUngrouped(accountHasGroups); } else { // Nothing found, so treat as create values.put(Settings.SHOULD_SYNC, DEFAULT_SHOULD_SYNC); values.put(Settings.UNGROUPED_VISIBLE, DEFAULT_VISIBLE); return fromAfter(values).setUngrouped(accountHasGroups); } } finally { if (cursor != null) cursor.close(); } } public static GroupDelta fromBefore(ContentValues before) { final GroupDelta entry = new GroupDelta(); entry.mBefore = before; entry.mAfter = new ContentValues(); return entry; } public static GroupDelta fromAfter(ContentValues after) { final GroupDelta entry = new GroupDelta(); entry.mBefore = null; entry.mAfter = after; return entry; } protected GroupDelta setUngrouped(boolean accountHasGroups) { mUngrouped = true; mAccountHasGroups = accountHasGroups; return this; } @Override public boolean beforeExists() { return mBefore != null; } public boolean getShouldSync() { return getAsInteger(mUngrouped ? Settings.SHOULD_SYNC : Groups.SHOULD_SYNC, DEFAULT_SHOULD_SYNC) != 0; } public boolean getVisible() { return getAsInteger(mUngrouped ? Settings.UNGROUPED_VISIBLE : Groups.GROUP_VISIBLE, DEFAULT_VISIBLE) != 0; } public void putShouldSync(boolean shouldSync) { put(mUngrouped ? Settings.SHOULD_SYNC : Groups.SHOULD_SYNC, shouldSync ? 1 : 0); } public void putVisible(boolean visible) { put(mUngrouped ? Settings.UNGROUPED_VISIBLE : Groups.GROUP_VISIBLE, visible ? 1 : 0); } private String getAccountType() { return (mBefore == null ? mAfter : mBefore).getAsString(Settings.ACCOUNT_TYPE); } public CharSequence getTitle(Context context) { if (mUngrouped) { final String customAllContactsName = LocalizedNameResolver.getAllContactsName(context, getAccountType()); if (customAllContactsName != null) { return customAllContactsName; } if (mAccountHasGroups) { return context.getText(R.string.display_ungrouped); } else { return context.getText(R.string.display_all_contacts); } } else { final Integer titleRes = getAsInteger(Groups.TITLE_RES); if (titleRes != null) { final String packageName = getAsString(Groups.RES_PACKAGE); return context.getPackageManager().getText(packageName, titleRes, null); } else { return getAsString(Groups.TITLE); } } } /** * Build a possible {@link ContentProviderOperation} to persist any * changes to the {@link Groups} or {@link Settings} row described by * this {@link GroupDelta}. */ public ContentProviderOperation buildDiff() { if (isInsert()) { // Only allow inserts for Settings if (mUngrouped) { mAfter.remove(mIdColumn); return ContentProviderOperation.newInsert(Settings.CONTENT_URI) .withValues(mAfter) .build(); } else { throw new IllegalStateException("Unexpected diff"); } } else if (isUpdate()) { if (mUngrouped) { + String accountName = this.getAsString(Settings.ACCOUNT_NAME); + String accountType = this.getAsString(Settings.ACCOUNT_TYPE); + String dataSet = this.getAsString(Settings.DATA_SET); + StringBuilder selection = new StringBuilder(Settings.ACCOUNT_NAME + "=? AND " + + Settings.ACCOUNT_TYPE + "=?"); + String[] selectionArgs; + if (dataSet == null) { + selection.append(" AND " + Settings.DATA_SET + " IS NULL"); + selectionArgs = new String[] {accountName, accountType}; + } else { + selection.append(" AND " + Settings.DATA_SET + "=?"); + selectionArgs = new String[] {accountName, accountType, dataSet}; + } return ContentProviderOperation.newUpdate(Settings.CONTENT_URI) - .withSelection(Settings.ACCOUNT_NAME + "=? AND " - + Settings.ACCOUNT_TYPE + "=?", - new String[] { - this.getAsString(Settings.ACCOUNT_NAME), - this.getAsString(Settings.ACCOUNT_TYPE) - }) + .withSelection(selection.toString(), selectionArgs) .withValues(mAfter) .build(); } else { return ContentProviderOperation.newUpdate( addCallerIsSyncAdapterParameter(Groups.CONTENT_URI)) .withSelection(Groups._ID + "=" + this.getId(), null) .withValues(mAfter) .build(); } } else { return null; } } } private static Uri addCallerIsSyncAdapterParameter(Uri uri) { return uri.buildUpon() .appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true") .build(); } /** * {@link Comparator} to sort by {@link Groups#_ID}. */ private static Comparator<GroupDelta> sIdComparator = new Comparator<GroupDelta>() { public int compare(GroupDelta object1, GroupDelta object2) { final Long id1 = object1.getId(); final Long id2 = object2.getId(); if (id1 == null && id2 == null) { return 0; } else if (id1 == null) { return -1; } else if (id2 == null) { return 1; } else if (id1 < id2) { return -1; } else if (id1 > id2) { return 1; } else { return 0; } } }; /** * Set of all {@link AccountDisplay} entries, one for each source. */ protected static class AccountSet extends ArrayList<AccountDisplay> { public ArrayList<ContentProviderOperation> buildDiff() { final ArrayList<ContentProviderOperation> diff = Lists.newArrayList(); for (AccountDisplay account : this) { account.buildDiff(diff); } return diff; } } /** * {@link GroupDelta} details for a single {@link AccountWithDataSet}, usually shown as * children under a single expandable group. */ protected static class AccountDisplay { public final String mName; public final String mType; public final String mDataSet; public GroupDelta mUngrouped; public ArrayList<GroupDelta> mSyncedGroups = Lists.newArrayList(); public ArrayList<GroupDelta> mUnsyncedGroups = Lists.newArrayList(); /** * Build an {@link AccountDisplay} covering all {@link Groups} under the * given {@link AccountWithDataSet}. */ public AccountDisplay(ContentResolver resolver, String accountName, String accountType, String dataSet) { mName = accountName; mType = accountType; mDataSet = dataSet; } /** * Add the given {@link GroupDelta} internally, filing based on its * {@link GroupDelta#getShouldSync()} status. */ private void addGroup(GroupDelta group) { if (group.getShouldSync()) { mSyncedGroups.add(group); } else { mUnsyncedGroups.add(group); } } /** * Set the {@link GroupDelta#putShouldSync(boolean)} value for all * children {@link GroupDelta} rows. */ public void setShouldSync(boolean shouldSync) { final Iterator<GroupDelta> oppositeChildren = shouldSync ? mUnsyncedGroups.iterator() : mSyncedGroups.iterator(); while (oppositeChildren.hasNext()) { final GroupDelta child = oppositeChildren.next(); setShouldSync(child, shouldSync, false); oppositeChildren.remove(); } } public void setShouldSync(GroupDelta child, boolean shouldSync) { setShouldSync(child, shouldSync, true); } /** * Set {@link GroupDelta#putShouldSync(boolean)}, and file internally * based on updated state. */ public void setShouldSync(GroupDelta child, boolean shouldSync, boolean attemptRemove) { child.putShouldSync(shouldSync); if (shouldSync) { if (attemptRemove) { mUnsyncedGroups.remove(child); } mSyncedGroups.add(child); Collections.sort(mSyncedGroups, sIdComparator); } else { if (attemptRemove) { mSyncedGroups.remove(child); } mUnsyncedGroups.add(child); } } /** * Build set of {@link ContentProviderOperation} to persist any user * changes to {@link GroupDelta} rows under this {@link AccountWithDataSet}. */ public void buildDiff(ArrayList<ContentProviderOperation> diff) { for (GroupDelta group : mSyncedGroups) { final ContentProviderOperation oper = group.buildDiff(); if (oper != null) diff.add(oper); } for (GroupDelta group : mUnsyncedGroups) { final ContentProviderOperation oper = group.buildDiff(); if (oper != null) diff.add(oper); } } } /** * {@link ExpandableListAdapter} that shows {@link GroupDelta} settings, * grouped by {@link AccountWithDataSet} type. Shows footer row when any groups are * unsynced, as determined through {@link AccountDisplay#mUnsyncedGroups}. */ protected static class DisplayAdapter extends BaseExpandableListAdapter { private Context mContext; private LayoutInflater mInflater; private AccountTypeManager mAccountTypes; private AccountSet mAccounts; private boolean mChildWithPhones = false; public DisplayAdapter(Context context) { mContext = context; mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mAccountTypes = AccountTypeManager.getInstance(context); } public void setAccounts(AccountSet accounts) { mAccounts = accounts; notifyDataSetChanged(); } /** * In group descriptions, show the number of contacts with phone * numbers, in addition to the total contacts. */ public void setChildDescripWithPhones(boolean withPhones) { mChildWithPhones = withPhones; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { if (convertView == null) { convertView = mInflater.inflate( R.layout.custom_contact_list_filter_account, parent, false); } final TextView text1 = (TextView)convertView.findViewById(android.R.id.text1); final TextView text2 = (TextView)convertView.findViewById(android.R.id.text2); final AccountDisplay account = (AccountDisplay)this.getGroup(groupPosition); final AccountType accountType = mAccountTypes.getAccountType( account.mType, account.mDataSet); text1.setText(account.mName); text1.setVisibility(account.mName == null ? View.GONE : View.VISIBLE); text2.setText(accountType.getDisplayLabel(mContext)); return convertView; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { if (convertView == null) { convertView = mInflater.inflate( R.layout.custom_contact_list_filter_group, parent, false); } final TextView text1 = (TextView)convertView.findViewById(android.R.id.text1); final TextView text2 = (TextView)convertView.findViewById(android.R.id.text2); final CheckBox checkbox = (CheckBox)convertView.findViewById(android.R.id.checkbox); final AccountDisplay account = mAccounts.get(groupPosition); final GroupDelta child = (GroupDelta)this.getChild(groupPosition, childPosition); if (child != null) { // Handle normal group, with title and checkbox final boolean groupVisible = child.getVisible(); checkbox.setVisibility(View.VISIBLE); checkbox.setChecked(groupVisible); final CharSequence groupTitle = child.getTitle(mContext); text1.setText(groupTitle); text2.setVisibility(View.GONE); } else { // When unknown child, this is "more" footer view checkbox.setVisibility(View.GONE); text1.setText(R.string.display_more_groups); text2.setVisibility(View.GONE); } return convertView; } @Override public Object getChild(int groupPosition, int childPosition) { final AccountDisplay account = mAccounts.get(groupPosition); final boolean validChild = childPosition >= 0 && childPosition < account.mSyncedGroups.size(); if (validChild) { return account.mSyncedGroups.get(childPosition); } else { return null; } } @Override public long getChildId(int groupPosition, int childPosition) { final GroupDelta child = (GroupDelta)getChild(groupPosition, childPosition); if (child != null) { final Long childId = child.getId(); return childId != null ? childId : Long.MIN_VALUE; } else { return Long.MIN_VALUE; } } @Override public int getChildrenCount(int groupPosition) { // Count is any synced groups, plus possible footer final AccountDisplay account = mAccounts.get(groupPosition); final boolean anyHidden = account.mUnsyncedGroups.size() > 0; return account.mSyncedGroups.size() + (anyHidden ? 1 : 0); } @Override public Object getGroup(int groupPosition) { return mAccounts.get(groupPosition); } @Override public int getGroupCount() { if (mAccounts == null) { return 0; } return mAccounts.size(); } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public boolean hasStableIds() { return true; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } } /** {@inheritDoc} */ public void onClick(View view) { switch (view.getId()) { case R.id.btn_done: { this.doSaveAction(); break; } case R.id.btn_discard: { this.finish(); break; } } } /** * Handle any clicks on {@link ExpandableListAdapter} children, which * usually mean toggling its visible state. */ @Override public boolean onChildClick(ExpandableListView parent, View view, int groupPosition, int childPosition, long id) { final CheckBox checkbox = (CheckBox)view.findViewById(android.R.id.checkbox); final AccountDisplay account = (AccountDisplay)mAdapter.getGroup(groupPosition); final GroupDelta child = (GroupDelta)mAdapter.getChild(groupPosition, childPosition); if (child != null) { checkbox.toggle(); child.putVisible(checkbox.isChecked()); } else { // Open context menu for bringing back unsynced this.openContextMenu(view); } return true; } // TODO: move these definitions to framework constants when we begin // defining this mode through <sync-adapter> tags private static final int SYNC_MODE_UNSUPPORTED = 0; private static final int SYNC_MODE_UNGROUPED = 1; private static final int SYNC_MODE_EVERYTHING = 2; protected int getSyncMode(AccountDisplay account) { // TODO: read sync mode through <sync-adapter> definition if (GoogleAccountType.ACCOUNT_TYPE.equals(account.mType) && account.mDataSet == null) { return SYNC_MODE_EVERYTHING; } else { return SYNC_MODE_UNSUPPORTED; } } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, view, menuInfo); // Bail if not working with expandable long-press, or if not child if (!(menuInfo instanceof ExpandableListContextMenuInfo)) return; final ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) menuInfo; final int groupPosition = ExpandableListView.getPackedPositionGroup(info.packedPosition); final int childPosition = ExpandableListView.getPackedPositionChild(info.packedPosition); // Skip long-press on expandable parents if (childPosition == -1) return; final AccountDisplay account = (AccountDisplay)mAdapter.getGroup(groupPosition); final GroupDelta child = (GroupDelta)mAdapter.getChild(groupPosition, childPosition); // Ignore when selective syncing unsupported final int syncMode = getSyncMode(account); if (syncMode == SYNC_MODE_UNSUPPORTED) return; if (child != null) { showRemoveSync(menu, account, child, syncMode); } else { showAddSync(menu, account, syncMode); } } protected void showRemoveSync(ContextMenu menu, final AccountDisplay account, final GroupDelta child, final int syncMode) { final CharSequence title = child.getTitle(this); menu.setHeaderTitle(title); menu.add(R.string.menu_sync_remove).setOnMenuItemClickListener( new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { handleRemoveSync(account, child, syncMode, title); return true; } }); } protected void handleRemoveSync(final AccountDisplay account, final GroupDelta child, final int syncMode, CharSequence title) { final boolean shouldSyncUngrouped = account.mUngrouped.getShouldSync(); if (syncMode == SYNC_MODE_EVERYTHING && shouldSyncUngrouped && !child.equals(account.mUngrouped)) { // Warn before removing this group when it would cause ungrouped to stop syncing final AlertDialog.Builder builder = new AlertDialog.Builder(this); final CharSequence removeMessage = this.getString( R.string.display_warn_remove_ungrouped, title); builder.setTitle(R.string.menu_sync_remove); builder.setMessage(removeMessage); builder.setNegativeButton(android.R.string.cancel, null); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Mark both this group and ungrouped to stop syncing account.setShouldSync(account.mUngrouped, false); account.setShouldSync(child, false); mAdapter.notifyDataSetChanged(); } }); builder.show(); } else { // Mark this group to not sync account.setShouldSync(child, false); mAdapter.notifyDataSetChanged(); } } protected void showAddSync(ContextMenu menu, final AccountDisplay account, final int syncMode) { menu.setHeaderTitle(R.string.dialog_sync_add); // Create item for each available, unsynced group for (final GroupDelta child : account.mUnsyncedGroups) { if (!child.getShouldSync()) { final CharSequence title = child.getTitle(this); menu.add(title).setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { // Adding specific group for syncing if (child.mUngrouped && syncMode == SYNC_MODE_EVERYTHING) { account.setShouldSync(true); } else { account.setShouldSync(child, true); } mAdapter.notifyDataSetChanged(); return true; } }); } } } @SuppressWarnings("unchecked") private void doSaveAction() { if (mAdapter == null || mAdapter.mAccounts == null) { finish(); return; } setResult(RESULT_OK); final ArrayList<ContentProviderOperation> diff = mAdapter.mAccounts.buildDiff(); if (diff.isEmpty()) { finish(); return; } new UpdateTask(this).execute(diff); } /** * Background task that persists changes to {@link Groups#GROUP_VISIBLE}, * showing spinner dialog to user while updating. */ public static class UpdateTask extends WeakAsyncTask<ArrayList<ContentProviderOperation>, Void, Void, Activity> { private ProgressDialog mProgress; public UpdateTask(Activity target) { super(target); } /** {@inheritDoc} */ @Override protected void onPreExecute(Activity target) { final Context context = target; mProgress = ProgressDialog.show( context, null, context.getText(R.string.savingDisplayGroups)); // Before starting this task, start an empty service to protect our // process from being reclaimed by the system. context.startService(new Intent(context, EmptyService.class)); } /** {@inheritDoc} */ @Override protected Void doInBackground( Activity target, ArrayList<ContentProviderOperation>... params) { final Context context = target; final ContentValues values = new ContentValues(); final ContentResolver resolver = context.getContentResolver(); try { final ArrayList<ContentProviderOperation> diff = params[0]; resolver.applyBatch(ContactsContract.AUTHORITY, diff); } catch (RemoteException e) { Log.e(TAG, "Problem saving display groups", e); } catch (OperationApplicationException e) { Log.e(TAG, "Problem saving display groups", e); } return null; } /** {@inheritDoc} */ @Override protected void onPostExecute(Activity target, Void result) { final Context context = target; try { mProgress.dismiss(); } catch (Exception e) { Log.e(TAG, "Error dismissing progress dialog", e); } target.finish(); // Stop the service that was protecting us context.stopService(new Intent(context, EmptyService.class)); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // Pretend cancel. setResult(Activity.RESULT_CANCELED); finish(); return true; default: break; } return super.onOptionsItemSelected(item); } }
false
false
null
null
diff --git a/ananya-kilkari-service/src/main/java/org/motechproject/ananya/kilkari/request/CallDurationWebRequest.java b/ananya-kilkari-service/src/main/java/org/motechproject/ananya/kilkari/request/CallDurationWebRequest.java index c537df62..19236d7f 100755 --- a/ananya-kilkari-service/src/main/java/org/motechproject/ananya/kilkari/request/CallDurationWebRequest.java +++ b/ananya-kilkari-service/src/main/java/org/motechproject/ananya/kilkari/request/CallDurationWebRequest.java @@ -1,76 +1,76 @@ package org.motechproject.ananya.kilkari.request; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.codehaus.jackson.annotate.JsonProperty; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.motechproject.ananya.kilkari.obd.service.validator.Errors; import org.motechproject.ananya.kilkari.subscription.validators.ValidationUtils; import java.io.Serializable; public class CallDurationWebRequest implements Serializable { private static final long serialVersionUID = 3563680146653893106L; @JsonProperty private String startTime; @JsonProperty private String endTime; public CallDurationWebRequest() { } public CallDurationWebRequest(String startTime, String endTime) { this.startTime = startTime; this.endTime = endTime; } public String getStartTime() { return startTime; } public String getEndTime() { return endTime; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CallDurationWebRequest)) return false; CallDurationWebRequest that = (CallDurationWebRequest) o; return new EqualsBuilder() .append(this.startTime, that.startTime) .append(this.endTime, that.endTime) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder() .append(this.startTime) .append(this.endTime) .hashCode(); } public Errors validate() { Errors errors = new Errors(); boolean formatInvalid = false; if (!ValidationUtils.assertDateTimeFormat(startTime)) { errors.add(String.format("Invalid start time format %s", startTime)); formatInvalid = true; } if (!ValidationUtils.assertDateTimeFormat(endTime)) { errors.add(String.format("Invalid end time format %s", endTime)); formatInvalid = true; } - if (!formatInvalid && (!ValidationUtils.assertDateBefore(parseDateTime(startTime), parseDateTime(endTime)) || !ValidationUtils.assertDateEquals(parseDateTime(startTime), parseDateTime(endTime)))) + if (!formatInvalid && (!ValidationUtils.assertDateBefore(parseDateTime(startTime), parseDateTime(endTime)) && !ValidationUtils.assertDateEquals(parseDateTime(startTime), parseDateTime(endTime)))) errors.add(String.format("Start DateTime[%s] should not be greater than End DateTime[%s]", startTime, endTime)); return errors; } private DateTime parseDateTime(String time) { return DateTimeFormat.forPattern("dd-MM-yyyy HH-mm-ss").parseDateTime(time); } } diff --git a/ananya-kilkari-service/src/main/java/org/motechproject/ananya/kilkari/service/KilkariSubscriptionService.java b/ananya-kilkari-service/src/main/java/org/motechproject/ananya/kilkari/service/KilkariSubscriptionService.java index fd1b8776..8e8ff2cd 100755 --- a/ananya-kilkari-service/src/main/java/org/motechproject/ananya/kilkari/service/KilkariSubscriptionService.java +++ b/ananya-kilkari-service/src/main/java/org/motechproject/ananya/kilkari/service/KilkariSubscriptionService.java @@ -1,284 +1,284 @@ package org.motechproject.ananya.kilkari.service; import org.joda.time.DateTime; import org.joda.time.Minutes; import org.motechproject.ananya.kilkari.mapper.ChangeMsisdnRequestMapper; import org.motechproject.ananya.kilkari.mapper.SubscriptionRequestMapper; import org.motechproject.ananya.kilkari.message.domain.CampaignMessageAlert; import org.motechproject.ananya.kilkari.message.service.CampaignMessageAlertService; import org.motechproject.ananya.kilkari.obd.domain.Channel; import org.motechproject.ananya.kilkari.obd.domain.PhoneNumber; import org.motechproject.ananya.kilkari.obd.service.CampaignMessageService; import org.motechproject.ananya.kilkari.obd.service.validator.Errors; import org.motechproject.ananya.kilkari.request.*; import org.motechproject.ananya.kilkari.subscription.domain.CampaignChangeReason; import org.motechproject.ananya.kilkari.subscription.domain.CampaignRescheduleRequest; import org.motechproject.ananya.kilkari.subscription.domain.ChangeSubscriptionType; import org.motechproject.ananya.kilkari.subscription.domain.DeactivationRequest; import org.motechproject.ananya.kilkari.subscription.domain.Operator; import org.motechproject.ananya.kilkari.subscription.domain.SubscriberCareDoc; import org.motechproject.ananya.kilkari.subscription.domain.Subscription; import org.motechproject.ananya.kilkari.subscription.domain.SubscriptionPack; import org.motechproject.ananya.kilkari.subscription.domain.SubscriptionStatus; import org.motechproject.ananya.kilkari.subscription.exceptions.DuplicateSubscriptionException; import org.motechproject.ananya.kilkari.subscription.exceptions.ValidationException; import org.motechproject.ananya.kilkari.subscription.repository.KilkariPropertiesData; import org.motechproject.ananya.kilkari.subscription.service.ChangeSubscriptionService; import org.motechproject.ananya.kilkari.subscription.service.SubscriptionService; import org.motechproject.ananya.kilkari.subscription.service.request.ChangeMsisdnRequest; import org.motechproject.ananya.kilkari.subscription.service.request.ChangeSubscriptionRequest; import org.motechproject.ananya.kilkari.subscription.service.request.SubscriberRequest; import org.motechproject.ananya.kilkari.subscription.service.request.SubscriptionRequest; import org.motechproject.ananya.kilkari.subscription.service.response.SubscriptionDetailsResponse; import org.motechproject.ananya.kilkari.utils.CampaignMessageIdStrategy; import org.motechproject.scheduler.MotechSchedulerService; import org.omg.PortableInterceptor.ACTIVE; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.TreeSet; @Service public class KilkariSubscriptionService { private SubscriptionPublisher subscriptionPublisher; private SubscriptionService subscriptionService; private MotechSchedulerService motechSchedulerService; private KilkariPropertiesData kilkariProperties; private ChangeSubscriptionService changeSubscriptionService; private CampaignMessageAlertService campaignMessageAlertService; private CampaignMessageService campaignMessageService; private final Logger logger = LoggerFactory.getLogger(KilkariSubscriptionService.class); @Autowired public KilkariSubscriptionService(SubscriptionPublisher subscriptionPublisher, SubscriptionService subscriptionService, MotechSchedulerService motechSchedulerService, ChangeSubscriptionService changeSubscriptionService, KilkariPropertiesData kilkariProperties, CampaignMessageAlertService campaignMessageAlertService, CampaignMessageService campaignMessageService) { this.subscriptionPublisher = subscriptionPublisher; this.subscriptionService = subscriptionService; this.motechSchedulerService = motechSchedulerService; this.changeSubscriptionService = changeSubscriptionService; this.kilkariProperties = kilkariProperties; this.campaignMessageAlertService = campaignMessageAlertService; this.campaignMessageService = campaignMessageService; } public void createSubscriptionAsync(SubscriptionWebRequest subscriptionWebRequest) { subscriptionPublisher.createSubscription(subscriptionWebRequest); } public void subscriptionAsyncForReferredBy(ReferredByFlwRequest referredByFlwMsisdnRequest) { subscriptionPublisher.processReferredByFLWRequest(referredByFlwMsisdnRequest); } public void subscriptionForReferredByFLWRequest(ReferredByFlwRequest referredByFlwMsisdnRequest) { validateSetReferredByFlwMsisdnRequest(referredByFlwMsisdnRequest); String msisdn = referredByFlwMsisdnRequest.getMsisdn(); SubscriptionPack pack = referredByFlwMsisdnRequest.getPack(); Channel channel = Channel.valueOf(referredByFlwMsisdnRequest.getChannel().toUpperCase()); boolean referredBy = false; referredBy = referredByFlwMsisdnRequest.isReferredBy(); List<Subscription> subscriptionList = findByMsisdnAndPack(msisdn, pack); List<Subscription> subscriptionListForRefByStatus = findByMsisdnPackAndStatus(msisdn, pack, SubscriptionStatus.REFERRED_MSISDN_RECEIVED); Subscription subscription = subscriptionExists(subscriptionList); if(subscription!=null){//updateSubscription ChangeSubscriptionRequest changeSubscriptionRequest = new ChangeSubscriptionRequest(ChangeSubscriptionType.CHANGE_REFERRED_BY, msisdn, subscription.getSubscriptionId(), pack, channel, referredByFlwMsisdnRequest.getCreatedAt(), null, null, null,null, referredBy); subscriptionService.updateReferredByMsisdn(subscription, changeSubscriptionRequest); }else if(!subscriptionListForRefByStatus.isEmpty()){//check for already existing entries with status REFERRED_MSISDN_FLAG_RECEIVED subscription= subscriptionListForRefByStatus.get(0); subscription.setCreationDate(referredByFlwMsisdnRequest.getCreatedAt()); subscription.setStartDate(DateTime.now()); subscriptionService.updateSubscription(subscription); }else{//createNewSubscription subscription = new Subscription(msisdn, referredByFlwMsisdnRequest.getPack(), referredByFlwMsisdnRequest.getCreatedAt(), DateTime.now(), null, null, referredBy); subscription.setStatus(SubscriptionStatus.REFERRED_MSISDN_RECEIVED); subscriptionService.createEntryInCouchForReferredBy(subscription); } } private static Subscription subscriptionExists(List<Subscription> subscriptionList) { if(subscriptionList.isEmpty()) return null; TreeSet<Subscription> subscriptionTreeSet =new TreeSet<Subscription>(new SubscriptionListComparator()); subscriptionTreeSet.addAll(subscriptionList); Subscription subscription= subscriptionTreeSet.first(); if(subscription.getStatus().equals(SubscriptionStatus.ACTIVE)) return subscription; if((subscription.getStatus().equals(SubscriptionStatus.ACTIVATION_FAILED)||subscription.getStatus().equals(SubscriptionStatus.PENDING_ACTIVATION )) && shouldUpdateSubscription(subscription)) return subscription; return null; } private static boolean shouldUpdateSubscription(Subscription subscription) { if(subscription.getCreationDate()==null) return false; return !subscription.getCreationDate().isBefore(DateTime.now().minusMinutes(10)); } public void createSubscription(SubscriptionWebRequest subscriptionWebRequest) { validateSubscriptionRequest(subscriptionWebRequest); SubscriptionRequest subscriptionRequest = SubscriptionRequestMapper.mapToSubscriptionRequest(subscriptionWebRequest); try { subscriptionService.createSubscription(subscriptionRequest, Channel.from(subscriptionWebRequest.getChannel())); } catch (DuplicateSubscriptionException e) { logger.warn(String.format("Subscription for msisdn[%s] and pack[%s] already exists.", subscriptionWebRequest.getMsisdn(), subscriptionWebRequest.getPack())); } } public void updateSubscriptionForFlw(SubscriptionWebRequest subscriptionWebRequest) { validateSubscriptionRequest(subscriptionWebRequest); SubscriptionRequest subscriptionRequest = SubscriptionRequestMapper.mapToSubscriptionRequest(subscriptionWebRequest); try { subscriptionService.updateSubscriptionForFlw(subscriptionRequest, Channel.from(subscriptionWebRequest.getChannel())); } catch (DuplicateSubscriptionException e) { logger.warn(String.format("Subscription for msisdn[%s] and pack[%s] already exists.", subscriptionWebRequest.getMsisdn(), subscriptionWebRequest.getPack())); } } public void processCallbackRequest(CallbackRequestWrapper callbackRequestWrapper) { subscriptionPublisher.processCallbackRequest(callbackRequestWrapper); } public List<SubscriptionDetailsResponse> getSubscriptionDetails(String msisdn, Channel channel) { validateMsisdn(msisdn); return subscriptionService.getSubscriptionDetails(msisdn, channel); } public List<Subscription> findByMsisdn(String msisdn) { return subscriptionService.findByMsisdn(msisdn); } public List<Subscription> findByMsisdnAndPack(String msisdn, SubscriptionPack pack ) { return subscriptionService.findByMsisdnAndPack(msisdn, pack); } public List<Subscription> findByMsisdnPackAndStatus(String msisdn, SubscriptionPack pack, SubscriptionStatus status) { return subscriptionService.findByMsisdnPackAndStatus(msisdn, pack, status); } public Subscription findBySubscriptionId(String subscriptionId) { return subscriptionService.findBySubscriptionId(subscriptionId); } public void processSubscriptionCompletion(Subscription subscription, String campaignName) { String subscriptionId = subscription.getSubscriptionId(); CampaignMessageAlert campaignMessageAlert = campaignMessageAlertService.findBy(subscriptionId); boolean isRenewed = campaignMessageAlert != null && campaignMessageAlert.isRenewed(); String messageId = new CampaignMessageIdStrategy().createMessageId(campaignName, subscription.getScheduleStartDate(), subscription.getPack()); if (isRenewed || campaignMessageService.find(subscriptionId, messageId) != null) { subscriptionService.scheduleCompletion(subscription, DateTime.now()); logger.info(String.format("Scheduling completion now for %s, since already renewed for last week", subscriptionId)); return; } markCampaignCompletion(subscription); subscriptionService.scheduleCompletion(subscription, subscription.getCurrentWeeksMessageExpiryDate()); } public void requestUnsubscription(String subscriptionId, UnSubscriptionWebRequest unSubscriptionWebRequest) { Errors validationErrors = unSubscriptionWebRequest.validate(); raiseExceptionIfThereAreErrors(validationErrors); subscriptionService.requestUnsubscription(new DeactivationRequest(subscriptionId, Channel.from(unSubscriptionWebRequest.getChannel()), unSubscriptionWebRequest.getCreatedAt(), unSubscriptionWebRequest.getReason())); } public void processCampaignChange(CampaignChangeRequest campaignChangeRequest, String subscriptionId) { Errors validationErrors = campaignChangeRequest.validate(); raiseExceptionIfThereAreErrors(validationErrors); subscriptionService.rescheduleCampaign(new CampaignRescheduleRequest(subscriptionId, CampaignChangeReason.from(campaignChangeRequest.getReason()), campaignChangeRequest.getCreatedAt())); } public void updateSubscriberDetails(SubscriberWebRequest request, String subscriptionId) { Errors errors = request.validate(); raiseExceptionIfThereAreErrors(errors); SubscriberRequest subscriberRequest = SubscriptionRequestMapper.mapToSubscriberRequest(request, subscriptionId); subscriptionService.updateSubscriberDetails(subscriberRequest); } public void changeSubscription(ChangeSubscriptionWebRequest changeSubscriptionWebRequest, String subscriptionId) { Errors errors = changeSubscriptionWebRequest.validate(); raiseExceptionIfThereAreErrors(errors); ChangeSubscriptionRequest changeSubscriptionRequest = SubscriptionRequestMapper.mapToChangeSubscriptionRequest(changeSubscriptionWebRequest, subscriptionId); changeSubscriptionService.process(changeSubscriptionRequest); } public void changeMsisdn(ChangeMsisdnWebRequest changeMsisdnWebRequest) { Errors validationErrors = changeMsisdnWebRequest.validate(); raiseExceptionIfThereAreErrors(validationErrors); ChangeMsisdnRequest changeMsisdnRequest = ChangeMsisdnRequestMapper.mapFrom(changeMsisdnWebRequest); subscriptionService.changeMsisdn(changeMsisdnRequest); } private void markCampaignCompletion(Subscription subscription) { subscription.campaignCompleted(); subscriptionService.updateSubscription(subscription); } private void validateMsisdn(String msisdn) { if (PhoneNumber.isNotValid(msisdn)) throw new ValidationException(String.format("Invalid msisdn %s", msisdn)); } private void raiseExceptionIfThereAreErrors(Errors validationErrors) { if (validationErrors.hasErrors()) { throw new ValidationException(validationErrors.allMessages()); } } private void validateSubscriptionRequest(SubscriptionWebRequest subscriptionWebRequest) { Errors errors = subscriptionWebRequest.validate(); if (errors.hasErrors()) { throw new ValidationException(errors.allMessages()); } } private void validateSetReferredByFlwMsisdnRequest(ReferredByFlwRequest setReferredByFlwMsisdnRequest) { Errors errors = setReferredByFlwMsisdnRequest.validate(); if (errors.hasErrors()) { throw new ValidationException(errors.allMessages()); } } public void updateReferredByMsisdn(Subscription subscription, ChangeSubscriptionRequest changeSubscriptionRequest) { subscriptionService.updateReferredByMsisdn(subscription, changeSubscriptionRequest); } public List<Subscription> getSubscriptionsReferredByFlw(SubscriptionReferredByFlwRequest subscriptionReferredByFlwRequest) { List<Subscription> subscriptionList=fetchSubscribers(subscriptionReferredByFlwRequest); List<Subscription> activeRefbyFlwSubscriptionList=new ArrayList<Subscription>(); for (Subscription subscription : subscriptionList) { - if(subscription.getStatus().equals(SubscriptionStatus.ACTIVE)&&subscription.isReferredByFLW()){ + if(subscription.getStatus().equals(SubscriptionStatus.ACTIVE)&&subscription.isReferredByFLW()&& subscription.getReferredBy()==null){ activeRefbyFlwSubscriptionList.add(subscription); } } return activeRefbyFlwSubscriptionList; } public List<Subscription> fetchSubscribers(SubscriptionReferredByFlwRequest subscriptionReferredByFlwRequest) { return subscriptionService.getAllSortedByDate(subscriptionReferredByFlwRequest.getStartTime(), subscriptionReferredByFlwRequest.getEndTime()); } }
false
false
null
null
diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/AbstractReconciler.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/AbstractReconciler.java index e1cf5013c..46f33d253 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/AbstractReconciler.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/AbstractReconciler.java @@ -1,532 +1,544 @@ /******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jface.text.reconciler; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.text.ITextInputListener; import org.eclipse.jface.text.ITextViewer; /** * Abstract implementation of <code>IReconciler</code>. The reconciler * listens to input document changes as well as changes of * the input document of the text viewer it is installed on. Depending on * its configuration it manages the received change notifications in a * queue folding neighboring or overlapping changes together. The reconciler * processes the dirty regions as a background activity after having waited for further * changes for the configured duration of time. A reconciler is started using its * <code>install</code> method. As a first step <code>initialProcess</code> is * executed in the background. Then, the reconciling thread waits for changes that * need to be reconciled. A reconciler can be resumed by calling <code>forceReconciling</code> * independent from the existence of actual changes. This mechanism is for subclasses only. * It is the clients responsibility to stop a reconciler using its <code>uninstall</code> * method. Unstopped reconcilers do not free their resources.<p> * It is subclass responsibility to specify how dirty regions are processed. * * @see IReconciler * @see IDocumentListener * @see ITextInputListener * @see DirtyRegion * @since 2.0 */ abstract public class AbstractReconciler implements IReconciler { /** * Background thread for the reconciling activity. */ class BackgroundThread extends Thread { /** Has the reconciler been canceled. */ private boolean fCanceled= false; /** Has the reconciler been reset. */ private boolean fReset= false; /** Some changes need to be processed. */ private boolean fIsDirty= false; /** Is a reconciling strategy active. */ private boolean fIsActive= false; /** * Creates a new background thread. The thread * runs with minimal priority. * * @param name the thread's name */ public BackgroundThread(String name) { super(name); setPriority(Thread.MIN_PRIORITY); setDaemon(true); } /** * Returns whether a reconciling strategy is active right now. * * @return <code>true</code> if a activity is active */ public boolean isActive() { return fIsActive; } /** * Returns whether some changes need to be processed. * * @return <code>true</code> if changes wait to be processed */ public synchronized boolean isDirty() { return fIsDirty; } /** * Cancels the background thread. */ public void cancel() { fCanceled= true; IProgressMonitor pm= fProgressMonitor; if (pm != null) pm.setCanceled(true); synchronized (fDirtyRegionQueue) { fDirtyRegionQueue.notifyAll(); } } /** * Suspends the caller of this method until this background thread has * emptied the dirty region queue. */ public void suspendCallerWhileDirty() { boolean isDirty; do { synchronized (fDirtyRegionQueue) { isDirty= fDirtyRegionQueue.getSize() > 0; if (isDirty) { try { fDirtyRegionQueue.wait(); } catch (InterruptedException x) { } } } } while (isDirty); } /** * Reset the background thread as the text viewer has been changed, */ public void reset() { if (fDelay > 0) { synchronized (this) { fIsDirty= true; fReset= true; } } else { synchronized (this) { fIsDirty= true; } synchronized (fDirtyRegionQueue) { fDirtyRegionQueue.notifyAll(); } } reconcilerReset(); } /** * The background activity. Waits until there is something in the * queue managing the changes that have been applied to the text viewer. * Removes the first change from the queue and process it.<p> * Calls <code>initialProcess</code> on entrance. */ public void run() { synchronized (fDirtyRegionQueue) { try { fDirtyRegionQueue.wait(fDelay); } catch (InterruptedException x) { } } initialProcess(); while (!fCanceled) { synchronized (fDirtyRegionQueue) { try { fDirtyRegionQueue.wait(fDelay); } catch (InterruptedException x) { } } if (fCanceled) break; if (!isDirty()) continue; synchronized (this) { if (fReset) { fReset= false; continue; } } DirtyRegion r= null; synchronized (fDirtyRegionQueue) { r= fDirtyRegionQueue.removeNextDirtyRegion(); } fIsActive= true; if (fProgressMonitor != null) fProgressMonitor.setCanceled(false); process(r); synchronized (fDirtyRegionQueue) { if (0 == fDirtyRegionQueue.getSize()) { synchronized (this) { fIsDirty= fProgressMonitor != null ? fProgressMonitor.isCanceled() : false; } fDirtyRegionQueue.notifyAll(); } } fIsActive= false; } } } /** * Internal document listener and text input listener. */ class Listener implements IDocumentListener, ITextInputListener { /* * @see IDocumentListener#documentAboutToBeChanged(DocumentEvent) */ public void documentAboutToBeChanged(DocumentEvent e) { } /* * @see IDocumentListener#documentChanged(DocumentEvent) */ public void documentChanged(DocumentEvent e) { if (!fThread.isDirty()) aboutToBeReconciled(); if (fProgressMonitor != null && fThread.isActive()) fProgressMonitor.setCanceled(true); if (fIsIncrementalReconciler) createDirtyRegion(e); fThread.reset(); } /* * @see ITextInputListener#inputDocumentAboutToBeChanged(IDocument, IDocument) */ public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { if (oldInput == fDocument) { if (fDocument != null) fDocument.removeDocumentListener(this); if (fIsIncrementalReconciler) { fDirtyRegionQueue.purgeQueue(); if (fDocument != null && fDocument.getLength() > 0) { DocumentEvent e= new DocumentEvent(fDocument, 0, fDocument.getLength(), null); createDirtyRegion(e); fThread.reset(); fThread.suspendCallerWhileDirty(); } } fDocument= null; } } /* * @see ITextInputListener#inputDocumentChanged(IDocument, IDocument) */ public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { fDocument= newInput; if (fDocument == null) return; reconcilerDocumentChanged(fDocument); fDocument.addDocumentListener(this); if (!fThread.isDirty()) aboutToBeReconciled(); if (fIsIncrementalReconciler) { DocumentEvent e= new DocumentEvent(fDocument, 0, 0, fDocument.get()); createDirtyRegion(e); } startReconciling(); } } /** Queue to manage the changes applied to the text viewer */ private DirtyRegionQueue fDirtyRegionQueue; /** The background thread */ private BackgroundThread fThread; /** Internal document and text input listener */ private Listener fListener; /** The background thread delay */ private int fDelay= 500; /** Are there incremental reconciling strategies? */ private boolean fIsIncrementalReconciler= true; /** The progress monitor used by this reconciler */ private IProgressMonitor fProgressMonitor; /** The text viewer's document */ private IDocument fDocument; /** The text viewer */ private ITextViewer fViewer; /** * Processes a dirty region. If the dirty region is <code>null</code> the whole * document is consider being dirty. The dirty region is partitioned by the * document and each partition is handed over to a reconciling strategy registered * for the partition's content type. * * @param dirtyRegion the dirty region to be processed */ abstract protected void process(DirtyRegion dirtyRegion); /** * Hook called when the document whose contents should be reconciled * has been changed, i.e., the input document of the text viewer this * reconciler is installed on. Usually, subclasses use this hook to * inform all their reconciling strategies about the change. * * @param newDocument the new reconciler document */ abstract protected void reconcilerDocumentChanged(IDocument newDocument); /** * Creates a new reconciler without configuring it. */ protected AbstractReconciler() { super(); } /** * Tells the reconciler how long it should wait for further text changes before * activating the appropriate reconciling strategies. * * @param delay the duration in milliseconds of a change collection period. */ public void setDelay(int delay) { fDelay= delay; } /** * Tells the reconciler whether any of the available reconciling strategies * is interested in getting detailed dirty region information or just in the * fact the the document has been changed. In the second case, the reconciling * can not incrementally be pursued. * * @param isIncremental indicates whether this reconciler will be configured with * incremental reconciling strategies * * @see DirtyRegion * @see IReconcilingStrategy */ public void setIsIncrementalReconciler(boolean isIncremental) { fIsIncrementalReconciler= isIncremental; } /** * Sets the progress monitor of this reconciler. * * @param monitor the monitor to be used */ public void setProgressMonitor(IProgressMonitor monitor) { fProgressMonitor= monitor; } /** * Returns whether any of the reconciling strategies is interested in * detailed dirty region information. * * @return whether this reconciler is incremental * * @see IReconcilingStrategy */ protected boolean isIncrementalReconciler() { return fIsIncrementalReconciler; } /** * Returns the input document of the text viewer this reconciler is installed on. * * @return the reconciler document */ protected IDocument getDocument() { return fDocument; } /** * Returns the text viewer this reconciler is installed on. * * @return the text viewer this reconciler is installed on */ protected ITextViewer getTextViewer() { return fViewer; } /** * Returns the progress monitor of this reconciler. * * @return the progress monitor of this reconciler */ protected IProgressMonitor getProgressMonitor() { return fProgressMonitor; } /* * @see IReconciler#install(ITextViewer) */ public void install(ITextViewer textViewer) { Assert.isNotNull(textViewer); + synchronized (this) { + if (fThread != null) + return; + fThread= new BackgroundThread(getClass().getName()); + } fViewer= textViewer; fListener= new Listener(); fViewer.addTextInputListener(fListener); fDirtyRegionQueue= new DirtyRegionQueue(); - fThread= new BackgroundThread(getClass().getName()); } /* * @see IReconciler#uninstall() */ public void uninstall() { if (fListener != null) { fViewer.removeTextInputListener(fListener); if (fDocument != null) fDocument.removeDocumentListener(fListener); fListener= null; synchronized (this) { // http://dev.eclipse.org/bugs/show_bug.cgi?id=19135 BackgroundThread bt= fThread; fThread= null; bt.cancel(); } } } /** * Creates a dirty region for a document event and adds it to the queue. * * @param e the document event for which to create a dirty region */ private void createDirtyRegion(DocumentEvent e) { if (e.getLength() == 0 && e.getText() != null) { // Insert fDirtyRegionQueue.addDirtyRegion(new DirtyRegion(e.getOffset(), e.getText().length(), DirtyRegion.INSERT, e.getText())); } else if (e.getText() == null || e.getText().length() == 0) { // Remove fDirtyRegionQueue.addDirtyRegion(new DirtyRegion(e.getOffset(), e.getLength(), DirtyRegion.REMOVE, null)); } else { // Replace (Remove + Insert) fDirtyRegionQueue.addDirtyRegion(new DirtyRegion(e.getOffset(), e.getLength(), DirtyRegion.REMOVE, null)); fDirtyRegionQueue.addDirtyRegion(new DirtyRegion(e.getOffset(), e.getText().length(), DirtyRegion.INSERT, e.getText())); } } /** * Hook for subclasses which want to perform some * action as soon as reconciliation is needed. * <p> * Default implementation is to do nothing. * </p> * * @since 3.0 */ protected void aboutToBeReconciled() { } /** * This method is called on startup of the background activity. It is called only * once during the life time of the reconciler. Clients may reimplement this method. */ protected void initialProcess() { } /** * Forces the reconciler to reconcile the structure of the whole document. * Clients may extend this method. */ protected void forceReconciling() { if (fDocument != null) { if (fIsIncrementalReconciler) { DocumentEvent e= new DocumentEvent(fDocument, 0, fDocument.getLength(), fDocument.get()); createDirtyRegion(e); } startReconciling(); } } /** * Starts the reconciler to reconcile the queued dirty-regions. * Clients may extend this method. */ protected synchronized void startReconciling() { if (fThread == null) return; - if (!fThread.isAlive()) - fThread.start(); - else + if (!fThread.isAlive()) { + try { + fThread.start(); + } catch (IllegalThreadStateException e) { + // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=40549 + // This is the only instance where the thread is started; since + // we checked that it is not alive, it must be dead already due + // to a run-time exception or error. Exit. + } + } else { fThread.reset(); + } } /** * Hook that is called after the reconciler thread has been reset. */ protected void reconcilerReset() { } }
false
false
null
null
diff --git a/src/ru/spbau/bioinf/evalue/SquareSearch.java b/src/ru/spbau/bioinf/evalue/SquareSearch.java index 909f91a..2bc18a2 100644 --- a/src/ru/spbau/bioinf/evalue/SquareSearch.java +++ b/src/ru/spbau/bioinf/evalue/SquareSearch.java @@ -1,47 +1,47 @@ package ru.spbau.bioinf.evalue; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import ru.spbau.bioinf.tagfinder.Configuration; import ru.spbau.bioinf.tagfinder.Scan; public class SquareSearch { private static Logger log = Logger.getLogger(SquareSearch.class); public static void main(String[] args) throws Exception { Configuration conf = new Configuration(args); EValueServer.init(args); Map<Integer,Scan> scans = conf.getScans(); DbUtil.initDatabase(); Connection con = DbUtil.getConnection(); PreparedStatement ps = null; ResultSet rs = null; List<Integer> proteinIds = new ArrayList<Integer>(); try { ps = con.prepareStatement("select protein_id from t_status where evalue < 0.0024 group by protein_id order by count(*)"); rs = ps.executeQuery(); while (rs.next()) { proteinIds.add(rs.getInt(1)); } } catch (SQLException e) { log.error("Error loading proteins from database", e); throw new RuntimeException(e); } finally { DbUtil.close(con, ps, rs); } for (Integer proteinId : proteinIds) { - log.debug("Processing protein " + proteinId); + System.out.println("Processing protein " + proteinId); for (Integer scanId : scans.keySet()) { EValueServer.getEvalue(scanId, proteinId); } } } }
true
true
public static void main(String[] args) throws Exception { Configuration conf = new Configuration(args); EValueServer.init(args); Map<Integer,Scan> scans = conf.getScans(); DbUtil.initDatabase(); Connection con = DbUtil.getConnection(); PreparedStatement ps = null; ResultSet rs = null; List<Integer> proteinIds = new ArrayList<Integer>(); try { ps = con.prepareStatement("select protein_id from t_status where evalue < 0.0024 group by protein_id order by count(*)"); rs = ps.executeQuery(); while (rs.next()) { proteinIds.add(rs.getInt(1)); } } catch (SQLException e) { log.error("Error loading proteins from database", e); throw new RuntimeException(e); } finally { DbUtil.close(con, ps, rs); } for (Integer proteinId : proteinIds) { log.debug("Processing protein " + proteinId); for (Integer scanId : scans.keySet()) { EValueServer.getEvalue(scanId, proteinId); } } }
public static void main(String[] args) throws Exception { Configuration conf = new Configuration(args); EValueServer.init(args); Map<Integer,Scan> scans = conf.getScans(); DbUtil.initDatabase(); Connection con = DbUtil.getConnection(); PreparedStatement ps = null; ResultSet rs = null; List<Integer> proteinIds = new ArrayList<Integer>(); try { ps = con.prepareStatement("select protein_id from t_status where evalue < 0.0024 group by protein_id order by count(*)"); rs = ps.executeQuery(); while (rs.next()) { proteinIds.add(rs.getInt(1)); } } catch (SQLException e) { log.error("Error loading proteins from database", e); throw new RuntimeException(e); } finally { DbUtil.close(con, ps, rs); } for (Integer proteinId : proteinIds) { System.out.println("Processing protein " + proteinId); for (Integer scanId : scans.keySet()) { EValueServer.getEvalue(scanId, proteinId); } } }
diff --git a/src/main/java/com/lenis0012/bukkit/ls/LoginListener.java b/src/main/java/com/lenis0012/bukkit/ls/LoginListener.java index 77cdb01..b95f571 100644 --- a/src/main/java/com/lenis0012/bukkit/ls/LoginListener.java +++ b/src/main/java/com/lenis0012/bukkit/ls/LoginListener.java @@ -1,250 +1,250 @@ package com.lenis0012.bukkit.ls; import org.apache.commons.lang.RandomStringUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityRegainHealthEvent; import org.bukkit.event.entity.FoodLevelChangeEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.AsyncPlayerPreLoginEvent; import org.bukkit.event.player.AsyncPlayerPreLoginEvent.Result; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import com.lenis0012.bukkit.ls.util.StringUtil; public class LoginListener implements Listener { private LoginSecurity plugin; public LoginListener(LoginSecurity i) { this.plugin = i; } @EventHandler (priority = EventPriority.MONITOR) public void onPlayerJoin(PlayerJoinEvent event) { final Player player = event.getPlayer(); final String name = player.getName().toLowerCase(); - if(!name.equals(StringUtil.cleanString(name))) { + if(!player.getName().equals(StringUtil.cleanString(player.getName()))) { player.kickPlayer("Invalid username!"); return; } if(plugin.sesUse && plugin.thread.session.containsKey(name) && plugin.checkLastIp(player)) { player.sendMessage("Extended session from last login"); return; } else if(plugin.data.isRegistered(name)) { plugin.AuthList.put(name, false); if(!plugin.messager) player.sendMessage(ChatColor.RED+"Please login using /login <password>"); if(plugin.blindness) player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 1728000, 15)); } else if(plugin.required) { plugin.AuthList.put(name, true); if(!plugin.messager) player.sendMessage(ChatColor.RED+"Please register using /register <password>"); if(plugin.blindness) player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 1728000, 15)); } else return; if(plugin.timeUse) { plugin.thread.timeout.put(name, plugin.timeDelay); } //Send daat to messager API if(plugin.messager) { plugin.messaging.add(name); Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { @Override public void run() { if(plugin.messaging.contains(name)) { boolean register = plugin.AuthList.get(name); plugin.messaging.remove(name); if(register) player.sendMessage(ChatColor.RED+"Please register using /register <password>"); else player.sendMessage(ChatColor.RED+"Please login using /login <password>"); } else plugin.sendCustomPayload(player, "Q_LOGIN"); } }, 20); } } @EventHandler (priority = EventPriority.LOWEST) public void onPlayerPreLogin(AsyncPlayerPreLoginEvent event) { String name = event.getName(); //Check if the player is already online for(Player player : Bukkit.getServer().getOnlinePlayers()) { String pname = player.getName().toLowerCase(); if(plugin.AuthList.containsKey(pname)) continue; if(pname.equalsIgnoreCase(name)) { event.setLoginResult(Result.KICK_OTHER); event.setKickMessage("A player with this name is already online!"); } } } @EventHandler public void onPlayerQuit(PlayerQuitEvent event) { Player player = event.getPlayer(); String name = player.getName().toLowerCase(); String ip = player.getAddress().getAddress().toString(); if(!plugin.data.isRegistered(name)) plugin.data.updateIp(name, ip); if(plugin.sesUse && !plugin.AuthList.containsKey(name) && plugin.data.isRegistered(name)) plugin.thread.session.put(name, plugin.sesDelay); } @EventHandler public void onPlayerMove(PlayerMoveEvent event) { Player player = event.getPlayer(); String name = player.getName().toLowerCase(); if(plugin.AuthList.containsKey(name)) player.teleport(event.getFrom()); else if(player.hasPotionEffect(PotionEffectType.BLINDNESS) && plugin.blindness) player.removePotionEffect(PotionEffectType.BLINDNESS); } @EventHandler public void onBlockPlace(BlockPlaceEvent event) { Player player = event.getPlayer(); String name = player.getName().toLowerCase(); if(plugin.AuthList.containsKey(name)) event.setCancelled(true); } @EventHandler public void onBlockBreak(BlockBreakEvent event) { Player player = event.getPlayer(); String name = player.getName().toLowerCase(); if(plugin.AuthList.containsKey(name)) event.setCancelled(true); } @EventHandler public void onPlayerDropItem(PlayerDropItemEvent event) { Player player = event.getPlayer(); String name = player.getName().toLowerCase(); if(plugin.AuthList.containsKey(name)) event.setCancelled(true); } @EventHandler public void onPlayerPickupItem(PlayerPickupItemEvent event) { Player player = event.getPlayer(); String name = player.getName().toLowerCase(); if(plugin.AuthList.containsKey(name)) event.setCancelled(true); } @EventHandler public void onPlayerChat(AsyncPlayerChatEvent chat){ Player player = chat.getPlayer(); String pname = player.getName().toLowerCase(); if(plugin.AuthList.containsKey(pname)){ chat.setCancelled(true); } } @EventHandler public void OnHealthRegain(EntityRegainHealthEvent event) { Entity entity = event.getEntity(); if(!(entity instanceof Player)) return; Player player = (Player)entity; String pname = player.getName().toLowerCase(); if(plugin.AuthList.containsKey(pname)) { event.setCancelled(true); } } @EventHandler public void OnFoodLevelChange(FoodLevelChangeEvent event) { Entity entity = event.getEntity(); if(!(entity instanceof Player)) return; Player player = (Player)entity; String pname = player.getName().toLowerCase(); if(plugin.AuthList.containsKey(pname)) { event.setCancelled(true); } } @EventHandler public void onInventoryClick(InventoryClickEvent event) { Entity entity = event.getWhoClicked(); if(!(entity instanceof Player)) return; Player player = (Player)entity; String pname = player.getName().toLowerCase(); if(plugin.AuthList.containsKey(pname)) { event.setCancelled(true); } } @EventHandler public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { Entity defender = event.getEntity(); Entity damager = event.getDamager(); if(defender instanceof Player) { Player p1 = (Player) defender; String n1 = p1.getName().toLowerCase(); if(plugin.AuthList.containsKey(n1)) { event.setCancelled(true); return; } if(damager instanceof Player) { Player p2 = (Player) damager; String n2 = p2.getName().toLowerCase(); if(plugin.AuthList.containsKey(n2)) event.setCancelled(true); } } } @EventHandler(priority=EventPriority.LOWEST) public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { Player player = event.getPlayer(); String name = player.getName().toLowerCase(); if(plugin.AuthList.containsKey(name)){ if(!event.getMessage().startsWith("/login") && !event.getMessage().startsWith("/register")) { //faction fix start if(event.getMessage().startsWith("/f")) event.setMessage("/" + RandomStringUtils.randomAscii(name.length())); //this command does not exist :P //faction fix end event.setCancelled(true); } } } } \ No newline at end of file
true
false
null
null
diff --git a/src/ServiceDiscovery/ServiceDiscovery.java b/src/ServiceDiscovery/ServiceDiscovery.java index aa41fd6e..501dd109 100644 --- a/src/ServiceDiscovery/ServiceDiscovery.java +++ b/src/ServiceDiscovery/ServiceDiscovery.java @@ -1,477 +1,477 @@ /* * ServiceDiscovery.java * * Created on 4.06.2005, 21:12 * Copyright (c) 2005-2008, Eugene Stahov (evgs), http://bombus-im.org * * 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. * * You can also redistribute and/or modify this program under the * terms of the Psi License, specified in the accompanied COPYING * file, as published by the Psi Project; either dated January 1st, * 2005, 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 library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package ServiceDiscovery; //#ifndef WMUC import Conference.ConferenceForm; //#endif import images.RosterIcons; import java.util.*; import Menu.MenuCommand; import locale.SR; import Colors.ColorTheme; import ui.*; import com.alsutton.jabber.*; import com.alsutton.jabber.datablocks.*; import Client.*; import ui.MainBar; import ui.controls.AlertBox; import ui.controls.form.DefForm; import xmpp.XmppError; import xmpp.extensions.IqRegister; /** * * @author Evg_S */ public class ServiceDiscovery extends DefForm implements JabberBlockListener, ServerBox.ServiceNotify { public final static String NS_ITEMS="http://jabber.org/protocol/disco#items"; public final static String NS_INFO="http://jabber.org/protocol/disco#info"; private final static String NS_SRCH="jabber:iq:search"; private final static String NS_GATE="jabber:iq:gateway"; private final static String NS_MUC="http://jabber.org/protocol/muc"; public final static String NS_CMDS="http://jabber.org/protocol/commands"; /*private final static String strCmds="Execute"; private final int AD_HOC_INDEX=17;*/ private MenuCommand cmdBrowse=new MenuCommand(SR.MS_BROWSE, MenuCommand.OK, 1, RosterIcons.ICON_PROGRESS_INDEX); private MenuCommand cmdRfsh=new MenuCommand(SR.MS_REFRESH, MenuCommand.SCREEN, 2, RosterIcons.ICON_FT); private MenuCommand cmdFeatures=new MenuCommand(SR.MS_FEATURES, MenuCommand.SCREEN, 3, RosterIcons.ICON_VCARD); private MenuCommand cmdSrv=new MenuCommand(SR.MS_SERVER, MenuCommand.SCREEN, 10, RosterIcons.ICON_ON); //private MenuCommand cmdAdd=new MenuCommand(SR.MS_ADD_TO_ROSTER, Command.SCREEN, 11, RosterIcons.ICON_NEW); //FS#464 => this string is commented in SR.java' private MenuCommand cmdBack=new MenuCommand(SR.MS_BACK, MenuCommand.BACK, 98, RosterIcons.ICON_BACK); private Stack stackItems=new Stack(); private Vector features = new Vector(); private Vector cmds; private String service; private String node; private int discoIcon; private JabberStream stream; /** Creates a new instance of ServiceDiscovery */ public ServiceDiscovery(String service, String node, boolean search) { super(null); mainbar = new MainBar(3, null, null, false); mainbar.addRAlign(); mainbar.addElement(null); stream=sd.theStream; stream.cancelBlockListenerByClass(this.getClass()); stream.addBlockListener(this); //sd.roster.discoveryListener=this; this.node=node; enableListWrapping(true); if (service != null && search) { this.service=service; requestQuery(NS_SRCH, "discosrch"); } else if (service != null) { browse(service, node, true); } else { browse(sd.account.JID.getServer(), null, true); } } private String discoId(String id) { return id+service.hashCode(); } protected void beginPaint(){ mainbar.setElementAt(sd.roster.getEventIcon(), 4); } private void mainbarUpdate(){ mainbar.setElementAt(new Integer(discoIcon), 0); mainbar.setElementAt((service==null)?SR.MS_RECENT:service, 2); mainbar.setElementAt(sd.roster.getEventIcon(), 4); int size = itemsList.size(); String count=null; removeMenuCommand(cmdBrowse); if (size > 0) { menuCommands.insertElementAt(cmdBrowse, 0); count=" ("+size+") "; } mainbar.setElementAt(count,1); } private void requestQuery(String namespace, String id){ discoIcon=RosterIcons.ICON_PROGRESS_INDEX; mainbarUpdate(); redraw(); JabberDataBlock req=new Iq(service, Iq.TYPE_GET, discoId(id)); JabberDataBlock qry=req.addChildNs("query", namespace); qry.setAttribute("node", node); //stream.addBlockListener(this); //System.out.println(">> "+req.toString()); stream.send(req); } private void requestCommand(String namespace, String id){ discoIcon=RosterIcons.ICON_PROGRESS_INDEX; mainbarUpdate(); redraw(); JabberDataBlock req=new Iq(service, Iq.TYPE_SET, id); JabberDataBlock qry=req.addChildNs("command", namespace); qry.setAttribute("node", node); qry.setAttribute("action", "execute"); //stream.addBlockListener(this); //System.out.println(req.toString()); stream.send(req); } public int blockArrived(JabberDataBlock data) { if (!(data instanceof Iq)) return JabberBlockListener.BLOCK_REJECTED; String id=data.getAttribute("id"); if (!id.startsWith("disco")) return JabberBlockListener.BLOCK_REJECTED; if (data.getTypeAttribute().equals("error")) { //System.out.println(data.toString()); - discoIcon=RosterIcons.ICON_ERROR_INDEX; + discoIcon = RosterIcons.ICON_ERROR_INDEX; mainbarUpdate(); - //redraw(); + redraw(); /*XmppError xe=XmppError.findInStanza(data); /*new AlertBox(data.getAttribute("from"), xe.toString()) { public void yes() { }; public void no() { }; public void destroyView() {exitDiscovery(false); super.destroyView();} };*/ - // return JabberBlockListener.BLOCK_PROCESSED; + return JabberBlockListener.BLOCK_PROCESSED; } if (!data.getTypeAttribute().equals("result")) { JabberDataBlock command1 = data.getChildBlock("query"); JabberDataBlock command2 = data.getChildBlock("command"); if (command1 == null) { if (command2 != null) { command1 = command2; } String node1 = command1.getAttribute("node"); if ((node1 != null) && (node1.startsWith("http://jabber.org/protocol/rc#"))) { id = "discocmd"; //hack } node1 = null; } } JabberDataBlock query=data.getChildBlock((id.equals("discocmd"))?"command":"query"); if ((query == null) && data.getTypeAttribute().equals("result")) return BLOCK_PROCESSED; Vector childs=query.getChildBlocks(); //System.out.println(id); if (id.equals(discoId("disco2"))) { Vector items1=new Vector(); if (childs!=null) for (Enumeration e = childs.elements(); e.hasMoreElements();) { JabberDataBlock i = (JabberDataBlock) e.nextElement(); if (i.getTagName().equals("item")) { String name = i.getAttribute("name"); String jid = i.getAttribute("jid"); String node1 = i.getAttribute("node"); if (name == null) { // workaround for M-Link (jabber.org) and maybe others int resourcePos = jid.indexOf('/'); if (resourcePos > -1) { name = jid.substring(resourcePos + 1, jid.length()); } } Object serv; if (node1 == null) { int resourcePos = jid.indexOf('/'); if (resourcePos > -1) { jid = jid.substring(0, resourcePos); } serv = new DiscoContact(name, jid, 0); } else { serv = new Node(name, node1); } items1.addElement(serv); } } showResults(items1); } else if (id.equals(discoId("disco"))) { Vector cmds1=new Vector(); boolean showPartialResults=false; boolean loadItems=true; boolean client=false; if (childs!=null) { JabberDataBlock identity=query.getChildBlock("identity"); if (identity!=null) { String category=identity.getAttribute("category"); String type=identity.getTypeAttribute(); if (category.equals("automation") && type.equals("command-node")) { // cmds1.addElement(new DiscoCommand(RosterIcons.ICON_AD_HOC, strCmds)); requestCommand(NS_CMDS, "discocmd"); } if (category.equals("conference")) { cmds1.addElement(new DiscoCommand(RosterIcons.ICON_GCJOIN_INDEX, SR.MS_JOIN_CONFERENCE)); if (service.indexOf('@')<=0) { loadItems=false; showPartialResults=true; cmds1.addElement(new DiscoCommand(RosterIcons.ICON_ROOMLIST, SR.MS_LOAD_ROOMLIST)); } } } for (Enumeration e=childs.elements(); e.hasMoreElements();) { JabberDataBlock i=(JabberDataBlock)e.nextElement(); if (i.getTagName().equals("feature")) { String var=i.getAttribute("var"); features.addElement(var); //if (var.equals(NS_MUC)) { cmds.addElement(new DiscoCommand(RosterIcons.ICON_GCJOIN_INDEX, strJoin)); } if (var.equals(NS_SRCH)) { cmds1.addElement(new DiscoCommand(RosterIcons.ICON_SEARCH_INDEX, SR.MS_SEARCH)); } if (var.equals(IqRegister.NS_REGS)) { cmds1.addElement(new DiscoCommand(RosterIcons.ICON_REGISTER_INDEX, SR.MS_REGISTER)); } if (var.equals(NS_GATE)) { showPartialResults=true; } //if (var.equals(NODE_CMDS)) { cmds.addElement(new DiscoCommand(AD_HOC_INDEX,strCmds)); } } } } /*if (data.getAttribute("from").equals(service)) */ { //FIXME!!! this.cmds=cmds1; if (loadItems) requestQuery(NS_ITEMS, "disco2"); if (showPartialResults) showResults(new Vector()); } } else if (id.startsWith ("discoreg")) { discoIcon=0; new DiscoForm(this, null, null, data, stream, "discoResult", "query").fetchMediaElements(query.getChildBlocks()); } else if (id.startsWith("discocmd")) { discoIcon=0; new DiscoForm(this, null, null, data, stream, "discocmd", "command"); } else if (id.startsWith("discosrch")) { discoIcon=0; new DiscoForm(this, null, null, data, stream, "discoRSearch", "query"); } else if (id.startsWith("discoR")) { String text=SR.MS_DONE; String mb=data.getTypeAttribute(); if (mb.equals("error")) { text=XmppError.findInStanza(data).toString(); } if (text.equals(SR.MS_DONE) && id.endsWith("Search") ) { new SearchResult( data); } else { new AlertBox(mb, text) { public void yes() { } public void no() { } public void destroyView() {exitDiscovery(false); super.destroyView();} }; } } redraw(); return JabberBlockListener.BLOCK_PROCESSED; } public void eventOk() { super.eventOk(); Object o = getFocusedObject(); if (o != null) { if (o instanceof Contact) { browse(((Contact) o).jid.toString(), null, false); } if (o instanceof Node) { browse(service, ((Node) o).getNode(), false); } } } public void eventLongOk() { showMenu(); } private void showResults(final Vector items) { try { sort(items); } catch (Exception e) { } /*if (data.getAttribute("from").equals(service)) - jid hashed in id attribute*/ //{ for (Enumeration e=cmds.elements(); e.hasMoreElements();) items.insertElementAt(e.nextElement(),0); loadItemsFrom(items); moveCursorHome(); discoIcon=0; mainbarUpdate(); //} } State st=new State(); public final void browse(String service, String node, boolean start) { if (!start) { if (node == null || !node.equals(NS_CMDS)) { pushState(); } } itemsList.removeAllElements(); features.removeAllElements(); this.service = service; this.node = node; requestQuery(NS_INFO, "disco"); } void pushState() { st.cursor = cursor; st.items = new Vector(); int size = itemsList.size(); for (int i = 0; i < size; i++) { st.items.addElement(itemsList.elementAt(i)); } st.service = this.service; st.node = this.node; st.features = features; stackItems.push(st); } void popState() { st = (State) stackItems.pop(); service = st.service; node = st.node; features = st.features; itemsList.removeAllElements(); int size = st.items.size(); for (int i = 0; i < size; i++) { itemsList.addElement(st.items.elementAt(i)); } moveCursorTo(st.cursor); } public void menuAction(MenuCommand c, VirtualList d){ if (c==cmdBrowse) eventOk(); if (c==cmdBack) exitDiscovery(false); if (c==cmdRfsh) { if (service!=null) requestQuery(NS_INFO, "disco"); } if (c==cmdSrv) { new ServerBox(service, this); } if (c==cmdFeatures) { new DiscoFeatures( service, features); } if (c==cmdCancel) exitDiscovery(true); } public void exitDiscovery(boolean cancel) { if (cancel || stackItems.empty()) { stream.cancelBlockListener(this); super.destroyView(); } else { popState(); discoIcon = 0; //requestQuery(NS_INFO,"disco"); mainbarUpdate(); moveCursorTo(st.cursor); redraw(); } } public void destroyView() { exitDiscovery(false); } public void OkNotify(String selectedServer) { browse(selectedServer, null, false); } private class DiscoCommand extends IconTextElement { String name; int index; int icon; public DiscoCommand(int icon, String name) { super(RosterIcons.getInstance()); this.icon=icon; this.name=name; } public int getColor(){ return ColorTheme.getColor(ColorTheme.DISCO_CMD); } public int getImageIndex() { return icon; } public String toString(){ return name; } public void onSelect(){ switch (icon) { //#ifndef WMUC case RosterIcons.ICON_GCJOIN_INDEX: int rp=service.indexOf('@'); String room = null; if (rp > 0) { room = service.substring(0, rp); } new ConferenceForm(room, service, null, false); break; //#endif case RosterIcons.ICON_SEARCH_INDEX: requestQuery(NS_SRCH, "discosrch"); break; case RosterIcons.ICON_REGISTER_INDEX: requestQuery(IqRegister.NS_REGS, "discoreg"); break; case RosterIcons.ICON_ROOMLIST: requestQuery(NS_ITEMS, "disco2"); break; /* case RosterIcons.ICON_AD_HOC: requestCommand(NODE_CMDS, "discocmd");*/ default: } } } /*public void showMenu() { new MyMenu( this, this, SR.MS_DISCO, null, menuCommands); }*/ public void commandState() { menuCommands.removeAllElements(); addMenuCommand(cmdBrowse); addMenuCommand(cmdRfsh); addMenuCommand(cmdSrv); addMenuCommand(cmdFeatures); //addCommand(cmdAdd); addMenuCommand(cmdCancel); } } class State{ public String service; public String node; public Vector items; public Vector features; public int cursor; }
false
false
null
null
diff --git a/EclipseProject/src/weatherOracle/activity/NotificationActivity.java b/EclipseProject/src/weatherOracle/activity/NotificationActivity.java index 3689dca..a7fb90a 100644 --- a/EclipseProject/src/weatherOracle/activity/NotificationActivity.java +++ b/EclipseProject/src/weatherOracle/activity/NotificationActivity.java @@ -1,318 +1,318 @@ package weatherOracle.activity; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.TimeZone; import weatherOracle.filter.ConditionRule; import weatherOracle.filter.Filter; import weatherOracle.notification.Notification; import weatherOracle.notification.NotificationStore; import android.app.Activity; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.RelativeLayout.LayoutParams; public class NotificationActivity extends Activity { /** * List of Notifications to be displayed by this activity */ List<Notification> notificationList; LinearLayout mainView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { instance=this; super.onCreate(savedInstanceState); setContentView(R.layout.notification_activity); mainView = (LinearLayout)findViewById(R.id.notification_activity_linear_layout); populateNotificationList(); displayNotifications(); } private void updateDisplay(){ mainView.removeAllViews(); populateNotificationList(); displayNotifications(); } public void onResume() { instance=this; super.onResume(); updateDisplay(); } public void onWindowFocusChanged(boolean hasFocus){ super.onWindowFocusChanged(hasFocus); if(hasFocus) { updateDisplay(); } else { mainView.removeAllViews(); } } /** * Populate and update the notificationList Field */ private void populateNotificationList() { notificationList = NotificationStore.getNotifications(); } private void displayNotifications() { try { if(notificationList.size()==1) - statusBarNotification(R.drawable.clouds, + statusBarNotification(R.drawable.icon, notificationList.get(0).getName(), "WeatherOracle", notificationList.get(0).getName() + ". Location:" + notificationList.get(0).getFilter().getLocationName() + ". First Occur at" + notificationList.get(0).getWeatherData().get(0).getTimeString()); else if(notificationList.size()>1) - statusBarNotification(R.drawable.clouds, + statusBarNotification(R.drawable.icon, notificationList.size()+" new notifications", "WeatherOracle", notificationList.size()+" new notifications"); } catch (Exception e) { } for (int i = 0;i<notificationList.size();i++) { boolean firstIteration = false; boolean lastIteration = false; if(i == 0){ firstIteration = true; } if(i == notificationList.size() - 1){ lastIteration = true; } // parentll represents an entire on screen notification element; it's first child is // the top divider ... its next is all of the main content of the notification ... and // its third and last child is the bottom divider final LinearLayout parentll = new LinearLayout(this); parentll.setOrientation(LinearLayout.VERTICAL); // set up top divider and add to parent final View divider = new View(this); divider.setBackgroundColor(R.color.grey); LayoutParams dividerParams; if(firstIteration){ dividerParams = new LayoutParams(LayoutParams.FILL_PARENT, 2); } else { dividerParams = new LayoutParams(LayoutParams.FILL_PARENT, 1); } //dividerParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); parentll.addView(divider, dividerParams); // set up ll view that will hold main content of notification LinearLayout ll = new LinearLayout(this); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); layoutParams.setMargins(8, 4, 8, 4); parentll.addView(ll,layoutParams); // set up bottom divider and add to parent final View divider2 = new View(this); divider2.setBackgroundColor(R.color.grey); LayoutParams dividerParams2; if(lastIteration){ dividerParams2 = new LayoutParams(LayoutParams.FILL_PARENT, 2); } else { dividerParams2 = new LayoutParams(LayoutParams.FILL_PARENT, 1); } //dividerParams2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); parentll.addView(divider2, dividerParams2); RelativeLayout nameAndDetails = new RelativeLayout(this); ll.addView(nameAndDetails); // LinearLayout.LayoutParams nameParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, 50); // ll.addView(nameAndDetails, nameParams); TextView name = new TextView(getApplicationContext()); name.setText(notificationList.get(i).getName()); name.setTextSize(2,25); name.setTextColor(Color.BLACK); nameAndDetails.addView(name); ll.setOrientation(0); // ll.addView(name); final int index = i; Button internet = new Button(getApplicationContext()); internet.setGravity(Gravity.CENTER_VERTICAL); internet.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { URL url; /*url = new URL("http://forecast.weather.gov/MapClick.php?lat=" + lat + "&lon=" + lon);*/ Filter currentFilter = notificationList.get(index).getFilter(); double lat = currentFilter.getLocation().lat; double lon = currentFilter.getLocation().lon; String conditionSpecifier = ""; int timeSpecifier = 0; long timeDiff = 0; TimeZone filterTimeZone = notificationList.get(index).getWeatherData().get(0).getTimeZone(); for(ConditionRule cr : currentFilter.getConditionRules()) { if (!conditionSpecifier.contains(ConditionRule.geturlSpecifier(cr.getCondition()))) { conditionSpecifier += ConditionRule.geturlSpecifier(cr.getCondition()) + "&"; } } if (notificationList.get(index).getWeatherData() != null) { timeDiff = (notificationList.get(index).getWeatherData().get(0).getMillisTime() - Calendar.getInstance(filterTimeZone).getTimeInMillis())/(1000*3600); timeSpecifier = (int) timeDiff; if (timeSpecifier < 0) { timeSpecifier = 0; } } url = new URL("http://forecast.weather.gov/MapClick.php?" + conditionSpecifier + "&w3u=1&AheadHour=" + timeSpecifier + "&Submit=Submit&FcstType=digital&textField1=" + lat + "&textField2=" + lon + "&site=all&unit=0&dd=0&bw=0"); Log.d("NOTIFICATION ACTIVITY", "http://forecast.weather.gov/MapClick.php?" + conditionSpecifier + "&w3u=1&AheadHour=" + timeSpecifier + "&Submit=Submit&FcstType=digital&textField1=" + lat + "&textField2=" + lon + "&site=all&unit=0&dd=0&bw=0"); Intent myIntent = new Intent(v.getContext(), InternetForecast.class); myIntent.putExtra("url", url); startActivity(myIntent); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); internet.setText("Details"); if((notificationList.get(i).getName().equals("No Internet Connection") || notificationList.get(i).getName().equals("No Notification Yet")) && notificationList.get(i).getFilter() == null && notificationList.get(i).getWeatherData() == null || notificationList.get(i).getName().contains("No data at location")) { //dont add the connect to internet button } else { nameAndDetails.addView(internet); LayoutParams params = (RelativeLayout.LayoutParams)internet.getLayoutParams(); params.setMargins(0, 6, -2, 4); params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); internet.setLayoutParams(params); //causes layout update } ll.setOrientation(1); if (notificationList.get(i).getWeatherData() != null) { TextView conditionTag = new TextView(getApplicationContext()); //conditionTag.setText(); conditionTag.setText("Will First Occur on:\n\t" + notificationList.get(i).getWeatherData().get(0).getTimeString() + "\nWill Occur during:\n\t" + notificationList.get(i).getDays()); ll.addView(conditionTag); } if (notificationList.get(i).getFilter() != null) { TextView locationTag = new TextView(getApplicationContext()); String location = ""; if (notificationList.get(i).getFilter().getLocationName() != null) { location = notificationList.get(i).getFilter().getLocationName(); locationTag.setText("Location:\n\t " + location); ll.addView(locationTag); } TextView conditionTag = new TextView(getApplicationContext()); conditionTag.setText("With Condition(s):"); ll.addView(conditionTag); List<ConditionRule> conditions = new ArrayList<ConditionRule>(notificationList.get(i).getFilter().getConditionRules()); for(int j = 0 ;j < conditions.size(); j++) { TextView condition = new TextView(getApplicationContext()); condition.setText("\t" +conditions.get(j).toString()); ll.addView(condition); } } mainView.addView(parentll); } } public void statusBarNotification(int icon,CharSequence tickerText,CharSequence contentTitle,CharSequence contentText) { //Example: statusBarNotification(R.drawable.rain,"It's raining!","WeatherOracle","It's raining outside! Get me my galoshes"); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); long when = System.currentTimeMillis(); android.app.Notification notification = new android.app.Notification(icon, tickerText, when); Context context = getApplicationContext(); Intent notificationIntent = new Intent(this, HomeMenuActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); final int HELLO_ID = 1; mNotificationManager.notify(HELLO_ID, notification); } private static class Updater implements Runnable { public void run() { instance.updateDisplay(); } } private static NotificationActivity instance=null; public static void asyncUpdate(){ synchronized(instance){ instance.runOnUiThread(new Updater()); } } }
false
true
private void displayNotifications() { try { if(notificationList.size()==1) statusBarNotification(R.drawable.clouds, notificationList.get(0).getName(), "WeatherOracle", notificationList.get(0).getName() + ". Location:" + notificationList.get(0).getFilter().getLocationName() + ". First Occur at" + notificationList.get(0).getWeatherData().get(0).getTimeString()); else if(notificationList.size()>1) statusBarNotification(R.drawable.clouds, notificationList.size()+" new notifications", "WeatherOracle", notificationList.size()+" new notifications"); } catch (Exception e) { } for (int i = 0;i<notificationList.size();i++) { boolean firstIteration = false; boolean lastIteration = false; if(i == 0){ firstIteration = true; } if(i == notificationList.size() - 1){ lastIteration = true; } // parentll represents an entire on screen notification element; it's first child is // the top divider ... its next is all of the main content of the notification ... and // its third and last child is the bottom divider final LinearLayout parentll = new LinearLayout(this); parentll.setOrientation(LinearLayout.VERTICAL); // set up top divider and add to parent final View divider = new View(this); divider.setBackgroundColor(R.color.grey); LayoutParams dividerParams; if(firstIteration){ dividerParams = new LayoutParams(LayoutParams.FILL_PARENT, 2); } else { dividerParams = new LayoutParams(LayoutParams.FILL_PARENT, 1); } //dividerParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); parentll.addView(divider, dividerParams); // set up ll view that will hold main content of notification LinearLayout ll = new LinearLayout(this); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); layoutParams.setMargins(8, 4, 8, 4); parentll.addView(ll,layoutParams); // set up bottom divider and add to parent final View divider2 = new View(this); divider2.setBackgroundColor(R.color.grey); LayoutParams dividerParams2; if(lastIteration){ dividerParams2 = new LayoutParams(LayoutParams.FILL_PARENT, 2); } else { dividerParams2 = new LayoutParams(LayoutParams.FILL_PARENT, 1); } //dividerParams2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); parentll.addView(divider2, dividerParams2); RelativeLayout nameAndDetails = new RelativeLayout(this); ll.addView(nameAndDetails); // LinearLayout.LayoutParams nameParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, 50); // ll.addView(nameAndDetails, nameParams); TextView name = new TextView(getApplicationContext()); name.setText(notificationList.get(i).getName()); name.setTextSize(2,25); name.setTextColor(Color.BLACK); nameAndDetails.addView(name); ll.setOrientation(0); // ll.addView(name); final int index = i; Button internet = new Button(getApplicationContext()); internet.setGravity(Gravity.CENTER_VERTICAL); internet.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { URL url; /*url = new URL("http://forecast.weather.gov/MapClick.php?lat=" + lat + "&lon=" + lon);*/ Filter currentFilter = notificationList.get(index).getFilter(); double lat = currentFilter.getLocation().lat; double lon = currentFilter.getLocation().lon; String conditionSpecifier = ""; int timeSpecifier = 0; long timeDiff = 0; TimeZone filterTimeZone = notificationList.get(index).getWeatherData().get(0).getTimeZone(); for(ConditionRule cr : currentFilter.getConditionRules()) { if (!conditionSpecifier.contains(ConditionRule.geturlSpecifier(cr.getCondition()))) { conditionSpecifier += ConditionRule.geturlSpecifier(cr.getCondition()) + "&"; } } if (notificationList.get(index).getWeatherData() != null) { timeDiff = (notificationList.get(index).getWeatherData().get(0).getMillisTime() - Calendar.getInstance(filterTimeZone).getTimeInMillis())/(1000*3600); timeSpecifier = (int) timeDiff; if (timeSpecifier < 0) { timeSpecifier = 0; } } url = new URL("http://forecast.weather.gov/MapClick.php?" + conditionSpecifier + "&w3u=1&AheadHour=" + timeSpecifier + "&Submit=Submit&FcstType=digital&textField1=" + lat + "&textField2=" + lon + "&site=all&unit=0&dd=0&bw=0"); Log.d("NOTIFICATION ACTIVITY", "http://forecast.weather.gov/MapClick.php?" + conditionSpecifier + "&w3u=1&AheadHour=" + timeSpecifier + "&Submit=Submit&FcstType=digital&textField1=" + lat + "&textField2=" + lon + "&site=all&unit=0&dd=0&bw=0"); Intent myIntent = new Intent(v.getContext(), InternetForecast.class); myIntent.putExtra("url", url); startActivity(myIntent); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); internet.setText("Details"); if((notificationList.get(i).getName().equals("No Internet Connection") || notificationList.get(i).getName().equals("No Notification Yet")) && notificationList.get(i).getFilter() == null && notificationList.get(i).getWeatherData() == null || notificationList.get(i).getName().contains("No data at location")) { //dont add the connect to internet button } else { nameAndDetails.addView(internet); LayoutParams params = (RelativeLayout.LayoutParams)internet.getLayoutParams(); params.setMargins(0, 6, -2, 4); params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); internet.setLayoutParams(params); //causes layout update } ll.setOrientation(1); if (notificationList.get(i).getWeatherData() != null) { TextView conditionTag = new TextView(getApplicationContext()); //conditionTag.setText(); conditionTag.setText("Will First Occur on:\n\t" + notificationList.get(i).getWeatherData().get(0).getTimeString() + "\nWill Occur during:\n\t" + notificationList.get(i).getDays()); ll.addView(conditionTag); } if (notificationList.get(i).getFilter() != null) { TextView locationTag = new TextView(getApplicationContext()); String location = ""; if (notificationList.get(i).getFilter().getLocationName() != null) { location = notificationList.get(i).getFilter().getLocationName(); locationTag.setText("Location:\n\t " + location); ll.addView(locationTag); } TextView conditionTag = new TextView(getApplicationContext()); conditionTag.setText("With Condition(s):"); ll.addView(conditionTag); List<ConditionRule> conditions = new ArrayList<ConditionRule>(notificationList.get(i).getFilter().getConditionRules()); for(int j = 0 ;j < conditions.size(); j++) { TextView condition = new TextView(getApplicationContext()); condition.setText("\t" +conditions.get(j).toString()); ll.addView(condition); } } mainView.addView(parentll); } }
private void displayNotifications() { try { if(notificationList.size()==1) statusBarNotification(R.drawable.icon, notificationList.get(0).getName(), "WeatherOracle", notificationList.get(0).getName() + ". Location:" + notificationList.get(0).getFilter().getLocationName() + ". First Occur at" + notificationList.get(0).getWeatherData().get(0).getTimeString()); else if(notificationList.size()>1) statusBarNotification(R.drawable.icon, notificationList.size()+" new notifications", "WeatherOracle", notificationList.size()+" new notifications"); } catch (Exception e) { } for (int i = 0;i<notificationList.size();i++) { boolean firstIteration = false; boolean lastIteration = false; if(i == 0){ firstIteration = true; } if(i == notificationList.size() - 1){ lastIteration = true; } // parentll represents an entire on screen notification element; it's first child is // the top divider ... its next is all of the main content of the notification ... and // its third and last child is the bottom divider final LinearLayout parentll = new LinearLayout(this); parentll.setOrientation(LinearLayout.VERTICAL); // set up top divider and add to parent final View divider = new View(this); divider.setBackgroundColor(R.color.grey); LayoutParams dividerParams; if(firstIteration){ dividerParams = new LayoutParams(LayoutParams.FILL_PARENT, 2); } else { dividerParams = new LayoutParams(LayoutParams.FILL_PARENT, 1); } //dividerParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); parentll.addView(divider, dividerParams); // set up ll view that will hold main content of notification LinearLayout ll = new LinearLayout(this); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); layoutParams.setMargins(8, 4, 8, 4); parentll.addView(ll,layoutParams); // set up bottom divider and add to parent final View divider2 = new View(this); divider2.setBackgroundColor(R.color.grey); LayoutParams dividerParams2; if(lastIteration){ dividerParams2 = new LayoutParams(LayoutParams.FILL_PARENT, 2); } else { dividerParams2 = new LayoutParams(LayoutParams.FILL_PARENT, 1); } //dividerParams2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); parentll.addView(divider2, dividerParams2); RelativeLayout nameAndDetails = new RelativeLayout(this); ll.addView(nameAndDetails); // LinearLayout.LayoutParams nameParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, 50); // ll.addView(nameAndDetails, nameParams); TextView name = new TextView(getApplicationContext()); name.setText(notificationList.get(i).getName()); name.setTextSize(2,25); name.setTextColor(Color.BLACK); nameAndDetails.addView(name); ll.setOrientation(0); // ll.addView(name); final int index = i; Button internet = new Button(getApplicationContext()); internet.setGravity(Gravity.CENTER_VERTICAL); internet.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { URL url; /*url = new URL("http://forecast.weather.gov/MapClick.php?lat=" + lat + "&lon=" + lon);*/ Filter currentFilter = notificationList.get(index).getFilter(); double lat = currentFilter.getLocation().lat; double lon = currentFilter.getLocation().lon; String conditionSpecifier = ""; int timeSpecifier = 0; long timeDiff = 0; TimeZone filterTimeZone = notificationList.get(index).getWeatherData().get(0).getTimeZone(); for(ConditionRule cr : currentFilter.getConditionRules()) { if (!conditionSpecifier.contains(ConditionRule.geturlSpecifier(cr.getCondition()))) { conditionSpecifier += ConditionRule.geturlSpecifier(cr.getCondition()) + "&"; } } if (notificationList.get(index).getWeatherData() != null) { timeDiff = (notificationList.get(index).getWeatherData().get(0).getMillisTime() - Calendar.getInstance(filterTimeZone).getTimeInMillis())/(1000*3600); timeSpecifier = (int) timeDiff; if (timeSpecifier < 0) { timeSpecifier = 0; } } url = new URL("http://forecast.weather.gov/MapClick.php?" + conditionSpecifier + "&w3u=1&AheadHour=" + timeSpecifier + "&Submit=Submit&FcstType=digital&textField1=" + lat + "&textField2=" + lon + "&site=all&unit=0&dd=0&bw=0"); Log.d("NOTIFICATION ACTIVITY", "http://forecast.weather.gov/MapClick.php?" + conditionSpecifier + "&w3u=1&AheadHour=" + timeSpecifier + "&Submit=Submit&FcstType=digital&textField1=" + lat + "&textField2=" + lon + "&site=all&unit=0&dd=0&bw=0"); Intent myIntent = new Intent(v.getContext(), InternetForecast.class); myIntent.putExtra("url", url); startActivity(myIntent); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); internet.setText("Details"); if((notificationList.get(i).getName().equals("No Internet Connection") || notificationList.get(i).getName().equals("No Notification Yet")) && notificationList.get(i).getFilter() == null && notificationList.get(i).getWeatherData() == null || notificationList.get(i).getName().contains("No data at location")) { //dont add the connect to internet button } else { nameAndDetails.addView(internet); LayoutParams params = (RelativeLayout.LayoutParams)internet.getLayoutParams(); params.setMargins(0, 6, -2, 4); params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); internet.setLayoutParams(params); //causes layout update } ll.setOrientation(1); if (notificationList.get(i).getWeatherData() != null) { TextView conditionTag = new TextView(getApplicationContext()); //conditionTag.setText(); conditionTag.setText("Will First Occur on:\n\t" + notificationList.get(i).getWeatherData().get(0).getTimeString() + "\nWill Occur during:\n\t" + notificationList.get(i).getDays()); ll.addView(conditionTag); } if (notificationList.get(i).getFilter() != null) { TextView locationTag = new TextView(getApplicationContext()); String location = ""; if (notificationList.get(i).getFilter().getLocationName() != null) { location = notificationList.get(i).getFilter().getLocationName(); locationTag.setText("Location:\n\t " + location); ll.addView(locationTag); } TextView conditionTag = new TextView(getApplicationContext()); conditionTag.setText("With Condition(s):"); ll.addView(conditionTag); List<ConditionRule> conditions = new ArrayList<ConditionRule>(notificationList.get(i).getFilter().getConditionRules()); for(int j = 0 ;j < conditions.size(); j++) { TextView condition = new TextView(getApplicationContext()); condition.setText("\t" +conditions.get(j).toString()); ll.addView(condition); } } mainView.addView(parentll); } }
diff --git a/cdi/tests/org.jboss.tools.cdi.ui.test/src/org/jboss/tools/cdi/ui/test/marker/CDIMarkerResolutionTest.java b/cdi/tests/org.jboss.tools.cdi.ui.test/src/org/jboss/tools/cdi/ui/test/marker/CDIMarkerResolutionTest.java index 072f4ad00..d43d9bd3a 100644 --- a/cdi/tests/org.jboss.tools.cdi.ui.test/src/org/jboss/tools/cdi/ui/test/marker/CDIMarkerResolutionTest.java +++ b/cdi/tests/org.jboss.tools.cdi.ui.test/src/org/jboss/tools/cdi/ui/test/marker/CDIMarkerResolutionTest.java @@ -1,426 +1,448 @@ /************************************************************************************* * Copyright (c) 2008-2009 JBoss by Red Hat 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: * JBoss by Red Hat - Initial implementation. ************************************************************************************/ package org.jboss.tools.cdi.ui.test.marker; import java.io.IOException; import java.io.InputStream; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.ltk.core.refactoring.Change; import org.eclipse.ltk.core.refactoring.CompositeChange; import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry; +import org.eclipse.ltk.core.refactoring.TextFileChange; import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor; import org.eclipse.ui.IMarkerResolution; import org.eclipse.ui.ide.IDE; import org.jboss.tools.cdi.core.test.tck.validation.ValidationTest; import org.jboss.tools.cdi.internal.core.validation.CDIValidationErrorManager; import org.jboss.tools.cdi.ui.marker.AddLocalBeanMarkerResolution; import org.jboss.tools.cdi.ui.marker.DeleteAllDisposerDuplicantMarkerResolution; import org.jboss.tools.cdi.ui.marker.DeleteAllInjectedConstructorsMarkerResolution; import org.jboss.tools.cdi.ui.marker.MakeFieldStaticMarkerResolution; import org.jboss.tools.cdi.ui.marker.MakeInjectedPointUnambiguousMarkerResolution; import org.jboss.tools.cdi.ui.marker.MakeMethodBusinessMarkerResolution; import org.jboss.tools.cdi.ui.marker.MakeMethodPublicMarkerResolution; import org.jboss.tools.cdi.ui.marker.SelectBeanMarkerResolution; import org.jboss.tools.cdi.ui.marker.TestableResolutionWithRefactoringProcessor; import org.jboss.tools.cdi.ui.marker.TestableResolutionWithSelectionWizard; +import org.jboss.tools.common.EclipseUtil; import org.jboss.tools.common.util.FileUtil; import org.jboss.tools.test.util.JobUtils; /** * @author Daniel Azarov * */ public class CDIMarkerResolutionTest extends ValidationTest { public static final String MARKER_TYPE = "org.jboss.tools.cdi.core.cdiproblem"; private void checkResolution(IProject project, String[] fileNames, String markerType, String idName, int id, Class<? extends IMarkerResolution> resolutionClass) throws CoreException { checkResolution(project, fileNames, new String[]{}, markerType, idName, id, resolutionClass); } private void checkResolution(IProject project, String[] fileNames, String[] results, String markerType, String idName, int id, Class<? extends IMarkerResolution> resolutionClass) throws CoreException { IFile file = project.getFile(fileNames[0]); assertTrue("File - "+file.getFullPath()+" must be exist",file.exists()); copyFiles(project, fileNames); try{ IMarker[] markers = file.findMarkers(markerType, true, IResource.DEPTH_INFINITE); for (int i = 0; i < markers.length; i++) { IMarker marker = markers[i]; Integer attribute = ((Integer) marker .getAttribute(CDIValidationErrorManager.MESSAGE_ID_ATTRIBUTE_NAME)); if (attribute != null){ int messageId = attribute.intValue(); if(messageId == id){ + String text = (String)marker.getAttribute(IMarker.MESSAGE,"none"); + System.out.println("Before quick fix: "+text); + IMarkerResolution[] resolutions = IDE.getMarkerHelpRegistry() .getResolutions(marker); for (int j = 0; j < resolutions.length; j++) { IMarkerResolution resolution = resolutions[j]; if (resolution.getClass().equals(resolutionClass)) { if(resolution instanceof TestableResolutionWithRefactoringProcessor){ RefactoringProcessor processor = ((TestableResolutionWithRefactoringProcessor)resolution).getRefactoringProcessor(); RefactoringStatus status = processor.checkInitialConditions(new NullProgressMonitor()); // RefactoringStatusEntry[] entries = status.getEntries(); // for(RefactoringStatusEntry entry : entries){ // System.out.println("Refactor status - "+entry.getMessage()); // } assertNull("Rename processor returns fatal error", status.getEntryMatchingSeverity(RefactoringStatus.FATAL)); status = processor.checkFinalConditions(new NullProgressMonitor(), null); // entries = status.getEntries(); // for(RefactoringStatusEntry entry : entries){ // System.out.println("Refactor status - "+entry.getMessage()); // } assertNull("Rename processor returns fatal error", status.getEntryMatchingSeverity(RefactoringStatus.FATAL)); CompositeChange rootChange = (CompositeChange)processor.createChange(new NullProgressMonitor()); - rootChange.perform(new NullProgressMonitor()); + for(Change change : rootChange.getChildren()){ + if(change instanceof TextFileChange){ + IFile cFile = ((TextFileChange)change).getFile(); + ICompilationUnit cUnit = EclipseUtil.getCompilationUnit(cFile); + ICompilationUnit compilationUnit = cUnit.getWorkingCopy(new NullProgressMonitor()); + + compilationUnit.applyTextEdit(((TextFileChange)change).getEdit(), new NullProgressMonitor()); + + compilationUnit.commitWorkingCopy(false, new NullProgressMonitor()); + compilationUnit.discardWorkingCopy(); + } + } + + //rootChange.perform(new NullProgressMonitor()); }else if(resolution instanceof TestableResolutionWithSelectionWizard){ ((TestableResolutionWithSelectionWizard)resolution).selectFirstElementAndRun(marker); }else{ resolution.run(marker); } refresh(project); IMarker[] newMarkers = file.findMarkers(markerType, true, IResource.DEPTH_INFINITE); System.out.println("Before: "+markers.length+" after: "+newMarkers.length); + + for(IMarker m : newMarkers){ - String text = (String)m.getAttribute(IMarker.TEXT,"none"); + text = (String)m.getAttribute(IMarker.MESSAGE,"none"); System.out.println("After quick fix: "+text); } assertTrue("Marker resolution did not decrease number of problems. was: "+markers.length+" now: "+newMarkers.length, newMarkers.length < markers.length); checkResults(project, fileNames, results); return; } } fail("Marker resolution: "+resolutionClass+" not found"); } } } fail("Problem marker with id: "+id+" not found"); }finally{ restoreFiles(project, fileNames); refresh(project); } } private void refresh(IProject project) throws CoreException{ project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); JobUtils.waitForIdle(); project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, null); JobUtils.waitForIdle(); } private void copyFiles(IProject project, String[] fileNames) throws CoreException{ for(String fileName : fileNames){ IFile file = project.getFile(fileName); IFile copyFile = project.getFile(fileName+".copy"); if(copyFile.exists()) copyFile.delete(true, null); InputStream is = null; try{ is = file.getContents(); copyFile.create(is, true, null); } finally { if(is!=null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } } private void restoreFiles(IProject project, String[] fileNames) throws CoreException { for(String fileName : fileNames){ IFile file = project.getFile(fileName); IFile copyFile = project.getFile(fileName+".copy"); InputStream is = null; try{ is = copyFile.getContents(); file.setContents(is, true, false, null); } finally { if(is!=null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } copyFile.delete(true, null); } } private void checkResults(IProject project, String[] fileNames, String[] results) throws CoreException{ for(int i = 0; i < results.length; i++){ IFile file = project.getFile(fileNames[i]); IFile resultFile = project.getFile(results[i]); String fileContent = FileUtil.readStream(file); String resultContent = FileUtil.readStream(resultFile); assertEquals("Wrong result of resolution", resultContent, fileContent); } } public void testMakeProducerFieldStaticResolution() throws CoreException { checkResolution(tckProject, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/NonStaticProducerOfSessionBeanBroken.java" }, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/NonStaticProducerOfSessionBeanBroken.qfxresult" }, MARKER_TYPE, CDIValidationErrorManager.MESSAGE_ID_ATTRIBUTE_NAME, CDIValidationErrorManager.ILLEGAL_PRODUCER_FIELD_IN_SESSION_BEAN_ID, MakeFieldStaticMarkerResolution.class); } public void testMakeProducerMethodBusinessResolution() throws CoreException { checkResolution( tckProject, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/FooProducer.java", "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/FooProducerLocal.java" }, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/FooProducer1.qfxresult", "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/FooProducerLocal.qfxresult" }, MARKER_TYPE, CDIValidationErrorManager.MESSAGE_ID_ATTRIBUTE_NAME, CDIValidationErrorManager.ILLEGAL_PRODUCER_METHOD_IN_SESSION_BEAN_ID, MakeMethodBusinessMarkerResolution.class); } public void testAddLocalBeanResolution() throws CoreException { checkResolution( tckProject, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/FooProducer.java" }, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/FooProducer2.qfxresult", }, MARKER_TYPE, CDIValidationErrorManager.MESSAGE_ID_ATTRIBUTE_NAME, CDIValidationErrorManager.ILLEGAL_PRODUCER_METHOD_IN_SESSION_BEAN_ID, AddLocalBeanMarkerResolution.class); } public void testMakeProducerMethodPublicResolution() throws CoreException { checkResolution(tckProject, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/FooProducerNoInterface.java" }, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/FooProducerNoInterface.qfxresult" }, MARKER_TYPE, CDIValidationErrorManager.MESSAGE_ID_ATTRIBUTE_NAME, CDIValidationErrorManager.ILLEGAL_PRODUCER_METHOD_IN_SESSION_BEAN_ID, MakeMethodPublicMarkerResolution.class); } public void testMakeObserverParamMethodBusinessResolution() throws CoreException { checkResolution(tckProject, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/TibetanTerrier_Broken.java", "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/Terrier.java" }, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/TibetanTerrier_Broken1.qfxresult", "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/Terrier.qfxresult" }, MARKER_TYPE, CDIValidationErrorManager.MESSAGE_ID_ATTRIBUTE_NAME, CDIValidationErrorManager.ILLEGAL_OBSERVER_IN_SESSION_BEAN_ID, MakeMethodBusinessMarkerResolution.class); } public void testAddLocalBeanResolution2() throws CoreException { checkResolution(tckProject, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/TibetanTerrier_Broken.java" }, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/TibetanTerrier_Broken2.qfxresult" }, MARKER_TYPE, CDIValidationErrorManager.MESSAGE_ID_ATTRIBUTE_NAME, CDIValidationErrorManager.ILLEGAL_OBSERVER_IN_SESSION_BEAN_ID, AddLocalBeanMarkerResolution.class); } public void testMakeObserverParamMethodPublicResolution() throws CoreException { checkResolution(tckProject, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/TibetanTerrier_BrokenNoInterface.java" }, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/TibetanTerrier_BrokenNoInterface.qfxresult" }, MARKER_TYPE, CDIValidationErrorManager.MESSAGE_ID_ATTRIBUTE_NAME, CDIValidationErrorManager.ILLEGAL_OBSERVER_IN_SESSION_BEAN_ID, MakeMethodPublicMarkerResolution.class); } public void testMakeDisposerParamMethodBusinessResolution() throws CoreException { checkResolution(tckProject, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/NotBusinessMethod_Broken.java", "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/LocalInt.java" }, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/NotBusinessMethod_Broken1.qfxresult", "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/LocalInt.qfxresult" }, MARKER_TYPE, CDIValidationErrorManager.MESSAGE_ID_ATTRIBUTE_NAME, CDIValidationErrorManager.ILLEGAL_DISPOSER_IN_SESSION_BEAN_ID, MakeMethodBusinessMarkerResolution.class); } public void testAddLocalBeanResolution3() throws CoreException { checkResolution(tckProject, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/NotBusinessMethod_Broken.java" }, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/NotBusinessMethod_Broken2.qfxresult" }, MARKER_TYPE, CDIValidationErrorManager.MESSAGE_ID_ATTRIBUTE_NAME, CDIValidationErrorManager.ILLEGAL_DISPOSER_IN_SESSION_BEAN_ID, AddLocalBeanMarkerResolution.class); } public void testMakeDisposerParamMethodPublicResolution() throws CoreException { checkResolution(tckProject, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/NotBusinessMethod_BrokenNoInterface.java" }, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/NotBusinessMethod_BrokenNoInterface.qfxresult" }, MARKER_TYPE, CDIValidationErrorManager.MESSAGE_ID_ATTRIBUTE_NAME, CDIValidationErrorManager.ILLEGAL_DISPOSER_IN_SESSION_BEAN_ID, MakeMethodPublicMarkerResolution.class); } public void testDeleteAllDisposerDuplicantsResolution() throws CoreException { checkResolution(tckProject, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/TimestampLogger_Broken.java" }, // new String[]{ // "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/TimestampLogger_Broken.qfxresult" // }, MARKER_TYPE, CDIValidationErrorManager.MESSAGE_ID_ATTRIBUTE_NAME, CDIValidationErrorManager.MULTIPLE_DISPOSERS_FOR_PRODUCER_ID, DeleteAllDisposerDuplicantMarkerResolution.class); } public void testDeleteAllInjectedConstructorsResolution() throws CoreException { checkResolution(tckProject, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/Goose_Broken.java" }, // new String[]{ // "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/Goose_Broken.qfxresult" // }, MARKER_TYPE, CDIValidationErrorManager.MESSAGE_ID_ATTRIBUTE_NAME, CDIValidationErrorManager.MULTIPLE_INJECTION_CONSTRUCTORS_ID, DeleteAllInjectedConstructorsMarkerResolution.class); } public void testMakeInjectedPointUnambiguousResolution() throws CoreException { checkResolution(tckProject, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/Farm_Broken1.java" }, MARKER_TYPE, CDIValidationErrorManager.MESSAGE_ID_ATTRIBUTE_NAME, CDIValidationErrorManager.AMBIGUOUS_INJECTION_POINTS_ID, MakeInjectedPointUnambiguousMarkerResolution.class); } public void testSelectBeanResolution() throws CoreException { checkResolution(tckProject, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/Office_Broken1.java" }, MARKER_TYPE, CDIValidationErrorManager.MESSAGE_ID_ATTRIBUTE_NAME, CDIValidationErrorManager.AMBIGUOUS_INJECTION_POINTS_ID, SelectBeanMarkerResolution.class); } public void testMakeInjectedPointUnambiguousResolution2() throws CoreException { checkResolution(tckProject, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/Farm_Broken2.java" }, MARKER_TYPE, CDIValidationErrorManager.MESSAGE_ID_ATTRIBUTE_NAME, CDIValidationErrorManager.UNSATISFIED_INJECTION_POINTS_ID, MakeInjectedPointUnambiguousMarkerResolution.class); } public void testSelectBeanResolution2() throws CoreException { checkResolution(tckProject, new String[]{ "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/Office_Broken2.java" }, MARKER_TYPE, CDIValidationErrorManager.MESSAGE_ID_ATTRIBUTE_NAME, CDIValidationErrorManager.UNSATISFIED_INJECTION_POINTS_ID, SelectBeanMarkerResolution.class); } }
false
false
null
null
diff --git a/tapestry-core/src/main/java/org/apache/tapestry5/services/ComponentInstanceOperation.java b/tapestry-core/src/main/java/org/apache/tapestry5/services/ComponentInstanceOperation.java index c2a944518..50504a789 100644 --- a/tapestry-core/src/main/java/org/apache/tapestry5/services/ComponentInstanceOperation.java +++ b/tapestry-core/src/main/java/org/apache/tapestry5/services/ComponentInstanceOperation.java @@ -1,31 +1,31 @@ // Copyright 2010 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.tapestry5.services; import org.apache.tapestry5.runtime.Component; /** * An operation that requires an instance of a component. * This is a simpler alternative to a {@link ComponentMethodAdvice}. * * @since 5.2.0 * @see TransformMethod#addOperationAfter(ComponentInstanceOperation) * @see TransformMethod#addOperationBefore(ComponentInstanceOperation) */ public interface ComponentInstanceOperation { - /** Called to preform the desired operation on a component instance. */ + /** Called to perform the desired operation on a component instance. */ public void invoke(Component instance); }
true
false
null
null