answer stringlengths 17 10.2M |
|---|
package com.hockeyhurd.mod;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.Item.ToolMaterial;
import net.minecraft.item.ItemArmor.ArmorMaterial;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.EnumHelper;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapedOreRecipe;
import com.hockeyhurd.block.BlockGlowIngot;
import com.hockeyhurd.block.BlockGlowRock;
import com.hockeyhurd.block.BlockGlowTorch;
import com.hockeyhurd.block.machines.BlockGlowFurnace;
import com.hockeyhurd.block.ores.BlockGlowOre;
import com.hockeyhurd.creativetab.MyCreativeTab;
import com.hockeyhurd.entity.tileentity.TileEntityGlowFurnace;
import com.hockeyhurd.gui.GuiHandlerGlowFurnace;
import com.hockeyhurd.handler.ConfigHandler;
import com.hockeyhurd.handler.EventHookContainer;
import com.hockeyhurd.handler.FuelHandler;
import com.hockeyhurd.item.ItemDiamondFusedNetherStar;
import com.hockeyhurd.item.ItemDiamondSacrifice;
import com.hockeyhurd.item.ItemGlowCoal;
import com.hockeyhurd.item.ItemGlowDust;
import com.hockeyhurd.item.ItemGlowIngot;
import com.hockeyhurd.item.ItemHockeyPuck;
import com.hockeyhurd.item.ItemNetherSoulCollector;
import com.hockeyhurd.item.ItemNetherStarFirery;
import com.hockeyhurd.item.ItemRubber;
import com.hockeyhurd.item.armor.ArmorSetGlow;
import com.hockeyhurd.item.tool.ItemDiamondDetector;
import com.hockeyhurd.item.tool.ItemGlowAxe;
import com.hockeyhurd.item.tool.ItemGlowExcavator;
import com.hockeyhurd.item.tool.ItemGlowHammer;
import com.hockeyhurd.item.tool.ItemGlowHoe;
import com.hockeyhurd.item.tool.ItemGlowPickaxe;
import com.hockeyhurd.item.tool.ItemGlowShovel;
import com.hockeyhurd.item.tool.ItemGlowSword;
import com.hockeyhurd.item.tool.ItemHockeyStick;
import com.hockeyhurd.item.tool.ItemItemReplacer;
import com.hockeyhurd.worldgen.OreGlowWorldgen;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;
@Mod(modid = "ExtraTools+", name = "ExtraTools+", version = "v0.1.6")
public class ExtraTools {
@SidedProxy(clientSide = "com.hockeyhurd.mod.ClientProxy", serverSide = "com.hockeyhurd.mod.CommonProxy")
public static CommonProxy proxy;
public static GuiHandlerGlowFurnace guiHandler;
@Instance("ExtraTools+")
public static ExtraTools instance;
public static String modPrefix = "extratools:";
public static ConfigHandler ch;
// Blocks
public static Block glowRock;
public static Block glowTorch;
public static Block glowIngotBlock;
// Machines
public static Block glowFurnaceOff;
public static Block glowFurnaceOn;
// Gui stuff
public static final int guiIDGlowFurnace = 0;
// Ores
public static Block glowOre;
// World generation.
public static OreGlowWorldgen worldgenGlowOre = new OreGlowWorldgen();
// Items
public static Item glowDust;
public static Item glowIngot;
public static Item diamondFusedNetherStar;
public static Item netherSoulCollector;
public static Item fireryNetherStar;
public static Item diamondSacrifice;
public static Item glowCoal;
public static Item hockeyPuck;
public static Item rubber;
// Tool materials.
public static ToolMaterial toolGlow = EnumHelper.addToolMaterial("GLOW", 3, 2000, 10.0f, 5.0f, 30);
public static ToolMaterial toolGlowUnbreakable = EnumHelper.addToolMaterial("GLOWUNBREAKING", 3, -1, 10.0f, 5.0f, 30);
public static ToolMaterial toolHockey = EnumHelper.addToolMaterial("HOCKEY", 3, 500, 10.0f, 2.0f, 30);
// Tool sets
public static Item glowPickaxeUnbreakable;
public static Item glowHoeUnbreakable;
public static Item glowSwordUnbreakable;
public static Item glowAxeUnbreakable;
public static Item glowShovelUnbreakable;
public static Item glowHammerUnbreakable;
public static Item glowExcavatorUnbreakable;
public static Item hockeyStick;
public static Item diamondDetector;
public static Item itemReplacer;
// Armor materials.
public static ArmorMaterial glowArmorMat = EnumHelper.addArmorMaterial("GLOWARMOR", 100, new int[] {
3, 8, 6, 3
}, 25);
// Armor sets.
public static Item glowHelmet;
public static Item glowChestplate;
public static Item glowLegging;
public static Item glowBoot;
// Creative Tabs
public static CreativeTabs myCreativeTab = new MyCreativeTab(CreativeTabs.getNextID(), "ExtraTools+");
@EventHandler
public void preInit(FMLPreInitializationEvent event) {
ch = new ConfigHandler(event);
ch.handleConfiguration();
}
@EventHandler
public void load(FMLInitializationEvent event) {
proxy.registerRenderInformation();
loadObj();
init();
}
private void loadObj() {
// Blocks
glowRock = new BlockGlowRock(Material.glass);
glowTorch = new BlockGlowTorch();
glowIngotBlock = new BlockGlowIngot(Material.rock);
// Machines
glowFurnaceOff = new BlockGlowFurnace(Material.rock, false);
glowFurnaceOn = new BlockGlowFurnace(Material.rock, true);
// Ores
glowOre = new BlockGlowOre(Material.rock);
// Items
glowDust = new ItemGlowDust();
glowIngot = new ItemGlowIngot();
diamondFusedNetherStar = new ItemDiamondFusedNetherStar();
netherSoulCollector = new ItemNetherSoulCollector(false);
fireryNetherStar = new ItemNetherStarFirery();
diamondSacrifice = new ItemDiamondSacrifice();
glowCoal = new ItemGlowCoal();
rubber = new ItemRubber();
hockeyPuck = new ItemHockeyPuck();
// Tool sets
glowPickaxeUnbreakable = new ItemGlowPickaxe(toolGlowUnbreakable);
glowHoeUnbreakable = new ItemGlowHoe(toolGlowUnbreakable);
glowSwordUnbreakable = new ItemGlowSword(toolGlowUnbreakable);
glowAxeUnbreakable = new ItemGlowAxe(toolGlowUnbreakable);
glowShovelUnbreakable = new ItemGlowShovel(toolGlowUnbreakable);
glowHammerUnbreakable = new ItemGlowHammer(toolGlowUnbreakable);
glowExcavatorUnbreakable = new ItemGlowExcavator(toolGlowUnbreakable);
hockeyStick = new ItemHockeyStick(toolHockey);
diamondDetector = new ItemDiamondDetector();
itemReplacer = new ItemItemReplacer();
// Armor sets.
glowHelmet = new ArmorSetGlow(glowArmorMat, 0, 0, "Glow", 0).setUnlocalizedName("GlowHelm");
glowChestplate = new ArmorSetGlow(glowArmorMat, 0, 1, "Glow", 1).setUnlocalizedName("GlowChestplate");
glowLegging = new ArmorSetGlow(glowArmorMat, 0, 2, "Glow", 2).setUnlocalizedName("GlowLeggings");
glowBoot = new ArmorSetGlow(glowArmorMat, 0, 3, "Glow", 3).setUnlocalizedName("GlowBoots");
}
public ExtraTools() {
}
// Handlers all init of blocks, items, etc.
private void init() {
registerEventHandlers();
registerWorldgen();
registerBlocks();
registerItems();
addOreDict();
addFuelRegister();
addLocalizedNames();
addCraftingRecipes();
addFurnaceRecipes();
// if (Loader.isModLoaded("ThermalExpansion")) pulverizeRecipes();
registerTileEntities();
registerGuiHandler();
}
private void registerEventHandlers() {
MinecraftForge.EVENT_BUS.register(new EventHookContainer());
}
private void registerWorldgen() {
GameRegistry.registerWorldGenerator(worldgenGlowOre, 1);
}
private void registerBlocks() {
GameRegistry.registerBlock(glowRock, "GlowRock");
GameRegistry.registerBlock(glowOre, "GlowOre");
GameRegistry.registerBlock(glowTorch, "GlowTorchOn");
GameRegistry.registerBlock(glowIngotBlock, "GlowIngotBlock");
GameRegistry.registerBlock(glowFurnaceOff, "GlowFurnaceOff");
GameRegistry.registerBlock(glowFurnaceOn, "GlowFurnaceOn");
}
private void registerItems() {
GameRegistry.registerItem(glowIngot, "GlowIngot");
GameRegistry.registerItem(glowDust, "Glow Dust");
GameRegistry.registerItem(diamondFusedNetherStar, "DiamondFusedNetherStar");
GameRegistry.registerItem(netherSoulCollector, "NetherSoulCollector");
GameRegistry.registerItem(fireryNetherStar, "FireryNetherStar");
GameRegistry.registerItem(diamondSacrifice, "Sacriment to The Nether");
GameRegistry.registerItem(glowCoal, "GlowCoal");
GameRegistry.registerItem(hockeyPuck, "HockeyPuck");
GameRegistry.registerItem(rubber, "Rubber");
GameRegistry.registerItem(glowPickaxeUnbreakable, "GlowPickaxeUnbreakable");
GameRegistry.registerItem(glowHoeUnbreakable, "GlowHoeUnbreakable");
GameRegistry.registerItem(glowSwordUnbreakable, "GlowSwordUnbreakable");
GameRegistry.registerItem(glowAxeUnbreakable, "GlowAxeUnbreakable");
GameRegistry.registerItem(glowShovelUnbreakable, "GlowShovelUnbreakable");
GameRegistry.registerItem(glowHammerUnbreakable, "GlowHammerUnbreakable");
GameRegistry.registerItem(glowExcavatorUnbreakable, "GlowExcavatorUnbreakable");
GameRegistry.registerItem(hockeyStick, "HockeyStick");
GameRegistry.registerItem(diamondDetector, "DiamondDetector");
GameRegistry.registerItem(itemReplacer, "ItemReplacer");
GameRegistry.registerItem(glowHelmet, "GlowHelmet");
GameRegistry.registerItem(glowChestplate, "GlowChestplate");
GameRegistry.registerItem(glowLegging, "GlowLegging");
GameRegistry.registerItem(glowBoot, "GlowBoot");
}
private void addOreDict() {
OreDictionary.registerOre("oreGlow", glowOre);
OreDictionary.registerOre("dustGlow", glowDust);
OreDictionary.registerOre("ingotGlow", glowIngot);
OreDictionary.registerOre("oreGlowCoal", glowCoal);
OreDictionary.registerOre("itemRubber", rubber);
}
private void addFuelRegister() {
GameRegistry.registerFuelHandler(new FuelHandler());
}
private void addLocalizedNames() {
// Blocks
LanguageRegistry.addName(glowRock, "Glow Rock");
LanguageRegistry.addName(glowOre, "Glow Ore");
LanguageRegistry.addName(glowTorch, "Glow Torch");
LanguageRegistry.addName(glowIngotBlock, "Block of Glow'");
// Machines
LanguageRegistry.addName(glowFurnaceOff, "Glow Furnace");
LanguageRegistry.addName(glowFurnaceOn, "Glow Furnace");
// Items
LanguageRegistry.addName(glowDust, "Glow Dust");
LanguageRegistry.addName(diamondFusedNetherStar, "Encaptured Soul of The Nether");
LanguageRegistry.addName(glowIngot, "Glow Ingot");
LanguageRegistry.addName(netherSoulCollector, "Soul Collector of The Nether");
LanguageRegistry.addName(glowCoal, "Glow Coal");
LanguageRegistry.addName(rubber, "Rubber");
LanguageRegistry.addName(hockeyPuck, "Hockey Puck");
LanguageRegistry.addName(fireryNetherStar, "Enflamed Star of The Nether");
LanguageRegistry.addName(diamondDetector, "Diamond Detector");
LanguageRegistry.addName(diamondSacrifice, "Sacriment to The Nether!");
// Other tools
LanguageRegistry.addName(hockeyStick, "Hockey Stick");
LanguageRegistry.addName(itemReplacer, "Wand of Soul Replacement");
// Glow Toolset
LanguageRegistry.addName(glowPickaxeUnbreakable, "Pickaxe of The Lost Souls");
LanguageRegistry.addName(glowShovelUnbreakable, "Glow Shovel");
LanguageRegistry.addName(glowHoeUnbreakable, "Glow Hoe");
LanguageRegistry.addName(glowAxeUnbreakable, "Glow Axe");
LanguageRegistry.addName(glowSwordUnbreakable, "Glow Sword");
LanguageRegistry.addName(glowHammerUnbreakable, "Glow Hammer");
LanguageRegistry.addName(glowExcavatorUnbreakable, "Glow Excavator");
// Glow Armor set
LanguageRegistry.addName(glowHelmet, "Glow Helmet");
LanguageRegistry.addName(glowChestplate, "Glow Chestplate");
LanguageRegistry.addName(glowLegging, "Glow Leggings");
LanguageRegistry.addName(glowBoot, "Glow Boots");
}
private void addCraftingRecipes() {
// General purpose items.
final String STICK = "stickWood";
// Glow rock recipe, similar to that of glowstone.
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(glowRock, 1), "xx", "xx", 'x', "dustGlow"));
// Glow ingot recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(glowIngot, 1), "xy", 'x', "ingotGold", 'y', glowDust));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(glowIngot, 1), new Object[] {
"xyy", "yyy", "yyy", 'x', glowDust, 'y', "ingotIron"
}));
GameRegistry.addRecipe(new ItemStack(glowIngot, 9), "x", 'x', glowIngotBlock);
// Crafting the GlowIngotBlock
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(glowIngotBlock, 1), new Object[] {
"xxx", "xxx", "xxx", 'x', "ingotGlow"
}));
// Crafting the glow furnace
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(glowFurnaceOff, 1), new Object[] {
" x ", "x x", "xyx", 'x', "ingotGlow", 'y', Blocks.furnace
}));
// Nether Start Firery
GameRegistry.addRecipe(new ItemStack(fireryNetherStar, 1), new Object[] {
"xyx", "yzy", "xyx", 'x', Blocks.nether_brick, 'y', glowIngot, 'z', Items.nether_star
});
GameRegistry.addRecipe(new ItemStack(fireryNetherStar, 1), new Object[] {
"xxx", "xyx", "xxx", 'x', diamondSacrifice, 'y', Blocks.redstone_block
});
// DiamondNetherStarIngot recipe
GameRegistry.addRecipe(new ItemStack(diamondFusedNetherStar, 1), new Object[] {
"xyx", "yzy", "xyx", 'x', Items.diamond, 'y', glowIngot, 'z', fireryNetherStar
});
// Crafting the NetherSoulCollector
GameRegistry.addRecipe(new ItemStack(netherSoulCollector, 1), new Object[] {
"xyx", "yzy", "xyx", 'x', glowIngot, 'y', Items.gold_ingot, 'z', diamondFusedNetherStar
});
// Crafting the 'Black Diamond'
GameRegistry.addRecipe(new ItemStack(diamondSacrifice, 1), new Object[] {
"xyx", "yzy", "xyx", 'x', Blocks.nether_brick, 'y', Items.diamond, 'z', Items.blaze_rod
});
// Crafting the ItemReplacer Tool
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(itemReplacer, 1), new Object[] {
" xy", " zx", "z ", 'x', "dyeBlue", 'y', fireryNetherStar, 'z', STICK
}));
// Crafting the glow coal
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(glowCoal, 1), new Object[] {
" x ", "xyx", " x ", 'x', glowDust, 'y', "coal"
}));
// Crafting the hockey stick
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(hockeyStick, 1), new Object[] {
" wx", " wx", "yxw", 'w', "itemRubber", 'x', STICK, 'y', Items.string
}));
// Crafting the hockey puck.
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(hockeyPuck, 4), new Object[] {
"xy", 'x', "itemRubber", 'y', "coal"
}));
// Crafting the DiamondDetector
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(diamondDetector, 1), new Object[] {
" x ", "xyx", " x ", 'x', "ingotGlow", 'y', Items.diamond
}));
// Craft the pick
ItemStack pick = new ItemStack(glowPickaxeUnbreakable, 1);
pick.addEnchantment(Enchantment.efficiency, 5);
pick.addEnchantment(Enchantment.fortune, 4);
GameRegistry.addRecipe(new ShapedOreRecipe(pick, new Object[] {
"yxy", " z ", " z ", 'x', diamondFusedNetherStar, 'y', glowIngot, 'z', STICK
}));
// Crafting the sword
ItemStack SWORD = new ItemStack(glowSwordUnbreakable, 1);
SWORD.addEnchantment(Enchantment.fireAspect, 1);
SWORD.addEnchantment(Enchantment.sharpness, 5);
SWORD.addEnchantment(Enchantment.looting, 4);
GameRegistry.addRecipe(new ShapedOreRecipe(SWORD, new Object[] {
" w ", " x ", " z ", 'w', glowIngot, 'x', diamondFusedNetherStar, 'z', STICK
}));
// Crafting the axe
ItemStack AXE = new ItemStack(glowAxeUnbreakable, 1);
AXE.addEnchantment(Enchantment.efficiency, 5);
GameRegistry.addRecipe(new ShapedOreRecipe(AXE, new Object[] {
"wx ", "xy ", " y ", 'w', diamondFusedNetherStar, 'x', glowIngot, 'y', STICK,
}));
// Crafting the glowHoe
ItemStack HOE = new ItemStack(glowHoeUnbreakable, 1);
GameRegistry.addRecipe(new ShapedOreRecipe(HOE, new Object[] {
"wx ", "yz ", " z ", 'w', glowIngot, 'x', diamondFusedNetherStar, 'y', Items.diamond, 'z', STICK
}));
// Crafting the glow Shovel
ItemStack SHOVEL = new ItemStack(glowShovelUnbreakable, 1);
SHOVEL.addEnchantment(Enchantment.efficiency, 5);
GameRegistry.addRecipe(new ShapedOreRecipe(SHOVEL, new Object[] {
" x ", " y ", " y ", 'x', diamondFusedNetherStar, 'y', STICK
}));
// Crafting the glow hammer
ItemStack HAMMER = new ItemStack(glowHammerUnbreakable, 1);
// HAMMER.addEnchantment(Enchantment.efficiency, 5); // TODO: Change this!
HAMMER.addEnchantment(Enchantment.fortune, 4);
GameRegistry.addRecipe(new ShapedOreRecipe(HAMMER, new Object[] {
"yxy", "wzw", " z ", 'x', diamondFusedNetherStar, 'y', glowIngot, 'w', Items.diamond, 'z', STICK
}));
// Crafting the glow excavator
ItemStack EXCAVATOR = new ItemStack(glowExcavatorUnbreakable, 1);
GameRegistry.addRecipe(new ShapedOreRecipe(EXCAVATOR, new Object[] {
" x ", "yzy", " z ", 'x', diamondFusedNetherStar, 'y', Items.diamond, 'z', STICK
}));
// Crafting the glow boots
ItemStack BOOT = new ItemStack(glowBoot, 1);
GameRegistry.addRecipe(BOOT, new Object[] {
"x x", "x x", 'x', glowIngot
});
// Crafting the glow leggings
ItemStack LEGGINGS = new ItemStack(glowLegging, 1);
GameRegistry.addRecipe(LEGGINGS, new Object[] {
"xxx", "x x", "x x", 'x', glowIngot
});
// Crafting the glow chestplate
ItemStack CHESTPLATE = new ItemStack(glowChestplate, 1);
GameRegistry.addRecipe(CHESTPLATE, new Object[] {
"x x", "xyx", "xxx", 'x', glowIngot, 'y', diamondFusedNetherStar
});
// Crafting the glow helmet
ItemStack HELMET = new ItemStack(glowHelmet, 1);
GameRegistry.addRecipe(HELMET, new Object[] {
"xxx", "x x", 'x', glowIngot
});
}
private void addFurnaceRecipes() {
// USE: args(use what block/item from id, (get what block/item from id, how much), how much xp should the player be rewarded.
GameRegistry.addSmelting(glowOre, new ItemStack(glowDust, 1), 100f);
}
/*
* private void pulverizeRecipes() { // Code performing glowOre into 2*glowDust via Thermal Expansion // Pulverizer. NBTTagCompound toSend = new NBTTagCompound(); toSend.setInteger("energy", 1000); toSend.setCompoundTag("input", new NBTTagCompound()); toSend.setCompoundTag("primaryOutput", new
* NBTTagCompound());
*
* ItemStack inputStack = new ItemStack(glowOre, 1); inputStack.writeToNBT(toSend.getCompoundTag("input"));
*
* ItemStack outputStack = new ItemStack(glowDust, 2); outputStack.writeToNBT(toSend.getCompoundTag("primaryOutput")); FMLInterModComms.sendMessage("ThermalExpansion", "PulverizerRecipe", toSend);
*
* }
*/
private void registerTileEntities() {
GameRegistry.registerTileEntity(TileEntityGlowFurnace.class, "tileEntityGlowFurnace");
}
private void registerGuiHandler() {
if (guiHandler != null) NetworkRegistry.INSTANCE.registerGuiHandler(this, guiHandler);
else {
guiHandler = new GuiHandlerGlowFurnace();
NetworkRegistry.INSTANCE.registerGuiHandler(this, guiHandler);
}
}
} |
package com.tapsterrock.mpp;
import java.io.InputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* This class is used to represent the "FixedData" file entries that are
* found in a Microsoft Project MPP file. The name "Fixed Data" appears to
* refer to the fact that the items held in these blocks have a known maximum
* size, rather than all of the items being identically sized records.
*
* Note that this class has package level access only, and is not intended
* for use outside of this context.
*/
final class FixedData extends MPPComponent
{
/**
* This constructor retrieves the data from the input stream. It
* makes use of the meta data regarding this data block that has
* already been read in from the MPP file.
*
* Note that we actually read in the entire data block in one go.
* This is due to the fact that MS Project sometimes describes data
* using offsets that are out of sequence, and items that may overlap.
* Ideally this data would be read directly from the input stream, but
* this was problematic, so this less than ideal solution has been
* adopted.
*
* @param meta meta data about the contents of this fixed data block
* @param is input stream from which the data is read
* @throws IOException on file read failure
*/
FixedData (FixedMeta meta, InputStream is)
throws IOException
{
byte[] buffer = new byte[is.available()];
is.read(buffer);
int itemCount = meta.getItemCount();
m_array = new Object[itemCount];
m_offset = new int[itemCount];
byte[] metaData;
int itemOffset;
int itemSize;
int available;
for (int loop=0; loop < itemCount; loop++)
{
metaData = meta.getByteArrayValue(loop);
itemSize = MPPUtility.getInt(metaData, 0);
itemOffset = MPPUtility.getInt(metaData, 4);
if (itemOffset > buffer.length)
{
continue;
}
available = buffer.length - itemOffset;
if (itemSize < 0)
{
itemSize = available;
}
else
{
if (itemSize > available)
{
itemSize = available;
}
}
m_array[loop] = MPPUtility.cloneSubArray(buffer, itemOffset, itemSize);
m_offset[loop] = itemOffset;
}
}
/**
* This constructor is provided to allow the contents of a fixed data
* block to be read when the size of the items in the data block is
* fixed and known in advance. This is used in one particular instance
* where the contents of the meta data block do not appear to be
* consistent.
*
* @param itemSize the size of the data items in the block
* @param is input stream from which the data is read
* @throws IOException on file read failure
*/
FixedData (int itemSize, InputStream is)
throws IOException
{
int offset = 0;
int itemCount = is.available() / itemSize;
m_array = new Object[itemCount];
m_offset = new int[itemCount];
for (int loop=0; loop < itemCount; loop++)
{
m_offset[loop] = offset;
m_array[loop] = readByteArray (is, itemSize);
offset += itemSize;
}
}
/**
* This method retrieves a byte array containing the data at the
* given index in the block. If no data is found at the given index
* this method returns null.
*
* @param index index of the data item to be retrieved
* @return byte array containing the requested data
*/
public byte[] getByteArrayValue (int index)
{
byte[] result = null;
if (m_array[index] != null)
{
result = (byte[])m_array[index];
}
return (result);
}
/**
* Accessor method used to retrieve the number of items held in
* this fixed data block. Note that this item count is made without
* reference to the meta data associated with this block.
*
* @return number of items in the block
*/
public int getItemCount ()
{
return (m_array.length);
}
/**
* Returns a flag indicating if the supplied offset is valid for
* the data in this fixed data block.
*
* @param offset offset value
* @return boolean flag
*/
public boolean isValidOffset (Integer offset)
{
return (offset==null?false:isValidOffset(offset.intValue()));
}
/**
* Returns a flag indicating if the supplied offset is valid for
* the data in this fixed data block.
*
* @param offset offset value
* @return boolean flag
*/
public boolean isValidOffset (int offset)
{
return (offset >= 0 && offset < m_array.length);
}
/**
* This method converts an offset value into an array index, which in
* turn allows the data present in the fixed block to be retrieved. Note
* that if the requested offset is not found, then this method returns -1.
*
* @param offset Offset of the data in the fixed block
* @return Index of data item within the fixed data block
*/
public int getIndexFromOffset (int offset)
{
int result = -1;
for (int loop=0; loop < m_offset.length; loop++)
{
if (m_offset[loop] == offset)
{
result = loop;
break;
}
}
return (result);
}
/**
* This method dumps the contents of this FixedData block as a String.
* Note that this facility is provided as a debugging aid.
*
* @return formatted contents of this block
*/
public String toString ()
{
StringWriter sw = new StringWriter ();
PrintWriter pw = new PrintWriter (sw);
pw.println ("BEGIN FixedData");
for (int loop=0; loop < m_array.length; loop++)
{
pw.println (" Data at index: " + loop + " offset: " + m_offset[loop]);
pw.println (" " + MPPUtility.hexdump ((byte[])m_array[loop], true));
}
pw.println ("END FixedData");
pw.println ();
pw.close();
return (sw.toString());
}
/**
* An array containing all of the items of data held in this block.
*/
private Object[] m_array;
/**
* Array containing offset values for each item in the array.
*/
private int[] m_offset;
} |
package gov.nrel.util;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.ByteBuffer;
import java.util.List;
import models.EntityUser;
import models.SecureSchema;
import models.message.Trigger;
import org.apache.commons.lang.StringUtils;
import org.mortbay.log.Log;
import org.playorm.cron.api.CronService;
import org.playorm.cron.api.CronServiceFactory;
import org.playorm.cron.api.PlayOrmCronJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import play.mvc.Http.Request;
import com.alvazan.orm.api.base.NoSqlEntityManager;
import com.alvazan.orm.api.base.NoSqlEntityManagerFactory;
import com.ning.http.client.AsyncHandler;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.HttpResponseBodyPart;
import com.ning.http.client.HttpResponseHeaders;
import com.ning.http.client.HttpResponseStatus;
import com.ning.http.client.ListenableFuture;
import com.ning.http.client.Realm;
import com.ning.http.client.RequestBuilder;
import com.ning.http.client.Realm.AuthScheme;
import controllers.api.CronJobController;
import controllers.modules2.framework.ProductionModule;
import controllers.modules2.framework.chain.AHttpChunkingListener;
import controllers.modules2.framework.http.HttpListener;
import controllers.modules2.framework.procs.PushProcessor;
import controllers.modules2.framework.procs.RemoteProcessor.AuthInfo;
import controllers.modules2.framework.translate.TranslationFactory;
public class ATriggerListener {
private static final Logger log = LoggerFactory.getLogger(ATriggerListener.class);
private Long startOverride;
private Long endOverride;
private CronService svc;
private AsyncHttpClient client = ProductionModule.createSingleton();
public ATriggerListener(CronService svc) {
this.svc = svc;
}
public ATriggerListener(CronService svc, long startOverride, long endOverride) {
this.svc = svc;
this.startOverride = startOverride;
this.endOverride = endOverride;
}
public void monitorFired(PlayOrmCronJob m) {
Trigger trigger = transform(m);
if(log.isInfoEnabled())
log.info("monitor firing for url="+trigger.getUrl());
String url = trigger.getUrl();
boolean success = false;
String exceptionString = "none";
//synchronously call the url awaiting a result here
String db = trigger.getDatabase();
String id = trigger.getId();
Long start = startOverride;
Long end = endOverride;
if(startOverride == null) {
long time = System.currentTimeMillis();
long range = time - trigger.getOffset();
long multiplier = range / trigger.getRate();
long endLastPeriod = trigger.getOffset()+multiplier*trigger.getRate();
if(endLastPeriod > time) {
log.warn("WE have a problem in that the window is in the future...this is our bug in that our trigger fired tooooo early then. db="+db+" cronjob="+id, new RuntimeException("trigger fired too early. look next log"));
}
long beginLastPeriod = endLastPeriod - trigger.getRate();
start = beginLastPeriod - trigger.getBefore();
end = endLastPeriod+trigger.getAfter();
while(end > time) {
start -= trigger.getRate();
end -= trigger.getRate();
if(log.isInfoEnabled())
log.info("db="+db+" cron="+id+"time="+time+" range="+range+" multiplier="+multiplier+" endLastPeriod="+endLastPeriod+" beginLastPer="+beginLastPeriod+" start="+start+" end="+end+" trigger="+trigger);
}
}
try {
fireHttpRequestAndWait(m, url, start, end);
success = true;
} catch(RuntimeException e) {
log.warn("Exception on cron job requesting url. triggerid="+m.getId()+" db="+db, e);
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
exceptionString = sw.toString();
//MUST be thrown as this is called from controller and we must give user exception if his url does not work at all
throw e;
} finally {
m.getProperties().put("success", success+"");
m.getProperties().put("lastException", exceptionString);
svc.saveMonitor(m);
}
}
private void fireHttpRequestAndWait(PlayOrmCronJob m, String url, long start, long end) {
String username = m.getProperties().get("userName");
String apiKey = m.getProperties().get("apiKey");
// fix this so it is passed in instead....
Realm realm = new Realm.RealmBuilder()
.setPrincipal(username)
.setPassword(apiKey)
.setUsePreemptiveAuth(true).setScheme(AuthScheme.BASIC)
.build();
String fullUrl = url+"/"+start+"/"+end;
if (log.isInfoEnabled())
log.info("CRON JOB-sending request to url=" + fullUrl);
RequestBuilder b = new RequestBuilder("GET").setUrl(fullUrl)
.setRealm(realm);
com.ning.http.client.Request httpReq = b.build();
try {
MyHandler handler = new MyHandler();
long startTime = System.currentTimeMillis();
long duration = 0;
m.getProperties().put("startTime", ""+startTime);
m.getProperties().put("duration", ""+duration);
client.executeRequest(httpReq, handler);
duration = startTime - System.currentTimeMillis();
m.getProperties().put("duration", ""+duration);
handler.checkStatus();
} catch(IOException e) {
throw new RuntimeException("Failed to send request. url="+url);
}
}
public static String formId(String origId) {
String id = "_log"+origId;
return id;
}
public static PlayOrmCronJob transform(Trigger msg, String id,
SecureSchema schemaDbo, EntityUser user) {
PlayOrmCronJob job;
job = new PlayOrmCronJob();
job.setId(id);
job.setType("trigger");
job.setTimePeriodMillis(msg.getRate());
//offset needs to be changed to offset+after so that we always fire after the after window
job.setEpochOffset(msg.getOffset()+msg.getAfter());
job.getProperties().put("offset", msg.getOffset()+"");
job.getProperties().put("before", msg.getBefore()+"");
job.getProperties().put("after", msg.getAfter()+"");
job.getProperties().put("schemaId", schemaDbo.getId());
job.getProperties().put("url", msg.getUrl());
job.getProperties().put("userId", user.getId());
job.getProperties().put("userName", user.getUsername());
job.getProperties().put("apiKey", user.getApiKey());
job.getProperties().put("database", schemaDbo.getSchemaName());
return job;
}
public static Trigger transform(PlayOrmCronJob job) {
Trigger t = new Trigger();
//trim off the 4 prefix we put on...
t.setId(job.getId().substring(4));
t.setRate(job.getTimePeriodMillis());
t.setOffset(CronJobController.toLong(job.getProperties().get("offset")));
t.setBefore(CronJobController.toLong(job.getProperties().get("before")));
t.setAfter(CronJobController.toLong(job.getProperties().get("after")));
t.setUrl(job.getProperties().get("url"));
t.setRunAsUser(job.getProperties().get("userName"));
t.setLastRunSuccess(toBoolean(job.getProperties().get("success")));
t.setDatabase(job.getProperties().get("database"));
if (StringUtils.isNotBlank(job.getProperties().get("startTime")))
t.setLastRunTime(Long.parseLong(job.getProperties().get("startTime")));
if (StringUtils.isNotBlank(job.getProperties().get("duration")))
t.setLastRunDuration(Long.parseLong(job.getProperties().get("duration")));
t.setLastException(job.getProperties().get("lastException"));
return t;
}
private static boolean toBoolean(String val) {
if("true".equals(val))
return true;
return false;
}
private static class MyHandler implements AsyncHandler<Object> {
private Throwable failure;
private HttpResponseStatus status;
private boolean complete;
private ByteBuffer buffer = ByteBuffer.allocate(5000);
@Override
public com.ning.http.client.AsyncHandler.STATE onBodyPartReceived(HttpResponseBodyPart part) throws Exception {
byte[] data = part.getBodyPartBytes();
if(buffer.remaining() > data.length)
buffer.put(data);
return AsyncHandler.STATE.CONTINUE;
}
public void checkStatus() {
synchronized(this) {
while(!complete && failure == null) {
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
if(failure != null) {
String dataMsg = read();
throw new RuntimeException("Failure. first 5000 bytes of body="+dataMsg+"(END)\n", failure);
} else if(status.getStatusCode() != 200) {
String dataMsg = read();
throw new RuntimeException("web url returned="+status.getStatusCode()+" first 5000 bytes of body message="+dataMsg+"(END)\n");
}
}
private String read() {
buffer.flip();
byte[] data = new byte[buffer.remaining()];
buffer.get(data);
String s = new String(data);
return s;
}
@Override
public Object onCompleted() throws Exception {
synchronized(this) {
this.complete = true;
this.notifyAll();
}
return null;
}
@Override
public com.ning.http.client.AsyncHandler.STATE onHeadersReceived(
HttpResponseHeaders arg0) throws Exception {
return AsyncHandler.STATE.CONTINUE;
}
@Override
public com.ning.http.client.AsyncHandler.STATE onStatusReceived(
HttpResponseStatus status) throws Exception {
this.status = status;
return AsyncHandler.STATE.CONTINUE;
}
@Override
public void onThrowable(Throwable t) {
failure = t;
synchronized(this) {
this.notifyAll();
}
}
}
} |
package net.sf.farrago.db;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import net.sf.farrago.catalog.*;
import net.sf.farrago.cwm.core.*;
import net.sf.farrago.cwm.relational.*;
import net.sf.farrago.ddl.*;
import net.sf.farrago.fem.fennel.*;
import net.sf.farrago.fem.security.*;
import net.sf.farrago.fennel.*;
import net.sf.farrago.parser.*;
import net.sf.farrago.query.*;
import net.sf.farrago.resource.*;
import net.sf.farrago.runtime.*;
import net.sf.farrago.session.*;
import net.sf.farrago.trace.*;
import net.sf.farrago.util.*;
import net.sf.farrago.plugin.*;
import org.eigenbase.resgen.*;
import org.eigenbase.resource.*;
import org.eigenbase.oj.rex.*;
import org.eigenbase.oj.stmt.*;
import org.eigenbase.sql.*;
import org.eigenbase.sql.fun.*;
import org.eigenbase.reltype.*;
import org.eigenbase.util.*;
import org.eigenbase.jmi.*;
/**
* FarragoDbSession implements the {@link
* net.sf.farrago.session.FarragoSession} interface as a connection to a {@link
* FarragoDatabase} instance. It manages private authorization and transaction
* context.
*
* @author John V. Sichi
* @version $Id: //open/dev/farrago/src/net/sf/farrago/db/FarragoDbSession.java#27
*/
public class FarragoDbSession extends FarragoCompoundAllocation
implements FarragoSession,
Cloneable
{
private static final Logger tracer =
FarragoTrace.getDatabaseSessionTracer();
public static final String MDR_USER_NAME = "MDR";
/** Default personality for this session. */
private FarragoSessionPersonality defaultPersonality;
/** Current personality for this session. */
private FarragoSessionPersonality personality;
/** Fennel transaction context for this session */
private FennelTxnContext fennelTxnContext;
/**
* Current transaction ID, or null if none active.
*/
private FarragoSessionTxnId txnId;
/** Qualifiers to assume for unqualified object references */
private FarragoSessionVariables sessionVariables;
/** Database accessed by this session */
private FarragoDatabase database;
/** Repos accessed by this session */
private FarragoRepos repos;
private String url;
/** Was this session produced by cloning? */
private boolean isClone;
private boolean isAutoCommit;
private boolean shutDownRequested;
private boolean catalogDumpRequested;
private boolean wasKilled;
/**
* List of savepoints established within current transaction which have
* not been released or rolled back; order is from earliest to latest.
*/
private List savepointList;
/**
* Generator for savepoint Id's.
*/
private int nextSavepointId;
private FarragoDbSessionIndexMap sessionIndexMap;
/**
* The connection source for this session.
*/
private FarragoSessionConnectionSource connectionSource;
/**
* Private cache of executable code pinned by the current txn.
*/
private Map txnCodeCache;
private DatabaseMetaData dbMetaData;
protected FarragoSessionFactory sessionFactory;
private FarragoSessionPrivilegeMap privilegeMap;
private FarragoDbSessionInfo sessionInfo;
/**
* Creates a new FarragoDbSession object.
*
* @param url URL used to connect (same as JDBC)
*
* @param info properties for this session
*
* @param sessionFactory factory which created this session
*/
public FarragoDbSession(
String url,
Properties info,
FarragoSessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
this.url = url;
database = FarragoDbSingleton.pinReference(sessionFactory);
FarragoDbSingleton.addSession(database, this);
boolean success = false;
try {
init(info);
success = true;
} finally {
if (!success) {
closeAllocation();
}
}
}
private void init(Properties info)
{
sessionVariables = new FarragoSessionVariables();
String sessionUser = info.getProperty("user", "GUEST");
sessionVariables.sessionUserName = sessionUser;
sessionVariables.currentUserName = sessionUser;
sessionVariables.currentRoleName = "";
sessionVariables.systemUserName = info.getProperty(
"clientUserName",
System.getProperty("user.name"));
sessionVariables.systemUserFullName = info.getProperty(
"clientUserFullName");
sessionVariables.schemaSearchPath = Collections.EMPTY_LIST;
sessionVariables.sessionName = info.getProperty("sessionName");
sessionVariables.programName = info.getProperty("clientProgramName");
sessionVariables.processId = 0L;
String processStr = info.getProperty("clientProcessId");
if (processStr != null) {
try {
sessionVariables.processId = Long.parseLong(processStr);
} catch (NumberFormatException e) {
tracer.warning("processId error: " +e.getMessage());
}
}
FemUser femUser = null;
if (MDR_USER_NAME.equals(sessionVariables.sessionUserName)) {
// This is a reentrant session from MDR.
repos = database.getSystemRepos();
if (sessionVariables.sessionName == null) {
sessionVariables.sessionName = MDR_USER_NAME;
}
} else {
// This is a normal session.
repos = database.getUserRepos();
femUser =
FarragoCatalogUtil.getUserByName(repos, sessionUser);
if (femUser == null) {
throw FarragoResource.instance().SessionUnknownUser.ex(
repos.getLocalizedObjectName(sessionUser));
} else {
// TODO: authenticate
}
}
fennelTxnContext =
sessionFactory.newFennelTxnContext(
repos,
database.getFennelDbHandle());
CwmNamespace defaultNamespace = null;
if (femUser != null) {
defaultNamespace = femUser.getDefaultNamespace();
}
if (defaultNamespace == null) {
sessionVariables.catalogName = repos.getSelfAsCatalog().getName();
} else if (defaultNamespace instanceof CwmCatalog) {
sessionVariables.catalogName = defaultNamespace.getName();
} else {
sessionVariables.schemaName = defaultNamespace.getName();
sessionVariables.catalogName =
defaultNamespace.getNamespace().getName();
}
txnCodeCache = new HashMap();
isAutoCommit = true;
savepointList = new ArrayList();
sessionIndexMap = new FarragoDbSessionIndexMap(this, database, repos);
personality = sessionFactory.newSessionPersonality(this, null);
defaultPersonality = personality;
sessionInfo = new FarragoDbSessionInfo(this, database);
}
// implement FarragoSession
public FarragoSessionFactory getSessionFactory()
{
return sessionFactory;
}
// implement FarragoSession
public FarragoSessionPersonality getPersonality()
{
return personality;
}
// implement FarragoSession
public void setDatabaseMetaData(DatabaseMetaData dbMetaData)
{
this.dbMetaData = dbMetaData;
}
// implement FarragoSession
public void setConnectionSource(FarragoSessionConnectionSource source)
{
this.connectionSource = source;
}
// implement FarragoSession
public DatabaseMetaData getDatabaseMetaData()
{
return dbMetaData;
}
// implement FarragoSession
public FarragoSessionConnectionSource getConnectionSource()
{
return connectionSource;
}
// implement FarragoSession
public String getUrl()
{
return url;
}
// implement FarragoSession
public FarragoPluginClassLoader getPluginClassLoader()
{
return database.getPluginClassLoader();
}
// implement FarragoSession
public List getModelExtensions()
{
return database.getModelExtensions();
}
// implement FarragoSession
public FarragoSessionInfo getSessionInfo() {
return sessionInfo;
}
// implement FarragoSession
public FarragoSessionStmtContext newStmtContext(
FarragoSessionStmtParamDefFactory paramDefFactory)
{
FarragoDbStmtContext stmtContext =
new FarragoDbStmtContext(
this, paramDefFactory, database.getDdlLockManager());
addAllocation(stmtContext);
return stmtContext;
}
// implement FarragoSession
public FarragoSessionStmtValidator newStmtValidator()
{
return new FarragoStmtValidator(
getRepos(),
getDatabase().getFennelDbHandle(),
this,
getDatabase().getCodeCache(),
getDatabase().getDataWrapperCache(),
getSessionIndexMap(),
getDatabase().getDdlLockManager());
}
// implement FarragoSession
public FarragoSessionPrivilegeChecker newPrivilegeChecker()
{
// Instantiate a new privilege checker
return new FarragoDbSessionPrivilegeChecker(this);
}
// implement FarragoSession
public FarragoSessionPrivilegeMap getPrivilegeMap()
{
if (privilegeMap == null) {
FarragoDbSessionPrivilegeMap newPrivilegeMap =
new FarragoDbSessionPrivilegeMap(repos.getModelView());
getPersonality().definePrivileges(newPrivilegeMap);
Iterator iter = getModelExtensions().iterator();
while (iter.hasNext()) {
FarragoSessionModelExtension ext =
(FarragoSessionModelExtension) iter.next();
ext.definePrivileges(newPrivilegeMap);
}
newPrivilegeMap.makeImmutable();
privilegeMap = newPrivilegeMap;
}
return privilegeMap;
}
// implement FarragoSession
public FarragoSession cloneSession(
FarragoSessionVariables inheritedVariables)
{
// TODO: keep track of clones and make sure they aren't left hanging
// around by the time stmt finishes executing
try {
FarragoDbSession clone = (FarragoDbSession) super.clone();
clone.isClone = true;
clone.allocations = new LinkedList();
clone.savepointList = new ArrayList();
if (isTxnInProgress()) {
// Calling statement has already started a transaction:
// make sure clone doesn't interfere by autocommitting.
clone.isAutoCommit = false;
} else {
// Otherwise, inherit autocommit setting.
clone.isAutoCommit = isAutoCommit;
}
if (inheritedVariables == null) {
inheritedVariables = sessionVariables;
}
clone.sessionVariables = inheritedVariables.cloneVariables();
return clone;
} catch (CloneNotSupportedException ex) {
throw Util.newInternal(ex);
}
}
// implement FarragoSession
public boolean isClone()
{
return isClone;
}
// implement FarragoSession
public synchronized boolean isClosed()
{
return (database == null);
}
// implement FarragoSession
public synchronized boolean wasKilled()
{
return isClosed() && wasKilled;
}
// implement FarragoSession
public boolean isTxnInProgress()
{
// TODO jvs 9-Mar-2006: Unify txn state.
if (txnId != null) {
return true;
}
if (fennelTxnContext == null) {
return false;
}
return fennelTxnContext.isTxnInProgress();
}
// implement FarragoSession
public FarragoSessionTxnId getTxnId(boolean createIfNeeded)
{
if ((txnId == null) && createIfNeeded) {
txnId = getTxnMgr().beginTxn(this);
}
return txnId;
}
// implement FarragoSession
public FarragoSessionTxnMgr getTxnMgr()
{
return database.getTxnMgr();
}
// implement FarragoSession
public void setAutoCommit(boolean autoCommit)
{
ResourceDefinition txnFeature =
EigenbaseResource.instance().SQLFeature_E151;
if (!autoCommit) {
if (!personality.supportsFeature(txnFeature)) {
throw EigenbaseResource.instance().SQLFeature_E151.ex();
}
}
commitImpl();
isAutoCommit = autoCommit;
}
// implement FarragoSession
public boolean isAutoCommit()
{
return isAutoCommit;
}
// implement FarragoSession
public FarragoSessionVariables getSessionVariables()
{
return sessionVariables;
}
// implement FarragoSession
public void endTransactionIfAuto(boolean commit)
{
if (isAutoCommit) {
if (commit) {
commitImpl();
} else {
rollbackImpl();
}
}
}
// implement FarragoSession
public FarragoRepos getRepos()
{
return repos;
}
public synchronized void kill()
{
closeAllocation();
wasKilled = true;
}
// implement FarragoAllocation
public synchronized void closeAllocation()
{
super.closeAllocation();
if (isClone || isClosed()) {
return;
}
if (isTxnInProgress()) {
if (isAutoCommit) {
commitImpl();
} else {
// NOTE jvs 10-May-2005: Technically, we're supposed to throw
// an invalid state exception here. However, it's very
// unlikely that the caller is going to handle it properly,
// so instead we roll back. If they wanted their
// changes committed, they should have said so.
rollbackImpl();
}
}
try {
FarragoDbSingleton.disconnectSession(this);
} finally {
database = null;
repos = null;
}
}
// implement FarragoSession
public void commit()
{
if (isAutoCommit) {
throw FarragoResource.instance().SessionNoCommitInAutocommit.ex();
}
commitImpl();
}
// implement FarragoSession
public FarragoSessionSavepoint newSavepoint(String name)
{
if (name != null) {
if (findSavepointByName(name, false) != -1) {
throw FarragoResource.instance().SessionDupSavepointName.ex(
repos.getLocalizedObjectName(name));
}
}
return newSavepointImpl(name);
}
// implement FarragoSession
public void releaseSavepoint(FarragoSessionSavepoint savepoint)
{
int iSavepoint = validateSavepoint(savepoint);
releaseSavepoint(iSavepoint);
}
// implement FarragoSession
public FarragoSessionAnalyzedSql analyzeSql(
String sql,
RelDataTypeFactory typeFactory,
RelDataType paramRowType,
boolean optimize)
{
FarragoSessionAnalyzedSql analyzedSql =
getAnalysisBlock(typeFactory);
analyzedSql.optimized = optimize;
analyzedSql.paramRowType = paramRowType;
FarragoSessionExecutableStmt stmt = prepare(
null, sql, null, false, analyzedSql);
assert (stmt == null);
if (typeFactory != null) {
// Have to copy types into the caller's factory since
// analysis uses a private factory.
if (analyzedSql.paramRowType != null) {
analyzedSql.paramRowType = typeFactory.copyType(
analyzedSql.paramRowType);
}
if (analyzedSql.resultType != null) {
analyzedSql.resultType = typeFactory.copyType(
analyzedSql.resultType);
}
}
return analyzedSql;
}
public FarragoSessionAnalyzedSql getAnalysisBlock(
RelDataTypeFactory typeFactory)
{
return new FarragoSessionAnalyzedSql();
}
public FarragoDatabase getDatabase()
{
return database;
}
public FarragoDbSessionIndexMap getSessionIndexMap()
{
return sessionIndexMap;
}
Map getTxnCodeCache()
{
return txnCodeCache;
}
FennelTxnContext getFennelTxnContext()
{
return fennelTxnContext;
}
void commitImpl()
{
tracer.info("commit");
if (fennelTxnContext != null) {
fennelTxnContext.commit();
}
onEndOfTransaction(FarragoSessionTxnEnd.COMMIT);
sessionIndexMap.onCommit();
}
void rollbackImpl()
{
tracer.info("rollback");
if (fennelTxnContext != null) {
fennelTxnContext.rollback();
}
onEndOfTransaction(FarragoSessionTxnEnd.ROLLBACK);
}
private void onEndOfTransaction(
FarragoSessionTxnEnd eot)
{
if (txnId != null) {
getTxnMgr().endTxn(txnId, eot);
txnId = null;
}
savepointList.clear();
Iterator iter = txnCodeCache.values().iterator();
while (iter.hasNext()) {
FarragoAllocation alloc = (FarragoAllocation) iter.next();
alloc.closeAllocation();
}
txnCodeCache.clear();
}
// implement FarragoSession
public void rollback(FarragoSessionSavepoint savepoint)
{
if (isAutoCommit) {
throw FarragoResource.instance().SessionNoRollbackInAutocommit.ex();
}
if (savepoint == null) {
rollbackImpl();
} else {
int iSavepoint = validateSavepoint(savepoint);
rollbackToSavepoint(iSavepoint);
}
}
// implement FarragoSession
public Collection executeLurqlQuery(
String lurql,
Map argMap)
{
// TODO jvs 24-May-2005: query cache
Connection connection = null;
try {
if (connectionSource != null) {
connection = connectionSource.newConnection();
}
JmiQueryProcessor queryProcessor =
getPersonality().newJmiQueryProcessor("LURQL");
JmiPreparedQuery query = queryProcessor.prepare(
getRepos().getModelView(), lurql);
return query.execute(connection, argMap);
} catch (JmiQueryException ex) {
throw FarragoResource.instance().SessionInternalQueryFailed.ex(ex);
} finally {
Util.squelchConnection(connection);
}
}
protected FarragoSessionRuntimeParams newRuntimeContextParams()
{
FarragoSessionRuntimeParams params = new FarragoSessionRuntimeParams();
params.session = this;
params.repos = getRepos();
params.codeCache = getDatabase().getCodeCache();
params.txnCodeCache = getTxnCodeCache();
params.fennelTxnContext = getFennelTxnContext();
params.indexMap = getSessionIndexMap();
params.sessionVariables = getSessionVariables().cloneVariables();
params.sharedDataWrapperCache = getDatabase().getDataWrapperCache();
params.streamFactoryProvider = personality;
return params;
}
private FarragoSessionSavepoint newSavepointImpl(String name)
{
if (isAutoCommit) {
throw FarragoResource.instance().SessionNoSavepointInAutocommit.ex();
}
FennelSvptHandle fennelSvptHandle = fennelTxnContext.newSavepoint();
FarragoDbSavepoint newSavepoint =
new FarragoDbSavepoint(nextSavepointId++, name, fennelSvptHandle,
this);
savepointList.add(newSavepoint);
return newSavepoint;
}
private int validateSavepoint(FarragoSessionSavepoint savepoint)
{
if (!(savepoint instanceof FarragoDbSavepoint)) {
throw FarragoResource.instance().SessionWrongSavepoint.ex(
repos.getLocalizedObjectName(savepoint.getName()));
}
FarragoDbSavepoint dbSavepoint = (FarragoDbSavepoint) savepoint;
if (dbSavepoint.session != this) {
throw FarragoResource.instance().SessionWrongSavepoint.ex(
savepoint.getName());
}
int iSavepoint = findSavepoint(savepoint);
if (iSavepoint == -1) {
if (savepoint.getName() == null) {
throw FarragoResource.instance().SessionInvalidSavepointId.ex(
new Integer(savepoint.getId()));
} else {
throw FarragoResource.instance().SessionInvalidSavepointName.ex(
repos.getLocalizedObjectName(savepoint.getName()));
}
}
return iSavepoint;
}
private int findSavepointByName(
String name,
boolean throwIfNotFound)
{
for (int i = 0; i < savepointList.size(); ++i) {
FarragoDbSavepoint savepoint =
(FarragoDbSavepoint) savepointList.get(i);
if (name.equals(savepoint.getName())) {
return i;
}
}
if (throwIfNotFound) {
throw FarragoResource.instance().SessionInvalidSavepointName.ex(name);
}
return -1;
}
private int findSavepoint(FarragoSessionSavepoint savepoint)
{
return savepointList.indexOf(savepoint);
}
private void releaseSavepoint(int iSavepoint)
{
// TODO: need Fennel support
throw Util.needToImplement(null);
}
private void rollbackToSavepoint(int iSavepoint)
{
if (isAutoCommit) {
throw FarragoResource.instance().SessionNoRollbackInAutocommit.ex();
}
FarragoDbSavepoint savepoint =
(FarragoDbSavepoint) savepointList.get(iSavepoint);
if (repos.isFennelEnabled()) {
fennelTxnContext.rollbackToSavepoint(
savepoint.getFennelSvptHandle());
}
// TODO: list truncation util
while (savepointList.size() > (iSavepoint + 1)) {
savepointList.remove(savepointList.size() - 1);
}
}
protected FarragoSessionExecutableStmt prepare(
FarragoDbStmtContextBase stmtContext,
String sql,
FarragoAllocationOwner owner,
boolean isExecDirect,
FarragoSessionAnalyzedSql analyzedSql)
{
tracer.info(sql);
// TODO jvs 20-Mar-2006: Get rid of this big mutex. First we need
// to make object-level DDL-locking incremental (rather than deferring
// it all to the end of preparation). For now the contention is the
// same as that due to the TODO below since the MDR write lock is
// exclusive.
synchronized (database.DDL_LOCK) {
FarragoReposTxnContext reposTxnContext =
new FarragoReposTxnContext(repos);
// TODO jvs 21-June-2004: It would be preferable to start with a
// read lock and only upgrade to write once we know we're dealing
// with DDL. However, at the moment that doesn't work because a
// write txn is required for creating transient objects. And MDR
// doesn't support upgrade. Use JmiMemFactory to solve this
// by creating transient objects in a separate repository.
reposTxnContext.beginWriteTxn();
boolean [] pRollback = new boolean[1];
pRollback[0] = true;
FarragoSessionStmtValidator stmtValidator =
newStmtValidator();
FarragoSessionExecutableStmt stmt = null;
try {
stmt =
prepareImpl(sql, owner, isExecDirect, analyzedSql,
stmtValidator, reposTxnContext, pRollback);
// NOTE jvs 17-Mar-2006: We have to do this here
// rather than in FarragoDbStmtContext.finishPrepare
// to ensure that's there's no window in between
// when we release the mutex and lock the objects;
// otherwise a DROP might slip in and yank them out
// from under us.
if ((stmt != null) && (stmtContext != null)) {
stmtContext.lockObjectsInUse(stmt);
}
} finally {
if (stmtValidator != null) {
stmtValidator.closeAllocation();
}
if (pRollback[0]) {
tracer.fine("rolling back DDL");
reposTxnContext.rollback();
} else {
reposTxnContext.commit();
}
}
return stmt;
}
}
private FarragoSessionExecutableStmt prepareImpl(
String sql,
FarragoAllocationOwner owner,
boolean isExecDirect,
FarragoSessionAnalyzedSql analyzedSql,
FarragoSessionStmtValidator stmtValidator,
FarragoReposTxnContext reposTxnContext,
boolean [] pRollback)
{
// REVIEW: For !isExecDirect, maybe should disable all DDL
// validation: just parse, because the catalog may change by the
// time the statement is executed. Also probably need to disallow
// some types of prepared DDL.
FarragoSessionDdlValidator ddlValidator =
personality.newDdlValidator(stmtValidator);
FarragoSessionParser parser = stmtValidator.getParser();
boolean expectStatement = true;
if ((analyzedSql != null) && (analyzedSql.paramRowType != null)) {
expectStatement = false;
}
Object parsedObj = parser.parseSqlText(
stmtValidator, ddlValidator, sql, expectStatement);
if (parsedObj instanceof SqlNode) {
SqlNode sqlNode = (SqlNode) parsedObj;
pRollback[0] = false;
ddlValidator.closeAllocation();
ddlValidator = null;
personality.validate(stmtValidator, sqlNode);
FarragoSessionExecutableStmt stmt =
database.prepareStmt(
stmtValidator, sqlNode, owner, analyzedSql);
if (isExecDirect
&& (stmt.getDynamicParamRowType().getFieldList().size() > 0))
{
owner.closeAllocation();
throw FarragoResource.instance().
SessionNoExecuteImmediateParameters.ex(sql);
}
return stmt;
}
FarragoSessionDdlStmt ddlStmt = (FarragoSessionDdlStmt) parsedObj;
validateDdl(ddlValidator, reposTxnContext, ddlStmt);
if (!isExecDirect) {
return null;
}
executeDdl(ddlValidator, reposTxnContext, ddlStmt);
pRollback[0] = false;
return null;
}
private void validateDdl(
FarragoSessionDdlValidator ddlValidator,
FarragoReposTxnContext reposTxnContext,
FarragoSessionDdlStmt ddlStmt)
{
if (ddlStmt.requiresCommit()) {
// most DDL causes implicit commit of any pending txn
commitImpl();
}
tracer.fine("validating DDL");
ddlValidator.validate(ddlStmt);
}
private void executeDdl(
FarragoSessionDdlValidator ddlValidator,
FarragoReposTxnContext reposTxnContext,
FarragoSessionDdlStmt ddlStmt)
{
tracer.fine("updating storage");
if (ddlStmt.requiresCommit()) {
// start a Fennel txn to cover any effects on storage
fennelTxnContext.initiateTxn();
}
boolean rollbackFennel = true;
try {
ddlValidator.executeStorage();
ddlStmt.preExecute();
if (ddlStmt instanceof DdlStmt) {
((DdlStmt) ddlStmt).visit(new DdlExecutionVisitor());
}
ddlStmt.postExecute();
tracer.fine("committing DDL");
reposTxnContext.commit();
commitImpl();
rollbackFennel = false;
if (shutDownRequested) {
closeAllocation();
database.shutdown();
if (catalogDumpRequested) {
try {
FarragoReposUtil.dumpRepository();
} catch (Exception ex) {
throw FarragoResource.instance().CatalogDumpFailed.ex(
ex);
}
}
}
} finally {
shutDownRequested = false;
catalogDumpRequested = false;
if (rollbackFennel) {
rollbackImpl();
}
}
}
private class DdlExecutionVisitor extends DdlVisitor
{
// implement DdlVisitor
public void visit(DdlCommitStmt stmt)
{
commit();
}
// implement DdlVisitor
public void visit(DdlRollbackStmt rollbackStmt)
{
if (rollbackStmt.getSavepointName() == null) {
rollback(null);
} else {
int iSavepoint =
findSavepointByName(
rollbackStmt.getSavepointName(),
true);
rollbackToSavepoint(iSavepoint);
}
}
// implement DdlVisitor
public void visit(DdlSavepointStmt savepointStmt)
{
newSavepoint(savepointStmt.getSavepointName());
}
// implement DdlVisitor
public void visit(DdlReleaseSavepointStmt releaseStmt)
{
int iSavepoint =
findSavepointByName(
releaseStmt.getSavepointName(),
true);
releaseSavepoint(iSavepoint);
}
// implement DdlVisitor
public void visit(DdlSetCatalogStmt stmt)
{
SqlIdentifier id = stmt.getCatalogName();
sessionVariables.catalogName = id.getSimple();
}
// implement DdlVisitor
public void visit(DdlSetSchemaStmt stmt)
{
SqlIdentifier id = stmt.getSchemaName();
if (id.isSimple()) {
sessionVariables.schemaName = id.getSimple();
} else {
sessionVariables.catalogName = id.names[0];
sessionVariables.schemaName = id.names[1];
}
}
// implement DdlVisitor
public void visit(DdlSetPathStmt stmt)
{
sessionVariables.schemaSearchPath =
Collections.unmodifiableList(stmt.getSchemaList());
}
// implement DdlVisitor
public void visit(DdlSetSystemParamStmt stmt)
{
database.updateSystemParameter(stmt);
}
// implement DdlVisitor
public void visit(DdlCheckpointStmt stmt)
{
database.requestCheckpoint(false, false);
}
// implement DdlVisitor
public void visit(DdlSetSessionImplementationStmt stmt)
{
personality = stmt.newPersonality(
FarragoDbSession.this,
defaultPersonality);
}
// implement DdlVisitor
public void visit(DdlExtendCatalogStmt stmt)
{
// record the model extension plugin jar URL outside of the catalog
// so that when we reboot it will be available to MDR
database.saveBootUrl(stmt.getJarUrl());
shutDownRequested = true;
catalogDumpRequested = true;
}
}
}
// End FarragoDbSession.java |
package edu.umd.cs.findbugs;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import edu.umd.cs.pugh.io.IO;
import edu.umd.cs.pugh.visitclass.Constants2;
import org.apache.bcel.classfile.*;
import org.apache.bcel.Repository;
import org.apache.bcel.util.ClassPath;
import org.apache.bcel.util.SyntheticRepository;
import edu.umd.cs.daveho.ba.AnalysisContext;
import edu.umd.cs.daveho.ba.AnalysisException;
import edu.umd.cs.daveho.ba.ClassContext;
import edu.umd.cs.daveho.ba.ClassObserver;
/**
* An instance of this class is used to apply the selected set of
* analyses on some collection of Java classes. It also implements the
* comand line interface.
*
* @author Bill Pugh
* @author David Hovemeyer
*/
public class FindBugs implements Constants2, ExitCodes
{
/**
* Interface for an object representing a source of class files to analyze.
*/
private interface ClassProducer {
/**
* Get the next class to analyze.
* @return the class, or null of there are no more classes for this ClassProducer
* @throws IOException if an IOException occurs
* @throws InterruptedException if the thread is interrupted
*/
public JavaClass getNextClass() throws IOException, InterruptedException;
/**
* Did this class producer scan any Java source files?
*/
public boolean containsSourceFiles();
}
/**
* ClassProducer for single class files.
*/
private static class SingleClassProducer implements ClassProducer {
private String fileName;
/**
* Constructor.
* @param fileName the single class file to be analyzed
*/
public SingleClassProducer(String fileName) {
this.fileName = fileName;
}
public JavaClass getNextClass() throws IOException, InterruptedException {
if (fileName == null)
return null;
if (Thread.interrupted())
throw new InterruptedException();
String fileNameToParse = fileName;
fileName = null; // don't return it next time
try {
return new ClassParser(fileNameToParse).parse();
} catch (ClassFormatException e) {
throw new ClassFormatException("Invalid class file format for " +
fileNameToParse + ": " + e.getMessage());
}
}
public boolean containsSourceFiles() {
return false;
}
}
/**
* ClassProducer for .zip and .jar files.
* Nested jar and zip files are also scanned for classes;
* this is needed for .ear and .war files associated with EJBs.
*/
private static class ZipClassProducer implements ClassProducer {
private String fileName;
private String nestedFileName;
private ZipFile zipFile;
private Enumeration entries;
private ZipInputStream zipStream;
private boolean containsSourceFiles;
// a DataInputStream wrapper that cannot be closed
private static class DupDataStream extends DataInputStream {
public DupDataStream( InputStream in ) {
super( in );
}
public void close() { };
}
/**
* Constructor.
* @param fileName the name of the zip or jar file
*/
public ZipClassProducer(String fileName) throws IOException {
this.fileName = fileName;
this.zipFile = new ZipFile(fileName);
this.entries = zipFile.entries();
this.zipStream = null;
this.nestedFileName = null;
this.containsSourceFiles = false;
}
private void setZipStream( ZipInputStream in, String fileName ) {
zipStream = in;
nestedFileName = fileName;
}
private void closeZipStream() throws IOException {
zipStream.close();
zipStream = null;
nestedFileName = null;
}
private JavaClass getNextNestedClass() throws IOException, InterruptedException {
JavaClass parsedClass = null;
if ( zipStream != null ) {
ZipEntry entry = zipStream.getNextEntry();
while ( entry != null ) {
if (Thread.interrupted()) throw new InterruptedException();
if ( entry.getName().endsWith( ".class" ) ) {
try {
parsedClass = new ClassParser( new DupDataStream(zipStream), entry.getName()).parse();
break;
} catch (ClassFormatException e) {
throw new ClassFormatException("Invalid class file format for " +
fileName + ":" + nestedFileName + ":" +
entry.getName() + ": " + e.getMessage());
}
}
entry = zipStream.getNextEntry();
}
if ( parsedClass == null ) {
closeZipStream();
}
}
return parsedClass;
}
public JavaClass getNextClass() throws IOException, InterruptedException {
JavaClass parsedClass = getNextNestedClass();
if ( parsedClass == null ) {
while (entries.hasMoreElements()) {
if (Thread.interrupted()) throw new InterruptedException();
ZipEntry entry = (ZipEntry) entries.nextElement();
String name = entry.getName();
if (name.endsWith(".class")) {
try {
parsedClass = new ClassParser(zipFile.getInputStream(entry), name).parse();
break;
} catch (ClassFormatException e) {
throw new ClassFormatException("Invalid class file format for " +
fileName + ":" + name + ": " + e.getMessage());
}
} else if ( name.endsWith(".jar") || name.endsWith( ".zip" ) ) {
setZipStream(new ZipInputStream(zipFile.getInputStream(entry)),
name );
parsedClass = getNextNestedClass();
if ( parsedClass != null ) {
break;
}
} else if (name.endsWith(".java"))
containsSourceFiles = true;
}
}
return parsedClass;
}
public boolean containsSourceFiles() {
return containsSourceFiles;
}
}
/**
* ClassProducer for directories.
* The directory is scanned recursively for class files.
*/
private static class DirectoryClassProducer implements ClassProducer {
private Iterator<String> rfsIter;
private boolean containsSourceFiles;
public DirectoryClassProducer(String dirName) throws InterruptedException {
FileFilter filter = new FileFilter() {
public boolean accept(File file) {
String fileName = file.getName();
if (file.isDirectory() || fileName.endsWith(".class"))
return true;
if (fileName.endsWith(".java"))
containsSourceFiles = true;
return false;
}
};
// This will throw InterruptedException if the thread is
// interrupted.
RecursiveFileSearch rfs = new RecursiveFileSearch(dirName, filter).search();
this.rfsIter = rfs.fileNameIterator();
this.containsSourceFiles = false;
}
public JavaClass getNextClass() throws IOException, InterruptedException {
if (!rfsIter.hasNext())
return null;
String fileName = rfsIter.next();
try {
return new ClassParser(fileName).parse();
} catch (ClassFormatException e) {
throw new ClassFormatException("Invalid class file format for " +
fileName + ": " + e.getMessage());
}
}
public boolean containsSourceFiles() {
return containsSourceFiles;
}
}
/**
* A delegating bug reporter which counts reported bug instances,
* missing classes, and serious analysis errors.
*/
private static class ErrorCountingBugReporter extends DelegatingBugReporter {
private int bugCount;
private int missingClassCount;
private int errorCount;
private Set<String> missingClassSet = new HashSet<String>();
public ErrorCountingBugReporter(BugReporter realBugReporter) {
super(realBugReporter);
this.bugCount = 0;
this.missingClassCount = 0;
this.errorCount = 0;
// Add an observer to record when bugs make it through
// all priority and filter criteria, so our bug count is
// accurate.
realBugReporter.addObserver(new BugReporterObserver() {
public void reportBug(BugInstance bugInstance) {
++bugCount;
}
});
}
public int getBugCount() {
return bugCount;
}
public int getMissingClassCount() {
return missingClassCount;
}
public int getErrorCount() {
return errorCount;
}
public void logError(String message) {
++errorCount;
super.logError(message);
}
public void reportMissingClass(ClassNotFoundException ex) {
String missing = AbstractBugReporter.getMissingClassName(ex);
if (missingClassSet.add(missing))
++missingClassCount;
super.reportMissingClass(ex);
}
}
private static final boolean DEBUG = Boolean.getBoolean("findbugs.debug");
/** FindBugs home directory. */
private static String home;
private ErrorCountingBugReporter bugReporter;
private Project project;
private List<ClassObserver> classObserverList;
private Detector detectors [];
private FindBugsProgress progressCallback;
/**
* Constructor.
* @param bugReporter the BugReporter object that will be used to report
* BugInstance objects, analysis errors, class to source mapping, etc.
* @param project the Project indicating which files to analyze and
* the auxiliary classpath to use
*/
public FindBugs(BugReporter bugReporter, Project project) {
if (bugReporter == null)
throw new IllegalArgumentException("null bugReporter");
if (project == null)
throw new IllegalArgumentException("null project");
this.bugReporter = new ErrorCountingBugReporter(bugReporter);
this.project = project;
this.classObserverList = new LinkedList<ClassObserver>();
// Create a no-op progress callback.
this.progressCallback = new FindBugsProgress() {
public void reportNumberOfArchives(int numArchives) { }
public void finishArchive() { }
public void startAnalysis(int numClasses) { }
public void finishClass() { }
public void finishPerClassAnalysis() { }
};
addClassObserver(bugReporter);
}
/**
* Set the progress callback that will be used to keep track
* of the progress of the analysis.
* @param progressCallback the progress callback
*/
public void setProgressCallback(FindBugsProgress progressCallback) {
this.progressCallback = progressCallback;
}
/**
* Set filter of bug instances to include or exclude.
* @param filterFileName the name of the filter file
* @param include true if the filter specifies bug instances to include,
* false if it specifies bug instances to exclude
*/
public void setFilter(String filterFileName, boolean include) throws IOException, FilterException {
Filter filter = new Filter(filterFileName);
BugReporter origBugReporter = bugReporter.getRealBugReporter();
BugReporter filterBugReporter = new FilterBugReporter(origBugReporter, filter, include);
bugReporter.setRealBugReporter(filterBugReporter);
}
/**
* Add a ClassObserver.
* @param classObserver the ClassObserver
*/
public void addClassObserver(ClassObserver classObserver) {
classObserverList.add(classObserver);
}
/**
* Execute FindBugs on the Project.
* All bugs found are reported to the BugReporter object which was set
* when this object was constructed.
* @throws java.io.IOException if an I/O exception occurs analyzing one of the files
* @throws InterruptedException if the thread is interrupted while conducting the analysis
*/
public void execute() throws java.io.IOException, InterruptedException {
// Configure the analysis context
AnalysisContext analysisContext = AnalysisContext.instance();
analysisContext.setLookupFailureCallback(bugReporter);
analysisContext.setSourcePath(project.getSourceDirList());
// Create detectors, if required
if (detectors == null)
createDetectors();
clearRepository();
String[] argv = project.getJarFileArray();
progressCallback.reportNumberOfArchives(argv.length);
List<String> repositoryClassList = new LinkedList<String>();
for (int i = 0; i < argv.length; i++) {
addFileToRepository(argv[i], repositoryClassList);
}
progressCallback.startAnalysis(repositoryClassList.size());
// Examine all classes for bugs.
// Don't examine the same class more than once.
// (The user might specify two jar files that contain
// the same class.)
Set<String> examinedClassSet = new HashSet<String>();
for (Iterator<String> i = repositoryClassList.iterator(); i.hasNext(); ) {
String className = i.next();
if (examinedClassSet.add(className))
examineClass(className);
}
progressCallback.finishPerClassAnalysis();
this.reportFinal();
// Flush any queued bug reports
bugReporter.finish();
// Flush any queued error reports
bugReporter.reportQueuedErrors();
}
/**
* Get the number of bug instances that were reported during analysis.
*/
public int getBugCount() {
return bugReporter.getBugCount();
}
/**
* Get the number of errors that occurred during analysis.
*/
public int getErrorCount() {
return bugReporter.getErrorCount();
}
/**
* Get the number of time missing classes were reported during analysis.
*/
public int getMissingClassCount() {
return bugReporter.getMissingClassCount();
}
/**
* Set the FindBugs home directory.
*/
public static void setHome(String home) {
FindBugs.home = home;
}
/**
* Get the FindBugs home directory.
*/
public static String getHome() {
if (home == null) {
home = System.getProperty("findbugs.home");
if (home == null) {
System.err.println("Error: The findbugs.home property is not set!");
System.exit(1);
}
}
return home;
}
/**
* Create Detectors for each DetectorFactory which is enabled.
* This will populate the detectors array.
*/
private void createDetectors() {
ArrayList<Detector> result = new ArrayList<Detector>();
Iterator<DetectorFactory> i = DetectorFactoryCollection.instance().factoryIterator();
int count = 0;
while (i.hasNext()) {
DetectorFactory factory = i.next();
if (factory.isEnabled())
result.add(factory.create(bugReporter));
}
detectors = result.toArray(new Detector[0]);
}
/**
* Clear the Repository and update it to reflect the classpath
* specified by the current project.
*/
private void clearRepository() {
// Purge repository of previous contents
Repository.clearCache();
// Create a SyntheticRepository based on the current project,
// and make it current.
// Add aux class path entries specified in project
StringBuffer buf = new StringBuffer();
List auxClasspathEntryList = project.getAuxClasspathEntryList();
Iterator i = auxClasspathEntryList.iterator();
while (i.hasNext()) {
String entry = (String) i.next();
buf.append(entry);
buf.append(File.pathSeparatorChar);
}
// Add the system classpath entries
buf.append(ClassPath.getClassPath());
// Set up the Repository to use the combined classpath
ClassPath classPath = new ClassPath(buf.toString());
SyntheticRepository repository = SyntheticRepository.getInstance(classPath);
Repository.setRepository(repository);
}
/**
* Add all classes contained in given file to the BCEL Repository.
* @param fileName the file, which may be a jar/zip archive, a single class file,
* or a directory to be recursively searched for class files
*/
private void addFileToRepository(String fileName, List<String> repositoryClassList)
throws IOException, InterruptedException {
try {
ClassProducer classProducer;
// Create the ClassProducer
if (fileName.endsWith(".jar") || fileName.endsWith(".zip") || fileName.endsWith(".war") || fileName.endsWith(".ear"))
classProducer = new ZipClassProducer(fileName);
else if (fileName.endsWith(".class"))
classProducer = new SingleClassProducer(fileName);
else {
File dir = new File(fileName);
if (!dir.isDirectory())
throw new IOException("Path " + fileName + " is not an archive, class file, or directory");
classProducer = new DirectoryClassProducer(fileName);
}
// Load all referenced classes into the Repository
for (;;) {
if (Thread.interrupted())
throw new InterruptedException();
try {
JavaClass jclass = classProducer.getNextClass();
if (jclass == null)
break;
Repository.addClass(jclass);
repositoryClassList.add(jclass.getClassName());
} catch (ClassFormatException e) {
e.printStackTrace();
bugReporter.logError(e.getMessage());
}
}
progressCallback.finishArchive();
} catch (IOException e) {
// You'd think that the message for a FileNotFoundException would include
// the filename, but you'd be wrong. So, we'll add it explicitly.
throw new IOException("Could not analyze " + fileName + ": " + e.getMessage());
}
}
/**
* Examine a single class by invoking all of the Detectors on it.
* @param className the fully qualified name of the class to examine
*/
private void examineClass(String className) throws InterruptedException {
if (DEBUG) System.out.println("Examining class " + className);
try {
JavaClass javaClass = Repository.lookupClass(className);
// Notify ClassObservers
for (Iterator<ClassObserver> i = classObserverList.iterator(); i.hasNext(); ) {
i.next().observeClass(javaClass);
}
// Create a ClassContext for the class
ClassContext classContext = AnalysisContext.instance().getClassContext(javaClass);
// Run the Detectors
for (int i = 0; i < detectors.length; ++i) {
if (Thread.interrupted())
throw new InterruptedException();
try {
Detector detector = detectors[i];
if (DEBUG) System.out.println(" running " + detector.getClass().getName());
detector.visitClassContext(classContext);
} catch (AnalysisException e) {
reportRecoverableException(className, e);
} catch (ArrayIndexOutOfBoundsException e) {
reportRecoverableException(className, e);
}
}
} catch (ClassNotFoundException e) {
// This should never happen unless there are bugs in BCEL.
bugReporter.reportMissingClass(e);
reportRecoverableException(className, e);
} catch (ClassFormatException e) {
reportRecoverableException(className, e);
}
progressCallback.finishClass();
}
private void reportRecoverableException(String className, Exception e) {
if (DEBUG) { e.printStackTrace(); }
bugReporter.logError("Exception analyzing " + className + ": " + e.toString());
}
/**
* Call report() on all detectors, to give them a chance to
* report any accumulated bug reports.
*/
private void reportFinal() throws InterruptedException {
for (int i = 0; i < detectors.length; ++i) {
if (Thread.interrupted())
throw new InterruptedException();
detectors[i].report();
}
}
private static final int PRINTING_REPORTER = 0;
private static final int SORTING_REPORTER = 1;
private static final int XML_REPORTER = 2;
private static final int EMACS_REPORTER = 3;
public static void main(String argv[]) throws Exception
{
int bugReporterType = PRINTING_REPORTER;
Project project = new Project();
boolean quiet = false;
String filterFile = null;
boolean include = false;
boolean setExitCode = false;
int priorityThreshold = Detector.NORMAL_PRIORITY;
PrintStream outputStream = null;
// Process command line options
int argCount = 0;
while (argCount < argv.length) {
String option = argv[argCount];
if (!option.startsWith("-"))
break;
if (option.equals("-home")) {
++argCount;
if (argCount == argv.length) throw new IllegalArgumentException(option + " option requires argument");
String homeDir = argv[argCount];
FindBugs.setHome(homeDir);
} else if (option.equals("-pluginList")) {
++argCount;
if (argCount == argv.length) throw new IllegalArgumentException(option + " option requires argument");
String pluginListStr = argv[argCount];
ArrayList<File> pluginList = new ArrayList<File>();
StringTokenizer tok = new StringTokenizer(pluginListStr, File.pathSeparator);
while (tok.hasMoreTokens()) {
pluginList.add(new File(tok.nextToken()));
}
DetectorFactoryCollection.setPluginList((File[]) pluginList.toArray(new File[0]));
} else if (option.equals("-low"))
priorityThreshold = Detector.LOW_PRIORITY;
else if (option.equals("-medium"))
priorityThreshold = Detector.NORMAL_PRIORITY;
else if (option.equals("-high"))
priorityThreshold = Detector.HIGH_PRIORITY;
else if (option.equals("-sortByClass"))
bugReporterType = SORTING_REPORTER;
else if (option.equals("-xml"))
bugReporterType = XML_REPORTER;
else if (option.equals("-emacs"))
bugReporterType = EMACS_REPORTER;
else if (option.equals("-outputFile")) {
++argCount;
if (argCount == argv.length) throw new IllegalArgumentException(option + " option requires argument");
String outputFile = argv[argCount];
try {
outputStream = new PrintStream(new BufferedOutputStream(new FileOutputStream(outputFile)));
} catch (IOException e) {
System.err.println("Couldn't open " + outputFile + " for output: " + e.toString());
System.exit(1);
}
} else if (option.equals("-visitors") || option.equals("-omitVisitors")) {
++argCount;
if (argCount == argv.length) throw new IllegalArgumentException(option + " option requires argument");
boolean omit = option.equals("-omitVisitors");
if (!omit) {
// Selecting detectors explicitly, so start out by
// disabling all of them. The selected ones will
// be re-enabled.
Iterator<DetectorFactory> factoryIter =
DetectorFactoryCollection.instance().factoryIterator();
while (factoryIter.hasNext()) {
DetectorFactory factory = factoryIter.next();
factory.setEnabled(false);
}
}
// Explicitly enable or disable the selected detectors.
StringTokenizer tok = new StringTokenizer(argv[argCount], ",");
while (tok.hasMoreTokens()) {
String visitorName = tok.nextToken();
DetectorFactory factory = DetectorFactoryCollection.instance().getFactory(visitorName);
if (factory == null)
throw new IllegalArgumentException("Unknown detector: " + visitorName);
factory.setEnabled(!omit);
}
} else if (option.equals("-exclude") || option.equals("-include")) {
++argCount;
if (argCount == argv.length) throw new IllegalArgumentException(option + " option requires argument");
filterFile = argv[argCount];
include = option.equals("-include");
} else if (option.equals("-quiet")) {
quiet = true;
} else if (option.equals("-auxclasspath")) {
++argCount;
if (argCount == argv.length)
throw new IllegalArgumentException(option + " option requires argument");
String auxClassPath = argv[argCount];
StringTokenizer tok = new StringTokenizer(auxClassPath, File.pathSeparator);
while (tok.hasMoreTokens())
project.addAuxClasspathEntry(tok.nextToken());
} else if (option.equals("-sourcepath")) {
++argCount;
if (argCount == argv.length)
throw new IllegalArgumentException(option + " option requires argument");
String sourcePath = argv[argCount];
StringTokenizer tok = new StringTokenizer(sourcePath, File.pathSeparator);
while (tok.hasMoreTokens()) {
project.addSourceDir(new File(tok.nextToken()).getAbsolutePath());
}
} else if (option.equals("-project")) {
++argCount;
if (argCount == argv.length)
throw new IllegalArgumentException(option + " option requires argument");
String projectFile = argv[argCount];
// Convert project file to be an absolute path
projectFile = new File(projectFile).getAbsolutePath();
try {
project = new Project(projectFile);
project.read(new BufferedInputStream(new FileInputStream(projectFile)));
} catch (IOException e) {
System.err.println("Error opening " + projectFile);
e.printStackTrace(System.err);
throw e;
}
} else if (option.equals("-exitcode")) {
setExitCode = true;
} else
throw new IllegalArgumentException("Unknown option: [" + option + "]");
++argCount;
}
if (argCount == argv.length && project.getNumJarFiles() == 0) {
InputStream in = FindBugs.class.getClassLoader().getResourceAsStream("USAGE");
if (in == null) {
System.out.println("FindBugs tool, version " + Version.RELEASE);
System.out.println("usage: java -jar findbugs.jar [options] <classfiles, zip/jar files, or directories>");
System.out.println("Example: java -jar findbugs.jar rt.jar");
System.out.println("Options:");
System.out.println(" -home <home directory> specify FindBugs home directory");
System.out.println(" -pluginList <jar1>" + File.pathSeparatorChar + "<jar2>... " +
"specify list of plugin Jar files to load");
System.out.println(" -quiet suppress error messages");
System.out.println(" -low report all bugs");
System.out.println(" -medium report medium and high priority bugs [default]");
System.out.println(" -high report high priority bugs only");
System.out.println(" -sortByClass sort bug reports by class");
System.out.println(" -xml XML output");
System.out.println(" -emacs Use emacs reporting format");
System.out.println(" -outputFile <filename> Save output in named file");
System.out.println(" -visitors <v1>,<v2>,... run only named visitors");
System.out.println(" -omitVisitors <v1>,<v2>,... omit named visitors");
System.out.println(" -exclude <filter file> exclude bugs matching given filter");
System.out.println(" -include <filter file> include only bugs matching given filter");
System.out.println(" -auxclasspath <classpath> set aux classpath for analysis");
System.out.println(" -sourcepath path in which source files are found");
System.out.println(" -project <project> analyze given project");
System.out.println(" -exitcode set exit code of process");
}
else
IO.copy(in,System.out);
return;
}
TextUIBugReporter bugReporter = null;
switch (bugReporterType) {
case PRINTING_REPORTER:
bugReporter = new PrintingBugReporter(); break;
case SORTING_REPORTER:
bugReporter = new SortingBugReporter(); break;
case XML_REPORTER:
bugReporter = new XMLBugReporter(project); break;
case EMACS_REPORTER:
bugReporter = new EmacsBugReporter(); break;
default:
throw new IllegalStateException();
}
if (quiet)
bugReporter.setErrorVerbosity(BugReporter.SILENT);
bugReporter.setPriorityThreshold(priorityThreshold);
if (outputStream != null)
bugReporter.setOutputStream(outputStream);
for (int i = argCount; i < argv.length; ++i)
project.addJar(argv[i]);
FindBugs findBugs = new FindBugs(bugReporter, project);
if (filterFile != null)
findBugs.setFilter(filterFile, include);
findBugs.execute();
int bugCount = findBugs.getBugCount();
int missingClassCount = findBugs.getMissingClassCount();
int errorCount = findBugs.getErrorCount();
if (!quiet || setExitCode) {
if (bugCount > 0)
System.err.println("Warnings generated: " + bugCount);
if (missingClassCount > 0)
System.err.println("Missing classes: " + missingClassCount);
if (errorCount > 0)
System.err.println("Analysis errors: " + errorCount);
}
if (setExitCode) {
int exitCode = 0;
if (errorCount > 0)
exitCode |= ERROR_FLAG;
if (missingClassCount > 0)
exitCode |= MISSING_CLASS_FLAG;
if (bugCount > 0)
exitCode |= BUGS_FOUND_FLAG;
System.exit(exitCode);
}
}
} |
/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 et: */
package jp.oist.flint.form;
import jp.oist.flint.desktop.Desktop;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class ModelLoaderLogger implements IFrame {
private final ArrayList<String> mLines = new ArrayList<>();
private final Desktop mDesktop;
public ModelLoaderLogger(Desktop desktop) {
mDesktop = desktop;
}
public Desktop getDesktop() {
return mDesktop;
}
@Override
public void appendLog(String s) {
mLines.add(s);
}
@Override
public void showErrorDialog(String message, String title) {
JTextArea textArea = new JTextArea(message);
textArea.setEditable(false);
textArea.append(System.getProperty("line.separator"));
for (String line : mLines) {
textArea.append(System.getProperty("line.separator"));
textArea.append(line);
}
final JScrollPane scrollPane = new JScrollPane(textArea);
// Trick for a resizeable JOptionPane dialog from:
scrollPane.addHierarchyListener(new HierarchyListener() {
@Override
public void hierarchyChanged(HierarchyEvent e) {
Window window = SwingUtilities.getWindowAncestor(scrollPane);
if (window instanceof Dialog) {
Dialog dialog = (Dialog)window;
if (!dialog.isResizable())
dialog.setResizable(true);
}
}
});
scrollPane.setPreferredSize(new Dimension(400, 100));
JOptionPane.showMessageDialog(mDesktop.getPane(), scrollPane, title, JOptionPane.ERROR_MESSAGE);
}
} |
package jolie.lang.parse;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Logger;
import jolie.lang.Constants.OperandType;
import jolie.lang.parse.ast.AndConditionNode;
import jolie.lang.parse.ast.AssignStatement;
import jolie.lang.parse.ast.CompareConditionNode;
import jolie.lang.parse.ast.CompensateStatement;
import jolie.lang.parse.ast.ConstantIntegerExpression;
import jolie.lang.parse.ast.ConstantRealExpression;
import jolie.lang.parse.ast.ConstantStringExpression;
import jolie.lang.parse.ast.CorrelationSetInfo;
import jolie.lang.parse.ast.CurrentHandlerStatement;
import jolie.lang.parse.ast.DeepCopyStatement;
import jolie.lang.parse.ast.EmbeddedServiceNode;
import jolie.lang.parse.ast.ExecutionInfo;
import jolie.lang.parse.ast.ExitStatement;
import jolie.lang.parse.ast.ExpressionConditionNode;
import jolie.lang.parse.ast.ForEachStatement;
import jolie.lang.parse.ast.ForStatement;
import jolie.lang.parse.ast.IfStatement;
import jolie.lang.parse.ast.InstallFixedVariableExpressionNode;
import jolie.lang.parse.ast.InstallStatement;
import jolie.lang.parse.ast.IsTypeExpressionNode;
import jolie.lang.parse.ast.LinkInStatement;
import jolie.lang.parse.ast.LinkOutStatement;
import jolie.lang.parse.ast.NDChoiceStatement;
import jolie.lang.parse.ast.NotConditionNode;
import jolie.lang.parse.ast.NotificationOperationStatement;
import jolie.lang.parse.ast.NullProcessStatement;
import jolie.lang.parse.ast.OLSyntaxNode;
import jolie.lang.parse.ast.OneWayOperationDeclaration;
import jolie.lang.parse.ast.OneWayOperationStatement;
import jolie.lang.parse.ast.OperationDeclaration;
import jolie.lang.parse.ast.OrConditionNode;
import jolie.lang.parse.ast.OutputPortInfo;
import jolie.lang.parse.ast.ParallelStatement;
import jolie.lang.parse.ast.PointerStatement;
import jolie.lang.parse.ast.PostDecrementStatement;
import jolie.lang.parse.ast.PostIncrementStatement;
import jolie.lang.parse.ast.PreDecrementStatement;
import jolie.lang.parse.ast.PreIncrementStatement;
import jolie.lang.parse.ast.ProductExpressionNode;
import jolie.lang.parse.ast.Program;
import jolie.lang.parse.ast.RequestResponseOperationDeclaration;
import jolie.lang.parse.ast.RequestResponseOperationStatement;
import jolie.lang.parse.ast.RunStatement;
import jolie.lang.parse.ast.Scope;
import jolie.lang.parse.ast.SequenceStatement;
import jolie.lang.parse.ast.InputPortInfo;
import jolie.lang.parse.ast.SolicitResponseOperationStatement;
import jolie.lang.parse.ast.DefinitionCallStatement;
import jolie.lang.parse.ast.DefinitionNode;
import jolie.lang.parse.ast.InterfaceDefinition;
import jolie.lang.parse.ast.SpawnStatement;
import jolie.lang.parse.ast.SumExpressionNode;
import jolie.lang.parse.ast.SynchronizedStatement;
import jolie.lang.parse.ast.ThrowStatement;
import jolie.lang.parse.ast.TypeCastExpressionNode;
import jolie.lang.parse.ast.UndefStatement;
import jolie.lang.parse.ast.ValueVectorSizeExpressionNode;
import jolie.lang.parse.ast.VariableExpressionNode;
import jolie.lang.parse.ast.VariablePathNode;
import jolie.lang.parse.ast.WhileStatement;
import jolie.lang.parse.ast.types.TypeDefinition;
import jolie.lang.parse.ast.types.TypeDefinitionLink;
import jolie.lang.parse.ast.types.TypeInlineDefinition;
import jolie.util.Pair;
/**
* Checks the well-formedness and validity of a JOLIE program.
* @see Program
* @author Fabrizio Montesi
*/
public class SemanticVerifier implements OLVisitor
{
private final Program program;
private boolean valid = true;
private final Map< String, InputPortInfo > inputPorts = new HashMap< String, InputPortInfo >();
private final Map< String, OutputPortInfo > outputPorts = new HashMap< String, OutputPortInfo >();
private final Set< String > subroutineNames = new HashSet< String > ();
private final Map< String, OneWayOperationDeclaration > oneWayOperations =
new HashMap< String, OneWayOperationDeclaration >();
private final Map< String, RequestResponseOperationDeclaration > requestResponseOperations =
new HashMap< String, RequestResponseOperationDeclaration >();
private boolean insideInputPort = false;
private boolean mainDefined = false;
private final Logger logger = Logger.getLogger( "JOLIE" );
private final Map< String, TypeDefinition > definedTypes = OLParser.createTypeDeclarationMap();
//private TypeDefinition rootType; // the type representing the whole session state
private final Map< String, Boolean > isConstantMap = new HashMap< String, Boolean >();
public SemanticVerifier( Program program )
{
this.program = program;
/*rootType = new TypeInlineDefinition(
new ParsingContext(),
"#RootType",
NativeType.VOID,
jolie.lang.Constants.RANGE_ONE_TO_ONE
);*/
}
private void encounteredAssignment( String varName )
{
if ( isConstantMap.containsKey( varName ) ) {
isConstantMap.put( varName, false );
} else {
isConstantMap.put( varName, true );
}
}
private void encounteredAssignment( VariablePathNode path )
{
encounteredAssignment( ((ConstantStringExpression)path.path().get( 0 ).key()).value() );
}
public Map< String, Boolean > isConstantMap()
{
return isConstantMap;
}
private void warning( OLSyntaxNode node, String message )
{
if ( node == null ) {
logger.warning( message );
} else {
logger.warning( node.context().sourceName() + ":" + node.context().line() + ": " + message );
}
}
private void error( OLSyntaxNode node, String message )
{
valid = false;
if ( node != null ) {
ParsingContext context = node.context();
logger.severe( context.sourceName() + ":" + context.line() + ": " + message );
} else {
logger.severe( message );
}
}
public boolean validate()
{
program.accept( this );
if ( mainDefined == false ) {
error( null, "Main procedure not defined" );
}
if ( !valid ) {
logger.severe( "Aborting: input file semantically invalid." );
return false;
}
return valid;
}
private boolean isTopLevelType = true;
public void visit( TypeInlineDefinition n )
{
checkCardinality( n );
boolean backupRootType = isTopLevelType;
if ( isTopLevelType ) {
// Check if the type has already been defined with a different structure
TypeDefinition type = definedTypes.get( n.id() );
if ( type != null && type.equals( n ) == false ) {
error( n, "type " + n.id() + " has already been defined with a different structure" );
}
}
isTopLevelType = false;
if ( n.hasSubTypes() ) {
for( Entry< String, TypeDefinition > entry : n.subTypes() ) {
entry.getValue().accept( this );
}
}
isTopLevelType = backupRootType;
if ( isTopLevelType ) {
definedTypes.put( n.id(), n );
}
}
public void visit( TypeDefinitionLink n )
{
checkCardinality( n );
if ( n.isValid() == false ) {
error( n, "type " + n.id() + " points to an undefined type" );
}
if ( isTopLevelType ) {
// Check if the type has already been defined with a different structure
TypeDefinition type = definedTypes.get( n.id() );
if ( type != null && type.equals( n ) == false ) {
error( n, "type " + n.id() + " has already been defined with a different structure" );
}
definedTypes.put( n.id(), n );
}
}
private void checkCardinality( TypeDefinition type )
{
if ( type.cardinality().min() < 0 ) {
error( type, "type " + type.id() + " specifies an invalid minimum range value (must be positive)" );
}
if ( type.cardinality().max() < 0 ) {
error( type, "type " + type.id() + " specifies an invalid maximum range value (must be positive)" );
}
}
public void visit( SpawnStatement n )
{
n.body().accept( this );
}
public void visit( Program n )
{
for( OLSyntaxNode node : n.children() ) {
node.accept( this );
}
}
public void visit( VariablePathNode n )
{}
public void visit( InputPortInfo n )
{
if ( inputPorts.get( n.id() ) != null ) {
error( n, "input port " + n.id() + " has been already defined" );
}
inputPorts.put( n.id(), n );
insideInputPort = true;
Set< String > opSet = new HashSet< String >();
for( OperationDeclaration op : n.operations() ) {
if ( opSet.contains( op.id() ) ) {
error( n, "input port " + n.id() + " declares operation " + op.id() + " multiple times" );
} else {
opSet.add( op.id() );
op.accept( this );
}
}
OutputPortInfo outputPort;
for( String portName : n.aggregationList() ) {
outputPort = outputPorts.get( portName );
if ( outputPort == null ) {
error( n, "input port " + n.id() + " aggregates an undefined output port (" + portName + ")" );
} else {
for( OperationDeclaration op : outputPort.operations() ) {
if ( opSet.contains( op.id() ) ) {
error( n, "input port " + n.id() + " declares duplicate operation " + op.id() + " from aggregated output port " + outputPort.id() );
} else {
opSet.add( op.id() );
}
}
}
}
insideInputPort = false;
}
public void visit( OutputPortInfo n )
{
if ( outputPorts.get( n.id() ) != null )
error( n, "output port " + n.id() + " has been already defined" );
outputPorts.put( n.id(), n );
encounteredAssignment( n.id() );
for( OperationDeclaration op : n.operations() ) {
op.accept( this );
}
}
public void visit( OneWayOperationDeclaration n )
{
if ( definedTypes.get( n.requestType().id() ) == null ) {
error( n, "unknown type: " + n.requestType().id() );
}
if ( insideInputPort ) { // Input operation
if ( oneWayOperations.containsKey( n.id() ) ) {
OneWayOperationDeclaration other = oneWayOperations.get( n.id() );
if ( n.requestType().equals( other.requestType() ) == false ) {
error( n, "input operations sharing the same name cannot declare different types (One-Way operation " + n.id() + ")" );
}
} else {
oneWayOperations.put( n.id(), n );
}
}
}
public void visit( RequestResponseOperationDeclaration n )
{
if ( definedTypes.get( n.requestType().id() ) == null ) {
error( n, "unknown type: " + n.requestType().id() );
}
if ( definedTypes.get( n.responseType().id() ) == null ) {
error( n, "unknown type: " + n.requestType().id() );
}
for( Entry< String, TypeDefinition > fault : n.faults().entrySet() ) {
if ( definedTypes.containsKey( fault.getValue().id() ) == false ) {
error( n, "unknown type for fault " + fault.getKey() );
}
}
if ( insideInputPort ) { // Input operation
if ( requestResponseOperations.containsKey( n.id() ) ) {
RequestResponseOperationDeclaration other = requestResponseOperations.get( n.id() );
checkEqualness( n, other );
} else {
requestResponseOperations.put( n.id(), n );
}
}
}
private void checkEqualness( RequestResponseOperationDeclaration n, RequestResponseOperationDeclaration other )
{
if ( n.requestType().equals( other.requestType() ) == false ) {
error( n, "input operations sharing the same name cannot declare different request types (Request-Response operation " + n.id() + ")" );
}
if ( n.responseType().equals( other.responseType() ) == false ) {
error( n, "input operations sharing the same name cannot declare different response types (Request-Response operation " + n.id() + ")" );
}
if ( n.faults().size() != other.faults().size() ) {
error( n, "input operations sharing the same name cannot declared different fault types (Request-Response operation " + n.id() );
}
for( Entry< String, TypeDefinition > fault : n.faults().entrySet() ) {
if ( fault.getValue() != null ) {
if ( !other.faults().containsKey( fault.getKey() ) || !other.faults().get( fault.getKey() ).equals( fault.getValue() ) ) {
error( n, "input operations sharing the same name cannot declared different fault types (Request-Response operation " + n.id() );
}
}
}
}
public void visit( DefinitionNode n )
{
if ( subroutineNames.contains( n.id() ) ) {
error( n, "Procedure " + n.id() + " uses an already defined identifier" );
} else {
subroutineNames.add( n.id() );
}
if ( "main".equals( n.id() ) ) {
mainDefined = true;
}
n.body().accept( this );
}
public void visit( ParallelStatement stm )
{
for( OLSyntaxNode node : stm.children() ) {
node.accept( this );
}
}
public void visit( SequenceStatement stm )
{
for( OLSyntaxNode node : stm.children() ) {
node.accept( this );
}
}
public void visit( NDChoiceStatement stm )
{
for( Pair< OLSyntaxNode, OLSyntaxNode > pair : stm.children() ) {
pair.key().accept( this );
pair.value().accept( this );
}
}
public void visit( NotificationOperationStatement n )
{
OutputPortInfo p = outputPorts.get( n.outputPortId() );
if ( p == null ) {
error( n, n.outputPortId() + " is not a valid output port" );
} else {
OperationDeclaration decl = p.operationsMap().get( n.id() );
if ( decl == null )
error( n, "Operation " + n.id() + " has not been declared in output port type " + p.id() );
else if ( !( decl instanceof OneWayOperationDeclaration ) )
error( n, "Operation " + n.id() + " is not a valid one-way operation in output port " + p.id() );
}
}
public void visit( SolicitResponseOperationStatement n )
{
if ( n.inputVarPath() != null ) {
encounteredAssignment( n.inputVarPath() );
}
OutputPortInfo p = outputPorts.get( n.outputPortId() );
if ( p == null )
error( n, n.outputPortId() + " is not a valid output port" );
else {
OperationDeclaration decl = p.operationsMap().get( n.id() );
if ( decl == null )
error( n, "Operation " + n.id() + " has not been declared in output port " + p.id() );
else if ( !( decl instanceof RequestResponseOperationDeclaration ) )
error( n, "Operation " + n.id() + " is not a valid request-response operation in output port " + p.id() );
}
}
public void visit( ThrowStatement n )
{
verify( n.expression() );
}
public void visit( CompensateStatement n ) {}
public void visit( InstallStatement n )
{
for( Pair< String, OLSyntaxNode > pair : n.handlersFunction().pairs() ) {
pair.value().accept( this );
}
}
public void visit( Scope n )
{
n.body().accept( this );
}
public void visit( OneWayOperationStatement n )
{
verify( n.inputVarPath() );
}
public void visit( RequestResponseOperationStatement n )
{
verify( n.inputVarPath() );
verify( n.process() );
}
public void visit( LinkInStatement n ) {}
public void visit( LinkOutStatement n ) {}
public void visit( SynchronizedStatement n )
{
n.body().accept( this );
}
public void visit( AssignStatement n )
{
encounteredAssignment( n.variablePath() );
n.variablePath().accept( this );
n.expression().accept( this );
}
private void verify( OLSyntaxNode n )
{
if ( n != null ) {
n.accept( this );
}
}
public void visit( PointerStatement n )
{
encounteredAssignment( n.leftPath() );
n.leftPath().accept( this );
n.rightPath().accept( this );
}
public void visit( DeepCopyStatement n )
{
encounteredAssignment( n.leftPath() );
n.leftPath().accept( this );
n.rightPath().accept( this );
}
public void visit( IfStatement n )
{
for( Pair< OLSyntaxNode, OLSyntaxNode > choice : n.children() ) {
choice.key().accept( this );
choice.value().accept( this );
}
verify( n.elseProcess() );
}
public void visit( DefinitionCallStatement n ) {}
public void visit( WhileStatement n )
{
n.condition().accept( this );
n.body().accept( this );
}
public void visit( OrConditionNode n )
{
for( OLSyntaxNode node : n.children() ) {
node.accept( this );
}
}
public void visit( AndConditionNode n )
{
for( OLSyntaxNode node : n.children() ) {
node.accept( this );
}
}
public void visit( NotConditionNode n )
{
n.condition().accept( this );
}
public void visit( CompareConditionNode n )
{
n.leftExpression().accept( this );
n.rightExpression().accept( this );
}
public void visit( ExpressionConditionNode n )
{
n.expression().accept( this );
}
public void visit( ConstantIntegerExpression n ) {}
public void visit( ConstantRealExpression n ) {}
public void visit( ConstantStringExpression n ) {}
public void visit( ProductExpressionNode n )
{
for( Pair< OperandType, OLSyntaxNode > pair : n.operands() ) {
pair.value().accept( this );
}
}
public void visit( SumExpressionNode n )
{
for( Pair< OperandType, OLSyntaxNode > pair : n.operands() ) {
pair.value().accept( this );
}
}
public void visit( VariableExpressionNode n )
{
n.variablePath().accept( this );
}
public void visit( InstallFixedVariableExpressionNode n )
{
n.variablePath().accept( this );
}
public void visit( NullProcessStatement n ) {}
public void visit( ExitStatement n ) {}
public void visit( ExecutionInfo n ) {}
public void visit( CorrelationSetInfo n ) {}
public void visit( RunStatement n )
{
warning( n, "Run statement is not a stable feature yet." );
}
public void visit( ValueVectorSizeExpressionNode n )
{
n.variablePath().accept( this );
}
public void visit( PreIncrementStatement n )
{
encounteredAssignment( n.variablePath() );
n.variablePath().accept( this );
}
public void visit( PostIncrementStatement n )
{
encounteredAssignment( n.variablePath() );
n.variablePath().accept( this );
}
public void visit( PreDecrementStatement n )
{
encounteredAssignment( n.variablePath() );
n.variablePath().accept( this );
}
public void visit( PostDecrementStatement n )
{
encounteredAssignment( n.variablePath() );
n.variablePath().accept( this );
}
public void visit( UndefStatement n )
{
encounteredAssignment( n.variablePath() );
n.variablePath().accept( this );
}
public void visit( ForStatement n )
{
n.init().accept( this );
n.condition().accept( this );
n.post().accept( this );
n.body().accept( this );
}
public void visit( ForEachStatement n )
{
n.keyPath().accept( this );
n.targetPath().accept( this );
n.body().accept( this );
}
public void visit( IsTypeExpressionNode n )
{
n.variablePath().accept( this );
}
public void visit( TypeCastExpressionNode n )
{
n.expression().accept( this );
}
public void visit( EmbeddedServiceNode n )
{}
/**
* @todo Must check if it's inside an install function
*/
public void visit( CurrentHandlerStatement n )
{}
public void visit( InterfaceDefinition n )
{}
} |
package jolie.lang.parse;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Logger;
import jolie.lang.Constants.ExecutionMode;
import jolie.lang.Constants.OperandType;
import jolie.lang.Constants.OperationType;
import jolie.lang.parse.CorrelationFunctionInfo.CorrelationPairInfo;
import jolie.lang.parse.ast.AddAssignStatement;
import jolie.lang.parse.ast.AssignStatement;
import jolie.lang.parse.ast.CompareConditionNode;
import jolie.lang.parse.ast.CompensateStatement;
import jolie.lang.parse.ast.CorrelationSetInfo;
import jolie.lang.parse.ast.CorrelationSetInfo.CorrelationAliasInfo;
import jolie.lang.parse.ast.CurrentHandlerStatement;
import jolie.lang.parse.ast.DeepCopyStatement;
import jolie.lang.parse.ast.DefinitionCallStatement;
import jolie.lang.parse.ast.DefinitionNode;
import jolie.lang.parse.ast.DivideAssignStatement;
import jolie.lang.parse.ast.DocumentationComment;
import jolie.lang.parse.ast.EmbeddedServiceNode;
import jolie.lang.parse.ast.ExecutionInfo;
import jolie.lang.parse.ast.ExitStatement;
import jolie.lang.parse.ast.ForEachArrayItemStatement;
import jolie.lang.parse.ast.ForEachSubNodeStatement;
import jolie.lang.parse.ast.ForStatement;
import jolie.lang.parse.ast.IfStatement;
import jolie.lang.parse.ast.InputPortInfo;
import jolie.lang.parse.ast.InstallFixedVariableExpressionNode;
import jolie.lang.parse.ast.InstallStatement;
import jolie.lang.parse.ast.InterfaceDefinition;
import jolie.lang.parse.ast.InterfaceExtenderDefinition;
import jolie.lang.parse.ast.LinkInStatement;
import jolie.lang.parse.ast.LinkOutStatement;
import jolie.lang.parse.ast.MultiplyAssignStatement;
import jolie.lang.parse.ast.NDChoiceStatement;
import jolie.lang.parse.ast.NotificationOperationStatement;
import jolie.lang.parse.ast.NullProcessStatement;
import jolie.lang.parse.ast.OLSyntaxNode;
import jolie.lang.parse.ast.OneWayOperationDeclaration;
import jolie.lang.parse.ast.OneWayOperationStatement;
import jolie.lang.parse.ast.OperationDeclaration;
import jolie.lang.parse.ast.OutputPortInfo;
import jolie.lang.parse.ast.ParallelStatement;
import jolie.lang.parse.ast.PointerStatement;
import jolie.lang.parse.ast.PostDecrementStatement;
import jolie.lang.parse.ast.PostIncrementStatement;
import jolie.lang.parse.ast.PreDecrementStatement;
import jolie.lang.parse.ast.PreIncrementStatement;
import jolie.lang.parse.ast.Program;
import jolie.lang.parse.ast.ProvideUntilStatement;
import jolie.lang.parse.ast.RequestResponseOperationDeclaration;
import jolie.lang.parse.ast.RequestResponseOperationStatement;
import jolie.lang.parse.ast.RunStatement;
import jolie.lang.parse.ast.Scope;
import jolie.lang.parse.ast.SequenceStatement;
import jolie.lang.parse.ast.SolicitResponseOperationStatement;
import jolie.lang.parse.ast.SpawnStatement;
import jolie.lang.parse.ast.SubtractAssignStatement;
import jolie.lang.parse.ast.SynchronizedStatement;
import jolie.lang.parse.ast.ThrowStatement;
import jolie.lang.parse.ast.TypeCastExpressionNode;
import jolie.lang.parse.ast.UndefStatement;
import jolie.lang.parse.ast.ValueVectorSizeExpressionNode;
import jolie.lang.parse.ast.VariablePathNode;
import jolie.lang.parse.ast.WhileStatement;
import jolie.lang.parse.ast.courier.CourierChoiceStatement;
import jolie.lang.parse.ast.courier.CourierDefinitionNode;
import jolie.lang.parse.ast.courier.NotificationForwardStatement;
import jolie.lang.parse.ast.courier.SolicitResponseForwardStatement;
import jolie.lang.parse.ast.expression.AndConditionNode;
import jolie.lang.parse.ast.expression.ConstantBoolExpression;
import jolie.lang.parse.ast.expression.ConstantDoubleExpression;
import jolie.lang.parse.ast.expression.ConstantIntegerExpression;
import jolie.lang.parse.ast.expression.ConstantLongExpression;
import jolie.lang.parse.ast.expression.ConstantStringExpression;
import jolie.lang.parse.ast.expression.FreshValueExpressionNode;
import jolie.lang.parse.ast.expression.InlineTreeExpressionNode;
import jolie.lang.parse.ast.expression.InstanceOfExpressionNode;
import jolie.lang.parse.ast.expression.IsTypeExpressionNode;
import jolie.lang.parse.ast.expression.NotExpressionNode;
import jolie.lang.parse.ast.expression.OrConditionNode;
import jolie.lang.parse.ast.expression.ProductExpressionNode;
import jolie.lang.parse.ast.expression.SumExpressionNode;
import jolie.lang.parse.ast.expression.VariableExpressionNode;
import jolie.lang.parse.ast.expression.VoidExpressionNode;
import jolie.lang.parse.ast.types.TypeChoiceDefinition;
import jolie.lang.parse.ast.types.TypeDefinition;
import jolie.lang.parse.ast.types.TypeDefinitionLink;
import jolie.lang.parse.ast.types.TypeInlineDefinition;
import jolie.lang.parse.context.URIParsingContext;
import jolie.util.ArrayListMultiMap;
import jolie.util.MultiMap;
import jolie.util.Pair;
/**
* Checks the well-formedness and validity of a JOLIE program.
* @see Program
* @author Fabrizio Montesi
*/
public class SemanticVerifier implements OLVisitor
{
public static class Configuration {
private boolean checkForMain = true;
public void setCheckForMain( boolean checkForMain )
{
this.checkForMain = checkForMain;
}
public boolean checkForMain()
{
return checkForMain;
}
}
private final Program program;
private boolean valid = true;
private final SemanticException semanticException = new SemanticException();
private final Configuration configuration;
private ExecutionInfo executionInfo = new ExecutionInfo( URIParsingContext.DEFAULT, ExecutionMode.SINGLE );
private final Map< String, InputPortInfo > inputPorts = new HashMap<>();
private final Map< String, OutputPortInfo > outputPorts = new HashMap<>();
private final Set< String > subroutineNames = new HashSet<> ();
private final Map< String, OneWayOperationDeclaration > oneWayOperations =
new HashMap<>();
private final Map< String, RequestResponseOperationDeclaration > requestResponseOperations =
new HashMap<>();
private final Map< TypeDefinition, List< TypeDefinition > > typesToBeEqual = new HashMap<>();
private final Map< OneWayOperationDeclaration, List< OneWayOperationDeclaration > > owToBeEqual =
new HashMap<>();
private final Map< RequestResponseOperationDeclaration, List< RequestResponseOperationDeclaration > > rrToBeEqual =
new HashMap<>();
private final List< CorrelationSetInfo > correlationSets = new LinkedList<>();
private boolean insideInputPort = false;
private boolean insideInit = false;
private boolean mainDefined = false;
private CorrelationFunctionInfo correlationFunctionInfo = new CorrelationFunctionInfo();
private final MultiMap< String, String > inputTypeNameMap =
new ArrayListMultiMap<>(); // Maps type names to the input operations that use them
private ExecutionMode executionMode = ExecutionMode.SINGLE;
private static final Logger logger = Logger.getLogger( "JOLIE" );
private final Map< String, TypeDefinition > definedTypes;
private final List< TypeDefinitionLink > definedTypeLinks = new LinkedList<>();
//private TypeDefinition rootType; // the type representing the whole session state
private final Map< String, Boolean > isConstantMap = new HashMap<>();
private OperationType insideCourierOperationType = null;
public SemanticVerifier( Program program, Configuration configuration )
{
this.program = program;
this.definedTypes = OLParser.createTypeDeclarationMap( program.context() );
this.configuration = configuration;
/*rootType = new TypeInlineDefinition(
new ParsingContext(),
"#RootType",
NativeType.VOID,
jolie.lang.Constants.RANGE_ONE_TO_ONE
);*/
}
public SemanticVerifier( Program program )
{
this( program, new Configuration() );
}
public CorrelationFunctionInfo correlationFunctionInfo()
{
return correlationFunctionInfo;
}
public ExecutionMode executionMode()
{
return executionMode;
}
private void encounteredAssignment( String varName )
{
if ( isConstantMap.containsKey( varName ) ) {
isConstantMap.put( varName, false );
} else {
isConstantMap.put( varName, true );
}
}
private void addTypeEqualnessCheck( TypeDefinition key, TypeDefinition type )
{
List< TypeDefinition > toBeEqualList = typesToBeEqual.get( key );
if ( toBeEqualList == null ) {
toBeEqualList = new LinkedList<>();
typesToBeEqual.put( key, toBeEqualList );
}
toBeEqualList.add( type );
}
private void addOneWayEqualnessCheck( OneWayOperationDeclaration key, OneWayOperationDeclaration oneWay )
{
List< OneWayOperationDeclaration > toBeEqualList = owToBeEqual.get( key );
if ( toBeEqualList == null ) {
toBeEqualList = new LinkedList<>();
owToBeEqual.put( key, toBeEqualList );
}
toBeEqualList.add( oneWay );
}
private void addRequestResponseEqualnessCheck( RequestResponseOperationDeclaration key, RequestResponseOperationDeclaration requestResponse )
{
List< RequestResponseOperationDeclaration > toBeEqualList = rrToBeEqual.get( key );
if ( toBeEqualList == null ) {
toBeEqualList = new LinkedList<>();
rrToBeEqual.put( key, toBeEqualList );
}
toBeEqualList.add( requestResponse );
}
private void encounteredAssignment( VariablePathNode path )
{
try {
encounteredAssignment( ( ( ConstantStringExpression ) path.path().get( 0 ).key()).value() );
} catch ( ClassCastException e ){
error( path, path.toPrettyString() + " is an invalid path" );
}
}
public Map< String, Boolean > isConstantMap()
{
return isConstantMap;
}
private void warning( OLSyntaxNode node, String message )
{
if ( node == null ) {
logger.warning( message );
} else {
logger.warning( node.context().sourceName() + ":" + node.context().line() + ": " + message );
}
}
private void error( OLSyntaxNode node, String message )
{
valid = false;
semanticException.addSemanticError( node, message);
}
private void resolveLazyLinks()
{
for( TypeDefinitionLink l : definedTypeLinks ) {
l.setLinkedType( definedTypes.get( l.linkedTypeName() ) );
if ( l.linkedType() == null ) {
error( l, "type " + l.id() + " points to an undefined type (" + l.linkedTypeName() + ")" );
}
}
}
private void checkToBeEqualTypes()
{
for( Entry< TypeDefinition, List< TypeDefinition > > entry : typesToBeEqual.entrySet() ) {
for( TypeDefinition type : entry.getValue() ) {
if ( entry.getKey().isEquivalentTo( type ) == false ) {
error( type, "type " + type.id() + " has already been defined with a different structure" );
}
}
}
for( Entry< OneWayOperationDeclaration, List< OneWayOperationDeclaration > > entry : owToBeEqual.entrySet() ) {
for( OneWayOperationDeclaration ow : entry.getValue() ) {
checkEqualness( entry.getKey(), ow );
}
}
for( Entry< RequestResponseOperationDeclaration, List< RequestResponseOperationDeclaration > > entry : rrToBeEqual.entrySet() ) {
for( RequestResponseOperationDeclaration rr : entry.getValue() ) {
checkEqualness( entry.getKey(), rr );
}
}
}
private void checkCorrelationSets()
{
Collection< String > operations;
Set< String > correlatingOperations = new HashSet<>();
Set< String > currCorrelatingOperations = new HashSet<>();
for( CorrelationSetInfo cset : correlationSets ) {
correlationFunctionInfo.correlationSets().add( cset );
currCorrelatingOperations.clear();
for( CorrelationSetInfo.CorrelationVariableInfo csetVar : cset.variables() ) {
for( CorrelationAliasInfo alias : csetVar.aliases() ) {
checkCorrelationAlias( alias );
operations = inputTypeNameMap.get( alias.guardName() );
for( String operationName : operations ) {
currCorrelatingOperations.add( operationName );
correlationFunctionInfo.putCorrelationPair(
operationName,
new CorrelationPairInfo(
csetVar.correlationVariablePath(),
alias.variablePath()
)
);
}
}
}
for( String operationName : currCorrelatingOperations ) {
if ( correlatingOperations.contains( operationName ) ) {
error( cset, "Operation " + operationName +
" is specified on more than one correlation set. Each operation can correlate using only one correlation set."
);
} else {
correlatingOperations.add( operationName );
correlationFunctionInfo.operationCorrelationSetMap().put( operationName, cset );
correlationFunctionInfo.correlationSetOperations().put( cset, operationName );
}
}
}
Collection< CorrelationPairInfo > pairs;
for( Map.Entry< String, CorrelationSetInfo > entry : correlationFunctionInfo.operationCorrelationSetMap().entrySet() ) {
pairs = correlationFunctionInfo.getOperationCorrelationPairs( entry.getKey() );
if ( pairs.size() != entry.getValue().variables().size() ) {
error( entry.getValue(), "Operation " + entry.getKey() +
" has not an alias specified for every variable in the correlation set."
);
}
}
}
private void checkCorrelationAlias( CorrelationAliasInfo alias )
{
TypeDefinition type = definedTypes.get( alias.guardName() );
if ( type == null ) {
error( alias.variablePath(), "type " + alias.guardName() + " is undefined" );
} else if ( type.containsPath( alias.variablePath() ) == false ) {
error( alias.variablePath(), "type " + alias.guardName() + " does not contain the specified path" );
}
}
public void validate()
throws SemanticException
{
program.accept( this );
resolveLazyLinks();
checkToBeEqualTypes();
checkCorrelationSets();
if ( configuration.checkForMain && mainDefined == false ) {
error( null, "Main procedure not defined" );
}
if ( !valid ) {
logger.severe( "Aborting: input file semantically invalid." );
/* for( SemanticException.SemanticError e : semanticException.getErrorList() ){
logger.severe( e.getMessage() );
} */
throw semanticException;
}
}
private boolean isTopLevelType = true;
@Override
public void visit( TypeInlineDefinition n )
{
checkCardinality( n );
boolean backupRootType = isTopLevelType;
if ( isTopLevelType ) {
// Check if the type has already been defined with a different structure
TypeDefinition type = definedTypes.get( n.id() );
if ( type != null ) {
addTypeEqualnessCheck( type, n );
}
}
isTopLevelType = false;
if ( n.hasSubTypes() ) {
for( Entry< String, TypeDefinition > entry : n.subTypes() ) {
entry.getValue().accept( this );
}
}
isTopLevelType = backupRootType;
if ( isTopLevelType ) {
definedTypes.put( n.id(), n );
}
}
@Override
public void visit( TypeDefinitionLink n )
{
checkCardinality( n );
if ( isTopLevelType ) {
// Check if the type has already been defined with a different structure
TypeDefinition type = definedTypes.get( n.id() );
if ( type != null ) {
addTypeEqualnessCheck( type, n );
}
definedTypes.put( n.id(), n );
}
definedTypeLinks.add( n );
}
public void visit( TypeChoiceDefinition n )
{
checkCardinality( n );
boolean backupRootType = isTopLevelType;
if ( isTopLevelType ) {
// Check if the type has already been defined with a different structure
TypeDefinition type = definedTypes.get( n.id() );
if ( type != null ) {
addTypeEqualnessCheck( type, n );
}
}
isTopLevelType = false;
verify( n.left() );
verify( n.right() );
isTopLevelType = backupRootType;
if ( isTopLevelType ) {
definedTypes.put( n.id(), n );
}
}
private void checkCardinality( TypeDefinition type )
{
if ( type.cardinality().min() < 0 ) {
error( type, "type " + type.id() + " specifies an invalid minimum range value (must be positive)" );
}
if ( type.cardinality().max() < 0 ) {
error( type, "type " + type.id() + " specifies an invalid maximum range value (must be positive)" );
}
}
@Override
public void visit( SpawnStatement n )
{
n.body().accept( this );
}
@Override
public void visit( DocumentationComment n )
{}
@Override
public void visit( Program n )
{
for( OLSyntaxNode node : n.children() ) {
node.accept( this );
}
}
@Override
public void visit( VariablePathNode n )
{
if ( insideInit && n.isCSet() ) {
error( n, "Correlation variable access is forbidden in init procedures" );
}
if ( n.isCSet() && !n.isStatic() ) {
error( n, "Correlation paths must be statically defined" );
}
if ( !(n.path().get( 0 ).key() instanceof ConstantStringExpression) ) {
if ( n.isGlobal() ) {
error( n, "the global keyword in paths must be followed by an identifier" );
} else if ( n.isCSet() ) {
error( n, "the csets keyword in paths must be followed by an identifier" );
} else {
error( n, "paths must start with an identifier" );
}
}
}
@Override
public void visit( final InputPortInfo n )
{
if ( inputPorts.get( n.id() ) != null ) {
error( n, "input port " + n.id() + " has been already defined" );
}
inputPorts.put( n.id(), n );
insideInputPort = true;
Set< String > opSet = new HashSet<>();
for( OperationDeclaration op : n.operations() ) {
if ( opSet.contains( op.id() ) ) {
error( n, "input port " + n.id() + " declares operation " + op.id() + " multiple times" );
} else {
opSet.add( op.id() );
op.accept( this );
}
}
for( InputPortInfo.AggregationItemInfo item : n.aggregationList() ) {
for( String portName : item.outputPortList() ) {
final OutputPortInfo outputPort = outputPorts.get( portName );
if ( outputPort == null ) {
error( n, "input port " + n.id() + " aggregates an undefined output port (" + portName + ")" );
} else {
if ( item.interfaceExtender() != null ) {
outputPort.operations().forEach( opDecl -> {
final TypeDefinition requestType =
opDecl instanceof OneWayOperationDeclaration
? ((OneWayOperationDeclaration)opDecl).requestType()
: ((RequestResponseOperationDeclaration)opDecl).requestType();
if ( requestType instanceof TypeInlineDefinition == false ) {
error( n, "input port " + n.id()
+ " is trying to extend the type of operation " + opDecl.id()
+ " in output port " + outputPort.id()
+ " but such operation has an unsupported type structure (type reference or type choice)" );
} else if ( ((TypeInlineDefinition)requestType).untypedSubTypes() ) {
error( n,
"input port " + n.id()
+ " is trying to extend the type of operation " + opDecl.id()
+ " in output port " + outputPort.id()
+ " but such operation has undefined subnode types ({ ? } or undefined)" );
}
} );
}
}
/* else {
for( OperationDeclaration op : outputPort.operations() ) {
if ( opSet.contains( op.id() ) ) {
error( n, "input port " + n.id() + " declares duplicate operation " + op.id() + " from aggregated output port " + outputPort.id() );
} else {
opSet.add( op.id() );
}
}
}*/
}
}
insideInputPort = false;
}
@Override
public void visit( OutputPortInfo n )
{
if ( outputPorts.get( n.id() ) != null )
error( n, "output port " + n.id() + " has been already defined" );
outputPorts.put( n.id(), n );
encounteredAssignment( n.id() );
for( OperationDeclaration op : n.operations() ) {
op.accept( this );
}
}
@Override
public void visit( OneWayOperationDeclaration n )
{
if ( definedTypes.get( n.requestType().id() ) == null ) {
error( n, "unknown type: " + n.requestType().id() + " for operation " + n.id() );
}
if ( insideInputPort ) { // Input operation
if ( oneWayOperations.containsKey( n.id() ) ) {
OneWayOperationDeclaration other = oneWayOperations.get( n.id() );
addOneWayEqualnessCheck( n, other );
} else {
oneWayOperations.put( n.id(), n );
inputTypeNameMap.put( n.requestType().id(), n.id() );
}
}
}
@Override
public void visit( RequestResponseOperationDeclaration n )
{
if ( definedTypes.get( n.requestType().id() ) == null ) {
error( n, "unknown type: " + n.requestType().id() + " for operation " + n.id() );
}
if ( definedTypes.get( n.responseType().id() ) == null ) {
error( n, "unknown type: " + n.responseType().id() + " for operation " + n.id() );
}
for( Entry< String, TypeDefinition > fault : n.faults().entrySet() ) {
if ( definedTypes.containsKey( fault.getValue().id() ) == false ) {
error( n, "unknown type for fault " + fault.getKey() );
}
}
if ( insideInputPort ) { // Input operation
if ( requestResponseOperations.containsKey( n.id() ) ) {
RequestResponseOperationDeclaration other = requestResponseOperations.get( n.id() );
addRequestResponseEqualnessCheck( n, other );
} else {
requestResponseOperations.put( n.id(), n );
inputTypeNameMap.put( n.requestType().id(), n.id() );
}
}
}
private void checkEqualness( OneWayOperationDeclaration n, OneWayOperationDeclaration other )
{
if ( n.requestType().isEquivalentTo( other.requestType() ) == false ) {
error( n, "input operations sharing the same name cannot declare different request types (One-Way operation " + n.id() + ")" );
}
}
private void checkEqualness( RequestResponseOperationDeclaration n, RequestResponseOperationDeclaration other )
{
if ( n.requestType().isEquivalentTo( other.requestType() ) == false ) {
error( n, "input operations sharing the same name cannot declare different request types (Request-Response operation " + n.id() + ")" );
}
if ( n.responseType().isEquivalentTo( other.responseType() ) == false ) {
error( n, "input operations sharing the same name cannot declare different response types (Request-Response operation " + n.id() + ")" );
}
if ( n.faults().size() != other.faults().size() ) {
error( n, "input operations sharing the same name cannot declared different fault types (Request-Response operation " + n.id() );
}
for( Entry< String, TypeDefinition > fault : n.faults().entrySet() ) {
if ( fault.getValue() != null ) {
if ( !other.faults().containsKey( fault.getKey() ) || !other.faults().get( fault.getKey() ).isEquivalentTo( fault.getValue() ) ) {
error( n, "input operations sharing the same name cannot declared different fault types (Request-Response operation " + n.id() );
}
}
}
}
@Override
public void visit( DefinitionNode n )
{
if ( subroutineNames.contains( n.id() ) ) {
error( n, "Procedure " + n.id() + " uses an already defined identifier" );
} else {
subroutineNames.add( n.id() );
}
if ( "main".equals( n.id() ) ) {
mainDefined = true;
if ( executionInfo.mode() != ExecutionMode.SINGLE ) {
if ( ( n.body() instanceof NDChoiceStatement
|| n.body() instanceof RequestResponseOperationStatement
|| n.body() instanceof OneWayOperationStatement
) == false
) {
// The main body is not an input
if ( n.body() instanceof SequenceStatement ) {
OLSyntaxNode first = ((SequenceStatement)n.body()).children().get( 0 );
if ( (first instanceof RequestResponseOperationStatement
|| first instanceof OneWayOperationStatement) == false
) {
// The main body is not even a sequence starting with an input
error( n.body(),
"The first statement of the main procedure must be an input if the execution mode is not single"
);
}
} else {
// The main body is not even a sequence
error( n.body(),
"The first statement of the main procedure must be an input if the execution mode is not single"
);
}
}
}
}
if ( n.id().equals( "init" ) ) {
insideInit = true;
}
n.body().accept( this );
insideInit = false;
}
@Override
public void visit( ParallelStatement stm )
{
for( OLSyntaxNode node : stm.children() ) {
node.accept( this );
}
}
@Override
public void visit( SequenceStatement stm )
{
for( OLSyntaxNode node : stm.children() ) {
node.accept( this );
}
}
@Override
public void visit( NDChoiceStatement stm )
{
Set< String > operations = new HashSet<>();
String name = null;
for( Pair< OLSyntaxNode, OLSyntaxNode > pair : stm.children() ) {
if ( pair.key() instanceof OneWayOperationStatement ) {
name = ((OneWayOperationStatement)pair.key()).id();
} else if ( pair.key() instanceof RequestResponseOperationStatement ) {
name = ((RequestResponseOperationStatement)pair.key()).id();
} else {
error( pair.key(), "Input choices can contain only One-Way or Request-Response guards" );
}
if ( operations.contains( name ) ) {
error( pair.key(), "Input choices can not have duplicate input guards (input statement for operation " + name + ")" );
} else {
operations.add( name );
}
pair.key().accept( this );
pair.value().accept( this );
}
}
@Override
public void visit( NotificationOperationStatement n )
{
OutputPortInfo p = outputPorts.get( n.outputPortId() );
if ( p == null ) {
error( n, n.outputPortId() + " is not a valid output port" );
} else {
OperationDeclaration decl = p.operationsMap().get( n.id() );
if ( decl == null )
error( n, "Operation " + n.id() + " has not been declared in output port type " + p.id() );
else if ( !( decl instanceof OneWayOperationDeclaration ) )
error( n, "Operation " + n.id() + " is not a valid one-way operation in output port " + p.id() );
}
}
@Override
public void visit( SolicitResponseOperationStatement n )
{
if ( n.inputVarPath() != null ) {
encounteredAssignment( n.inputVarPath() );
}
OutputPortInfo p = outputPorts.get( n.outputPortId() );
if ( p == null ) {
error( n, n.outputPortId() + " is not a valid output port" );
} else {
OperationDeclaration decl = p.operationsMap().get( n.id() );
if ( decl == null ) {
error( n, "Operation " + n.id() + " has not been declared in output port " + p.id() );
} else if ( !(decl instanceof RequestResponseOperationDeclaration) ) {
error( n, "Operation " + n.id() + " is not a valid request-response operation in output port " + p.id() );
}
}
/*if ( n.inputVarPath() != null && n.inputVarPath().isCSet() ) {
error( n, "Receiving a message in a correlation variable is forbidden" );
}*/
}
@Override
public void visit( ThrowStatement n )
{
verify( n.expression() );
}
@Override
public void visit( CompensateStatement n ) {}
@Override
public void visit( InstallStatement n )
{
for( Pair< String, OLSyntaxNode > pair : n.handlersFunction().pairs() ) {
pair.value().accept( this );
}
}
@Override
public void visit( Scope n )
{
n.body().accept( this );
}
@Override
public void visit( OneWayOperationStatement n )
{
if ( insideCourierOperationType != null ) {
error( n, "input statements are forbidden inside courier definitions" );
}
verify( n.inputVarPath() );
if ( n.inputVarPath() != null ) {
if ( n.inputVarPath().isCSet() ) {
error( n, "Receiving a message in a correlation variable is forbidden" );
}
encounteredAssignment( n.inputVarPath() );
}
}
@Override
public void visit( RequestResponseOperationStatement n )
{
if ( insideCourierOperationType != null ) {
error( n, "input statements are forbidden inside courier definitions" );
}
verify( n.inputVarPath() );
verify( n.process() );
if ( n.inputVarPath() != null ) {
if ( n.inputVarPath().isCSet() ) {
error( n, "Receiving a message in a correlation variable is forbidden" );
}
encounteredAssignment( n.inputVarPath() );
}
}
@Override
public void visit( LinkInStatement n ) {}
@Override
public void visit( LinkOutStatement n ) {}
@Override
public void visit( SynchronizedStatement n )
{
n.body().accept( this );
}
@Override
public void visit( AssignStatement n )
{
n.variablePath().accept( this );
encounteredAssignment( n.variablePath() );
n.expression().accept( this );
}
@Override
public void visit( InstanceOfExpressionNode n )
{
n.expression().accept( this );
}
@Override
public void visit( AddAssignStatement n )
{
encounteredAssignment( n.variablePath() );
n.variablePath().accept( this );
n.expression().accept( this );
}
@Override
public void visit( SubtractAssignStatement n )
{
encounteredAssignment( n.variablePath() );
n.variablePath().accept( this );
n.expression().accept( this );
}
@Override
public void visit( MultiplyAssignStatement n )
{
encounteredAssignment( n.variablePath() );
n.variablePath().accept( this );
n.expression().accept( this );
}
@Override
public void visit( DivideAssignStatement n )
{
encounteredAssignment( n.variablePath() );
n.variablePath().accept( this );
n.expression().accept( this );
}
private void verify( OLSyntaxNode n )
{
if ( n != null ) {
n.accept( this );
}
}
@Override
public void visit( PointerStatement n )
{
encounteredAssignment( n.leftPath() );
encounteredAssignment( n.rightPath() );
n.leftPath().accept( this );
n.rightPath().accept( this );
if ( n.rightPath().isCSet() ) {
error( n, "Making an alias to a correlation variable is forbidden" );
}
}
@Override
public void visit( DeepCopyStatement n )
{
encounteredAssignment( n.leftPath() );
n.leftPath().accept( this );
n.rightExpression().accept( this );
if ( n.leftPath().isCSet() ) {
error( n, "Deep copy on a correlation variable is forbidden" );
}
}
@Override
public void visit( IfStatement n )
{
for( Pair< OLSyntaxNode, OLSyntaxNode > choice : n.children() ) {
verify( choice.key() );
verify( choice.value() );
}
verify( n.elseProcess() );
}
@Override
public void visit( DefinitionCallStatement n )
{
if ( !subroutineNames.contains( n.id() ) ) {
error( n, "Call to undefined definition: " + n.id() );
}
}
@Override
public void visit( WhileStatement n )
{
n.condition().accept( this );
n.body().accept( this );
}
@Override
public void visit( OrConditionNode n )
{
for( OLSyntaxNode node : n.children() ) {
node.accept( this );
}
}
@Override
public void visit( AndConditionNode n )
{
for( OLSyntaxNode node : n.children() ) {
node.accept( this );
}
}
@Override
public void visit( NotExpressionNode n )
{
n.expression().accept( this );
}
@Override
public void visit( CompareConditionNode n )
{
n.leftExpression().accept( this );
n.rightExpression().accept( this );
}
@Override
public void visit( ConstantIntegerExpression n ) {}
@Override
public void visit( ConstantDoubleExpression n ) {}
@Override
public void visit( ConstantStringExpression n ) {}
@Override
public void visit( ConstantLongExpression n ) {}
@Override
public void visit( ConstantBoolExpression n ) {}
@Override
public void visit( ProductExpressionNode n )
{
for( Pair< OperandType, OLSyntaxNode > pair : n.operands() ) {
pair.value().accept( this );
}
}
@Override
public void visit( SumExpressionNode n )
{
for( Pair< OperandType, OLSyntaxNode > pair : n.operands() ) {
pair.value().accept( this );
}
}
@Override
public void visit( VariableExpressionNode n )
{
n.variablePath().accept( this );
}
@Override
public void visit( InstallFixedVariableExpressionNode n )
{
n.variablePath().accept( this );
}
@Override
public void visit( NullProcessStatement n ) {}
@Override
public void visit( ExitStatement n ) {}
@Override
public void visit( ExecutionInfo n )
{
executionMode = n.mode();
executionInfo = n;
}
@Override
public void visit( CorrelationSetInfo n )
{
VariablePathSet pathSet = new VariablePathSet();
VariablePathNode path;
for( CorrelationSetInfo.CorrelationVariableInfo csetVar : n.variables() ) {
path = csetVar.correlationVariablePath();
if ( path.isGlobal() ) {
error( path, "Correlation variables can not be global" );
} else if ( path.isCSet() ) {
error( path, "Correlation variables can not be in the csets structure" );
} else {
if ( path.isStatic() == false ) {
error( path, "correlation variable paths can not make use of dynamic evaluation" );
}
}
if ( pathSet.contains( path ) ) {
error( path, "Duplicate correlation variable" );
} else {
pathSet.add( path );
}
for( CorrelationAliasInfo alias : csetVar.aliases() ) {
if ( alias.variablePath().isGlobal() ) {
error( alias.variablePath(), "Correlation variables can not be global" );
} else if ( path.isCSet() ) {
error( alias.variablePath(), "Correlation variables can not be in the csets structure" );
} else {
if ( alias.variablePath().isStatic() == false ) {
error( alias.variablePath(), "correlation variable path aliases can not make use of dynamic evaluation" );
}
}
}
}
correlationSets.add( n );
/*VariablePathNode varPath;
List< Pair< OLSyntaxNode, OLSyntaxNode > > path;
for( List< VariablePathNode > list : n.variables() ) {
varPath = list.get( 0 );
if ( varPath.isGlobal() ) {
error( list.get( 0 ), "Correlation variables can not be global" );
}
path = varPath.path();
if ( path.size() > 1 ) {
error( varPath, "Correlation variables can not be nested paths" );
} else if ( path.get( 0 ).value() != null ) {
error( varPath, "Correlation variables can not use arrays" );
} else {
correlationSet.add( ((ConstantStringExpression)path.get( 0 ).key()).value() );
}
}*/
}
@Override
public void visit( RunStatement n )
{
warning( n, "Run statement is not a stable feature yet." );
}
@Override
public void visit( ValueVectorSizeExpressionNode n )
{
n.variablePath().accept( this );
}
@Override
public void visit( InlineTreeExpressionNode n )
{
n.rootExpression().accept( this );
for( Pair< VariablePathNode, OLSyntaxNode > pair : n.assignments() ) {
pair.key().accept( this );
pair.value().accept( this );
}
}
@Override
public void visit( PreIncrementStatement n )
{
encounteredAssignment( n.variablePath() );
n.variablePath().accept( this );
}
@Override
public void visit( PostIncrementStatement n )
{
encounteredAssignment( n.variablePath() );
n.variablePath().accept( this );
}
@Override
public void visit( PreDecrementStatement n )
{
encounteredAssignment( n.variablePath() );
n.variablePath().accept( this );
}
@Override
public void visit( PostDecrementStatement n )
{
encounteredAssignment( n.variablePath() );
n.variablePath().accept( this );
}
@Override
public void visit( UndefStatement n )
{
encounteredAssignment( n.variablePath() );
n.variablePath().accept( this );
if ( n.variablePath().isCSet() ) {
error( n, "Undefining a correlation variable is forbidden" );
}
}
@Override
public void visit( ForStatement n )
{
n.init().accept( this );
n.condition().accept( this );
n.post().accept( this );
n.body().accept( this );
}
@Override
public void visit( ForEachSubNodeStatement n )
{
n.keyPath().accept( this );
n.targetPath().accept( this );
n.body().accept( this );
}
@Override
public void visit(ForEachArrayItemStatement n) {
n.keyPath().accept( this );
n.targetPath().accept( this );
n.body().accept( this );
}
@Override
public void visit( IsTypeExpressionNode n )
{
n.variablePath().accept( this );
}
@Override
public void visit( TypeCastExpressionNode n )
{
n.expression().accept( this );
}
@Override
public void visit( EmbeddedServiceNode n ) {}
@Override
public void visit( InterfaceExtenderDefinition n ) {}
@Override
public void visit( CourierDefinitionNode n )
{
if ( inputPorts.containsKey( n.inputPortName() ) == false ) {
error( n, "undefined input port: " + n.inputPortName() );
}
verify( n.body() );
}
@Override
public void visit( CourierChoiceStatement n )
{
for( CourierChoiceStatement.InterfaceOneWayBranch branch : n.interfaceOneWayBranches() ) {
insideCourierOperationType = OperationType.ONE_WAY;
verify( branch.body );
}
for( CourierChoiceStatement.InterfaceRequestResponseBranch branch : n.interfaceRequestResponseBranches() ) {
insideCourierOperationType = OperationType.REQUEST_RESPONSE;
verify( branch.body );
}
for( CourierChoiceStatement.OperationOneWayBranch branch : n.operationOneWayBranches() ) {
insideCourierOperationType = OperationType.ONE_WAY;
verify( branch.body );
}
for( CourierChoiceStatement.OperationRequestResponseBranch branch : n.operationRequestResponseBranches() ) {
insideCourierOperationType = OperationType.REQUEST_RESPONSE;
verify( branch.body );
}
insideCourierOperationType = null;
}
/*
* todo: Check that the output port of the forward statement is right wrt the input port aggregation definition.
*/
@Override
public void visit( NotificationForwardStatement n )
{
if ( insideCourierOperationType == null ) {
error( n, "the forward statement may be used only inside a courier definition" );
} else if ( insideCourierOperationType != OperationType.ONE_WAY ) {
error( n, "forward statement is a notification, but is inside a request-response courier definition. Maybe you wanted to specify a solicit-response forward?" );
}
}
/**
* todo: Check that the output port of the forward statement is right wrt the input port aggregation definition.
*/
@Override
public void visit( SolicitResponseForwardStatement n )
{
if ( insideCourierOperationType == null ) {
error( n, "the forward statement may be used only inside a courier definition" );
} else if ( insideCourierOperationType != OperationType.REQUEST_RESPONSE ) {
error( n, "forward statement is a solicit-response, but is inside a one-way courier definition. Maybe you wanted to specify a notification forward?" );
}
}
/**
* todo: Must check if it's inside an install function
*/
@Override
public void visit( CurrentHandlerStatement n )
{}
@Override
public void visit( InterfaceDefinition n )
{}
@Override
public void visit( FreshValueExpressionNode n )
{}
@Override
public void visit( VoidExpressionNode n ) {}
@Override
public void visit( ProvideUntilStatement n )
{
if ( !( n.provide() instanceof NDChoiceStatement ) ) {
error( n, "provide branch is not an input choice" );
} else if ( !( n.until() instanceof NDChoiceStatement ) ) {
error( n, "until branch is not an input choice" );
}
NDChoiceStatement provide = (NDChoiceStatement) n.provide();
NDChoiceStatement until = (NDChoiceStatement) n.until();
NDChoiceStatement total = new NDChoiceStatement( n.context() );
total.children().addAll( provide.children() );
total.children().addAll( until.children() );
total.accept( this );
}
} |
package se.emilsjolander.flipview;
import android.annotation.TargetApi;
import android.os.Build;
import android.util.SparseArray;
import android.view.View;
public class Recycler {
static class Scrap {
View v;
boolean valid;
public Scrap(View scrap, boolean valid) {
this.v = scrap;
this.valid = valid;
}
}
/** Unsorted views that can be used by the adapter as a convert view. */
private SparseArray<Scrap>[] scraps;
private SparseArray<Scrap> currentScraps;
private int viewTypeCount;
void setViewTypeCount(int viewTypeCount) {
if (viewTypeCount < 1) {
throw new IllegalArgumentException("Can't have a viewTypeCount < 1");
}
// do nothing if the view type count has not changed.
if (currentScraps != null && viewTypeCount == scraps.length) {
return;
}
// noinspection unchecked
@SuppressWarnings("unchecked")
SparseArray<Scrap>[] scrapViews = new SparseArray[viewTypeCount];
for (int i = 0; i < viewTypeCount; i++) {
scrapViews[i] = new SparseArray<Scrap>();
}
this.viewTypeCount = viewTypeCount;
currentScraps = scrapViews[0];
this.scraps = scrapViews;
}
/** @return A view from the ScrapViews collection. These are unordered. */
Scrap getScrapView(int position, int viewType) {
if (viewTypeCount == 1) {
return retrieveFromScrap(currentScraps, position);
} else if (viewType >= 0 && viewType < scraps.length) {
return retrieveFromScrap(scraps[viewType], position);
}
return null;
}
/**
* Put a view into the ScrapViews list. These views are unordered.
*
* @param scrap
* The view to add
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
void addScrapView(View scrap, int position, int viewType) {
// create a new Scrap
Scrap item = new Scrap(scrap, true);
if (viewTypeCount == 1) {
currentScraps.put(position, item);
} else {
scraps[viewType].put(position, item);
}
if (Build.VERSION.SDK_INT >= 14) {
scrap.setAccessibilityDelegate(null);
}
}
static Scrap retrieveFromScrap(SparseArray<Scrap> scrapViews, int position) {
int size = scrapViews.size();
if (size > 0) {
// See if we still have a view for this position.
Scrap result = scrapViews.get(position, null);
if (result != null) {
scrapViews.remove(position);
return result;
}
int index = size - 1;
result = scrapViews.valueAt(index);
scrapViews.removeAt(index);
result.valid = false;
return result;
}
return null;
}
void invalidateScraps() {
for (SparseArray<Scrap> array : scraps) {
for (int i = 0; i < array.size(); i++) {
array.valueAt(i).valid = false;
}
}
}
} |
package me.shoutto.sdk;
import android.util.Log;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import me.shoutto.sdk.internal.PendingApiObjectChange;
/**
* This class represents a Shout to Me user entity. A Shout to Me User entity is generally used
* by client apps to enable push notifications, get and set various properties and preferences,
* and to access the user's auth token in the event the client app wants to call the Shout to Me REST API directly.
*/
public class User extends StmBaseEntity {
/**
* The base endpoint of users on the Shout to Me REST API.
*/
public static final String BASE_ENDPOINT = "/users";
/**
* The key used for JSON serialization of conversation objects.
*/
public static final String SERIALIZATION_KEY = "user";
private String authToken;
private List<String> channelSubscriptions;
private String email;
private String handle;
private String phone;
private String platformEndpointArn;
private Boolean platformEndpointEnabled;
private List<String> topicPreferences;
private transient boolean isInitialized = false;
/**
* A constructor that allows setting <code>StmService</code> which is used for context and other
* SDK functionality.
* @param stmService the Shout to Me service
*/
public User(StmService stmService) {
super(stmService, SERIALIZATION_KEY, BASE_ENDPOINT);
}
public User() { super(SERIALIZATION_KEY, BASE_ENDPOINT); }
public boolean isInitialized() {
return isInitialized;
}
void setIsInitialized(boolean isInitialized) {
this.isInitialized = isInitialized;
}
String getAuthToken() {
return authToken;
}
/**
* Sets the auth token to be used in requests to the Shout to Me service.
* @param authToken the auth token
*/
public void setAuthToken(String authToken) {
this.authToken = authToken;
}
public List<String> getChannelSubscriptions() {
return channelSubscriptions;
}
public void setChannelSubscriptions(List<String> channelSubscriptions) {
this.channelSubscriptions = channelSubscriptions;
}
/**
* Gets the user's email address
* @return The user's email address
*/
public String getEmail() {
return email;
}
/**
* Sets the user's email address
* @param email The user's email address
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Gets the user's handle.
* @return The user's handle.
*/
public String getHandle() {
return handle;
}
/**
* Sets the user's handle.
* @param handle The user's handle.
*/
public void setHandle(String handle) {
pendingChanges.put("handle", new PendingApiObjectChange("handle", handle, this.handle));
this.handle = handle;
}
/**
* Gets the <code>Date</code> of the last time the user read messages.
* @return The <code>Date</code> representing the last time the user read their messages.
*
* @deprecated This property is no longer used
*/
@SuppressWarnings("unused")
@Deprecated
public Date getLastReadMessagesDate() {
return null;
}
/**
* Sets the <code>Date</code> of the last time the user read their messages.
* @param lastReadMessagesDate The <code>Date</code> representing the last time the user read their messages.
*
* @deprecated This property is no longer used
*/
@Deprecated
public void setLastReadMessagesDate(Date lastReadMessagesDate) {
// Stubbed for backwards compatibility but does not do anything
}
/**
* Gets the user's phone number
* @return The user's phone number
*/
public String getPhone() {
return phone;
}
/**
* Sets the user's phone number
* @param phone The user's phone number
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
* Gets the platform endpoint ARN. This is the unique ID that the Shout to Me system uses to
* send push notifications.
* @return The platform endpoint ARN.
*/
public String getPlatformEndpointArn() {
return platformEndpointArn;
}
void setPlatformEndpointArn(String platformEndpointArn) {
pendingChanges.put("platform_endpoint_arn",
new PendingApiObjectChange("platform_endpoing_arn", platformEndpointArn, this.platformEndpointArn));
this.platformEndpointArn = platformEndpointArn;
}
public Boolean getPlatformEndpointEnabled() {
return platformEndpointEnabled;
}
public void setPlatformEndpointEnabled(Boolean platformEndpointEnabled) {
this.platformEndpointEnabled = platformEndpointEnabled;
}
@Override
protected void adaptFromJson(JSONObject jsonObject) throws JSONException {
populateUserFieldsFromJson(jsonObject);
}
/**
* Gets the serialization type that is used in Gson parsing.
* @return The serialization type to be used in Gson parsing.
*/
@SuppressWarnings("unused")
public static Type getSerializationType() {
return new TypeToken<User>(){}.getType();
}
@Override
public Type getEntitySerializationType() {
return User.getSerializationType();
}
public List<String> getTopicPreferences() {
return topicPreferences;
}
public void setTopicPreferences(List<String> topicPreferences) {
this.topicPreferences = topicPreferences;
}
/**
* Sends an update request to save the <code>User</code> object to the Shout to Me platform.
* @deprecated This method has been moved to {@link StmService#updateUser(UpdateUserRequest, StmCallback)}
* @param callback The callback to be executed on completion of the request or null.
*/
@Deprecated
public void save(final StmCallback<User> callback) {
if (pendingChanges.size() == 0) {
return;
}
// Prepare request
JSONObject userUpdateJson = new JSONObject();
try {
Set<Map.Entry<String, PendingApiObjectChange>> entrySet = pendingChanges.entrySet();
for (Map.Entry<String, PendingApiObjectChange> entry : entrySet) {
if (entry.getValue() != null) {
userUpdateJson.put(entry.getKey(), entry.getValue().getNewValue());
}
}
} catch (JSONException ex) {
Log.w(TAG, "Could not prepare JSON for user update request. Aborting", ex);
callback.onError(new StmError("An error occurred trying to user",
false, StmError.SEVERITY_MINOR));
return;
}
Response.Listener<JSONObject> responseListener = new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
User user = null;
StmError stmError = null;
try {
JSONObject data = response.getJSONObject("data");
JSONObject userJson = data.getJSONObject("user");
try {
user = populateUserFieldsFromJson(userJson);
} catch(JSONException ex) {
Log.w(TAG, "Unable to populate user fields from JSON", ex);
stmError = new StmError("An error occurred trying to user", false,
StmError.SEVERITY_MINOR);
}
} catch(JSONException ex) {
Log.e(TAG, "Unable to parse user update response JSON", ex);
stmError = new StmError("An error occurred trying to user", false,
StmError.SEVERITY_MINOR);
} finally {
if (callback != null) {
if (stmError != null) {
rollbackPendingChanges();
callback.onError(stmError);
} else {
callback.onResponse(user);
}
}
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
rollbackPendingChanges();
StmError stmError = new StmError();
stmError.setSeverity(StmError.SEVERITY_MINOR);
stmError.setBlocking(false);
try {
JSONObject responseData = new JSONObject(new String(error.networkResponse.data));
stmError.setMessage(responseData.getString("message"));
} catch (JSONException ex) {
Log.e(TAG, "Error parsing JSON from user update response");
stmError.setMessage("An error occurred trying to PUT user");
}
if (callback != null) {
callback.onError(stmError);
}
}
};
sendAuthorizedPutRequest(this, userUpdateJson, responseListener, errorListener);
}
void get(final StmCallback<User> callback) {
Response.Listener<JSONObject> responseListener = new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
User user = null;
StmError stmError = null;
try {
// We don't update the ID or authToken here as that is handled elsewhere
JSONObject data = response.getJSONObject("data");
JSONObject userJson = data.getJSONObject("user");
try {
user = populateUserFieldsFromJson(userJson);
} catch(JSONException ex) {
Log.w(TAG, "Unable to populate user fields from JSON. " + response.toString(), ex);
stmError = new StmError("Unable to populate user fields from JSON", false,
StmError.SEVERITY_MINOR);
}
} catch(JSONException ex) {
Log.e(TAG, "Unable to parse response JSON. " + response.toString(), ex);
stmError = new StmError("Unable to parse user update response JSON", false,
StmError.SEVERITY_MINOR);
} finally {
pendingChanges.clear();
if (callback != null) {
if (stmError != null) {
callback.onError(stmError);
} else {
callback.onResponse(user);
}
}
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "An error occurred trying to contact the Shout to Me API", error);
StmError stmError = new StmError();
stmError.setMessage("Error occurred loading user");
stmError.setSeverity(StmError.SEVERITY_MAJOR);
stmError.setBlocking(true);
if (callback != null) {
callback.onError(stmError);
}
}
};
sendAuthorizedGetRequest("/users/me", responseListener, errorListener);
}
private User populateUserFieldsFromJson(JSONObject json) throws JSONException {
// Handle is an optional field so we bury the exception
try {
handle = json.getString("handle");
} catch (JSONException ex) {
Log.i(TAG, "User does not have a handle set");
}
try {
platformEndpointArn = json.getString("platform_endpoint_arn");
} catch (JSONException ex) {
// Ignore. Scenario occurs during first app launch.
}
return this;
}
private void rollbackPendingChanges() {
Set<Map.Entry<String, PendingApiObjectChange>> entrySet = pendingChanges.entrySet();
for (Map.Entry<String, PendingApiObjectChange> property: entrySet) {
if (property.getKey().equals("handle")) {
if (property.getValue().getOldValue() == null) {
handle = null;
} else {
handle = property.getValue().getOldValue();
}
}
}
pendingChanges.clear();
}
static class MetaInfo {
private String gender;
private String operatingSystem;
private String operatingSystemVersion;
public void setGender(String gender) {
this.gender = gender;
}
public void setOperatingSystem(String operatingSystem) {
this.operatingSystem = operatingSystem;
}
public void setOperatingSystemVersion(String operatingSystemVersion) {
this.operatingSystemVersion = operatingSystemVersion;
}
}
} |
package hex.kmeans;
import hex.Model;
import hex.schemas.KMeansModelV2;
import water.Key;
import water.api.ModelSchema;
import water.util.TwoDimTable;
import water.fvec.Frame;
public class KMeansModel extends Model<KMeansModel,KMeansModel.KMeansParameters,KMeansModel.KMeansOutput> {
public static class KMeansParameters extends Model.Parameters {
public int _k = 1; // Number of clusters
public int _max_iters = 1000; // Max iterations
public boolean _standardize = true; // Standardize columns
public long _seed = System.nanoTime(); // RNG seed
public KMeans.Initialization _init = KMeans.Initialization.Furthest;
Key<Frame> _user_points;
}
public static class KMeansOutput extends Model.Output {
// Number of categorical variables in the training set; they are all moved
// up-front and use a different distance metric than numerical variables
public int _ncats;
// Iterations executed
public int _iters;
// Cluster centers_raw. During model init, might be null or might have a "k"
// which is oversampled a lot. Not standardized (although if standardization
// is used during the building process, the *builders* cluster centers_raw are standardized).
public TwoDimTable _centers;
public double[][] _centers_raw;
// Cluster size. Defined as the number of rows in each cluster.
public long[] _size;
// Sum squared distance between each point and its cluster center, divided by total observations in cluster.
public double[] _within_mse; // Within-cluster MSE, variance
// Sum squared distance between each point and its cluster center, divided by total number of observations.
public double _avg_within_ss; // Average within-cluster sum-of-square error
// Sum squared distance between each point and grand mean, divided by total number of observations.
public double _avg_ss; // Total MSE to grand mean centroid
// Sum squared distance between each cluster center and grand mean, divided by total number of observations.
public double _avg_between_ss; // Total between-cluster MSE (avgss - avgwithinss)
public KMeansOutput( KMeans b ) { super(b); }
@Override public ModelCategory getModelCategory() {
return Model.ModelCategory.Clustering;
}
}
public KMeansModel(Key selfKey, KMeansParameters parms, KMeansOutput output) { super(selfKey,parms,output); }
// Default publicly visible Schema is V2
@Override public ModelSchema schema() { return new KMeansModelV2(); }
@Override protected float[] score0(double data[/*ncols*/], float preds[/*nclasses+1*/]) {
preds[0] = KMeans.closest(_output._centers_raw,data,_output._ncats);
return preds;
}
} |
package water.fvec;
import hex.CreateFrame;
import jsr166y.CountedCompleter;
import water.*;
import static water.fvec.Vec.makeCon;
import water.util.ArrayUtils;
import java.util.Arrays;
import java.util.Random;
import java.util.UUID;
/**
* Helper to make up a Frame from scratch, with random content
*/
public class FrameCreator extends H2O.H2OCountedCompleter {
public FrameCreator(CreateFrame createFrame, Key job) {
super(null);
_job=job;
_createFrame = createFrame;
int[] idx = _createFrame.has_response ? ArrayUtils.seq(1, _createFrame.cols + 1) : ArrayUtils.seq(0, _createFrame.cols);
int[] shuffled_idx = new int[idx.length];
ArrayUtils.shuffleArray(idx, idx.length, shuffled_idx, _createFrame.seed, 0);
int catcols = (int)(_createFrame.categorical_fraction * _createFrame.cols);
int intcols = (int)(_createFrame.integer_fraction * _createFrame.cols);
int bincols = (int)(_createFrame.binary_fraction * _createFrame.cols);
int realcols = _createFrame.cols - catcols - intcols - bincols;
assert(catcols >= 0);
assert(intcols >= 0);
assert(bincols >= 0);
assert(realcols >= 0);
_cat_cols = Arrays.copyOfRange(shuffled_idx, 0, catcols);
_int_cols = Arrays.copyOfRange(shuffled_idx, catcols, catcols+intcols);
_real_cols = Arrays.copyOfRange(shuffled_idx, catcols+intcols, catcols+intcols+realcols);
_bin_cols = Arrays.copyOfRange(shuffled_idx, catcols+intcols+realcols, catcols+intcols+realcols+bincols);
// create domains for categorical variables
_domain = new String[_createFrame.cols + (_createFrame.has_response ? 1 : 0)][];
if(createFrame.randomize) {
if(_createFrame.has_response) {
assert (_createFrame.response_factors >= 1);
_domain[0] = _createFrame.response_factors == 1 ? null : new String[_createFrame.response_factors];
if (_domain[0] != null) {
for (int i = 0; i < _domain[0].length; ++i) {
_domain[0][i] = new Integer(i).toString();
}
}
}
for (int c : _cat_cols) {
_domain[c] = new String[_createFrame.factors];
for (int i = 0; i < _createFrame.factors; ++i) {
_domain[c][i] = UUID.randomUUID().toString().subSequence(0, 5).toString();
// make sure that there's no pure number-labels
while (_domain[c][i].matches("^\\d+$") || _domain[c][i].matches("^\\d+e\\d+$")) {
_domain[c][i] = UUID.randomUUID().toString().subSequence(0, 5).toString();
}
}
}
}
// All columns together fill one chunk
final int log_rows_per_chunk = Math.max(1, Vec.LOG_CHK - (int)Math.floor(Math.log(_createFrame.cols)/Math.log(2.)));
_v = makeCon(_createFrame.value, _createFrame.rows, log_rows_per_chunk);
}
transient Vec _v;
public int nChunks() { return _v.nChunks(); }
final private CreateFrame _createFrame;
private int[] _cat_cols;
private int[] _int_cols;
private int[] _real_cols;
private int[] _bin_cols;
private String[][] _domain;
private Frame _out;
final private Key _job;
@Override public void compute2() {
int totcols = _createFrame.cols + (_createFrame.has_response ? 1 : 0);
Vec[] vecs = new Vec[totcols];
if(_createFrame.randomize) {
for (int i = 0; i < vecs.length; ++i)
vecs[i] = _v.makeZero(_domain[i]);
} else {
for (int i = 0; i < vecs.length; ++i)
vecs[i] = _v.makeCon(_createFrame.value);
}
_v.remove();
_v=null;
String[] names = new String[vecs.length];
if(_createFrame.has_response) {
names[0] = "response";
for (int i = 1; i < vecs.length; i++) names[i] = "C" + i;
} else {
for (int i = 0; i < vecs.length; i++) names[i] = "C" + (i+1);
}
_out = new Frame(_createFrame._dest, names, vecs);
assert _out.numRows() == _createFrame.rows;
assert _out.numCols() == totcols;
_out.delete_and_lock(_job);
// fill with random values
new FrameRandomizer(_createFrame, _cat_cols, _int_cols, _real_cols, _bin_cols).doAll(_out);
//overwrite a fraction with N/A
new MissingInserter(this, _createFrame.seed, _createFrame.missing_fraction).asyncExec(_out);
}
@Override public void onCompletion(CountedCompleter caller){
_out.update(_job);
_out.unlock(_job);
((Job)DKV.getGet(_job)).done();
}
private static class FrameRandomizer extends MRTask<FrameRandomizer> {
final private CreateFrame _createFrame;
final private int[] _cat_cols;
final private int[] _int_cols;
final private int[] _real_cols;
final private int[] _bin_cols;
public FrameRandomizer(CreateFrame createFrame, int[] cat_cols, int[] int_cols, int[] real_cols, int[] bin_cols){
_createFrame = createFrame;
_cat_cols = cat_cols;
_int_cols = int_cols;
_real_cols = real_cols;
_bin_cols = bin_cols;
}
//row+col-dependent RNG for reproducibility with different number of VMs, chunks, etc.
void setSeed(Random rng, int col, long row) {
rng.setSeed(_createFrame.seed + _createFrame.cols * row + col);
rng.setSeed(rng.nextLong());
}
@Override
public void map (Chunk[]cs){
if (!_createFrame.randomize) return;
final Random rng = new Random();
// response
if(_createFrame.has_response) {
for (int r = 0; r < cs[0]._len; r++) {
setSeed(rng, 0, cs[0]._start + r);
if (_createFrame.response_factors > 1)
cs[0].set(r, (int) (rng.nextDouble() * _createFrame.response_factors)); //classification
else if (_createFrame.positive_response)
cs[0].set(r, _createFrame.real_range * rng.nextDouble()); //regression with positive response
else
cs[0].set(r, _createFrame.real_range * (1 - 2 * rng.nextDouble())); //regression
}
}
_createFrame.update(1);
for (int c : _cat_cols) {
for (int r = 0; r < cs[c]._len; r++) {
setSeed(rng, c, cs[c]._start + r);
cs[c].set(r, (int)(rng.nextDouble() * _createFrame.factors));
}
}
_createFrame.update(1);
for (int c : _int_cols) {
for (int r = 0; r < cs[c]._len; r++) {
setSeed(rng, c, cs[c]._start + r);
cs[c].set(r, (long) ((_createFrame.integer_range+1) * (1 - 2 * rng.nextDouble())));
}
}
_createFrame.update(1);
for (int c : _real_cols) {
for (int r = 0; r < cs[c]._len; r++) {
setSeed(rng, c, cs[c]._start + r);
cs[c].set(r, _createFrame.real_range * (1 - 2 * rng.nextDouble()));
}
}
_createFrame.update(1);
for (int c : _bin_cols) {
for (int r = 0; r < cs[c]._len; r++) {
setSeed(rng, c, cs[c]._start + r);
cs[c].set(r, rng.nextFloat() > _createFrame.binary_ones_fraction ? 0 : 1);
}
}
_createFrame.update(1);
}
}
public static class MissingInserter extends MRTask<MissingInserter> {
final long _seed;
final double _frac;
public MissingInserter(long seed, double frac) {
super(null);
_seed = seed;
_frac = frac;
}
public MissingInserter(H2O.H2OCountedCompleter cmp, long seed, double frac) {
super(cmp);
_seed = seed;
_frac = frac;
}
@Override
public void map(Chunk[] cs) {
if (_frac == 0) return;
final Random rng = new Random();
for (int c = 0; c < cs.length; c++) {
for (int r = 0; r < cs[c]._len; r++) {
rng.setSeed(_seed + 1234 * c ^ 1723 * (cs[c]._start + r)); //row+col-dependent RNG for reproducibility
if (rng.nextDouble() < _frac) cs[c].setNA(r);
}
}
}
}
} |
package water.persist;
import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import water.*;
import water.api.FSIOException;
import water.fvec.NFSFileVec;
import water.util.Log;
/**
* Persistence backend using local file system.
*/
final class PersistFS extends Persist {
final File _root;
final File _dir;
PersistFS(File root) {
_root = root;
_dir = new File(root, "ice" + H2O.API_PORT);
//deleteRecursive(_dir);
// Make the directory as-needed
root.mkdirs();
if( !(root.isDirectory() && root.canRead() && root.canWrite()) )
H2O.die("ice_root not a read/writable directory");
}
public void cleanUp() { deleteRecursive(_dir); }
private static void deleteRecursive(File path) {
if( !path.exists() ) return;
if( path.isDirectory() )
for (File f : path.listFiles())
deleteRecursive(f);
path.delete();
}
private File getFile(Value v) {
return new File(_dir, getIceName(v));
}
@Override public byte[] load(Value v) throws IOException {
File f = getFile(v);
if( f.length() < v._max ) { // Should be fully on disk...
// or it's a racey delete of a spilled value
assert !v.isPersisted() : f.length() + " " + v._max + " " + v._key;
return null; // No value
}
try (FileInputStream s = new FileInputStream(f)) {
AutoBuffer ab = new AutoBuffer(s.getChannel(), true, Value.ICE);
byte[] b = ab.getA1(v._max);
ab.close();
return b;
}
}
// Store Value v to disk.
@Override public void store(Value v) throws IOException {
assert !v.isPersisted();
File dirs = new File(_dir, getIceDirectory(v._key));
if( !dirs.mkdirs() && !dirs.exists() )
throw new java.io.IOException("mkdirs failed making "+dirs);
try(FileOutputStream s = new FileOutputStream(getFile(v))) {
byte[] m = v.memOrLoad(); // we are not single threaded anymore
if( m != null && m.length != v._max ) {
Log.warn("Value size mismatch? " + v._key + " byte[].len=" + m.length+" v._max="+v._max);
v._max = m.length; // Implies update of underlying POJO, then re-serializing it without K/V storing it
}
new AutoBuffer(s.getChannel(), false, Value.ICE).putA1(m, m.length).close();
} catch( AutoBuffer.AutoBufferException abe ) {
throw abe._ioe;
}
}
@Override public void delete(Value v) {
getFile(v).delete(); // Silently ignore errors
// Attempt to delete empty containing directory
new File(_dir, getIceDirectory(v._key)).delete();
}
@Override public long getUsableSpace() {
return _root.getUsableSpace();
}
@Override public long getTotalSpace() {
return _root.getTotalSpace();
}
@Override
public Key uriToKey(URI uri) {
return NFSFileVec.make(new File(uri.toString()))._key;
}
@Override
public ArrayList<String> calcTypeaheadMatches(String src, int limit) {
assert false;
return new ArrayList<>();
}
@Override
public void importFiles(String path, ArrayList<String> files, ArrayList<String> keys, ArrayList<String> fails, ArrayList<String> dels) {
assert false;
}
@Override
public OutputStream create(String path, boolean overwrite) {
File f = new File(URI.create(path));
if (f.exists() && !overwrite)
throw new FSIOException(path, "File already exists");
try {
return new FileOutputStream(f, false);
} catch (IOException e) {
throw new FSIOException(path, e);
}
}
@Override
public PersistEntry[] list(String path) {
File f = new File(URI.create(path));
if (f.isFile()) {
return new PersistEntry[] { getPersistEntry(f) };
} else if (f.isDirectory()) {
File[] files = f.listFiles();
PersistEntry[] entries = new PersistEntry[files.length];
for (int i = 0; i < files.length; i++) {
entries[i] = getPersistEntry(files[i]);
}
return entries;
}
throw H2O.unimpl();
}
@Override
public InputStream open(String path) {
try {
File f = new File(URI.create(path));
return new FileInputStream(f);
} catch (FileNotFoundException e) {
throw new FSIOException(path, "File not found");
} catch (Exception e) {
throw new FSIOException(path, e);
}
}
@Override
public boolean mkdirs(String path) {
return new File(URI.create(path)).mkdirs();
}
@Override
public boolean exists(String path) {
return new File(URI.create(path)).exists();
}
private PersistEntry getPersistEntry(File f) {
return new PersistEntry(f.getName(), f.length(), f.lastModified());
}
} |
package com.ae.apps.tripmeter;
import org.junit.Test;
import static org.junit.Assert.*;
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
@Test
public void multiplication_isCorrect() throws Exception {
assertEquals(4, 2 * 2);
}
} |
package edu.utah.sci.cyclist.core.model;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
import org.apache.log4j.Logger;
import edu.utah.sci.cyclist.core.controller.IMemento;
import edu.utah.sci.cyclist.core.controller.WorkDirectoryController;
import edu.utah.sci.cyclist.core.controller.XMLMemento;
import edu.utah.sci.cyclist.core.model.DataType.Role;
import edu.utah.sci.cyclist.core.util.QueryBuilder;
import edu.utah.sci.cyclist.core.util.SQL;
import edu.utah.sci.cyclist.core.util.SQLUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import javafx.concurrent.Task;
public class Table {
public static final String DATA_SOURCE = "datasource";
public static final String REMOTE_TABLE_NAME = "remote-table-name";
static Logger log = Logger.getLogger(Table.class);
public enum SourceLocation {
REMOTE,
LOCAL_ALL,
LOCAL_SUBSET
}
public enum NumericRangeValues {
MIN,
MAX,
CHOSEN_MIN,
CHOSEN_MAX
}
private String _alias;
private String _name;
private Schema _schema = new Schema(this);
private CyclistDatasource _datasource;
private Map<String, Object> _properties = new HashMap<>();
private List<TableRow> _rows = new ArrayList<>();
private String _localDataFile;
private SourceLocation _sourceLocation;
private int _dataSubset;
private String _saveDir = "";
private Boolean _isStandardSimulation = false;
//Holds the list of values of a field in the current table in a specified data source.
//First key - the data source.
//Then inside the specified data source it maps between a field and a list of values.
private Map<String,Map<String,List<Object>>> _cachedFieldsValues = new HashMap<>();
public Table() {
this("");
}
public Table(String name) {
_name = name;
_alias = name;
_sourceLocation = SourceLocation.REMOTE;
_dataSubset = 0;
setProperty("uid", UUID.randomUUID().toString());
}
public Table(Table tbl){
_name = tbl.getName();
_alias = tbl.getAlias();
_sourceLocation = tbl.getSourceLocation();
_datasource = tbl.getDataSource();
_localDataFile = tbl.getLocalDatafile();
_saveDir = tbl.getSaveDir();
setProperty(REMOTE_TABLE_NAME, _name);
extractSchema();
}
// Save the table
public void save(IMemento memento) {
// Set the name
memento.putString("name", getName());
// Set the alias
memento.putString("alias", getAlias());
// Save the schema
_schema.save(memento.createChild("Schema"));
// Save the uid of the data source
memento.putString("datasource-uid", _datasource.getUID());
// Save the location of the data source
memento.putString("source-location", _sourceLocation.toString());
// Save the subset
memento.putInteger("subset", _dataSubset);
// Save the map
IMemento mapMemento = memento.createChild("property-map");
// Set things saved in the properties map
Set<String> keys = _properties.keySet();
for(String key: keys){
Object value = _properties.get(key);
IMemento entryMemento = mapMemento.createChild("entry");
entryMemento.putString("key", key);
entryMemento.putString("class", value.getClass().toString());
// Save integers or strings as strings
if(value.getClass().toString().equals(String.class.toString()) ||
value.getClass().toString().equals(Integer.class.toString()))
entryMemento.putTextData((String)value);
else{
System.out.println("Table:save() NEED TO CHECK FOR SAVE-ABLE OBJECTS!!");
IMemento valueMemento = entryMemento.createChild("value");
valueMemento.putString("value-ID", value.toString());
}
}
}
// Restore the table
public void restore(IMemento memento, ObservableList<CyclistDatasource> sources){
// Get the name
setName(memento.getString("name"));
// Get the alias
setAlias(memento.getString("alias"));
// Get the number of rows
// _numRows = memento.getInteger("NumRows");
// Get the datasource
String datasourceUID = memento.getString("datasource-uid");
for(CyclistDatasource source: sources){
if(source.getUID().equals(datasourceUID))
setDataSource(source);
}
// Get the location of the data source
setSourceLocation(memento.getString("source-location"));
// Get the data subset
setDataSubset(memento.getInteger("subset"));
// Save the subset
memento.putInteger("subset", _dataSubset);
// Get values in the property map
IMemento mapMemento = memento.getChild("property-map");
IMemento[] entries = mapMemento.getChildren("entry");
for(IMemento entry: entries){
// Get the key of the object
String key = entry.getString("key");
// Get the class of the object
String classType = entry.getString("class");
// If we have a string
if(classType.equals(String.class.toString())){
String value = entry.getTextData();
setProperty(key, value);
}
// If we have an Integer
else if(classType.equals(Integer.class.toString())){
Integer value = Integer.parseInt(entry.getTextData());
setProperty(key, value);
}
else{
System.out.println("Table:load() NEED TO IMPLEMENT OBJECT FACTORIES!!");
}
}
// Restore the schema
Schema schema = new Schema(this);
schema.restore(memento.getChild("Schema"));
setSchema(schema);
// extractSchema();
}
// Extract the table schema from the database
public void extractSchema(){
try (Connection conn = _datasource.getConnection()) {
//printTypeInfo(conn);
DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.getColumns(null, null, getName(), null);
while (rs.next()) {
String colName = rs.getString("COLUMN_NAME");
Field field = new Field(colName);
field.setTable(this);
field.set(FieldProperties.REMOTE_NAME, colName);
field.set(FieldProperties.REMOTE_DATA_TYPE, rs.getInt("DATA_TYPE"));
field.set(FieldProperties.REMOTE_DATA_TYPE_NAME, rs.getString("TYPE_NAME"));
_schema.addField(field);
}
} catch (Exception e) {
System.out.println("Error while parsing schema: "+e.getMessage());
}finally{
_datasource.releaseConnection();
}
_schema.update();
}
/*
* Restores table from the simulation configuration file.
* Restores only the information which is relevant to the simulation.
*/
public void restoreSimulated(IMemento memento){
setName(memento.getString("name"));
setDataSource(null);
// Restore the schema
Schema schema = new Schema(this);
schema.restoreSimulated(memento.getChild("Schema"));
setSchema(schema);
_isStandardSimulation = true;
}
// private void printTypeInfo(Connection conn) {
// DatabaseMetaData d;
// try {
// d = conn.getMetaData();
// ResultSet rs = d.getTypeInfo();
// ResultSetMetaData cmd = rs.getMetaData();
// System.out.println("database types:");
// while (rs.next()) {
// for (int i=1; i<=cmd.getColumnCount(); i++) {
// System.out.print(cmd.getColumnName(i)+": "+rs.getObject(i)+" ");
// System.out.println();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
public String getName() {
return _name;
}
public void setName(String name) {
_name = name;
}
public String getAlias(){
if(_alias.equals(""))
return getName();
else
return _alias;
}
public void setAlias(String alias){
_alias = alias;
}
public void setSourceLocation(SourceLocation source){
_sourceLocation = source;
}
public void setSourceLocation(String source){
if(source.equals("REMOTE"))
_sourceLocation = SourceLocation.REMOTE;
else if(source.equals("LOCAL_ALL"))
_sourceLocation = SourceLocation.LOCAL_ALL;
else if(source.equals("LOCAL_SUBSET"))
_sourceLocation = SourceLocation.LOCAL_SUBSET;
}
public SourceLocation getSourceLocation(){
return _sourceLocation;
}
public void setDataSubset(int subset){
_dataSubset = subset;
}
public int getDataSubset(){
return _dataSubset;
}
@Override
public String toString() {
return getName();
}
public void setProperty(String property, Object value) {
_properties.put(property, value);
}
public void removeProperty(String property) {
_properties.remove(property);
}
public Object getProperty(String property) {
return _properties.get(property);
}
public boolean hasProperty(String property) {
return _properties.containsKey(property);
}
public String getStringProperty(String property) {
Object value = _properties.get(property);
if (value == null)
return null;
else if (value instanceof String)
return (String)value;
else
return value.toString();
}
/**
* Convenient method
* @param datasource
*/
public void setDataSource(CyclistDatasource datasource){
_datasource = datasource;
}
/**
* Convenient method
* @return
*/
public CyclistDatasource getDataSource(){
return _datasource;
}
public void setSchema(Schema schema) {
_schema = schema;
clear();
}
public Schema getSchema() {
return _schema;
}
public List<Field> getFields() {
List<Field> list = new ArrayList<Field>();
int n = _schema.size();
for (int i=0; i<n; i++) {
list.add(_schema.getField(i));
}
return list;
}
public Field getField(int index) {
return _schema.getField(index);
}
public Field getField(String name) {
return _schema.getField(name);
}
public void setFieldSelected(int index, boolean selected){
_schema.getField(index).setSelectedProperty(selected);
}
public boolean hasField(Field field) {
if (field.getTable() == this) return true;
// for now check based on field name
return _schema.contain(field);
}
public int getNumColumns() {
return _schema.size();
}
public void addRow(TableRow row) {
_rows.add(row);
}
public List<TableRow> getRows() {
return _rows;
}
public QueryBuilder queryBuilder() {
return new QueryBuilder(this);
}
/*
* Returns whether the table was loaded for simulation purpose
* (from the simulation configuration file)
* @return true- if the table is for simulation, false - otherwise.
*/
public Boolean getIsStandardSimulation(){
return _isStandardSimulation;
}
public Task<ObservableList<Object>> getFieldValues(final Field field) {
CyclistDatasource ds = getDataSource();
return getFieldValues(ds, field);
}
public Task<ObservableList<Object>> getFieldValues(CyclistDatasource ds, final Field field)
{
return getFieldValues(ds, field, false);
}
public Task<ObservableList<Object>> getFieldValues(CyclistDatasource ds1, final Field field, boolean force) {
final CyclistDatasource ds = getAvailableDataSource(ds1,force);
Task<ObservableList<Object>> task = new Task<ObservableList<Object>>() {
@Override
protected ObservableList<Object> call() throws Exception {
List<Object> values = new ArrayList<>();
if (ds != null) {
values = readFieldValuesFromCache(field.getName(), ds);
//If couldn't find in the cache - try from the file.
if(values.size() == 0){
values = readFieldValuesFromFile(field.getName(),ds);
}
if(values.size() == 0)
{
try (Connection conn = ds.getConnection(); Statement stmt = conn.createStatement()){
updateMessage("querying");
// TODO: Fix this query building hack
String query = "select distinct "+field.getName()+" from "+getName()+" order by "+field.getName();
log.debug("query: "+query);
ResultSet rs = stmt.executeQuery(query);
Function<Object, Object> convert[] = SQLUtil.factories(rs.getMetaData());
while (rs.next()) {
if (isCancelled()) {
System.out.println("task canceled");
stmt.cancel();
updateMessage("Canceled");
break;
}
values.add(convert[0].apply(rs.getObject(1)));
}
writeFieldValuesToCache(field.getName(), ds, values);
writeFieldValuesToFile(field.getName(), field.getType().toString(), field.getRole().toString(), ds, values);
} catch (SQLException e) {
System.out.println("task sql exception: "+e.getLocalizedMessage());
updateMessage(e.getLocalizedMessage());
throw new Exception(e.getMessage(), e);
} finally {
ds.releaseConnection();
}
}
}
return FXCollections.observableList(values);
}
};
Thread th = new Thread(task);
th.setDaemon(true);
th.start();
return task;
}
public TableRow getRow(int index) {
return _rows.get(index);
}
public void clear() {
_rows.clear();
}
public String getLocalDatafile() {
return _localDataFile;
}
public void setLocalDatafile(String workDir) {
_saveDir = workDir;
_localDataFile = workDir + "/" + getDataSource()+"/" + getName() + ".sqlite";
}
public String getSaveDir(){
return _saveDir;
}
/* Saves the values of a chosen filter into a file
* Creates an xml file with the table name, and writes the filter's field name, its type, role and its values
* If the field already exist in the file - do nothing.
* @param fieldName - String.
* @param fieldType - DataType.Type enum.
* @param role - DataType.Role enum
* @param ds - data source.
* @param List<Object> values - list of values to save.
* */
private void writeFieldValuesToFile(String fieldName, String fieldType, String role ,CyclistDatasource ds, List<Object> values){
if(_saveDir == ""){
_saveDir = WorkDirectoryController.DEFAULT_WORKSPACE;
}
// If the save directory does not exist, create it
File saveDir = new File(_saveDir+ "/" + ds.getUID() +"/");
if (!saveDir.exists()){
saveDir.mkdir();
}
// The save file
File saveFile = new File(saveDir+"/"+ getName() + ".xml");
XMLMemento root;
IMemento fieldsNode = null;
Boolean writeNewNode= true;
try {
//If file already exists - read the existing nodes, and add the new Field in its place.
if(saveFile.exists()){
Reader reader = new FileReader(saveFile);
//Checks if the root node exists.
try{
root = XMLMemento.createReadRoot(reader);
fieldsNode = root.getChild("Fields");
}catch(Exception e){
root = XMLMemento.createWriteRoot("root");
}
// Checks if the "Fields" node exists.
// If yes - try to find the Field node with the given name.
// If not - creates a new "Fields" node and mark that a new field node has to be written.
if(fieldsNode != null)
{
//Check if the field node already exists. If yes - no need to write it again to the table xml file.
if (getField(fieldsNode, fieldName) != null)
{
writeNewNode = false;
}
} else{
fieldsNode = root.createChild("Fields");
}
} else{
// If new file - Create the root memento
root = XMLMemento.createWriteRoot("root");
// Create Fields node
fieldsNode = root.createChild("Fields");
}
//If no such field node yet - write the field and its values into the file.
if(writeNewNode){
writeFieldNodeToFile(fieldName, fieldType, role, fieldsNode, values);
}
root.save(new PrintWriter(saveFile));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*Checks if a given field already exists in the table xml file.
* If field exists - return the field else- return null */
private IMemento getField(IMemento fields, String fieldName){
IMemento fieldResult = null;
try
{
IMemento[] fieldNodes = fields.getChildren("Field");
for (IMemento field:fieldNodes){
String name = field.getString("name");
if (name.equals(fieldName)){
fieldResult = field;
break;
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return fieldResult;
}
/* Creates a new Field node in the table xml file*/
private void writeFieldNodeToFile(String fieldName, String fieldType, String fieldRole, IMemento fieldsNode, List<Object> values){
//Create the Field node
IMemento FieldNode = fieldsNode.createChild("Field");
// Set the field name
FieldNode.putString("name", fieldName);
FieldNode.putString("type", fieldType);
FieldNode.putString("role", fieldRole);
StringBuilder sb = new StringBuilder();
for(Object value:values){
if (value == null) {
System.out.println("*** Warning: field '"+fieldName+"' has a null value");
} else {
sb.append(value.toString()+";");
}
}
FieldNode.putTextData(sb.toString());
}
/* Saves a distinct values list to the cache.
* For a given field in the current table in the specified data source -
* write the list values to the cache, where the keys are the field and the data source.
*
* @param String fieldName - the field to use as a key in the map.
* @param CyclistDatasource ds - the data source to to use as a key in the map.
* @param List<Object> - the list of values to write in the cache for the specified keys. */
private void writeFieldValuesToCache(String fieldName, CyclistDatasource ds, List<Object> values){
Map<String,List<Object>> fieldValues = _cachedFieldsValues.get(ds.getUID());
if(fieldValues == null){
fieldValues = new HashMap<String,List<Object>>();
fieldValues.put(fieldName, values);
_cachedFieldsValues.put(ds.getUID(), fieldValues);
} else{
fieldValues.put(fieldName, values);
}
}
/* Reads distinct values from the cache.
* For a given field in the current table in the specified data source -
* if the data source key and the field key exist in the cache - read its values from the cache.
*
* @param String fieldName - the field to look for in the map.
* @param CyclistDatasource ds - the data source to look for in the map
* @return List<Object> - the list of values found for the given data source and field.
* (returns an empty list if not found) */
private List<Object> readFieldValuesFromCache(String fieldName, CyclistDatasource ds){
List<Object> values = new ArrayList<>();
Map<String,List<Object>> fieldValues = _cachedFieldsValues.get(ds.getUID());
if(fieldValues != null){
if(fieldValues.get(fieldName) != null){
values = fieldValues.get(fieldName);
}
}
return values;
}
/* Reads distinct values from a file
* For a given field in a given table-
* if the table xml file exists and it contains the field values - read the values from the file
* Before reading - check the field type, and convert the values to the right type.
* @param fieldName - field name to search
* @param ds - defines the file to look for the field properties
* */
private List<Object> readFieldValuesFromFile(String fieldName, CyclistDatasource ds){
List<Object> values = new ArrayList<>();
if(_saveDir == ""){
_saveDir = WorkDirectoryController.DEFAULT_WORKSPACE;
}
// If the save file does not exist - return an empty list.
File saveFile = new File(_saveDir+ "/" + ds.getUID() +"/"+ getName() + ".xml");
if (!saveFile.exists()){
return values;
} else{
try{
Reader reader = new FileReader(saveFile);
XMLMemento root = XMLMemento.createReadRoot(reader);
IMemento fieldsNode = root.getChild("Fields");
IMemento field = getField(fieldsNode, fieldName);
if(field != null){
String[] tmpValues = field.getTextData().split(";");
String type = field.getString("type") == null?"TEXT":field.getString("type");
try{
switch(DataType.Type.valueOf(type)){
case TEXT:
for(String value: tmpValues){
values.add(value);
}
break;
case NUMERIC:
String role = field.getString("role")==null? "MEASURE":field.getString("role");
if(DataType.Role.valueOf(role) == Role.MEASURE){
for(String value: tmpValues){
values.add(Double.parseDouble(value));
}
}else{
for(String value: tmpValues){
values.add(Integer.parseInt(value));
}
}
break;
case INT_TIME:
for(String value: tmpValues){
values.add(Integer.parseInt(value));
}
break;
default:
for(String value: tmpValues){
values.add(value);
}
}
}catch(NumberFormatException ex){
for(String value: tmpValues){
values.add(value);
}
}
}
//If reading from file - it means the values weren't found in the cache.
//Save them in the cache for the next time.
if(values.size() >0){
writeFieldValuesToCache(fieldName, ds, values);
}
return values;
}catch(Exception e){
return values;
}
}
}
/*
* Returns the currently available data source.
*
* @param CyclistDatasource externalDs - suggested data source other than the table's data source.
* @param boolean force - whether the external data source must be applied
* (even it the table has its own data source), or not.
* @return CyclistDatasource
*/
private CyclistDatasource getAvailableDataSource(CyclistDatasource externalDs, boolean force){
CyclistDatasource lds = getDataSource();
CyclistDatasource ds = force ? ( externalDs != null ? externalDs : lds ) : (lds != null ? lds : externalDs);
return ds;
}
public Task<ObservableMap<Object,Object>> getFieldRange(final Field field) {
CyclistDatasource ds = getDataSource();
return getFieldRange(ds, field);
}
public Task<ObservableMap<Object,Object>> getFieldRange(CyclistDatasource ds, final Field field)
{
return getFieldRange(ds, field, false);
}
/* Name: getFieldRange
* For a numeric field filter - gets the minimum and maximum values within its possible range, for any possible grouping.
* It checks for the field SQL function and finds the values accordingly.
*/
public Task<ObservableMap<Object, Object>> getFieldRange(CyclistDatasource externalDs, final Field field, boolean force) {
final CyclistDatasource ds = getAvailableDataSource(externalDs, force);
Task<ObservableMap<Object, Object>> task = new Task<ObservableMap<Object, Object>>() {
@Override
protected ObservableMap<Object, Object> call() throws Exception {
Map<Object, Object> values = new HashMap<>();
if (ds != null) {
try (Connection conn = ds.getConnection(); Statement stmt = conn.createStatement()){
updateMessage("querying");
System.out.println("querying field range");
SQL.Functions function = SQL.Functions.VALUE;
if(field.getString(FieldProperties.AGGREGATION_FUNC) != null){
function = SQL.Functions.getEnum(field.getString(FieldProperties.AGGREGATION_FUNC));
}
String query = "";
Boolean checkForSum = false;
double min,max=0;
switch(function){
case AVG:
case MIN:
case MAX:
case VALUE:
query = "SELECT MIN("+field.getName()+") AS min, MAX(" + field.getName() + ") AS max FROM "+ getName();
break;
case COUNT:
query = "SELECT 0 AS min, COUNT(" + field.getName() + ") AS max FROM "+ getName();
break;
case COUNT_DISTINCT:
query = "SELECT 0 AS min, COUNT( DISTINCT " + field.getName() + ") AS max FROM "+ getName();
case SUM:
query = "SELECT SUM( CASE WHEN " + field.getName()+ " <0 THEN " + field.getName() + " ELSE 0 END) AS neg_sum, " +
"SUM( CASE WHEN " + field.getName()+ " >0 THEN " + field.getName() + " ELSE 0 END) AS pos_sum, " +
"MIN(" + field.getName() +") as min, MAX(" + field.getName() +") as max "+
"FROM " + getName();
checkForSum = true;
break;
}
log.debug("query: "+query);
System.out.println(query);
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
if (isCancelled()) {
System.out.println("task canceled");
updateMessage("Canceled");
break;
}
min = rs.getDouble("min");
max = rs.getDouble("max");
if(checkForSum)
{
double posSum = rs.getDouble("pos_sum");
max= (posSum==0)?max:posSum;
double negSum = rs.getDouble("neg_sum");
min= (negSum==0)?min:negSum;
}
values.put(NumericRangeValues.MIN, min);
values.put(NumericRangeValues.MAX, max);
}
}catch(Exception e){
e.printStackTrace();
}finally {
ds.releaseConnection();
}
}
return FXCollections.observableMap(values);
}
};
Thread th = new Thread(task);
th.setDaemon(true);
th.start();
return task;
}
private static final String GET_ROWS_QUERY = "select * from $table limit ?";
} |
package com.example.baard;
import com.example.baard.Entities.Day;
import com.example.baard.Entities.Habit;
import com.example.baard.Entities.HabitEvent;
import com.example.baard.Habits.HabitStatistics;
import junit.framework.TestCase;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class HabitStatisticsTest extends TestCase {
private Habit habit;
private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
public void setUp() {
ArrayList<Day> frequency = new ArrayList<Day>();
frequency.add(Day.MONDAY);
frequency.add(Day.WEDNESDAY);
frequency.add(Day.FRIDAY);
try {
habit = new Habit("Practicing guitar", "To get better", sdf.parse("01/11/2017"), frequency);
habit.getEvents().add(new HabitEvent(habit, sdf.parse("01/11/2017")));
habit.getEvents().add(new HabitEvent(habit, sdf.parse("03/11/2017")));
habit.getEvents().add(new HabitEvent(habit, sdf.parse("06/11/2017")));
habit.getEvents().add(new HabitEvent(habit, sdf.parse("08/11/2017")));
habit.getEvents().add(new HabitEvent(habit, sdf.parse("09/11/2017")));
habit.getEvents().add(new HabitEvent(habit, sdf.parse("10/11/2017")));
} catch (Exception e) {}
}
public void testCalcHabitCompletionAllWithinStartEnd() {
HabitStatistics.HabitCompletionData habitCompletionData = null;
Date startDate = null, endDate = null;
try {
startDate = sdf.parse("01/11/2017");
endDate = sdf.parse("10/11/2017");
} catch (Exception e) {}
habitCompletionData = new HabitStatistics().calcHabitCompletion(habit, startDate, endDate);
assertEquals(5, habitCompletionData.completed);
assertEquals(1, habitCompletionData.notCompleted);
}
public void testCalcHabitCompletionOneOutFromStart() {
HabitStatistics.HabitCompletionData habitCompletionData = null;
Date startDate = null, endDate = null;
try {
startDate = sdf.parse("02/11/2017");
endDate = sdf.parse("10/11/2017");
} catch (Exception e) {}
habitCompletionData = new HabitStatistics().calcHabitCompletion(habit, startDate, endDate);
assertEquals(4, habitCompletionData.completed);
assertEquals(1, habitCompletionData.notCompleted);
}
public void testCalcHabitCompletionOneOutFromEnd() {
HabitStatistics.HabitCompletionData habitCompletionData = null;
Date startDate = null, endDate = null;
try {
startDate = sdf.parse("01/11/2017");
endDate = sdf.parse("08/11/2017");
} catch (Exception e) {}
habitCompletionData = new HabitStatistics().calcHabitCompletion(habit, startDate, endDate);
assertEquals(4, habitCompletionData.completed);
assertEquals(0, habitCompletionData.notCompleted);
}
public void testCalcHabitCompletionNone() {
HabitStatistics.HabitCompletionData habitCompletionData = null;
Date startDate = null, endDate = null;
try {
startDate = sdf.parse("01/11/2015");
endDate = sdf.parse("08/11/2015");
} catch (Exception e) {}
habitCompletionData = new HabitStatistics().calcHabitCompletion(habit, startDate, endDate);
assertEquals(0, habitCompletionData.completed);
assertEquals(0, habitCompletionData.notCompleted);
}
public void testGetHabitCompletionVsTime() {
ArrayList<HabitStatistics.HabitCompletionVsTimeData> habitCompletionVsTimeDatas = null;
Date startDate = null, endDate = null;
try {
startDate = sdf.parse("08/11/2017");
endDate = sdf.parse("10/11/2017");
} catch (Exception e) {}
habitCompletionVsTimeDatas = new HabitStatistics().getHabitCompletionVsTimeData(habit, startDate, endDate);
assertEquals(2, habitCompletionVsTimeDatas.size());
HabitStatistics.HabitCompletionVsTimeData habitCompletionByTimeData0 = habitCompletionVsTimeDatas.get(0);
HabitStatistics.HabitCompletionVsTimeData habitCompletionByTimeData1 = habitCompletionVsTimeDatas.get(1);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(habitCompletionByTimeData0.time);
assertEquals(1, habitCompletionByTimeData0.habitCompletion);
assertEquals("08/11/2017", sdf.format(calendar.getTime()));
calendar.setTimeInMillis(habitCompletionByTimeData1.time);
assertEquals(2, habitCompletionByTimeData1.habitCompletion);
assertEquals("10/11/2017", sdf.format(calendar.getTime()));
}
public void testGetHabitCompletionVsTimeNone() {
ArrayList<HabitStatistics.HabitCompletionVsTimeData> habitCompletionVsTimeDatas = null;
Date startDate = null, endDate = null;
try {
startDate = sdf.parse("08/11/2015");
endDate = sdf.parse("10/11/2015");
} catch (Exception e) {}
habitCompletionVsTimeDatas = new HabitStatistics().getHabitCompletionVsTimeData(habit, startDate, endDate);
assertEquals(0, habitCompletionVsTimeDatas.size());
}
} |
package idv.xfl03.quesreg.question;
import idv.xfl03.quesreg.config.MainConfig;
import idv.xfl03.quesreg.data.MainData;
import idv.xfl03.quesreg.data.ResourceFileTool;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
public class QuestionList {
public ArrayList<ArrayList<Question>> alq;
public int[] sum={-1,0,0,0,0};
private final static QuestionFileFilter qff0=new QuestionFileFilter();;
private final static QuestionFolderFilter qff1=new QuestionFolderFilter();
private final static int SPLIT_BASIC=10000;
private MainConfig mc;
private MainData md;
public QuestionList(File questionFolder,MainConfig mc,MainData md){
this.mc=mc;
this.md=md;
alq=new ArrayList<ArrayList<Question>>();
alq.add(null);
for(int i=1;i<=4;i++){
alq.add(new ArrayList<Question>());
}
File[] subFolder=questionFolder.listFiles(qff1);
if(subFolder.length==0){
//First time
System.out.println("Init Questions!");
ResourceFileTool rft=this.md.rft;
for(int i=1;i<=10;i++){
File t=md.getSubFile(questionFolder, "/official-default-en/"+i+".txt");
t.getParentFile().mkdirs();
try {
t.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
rft.resourceFileCopy("/resource/question/official-default-en/"+i+".txt",t);
//zh-cn
t=md.getSubFile(questionFolder, "/official-default-zh-cn/"+i+".txt");
t.getParentFile().mkdirs();
try {
t.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
rft.resourceFileCopy("/resource/question/official-default-zh-cn/"+i+".txt", t);
//anti xiong hai zi
t=md.getSubFile(questionFolder, "/anti-little-child-zh-cn/"+i+".txt");
t.getParentFile().mkdirs();
try {
t.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
rft.resourceFileCopy("/resource/question/anti-little-child-zh-cn/"+i+".txt", t);
}
subFolder=questionFolder.listFiles(qff1);
}
for(File f : subFolder){
if(!f.getAbsolutePath().endsWith(mc.language)){
continue;
}
File[] subFile=f.listFiles(qff0);
for(File f1 : subFile){
Question q=new Question(f1);
alq.get(q.type).add(q);
//System.out.println(q.type+" "+q.question);
sum[q.type]++;
}
}
for(int i=1;i<=4;i++){
if(sum[i]<mc.questionNumber[i]){
System.out.println("TYPE "+i+" "+sum[i]+"/"+mc.questionNumber[i]);
for(int j=sum[i];j<mc.questionNumber[i];j++){
alq.get(i).add(new Question(i));
//System.out.println(i+" blank");
}
}
}
}
public String getRandomQuestions(){
//System.out.println("getRandomQuestions");
StringBuilder sb=new StringBuilder();
for(int i=1;i<=4;i++){
System.out.println(i);
int questionNumber=mc.questionNumber[i];
if(questionNumber==0){
//System.out.println(i+" Needs Nothing");
continue;
}
int[] id=new int[questionNumber];
System.out.println(mc.questionNumber.length+" "+id.length+" "+i);
for(int j=0;j<questionNumber;j++){
//int max=alq.get(i).size();
int temp=i*SPLIT_BASIC+getRandom(1,questionNumber);
int loopCount=0;
while(isUsed(id,temp)&&loopCount<=questionNumber){
loopCount++;
temp=i*10000+getRandom(1,alq.get(i).size()-1);
}
if(isUsed(id,temp)){
//Too much Loop Times
for(int k=i*SPLIT_BASIC+1;i<=i*SPLIT_BASIC+questionNumber;i++){
if(!isUsed(id,k)){
temp=k;
break;
}
}
}
//System.out.println(temp+" "+max);
id[j]=temp;
}
if(sb.length()>0){
sb.append(",");
}
sb.append(idsToString(id));
}
return sb.toString();
}
public Question getQuestion(int id){
int type=id/SPLIT_BASIC;
int i=id%SPLIT_BASIC;
return alq.get(type).get(i-1);
}
public int[] getIds(String ids){
String[] temp=ids.split(",");
int[] id=new int[temp.length];
for(int i=0;i<temp.length;i++){
id[i]=Integer.parseInt(temp[i]);
}
return id;
}
private int getRandom(int min,int max){
return (int)(Math.random()*(max-min+1))+min;
}
private boolean isUsed(int[] array,int test){
for(int i=0;i < array.length;i++){
if(array[i]==test){
return true;
}
}
return false;
}
private String idsToString(int[] array){
StringBuilder sb=new StringBuilder();
sb.append(array[0]);
for(int i=1;i<array.length;i++){
sb.append(",");
sb.append(""+array[i]);
}
return sb.toString();
}
} |
package org.webrtc;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.opengl.GLES11Ext;
import android.opengl.GLES20;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;
import android.view.Surface;
import android.view.WindowManager;
import org.json.JSONException;
import org.webrtc.CameraEnumerationAndroid.CaptureFormat;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
// Android specific implementation of VideoCapturer.
// VideoCapturerAndroid.create();
// This class extends VideoCapturer with a method to easily switch between the
// front and back camera. It also provides methods for enumerating valid device
// names.
// Threading notes: this class is called from C++ code, and from Camera
// Java callbacks. Since these calls happen on different threads,
// the entry points to this class are all synchronized. This shouldn't present
// a performance bottleneck because only onPreviewFrame() is called more than
// once (and is called serially on a single thread), so the lock should be
// uncontended. Note that each of these synchronized methods must check
// |camera| for null to account for having possibly waited for stopCapture() to
// complete.
@SuppressWarnings("deprecation")
public class VideoCapturerAndroid extends VideoCapturer implements PreviewCallback {
private final static String TAG = "VideoCapturerAndroid";
private final static int CAMERA_OBSERVER_PERIOD_MS = 5000;
private Camera camera; // Only non-null while capturing.
private CameraThread cameraThread;
private Handler cameraThreadHandler;
private Context applicationContext;
private int id;
private Camera.CameraInfo info;
private SurfaceTexture cameraSurfaceTexture;
private int cameraGlTexture = 0;
private final FramePool videoBuffers = new FramePool();
// Remember the requested format in case we want to switch cameras.
private int requestedWidth;
private int requestedHeight;
private int requestedFramerate;
// The capture format will be the closest supported format to the requested format.
private CaptureFormat captureFormat;
private int cameraFramesCount;
private int captureBuffersCount;
private volatile boolean pendingCameraSwitch;
private CapturerObserver frameObserver = null;
private CameraErrorHandler errorHandler = null;
// Camera error callback.
private final Camera.ErrorCallback cameraErrorCallback =
new Camera.ErrorCallback() {
@Override
public void onError(int error, Camera camera) {
String errorMessage;
if (error == android.hardware.Camera.CAMERA_ERROR_SERVER_DIED) {
errorMessage = "Camera server died!";
} else {
errorMessage = "Camera error: " + error;
}
Log.e(TAG, errorMessage);
if (errorHandler != null) {
errorHandler.onCameraError(errorMessage);
}
}
};
// Camera observer - monitors camera framerate and amount of available
// camera buffers. Observer is excecuted on camera thread.
private final Runnable cameraObserver = new Runnable() {
@Override
public void run() {
int cameraFps = (cameraFramesCount * 1000 + CAMERA_OBSERVER_PERIOD_MS / 2)
/ CAMERA_OBSERVER_PERIOD_MS;
double averageCaptureBuffersCount = 0;
if (cameraFramesCount > 0) {
averageCaptureBuffersCount =
(double)captureBuffersCount / cameraFramesCount;
}
Log.d(TAG, "Camera fps: " + cameraFps + ". CaptureBuffers: " +
String.format("%.1f", averageCaptureBuffersCount) +
". Pending buffers: " + videoBuffers.pendingFramesTimeStamps());
if (cameraFramesCount == 0) {
Log.e(TAG, "Camera freezed.");
if (errorHandler != null) {
errorHandler.onCameraError("Camera failure.");
}
} else {
cameraFramesCount = 0;
captureBuffersCount = 0;
if (cameraThreadHandler != null) {
cameraThreadHandler.postDelayed(this, CAMERA_OBSERVER_PERIOD_MS);
}
}
}
};
// Camera error handler - invoked when camera stops receiving frames
// or any camera exception happens on camera thread.
public static interface CameraErrorHandler {
public void onCameraError(String errorDescription);
}
public static VideoCapturerAndroid create(String name,
CameraErrorHandler errorHandler) {
VideoCapturer capturer = VideoCapturer.create(name);
if (capturer != null) {
VideoCapturerAndroid capturerAndroid = (VideoCapturerAndroid) capturer;
capturerAndroid.errorHandler = errorHandler;
return capturerAndroid;
}
return null;
}
// Switch camera to the next valid camera id. This can only be called while
// the camera is running.
// Returns true on success. False if the next camera does not support the
// current resolution.
public synchronized boolean switchCamera(final Runnable switchDoneEvent) {
if (Camera.getNumberOfCameras() < 2 )
return false;
if (cameraThreadHandler == null) {
Log.e(TAG, "Calling switchCamera() for stopped camera.");
return false;
}
if (pendingCameraSwitch) {
// Do not handle multiple camera switch request to avoid blocking
// camera thread by handling too many switch request from a queue.
Log.w(TAG, "Ignoring camera switch request.");
return false;
}
pendingCameraSwitch = true;
id = (id + 1) % Camera.getNumberOfCameras();
cameraThreadHandler.post(new Runnable() {
@Override public void run() {
switchCameraOnCameraThread(switchDoneEvent);
}
});
return true;
}
// Requests a new output format from the video capturer. Captured frames
// by the camera will be scaled/or dropped by the video capturer.
public synchronized void onOutputFormatRequest(
final int width, final int height, final int fps) {
if (cameraThreadHandler == null) {
Log.e(TAG, "Calling onOutputFormatRequest() for already stopped camera.");
return;
}
cameraThreadHandler.post(new Runnable() {
@Override public void run() {
onOutputFormatRequestOnCameraThread(width, height, fps);
}
});
}
// Reconfigure the camera to capture in a new format. This should only be called while the camera
// is running.
public synchronized void changeCaptureFormat(
final int width, final int height, final int framerate) {
if (cameraThreadHandler == null) {
Log.e(TAG, "Calling changeCaptureFormat() for already stopped camera.");
return;
}
cameraThreadHandler.post(new Runnable() {
@Override public void run() {
startPreviewOnCameraThread(width, height, framerate);
}
});
}
public synchronized List<CaptureFormat> getSupportedFormats() {
return CameraEnumerationAndroid.getSupportedFormats(id);
}
// Return a list of timestamps for the frames that have been sent out, but not returned yet.
// Useful for logging and testing.
public String pendingFramesTimeStamps() {
return videoBuffers.pendingFramesTimeStamps();
}
private VideoCapturerAndroid() {
Log.d(TAG, "VideoCapturerAndroid");
}
// Called by native code.
// Initializes local variables for the camera named |deviceName|. If |deviceName| is empty, the
// first available device is used in order to be compatible with the generic VideoCapturer class.
synchronized boolean init(String deviceName) {
Log.d(TAG, "init: " + deviceName);
if (deviceName == null)
return false;
boolean foundDevice = false;
if (deviceName.isEmpty()) {
this.id = 0;
foundDevice = true;
} else {
for (int i = 0; i < Camera.getNumberOfCameras(); ++i) {
String existing_device = CameraEnumerationAndroid.getDeviceName(i);
if (existing_device != null && deviceName.equals(existing_device)) {
this.id = i;
foundDevice = true;
}
}
}
return foundDevice;
}
String getSupportedFormatsAsJson() throws JSONException {
return CameraEnumerationAndroid.getSupportedFormatsAsJson(id);
}
private class CameraThread extends Thread {
private Exchanger<Handler> handlerExchanger;
public CameraThread(Exchanger<Handler> handlerExchanger) {
this.handlerExchanger = handlerExchanger;
}
@Override public void run() {
Looper.prepare();
exchange(handlerExchanger, new Handler());
Looper.loop();
}
}
// Called by native code. Returns true if capturer is started.
// Note that this actually opens the camera, and Camera callbacks run on the
// thread that calls open(), so this is done on the CameraThread. Since the
// API needs a synchronous success return value we wait for the result.
synchronized void startCapture(
final int width, final int height, final int framerate,
final Context applicationContext, final CapturerObserver frameObserver) {
Log.d(TAG, "startCapture requested: " + width + "x" + height
+ "@" + framerate);
if (applicationContext == null) {
throw new RuntimeException("applicationContext not set.");
}
if (frameObserver == null) {
throw new RuntimeException("frameObserver not set.");
}
if (cameraThreadHandler != null) {
throw new RuntimeException("Camera has already been started.");
}
Exchanger<Handler> handlerExchanger = new Exchanger<Handler>();
cameraThread = new CameraThread(handlerExchanger);
cameraThread.start();
cameraThreadHandler = exchange(handlerExchanger, null);
cameraThreadHandler.post(new Runnable() {
@Override public void run() {
startCaptureOnCameraThread(width, height, framerate, frameObserver,
applicationContext);
}
});
}
private void startCaptureOnCameraThread(
int width, int height, int framerate, CapturerObserver frameObserver,
Context applicationContext) {
Throwable error = null;
this.applicationContext = applicationContext;
this.frameObserver = frameObserver;
try {
Log.d(TAG, "Opening camera " + id);
camera = Camera.open(id);
info = new Camera.CameraInfo();
Camera.getCameraInfo(id, info);
// No local renderer (we only care about onPreviewFrame() buffers, not a
// directly-displayed UI element). Camera won't capture without
// setPreview{Texture,Display}, so we create a SurfaceTexture and hand
// it over to Camera, but never listen for frame-ready callbacks,
// and never call updateTexImage on it.
try {
cameraGlTexture = GlUtil.generateTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES);
cameraSurfaceTexture = new SurfaceTexture(cameraGlTexture);
cameraSurfaceTexture.setOnFrameAvailableListener(null);
camera.setPreviewTexture(cameraSurfaceTexture);
} catch (IOException e) {
Log.e(TAG, "setPreviewTexture failed", error);
throw new RuntimeException(e);
}
Log.d(TAG, "Camera orientation: " + info.orientation +
" .Device orientation: " + getDeviceOrientation());
camera.setErrorCallback(cameraErrorCallback);
startPreviewOnCameraThread(width, height, framerate);
frameObserver.OnCapturerStarted(true);
// Start camera observer.
cameraFramesCount = 0;
captureBuffersCount = 0;
cameraThreadHandler.postDelayed(cameraObserver, CAMERA_OBSERVER_PERIOD_MS);
return;
} catch (RuntimeException e) {
error = e;
}
Log.e(TAG, "startCapture failed", error);
stopCaptureOnCameraThread();
cameraThreadHandler = null;
frameObserver.OnCapturerStarted(false);
if (errorHandler != null) {
errorHandler.onCameraError("Camera can not be started.");
}
return;
}
// (Re)start preview with the closest supported format to |width| x |height| @ |framerate|.
private void startPreviewOnCameraThread(int width, int height, int framerate) {
Log.d(TAG, "startPreviewOnCameraThread requested: " + width + "x" + height + "@" + framerate);
if (camera == null) {
Log.e(TAG, "Calling startPreviewOnCameraThread on stopped camera.");
return;
}
requestedWidth = width;
requestedHeight = height;
requestedFramerate = framerate;
// Find closest supported format for |width| x |height| @ |framerate|.
final Camera.Parameters parameters = camera.getParameters();
final int[] range = CameraEnumerationAndroid.getFramerateRange(parameters, framerate * 1000);
final Camera.Size previewSize = CameraEnumerationAndroid.getClosestSupportedSize(
parameters.getSupportedPreviewSizes(), width, height);
final CaptureFormat captureFormat = new CaptureFormat(
previewSize.width, previewSize.height,
range[Camera.Parameters.PREVIEW_FPS_MIN_INDEX],
range[Camera.Parameters.PREVIEW_FPS_MAX_INDEX]);
// Check if we are already using this capture format, then we don't need to do anything.
if (captureFormat.equals(this.captureFormat)) {
return;
}
// Update camera parameters.
Log.d(TAG, "isVideoStabilizationSupported: " +
parameters.isVideoStabilizationSupported());
if (parameters.isVideoStabilizationSupported()) {
parameters.setVideoStabilization(true);
}
// Note: setRecordingHint(true) actually decrease frame rate on N5.
// parameters.setRecordingHint(true);
if (captureFormat.maxFramerate > 0) {
parameters.setPreviewFpsRange(captureFormat.minFramerate, captureFormat.maxFramerate);
}
parameters.setPreviewSize(captureFormat.width, captureFormat.height);
parameters.setPreviewFormat(captureFormat.imageFormat);
// Picture size is for taking pictures and not for preview/video, but we need to set it anyway
// as a workaround for an aspect ratio problem on Nexus 7.
final Camera.Size pictureSize = CameraEnumerationAndroid.getClosestSupportedSize(
parameters.getSupportedPictureSizes(), width, height);
parameters.setPictureSize(pictureSize.width, pictureSize.height);
// Temporarily stop preview if it's already running.
if (this.captureFormat != null) {
camera.stopPreview();
// Calling |setPreviewCallbackWithBuffer| with null should clear the internal camera buffer
// queue, but sometimes we receive a frame with the old resolution after this call anyway.
camera.setPreviewCallbackWithBuffer(null);
}
// (Re)start preview.
Log.d(TAG, "Start capturing: " + captureFormat);
this.captureFormat = captureFormat;
camera.setParameters(parameters);
videoBuffers.queueCameraBuffers(captureFormat.frameSize(), camera);
camera.setPreviewCallbackWithBuffer(this);
camera.startPreview();
}
// Called by native code. Returns true when camera is known to be stopped.
synchronized void stopCapture() throws InterruptedException {
if (cameraThreadHandler == null) {
Log.e(TAG, "Calling stopCapture() for already stopped camera.");
return;
}
Log.d(TAG, "stopCapture");
cameraThreadHandler.post(new Runnable() {
@Override public void run() {
stopCaptureOnCameraThread();
}
});
cameraThread.join();
cameraThreadHandler = null;
Log.d(TAG, "stopCapture done");
}
private void stopCaptureOnCameraThread() {
doStopCaptureOnCameraThread();
Looper.myLooper().quit();
return;
}
private void doStopCaptureOnCameraThread() {
Log.d(TAG, "stopCaptureOnCameraThread");
if (camera == null) {
return;
}
try {
cameraThreadHandler.removeCallbacks(cameraObserver);
Log.d(TAG, "Stop preview.");
camera.stopPreview();
camera.setPreviewCallbackWithBuffer(null);
videoBuffers.stopReturnBuffersToCamera();
captureFormat = null;
camera.setPreviewTexture(null);
cameraSurfaceTexture = null;
if (cameraGlTexture != 0) {
GLES20.glDeleteTextures(1, new int[] {cameraGlTexture}, 0);
cameraGlTexture = 0;
}
Log.d(TAG, "Release camera.");
camera.release();
camera = null;
} catch (IOException e) {
Log.e(TAG, "Failed to stop camera", e);
}
}
private void switchCameraOnCameraThread(Runnable switchDoneEvent) {
Log.d(TAG, "switchCameraOnCameraThread");
doStopCaptureOnCameraThread();
startCaptureOnCameraThread(requestedWidth, requestedHeight, requestedFramerate, frameObserver,
applicationContext);
pendingCameraSwitch = false;
Log.d(TAG, "switchCameraOnCameraThread done");
if (switchDoneEvent != null) {
switchDoneEvent.run();
}
}
private void onOutputFormatRequestOnCameraThread(
int width, int height, int fps) {
if (camera == null) {
return;
}
Log.d(TAG, "onOutputFormatRequestOnCameraThread: " + width + "x" + height +
"@" + fps);
frameObserver.OnOutputFormatRequest(width, height, fps);
}
void returnBuffer(long timeStamp) {
videoBuffers.returnBuffer(timeStamp);
}
private int getDeviceOrientation() {
int orientation = 0;
WindowManager wm = (WindowManager) applicationContext.getSystemService(
Context.WINDOW_SERVICE);
switch(wm.getDefaultDisplay().getRotation()) {
case Surface.ROTATION_90:
orientation = 90;
break;
case Surface.ROTATION_180:
orientation = 180;
break;
case Surface.ROTATION_270:
orientation = 270;
break;
case Surface.ROTATION_0:
default:
orientation = 0;
break;
}
return orientation;
}
// Called on cameraThread so must not "synchronized".
@Override
public void onPreviewFrame(byte[] data, Camera callbackCamera) {
if (Thread.currentThread() != cameraThread) {
throw new RuntimeException("Camera callback not on camera thread?!?");
}
if (camera == null) {
return;
}
if (camera != callbackCamera) {
throw new RuntimeException("Unexpected camera in callback!");
}
final long captureTimeNs =
TimeUnit.MILLISECONDS.toNanos(SystemClock.elapsedRealtime());
captureBuffersCount += videoBuffers.numCaptureBuffersAvailable();
int rotation = getDeviceOrientation();
if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
rotation = 360 - rotation;
}
rotation = (info.orientation + rotation) % 360;
// Mark the frame owning |data| as used.
// Note that since data is directBuffer,
// data.length >= videoBuffers.frameSize.
if (videoBuffers.reserveByteBuffer(data, captureTimeNs)) {
cameraFramesCount++;
frameObserver.OnFrameCaptured(data, videoBuffers.frameSize, captureFormat.width,
captureFormat.height, rotation, captureTimeNs);
} else {
Log.w(TAG, "reserveByteBuffer failed - dropping frame.");
}
}
// runCameraThreadUntilIdle make sure all posted messages to the cameraThread
// is processed before returning. It does that by itself posting a message to
// to the message queue and waits until is has been processed.
// It is used in tests.
void runCameraThreadUntilIdle() {
if (cameraThreadHandler == null)
return;
final Exchanger<Boolean> result = new Exchanger<Boolean>();
cameraThreadHandler.post(new Runnable() {
@Override public void run() {
exchange(result, true); // |true| is a dummy here.
}
});
exchange(result, false); // |false| is a dummy value here.
return;
}
// Exchanges |value| with |exchanger|, converting InterruptedExceptions to
// RuntimeExceptions (since we expect never to see these).
private static <T> T exchange(Exchanger<T> exchanger, T value) {
try {
return exchanger.exchange(value);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
// Class used for allocating and bookkeeping video frames. All buffers are
// direct allocated so that they can be directly used from native code. This class is
// synchronized and can be called from multiple threads.
private static class FramePool {
// Arbitrary queue depth. Higher number means more memory allocated & held,
// lower number means more sensitivity to processing time in the client (and
// potentially stalling the capturer if it runs out of buffers to write to).
private static final int numCaptureBuffers = 3;
// This container tracks the buffers added as camera callback buffers. It is needed for finding
// the corresponding ByteBuffer given a byte[].
private final Map<byte[], ByteBuffer> queuedBuffers = new IdentityHashMap<byte[], ByteBuffer>();
// This container tracks the frames that have been sent but not returned. It is needed for
// keeping the buffers alive and for finding the corresponding ByteBuffer given a timestamp.
private final Map<Long, ByteBuffer> pendingBuffers = new HashMap<Long, ByteBuffer>();
private int frameSize = 0;
private Camera camera;
synchronized int numCaptureBuffersAvailable() {
return queuedBuffers.size();
}
// Discards previous queued buffers and adds new callback buffers to camera.
synchronized void queueCameraBuffers(int frameSize, Camera camera) {
this.camera = camera;
this.frameSize = frameSize;
queuedBuffers.clear();
for (int i = 0; i < numCaptureBuffers; ++i) {
final ByteBuffer buffer = ByteBuffer.allocateDirect(frameSize);
camera.addCallbackBuffer(buffer.array());
queuedBuffers.put(buffer.array(), buffer);
}
Log.d(TAG, "queueCameraBuffers enqueued " + numCaptureBuffers
+ " buffers of size " + frameSize + ".");
}
synchronized String pendingFramesTimeStamps() {
List<Long> timeStampsMs = new ArrayList<Long>();
for (Long timeStampNs : pendingBuffers.keySet()) {
timeStampsMs.add(TimeUnit.NANOSECONDS.toMillis(timeStampNs));
}
return timeStampsMs.toString();
}
synchronized void stopReturnBuffersToCamera() {
this.camera = null;
queuedBuffers.clear();
// Frames in |pendingBuffers| need to be kept alive until they are returned.
Log.d(TAG, "stopReturnBuffersToCamera called."
+ (pendingBuffers.isEmpty() ?
" All buffers have been returned."
: " Pending buffers: " + pendingFramesTimeStamps() + "."));
}
synchronized boolean reserveByteBuffer(byte[] data, long timeStamp) {
final ByteBuffer buffer = queuedBuffers.remove(data);
if (buffer == null) {
// Frames might be posted to |onPreviewFrame| with the previous format while changing
// capture format in |startPreviewOnCameraThread|. Drop these old frames.
Log.w(TAG, "Received callback buffer from previous configuration with length: "
+ (data == null ? "null" : data.length));
return false;
}
if (buffer.capacity() != frameSize) {
throw new IllegalStateException("Callback buffer has unexpected frame size");
}
if (pendingBuffers.containsKey(timeStamp)) {
Log.e(TAG, "Timestamp already present in pending buffers - they need to be unique");
return false;
}
pendingBuffers.put(timeStamp, buffer);
if (queuedBuffers.isEmpty()) {
Log.v(TAG, "Camera is running out of capture buffers."
+ " Pending buffers: " + pendingFramesTimeStamps());
}
return true;
}
synchronized void returnBuffer(long timeStamp) {
final ByteBuffer returnedFrame = pendingBuffers.remove(timeStamp);
if (returnedFrame == null) {
throw new RuntimeException("unknown data buffer with time stamp "
+ timeStamp + "returned?!?");
}
if (camera != null && returnedFrame.capacity() == frameSize) {
camera.addCallbackBuffer(returnedFrame.array());
if (queuedBuffers.isEmpty()) {
Log.v(TAG, "Frame returned when camera is running out of capture"
+ " buffers for TS " + TimeUnit.NANOSECONDS.toMillis(timeStamp));
}
queuedBuffers.put(returnedFrame.array(), returnedFrame);
return;
}
if (returnedFrame.capacity() != frameSize) {
Log.d(TAG, "returnBuffer with time stamp "
+ TimeUnit.NANOSECONDS.toMillis(timeStamp)
+ " called with old frame size, " + returnedFrame.capacity() + ".");
// Since this frame has the wrong size, don't requeue it. Frames with the correct size are
// created in queueCameraBuffers so this must be an old buffer.
return;
}
Log.d(TAG, "returnBuffer with time stamp "
+ TimeUnit.NANOSECONDS.toMillis(timeStamp)
+ " called after camera has been stopped.");
}
}
// Interface used for providing callbacks to an observer.
interface CapturerObserver {
// Notify if the camera have been started successfully or not.
// Called on a Java thread owned by VideoCapturerAndroid.
abstract void OnCapturerStarted(boolean success);
// Delivers a captured frame. Called on a Java thread owned by
// VideoCapturerAndroid.
abstract void OnFrameCaptured(byte[] data, int length, int width, int height,
int rotation, long timeStamp);
// Requests an output format from the video capturer. Captured frames
// by the camera will be scaled/or dropped by the video capturer.
// Called on a Java thread owned by VideoCapturerAndroid.
abstract void OnOutputFormatRequest(int width, int height, int fps);
}
// An implementation of CapturerObserver that forwards all calls from
// Java to the C layer.
static class NativeObserver implements CapturerObserver {
private final long nativeCapturer;
public NativeObserver(long nativeCapturer) {
this.nativeCapturer = nativeCapturer;
}
@Override
public void OnCapturerStarted(boolean success) {
nativeCapturerStarted(nativeCapturer, success);
}
@Override
public void OnFrameCaptured(byte[] data, int length, int width, int height,
int rotation, long timeStamp) {
nativeOnFrameCaptured(nativeCapturer, data, length, width, height, rotation, timeStamp);
}
@Override
public void OnOutputFormatRequest(int width, int height, int fps) {
nativeOnOutputFormatRequest(nativeCapturer, width, height, fps);
}
private native void nativeCapturerStarted(long nativeCapturer,
boolean success);
private native void nativeOnFrameCaptured(long nativeCapturer,
byte[] data, int length, int width, int height, int rotation, long timeStamp);
private native void nativeOnOutputFormatRequest(long nativeCapturer,
int width, int height, int fps);
}
} |
package sophena.math.costs;
import static java.lang.Math.pow;
import sophena.calc.CostResultItem;
import sophena.model.Project;
public class CapitalCosts {
private CapitalCosts() {
}
public static double get(CostResultItem item, Project project,
double interestRate) {
if (item == null || item.costs == null
|| project == null || project.costSettings == null)
return 0;
double interestFactor = 1 + interestRate / 100;
double priceChangeFactor = project.costSettings.investmentFactor;
return calculate(
item.costs.investment,
item.costs.duration,
project.duration,
interestFactor,
priceChangeFactor);
}
/**
* Low level function to calculate the capital costs of a component
* according to VDI 2067.
*
* @param A
* Investment amount (in EUR)
* @param Tu
* service life (in years) of the component
* @param T
* obervation period (in years)
* @param q
* interest factor (e.g. 1.02)
* @param r
* price change factor (e.g. 1.02)
*/
private static double calculate(
double A,
int Tu,
int T,
double q,
double r) {
double sum = A;
// add cash values of possible replacements
int t = Tu;
int n = 0; // the number of replacements
while (t < T) {
sum += A * pow(r, t) / pow(q, t);
n++;
t += Tu;
}
// remove a possible residual value
int Tr = Tu * (1 + n) - T;
if (Tr > 0) {
double factor = ((double) ((n + 1) * Tu - T)) / ((double) Tu);
double Rv = A * pow(r, n * Tu) * factor * 1 / pow(q, T);
sum -= Rv;
}
// apply the annuity factor
double a = (q - 1) / (1 - pow(q, -T));
return sum * a;
}
} |
package org.hd.d.edh;
import java.util.Arrays;
import org.hd.d.edh.FUELINST.TrafficLightsInterface;
/**Main (command-line) entry-point for the data handler.
*
*/
public final class Main
{
/**Print a summary of command options to stderr. */
public static void printOptions()
{
System.err.println("Commands/options");
System.err.println(" -help");
System.err.println(" This summary/help.");
System.err.println(" trafficLights [-class full.generator.classname] {args}");
System.err.println(" FUELINST outfile.html TIBCOfile.gz {TIBCOfile.gz*}");
System.err.println(" FUELINST outfile.html <directory> [regex-filematch-pattern]");
}
/**Accepts command-line arguments.
*
* Accepts the following commands:
* <ul>
* <li>trafficLights [-class full.generator.classname] {args}<br />
* Using the default implementation,
* args consists of one optional filename.html
* from which other output file names (for flags, xhtml, caches, etc)
* are derived.
* <p>
* Shows red/yellow/green 'start your appliance now' indication
* based primarily on current UK grid carbon intensity.
* Can write HTML output for eou site if output filename is supplied,
* else writes a summary on System.out.
* Will also delete outfile.html.flag file if status is GREEN, else will create it,
* which is useful for automated remote 200/404 status check.
* <p>
* If a full class name is supplied
* then it is passed the remaining arguments
* and may interpret them as it wishes.
* </li>
* <li>FUELINST outfile.html TIBCOfile.gz {TIBCOfile.gz*}</li>
* <li>FUELINST outfile.html <directory> [regex-filematch-pattern]<br />
* Extracts fuel mix and carbon-intensity info,
* from one or more historical TIBCO GZipped format files
* either listed as explicit files
* or as a directory and an optional regex pattern to accept files by name,
* and then is parsed into MW by fuel type
* or converted to intensity in units of kgCO2/kWh
* with various analyses performed over the data.
* </li>
* </ul>
*/
public static void main(final String[] args)
{
if((args.length < 1) || "-help".equals(args[0]))
{
printOptions();
return; // Not an error.
}
// Command is first argument.
final String command = args[0];
try
{
if("FUELINST".equals(command))
{
FUELINSTHistorical.doHistoricalAnalysis(args);
return; // Completed.
}
else if("trafficLights".equals(command))
{;
final TrafficLightsInterface impl;
// Check if "-class" "name" optional args are present.
final boolean classSpecified = (args.length >= 2) && "-class".equals(args[1]);
// If first optional argument is "-class"
// then attempt to create an instance of the specified class.
if(classSpecified)
{
final String classname = args[2];
System.out.println("Class specified: " + classname);
impl = (TrafficLightsInterface) Class.forName(classname).newInstance();
}
// Else use the default implementation.
else
{ impl = (new FUELINST.TrafficLightsDEFAULT()); }
// Pass in trailing args (if any) to impl;
// leading 'trafficLights' (and possible -class name) is omitted.
impl.doTrafficLights(Arrays.copyOfRange(args, classSpecified ? 3 : 1, args.length));
return; // Completed.
}
}
catch(final Throwable e)
{
System.err.println("FAILED command: " + command);
e.printStackTrace();
System.exit(1);
}
// Unrecognised/unhandled command.
System.err.println("Unrecognised or unhandled command: " + command);
printOptions();
System.exit(1);
}
} |
package com.googlecode.yatspec.state;
import com.googlecode.yatspec.rendering.junit.MavenSurefireScenarioNameRenderer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static com.googlecode.yatspec.fixture.RandomFixtures.anyString;
import static com.googlecode.yatspec.junit.SpecRunner.SCENARIO_NAME_RENDERER;
import static com.googlecode.yatspec.state.TestMethod.invocationName;
import static java.util.Collections.emptyList;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class TestMethodTest {
private static final String MAVEN_SCENARIO_NAME_RENDERER = MavenSurefireScenarioNameRenderer.class.getName();
private String originalScenarioNameRenderer;
@Before
public void setUp() throws Exception {
originalScenarioNameRenderer = System.getProperty(SCENARIO_NAME_RENDERER);
}
@After
public void tearDown() throws Exception {
if (null != originalScenarioNameRenderer) {
System.setProperty(SCENARIO_NAME_RENDERER, originalScenarioNameRenderer);
} else {
System.clearProperty(SCENARIO_NAME_RENDERER);
}
}
@Test
public void createsAnInvocationNameForAScenarioNameWithoutArgsWithDefaultRenderer() throws Exception {
System.clearProperty(SCENARIO_NAME_RENDERER);
String methodName = anyString();
String expectedInvocationName = methodName + "()";
List<String> noArgs = emptyList();
ScenarioName scenarioName = new ScenarioName(methodName, noArgs);
String actualInvocationName = invocationName(scenarioName);
assertThat(actualInvocationName, is(expectedInvocationName));
}
@Test
public void createsAnInvocationNameForAScenarioNameWithArgs() throws Exception {
String methodName = anyString();
String firstArg = anyString();
String secondArg = anyString();
String expectedInvocationName = String.format("%s(%s, %s)", methodName, firstArg, secondArg);
List<String> someArgs = Arrays.asList(firstArg, secondArg);
ScenarioName scenarioName = new ScenarioName(methodName, someArgs);
String actualInvocationName = invocationName(scenarioName);
assertThat(actualInvocationName, is(expectedInvocationName));
}
@Test
public void createsAMavenSurefireInvocationNameForAScenarioNameWithoutArgs() throws Exception {
System.setProperty(SCENARIO_NAME_RENDERER, MAVEN_SCENARIO_NAME_RENDERER);
String methodName = anyString();
List<String> noArgs = emptyList();
ScenarioName scenarioName = new ScenarioName(methodName, noArgs);
String actualInvocationName = invocationName(scenarioName);
assertThat(actualInvocationName, is(methodName));
}
} |
package com.axelor.gradle;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.publish.maven.tasks.PublishToMavenRepository;
import com.axelor.gradle.support.HotswapSupport;
import com.axelor.gradle.support.ScriptsSupport;
import com.axelor.gradle.support.TomcatSupport;
import com.axelor.gradle.support.WarSupport;
public class AppPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
project.getPlugins().apply(ModulePlugin.class);
project.getPlugins().apply(WarSupport.class);
project.getPlugins().apply(ScriptsSupport.class);
project.getPlugins().apply(TomcatSupport.class);
project.getPlugins().apply(HotswapSupport.class);
// disable publishing apps by default
project.getTasks().withType(PublishToMavenRepository.class).all(task -> task.setEnabled(false));
}
} |
package thredds.featurecollection;
import org.slf4j.Logger;
import thredds.client.catalog.Catalog;
import thredds.client.catalog.Dataset;
import thredds.client.catalog.Documentation;
import thredds.client.catalog.ThreddsMetadata;
import thredds.client.catalog.builder.CatalogBuilder;
import thredds.client.catalog.builder.CatalogRefBuilder;
import thredds.client.catalog.builder.DatasetBuilder;
import thredds.inventory.CollectionUpdateType;
import thredds.inventory.MFileCollectionManager;
import thredds.server.catalog.FeatureCollectionRef;
import thredds.server.catalog.writer.ThreddsMetadataExtractor;
import ucar.nc2.constants.FeatureType;
import ucar.nc2.dataset.NetcdfDataset;
import ucar.nc2.dt.GridDataset;
import ucar.nc2.ft.fmrc.Fmrc;
import ucar.nc2.ft2.coverage.CoverageCollection;
import ucar.nc2.ft2.coverage.FeatureDatasetCoverage;
import ucar.nc2.ft2.coverage.adapter.DtCoverageAdapter;
import ucar.nc2.ft2.coverage.adapter.DtCoverageDataset;
import ucar.nc2.time.CalendarDate;
import ucar.nc2.time.CalendarDateRange;
import ucar.nc2.units.DateRange;
import ucar.unidata.util.StringUtil2;
import javax.annotation.concurrent.ThreadSafe;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.util.*;
/**
* InvDataset Feature Collection for Fmrc
* Generate anew each call; use object caching if needed to improve efficiency
*
* @author caron
* @since Mar 3, 2010
*/
@ThreadSafe
public class InvDatasetFcFmrc extends InvDatasetFeatureCollection {
static private final Logger logger = org.slf4j.LoggerFactory.getLogger(InvDatasetFcFmrc.class);
static private final String FMRC = "fmrc.ncd";
static private final String BEST = "best.ncd";
static private final String RUNS = "runs";
static private final String RUN_NAME = "RUN_";
static private final String RUN_TITLE = "Forecast Model Run";
static private final String FORECAST = "forecast";
static private final String FORECAST_NAME = "ConstantForecast_";
static private final String FORECAST_TITLE = "Constant Forecast Date";
static private final String OFFSET = "offset";
static private final String OFFSET_NAME = "Offset_";
static private final String OFFSET_TITLE = "Constant Forecast Offset";
private final Fmrc fmrc;
private final Set<FeatureCollectionConfig.FmrcDatasetType> wantDatasets;
InvDatasetFcFmrc(FeatureCollectionRef parent, FeatureCollectionConfig config) {
super(parent, config);
makeCollection();
// check if FMRC is empty, and if so, throw excpetion and log it.
boolean filesFound = datasetCollection.getFilesSorted().iterator().hasNext();
if (!filesFound) {
String collectionName = parent.getCollectionName();
String spec = config.spec;
String catalog = parent.getParentCatalog().getUriString();
String logMsg = String.format("The FMRC %s defined in %s cannot find any files matching the spec %s.",
collectionName, catalog,spec);
logger.warn(logMsg);
String errMsg = String.format("The FMRC %s cannot find any files in the collection.", collectionName);
throw new RuntimeException(errMsg);
}
Formatter errlog = new Formatter();
try {
fmrc = new Fmrc(datasetCollection, config);
} catch (Exception e) {
throw new RuntimeException(errlog.toString());
}
this.wantDatasets = config.fmrcConfig.datasets;
state = new State(null);
}
@Override
public void close() {
if (fmrc != null)
fmrc.close();
super.close();
}
/* @Override // overriding superclass -WHY?
public void update(CollectionUpdateType force) {
fmrc.update(); // so when is work done?
} */
protected void update(CollectionUpdateType force) throws IOException { // this may be called from a background thread, or from checkState() request thread
logger.debug("update {} force={}", name, force);
boolean changed;
MFileCollectionManager dcm;
switch (force) {
case always:
case test:
dcm = (MFileCollectionManager) getDatasetCollectionManager();
changed = dcm.scan(false);
if (changed)
super.update(force);
break;
case never:
return;
default:
super.update(force);
}
}
public void updateProto() {
fmrc.updateProto();
}
@Override
protected void updateCollection(State localState, CollectionUpdateType force) { // LOOK probably not right
try {
fmrc.update();
boolean checkInv = fmrc.checkInvState(localState.lastInvChange);
boolean checkProto = fmrc.checkProtoState(localState.lastProtoChange);
if (checkProto) {
// add Variables, GeospatialCoverage, TimeCoverage
GridDataset gds = fmrc.getDataset2D(null);
if (null != gds) {
ThreddsMetadataExtractor extractor = new ThreddsMetadataExtractor();
localState.vars = extractor.extractVariables(null, gds);
localState.coverage = extractor.extractGeospatial(gds);
localState.dateRange = extractor.extractCalendarDateRange(gds);
}
localState.lastProtoChange = System.currentTimeMillis();
}
if (checkInv) {
// makeDatasetTop(localState);
localState.lastInvChange = System.currentTimeMillis();
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
// called by DataRootHandler.makeDynamicCatalog() when the catref is requested
@Override
public CatalogBuilder makeCatalog(String match, String orgPath, URI catURI) throws IOException {
logger.debug("FMRC make catalog for " + match + " " + catURI);
State localState = checkState();
try {
if ((match == null) || (match.length() == 0)) {
return makeCatalogTop(catURI, localState);
} else if (match.equals(RUNS) && wantDatasets.contains(FeatureCollectionConfig.FmrcDatasetType.Runs))
return makeCatalogRuns(catURI, localState);
else if (match.equals(OFFSET) && wantDatasets.contains(FeatureCollectionConfig.FmrcDatasetType.ConstantOffsets))
return makeCatalogOffsets(catURI, localState);
else if (match.equals(FORECAST) && wantDatasets.contains(FeatureCollectionConfig.FmrcDatasetType.ConstantForecasts))
return makeCatalogForecasts(catURI, localState);
else if (match.startsWith(FILES) && wantDatasets.contains(FeatureCollectionConfig.FmrcDatasetType.Files)) {
return makeCatalogFiles(catURI, localState, datasetCollection.getFilenames(), true);
}
} catch (Exception e) {
logger.error("Error making catalog for " + configPath, e);
}
return null;
}
private CatalogBuilder makeCatalog(URI catURI, State localState, String name) throws IOException {
Catalog parentCatalog = parent.getParentCatalog();
CatalogBuilder result = new CatalogBuilder();
result.setName(makeFullName(parent));
result.setVersion(parentCatalog.getVersion());
result.setBaseURI(catURI); // LOOK is catURI right ??
result.addService(virtualService);
DatasetBuilder top = new DatasetBuilder(null);
top.transferInheritedMetadata(parent); // make all inherited metadata local
top.setName(name);
ThreddsMetadata tmi = top.getInheritableMetadata();
tmi.set(Dataset.ServiceName, virtualService.getName());
if (localState.coverage != null) tmi.set(Dataset.GeospatialCoverage, localState.coverage);
if (localState.dateRange != null) tmi.set(Dataset.TimeCoverage, localState.dateRange);
if (localState.vars != null) tmi.set(Dataset.VariableGroups, localState.vars);
result.addDataset(top);
for (DatasetBuilder ds : makeRunDatasets(top))
top.addDataset(ds);
return result;
}
private CatalogBuilder makeCatalogRuns(URI catURI, State localState) throws IOException {
CatalogBuilder runCatalog = makeCatalog(catURI, localState, RUN_TITLE);
DatasetBuilder top = runCatalog.getTopDataset();
if (top != null)
for (DatasetBuilder ds : makeRunDatasets(top))
top.addDataset(ds);
return runCatalog;
}
private CatalogBuilder makeCatalogOffsets(URI catURI, State localState) throws IOException {
CatalogBuilder offCatalog = makeCatalog(catURI, localState, OFFSET_TITLE);
DatasetBuilder top = offCatalog.getTopDataset();
if (top != null)
for (DatasetBuilder ds : makeOffsetDatasets(top))
top.addDataset(ds);
return offCatalog;
}
private CatalogBuilder makeCatalogForecasts(URI catURI, State localState) throws IOException {
CatalogBuilder offCatalog = makeCatalog(catURI, localState, OFFSET_TITLE);
DatasetBuilder top = offCatalog.getTopDataset();
if (top != null)
for (DatasetBuilder ds : makeOffsetDatasets(top))
top.addDataset(ds);
return offCatalog;
}
private List<DatasetBuilder> makeRunDatasets(DatasetBuilder parent) throws IOException {
List<DatasetBuilder> datasets = new ArrayList<>();
for (CalendarDate runDate : fmrc.getRunDates()) {
String myname = name + "_" + RUN_NAME + runDate;
myname = StringUtil2.replace(myname, ' ', "_");
DatasetBuilder nested = new DatasetBuilder(parent);
nested.setName(myname);
nested.put(Dataset.UrlPath, this.configPath + "/" + RUNS + "/" + myname);
nested.put(Dataset.Id, this.configPath + "/" + RUNS + "/" + myname);
nested.addToList(Dataset.Documentation, new Documentation(null, null, null, "summary", "Data from Run " + myname));
CalendarDateRange cdr = fmrc.getDateRangeForRun(runDate);
if (cdr != null)
nested.put(Dataset.TimeCoverage, new DateRange(cdr));
datasets.add(nested);
}
Collections.reverse(datasets);
return datasets;
}
private List<DatasetBuilder> makeOffsetDatasets(DatasetBuilder parent) throws IOException {
List<DatasetBuilder> datasets = new ArrayList<>();
for (double offset : fmrc.getForecastOffsets()) {
String myname = name + "_" + OFFSET_NAME + offset + "hr";
myname = StringUtil2.replace(myname, ' ', "_");
DatasetBuilder nested = new DatasetBuilder(parent);
nested.setName(myname);
nested.put(Dataset.UrlPath, this.configPath + "/" + OFFSET + "/" + myname);
nested.put(Dataset.Id, this.configPath + "/" + OFFSET + "/" + myname);
nested.addToList(Dataset.Documentation, new Documentation(null, null, null, "summary", "Data from the " + offset + " hour forecasts, across different model runs."));
CalendarDateRange cdr = fmrc.getDateRangeForOffset(offset);
if (cdr != null)
nested.put(Dataset.TimeCoverage, new DateRange(cdr));
datasets.add(nested);
}
return datasets;
}
private List<DatasetBuilder> makeForecastDatasets(DatasetBuilder parent) throws IOException {
List<DatasetBuilder> datasets = new ArrayList<>();
for (CalendarDate forecastDate : fmrc.getForecastDates()) {
String myname = name + "_" + FORECAST_NAME + forecastDate;
myname = StringUtil2.replace(myname, ' ', "_");
DatasetBuilder nested = new DatasetBuilder(parent);
nested.setName(myname);
nested.put(Dataset.UrlPath, this.configPath + "/" + FORECAST + "/" + myname);
nested.put(Dataset.Id, this.configPath + "/" + FORECAST + "/" + myname);
nested.addToList(Dataset.Documentation, new Documentation(null, null, null, "summary", "Data with the same forecast date, " + name + ", across different model runs."));
nested.put(Dataset.TimeCoverage, new DateRange(CalendarDateRange.of(forecastDate, forecastDate)));
datasets.add(nested);
}
return datasets;
}
@Override
protected DatasetBuilder makeDatasetTop(URI catURI, State localState) {
DatasetBuilder top = new DatasetBuilder(null);
top.transferInheritedMetadata(parent); // make all inherited metadata local
top.setName(name);
top.addServiceToCatalog(virtualService);
ThreddsMetadata tmi = top.getInheritableMetadata(); // LOOK allow to change ??
tmi.set(Dataset.FeatureType, FeatureType.GRID.toString()); // override GRIB
tmi.set(Dataset.ServiceName, virtualService.getName());
if (localState.coverage != null) tmi.set(Dataset.GeospatialCoverage, localState.coverage);
if (localState.dateRange != null) tmi.set(Dataset.TimeCoverage, localState.dateRange);
if (localState.vars != null) tmi.set(Dataset.VariableGroups, localState.vars);
if (wantDatasets.contains(FeatureCollectionConfig.FmrcDatasetType.TwoD)) {
DatasetBuilder twoD = new DatasetBuilder(top);
twoD.setName("Forecast Model Run Collection (2D time coordinates)");
String myname = name + "_" + FMRC;
myname = StringUtil2.replace(myname, ' ', "_");
twoD.put(Dataset.UrlPath, this.configPath + "/" + myname);
twoD.put(Dataset.Id, this.configPath + "/" + myname);
twoD.addToList(Dataset.Documentation, new Documentation(null, null, null, "summary", "Forecast Model Run Collection (2D time coordinates)."));
top.addDataset(twoD);
}
if (wantDatasets.contains(FeatureCollectionConfig.FmrcDatasetType.Best)) {
DatasetBuilder best = new DatasetBuilder(top);
best.setName("Best Time Series");
String myname = name + "_" + BEST;
myname = StringUtil2.replace(myname, ' ', "_");
best.put(Dataset.UrlPath, this.configPath + "/" + myname);
best.put(Dataset.Id, this.configPath + "/" + myname);
best.addToList(Dataset.Documentation, new Documentation(null, null, null, "summary", "Best time series, taking the data from the most recent run available."));
top.addDataset(best);
}
if (config.fmrcConfig.getBestDatasets() != null) {
for (FeatureCollectionConfig.BestDataset bd : config.fmrcConfig.getBestDatasets()) {
DatasetBuilder ds = new DatasetBuilder(top);
ds.setName(bd.name);
String myname = name + "_" + bd.name;
myname = StringUtil2.replace(myname, ' ', "_");
ds.put(Dataset.UrlPath, this.configPath + "/" + myname);
ds.put(Dataset.Id, this.configPath + "/" + myname);
ds.addToList(Dataset.Documentation, new Documentation(null, null, null, "summary", "Best time series, excluding offset hours less than " + bd.greaterThan));
top.addDataset(ds);
}
}
if (wantDatasets.contains(FeatureCollectionConfig.FmrcDatasetType.Runs)) {
CatalogRefBuilder ds = new CatalogRefBuilder(top);
ds.setTitle(RUN_TITLE);
ds.setHref(getCatalogHref(RUNS));
top.addDataset(ds);
}
if (wantDatasets.contains(FeatureCollectionConfig.FmrcDatasetType.ConstantForecasts)) {
CatalogRefBuilder ds = new CatalogRefBuilder(top);
ds.setTitle(FORECAST_TITLE);
ds.setHref(getCatalogHref(FORECAST));
top.addDataset(ds);
}
if (wantDatasets.contains(FeatureCollectionConfig.FmrcDatasetType.ConstantOffsets)) {
CatalogRefBuilder ds = new CatalogRefBuilder(top);
ds.setTitle(OFFSET_TITLE);
ds.setHref(getCatalogHref(OFFSET));
top.addDataset(ds);
}
if (wantDatasets.contains(FeatureCollectionConfig.FmrcDatasetType.Files) && (topDirectory != null)) {
CatalogRefBuilder ds = new CatalogRefBuilder(top);
ds.setTitle(FILES);
ds.setHref(getCatalogHref(FILES));
top.addDataset(ds);
}
return top;
}
public CoverageCollection getGridCoverage(String matchPath) throws IOException {
NetcdfDataset ncd = getNetcdfDataset(matchPath);
if (ncd == null) return null;
DtCoverageDataset gds = new DtCoverageDataset(ncd);
FeatureDatasetCoverage cc = DtCoverageAdapter.factory(gds, new Formatter());
if (cc == null) return null;
assert cc.getCoverageCollections().size() == 1; // LOOK probably want to use endpoint#datasetName ?
return cc.getCoverageCollections().get(0);
}
@Override
public ucar.nc2.dt.grid.GridDataset getGridDataset(String matchPath) throws IOException {
State localState = checkState();
int pos = matchPath.indexOf('/');
String wantType = (pos > -1) ? matchPath.substring(0, pos) : matchPath;
String wantName = (pos > -1) ? matchPath.substring(pos + 1) : matchPath;
String hasName = StringUtil2.replace(name, ' ', "_") + "_";
try {
if (wantType.equalsIgnoreCase(FILES)) {
NetcdfDataset ncd = getNetcdfDataset(matchPath);
return ncd == null ? null : new ucar.nc2.dt.grid.GridDataset(ncd);
} else if (wantName.equals(hasName + FMRC) && wantDatasets.contains(FeatureCollectionConfig.FmrcDatasetType.TwoD)) {
return fmrc.getDataset2D(null);
} else if (wantName.equals(hasName + BEST) && wantDatasets.contains(FeatureCollectionConfig.FmrcDatasetType.Best)) {
return fmrc.getDatasetBest();
} else if (wantType.equals(OFFSET) && wantDatasets.contains(FeatureCollectionConfig.FmrcDatasetType.ConstantOffsets)) {
int pos1 = wantName.lastIndexOf(OFFSET_NAME);
int pos2 = wantName.lastIndexOf("hr");
if ((pos1 < 0) || (pos2 < 0)) return null;
String id = wantName.substring(pos1 + OFFSET_NAME.length(), pos2);
try {
double hour = Double.parseDouble(id);
return fmrc.getConstantOffsetDataset(hour);
} catch (NumberFormatException e) {
return null; // user input error
}
} else if (wantType.equals(RUNS) && wantDatasets.contains(FeatureCollectionConfig.FmrcDatasetType.Runs)) {
int pos1 = wantName.indexOf(RUN_NAME);
if (pos1 < 0) return null;
String id = wantName.substring(pos1 + RUN_NAME.length());
CalendarDate date = CalendarDate.parseISOformat(null, id);
if (date == null) return null; // user input error
return fmrc.getRunTimeDataset(date);
} else if (wantType.equals(FORECAST) && wantDatasets.contains(FeatureCollectionConfig.FmrcDatasetType.ConstantForecasts)) {
int pos1 = wantName.indexOf(FORECAST_NAME);
if (pos1 < 0) return null;
String id = wantName.substring(pos1 + FORECAST_NAME.length());
CalendarDate date = CalendarDate.parseISOformat(null, id);
if (date == null) return null; // user input error
return fmrc.getConstantForecastDataset(date);
} else if (config.fmrcConfig.getBestDatasets() != null) {
for (FeatureCollectionConfig.BestDataset bd : config.fmrcConfig.getBestDatasets()) {
if (wantName.endsWith(bd.name)) {
return fmrc.getDatasetBest(bd);
}
}
}
} catch (FileNotFoundException e) {
return null;
}
return null;
}
} |
package lab3;
public class SplayTreeSet<E extends Comparable<? super E>> implements SimpleSet<E> {
private int size;
private SplayNode root;
private class SplayNode{
private E value;
private SplayNode left, right;
public SplayNode(E value){
this.value = value;
}
}
public SplayTreeSet(){
size = 0;
}
public int size(){
return size;
}
public boolean add(E x){
size++;
return false;
}
public boolean remove(E x){
size
return false;
}
public boolean contains(E x){
return false;
}
private SplayNode splay(SplayNode node, E value){
if(node == null) return null;
if(value.compareTo(node.value) < 0){
if(node.left == null) return node;
if(value.compareTo(node.left.value) < 0){
node.left.left = splay(node.left.left, value);
node = rotateRight(node);
}
else if(value.compareTo(node.left.value) > 0){
node.left.right = splay(node.left.right, value);
if(node.left.right != null){
node.left = rotateLeft(node.left);
}
}
if(node.left == null) return node;
else return rotateLeft(node);
}
else if(value.compareTo(node.value) > 0){
if(node.right == null) return node;
}
return node;
}
private SplayNode rotateRight(SplayNode node){
SplayNode newNode = node.left;
node.left = newNode.right;
newNode.right = node;
return newNode;
}
private SplayNode rotateLeft(SplayNode node){
SplayNode newNode = node.right;
node.right = newNode.left;
newNode.left = node;
return newNode;
}
} |
package me.lucko.luckperms.inject;
import lombok.experimental.UtilityClass;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permissible;
import org.bukkit.permissions.PermissibleBase;
import java.lang.reflect.Field;
/**
* Injects a {@link LPPermissible} into a {@link Player}
*/
@UtilityClass
public class Injector {
private static Field HUMAN_ENTITY_FIELD;
static {
try {
HUMAN_ENTITY_FIELD = Class.forName(getInternalClassName("entity.CraftHumanEntity")).getDeclaredField("perm");
HUMAN_ENTITY_FIELD.setAccessible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean inject(CommandSender sender, PermissibleBase permissible) {
try {
Field f = getPermField(sender);
f.set(sender, permissible);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static boolean unInject(CommandSender sender) {
try {
Permissible permissible = getPermissible(sender);
if (permissible instanceof LPPermissible) {
getPermField(sender).set(sender, new PermissibleBase(sender));
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private static Permissible getPermissible(CommandSender sender) {
try {
Field f = getPermField(sender);
return (Permissible) f.get(sender);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static Field getPermField(CommandSender sender) {
if (sender instanceof Player) {
return HUMAN_ENTITY_FIELD;
}
throw new RuntimeException("Couldn't get perm field for sender " + sender.getClass().getName());
}
private static String getInternalClassName(String className) {
Class server = Bukkit.getServer().getClass();
if (!server.getSimpleName().equals("CraftServer")) {
throw new RuntimeException("Couldn't inject into server " + server);
}
String version;
if (server.getName().equals("org.bukkit.craftbukkit.CraftServer")) {
// Non versioned class
version = ".";
} else {
version = server.getName().substring("org.bukkit.craftbukkit".length());
version = version.substring(0, version.length() - "CraftServer".length());
}
return "org.bukkit.craftbukkit" + version + className;
}
} |
package pl.tajchert.buswear.wear;
import android.content.Context;
import android.os.Parcel;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.android.gms.wearable.MessageEvent;
import java.lang.reflect.Constructor;
/**
* An extension of the Greenrobot EventBus that allows syncing events over the Android Wearable API
*/
public class EventBus extends org.greenrobot.eventbus.EventBus {
private static EventBus defaultInstance;
public static EventBus getDefault(@NonNull Context context) {
if (defaultInstance == null) {
synchronized (org.greenrobot.eventbus.EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus(context);
}
}
}
return defaultInstance;
}
private final Context context;
public EventBus(@NonNull Context context) {
this.context = context.getApplicationContext();
}
/**
* Posts the given event (object) to the remote event bus only
*
* @param event any kind of Object, no restrictions.
*/
public void postRemote(Object event) {
sendEventOverGooglePlayServices(event, false);
}
/**
* Posts the given sticky event (object) to the remote event bus only
*
* @param event any kind of Object, no restrictions.
*/
public void postStickyRemote(Object event) {
sendEventOverGooglePlayServices(event, true);
}
/**
* Remove and gets the recent sticky event for the given event type, on the remote event bus only
*
* @param eventType
* @param <T>
* @return
*/
public <T> void removeStickyEventRemote(Class<T> eventType) {
new SendCommandToNode(WearBusTools.PREFIX_CLASS + WearBusTools.MESSAGE_PATH_COMMAND, null, eventType, context).start();
}
/**
* Removes the sticky event if it equals to the given event, on the remote event bus only
*
* @return true if the events matched and the sticky event was removed.
*/
public void removeStickyEventRemote(Object event) {
byte[] objectInArray = WearBusTools.parseToSend(event);
if (objectInArray != null) {
new SendCommandToNode(WearBusTools.PREFIX_EVENT + WearBusTools.MESSAGE_PATH_COMMAND, objectInArray, event.getClass(), context).start();
}
}
/**
* Removes all sticky events, on the remote event bus only
*/
public void removeAllStickyEventsRemote() {
new SendCommandToNode(WearBusTools.MESSAGE_PATH_COMMAND, WearBusTools.ACTION_STICKY_CLEAR_ALL.getBytes(), String.class, context).start();
}
/**
* Posts the given event (object) to the local and remote event bus
*
* @param event any kind of Object, no restrictions.
*/
public void postGlobal(Object event) {
postRemote(event);
post(event);
}
/**
* Posts the given sticky event (object) to the local and remote event bus
*
* @param event any kind of Object, no restrictions.
*/
public void postStickyGlobal(Object event) {
postStickyRemote(event);
postSticky(event);
}
/**
* Remove and gets the recent sticky event for the given event type, on local and remote event bus
*
* @param eventType
* @param <T>
* @return
*/
public <T> T removeStickyEventGlobal(Class<T> eventType) {
removeStickyEventRemote(eventType);
return removeStickyEvent(eventType);
}
/**
* Removes the sticky event if it equals to the given event, on local and remote event bus
*
* @return true if the events matched and the sticky event was removed.
*/
public boolean removeStickyEventGlobal(Object event) {
removeStickyEventRemote(event);
return removeStickyEvent(event);
}
/**
* Removes all sticky events, on local and remote event bus
*/
public void removeAllStickyEventsGlobal() {
removeAllStickyEventsRemote();
removeAllStickyEvents();
}
/**
* Will take a MessageEvent from GooglePlayServices and attempt to parse WearEventBus data to sync with the local EventBus
*
* @param messageEvent
*/
public void syncEvent(@NonNull MessageEvent messageEvent) {
byte[] objectArray = messageEvent.getData();
int indexClassDelimiter = messageEvent.getPath().lastIndexOf(WearBusTools.CLASS_NAME_DELIMITER);
String className = messageEvent.getPath().substring(indexClassDelimiter);
boolean isEventMessage = messageEvent.getPath().contains(WearBusTools.MESSAGE_PATH) || messageEvent.getPath().contains(WearBusTools.MESSAGE_PATH_STICKY);
if (isEventMessage) {
//Try simple types (String, Integer, Long...)
Object obj = WearBusTools.getSendSimpleObject(objectArray, className);
if (obj == null) {
//Find corresponding parcel for particular object in local receivers
obj = findParcel(objectArray, className);
}
if (obj != null) {
boolean isSticky = messageEvent.getPath().contains(WearBusTools.MESSAGE_PATH_STICKY);
//send them to local bus
if (isSticky) {
postSticky(obj);
} else {
post(obj);
}
}
} else if (messageEvent.getPath().contains(WearBusTools.MESSAGE_PATH_COMMAND)) {
//Commands used for managing sticky events.
stickyEventCommand(context, messageEvent, objectArray, className);
}
}
/**
* Method used to find which command and if class/object is needed to retrieve it and call local method.
*
* @param context
* @param messageEvent
* @param objectArray
*/
private void stickyEventCommand(@NonNull Context context, @NonNull MessageEvent messageEvent, @NonNull byte[] objectArray, @NonNull String className) {
if (className.equals(String.class.getName())) {
String action = new String(objectArray);
Log.d(WearBusTools.BUSWEAR_TAG, "syncEvent action: " + action);
if (action.equals(WearBusTools.ACTION_STICKY_CLEAR_ALL)) {
removeAllStickyEvents();
} else {
//Even if it was String it should be removeStickyEventLocal instead of all, it is due to fact that action key is sent as a String.
Class classTmp = getClassForName(className);
removeStickyEvent(classTmp);
}
} else {
if (messageEvent.getPath().startsWith(WearBusTools.PREFIX_CLASS)) {
//Call removeStickyEventLocal so first retrieve class that needs to be removed.
Class classTmp = getClassForName(className);
removeStickyEvent(classTmp);
} else {
//Call removeStickyEventLocal so first retrieve object that needs to be removed.
Object obj = WearBusTools.getSendSimpleObject(objectArray, className);
if (obj == null) {
//Find corresponding parcel for particular object in local receivers
obj = findParcel(objectArray, className);
}
if (obj != null) {
removeStickyEvent(obj);
}
}
}
}
/**
* Attempts to locate the class specified by className to instantiate with the given objectArray
*
* @param objectArray
* @param className
* @return
*/
private Object findParcel(@NonNull byte[] objectArray, @NonNull String className) {
try {
Class classTmp = getClassForName(className);
Constructor declaredConstructor = classTmp.getDeclaredConstructor(Parcel.class);
declaredConstructor.setAccessible(true);
return declaredConstructor.newInstance(WearBusTools.byteToParcel(objectArray));
} catch (Exception e) {
Log.d(WearBusTools.BUSWEAR_TAG, "syncEvent error: " + e.getMessage());
}
return null;
}
@Nullable
private Class getClassForName(@NonNull String className) {
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
Log.d(WearBusTools.BUSWEAR_TAG, "syncEvent error: " + e.getMessage());
return null;
}
}
private void sendEventOverGooglePlayServices(Object event, boolean isSticky) {
//Try to parse it for sending and then send it
byte[] objectInArray = WearBusTools.parseToSend(event);
try {
new SendByteArrayToNode(objectInArray, event.getClass(), context, isSticky).start();
} catch (Exception e) {
Log.e(WearBusTools.BUSWEAR_TAG, "Object cannot be sent: " + e.getMessage());
}
}
} |
package src;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
public class DBManager {
private Connection connection = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
private final static String DBNAME = "ideascale";
private final static String DBUSER = "ideascale";
private final static String DBPASS = "ideascale";
private final static String HOST = "localhost";
private final static String PORT = "8889";
public DBManager() {
// This will load the MySQL driver, each DB has its own driver
try {
Class.forName("com.mysql.jdbc.Driver");
String connectionStatement = "jdbc:mysql://"+HOST+":"+PORT+"/" +
DBNAME + "?user=" + DBUSER +
"&password=" + DBPASS;
// Setup the connection with the DB
connection = DriverManager.getConnection(connectionStatement);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void insertCommunityFromCSV(HashMap<String,Object> community)
throws SQLException
{
preparedStatement = connection.prepareStatement("INSERT INTO communities " +
"(name, url, type, orientation, ideas, ideas_implemented, " +
"members, votes, comments, owner, purpose, language, " +
"status, outlier) values (?, ?, ?, ? , ?, ?, ?, ?, ?, " +
"?, ?, ?, ?, ?)");
preparedStatement.setString(1, (String) community.get("name"));
preparedStatement.setString(2, (String) community.get("url"));
preparedStatement.setString(3, (String) community.get("type"));
preparedStatement.setString(4, (String) community.get("orientation"));
preparedStatement.setInt(5, Integer.parseInt((String) community.get("ideas")));
if (community.get("ideas_implemented").toString().contains("
preparedStatement.setNull(6, Types.INTEGER);
else
preparedStatement.setInt(6,Integer.parseInt((String) community.get("ideas_implemented")));
preparedStatement.setInt(7,Integer.parseInt((String) community.get("members")));
preparedStatement.setInt(8,Integer.parseInt((String) community.get("votes")));
preparedStatement.setInt(9, Integer.parseInt((String) community.get("comments")));
preparedStatement.setString(10, (String) community.get("owner"));
preparedStatement.setString(11, (String) community.get("purpose"));
preparedStatement.setString(12, (String) community.get("language"));
preparedStatement.setString(13, (String) community.get("status"));
preparedStatement.setBoolean(14,(Boolean) community.get("outlier"));
preparedStatement.executeUpdate();
preparedStatement.close();
}
public ArrayList<HashMap<String,String>> getCommunitiesURL(ArrayList<ArrayList<String>> filters)
{
ArrayList<HashMap<String,String>> communitiesURL = new ArrayList<HashMap<String,String>>();
try {
if (filters == null) {
preparedStatement = connection.prepareStatement("SELECT id, name, url FROM communities");
}
else {
String whereClause = "";
for (ArrayList<String> filter : filters) {
if (!whereClause.isEmpty())
whereClause += " AND ";
whereClause += filter.get(0) + " " + filter.get(1) + " " + filter.get(2);
}
preparedStatement = connection.prepareStatement("SELECT id, name, url FROM communities WHERE " + whereClause);
}
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
HashMap<String,String> community = new HashMap<String,String>();
community.put("id", resultSet.getString("id"));
community.put("name", resultSet.getString("name"));
community.put("url", resultSet.getString("url"));
communitiesURL.add(community);
}
} catch(SQLException e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return communitiesURL;
}
public void saveCommunityDates(String idCommunity,
HashMap<String,Object> commInfo)
throws SQLException
{
PreparedStatement preparedStatement = connection.prepareStatement(
"UPDATE communities SET " +
"firstidea_ts = ?, lastidea_ts = ?, " +
"lifespan = ?, status = ? WHERE id = ?");
HashMap<String,Object> dateInfo = getDatesParams(commInfo);
if (dateInfo.get("first_idea") != null)
preparedStatement.setDate(1, (java.sql.Date) dateInfo.get("first_idea"));
else
preparedStatement.setNull(1, java.sql.Types.DATE);
if (dateInfo.get("last_idea") != null)
preparedStatement.setDate(2, (java.sql.Date) dateInfo.get("last_idea"));
else
preparedStatement.setNull(2, java.sql.Types.DATE);
if (dateInfo.get("lifespan") != null)
preparedStatement.setInt(3, (Integer) dateInfo.get("lifespan"));
else
preparedStatement.setNull(3, java.sql.Types.INTEGER);
preparedStatement.setString(4, (String) commInfo.get("status"));
preparedStatement.setInt(5, Integer.parseInt(idCommunity));
preparedStatement.executeUpdate();
preparedStatement.close();
}
private HashMap<String,Object> getDatesParams(HashMap<String,Object> commInfo)
{
java.sql.Date dateFirstIdea = null;
java.sql.Date dateLastIdea = null;
Integer lifespan = null;
HashMap<String,Object> dateInfo = new HashMap<String,Object>();
if (commInfo.get("dateFirstIdea") != null &&
commInfo.get("dateLastIdea") != null)
{
/* First, I need to convert from java.util.Date to java.sql.Date */
Date dateUtil = (Date) commInfo.get("dateFirstIdea");
dateFirstIdea = new java.sql.Date(dateUtil.getTime());
dateUtil = (Date) commInfo.get("dateLastIdea");
dateLastIdea = new java.sql.Date(dateUtil.getTime());
lifespan = (Integer) commInfo.get("lifespan");
dateInfo.put("first_idea", dateFirstIdea);
dateInfo.put("last_idea", dateLastIdea);
dateInfo.put("lifespan", lifespan);
}
else {
dateInfo.put("first_idea", null);
dateInfo.put("last_idea", null);
dateInfo.put("lifespan", null);
}
return dateInfo;
}
public void close() {
try {
if (connection != null) {
connection.close();
}
}
catch (Exception e) {
}
}
public void updateCommunityInfo(String idCommunity,
HashMap<String,Object> communityInfo)
throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement(
"UPDATE communities SET " +
"ideas = ?, ideas_in_review = ?, " +
"ideas_in_progress = ?, ideas_implemented = ?, " +
"members = ?, votes = ?, " +
"comments = ?, " +
"firstidea_ts = ?, lastidea_ts = ?, " +
"lifespan = ?, status = ?, updated = ?, " +
"facebook = ?, logo = ?, description = ?, " +
"twitter = ?, url = ? " +
"WHERE id = ?");
if (communityInfo.get("ideas") != null)
preparedStatement.setInt(1, Integer.parseInt((String) communityInfo.get("ideas")));
else
preparedStatement.setNull(1, java.sql.Types.INTEGER);
if (communityInfo.get("ideas_in_review") != null)
preparedStatement.setInt(2, Integer.parseInt((String) communityInfo.get("ideas_in_review")));
else
preparedStatement.setNull(2, java.sql.Types.INTEGER);
if (communityInfo.get("ideas_in_progress") != null)
preparedStatement.setInt(3, Integer.parseInt((String) communityInfo.get("ideas_in_progress")));
else
preparedStatement.setNull(3, java.sql.Types.INTEGER);
if (communityInfo.get("ideas_completed") != null)
preparedStatement.setInt(4, Integer.parseInt((String) communityInfo.get("ideas_completed")));
else
preparedStatement.setNull(4, java.sql.Types.INTEGER);
if (communityInfo.get("members") != null)
preparedStatement.setInt(5, Integer.parseInt((String) communityInfo.get("members")));
else
preparedStatement.setNull(5, java.sql.Types.INTEGER);
if (communityInfo.get("votes") != null)
preparedStatement.setInt(6, Integer.parseInt((String) communityInfo.get("votes")));
else
preparedStatement.setNull(6, java.sql.Types.INTEGER);
if (communityInfo.get("comments") != null)
preparedStatement.setInt(7, Integer.parseInt((String) communityInfo.get("comments")));
else
preparedStatement.setNull(7, java.sql.Types.INTEGER);
HashMap<String,Object> dateInfo = getDatesParams(communityInfo);
if (dateInfo.get("first_idea") != null)
preparedStatement.setDate(8, (java.sql.Date) dateInfo.get("first_idea"));
else
preparedStatement.setNull(8, java.sql.Types.DATE);
if (dateInfo.get("last_idea") != null)
preparedStatement.setDate(9, (java.sql.Date) dateInfo.get("last_idea"));
else
preparedStatement.setNull(9, java.sql.Types.DATE);
if (dateInfo.get("lifespan") != null)
preparedStatement.setInt(10, (Integer) dateInfo.get("lifespan"));
else
preparedStatement.setNull(10, java.sql.Types.INTEGER);
preparedStatement.setString(11, (String) communityInfo.get("status"));
preparedStatement.setBoolean(12, true);
if (communityInfo.get("facebook") != null)
preparedStatement.setInt(13, Integer.parseInt((String) communityInfo.get("facebook")));
else
preparedStatement.setNull(13, java.sql.Types.INTEGER);
if (communityInfo.get("logo") != null)
preparedStatement.setBoolean(14, true);
else
preparedStatement.setBoolean(14, false);
if (communityInfo.get("explanation_text") != null)
preparedStatement.setBoolean(15, true);
else
preparedStatement.setBoolean(15, false);
if (communityInfo.get("twitter") != null)
preparedStatement.setInt(16, Integer.parseInt((String) communityInfo.get("twitter")));
else
preparedStatement.setInt(16, java.sql.Types.INTEGER);
preparedStatement.setString(17, (String) communityInfo.get("url"));
preparedStatement.setInt(18, Integer.parseInt(idCommunity));
preparedStatement.executeUpdate();
preparedStatement.close();
}
public void insertCommunityFromHash(HashMap<String,Object> community)
throws SQLException
{
preparedStatement = connection.prepareStatement("INSERT INTO communities " +
"(name, url, ideas, ideas_in_review, ideas_in_progress," +
"ideas_implemented, members, votes, comments, " +
"firstidea_ts, lastidea_ts, lifespan, status, " +
"outlier, updated, facebook, logo, description, twitter) " +
"values (?, ?, ?, ? , ?, ?, ?, ?, ?, " +
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
preparedStatement.setString(1, (String) community.get("name"));
preparedStatement.setString(2, (String) community.get("url"));
if (community.get("ideas") != null)
preparedStatement.setInt(3, Integer.parseInt((String) community.get("ideas")));
else
preparedStatement.setInt(3, -1);
if (community.get("ideas_in_review") != null)
preparedStatement.setInt(4, Integer.parseInt((String) community.get("ideas_in_review")));
else
preparedStatement.setInt(4, -1);
if (community.get("ideas_in_progress") != null)
preparedStatement.setInt(5, Integer.parseInt((String) community.get("ideas_in_progress")));
else
preparedStatement.setInt(5, -1);
if (community.get("ideas_completed") != null)
preparedStatement.setInt(6, Integer.parseInt((String) community.get("ideas_completed")));
else
preparedStatement.setInt(6, -1);
if (community.get("members") != null)
preparedStatement.setInt(7, Integer.parseInt((String) community.get("members")));
else
preparedStatement.setInt(7, -1);
if (community.get("votes") != null)
preparedStatement.setInt(8, Integer.parseInt((String) community.get("votes")));
else
preparedStatement.setInt(8, -1);
if (community.get("comments") != null)
preparedStatement.setInt(9, Integer.parseInt((String) community.get("comments")));
else
preparedStatement.setInt(9, -1);
HashMap<String,Object> dateInfo = getDatesParams(community);
if (dateInfo.get("first_idea") != null)
preparedStatement.setDate(10, (java.sql.Date) dateInfo.get("first_idea"));
else
preparedStatement.setNull(10, java.sql.Types.DATE);
if (dateInfo.get("last_idea") != null)
preparedStatement.setDate(11, (java.sql.Date) dateInfo.get("last_idea"));
else
preparedStatement.setNull(11, java.sql.Types.DATE);
if (dateInfo.get("lifespan") != null)
preparedStatement.setInt(12, (Integer) dateInfo.get("lifespan"));
else
preparedStatement.setInt(12, -1);
preparedStatement.setString(13, (String) community.get("status"));
preparedStatement.setBoolean(14, false);
preparedStatement.setBoolean(15, true);
if (community.get("facebook") != null)
preparedStatement.setInt(16, Integer.parseInt((String) community.get("facebook")));
else
preparedStatement.setInt(16, -1);
if (community.get("logo") != null)
preparedStatement.setBoolean(17, true);
else
preparedStatement.setBoolean(17, false);
if (community.get("explanation_text") != null)
preparedStatement.setBoolean(18, true);
else
preparedStatement.setBoolean(18, false);
if (community.get("twitter") != null)
preparedStatement.setInt(19, Integer.parseInt((String) community.get("twitter")));
else
preparedStatement.setInt(19, -1);
preparedStatement.executeUpdate();
preparedStatement.close();
}
public String alreadyOnDB(String url) throws SQLException {
String idCommunity = null;
preparedStatement = connection.prepareStatement("SELECT * FROM communities " +
"WHERE url = ?");
preparedStatement.setString(1, url);
resultSet = preparedStatement.executeQuery();
if (resultSet.first())
idCommunity = resultSet.getString("id");
preparedStatement.close();
resultSet.close();
return idCommunity;
}
public int removeUnexistingCommunities(String letter) throws SQLException {
int deletedRows = 0;
if (letter.isEmpty()) {
preparedStatement = connection.prepareStatement("DELETE FROM communities " +
"WHERE updated = ?");
preparedStatement.setBoolean(1, false);
}
else {
preparedStatement = connection.prepareStatement("DELETE FROM communities " +
"WHERE updated = ? AND " +
"name LIKE ?");
preparedStatement.setBoolean(1, false);
preparedStatement.setString(2, letter+"%");
}
deletedRows = preparedStatement.executeUpdate();
preparedStatement.close();
return deletedRows;
}
public void insertCommunityTweets(HashMap<String,Object> tweet, String idCommunity)
throws SQLException, ParseException
{
preparedStatement = connection.prepareStatement("INSERT INTO tweets_communities " +
"(id_community, id_tweet, author, datetime, url," +
"replies, favorites, retweets, text) " +
"values (?, ?, ?, ? , ?, ?, ?, ?, ?)");
preparedStatement.setString(1, (String) idCommunity);
preparedStatement.setString(2, (String) tweet.get("id"));
preparedStatement.setString(3, (String) tweet.get("author"));
Date dateUtil = (Date) tweet.get("datetime");
java.sql.Timestamp ideaDateTime = new java.sql.Timestamp(dateUtil.getTime());
preparedStatement.setTimestamp(4, ideaDateTime);
preparedStatement.setString(5, (String) tweet.get("url"));
preparedStatement.setInt(6, (Integer) tweet.get("replies"));
preparedStatement.setLong(7, (Long) tweet.get("favorites"));
preparedStatement.setLong(8, (Long) tweet.get("retweets"));
preparedStatement.setString(9, (String) tweet.get("text"));
preparedStatement.executeUpdate();
preparedStatement.close();
}
public void insertTweetsIdea(HashMap<String,Object> tweet, String idIdea)
throws SQLException, ParseException
{
preparedStatement = connection.prepareStatement("INSERT INTO tweets_ideas " +
"(id_idea, id_tweet, author, datetime, url," +
"replies, favorites, retweets, text) " +
"values (?, ?, ?, ? , ?, ?, ?, ?, ?)");
preparedStatement.setString(1, (String) idIdea);
preparedStatement.setString(2, (String) tweet.get("id"));
preparedStatement.setString(3, (String) tweet.get("author"));
Date dateUtil = (Date) tweet.get("datetime");
java.sql.Timestamp ideaDateTime = new java.sql.Timestamp(dateUtil.getTime());
preparedStatement.setTimestamp(4, ideaDateTime);
preparedStatement.setString(5, (String) tweet.get("url"));
preparedStatement.setInt(6, (Integer) tweet.get("replies"));
preparedStatement.setLong(7, (Long) tweet.get("favorites"));
preparedStatement.setLong(8, (Long) tweet.get("retweets"));
preparedStatement.setString(9, (String) tweet.get("text"));
preparedStatement.executeUpdate();
preparedStatement.close();
}
public boolean tweetAlreadyInserted(String idTweet) throws SQLException {
Boolean existsTweet = false;
preparedStatement = connection.prepareStatement("SELECT * " +
"FROM tweets_communities " +
"WHERE id_tweet = ?");
preparedStatement.setString(1, (String) idTweet);
resultSet = preparedStatement.executeQuery();
existsTweet = resultSet.first();
resultSet.close();
preparedStatement.close();
return existsTweet;
}
public boolean commentAlreadyExisting(Integer idComment, Integer idIdea)
throws SQLException {
Boolean existsComment = false;
preparedStatement = connection.prepareStatement("SELECT * " +
"FROM comments " +
"WHERE idea_id = ? " +
"AND ideascale_id = ?");
preparedStatement.setInt(1, idIdea);
preparedStatement.setInt(2, idComment);
resultSet = preparedStatement.executeQuery();
existsComment = resultSet.first();
resultSet.close();
preparedStatement.close();
return existsComment;
}
public boolean voteAlreadyExisting(Integer idAuthor, String nameAuthor, Integer idIdea)
throws SQLException {
Boolean existsVote = false;
preparedStatement = connection.prepareStatement("SELECT * " +
"FROM votes " +
"WHERE idea_id = ? " +
"AND author_id = ? AND " +
"author_name = ?");
preparedStatement.setInt(1, idIdea);
preparedStatement.setInt(2, idAuthor);
preparedStatement.setString(3, nameAuthor);
resultSet = preparedStatement.executeQuery();
existsVote = resultSet.first();
resultSet.close();
preparedStatement.close();
return existsVote;
}
public void insertComment(HashMap<String,String> comment, Integer idIdea,
Date storeDT)
throws SQLException {
preparedStatement = connection.prepareStatement("INSERT INTO comments " +
"(author_id, author_name, " +
"creation_datetime, description, " +
"ideascale_id, idea_id, " +
"store_datetime, parent_ideascale_id, " +
"author_type) " +
"values (?, ?, ?, ? , ?, ?, ?, ?, ?)");
preparedStatement.setInt(1, Integer.parseInt(comment.get("author-id")));
preparedStatement.setString(2, comment.get("author-name"));
preparedStatement.setString(3, comment.get("date"));
preparedStatement.setString(4, comment.get("description"));
preparedStatement.setInt(5, Integer.parseInt(comment.get("id")));
preparedStatement.setInt(6, idIdea);
java.sql.Timestamp storeDateTime = new java.sql.Timestamp(storeDT.getTime());
preparedStatement.setTimestamp(7, storeDateTime);
preparedStatement.setInt(8, Integer.parseInt(comment.get("parent")));
preparedStatement.setString(9, comment.get("author-type"));
preparedStatement.executeUpdate();
preparedStatement.close();
}
public void updateComment(HashMap<String,String> comment, Integer idComment)
throws SQLException {
preparedStatement = connection.prepareStatement("UPDATE comments " +
"SET author_type = ? " +
"WHERE ideascale_id = ?");
preparedStatement.setString(1, comment.get("author-type"));
preparedStatement.setInt(2, idComment);
preparedStatement.executeUpdate();
preparedStatement.close();
}
public void insertVote(HashMap<String,String> vote, Integer idIdea, Date storeDT)
throws SQLException {
preparedStatement = connection.prepareStatement("INSERT INTO votes " +
"(author_id, author_name, " +
"creation_datetime, value, " +
"idea_id, store_datetime) " +
"values (?, ?, ?, ? , ?, ?)");
preparedStatement.setInt(1, Integer.parseInt(vote.get("author-id")));
preparedStatement.setString(2, vote.get("author-name"));
preparedStatement.setString(3, vote.get("date"));
preparedStatement.setString(4, vote.get("value"));
preparedStatement.setInt(5, idIdea);
java.sql.Timestamp storeDateTime = new java.sql.Timestamp(storeDT.getTime());
preparedStatement.setTimestamp(6, storeDateTime);
preparedStatement.executeUpdate();
preparedStatement.close();
}
public ArrayList<HashMap<String,String>> getActiveCommunities()
throws SQLException
{
ArrayList<HashMap<String,String>> activeCommunities = new ArrayList<HashMap<String,String>>();
preparedStatement = connection.prepareStatement("SELECT id, name, url, " +
"facebook, twitter, " +
"ideas, comments, votes, " +
"members " +
"FROM communities " +
"WHERE status = ? AND " +
"facebook IS NOT ? AND " +
"synchronized = ? " +
"ORDER BY ideas ASC");
preparedStatement.setString(1, "active");
preparedStatement.setString(2, null);
preparedStatement.setBoolean(3, false);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
HashMap<String,String> community = new HashMap<String,String>();
community.put("id", resultSet.getString("id"));
community.put("url", resultSet.getString("url"));
community.put("name", resultSet.getString("name"));
community.put("facebook", resultSet.getString("facebook"));
community.put("twitter", resultSet.getString("twitter"));
community.put("ideas", resultSet.getString("ideas"));
community.put("comments", resultSet.getString("comments"));
community.put("votes", resultSet.getString("votes"));
community.put("members", resultSet.getString("members"));
activeCommunities.add(community);
}
resultSet.close();
preparedStatement.close();
return activeCommunities;
}
public ArrayList<HashMap<String,String>> getCivicParticipationCommunities()
throws SQLException
{
ArrayList<HashMap<String,String>> cpCommunities = new ArrayList<HashMap<String,String>>();
preparedStatement = connection.prepareStatement("SELECT id, name, url, " +
"facebook, twitter, " +
"ideas, comments, votes, " +
"members " +
"FROM communities " +
"WHERE orientation = ? " +
"ORDER BY ideas ASC");
preparedStatement.setString(1, "Civic Participation");
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
HashMap<String,String> community = new HashMap<String,String>();
community.put("id", resultSet.getString("id"));
community.put("url", resultSet.getString("url"));
community.put("name", resultSet.getString("name"));
community.put("facebook", resultSet.getString("facebook"));
community.put("twitter", resultSet.getString("twitter"));
community.put("ideas", resultSet.getString("ideas"));
community.put("comments", resultSet.getString("comments"));
community.put("votes", resultSet.getString("votes"));
community.put("members", resultSet.getString("members"));
cpCommunities.add(community);
}
resultSet.close();
preparedStatement.close();
return cpCommunities;
}
public void updateCommunityStats(HashMap<String,Object> stats,
String idCommunity)
throws SQLException
{
preparedStatement = connection.prepareStatement("UPDATE communities SET " +
"twitter = ?, facebook = ?, " +
"ideas = ?, comments = ?, " +
"votes = ?, ideas_in_review = ?, " +
"ideas_in_progress = ?, " +
"ideas_implemented = ?," +
"members = ? " +
"WHERE id = ?");
if (stats.get("twitter") != null)
preparedStatement.setInt(1, Integer.parseInt((String) stats.get("twitter")));
else
preparedStatement.setInt(1, -1);
if (stats.get("facebook") != null)
preparedStatement.setInt(2, Integer.parseInt((String) stats.get("facebook")));
else
preparedStatement.setInt(2, -1);
if (stats.get("ideas") != null)
preparedStatement.setInt(3, Integer.parseInt((String) stats.get("ideas")));
else
preparedStatement.setInt(3, -1);
if (stats.get("comments") != null)
preparedStatement.setInt(4, Integer.parseInt((String) stats.get("comments")));
else
preparedStatement.setInt(4, -1);
if (stats.get("votes") != null)
preparedStatement.setInt(5, Integer.parseInt((String) stats.get("votes")));
else
preparedStatement.setInt(5, -1);
if (stats.get("ideas_in_review") != null)
preparedStatement.setInt(6, Integer.parseInt((String) stats.get("ideas_in_review")));
else
preparedStatement.setInt(6, -1);
if (stats.get("ideas_in_progress") != null)
preparedStatement.setInt(7, Integer.parseInt((String) stats.get("ideas_in_progress")));
else
preparedStatement.setInt(7, -1);
if (stats.get("ideas_completed") != null)
preparedStatement.setInt(8, Integer.parseInt((String) stats.get("ideas_completed")));
else
preparedStatement.setInt(8, -1);
if (stats.get("members") != null)
preparedStatement.setInt(9, Integer.parseInt((String) stats.get("members")));
else
preparedStatement.setInt(9, -1);
preparedStatement.setString(10, (String) idCommunity);
preparedStatement.executeUpdate();
preparedStatement.close();
}
public void insertCommunityIdea(HashMap<String,Object> idea, String communityId)
throws SQLException, ParseException {
Integer idIdea = Integer.parseInt((String) idea.get("id"));
preparedStatement = connection.prepareStatement("INSERT INTO ideas " +
"(ideascale_id, title, description, " +
"creation_datetime, tags, author_name, " +
"community_id, twitter, facebook, url, score, comments, " +
"similar_to, author_id, status, considered, page, list_pos) " +
"values (?, ?, ?, ? , ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
preparedStatement.setInt(1, idIdea);
preparedStatement.setString(2, (String) idea.get("title"));
if (idea.get("description") != null)
preparedStatement.setString(3, (String) idea.get("description"));
else
preparedStatement.setNull(3, java.sql.Types.NULL);
if (idea.get("datetime") != null) {
Date dateUtil = (Date) idea.get("datetime");
java.sql.Timestamp ideaDateTime = new java.sql.Timestamp(dateUtil.getTime());
preparedStatement.setTimestamp(4, ideaDateTime);
}
else
preparedStatement.setNull(4, java.sql.Types.DATE);
if (idea.get("tags") != null)
preparedStatement.setString(5, (String) idea.get("tags"));
else
preparedStatement.setString(5, "");
if (idea.get("author-name") != null)
preparedStatement.setString(6, (String) idea.get("author-name"));
else
preparedStatement.setNull(6, java.sql.Types.NULL);
preparedStatement.setString(7, (String) communityId);
if (idea.get("twitter") != null)
preparedStatement.setInt(8, Integer.parseInt((String) idea.get("twitter")));
else
preparedStatement.setInt(8, -1);
if (idea.get("facebook") != null)
preparedStatement.setInt(9, Integer.parseInt((String) idea.get("facebook")));
else
preparedStatement.setInt(9, -1);
preparedStatement.setString(10, (String) idea.get("url"));
if (idea.get("score") != null)
preparedStatement.setInt(11, (Integer) idea.get("score"));
else
preparedStatement.setNull(11, java.sql.Types.INTEGER);
if (idea.get("comments") != null)
preparedStatement.setInt(12, (Integer) idea.get("comments"));
else
preparedStatement.setNull(12, java.sql.Types.INTEGER);
if (idea.get("similar") != null)
preparedStatement.setInt(13, (Integer) idea.get("similar"));
else
preparedStatement.setNull(13, java.sql.Types.INTEGER);
if (idea.get("author-id") == "")
System.out.println("Idea: "+idea.get("url"));
if (idea.get("author-id") != null)
preparedStatement.setInt(14, Integer.parseInt((String) idea.get("author-id")));
else
preparedStatement.setNull(14, java.sql.Types.INTEGER);
if (idea.get("status") != null) {
String status = (String) idea.get("status");
preparedStatement.setString(15, status);
if (status.equals("completed") || status.equals("under-review") ||
status.equals("in-progress"))
preparedStatement.setBoolean(16, true);
else
preparedStatement.setBoolean(16, false);
}
else {
preparedStatement.setNull(15, java.sql.Types.NULL);
preparedStatement.setBoolean(16, false);
}
preparedStatement.setInt(17, (Integer) idea.get("page"));
preparedStatement.setInt(18, (Integer) idea.get("list_pos"));
preparedStatement.executeUpdate();
preparedStatement.close();
}
public void updateCommunityIdea(HashMap<String,Object> idea, Integer idIdea)
throws SQLException {
preparedStatement = connection.prepareStatement(
"UPDATE ideas SET " +
"twitter = ?, facebook = ?, score = ?, " +
"comments = ?, similar_to = ?, status = ?, author_name = ?, " +
"considered = ?, page = ?, list_pos = ? " +
"WHERE id = ?");
if (idea.get("twitter") != null)
preparedStatement.setInt(1, Integer.parseInt((String) idea.get("twitter")));
else
preparedStatement.setInt(1, -1);
if (idea.get("facebook") != null)
preparedStatement.setInt(2, Integer.parseInt((String) idea.get("facebook")));
else
preparedStatement.setInt(2, -1);
if (idea.get("score") != null)
preparedStatement.setInt(3, (Integer) idea.get("score"));
else
preparedStatement.setNull(3, java.sql.Types.INTEGER);
if (idea.get("comments") != null)
preparedStatement.setInt(4, (Integer) idea.get("comments"));
else
preparedStatement.setNull(4, java.sql.Types.INTEGER);
if (idea.get("similar") != null)
preparedStatement.setInt(5, (Integer) idea.get("similar"));
else
preparedStatement.setNull(5, java.sql.Types.INTEGER);
if (idea.get("status") != null) {
String status = (String) idea.get("status");
preparedStatement.setString(6, status);
if (status.equals("completed") || status.equals("under-review") ||
status.equals("in-progress"))
preparedStatement.setBoolean(8, true);
else
preparedStatement.setBoolean(8, false);
}
else {
preparedStatement.setNull(6, java.sql.Types.NULL);
preparedStatement.setBoolean(8, false);
}
if (idea.get("author-name") != null)
preparedStatement.setString(7, (String) idea.get("author-name"));
else
preparedStatement.setNull(7, java.sql.Types.NULL);
preparedStatement.setInt(9, (Integer) idea.get("page"));
preparedStatement.setInt(10, (Integer) idea.get("list_pos"));
preparedStatement.setInt(11, idIdea);
preparedStatement.executeUpdate();
preparedStatement.close();
}
public void updateIdeaPos(Integer page, Integer listPos, Integer idIdea)
throws SQLException {
preparedStatement = connection.prepareStatement(
"UPDATE ideas SET " +
"page = ?, list_pos = ? " +
"WHERE id = ?");
preparedStatement.setInt(1, page);
preparedStatement.setInt(2, listPos);
preparedStatement.setInt(3, idIdea);
preparedStatement.executeUpdate();
preparedStatement.close();
}
public HashMap<String,String> ideaAlreadyInserted(Integer idIdea) throws SQLException {
HashMap<String,String> existingIdea = new HashMap<String,String>();
preparedStatement = connection.prepareStatement("SELECT * " +
"FROM ideas " +
"WHERE ideascale_id = ?");
preparedStatement.setInt(1, idIdea);
resultSet = preparedStatement.executeQuery();
if (resultSet.first()) {
existingIdea.put("id", resultSet.getString("id"));
existingIdea.put("name", resultSet.getString("title"));
existingIdea.put("facebook", resultSet.getString("facebook"));
existingIdea.put("twitter", resultSet.getString("twitter"));
existingIdea.put("score", resultSet.getString("score"));
existingIdea.put("comments", resultSet.getString("comments"));
existingIdea.put("url", resultSet.getString("url"));
existingIdea.put("page", resultSet.getString("page"));
existingIdea.put("list_pos", resultSet.getString("list_pos"));
}
resultSet.close();
preparedStatement.close();
return existingIdea;
}
public ArrayList<HashMap<String,String>> getCommunityIdeas(String idCommunity)
throws SQLException
{
ArrayList<HashMap<String,String>> ideas = new ArrayList<HashMap<String,String>>();
preparedStatement = connection.prepareStatement("SELECT id, url, facebook, twitter " +
"FROM ideas " +
"WHERE community_id = ?");
preparedStatement.setInt(1, Integer.parseInt(idCommunity));
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
HashMap<String,String> idea = new HashMap<String,String>();
idea.put("id", resultSet.getString("id"));
idea.put("url", resultSet.getString("url"));
idea.put("facebook", resultSet.getString("facebook"));
idea.put("twitter", resultSet.getString("twitter"));
ideas.add(idea);
}
preparedStatement.close();
resultSet.close();
return ideas;
}
public void registerOperation(Date date, String operation, Date duration,
Integer observation)
throws SQLException {
preparedStatement = connection.prepareStatement("INSERT INTO audit " +
"(date, operation, duration, " +
"observation) " +
"values (?, ?, ?, ?)");
java.sql.Timestamp opDateTime = new java.sql.Timestamp(date.getTime());
preparedStatement.setTimestamp(1, opDateTime);
preparedStatement.setString(2, operation);
java.sql.Time opDuration = new java.sql.Time(duration.getTime());
preparedStatement.setTime(3, opDuration);
preparedStatement.setInt(4, observation);
preparedStatement.executeUpdate();
preparedStatement.close();
}
public void resetUpdateFlag(String letter) throws SQLException {
if (letter.isEmpty()) {
preparedStatement = connection.prepareStatement("UPDATE communities SET " +
"updated = ?");
preparedStatement.setBoolean(1, false);
}
else {
preparedStatement = connection.prepareStatement("UPDATE communities SET " +
"updated = ? " +
"WHERE name LIKE ?");
preparedStatement.setBoolean(1, false);
preparedStatement.setString(2, letter+"%");
}
preparedStatement.executeUpdate();
preparedStatement.close();
}
public void saveLogCommunity(Integer observation,
HashMap<String,String> community,
HashMap<String,Object> newStats)
throws SQLException {
preparedStatement = connection.prepareStatement("INSERT INTO log_communities " +
"(observation, community_id, name," +
"old_facebook, new_facebook," +
"old_twitter, new_twitter," +
"old_members, new_members," +
"old_ideas, new_ideas," +
"old_comments, new_comments," +
"old_votes, new_votes) " +
"values (?, ?, ?, ?, ?, ?, " +
"?, ?, ?, ?, ?, ?, ?, ?, ?)");
preparedStatement.setInt(1, observation);
preparedStatement.setString(2, community.get("id"));
preparedStatement.setString(3, community.get("name"));
preparedStatement.setInt(4, Integer.parseInt(community.get("facebook")));
preparedStatement.setInt(5, Integer.parseInt((String) newStats.get("facebook")));
preparedStatement.setInt(6, Integer.parseInt(community.get("twitter")));
preparedStatement.setInt(7, Integer.parseInt((String) newStats.get("twitter")));
preparedStatement.setInt(8, Integer.parseInt(community.get("members")));
preparedStatement.setInt(9, Integer.parseInt((String) newStats.get("members")));
preparedStatement.setInt(10, Integer.parseInt(community.get("ideas")));
preparedStatement.setInt(11, Integer.parseInt((String) newStats.get("ideas")));
preparedStatement.setInt(12, Integer.parseInt(community.get("comments")));
preparedStatement.setInt(13, Integer.parseInt((String) newStats.get("comments")));
preparedStatement.setInt(14, Integer.parseInt(community.get("votes")));
preparedStatement.setInt(15, Integer.parseInt((String) newStats.get("votes")));
preparedStatement.executeUpdate();
preparedStatement.close();
}
public void saveLogIdea(Integer observation, HashMap<String,String> existingIdea,
HashMap<String,Object> newIdea)
throws SQLException {
preparedStatement = connection.prepareStatement("INSERT INTO log_ideas " +
"(observation, idea_id, name," +
"old_facebook, new_facebook," +
"old_twitter, new_twitter," +
"old_comments, new_comments) " +
"values (?, ?, ?, ?, ?, ?, " +
"?, ?, ?)");
preparedStatement.setInt(1, observation);
preparedStatement.setString(2, existingIdea.get("id"));
preparedStatement.setString(3, existingIdea.get("name"));
preparedStatement.setInt(4, Integer.parseInt(existingIdea.get("facebook")));
preparedStatement.setInt(5, Integer.parseInt((String) newIdea.get("facebook")));
preparedStatement.setInt(6, Integer.parseInt(existingIdea.get("twitter")));
preparedStatement.setInt(7, Integer.parseInt((String) newIdea.get("twitter")));
preparedStatement.setInt(8, Integer.parseInt(existingIdea.get("comments")));
preparedStatement.setInt(9, (Integer) newIdea.get("comments"));
preparedStatement.executeUpdate();
preparedStatement.close();
}
public void resetSyncFlag() throws SQLException {
preparedStatement = connection.prepareStatement("UPDATE communities SET " +
"synchronized = ?");
preparedStatement.setBoolean(1, false);
preparedStatement.executeUpdate();
preparedStatement.close();
}
public void updateSyncFlag(String idCommunity) throws SQLException {
preparedStatement = connection.prepareStatement("UPDATE communities SET " +
"synchronized = ? WHERE " +
"id = ?");
preparedStatement.setBoolean(1, true);
preparedStatement.setString(2, idCommunity);
preparedStatement.executeUpdate();
preparedStatement.close();
}
public Integer getIdeaId(Integer idIdeaScale) throws SQLException {
Integer idIdeaDB = -1;
preparedStatement = connection.prepareStatement("SELECT id " +
"FROM ideas " +
"WHERE ideascale_id = ?");
preparedStatement.setInt(1, idIdeaScale);
resultSet = preparedStatement.executeQuery();
if (resultSet.first())
idIdeaDB = resultSet.getInt("id");
preparedStatement.close();
resultSet.close();
return idIdeaDB;
}
public ArrayList<HashMap<String,String>> getIdeasTweets() throws SQLException {
ArrayList<HashMap<String,String>> tweets = new ArrayList<HashMap<String,String>>();
preparedStatement = connection.prepareStatement("SELECT id, id_tweet " +
"FROM tweets_ideas");
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
HashMap<String,String> tweet = new HashMap<String,String>();
tweet.put("id", resultSet.getString("id"));
tweet.put("id_tweet", resultSet.getString("id_tweet"));
tweets.add(tweet);
}
preparedStatement.close();
resultSet.close();
return tweets;
}
public void updateIdeaTweetMetric(String id, HashMap<String,Long> newMetrics)
throws SQLException {
preparedStatement = connection.prepareStatement("UPDATE tweets_ideas SET " +
"retweets = ?, favorites = ?, " +
"replies = ? WHERE " +
"id = ?");
preparedStatement.setLong(1, newMetrics.get("retweets"));
preparedStatement.setLong(2, newMetrics.get("favorites"));
preparedStatement.setLong(3, newMetrics.get("replies"));
preparedStatement.setString(4, id);
preparedStatement.executeUpdate();
preparedStatement.close();
}
public ArrayList<HashMap<String,String>> getCommunitiesTweets() throws SQLException {
ArrayList<HashMap<String,String>> tweets = new ArrayList<HashMap<String,String>>();
preparedStatement = connection.prepareStatement("SELECT id, id_tweet " +
"FROM tweets_communities");
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
HashMap<String,String> tweet = new HashMap<String,String>();
tweet.put("id", resultSet.getString("id"));
tweet.put("id_tweet", resultSet.getString("id_tweet"));
tweets.add(tweet);
}
preparedStatement.close();
resultSet.close();
return tweets;
}
public void updateCommunityTweetMetric(String id, HashMap<String,Long> newMetrics)
throws SQLException {
preparedStatement = connection.prepareStatement("UPDATE tweets_communities SET " +
"retweets = ?, favorites = ?, " +
"replies = ? WHERE " +
"id = ?");
preparedStatement.setLong(1, newMetrics.get("retweets"));
preparedStatement.setLong(2, newMetrics.get("favorites"));
preparedStatement.setLong(3, newMetrics.get("replies"));
preparedStatement.setString(4, id);
preparedStatement.executeUpdate();
preparedStatement.close();
}
public void insertSyncProcess(String communityURL, String currentTab,
Integer currentPage, Integer communityId,
Integer observation)
throws SQLException {
preparedStatement = connection.prepareStatement("INSERT INTO sync_progress " +
"(community_url, current_tab, " +
"current_page, community_id, " +
"observation) " +
"values (?, ?, ?, ?, ?)");
preparedStatement.setString(1, communityURL);
preparedStatement.setString(2, currentTab);
preparedStatement.setInt(3, currentPage);
preparedStatement.setInt(4, communityId);
preparedStatement.setInt(5, observation);
preparedStatement.executeUpdate();
preparedStatement.close();
}
public HashMap<String,Object> getUnfinishedSyncProcess() throws SQLException {
HashMap<String,Object> unfinishedProcess = new HashMap<String,Object>();
preparedStatement = connection.prepareStatement("SELECT * " +
"FROM sync_progress");
resultSet = preparedStatement.executeQuery();
if (resultSet.first()) {
unfinishedProcess.put("id", resultSet.getInt("id"));
unfinishedProcess.put("community_id", resultSet.getInt("community_id"));
unfinishedProcess.put("community_url", resultSet.getString("community_url"));
unfinishedProcess.put("current_tab", resultSet.getString("current_tab"));
unfinishedProcess.put("current_page", resultSet.getInt("current_page"));
unfinishedProcess.put("observation", resultSet.getInt("observation"));
}
preparedStatement.close();
resultSet.close();
return unfinishedProcess;
}
public void cleanSyncProgressTable() throws SQLException {
//Clean the table since it should be only one progress running at
//the same time
preparedStatement = connection.prepareStatement("DELETE FROM sync_progress");
preparedStatement.executeUpdate();
preparedStatement.close();
}
public void updateSyncProcess(Integer currentPage)
throws SQLException {
preparedStatement = connection.prepareStatement("UPDATE sync_progress SET " +
"current_page = ?");
preparedStatement.setInt(1, currentPage);
preparedStatement.executeUpdate();
preparedStatement.close();
}
public Integer getLastObservationId() throws SQLException {
Integer observation;
preparedStatement = connection.prepareStatement("SELECT observation " +
"FROM audit");
resultSet = preparedStatement.executeQuery();
if (resultSet.first())
observation = resultSet.getInt("observation");
else
observation = 0;
preparedStatement.close();
resultSet.close();
return observation;
}
} |
package org.jasig.portal.tools.al;
import org.jasig.portal.utils.XSLT;
import org.jasig.portal.utils.SAX2FilterImpl;
import org.jasig.portal.groups.*;
import org.jasig.portal.services.*;
import org.xml.sax.helpers.*;
import org.xml.sax.*;
import org.jasig.portal.*;
import java.sql.*;
import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.sax.*;
import javax.xml.transform.stream.*;
import org.apache.xalan.serialize.SerializerFactory;
import org.apache.xalan.serialize.Serializer;
import org.apache.xalan.templates.OutputProperties;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.Types;
import java.sql.Timestamp;
import java.sql.SQLException;
/**
* A utility class to load pushed fragment configuration into the database
* used by the alconfg ant target.
*
* @author <a href="mailto:pkharchenko@interactivebusiness.com">Peter Kharchenko</a>
* @author <a href="mailto:mvi@immagic.com">Michael Ivanov</a>
* @version 1.0
*/
public class ConfigToDataXML {
static final String configXSL="/org/jasig/portal/tools/al/ConfigToDataXML.xsl";
public static void main(String[] args) throws Exception {
String alConfigFile=args[0];
String outputDataFile=args[1];
HashMap rNames=new HashMap();
// compile a table of restriction types
Connection con=null;
try {
con=RDBMServices.getConnection();
if(con!=null) {
Statement stmt = con.createStatement();
String query="SELECT RESTRICTION_TYPE,RESTRICTION_NAME FROM UP_RESTRICTIONS";
ResultSet rs=stmt.executeQuery(query);
while(rs.next()) {
rNames.put(rs.getString("RESTRICTION_NAME"),rs.getString("RESTRICTION_TYPE"));
System.out.println("DEBUG: restriction type mapping "+rs.getString("RESTRICTION_NAME")+" -> "+rs.getString("RESTRICTION_TYPE"));
}
} else {
System.out.println("ERROR: unable to obtain database connection.");
System.exit(1);
}
} catch (Exception e) {
System.out.println("ERROR: exception raised while reading restriction type mappings:");
e.printStackTrace();
System.exit(1);
} finally {
if(con!=null) {
RDBMServices.releaseConnection(con);
}
}
// instantiate transfomer
SAXTransformerFactory saxTFactory=(SAXTransformerFactory) TransformerFactory.newInstance();
System.out.println("DEBUG: reading XSLT from url="+ConfigToDataXML.class.getResource(configXSL));
XMLReader reader = XMLReaderFactory.createXMLReader();
// for some weird weird reason, the following way of instantiating the parser causes all elements to dissapear ...
// nothing like a bizzare bug like that to take up your afternoon :(
// XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
TransformerHandler thand=saxTFactory.newTransformerHandler(new StreamSource(ConfigToDataXML.class.getResourceAsStream(configXSL)));
// instantiate filter
ConfigFilter filter=new ConfigFilter(thand,rNames);
reader.setContentHandler(filter);
thand.setResult(new StreamResult(outputDataFile));
reader.parse(new InputSource(ConfigToDataXML.class.getResourceAsStream(alConfigFile)));
// Cleaning the database before the DbLoader is called
(new DbCleaner(filter.getFragmentIds())).cleanTables();
System.out.println("DEBUG: done.");
}
/**
* Cleans up the tables contained the old data of the fragments to be reloaded
* It is used before the DbLoader utility is called
*
*/
private static class DbCleaner {
private static Vector fragmentIds;
public DbCleaner ( Vector fragmentIds ) {
this.fragmentIds = fragmentIds;
}
public static void cleanTables() {
if ( fragmentIds != null && fragmentIds.size() > 0 ) {
System.out.println("DEBUG: cleaning tables...");
Connection con = RDBMServices.getConnection();
try {
con.setAutoCommit(false);
PreparedStatement deleteLayoutStruct = con.prepareStatement("DELETE FROM up_layout_struct_aggr WHERE fragment_id = ?");
PreparedStatement deleteFragments = con.prepareStatement("DELETE FROM up_fragments WHERE fragment_id = ?");
PreparedStatement deleteFragmentRestrictions = con.prepareStatement("DELETE FROM up_fragment_restrictions WHERE fragment_id = ?");
PreparedStatement deleteFragmentParams = con.prepareStatement("DELETE FROM up_fragment_param WHERE fragment_id = ?");
PreparedStatement deleteOwnerFragment = con.prepareStatement("DELETE FROM up_owner_fragment WHERE fragment_id = ?");
PreparedStatement deleteGroupFragment = con.prepareStatement("DELETE FROM up_group_fragment WHERE fragment_id = ?");
for ( int i = 0; i < fragmentIds.size(); i++ ) {
int fragmentId = Integer.parseInt(fragmentIds.get(i).toString());
// Setting the parameter - fragment id
deleteLayoutStruct.setInt(1,fragmentId);
deleteFragments.setInt(1,fragmentId);
deleteFragmentRestrictions.setInt(1,fragmentId);
deleteFragmentParams.setInt(1,fragmentId);
deleteOwnerFragment.setInt(1,fragmentId);
deleteGroupFragment.setInt(1,fragmentId);
// Executing statements
deleteLayoutStruct.executeUpdate();
deleteFragments.executeUpdate();
deleteFragmentRestrictions.executeUpdate();
deleteFragmentParams.executeUpdate();
deleteOwnerFragment.executeUpdate();
deleteGroupFragment.executeUpdate();
}
// Commit
con.commit();
if ( deleteLayoutStruct != null ) deleteLayoutStruct.close();
if ( deleteFragments != null ) deleteFragments.close();
if ( deleteFragmentRestrictions != null ) deleteFragmentRestrictions.close();
if ( deleteFragmentParams != null ) deleteFragmentParams.close();
if ( deleteOwnerFragment != null ) deleteOwnerFragment.close();
if ( deleteGroupFragment != null ) deleteGroupFragment.close();
if ( con != null ) con.close();
System.out.println("DEBUG: cleaning done...");
} catch ( Exception e ) {
System.out.println ( "DEBUG: " + e.getMessage() );
e.printStackTrace();
}
}
}
};
/**
* Attempts to determine group key based on a group name.
* If the group key can not be determined in a unique way, the method will terminate!
*
* @param groupName a <code>String</code> value
* @return a group key
*/
static String getGroupKey(String groupName) throws Exception {
EntityIdentifier[] mg=GroupService.searchForGroups(groupName,IGroupConstants.IS,Class.forName("org.jasig.portal.security.IPerson"));
if(mg!=null && mg.length>0) {
if(mg.length>1) {
// multiple matches
System.out.println("ERROR: group name \""+groupName+"\" matches several existing groups: [Key\tName\tDescription]");
for(int i=0;i<mg.length;i++) {
IEntityGroup g=GroupService.findGroup(mg[i].getKey());
System.out.print("\t\""+g.getKey()+"\"\t"+g.getName()+"\"\t"+g.getDescription());
}
System.out.println("Please modify config file to specify group key directly (i.e. <group key=\"keyValue\">...)");
System.exit(1);
} else {
System.out.println("DEBUG: group \""+groupName+"\", key=\""+mg[0].getKey()+"\"");
return mg[0].getKey();
}
} else {
// didnt' match
System.out.println("ERROR: can not find user group with name \""+groupName+"\" in the database !");
// try nonexact match
EntityIdentifier[] mg2=GroupService.searchForGroups(groupName,IGroupConstants.CONTAINS,Class.forName("org.jasig.portal.security.IPerson"));
if(mg2!=null && mg2.length>0) {
System.out.print("Possible matches are: [");
for(int i=0;i<mg2.length;i++) {
IEntityGroup g=GroupService.findGroup(mg2[i].getKey());
System.out.print("\""+g.getName()+"\" ");
}
System.out.println("]");
}
throw new PortalException("ERROR: can not find user group with name \""+groupName+"\" in the database !");
}
return null;
}
/**
* A filter that will perform the following functions:
* - intercept and verify restriction names, writing out ids
* - intercept and verify user group names, writing out ids
*
*/
private static class ConfigFilter extends SAX2FilterImpl {
Map rMap;
boolean groupMode=false;
AttributesImpl groupAtts;
String groupLocalName;
String groupUri;
String groupData=null;
private Vector fragmentIds;
public ConfigFilter(ContentHandler ch,Map rMap) {
super(ch);
this.rMap=rMap;
fragmentIds= new Vector();
}
public Vector getFragmentIds() {
return fragmentIds;
}
public void characters (char ch[], int start, int length) throws SAXException {
if(groupMode) {
// accumulate character data
String ds=new String(ch,start,length);
if(groupData==null) {
groupData=ds;
} else {
groupData=groupData+ds;
}
} else {
super.characters(ch,start,length);
}
}
public void startElement (String uri, String localName, String qName, Attributes atts) throws SAXException {
// Adding the fragment id to the vector
if ( qName.equals("fragment") )
fragmentIds.add(atts.getValue("id"));
if(qName.equals("group")) { // this could be made more robust by adding another mode for "groups" element
groupMode=true;
groupUri=uri; groupLocalName=localName; groupAtts=new AttributesImpl(atts);
} else if(qName.equals("restriction")) { // this can also be made more robust by adding another mode for "restrictions" element
AttributesImpl ai=new AttributesImpl(atts);
// look up restriction name in the DB
String restrType;
if(ai.getIndex("type")!=-1) {
// restriction type was specified
if(!rMap.containsValue(ai.getValue("type"))) {
System.out.println("ERROR: specified restriction type \""+ai.getValue("type")+"\" does not exist ! Either correct the type value, or consider using match by restriction name (i.e. <restriction name=\"priority\" ...)");
System.exit(1);
} else {
if(ai.getIndex("name")!=-1 && rMap.containsKey(ai.getValue("name")) && (!ai.getValue("type").equals((String)rMap.get(ai.getValue("name"))))) {
System.out.println("ERROR: specified restriction type \""+ai.getValue("type")+"\" does not match the specified name \""+ai.getValue("name")+"\" in the database. name \""+ai.getValue("name")+"\" matches restriction type \""+(String)rMap.get(ai.getValue("name"))+"\"");
System.exit(1);
} else {
super.startElement(uri,localName,qName,atts);
}
}
} else {
String restrName=ai.getValue("name");
restrType=(String)rMap.get(restrName);
if(restrType!=null) {
ai.addAttribute(uri,"type","type","CDATA",restrType);
} else {
System.out.println("ERROR: config file specifies a restriction name \""+restrName+"\" which is not registered with the database!");
System.exit(1);
}
super.startElement(uri,localName,qName,ai);
}
} else {
super.startElement(uri,localName,qName,atts);
}
}
public void endElement (String uri, String localName, String qName) throws SAXException {
if(groupMode) {
if(qName.equals("group")) {
if(groupAtts.getIndex("key")==-1) {
if(groupData!=null) {
String groupKey=null;
try {
groupKey=getGroupKey(groupData);
} catch (Exception e) {
System.out.println("ERROR: encountered exception while trying to determine group key for a group name \""+groupData+"\"");
e.printStackTrace();
System.exit(1);
}
groupAtts.addAttribute(groupUri,"key","key","CDATA",groupKey);
// output group element
super.startElement(groupUri,groupLocalName,"group",groupAtts);
super.characters(groupData.toCharArray(), 0, groupData.length());
super.endElement(groupUri,groupLocalName,"group");
} else {
System.out.println("ERROR: one of the group elements is empty and no group key has been specified !");
System.exit(1);
}
} else {
// check specified group key
try {
IEntityGroup g=GroupService.findGroup(groupAtts.getValue("key"));
if(g!=null) {
if(groupData!=null) {
if(g.getName().equals(groupData)) {
System.out.println("DEBUG: group key=\""+groupAtts.getValue("key")+"\" checked out with the name \""+groupData+"\".");
// output group element
super.startElement(groupUri,groupLocalName,"group",groupAtts);
if(groupData!=null) {
super.characters(groupData.toCharArray(), 0, groupData.length());
}
super.endElement(groupUri,groupLocalName,"group");
} else {
System.out.println("ERROR: group key \""+groupAtts.getValue("key")+"\" belongs to a group with a name \""+g.getName()+"\", where the name specified by the config file is \""+groupData+"\". Please fix the config file.");
System.exit(1);
}
}
} else {
System.out.println("ERROR: unable to find a group with a key \""+groupAtts.getValue("key")+"\"! Either correct the key, or consider matching the group by name.");
System.exit(1);
}
} catch (Exception e) {
System.out.println("ERROR: exception raised while trying to look up group by a key=\""+groupAtts.getValue("key")+"\"!");
e.printStackTrace();
System.exit(1);
}
}
} else {
System.out.println("WARNING: <group/> contains other elements, which it shouldn't! Please check config validity.");
}
groupMode=false;
groupData=null;
groupAtts=null;
groupUri=null;
groupLocalName=null;
} else {
super.endElement(uri,localName,qName);
}
}
};
} |
package io.ddf.spark;
import com.google.gson.Gson;
import io.ddf.DDF;
import io.ddf.DDFManager;
import io.ddf.content.Schema;
import io.ddf.datasource.DataSourceDescriptor;
import io.ddf.datasource.JDBCDataSourceCredentials;
import io.ddf.datasource.JDBCDataSourceDescriptor;
import io.ddf.exception.DDFException;
import io.ddf.spark.content.SchemaHandler;
import io.ddf.spark.etl.udf.DateParse;
import io.ddf.spark.etl.udf.DateTimeExtract;
import io.ddf.spark.util.SparkUtils;
import io.ddf.spark.util.Utils;
import org.apache.commons.lang.StringUtils;
import org.apache.spark.SparkContext;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.rdd.RDD;
import org.apache.spark.sql.DataFrame;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.hive.HiveContext;
import java.io.File;
import java.security.SecureRandom;
import java.util.*;
//import shark.SharkEnv;
//import shark.api.JavaSharkContext;
/**
* An Apache-Spark-based implementation of DDFManager
*/
public class SparkDDFManager extends DDFManager {
@Override
public String getEngine() {
return "spark";
}
private static final String DEFAULT_SPARK_APPNAME = "DDFClient";
private static final String DEFAULT_SPARK_MASTER = "local[4]";
public SparkDDFManager(SparkContext sparkContext) throws DDFException {
this.setEngineName("spark");
this.initialize(sparkContext, null);
}
@Override
public DDF transferByTable(String fromEngine, String tableName) throws
DDFException {
mLog.info("Get the engine " + fromEngine + " to transfer table : " +
tableName);
DDFManager fromManager = this.getDDFCoordinator().getEngine(fromEngine);
DataSourceDescriptor dataSourceDescriptor = fromManager
.getDataSourceDescriptor();
if (dataSourceDescriptor instanceof JDBCDataSourceDescriptor) {
// JDBCConnection.
JDBCDataSourceDescriptor jdbcDataSourceDescriptor = (JDBCDataSourceDescriptor)
dataSourceDescriptor;
Map<String, String> options = new HashMap<String, String>();
options.put("dbtable", tableName);
JDBCDataSourceCredentials jdbcCredential =
jdbcDataSourceDescriptor.getCredentials();
// TODO
if (fromManager.getEngine().equals("sfdc")) {
options.put("url", jdbcDataSourceDescriptor.getDataSourceUri().getUri
().toString());
mLog.info("sfdc uri: " + jdbcDataSourceDescriptor.getDataSourceUri()
.getUri().toString());
} else {
options.put("url", jdbcDataSourceDescriptor.getDataSourceUri().getUri()
.toString() + "?user=" + jdbcCredential.getUsername() +
"&password="+jdbcCredential.getPassword());
}
// TODO: Pay attention here. Some maybe username?
// options.put("user", jdbcCredential.getUserName());
// options.put("password", jdbcCredential.getPassword());
// TODO: What if sfdc.
DataFrame rdd = mHiveContext.load("jdbc", options);
if (rdd == null) {
throw new DDFException("fail use spark datasource api");
}
Schema schema = SchemaHandler.getSchemaFromDataFrame(rdd);
DDF ddf = this.newDDF(this, rdd, new Class<?>[]
{DataFrame.class}, null, null, null, schema);
ddf.getRepresentationHandler().get(new Class<?>[]{RDD.class, Row.class});
return ddf;
} else {
throw new DDFException("Currently no other DataSourceDescriptor is " +
"supported");
}
}
@Override
public DDF transfer(String fromEngine, String ddfuri) throws DDFException {
DDFManager fromManager = this.getDDFCoordinator().getEngine(fromEngine);
mLog.info("Get the engine " + fromEngine + " to transfer ddf : " + ddfuri);
DDF fromDDF = fromManager.getDDFByURI(ddfuri);
if (fromDDF == null) {
throw new DDFException("There is no ddf with uri : " + ddfuri + " in " +
"another engine");
}
String fromTableName = fromDDF.getTableName();
return this.transferByTable(fromEngine, fromTableName);
}
/**
* Use system environment variables to configure the SparkContext creation.
*
* @throws DDFException
*/
public SparkDDFManager() throws DDFException {
this.setEngineName("spark");
this.initialize(null, new HashMap<String, String>());
}
public SparkDDFManager(Map<String, String> params) throws DDFException {
this.setEngineName("spark");
this.initialize(null, params);
}
private void initialize(SparkContext sparkContext, Map<String, String> params) throws DDFException {
this.setSparkContext(sparkContext == null ? this.createSparkContext(params) : sparkContext);
this.mHiveContext = new HiveContext(this.mSparkContext);
String compression = System.getProperty("spark.sql.inMemoryColumnarStorage.compressed", "true");
String batchSize = System.getProperty("spark.sql.inMemoryColumnarStorage.batchSize", "1000");
mLog.info(">>>> spark.sql.inMemoryColumnarStorage.compressed= " + compression);
mLog.info(">>>> spark.sql.inMemoryColumnarStorage.batchSize= " + batchSize);
this.mHiveContext.setConf("spark.sql.inMemoryColumnarStorage.compressed", compression);
this.mHiveContext.setConf("spark.sql.inMemoryColumnarStorage.batchSize", batchSize);
// register SparkSQL UDFs
this.registerUDFs();
}
// TODO: Dynamically load UDFs
private void registerUDFs() {
DateParse.register(this.mHiveContext);
DateTimeExtract.register(this.mHiveContext);
}
public String getDDFEngine() {
return "spark";
}
private SparkContext mSparkContext;
private JavaSparkContext mJavaSparkContext;
public SparkContext getSparkContext() {
return mSparkContext;
}
private void setSparkContext(SparkContext sparkContext) {
this.mSparkContext = sparkContext;
}
private HiveContext mHiveContext;
private static final String[][] SPARK_ENV_VARS = new String[][] {
// @formatter:off
{ "SPARK_APPNAME", "spark.appname" },
{ "SPARK_MASTER", "spark.master" },
{ "SPARK_HOME", "spark.home" },
{ "SPARK_SERIALIZER", "spark.kryo.registrator" },
{ "HIVE_HOME", "hive.home" },
{ "HADOOP_HOME", "hadoop.home" },
{ "DDFSPARK_JAR", "ddfspark.jar" }
// @formatter:on
};
public HiveContext getHiveContext() {
return mHiveContext;
}
// private SparkUtils.createSharkContext mSharkContext;
// public SharkContext getSharkContext() {
// return mSharkContext;
// private JavaSharkContext mJavaSharkContext;
// public JavaSharkContext getJavaSharkContext() {
// return mJavaSharkContext;
// public void setJavaSharkContext(JavaSharkContext javaSharkContext) {
// this.mJavaSharkContext = javaSharkContext;
/**
* Also calls setSparkContext() to the same sharkContext
*
* @param sharkContext
*/
// private void setSharkContext(SharkContext sharkContext) {
// this.mSharkContext = sharkContext;
// this.setSparkContext(sharkContext);
private Map<String, String> mSparkContextParams;
public Map<String, String> getSparkContextParams() {
return mSparkContextParams;
}
private void setSparkContextParams(Map<String, String> mSparkContextParams) {
this.mSparkContextParams = mSparkContextParams;
}
/* merge priority is as follows: (1) already set in params, (2) in system properties (e.g., -Dspark.home=xxx), (3) in
* environment variables (e.g., export SPARK_HOME=xxx)
*
* @param params
* @return
*/
private Map<String, String> mergeSparkParamsFromSettings(Map<String, String> params) {
if (params == null) params = new HashMap<String, String>();
Map<String, String> env = System.getenv();
for (String[] varPair : SPARK_ENV_VARS) {
if (params.containsKey(varPair[0])) continue; // already set in params
// Read setting either from System Properties, or environment variable.
// Env variable has lower priority if both are set.
String value = System.getProperty(varPair[1], env.get(varPair[0]));
if (value != null && value.length() > 0) params.put(varPair[0], value);
}
// Some well-known defaults
if (!params.containsKey("SPARK_MASTER")) params.put("SPARK_MASTER", DEFAULT_SPARK_MASTER);
if (!params.containsKey("SPARK_APPNAME")) params.put("SPARK_APPNAME", DEFAULT_SPARK_APPNAME);
params.put("SPARK_SERIALIZER", "io.spark.content.KryoRegistrator");
Gson gson = new Gson();
mLog.info(String.format(">>>>>>> params = %s", gson.toJson(params)));
return params;
}
/**
* Side effect: also sets SharkContext and SparkContextParams in case the client wants to examine or use those.
*
* @param params
* @return
* @throws DDFException
*/
private SparkContext createSparkContext(Map<String, String> params) throws DDFException {
this.setSparkContextParams(this.mergeSparkParamsFromSettings(params));
String ddfSparkJar = params.get("DDFSPARK_JAR");
String[] jobJars = ddfSparkJar != null ? ddfSparkJar.split(",") : new String[] { };
ArrayList<String> finalJobJars = new ArrayList<String>();
// DDFSPARK_JAR could contain directories too, used in case of Databricks Cloud where we don't have the jars at start-up
// time but the directory and we will search and includes all of jars at run-time
for (String jobJar: jobJars) {
if ((!jobJar.endsWith(".jar")) && (new File(jobJar).list() != null)) {
// This is a directory
ArrayList<String> jars = Utils.listJars(jobJar);
if (jars != null) {
finalJobJars.addAll(jars);
}
} else {
finalJobJars.add(jobJar);
}
}
mLog.info(">>>>> ddfSparkJar = " + ddfSparkJar);
for(String jar: finalJobJars) {
mLog.info(">>>>> " + jar);
}
jobJars = new String[finalJobJars.size()];
jobJars = finalJobJars.toArray(jobJars);
for (String key : params.keySet()) {
mLog.info(">>>> key = " + key + ", value = " + params.get(key));
}
SparkContext context = SparkUtils.createSparkContext(params.get("SPARK_MASTER"), params.get("SPARK_APPNAME"),
params.get("SPARK_HOME"), jobJars, params);
this.mSparkContext = context;
this.mJavaSparkContext = new JavaSparkContext(context);
return this.getSparkContext();
}
@Override
public DDF newDDF(DDFManager manager, Object data, Class<?>[] typeSpecs,
String engineName, String namespace, String name, Schema
schema)
throws DDFException {
DDF ddf = super.newDDF(manager, data, typeSpecs, engineName, namespace,
name, schema);
if(ddf instanceof SparkDDF) {
((SparkDDF) ddf).saveAsTable();
}
return ddf;
}
@Override
public DDF newDDF(Object data, Class<?>[] typeSpecs, String engineName,
String namespace, String name, Schema schema)
throws DDFException {
DDF ddf = super.newDDF(data, typeSpecs, engineName, namespace, name,
schema);
if(ddf instanceof SparkDDF) {
((SparkDDF) ddf).saveAsTable();
}
return ddf;
}
public DDF loadTable(String fileURL, String fieldSeparator) throws DDFException {
JavaRDD<String> fileRDD = mJavaSparkContext.textFile(fileURL);
String[] metaInfos = getMetaInfo(fileRDD, fieldSeparator);
SecureRandom rand = new SecureRandom();
String tableName = "tbl" + String.valueOf(Math.abs(rand.nextLong()));
String cmd = "CREATE TABLE " + tableName + "(" + StringUtils.join(metaInfos, ", ")
+ ") ROW FORMAT DELIMITED FIELDS TERMINATED BY '" + fieldSeparator + "'";
sql(cmd, "SparkSQL");
sql("LOAD DATA LOCAL INPATH '" + fileURL + "' " +
"INTO TABLE " + tableName, "SparkSQL");
return sql2ddf("SELECT * FROM " + tableName, "SparkSQL");
}
@Override
public DDF getOrRestoreDDFUri(String ddfURI) throws DDFException {
return null;
}
@Override
public DDF getOrRestoreDDF(UUID uuid) throws DDFException {
return null;
}
/**
* Given a String[] vector of data values along one column, try to infer what the data type should be.
* <p/>
* TODO: precompile regex
*
* @param vector
* @return string representing name of the type "integer", "double", "character", or "logical" The algorithm will
* first scan the vector to detect whether the vector contains only digits, ',' and '.', <br>
* if true, then it will detect whether the vector contains '.', <br>
* if true then the vector is double else it is integer <br>
* if false, then it will detect whether the vector contains only 'T' and 'F' <br>
* if true then the vector is logical, otherwise it is characters
*/
public static String determineType(String[] vector, Boolean doPreferDouble) {
boolean isNumber = true;
boolean isInteger = true;
boolean isLogical = true;
boolean allNA = true;
for (String s : vector) {
if (s == null || s.startsWith("NA") || s.startsWith("Na") || s.matches("^\\s*$")) {
// Ignore, don't set the type based on this
continue;
}
allNA = false;
if (isNumber) {
// match numbers: 123,456.123 123 123,456 456.123 .123
if (!s.matches("(^|^-)((\\d+(,\\d+)*)|(\\d*))\\.?\\d+$")) {
isNumber = false;
}
// match double
else if (isInteger && s.matches("(^|^-)\\d*\\.{1}\\d+$")) {
isInteger = false;
}
}
// NOTE: cannot use "else" because isNumber changed in the previous
// if block
if (isLogical && !s.toLowerCase().matches("^t|f|true|false$")) {
isLogical = false;
}
}
// String result = "Unknown";
String result = "string";
if (!allNA) {
if (isNumber) {
if (!isInteger || doPreferDouble) {
result = "double";
} else {
result = "int";
}
} else {
if (isLogical) {
result = "boolean";
} else {
result = "string";
}
}
}
return result;
}
/**
* TODO: check more than a few lines in case some lines have NA
*
* @param fileRDD
* @return
*/
public String[] getMetaInfo(JavaRDD<String> fileRDD, String fieldSeparator) {
String[] headers = null;
int sampleSize = 5;
// sanity check
if (sampleSize < 1) {
mLog.info("DATATYPE_SAMPLE_SIZE must be bigger than 1");
return null;
}
List<String> sampleStr = fileRDD.take(sampleSize);
sampleSize = sampleStr.size(); // actual sample size
mLog.info("Sample size: " + sampleSize);
// create sample list for getting data type
String[] firstSplit = sampleStr.get(0).split(fieldSeparator);
// get header
boolean hasHeader = false;
if (hasHeader) {
headers = firstSplit;
} else {
headers = new String[firstSplit.length];
int size = headers.length;
for (int i = 0; i < size; ) {
headers[i] = "V" + (++i);
}
}
String[][] samples = hasHeader ? (new String[firstSplit.length][sampleSize - 1])
: (new String[firstSplit.length][sampleSize]);
String[] metaInfoArray = new String[firstSplit.length];
int start = hasHeader ? 1 : 0;
for (int j = start; j < sampleSize; j++) {
firstSplit = sampleStr.get(j).split(fieldSeparator);
for (int i = 0; i < firstSplit.length; i++) {
samples[i][j - start] = firstSplit[i];
}
}
boolean doPreferDouble = true;
for (int i = 0; i < samples.length; i++) {
String[] vector = samples[i];
metaInfoArray[i] = headers[i] + " " + determineType(vector, doPreferDouble);
}
return metaInfoArray;
}
} |
package functions;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class ChronOntology {
public static final String WELT_URI = "https://gazetteer.dainst.org/place/2042600";
public static final String[] TYPES = {"spatiallyPartOfRegion", "isNamedAfter", "hasCoreArea"};
public static final String GAZETTEER_HOST = "https://gazetteer.dainst.org";
public static final String GAZETTEER_DATA_INTERFACE = "doc";
public static final String GAZETTEER_RESOURCE_INTERFACE = "place";
public static JSONArray getSpatialData(String uri) throws Exception {
// init output
JSONArray spatialData = new JSONArray();
// get data from chronontology
String url = uri.replace("period", "data/period");
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
if (con.getResponseCode() == 200) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// parse data
JSONObject data = (JSONObject) new JSONParser().parse(response.toString());
JSONObject resource = (JSONObject) data.get("resource");
for (String item : TYPES) {
JSONArray spatial = (JSONArray) resource.get(item);
if (spatial != null) {
JSONArray spatialHTTPS = new JSONArray();
for (Object element : spatial) {
String tmp = element.toString().replace("http:
spatialHTTPS.add(tmp);
}
for (Object element : spatialHTTPS) {
URL daiURL = new URL(GAZETTEER_HOST + "/" + GAZETTEER_DATA_INTERFACE + "/" + element.toString().replace(GAZETTEER_HOST + "/" + GAZETTEER_RESOURCE_INTERFACE + "/", "") + ".geojson");
HttpURLConnection con2 = (HttpURLConnection) daiURL.openConnection();
con2.setRequestMethod("GET");
con2.setRequestProperty("Accept", "application/json");
if (con2.getResponseCode() < 400) {
BufferedReader in2 = new BufferedReader(new InputStreamReader(con2.getInputStream(), "UTF-8"));
String inputLine2;
StringBuilder response2 = new StringBuilder();
while ((inputLine2 = in2.readLine()) != null) {
response2.append(inputLine2);
}
in2.close();
// parse data
JSONObject dataDAI = (JSONObject) new JSONParser().parse(response2.toString());
JSONObject propertiesDAI = (JSONObject) dataDAI.get("properties");
JSONObject prefName = (JSONObject) propertiesDAI.get("prefName");
String parentURLStr = (String) propertiesDAI.get("parent");
JSONObject geometryDAI = (JSONObject) dataDAI.get("geometry");
JSONArray geometriesDAI = (JSONArray) geometryDAI.get("geometries");
JSONObject parentGeometry = new JSONObject();
while (geometriesDAI.size() == 0) {
// of geometry is empty get geometry from parent and loop it
String parentURLStrOrigin = parentURLStr;
// if URI is "Welt" quit loop
if (parentURLStrOrigin.equals(WELT_URI)) {
// set spatialData to length zero if uri is "Welt"
spatialData = new JSONArray();
break;
}
parentURLStr = parentURLStr.replace("/" + GAZETTEER_RESOURCE_INTERFACE + "/", "/" + GAZETTEER_DATA_INTERFACE + "/");
parentURLStr += ".geojson";
URL parentURL = new URL(parentURLStr);
HttpURLConnection con3 = (HttpURLConnection) parentURL.openConnection();
con3.setRequestMethod("GET");
con3.setRequestProperty("Accept", "application/json");
if (con3.getResponseCode() < 400) {
BufferedReader in3 = new BufferedReader(new InputStreamReader(con3.getInputStream(), "UTF-8"));
String inputLine3;
StringBuilder response3 = new StringBuilder();
while ((inputLine3 = in3.readLine()) != null) {
response3.append(inputLine3);
}
in3.close();
// parse data
JSONObject dataDAIparent = (JSONObject) new JSONParser().parse(response3.toString());
JSONObject geometryDAIparent = (JSONObject) dataDAIparent.get("geometry");
JSONArray geometriesDAIparent = (JSONArray) geometryDAIparent.get("geometries");
JSONObject propertiesDAIparent = (JSONObject) dataDAIparent.get("properties");
JSONObject prefNameParent = (JSONObject) propertiesDAIparent.get("prefName");
String prefNameTitleParent = (String) prefNameParent.get("title");
parentURLStr = (String) propertiesDAIparent.get("parent");
if (geometriesDAIparent.size() > 0) {
parentGeometry.put("uri", parentURLStrOrigin);
String[] idSplit = parentURLStrOrigin.split("/");
parentGeometry.put("id", idSplit[idSplit.length-1]);
parentGeometry.put("name", prefNameTitleParent);
geometriesDAI = geometriesDAIparent;
}
}
}
// create output geojson
JSONObject feature = new JSONObject();
feature.put("type", "Feature");
JSONObject properties = new JSONObject();
properties.put("name", (String) prefName.get("title"));
properties.put("relation", item);
properties.put("uri", (String) dataDAI.get("id"));
String idStr = (String) dataDAI.get("id");
String[] idSplit = idStr.split("/");
properties.put("id", idSplit[idSplit.length-1]);
if (parentGeometry.isEmpty()) {
parentGeometry.put("uri", null);
parentGeometry.put("id", null);
parentGeometry.put("name", "geom origin");
properties.put("parentGeometry", parentGeometry);
} else {
properties.put("parentGeometry", parentGeometry);
}
feature.put("properties", properties);
for (Object geom : geometriesDAI) {
JSONObject geomEntry = (JSONObject) geom;
if (geomEntry.get("type").equals("MultiPolygon")) {
feature.put("geometry", geomEntry);
} else if (geomEntry.get("type").equals("Point")) {
feature.put("geometry", geomEntry);
}
}
spatialData.add(feature);
}
}
}
}
}
// if no geom available load world json
if (spatialData.isEmpty()) {
BufferedReader reader = new BufferedReader(new FileReader(ChronOntology.class.getClassLoader().getResource("world.json").getFile()));
String line;
String json = "";
while ((line = reader.readLine()) != null) {
json += line;
}
JSONObject dataWORLD = (JSONObject) new JSONParser().parse(json.toString());
JSONArray featureWorldArray = (JSONArray) dataWORLD.get("features");
JSONObject featureWorld = (JSONObject) featureWorldArray.get(0);
JSONObject properties = new JSONObject();
JSONObject parentGeometry = new JSONObject();
parentGeometry.put("uri", null);
parentGeometry.put("id", null);
parentGeometry.put("name", "geom origin");
properties.put("parentGeometry", parentGeometry);
properties.put("name", "world");
properties.put("relation", "unknown");
properties.put("uri", "https://gazetteer.dainst.org/place/2042600");
properties.put("id", "2042600");
featureWorld.remove("properties");
featureWorld.put("properties", properties);
spatialData.add(featureWorld);
}
return spatialData;
}
} |
package com.complet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
public class LinkRetrieve extends HTMLEditorKit.ParserCallback {
// Extensions to EXCLUDE
private final static Pattern excludes = Pattern.compile(".*(\\.(css|js|gif|jpg|png|mp3|mp4|zip|gz|jpeg|pdf))$");
public static void start(String link) {
try {
URL url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
new ParserDelegator().parse(reader, new LinkRetrieve(), true);
} catch (IOException e) {
System.err.println("This URL was malformed --> " + link + " !");
}
}
@Override
public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {
String link = null;
if (t == HTML.Tag.A) {
try {
Enumeration<?> attributeNames = a.getAttributeNames();
if (attributeNames.nextElement().equals(HTML.Attribute.HREF))
link = a.getAttribute(HTML.Attribute.HREF).toString();
} catch (NoSuchElementException e) {
System.err.println("No HREF Attribute Found in Link ! ");
return;
}
if (link != null) {
// Exclude links that end in
// jpeg,jpg,zip,mp,pdf,png,gz,gif,css,gif not contain ://dl.
// and not javascript:void(0)
Matcher li = excludes.matcher(link);
if (!(li.matches() || link.contains("://dl.") || link == ("javascript:void(0)"))) {
if (link.startsWith("http") && link.contains(":
try {
// If thread 1 then
if (RunClass.currentThread().getName().equals(Mainclass.getT1name())) {
// Check Link Does NOT already Exist in list
if (!Mainclass.getThread1_list().contains(link)) {
// check if link broken... if not returns
// "OK" and
// make sure link is not an image
if (ServerResponse.response(new URL(link)).equals("OK")
&& MediaCheck.media(new URL(link))) {
// Checks link's robot's content
// I only care if it's indexalbe or
// followable
// If link is suitable for me i take it
// (The noindexables which may stay will
// be removed after i make use of them)
RobotTags.checkAccess(link);
if (RunClass.robotIndex_thread1 == true
|| RunClass.robotFollow_thread1 == true) {
Mainclass.getThread1_list().add(link);
if (RunClass.robotFollow_thread1 == true) {
RobotTags.thread1_mFollow.add(true);
} else {
RobotTags.thread1_mFollow.add(false);
}
if (RunClass.robotIndex_thread1 == true) {
RobotTags.thread1_mIndex.add(true);
} else {
RobotTags.counter++;
RobotTags.thread1_mIndex.add(false);
}
}
}
}
} else if (RunClass.currentThread().getName().equals(Mainclass.getT2name())) {
// Check Link Does NOT already Exist in list
if (!Mainclass.getThread2_list().contains(link)) {
// check if link broken... if not returns
// "OK" and
// make sure link is not an image
if (ServerResponse.response(new URL(link)).equals("OK")
&& MediaCheck.media(new URL(link))) {
// Checks link's robot's content
// I only care if it's indexalbe or
// followable
// If link is suitable for me i take it
// (The noindexables which may stay will
// be removed after i make use of them)
RobotTags.checkAccess(link);
if (RunClass.robotIndex_thread2 == true
|| RunClass.robotFollow_thread2 == true) {
Mainclass.getThread2_list().add(link);
if (RunClass.robotFollow_thread2 == true) {
RobotTags.thread2_mFollow.add(true);
} else {
RobotTags.thread2_mFollow.add(false);
}
if (RunClass.robotIndex_thread2 == true) {
RobotTags.thread2_mIndex.add(true);
} else {
RobotTags.counter++;
RobotTags.thread2_mIndex.add(false);
}
}
}
}
} else if (RunClass.currentThread().getName().equals(Mainclass.getT3name())) {
// Check Link Does NOT already Exist in list
if (!Mainclass.getThread3_list().contains(link)) {
// check if link broken... if not returns
// "OK" and
// make sure link is not an image
if (ServerResponse.response(new URL(link)).equals("OK")
&& MediaCheck.media(new URL(link))) {
// Checks link's robot's content
// I only care if it's indexalbe or
// followable
// If link is suitable for me i take it
// (The noindexables which may stay will
// be removed after i make use of them)
RobotTags.checkAccess(link);
if (RunClass.robotIndex_thread3 == true
|| RunClass.robotFollow_thread3 == true) {
Mainclass.getThread3_list().add(link);
if (RunClass.robotFollow_thread3 == true) {
RobotTags.thread3_mFollow.add(true);
} else {
RobotTags.thread3_mFollow.add(false);
}
if (RunClass.robotIndex_thread3 == true) {
RobotTags.thread3_mIndex.add(true);
} else {
RobotTags.counter++;
RobotTags.thread3_mIndex.add(false);
}
}
}
}
}
} catch (IOException e) {
System.err.println("Something Went Wrong...Chill");
}
} else if (link.startsWith("
link = "http:/".concat(link.replaceFirst("
try {
// If thread 1 then
if (RunClass.currentThread().getName().equals(Mainclass.getT1name())) {
// Check Link Does NOT already Exist in list
if (!Mainclass.getThread1_list().contains(link)) {
// check if link broken... if not returns
// "OK" and
// make sure link is not an image
if (ServerResponse.response(new URL(link)).equals("OK")
&& MediaCheck.media(new URL(link))) {
// Checks link's robot's content
// I only care if it's indexalbe or
// followable
// If link is suitable for me i take it
// (The noindexables which may stay will
// be removed after i make use of them)
RobotTags.checkAccess(link);
if (RunClass.robotIndex_thread1 == true
|| RunClass.robotFollow_thread1 == true) {
Mainclass.getThread1_list().add(link);
if (RunClass.robotFollow_thread1 == true) {
RobotTags.thread1_mFollow.add(true);
} else {
RobotTags.thread1_mFollow.add(false);
}
if (RunClass.robotIndex_thread1 == true) {
RobotTags.thread1_mIndex.add(true);
} else {
RobotTags.counter++;
RobotTags.thread1_mIndex.add(false);
}
}
}
}
} else if (RunClass.currentThread().getName().equals(Mainclass.getT2name())) {
// Check Link Does NOT already Exist in list
if (!Mainclass.getThread2_list().contains(link)) {
// check if link broken... if not returns
// "OK" and
// make sure link is not an image
if (ServerResponse.response(new URL(link)).equals("OK")
&& MediaCheck.media(new URL(link))) {
// Checks link's robot's content
// I only care if it's indexalbe or
// followable
// If link is suitable for me i take it
// (The noindexables which may stay will
// be removed after i make use of them)
RobotTags.checkAccess(link);
if (RunClass.robotIndex_thread2 == true
|| RunClass.robotFollow_thread2 == true) {
Mainclass.getThread2_list().add(link);
if (RunClass.robotFollow_thread2 == true) {
RobotTags.thread2_mFollow.add(true);
} else {
RobotTags.thread2_mFollow.add(false);
}
if (RunClass.robotIndex_thread2 == true) {
RobotTags.thread2_mIndex.add(true);
} else {
RobotTags.counter++;
RobotTags.thread2_mIndex.add(false);
}
}
}
}
} else if (RunClass.currentThread().getName().equals(Mainclass.getT3name())) {
// Check Link Does NOT already Exist in list
if (!Mainclass.getThread3_list().contains(link)) {
// check if link broken... if not returns
// "OK" and
// make sure link is not an image
if (ServerResponse.response(new URL(link)).equals("OK")
&& MediaCheck.media(new URL(link))) {
// Checks link's robot's content
// I only care if it's indexalbe or
// followable
// If link is suitable for me i take it
// (The noindexables which may stay will
// be removed after i make use of them)
RobotTags.checkAccess(link);
if (RunClass.robotIndex_thread3 == true
|| RunClass.robotFollow_thread3 == true) {
Mainclass.getThread3_list().add(link);
if (RunClass.robotFollow_thread3 == true) {
RobotTags.thread3_mFollow.add(true);
} else {
RobotTags.thread3_mFollow.add(false);
}
if (RunClass.robotIndex_thread3 == true) {
RobotTags.thread3_mIndex.add(true);
} else {
RobotTags.counter++;
RobotTags.thread3_mIndex.add(false);
}
}
}
}
}
} catch (IOException e) {
System.err.println("Something Went Wrong...Chill");
}
// if it does not start with an '/' then it is NOT a
// path of the root link.
} else if (link.startsWith("/")) {
try {
// If thread 1
if (RunClass.currentThread().getName().equals(Mainclass.getT1name())) {
// Concatenates path with root link the correct
// way
link = new URL(new URL(Mainclass.getLink1()), link).toString();
// Check Link Does NOT already Exist in list
if (!Mainclass.getThread1_list().contains(link)) {
// check if link broken... if not returns
// "OK" and
// make sure link is not an image
if (ServerResponse.response(new URL(link)).equals("OK")
&& MediaCheck.media(new URL(link))) {
// Checks link's robot's content
// I only care if it's indexalbe or
// followable
// If link is suitable for me i take it
// (The noindexables which may stay will
// be removed after i make use of them)
RobotTags.checkAccess(link);
if (RunClass.robotIndex_thread1 == true
|| RunClass.robotFollow_thread1 == true) {
Mainclass.getThread1_list().add(link);
if (RunClass.robotFollow_thread1 == true) {
RobotTags.thread1_mFollow.add(true);
} else {
RobotTags.thread1_mFollow.add(false);
}
if (RunClass.robotIndex_thread1 == true) {
RobotTags.thread1_mIndex.add(true);
} else {
RobotTags.counter++;
RobotTags.thread1_mIndex.add(false);
}
}
}
}
// if thread 2
} else if (RunClass.currentThread().getName().equals(Mainclass.getT2name())) {
// Concatenates path with root link the correct
// way
link = new URL(new URL(Mainclass.getLink2()), link).toString();
// Check Link Does NOT already Exist in list
if (!Mainclass.getThread2_list().contains(link)) {
// check if link broken... if not returns
// "OK" and
// make sure link is not an image
if (ServerResponse.response(new URL(link)).equals("OK")
&& MediaCheck.media(new URL(link))) {
// Checks link's robot's content
// I only care if it's indexalbe or
// followable
// If link is suitable for me i take it
// (The noindexables which may stay will
// be removed after i make use of them)
RobotTags.checkAccess(link);
if (RunClass.robotIndex_thread2 == true
|| RunClass.robotFollow_thread2 == true) {
Mainclass.getThread2_list().add(link);
if (RunClass.robotFollow_thread2 == true) {
RobotTags.thread2_mFollow.add(true);
} else {
RobotTags.thread2_mFollow.add(false);
}
if (RunClass.robotIndex_thread2 == true) {
RobotTags.thread2_mIndex.add(true);
} else {
RobotTags.counter++;
RobotTags.thread2_mIndex.add(false);
}
}
}
}
// if thread 3
} else if (RunClass.currentThread().getName().equals(Mainclass.getT3name())) {
// Concatenates path with root link the correct
// way
link = new URL(new URL(Mainclass.getLink3()), link).toString();
// Check Link Does NOT already Exist in list
if (!Mainclass.getThread3_list().contains(link)) {
// check if link broken... if not returns
// "OK" and
// make sure link is not an image
if (ServerResponse.response(new URL(link)).equals("OK")
&& MediaCheck.media(new URL(link))) {
// Checks link's robot's content
// I only care if it's indexalbe or
// followable
// If link is suitable for me i take it
// (The noindexables which may stay will
// be removed after i make use of them)
RobotTags.checkAccess(link);
if (RunClass.robotIndex_thread3 == true
|| RunClass.robotFollow_thread3 == true) {
Mainclass.getThread3_list().add(link);
if (RunClass.robotFollow_thread3 == true) {
RobotTags.thread3_mFollow.add(true);
} else {
RobotTags.thread3_mFollow.add(false);
}
if (RunClass.robotIndex_thread3 == true) {
RobotTags.thread3_mIndex.add(true);
} else {
RobotTags.counter++;
RobotTags.thread3_mIndex.add(false);
}
}
}
}
}
} catch (IOException e) {
System.err.println("Just handled an exception..dont worry!");
}
// Avoid Getting Thrown Out From The Server
try {
Thread.sleep(1500);
} catch (Exception e) {
System.err.println("Oups Something Interrupted The Thread ...");
}
}
}
}
}
}
} |
package org.apache.batik.css.parser;
import java.io.IOException;
import java.io.Reader;
/**
* This class represents a CSS scanner - an object which decodes CSS lexical
* units.
*
* @author <a href="mailto:stephane@hillion.org">Stephane Hillion</a>
* @version $Id$
*/
public class Scanner {
/**
* The reader.
*/
protected Reader reader;
/**
* The current line.
*/
protected int line = 1;
/**
* The current column.
*/
protected int column = 1;
/**
* The current char.
*/
protected int current;
/**
* The reading buffer.
*/
protected char[] readBuffer;
/**
* The current position in the read buffer.
*/
protected int readPosition;
/**
* The current read buffer count.
*/
protected int readCount;
/**
* The recording buffer.
*/
protected char[] buffer = new char[128];
/**
* The current position in the buffer.
*/
protected int position;
/**
* The type of the current lexical unit.
*/
protected int type;
/**
* The start offset of the last lexical unit.
*/
protected int start;
/**
* The end offset of the last lexical unit.
*/
protected int end;
/**
* The characters to skip to create the string which represents the
* current token.
*/
protected int blankCharacters;
/**
* Creates a new Scanner object.
* @param r The reader to scan.
*/
public Scanner(Reader r) throws ParseException {
try {
reader = r;
readBuffer = new char[4096];
current = nextChar();
} catch (IOException e) {
throw new ParseException(e);
}
}
/**
* Creates a new Scanner object.
* @param r The reader to scan.
*/
public Scanner(String s) throws ParseException {
try {
reader = null;
readBuffer = s.toCharArray();
readPosition = 0;
readCount = readBuffer.length;
collapseCRNL(0);
if (readCount == 0) {
current = -1;
} else {
current = nextChar();
}
} catch (IOException e) {
throw new ParseException(e);
}
}
/**
* Returns the current line.
*/
public int getLine() {
return line;
}
/**
* Returns the current column.
*/
public int getColumn() {
return column;
}
/**
* Returns the buffer used to store the chars.
*/
public char[] getBuffer() {
return buffer;
}
/**
* Returns the start offset of the last lexical unit.
*/
public int getStart() {
return start;
}
/**
* Returns the end offset of the last lexical unit.
*/
public int getEnd() {
return end;
}
/**
* Clears the buffer.
*/
public void clearBuffer() {
if (position <= 0) {
position = 0;
} else {
buffer[0] = buffer[position-1];
position = 1;
}
}
/**
* The current lexical unit type like defined in LexicalUnits.
*/
public int getType() {
return type;
}
/**
* Returns the string representation of the current lexical unit.
*/
public String getStringValue() {
return new String(buffer, start, end - start);
}
/**
* Scans a @rule value. This method assumes that the current
* lexical unit is a at keyword.
*/
public void scanAtRule() throws ParseException {
try {
// waiting for EOF, ';' or '{'
loop: for (;;) {
switch (current) {
case '{':
int brackets = 1;
for (;;) {
nextChar();
switch (current) {
case '}':
if (--brackets > 0) {
break;
}
case -1:
break loop;
case '{':
brackets++;
}
}
case -1:
case ';':
break loop;
}
nextChar();
}
end = position;
} catch (IOException e) {
throw new ParseException(e);
}
}
/**
* Returns the next token.
*/
public int next() throws ParseException {
blankCharacters = 0;
start = position - 1;
nextToken();
end = position - endGap();
return type;
}
/**
* Returns the end gap of the current lexical unit.
*/
protected int endGap() {
int result = (current == -1) ? 0 : 1;
switch (type) {
case LexicalUnits.FUNCTION:
case LexicalUnits.STRING:
case LexicalUnits.S:
case LexicalUnits.PERCENTAGE:
result += 1;
break;
case LexicalUnits.COMMENT:
case LexicalUnits.HZ:
case LexicalUnits.EM:
case LexicalUnits.EX:
case LexicalUnits.PC:
case LexicalUnits.PT:
case LexicalUnits.PX:
case LexicalUnits.CM:
case LexicalUnits.MM:
case LexicalUnits.IN:
case LexicalUnits.MS:
result += 2;
break;
case LexicalUnits.KHZ:
case LexicalUnits.DEG:
case LexicalUnits.RAD:
result += 3;
break;
case LexicalUnits.GRAD:
result += 4;
}
return result + blankCharacters;
}
/**
* Returns the next token.
*/
protected void nextToken() throws ParseException {
try {
switch (current) {
case -1:
type = LexicalUnits.EOF;
return;
case '{':
nextChar();
type = LexicalUnits.LEFT_CURLY_BRACE;
return;
case '}':
nextChar();
type = LexicalUnits.RIGHT_CURLY_BRACE;
return;
case '=':
nextChar();
type = LexicalUnits.EQUAL;
return;
case '+':
nextChar();
type = LexicalUnits.PLUS;
return;
case ',':
nextChar();
type = LexicalUnits.COMMA;
return;
case ';':
nextChar();
type = LexicalUnits.SEMI_COLON;
return;
case '>':
nextChar();
type = LexicalUnits.PRECEDE;
return;
case '[':
nextChar();
type = LexicalUnits.LEFT_BRACKET;
return;
case ']':
nextChar();
type = LexicalUnits.RIGHT_BRACKET;
return;
case '*':
nextChar();
type = LexicalUnits.ANY;
return;
case '(':
nextChar();
type = LexicalUnits.LEFT_BRACE;
return;
case ')':
nextChar();
type = LexicalUnits.RIGHT_BRACE;
return;
case ':':
nextChar();
type = LexicalUnits.COLON;
return;
case ' ':
case '\t':
case '\r':
case '\n':
case '\f':
do {
nextChar();
} while (ScannerUtilities.isCSSSpace((char)current));
type = LexicalUnits.SPACE;
return;
case '/':
nextChar();
if (current != '*') {
type = LexicalUnits.DIVIDE;
return;
}
// Comment
nextChar();
start = position - 1;
do {
while (current != -1 && current != '*') {
nextChar();
}
do {
nextChar();
} while (current != -1 && current == '*');
} while (current != -1 && current != '/');
if (current == -1) {
throw new ParseException("eof", line, column);
}
nextChar();
type = LexicalUnits.COMMENT;
return;
case '\'': // String1
type = string1();
return;
case '"': // String2
type = string2();
return;
case '<':
nextChar();
if (current != '!') {
throw new ParseException("character", line, column);
}
nextChar();
if (current == '-') {
nextChar();
if (current == '-') {
nextChar();
type = LexicalUnits.CDO;
return;
}
}
throw new ParseException("character", line, column);
case '-':
nextChar();
if (current != '-') {
type = LexicalUnits.MINUS;
return;
}
nextChar();
if (current == '>') {
nextChar();
type = LexicalUnits.CDC;
return;
}
throw new ParseException("character", line, column);
case '|':
nextChar();
if (current == '=') {
nextChar();
type = LexicalUnits.DASHMATCH;
return;
}
throw new ParseException("character", line, column);
case '~':
nextChar();
if (current == '=') {
nextChar();
type = LexicalUnits.INCLUDES;
return;
}
throw new ParseException("character", line, column);
case '
nextChar();
if (ScannerUtilities.isCSSNameCharacter((char)current)) {
start = position - 1;
do {
nextChar();
if (current == '\\') {
nextChar();
escape();
}
} while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current));
type = LexicalUnits.HASH;
return;
}
throw new ParseException("character", line, column);
case '@':
nextChar();
switch (current) {
case 'c':
case 'C':
start = position - 1;
if (isEqualIgnoreCase(nextChar(), 'h') &&
isEqualIgnoreCase(nextChar(), 'a') &&
isEqualIgnoreCase(nextChar(), 'r') &&
isEqualIgnoreCase(nextChar(), 's') &&
isEqualIgnoreCase(nextChar(), 'e') &&
isEqualIgnoreCase(nextChar(), 't')) {
nextChar();
type = LexicalUnits.CHARSET_SYMBOL;
return;
}
break;
case 'f':
case 'F':
start = position - 1;
if (isEqualIgnoreCase(nextChar(), 'o') &&
isEqualIgnoreCase(nextChar(), 'n') &&
isEqualIgnoreCase(nextChar(), 't') &&
isEqualIgnoreCase(nextChar(), '-') &&
isEqualIgnoreCase(nextChar(), 'f') &&
isEqualIgnoreCase(nextChar(), 'a') &&
isEqualIgnoreCase(nextChar(), 'c') &&
isEqualIgnoreCase(nextChar(), 'e')) {
nextChar();
type = LexicalUnits.FONT_FACE_SYMBOL;
return;
}
break;
case 'i':
case 'I':
start = position - 1;
if (isEqualIgnoreCase(nextChar(), 'm') &&
isEqualIgnoreCase(nextChar(), 'p') &&
isEqualIgnoreCase(nextChar(), 'o') &&
isEqualIgnoreCase(nextChar(), 'r') &&
isEqualIgnoreCase(nextChar(), 't')) {
nextChar();
type = LexicalUnits.IMPORT_SYMBOL;
return;
}
break;
case 'm':
case 'M':
start = position - 1;
if (isEqualIgnoreCase(nextChar(), 'e') &&
isEqualIgnoreCase(nextChar(), 'd') &&
isEqualIgnoreCase(nextChar(), 'i') &&
isEqualIgnoreCase(nextChar(), 'a')) {
nextChar();
type = LexicalUnits.MEDIA_SYMBOL;
return;
}
break;
case 'p':
case 'P':
start = position - 1;
if (isEqualIgnoreCase(nextChar(), 'a') &&
isEqualIgnoreCase(nextChar(), 'g') &&
isEqualIgnoreCase(nextChar(), 'e')) {
nextChar();
type = LexicalUnits.PAGE_SYMBOL;
return;
}
break;
default:
if (!ScannerUtilities.isCSSIdentifierStartCharacter((char)current)) {
throw new ParseException("character", line, column);
}
start = position - 1;
}
do {
nextChar();
if (current == '\\') {
nextChar();
escape();
}
} while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current));
type = LexicalUnits.AT_KEYWORD;
return;
case '!':
do {
nextChar();
} while (current != -1 && ScannerUtilities.isCSSSpace((char)current));
if (isEqualIgnoreCase(current, 'i') &&
isEqualIgnoreCase(nextChar(), 'm') &&
isEqualIgnoreCase(nextChar(), 'p') &&
isEqualIgnoreCase(nextChar(), 'o') &&
isEqualIgnoreCase(nextChar(), 'r') &&
isEqualIgnoreCase(nextChar(), 't') &&
isEqualIgnoreCase(nextChar(), 'a') &&
isEqualIgnoreCase(nextChar(), 'n') &&
isEqualIgnoreCase(nextChar(), 't')) {
nextChar();
type = LexicalUnits.IMPORTANT_SYMBOL;
return;
}
if (current == -1) {
throw new ParseException("eof", line, column);
} else {
throw new ParseException("character", line, column);
}
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
type = number();
return;
case '.':
switch (nextChar()) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
type = dotNumber();
return;
default:
type = LexicalUnits.DOT;
return;
}
case 'u':
case 'U':
nextChar();
switch (current) {
case '+':
boolean range = false;
for (int i = 0; i < 6; i++) {
nextChar();
switch (current) {
case '?':
range = true;
break;
default:
if (range &&
!ScannerUtilities.isCSSHexadecimalCharacter((char)current)) {
throw new ParseException("character", line, column);
}
}
}
nextChar();
if (range) {
type = LexicalUnits.UNICODE_RANGE;
return;
}
if (current == '-') {
nextChar();
if (!ScannerUtilities.isCSSHexadecimalCharacter((char)current)) {
throw new ParseException("character",
line,
column);
}
nextChar();
if (!ScannerUtilities.isCSSHexadecimalCharacter((char)current)) {
type = LexicalUnits.UNICODE_RANGE;
return;
}
nextChar();
if (!ScannerUtilities.isCSSHexadecimalCharacter((char)current)) {
type = LexicalUnits.UNICODE_RANGE;
return;
}
nextChar();
if (!ScannerUtilities.isCSSHexadecimalCharacter((char)current)) {
type = LexicalUnits.UNICODE_RANGE;
return;
}
nextChar();
if (!ScannerUtilities.isCSSHexadecimalCharacter((char)current)) {
type = LexicalUnits.UNICODE_RANGE;
return;
}
nextChar();
if (!ScannerUtilities.isCSSHexadecimalCharacter((char)current)) {
type = LexicalUnits.UNICODE_RANGE;
return;
}
nextChar();
type = LexicalUnits.UNICODE_RANGE;
return;
}
case 'r':
case 'R':
nextChar();
switch (current) {
case 'l':
case 'L':
nextChar();
switch (current) {
case '(':
do {
nextChar();
} while (current != -1 &&
ScannerUtilities.isCSSSpace((char)current));
switch (current) {
case '\'':
string1();
blankCharacters += 2;
while (current != -1 &&
ScannerUtilities.isCSSSpace((char)current)) {
blankCharacters++;
nextChar();
}
if (current == -1) {
throw new ParseException("eof", line, column);
}
if (current != ')') {
throw new ParseException("character", line, column);
}
nextChar();
type = LexicalUnits.URI;
return;
case '"':
string2();
blankCharacters += 2;
while (current != -1 &&
ScannerUtilities.isCSSSpace((char)current)) {
blankCharacters++;
nextChar();
}
if (current == -1) {
throw new ParseException("eof", line, column);
}
if (current != ')') {
throw new ParseException("character", line, column);
}
nextChar();
type = LexicalUnits.URI;
return;
case ')':
throw new ParseException("character", line, column);
default:
if (!ScannerUtilities.isCSSURICharacter((char)current)) {
throw new ParseException("character", line, column);
}
start = position - 1;
do {
nextChar();
} while (current != -1 &&
ScannerUtilities.isCSSURICharacter((char)current));
blankCharacters++;
while (current != -1 &&
ScannerUtilities.isCSSSpace((char)current)) {
blankCharacters++;
nextChar();
}
if (current == -1) {
throw new ParseException("eof", line, column);
}
if (current != ')') {
throw new ParseException("character", line, column);
}
nextChar();
type = LexicalUnits.URI;
return;
}
}
}
}
while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
nextChar();
}
if (current == '(') {
nextChar();
type = LexicalUnits.FUNCTION;
return;
}
type = LexicalUnits.IDENTIFIER;
return;
default:
if (ScannerUtilities.isCSSIdentifierStartCharacter((char)current)) {
// Identifier
do {
nextChar();
if (current == '\\') {
nextChar();
escape();
}
} while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current));
if (current == '(') {
nextChar();
type = LexicalUnits.FUNCTION;
return;
}
type = LexicalUnits.IDENTIFIER;
return;
}
nextChar();
throw new ParseException("character", line, column);
}
} catch (IOException e) {
throw new ParseException(e);
}
}
/**
* Scans a single quoted string.
*/
protected int string1() throws IOException {
nextChar();
start = position - 1;
loop: for (;;) {
switch (nextChar()) {
case -1:
throw new ParseException("eof", line, column);
case '\'':
break loop;
case '"':
break;
case '\\':
switch (nextChar()) {
case '\n':
case '\f':
break;
default:
escape();
}
break;
default:
if (!ScannerUtilities.isCSSStringCharacter((char)current)) {
throw new ParseException("character", line, column);
}
}
}
nextChar();
return LexicalUnits.STRING;
}
/**
* Scans a double quoted string.
*/
protected int string2() throws IOException {
nextChar();
start = position - 1;
loop: for (;;) {
switch (nextChar()) {
case -1:
throw new ParseException("eof", line, column);
case '\'':
break;
case '"':
break loop;
case '\\':
switch (nextChar()) {
case '\n':
case '\f':
break;
default:
escape();
}
break;
default:
if (!ScannerUtilities.isCSSStringCharacter((char)current)) {
throw new ParseException("character", line, column);
}
}
}
nextChar();
return LexicalUnits.STRING;
}
/**
* Scans a number.
*/
protected int number() throws IOException {
loop: for (;;) {
switch (nextChar()) {
case '.':
switch (nextChar()) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
return dotNumber();
}
throw new ParseException("character", line, column);
default:
break loop;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
}
}
return numberUnit(true);
}
/**
* Scans the decimal part of a number.
*/
protected int dotNumber() throws IOException {
loop: for (;;) {
switch (nextChar()) {
default:
break loop;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
}
}
return numberUnit(false);
}
/**
* Scans the unit of a number.
*/
protected int numberUnit(boolean integer) throws IOException {
switch (current) {
case '%':
nextChar();
return LexicalUnits.PERCENTAGE;
case 'c':
case 'C':
switch(nextChar()) {
case 'm':
case 'M':
nextChar();
if (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
do {
nextChar();
} while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current));
return LexicalUnits.DIMENSION;
}
return LexicalUnits.CM;
default:
while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
nextChar();
}
return LexicalUnits.DIMENSION;
}
case 'd':
case 'D':
switch(nextChar()) {
case 'e':
case 'E':
switch(nextChar()) {
case 'g':
case 'G':
nextChar();
if (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
do {
nextChar();
} while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current));
return LexicalUnits.DIMENSION;
}
return LexicalUnits.DEG;
}
default:
while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
nextChar();
}
return LexicalUnits.DIMENSION;
}
case 'e':
case 'E':
switch(nextChar()) {
case 'm':
case 'M':
nextChar();
if (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
do {
nextChar();
} while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current));
return LexicalUnits.DIMENSION;
}
return LexicalUnits.EM;
case 'x':
case 'X':
nextChar();
if (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
do {
nextChar();
} while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current));
return LexicalUnits.DIMENSION;
}
return LexicalUnits.EX;
default:
while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
nextChar();
}
return LexicalUnits.DIMENSION;
}
case 'g':
case 'G':
switch(nextChar()) {
case 'r':
case 'R':
switch(nextChar()) {
case 'a':
case 'A':
switch(nextChar()) {
case 'd':
case 'D':
nextChar();
if (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
do {
nextChar();
} while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current));
return LexicalUnits.DIMENSION;
}
return LexicalUnits.GRAD;
}
}
default:
while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
nextChar();
}
return LexicalUnits.DIMENSION;
}
case 'h':
case 'H':
nextChar();
switch(current) {
case 'z':
case 'Z':
nextChar();
if (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
do {
nextChar();
} while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current));
return LexicalUnits.DIMENSION;
}
return LexicalUnits.HZ;
default:
while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
nextChar();
}
return LexicalUnits.DIMENSION;
}
case 'i':
case 'I':
switch(nextChar()) {
case 'n':
case 'N':
nextChar();
if (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
do {
nextChar();
} while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current));
return LexicalUnits.DIMENSION;
}
return LexicalUnits.IN;
default:
while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
nextChar();
}
return LexicalUnits.DIMENSION;
}
case 'k':
case 'K':
switch(nextChar()) {
case 'h':
case 'H':
switch(nextChar()) {
case 'z':
case 'Z':
nextChar();
if (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
do {
nextChar();
} while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current));
return LexicalUnits.DIMENSION;
}
return LexicalUnits.KHZ;
}
default:
while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
nextChar();
}
return LexicalUnits.DIMENSION;
}
case 'm':
case 'M':
switch(nextChar()) {
case 'm':
case 'M':
nextChar();
if (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
do {
nextChar();
} while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current));
return LexicalUnits.DIMENSION;
}
return LexicalUnits.MM;
case 's':
case 'S':
nextChar();
if (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
do {
nextChar();
} while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current));
return LexicalUnits.DIMENSION;
}
return LexicalUnits.MS;
default:
while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
nextChar();
}
return LexicalUnits.DIMENSION;
}
case 'p':
case 'P':
switch(nextChar()) {
case 'c':
case 'C':
nextChar();
if (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
do {
nextChar();
} while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current));
return LexicalUnits.DIMENSION;
}
return LexicalUnits.PC;
case 't':
case 'T':
nextChar();
if (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
do {
nextChar();
} while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current));
return LexicalUnits.DIMENSION;
}
return LexicalUnits.PT;
case 'x':
case 'X':
nextChar();
if (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
do {
nextChar();
} while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current));
return LexicalUnits.DIMENSION;
}
return LexicalUnits.PX;
default:
while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
nextChar();
}
return LexicalUnits.DIMENSION;
}
case 'r':
case 'R':
switch(nextChar()) {
case 'a':
case 'A':
switch(nextChar()) {
case 'd':
case 'D':
nextChar();
if (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
do {
nextChar();
} while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current));
return LexicalUnits.DIMENSION;
}
return LexicalUnits.RAD;
}
default:
while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current)) {
nextChar();
}
return LexicalUnits.DIMENSION;
}
case 's':
case 'S':
nextChar();
return LexicalUnits.S;
default:
if (current != -1 &&
ScannerUtilities.isCSSIdentifierStartCharacter((char)current)) {
do {
nextChar();
} while (current != -1 &&
ScannerUtilities.isCSSNameCharacter((char)current));
return LexicalUnits.DIMENSION;
}
return (integer) ? LexicalUnits.INTEGER : LexicalUnits.REAL;
}
}
/**
* Scans an escape sequence, if one.
*/
protected void escape() throws IOException {
if (ScannerUtilities.isCSSHexadecimalCharacter((char)current)) {
nextChar();
if (!ScannerUtilities.isCSSHexadecimalCharacter((char)current)) {
if (ScannerUtilities.isCSSSpace((char)current)) {
nextChar();
}
return;
}
nextChar();
if (!ScannerUtilities.isCSSHexadecimalCharacter((char)current)) {
if (ScannerUtilities.isCSSSpace((char)current)) {
nextChar();
}
return;
}
nextChar();
if (!ScannerUtilities.isCSSHexadecimalCharacter((char)current)) {
if (ScannerUtilities.isCSSSpace((char)current)) {
nextChar();
}
return;
}
nextChar();
if (!ScannerUtilities.isCSSHexadecimalCharacter((char)current)) {
if (ScannerUtilities.isCSSSpace((char)current)) {
nextChar();
}
return;
}
nextChar();
if (!ScannerUtilities.isCSSHexadecimalCharacter((char)current)) {
if (ScannerUtilities.isCSSSpace((char)current)) {
nextChar();
}
return;
}
}
if ((current >= ' ' && current <= '~') || current >= 128) {
nextChar();
return;
}
throw new ParseException("character", line, column);
}
/**
* Compares the given int with the given character, ignoring case.
*/
protected static boolean isEqualIgnoreCase(int i, char c) {
return (i == -1) ? false : Character.toLowerCase((char)i) == c;
}
/**
* Sets the value of the current char to the next character or -1 if the
* end of stream has been reached.
*/
protected int nextChar() throws IOException {
if ((readPosition == readCount) && (!fillReadBuffer())) {
return current = -1;
}
current = readBuffer[readPosition++];
if (current != 10) {
column++;
} else {
line++;
column = 1;
}
if (position == buffer.length) {
char[] t = new char[position * 3 / 2];
System.arraycopy(buffer, 0, t, 0, position);
buffer = t;
}
return buffer[position++] = (char)current;
}
protected final boolean fillReadBuffer() throws IOException {
if (readCount != 0) {
if (readPosition == readCount) {
readBuffer[0] = readBuffer[readCount-1];
readCount=readPosition=1;
} else {
// we keep the last char in our readBuffer.
System.arraycopy(readBuffer, readPosition-1, readBuffer, 0,
readCount-readPosition+1);
readCount = (readCount-readPosition)+1;
readPosition = 1;
}
}
// No reader so can't extend...
if (reader == null)
return (readCount != readPosition);
// remember where the fill starts...
int src=readCount-1;
if (src < 0) src = 0;
// Refill the readBuffer...
int read = reader.read(readBuffer, readCount,
readBuffer.length-readCount);
if (read == -1)
return (readCount != readPosition);
readCount+=read; // add in chars read.
collapseCRNL(src); // Now collapse cr/nl...
return (readCount != readPosition);
}
protected final void collapseCRNL(int src) {
// Now collapse cr/nl...
while (src<readCount) {
if (readBuffer[src] != 13) {
src++;
} else {
readBuffer[src] = 10;
src++;
if (src>=readCount) break;
if (readBuffer[src] == 10) {
// We now need to collapse some of the chars to
// eliminate cr/nl pairs. This is where we do it...
int dst = src; // start writing where this 10 is
src++; // skip reading this 10.
while (src<readCount) {
if (readBuffer[src] == 13) {
readBuffer[dst++] = 10;
src++;
if (src>=readCount) break;
if (readBuffer[src] == 10) {
src++;
}
continue;
}
readBuffer[dst++] = readBuffer[src++];
}
readCount = dst;
break;
}
}
}
}
} |
package FlightScheduler;
// INPUT.JAVA
// Input reader for Lab 4b airport and flight data
// To read all the information necessary for this lab:
// (1) Create an object (say, "input") of type Input.
// (2) Call input.readAirports(<airportFileName>)
// (3) Call input.readFlights(<flightFileName>)
// Note that you *must* do (3) after (2).
// If all goes well, you will then have access to
// * input.airports -- an array of Airport objects
// * input.flights -- an array of Flight objects
// * input.airportMap -- a HashMap mapping airport codes to the corresponding Airport objects
import java.util.*;
class Input {
// Airport information
class Airport {
public String name; // name of airport (3-letter code)
public int offset; // offset of local time from GMT (in minutes)
public int id; // convenient integer identifier
}
// Flight information
// NB: all times are GMT, in minutes since midnight
class Flight {
public String name; // flight name
public Airport startAirport, endAirport; // flight termini
public int startTime, endTime; // departure and arrival times
}
// array of all airports read from input
public Airport airports[];
// array of all flights read from input
public Flight flights[];
// mapping from airport codes (strings) to Airport objects
public HashMap<String,Airport> airportMap;
// constructor
public Input()
{
airportMap = new HashMap<String,Airport>();
}
// readAirports()
// Read the airport file
public void readAirports(String filename)
{
FileParser fp = new FileParser(filename);
// hold the airports as they are read
ArrayList<Airport> aplist = new ArrayList<Airport>();
while (!fp.isEof())
{
Airport ap = new Airport();
ap.name = fp.readWord();
ap.offset = (fp.readInt() / 100) * 60;
if (!fp.isEof())
{
// crete mapping from names to objects
airportMap.put(ap.name, ap);
aplist.add(ap);
}
}
airports = new Airport [aplist.size()];
aplist.toArray(airports);
}
// readFlights()
// read the flight file
public void readFlights(String filename)
{
FileParser fp = new FileParser(filename);
// hold the flights as they are read
ArrayList<Flight> fllist = new ArrayList<Flight>();
// read the flights and store their times in GMT
while (!fp.isEof())
{
Flight fl = new Flight();
String airline;
int flightno;
airline = fp.readWord();
flightno = fp.readInt();
fl.name = airline + "-" + flightno;
if (fp.isEof())
break;
String code;
int tm;
String ampm;
code = fp.readWord();
fl.startAirport = airportMap.get(code);
tm = fp.readInt();
ampm = fp.readWord();
fl.startTime = toTime(tm, ampm, fl.startAirport.offset);
code = fp.readWord();
fl.endAirport = airportMap.get(code);
tm = fp.readInt();
ampm = fp.readWord();
fl.endTime = toTime(tm, ampm, fl.endAirport.offset);
fllist.add(fl);
}
flights = new Flight [fllist.size()];
fllist.toArray(flights);
}
// toTime()
// convert raw time value and AM/PM in local time, to minutes
// since midnight in GMT, using supplied offset from GMT.
int toTime(int timeRaw, String ampm, int offset)
{
int hour = (timeRaw / 100) % 12;
int minute = timeRaw % 100;
boolean isPM = (ampm.charAt(0) == 'P');
int minutes = hour * 60 + minute;
if (isPM) minutes += 12 * 60;
int finalTime = (minutes - offset + 24 * 60) % (24 * 60);
return finalTime;
}
} |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.ArrayList;
import javax.swing.JPanel;
import javax.swing.text.StyledEditorKit.ForegroundAction;
import org.newdawn.slick.Color;
import org.newdawn.slick.Image;
import com.google.gson.Gson;
import com.sun.corba.se.spi.servicecontext.SendingContextServiceContext;
import com.sun.xml.internal.messaging.saaj.soap.ver1_1.Message1_1Impl;
import com.sun.xml.internal.ws.api.model.wsdl.editable.EditableWSDLBoundFault;
public class main extends JPanel {
static Board b1;
public static Train t;
public static Stack t2;
public static Stack t6;
public static Stack t8;
public static Connection t9;
public static PlayerPiece t10;
public static Card m1;
public static Town townA,townB;
public static Card missionCard;
public static ArrayList<Integer> arrayTest;
public static Town tempCityB, tempCityA;
public static Card tempCard;
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
main client = new main();
client.run();
}
public void run() throws Exception {
Socket Sock = new Socket("172.20.10.2", 2222);
PrintStream ps = new PrintStream(Sock.getOutputStream());
String activator = new String("1");
b1 = new Board(4);
t = new Train(null);
t.decrease(3);
//t2 = new Stack(null);
//t3 = new TrainCardStack(null);
//t4 = new DisplayedTrainStack(null);
//t5 = new HandMissionStack(5);
//t6 = new Stack(null);
//t7 = new TrainTrashStack(5);
//t8 = new Stack(5);
//t9 = new Connection(null, b1.towns[1], b1.towns[2], 5, 6);
arrayTest = new ArrayList<Integer>();
arrayTest.add(2);
arrayTest.add(5);
arrayTest.add(100);
Gson serializer = new Gson();
//Gson serializer2 = new GsonBuilder().create();
String json = serializer.toJson(t);
String json1 = serializer.toJson(t2);
String json5 = serializer.toJson(t6);
String json7 = serializer.toJson(t8);
String json8 = serializer.toJson(t9);
String json9 = serializer.toJson(t10);
String jsonTest = serializer.toJson(arrayTest);
String missionTest = serializer.toJson(new MissionCard(new Town(b1.towns[1].getName(), 4, b1.connections.get(1).getTownA().getxPos(), b1.towns[1].getyPos()), new Town(b1.towns[4].getName(), 6, b1.towns[4].getxPos(), b1.towns[4].getxPos()), 2));
//String townTest = serializer.toJson(new Town(b1.towns[1].getName(), 5, 74, 499));
//jsonTest2=null;
/* String jsonTest2 = serializer.toJson(
new Connection(
new CustomColor("red",
2,
new Color(255,0,0)),
new Town("piK",
2,
3,
4),
new Town("fisse",
5,
6,
7),
8,
9,1));*/
String jsontest2 = null;
String[] jsontest3 = new String[b1.connections.size()];
//sending the connections into a array of Strings.
for (int i=0; i<b1.connections.size(); i++){
String temp = serializer.toJson(
new Connection(
new CustomColor(b1.connections.get(i).getColor().getColorName(),
b1.connections.get(i).getColor().getColorNum(),
b1.connections.get(i).getColor().getColor()),
new Town(b1.connections.get(i).getTownA().getName(),
b1.connections.get(i).getTownA().getAmountOfConnections(),
b1.connections.get(i).getTownA().getxPos(),
b1.connections.get(i).getTownA().getyPos()),
new Town(b1.connections.get(i).getTownB().getName(),
b1.connections.get(i).getTownB().getAmountOfConnections(),
b1.connections.get(i).getTownB().getxPos(),
b1.connections.get(i).getTownB().getyPos()),
b1.connections.get(i).getLength(),
b1.connections.get(i).getPoint(),1));
jsontest3[i]=temp;
}
//Sending all the traincard from the traincardstack to the arraystring
String[] jsonTCS = new String[b1.arrayOfTrainCards.size()];
System.out.println(b1.arrayOfTrainCards.size());
for (int i =0; i<b1.arrayOfTrainCards.size(); i++)
{
String temp = serializer.toJson(b1.arrayOfTrainCards.get(i));
jsonTCS[i]=temp;
}
System.out.println(jsonTCS[4]);
//DisplayedTrainStack to JSON string
String[] jsonDTS = new String[b1.displayedTrainStack.size()];
for (int i=0; i<b1.displayedTrainStack.size(); i++)
{
String temp = serializer.toJson(b1.displayedTrainStack.get(i));
jsonDTS[i] = temp;
}
// PlayerPiece to JSON string
String[] jsonPlP = new String[b1.players.length];
for (int i = 0; i < b1.players.length; i++) {
String temp = serializer.toJson(b1.players[i]);
jsonPlP[i] = temp;
}
String[] cStringsIsTaken = new String[b1.connections.size()];
for (int i=0; i<b1.connections.size();i++)
{
String temp = serializer.toJson(0+i);
cStringsIsTaken[i]=temp;
}
/*
//DisplayedMissionStack to JSON string
String[] jsonMCS = new String[b1.displayedMissionStack.size()];;
for (int i=0; i<b1.displayedMissionStack.size(); i++)
{
String temp = serializer.toJson(b1.displayedMissionStack.get(i));
jsonMCS[i] = temp;
}
*/
//Trains to JSON
//String[] jsonTra = null;
//Player to Json
//TrashTrainCard to JSON
//TrashMissionCard to JSON
//MissionCards on hand to JSON
//TrainCards on hand to JSON
//This is where we start sending the JSONS
ps.println(activator +"\n");
//Sending all the connections.
for (int i=0; i<b1.connections.size();i++)
{
ps.println(jsontest3[i]);
//ps.println(activator + "\n" + jsontest3[i] +/* "\n" + json1 + "\n"+ json2 + "\n" +json3 + "\n"+json4 + "\n"+json5 + "\n"+json6 + "\n"+json7 +*/ "\n"+ jsontest3[5] + "\n"+json9 + "\n");
}
//sending the arrayoftraincards.
for (int i =0; i<b1.arrayOfTrainCards.size();i++)
{
ps.println(jsonTCS[i]);
}
//Sending displayedTrainStack
for (int i=0; i<b1.displayedTrainStack.size(); i++)
{
ps.println(jsonDTS[i]);
}
// Sending the playerpieces
for (int i = 0; i < b1.players.length; i++) {
ps.println(jsonPlP[i]);
}
for (int i=0; i<b1.connections.size();i++)
{
ps.println(0+i);
}
/*
* //Sending the missionCardStack for (int i=0;
* i<b1.displayedMissionStack.size(); i++) { ps.println(jsonMCS[i]); }
*
*/
InputStreamReader ir = new InputStreamReader(Sock.getInputStream());
BufferedReader br = new BufferedReader(ir);
while (true) {
String Message = br.readLine();
System.out.println(Message);
}
}
}
// Commenting this out and trying with an alternative |
public class Philosopher implements Runnable {
private Fork leftFork;
private Fork rightFork;
private String name;
private Plate plate;
public Philosopher(Fork leftFork, Fork rightFork, String name, Plate plate) {
this.leftFork = leftFork;
this.rightFork = rightFork;
this.name = name;
this.plate = plate;
}
private void eat() throws InterruptedException {
System.out.println(name.concat(" Eating"));
plate.takeFood();
}
private void think() throws InterruptedException {
Thread.sleep(100);
}
@Override
public void run() {
try {
while (plate.hasFood()) {
if (leftFork.pickUp(10)) {
if (rightFork.pickUp(10)) {
eat();
rightFork.putDown();
leftFork.putDown();
} else {
leftFork.putDown();
}
}
think();
}
} catch (InterruptedException ex) {
}
}
} |
package ru.job4j.taskchapter2;
import java.util.ArrayList;
import java.util.Arrays;
public class Tracker {
//Item[] list = new Item[100];
private ArrayList<Item> items = new ArrayList<>();
private int index = 0;
public Item add(Item item) {
for (int i = 0; i < items.size(); i++) {
if (this.items.get(i) == null) {
this.items.add(i, item);
index++;
break;
}
}
for (int i = 0; i < this.items.size() ; i++) {
System.out.println("cikl " + this.items.get(i));
}
System.out.println("sout " + this.items);
System.out.println("size " + this.items.size());
return item;
}
public void update(Item item) {
for (int i = 0; i < items.size(); i++) {
if (this.items.get(i) != null && this.items.get(i).getId().equals(item.getId())) {
this.items.add(i, item);
System.out.println(this.items.get(i));
break;
}
}
}
public void delete(Item item) {
for (int i = 0; i < this.index; i++) {
Item it = this.items.get(i);
if (it != null && it.getId().equals(item.getId())) {
System.arraycopy(this.items, i + 1, this.items, i, index
break;
}
}
}
public ArrayList<Item> findAll() {
for (int i = 0; i < this.items.size(); i++) {
System.out.println("items " + this.items.get(i));
}
return this.items;
}
/* public Item[] findAll2() {
return Arrays.copyOf(this.items, index);
}*/
public ArrayList<Item> findByName(String key) {
int count = 1;
ArrayList<Item> result = new ArrayList<>();
for (int i = 0; i < index; i++) {
if (this.items.get(i) != null
&& this.items.get(i).getName().equals(key)) {
if (result.get(count - 1) != null) {
ArrayList<Item> tmp = result;
result = new ArrayList<Item>();
System.arraycopy(tmp, 0, result, 0, count - 1);
}
result.add((count - 1), this.items.get(i));
}
}
return result;
}
// for (int i = 0; i < this.items.length; i++) {
// if (this.items[i] != null && this.items[i].getId().equals(id)) {
// return this.items[i];
// break;
// return null;
public Item findById(String id) {
Item copyitem = new Item();
for (int i = 0; i < this.items.size(); i++) {
if (this.items.get(i) != null && this.items.get(i).getId().equals(id)) {
copyitem = this.items.get(i);
} else {
copyitem = null;
}
break;
}
return copyitem;
}
public ArrayList<Item> getItems() {
return items;
}
} |
package com.topcat.npclib.nms;
import java.io.IOException;
import java.lang.reflect.Field;
import net.minecraft.server.v1_5_R2.Connection;
import net.minecraft.server.v1_5_R2.MinecraftServer;
import net.minecraft.server.v1_5_R2.NetworkManager;
import net.minecraft.server.v1_5_R2.Packet;
/**
*
* @author martin
*/
public class NPCNetworkManager extends NetworkManager {
NPCEntity npc;
public NPCNetworkManager() throws IOException {
//ConsoleLogManager, when declared in this way, creates 2 new files every load of plugin
super(MinecraftServer.getServer().getLogger(), new NullSocket(), "NPC Manager", new Connection() {
@Override
public boolean a() {
return true;
}
}, null);
try {
Field f = NetworkManager.class.getDeclaredField("n");
f.setAccessible(true);
f.set(this, false);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void a(Connection nethandler) {
}
@Override
public void queue(Packet packet) {
}
@Override
public void a(String s, Object... aobject) {
}
@Override
public void a() {
}
} |
package ru.job4j.generics;
/**
* The type Simple array.
*
* @param <E> the type parameter
*/
public class SimpleArray<E> {
/**
* Array of any type objects.
*/
private Object[] objects;
/**
* Index of addition.
*/
private int lastIndex = 0;
/**
* Instantiates a new Simple array.
*
* @param size the size
*/
public SimpleArray(int size) {
this.objects = new Object[size];
}
/**
* Check if index is correct.
* @param position the checked position
* @return isCheckedIndex
*/
private boolean checkIndex(int position) {
return !(position > lastIndex);
}
/**
* Add.
*
* @param value the value
*/
public void add(E value) {
if (objects.length < lastIndex + 1) {
throw new IndexOutOfBoundsException();
}
this.objects[lastIndex++] = value;
}
/**
* Get item by index.
*
* @param position the position
* @return the item
*/
public E get(int position) {
if (!checkIndex(position)) {
throw new IndexOutOfBoundsException();
}
return (E) this.objects[position];
}
/**
* Update boolean.
*
* @param value the value
* @param position the position
* @return the boolean
*/
public boolean update(E value, int position) {
boolean isUpdated = false;
if (checkIndex(position)) {
this.objects[position] = value;
isUpdated = true;
}
return isUpdated;
}
/**
* Delete boolean.
*
* @param position the position
* @return the boolean
*/
public boolean delete(int position) {
boolean isDeleted = false;
if (checkIndex(position)) {
objects[position] = null;
isDeleted = true;
}
return isDeleted;
}
/**
* Gets last index.
*
* @return the last index
*/
public int getLastIndex() {
return lastIndex;
}
} |
package io.skygear.plugins.chat;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IllegalFormatException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.skygear.skygear.Record;
/**
* The Conversation model for the Chat Plugin.
*/
public class Conversation {
static final String TYPE_KEY = "conversation";
static final String TITLE_KEY = "title";
static final String ADMIN_IDS_KEY = "admin_ids";
static final String PARTICIPANT_IDS_KEY = "participant_ids";
static final String DISTINCT_BY_PARTICIPANTS_KEY = "distinct_by_participant";
static final String METADATA_KEY = "metadata";
final Record record;
private Set<String> adminIds;
private Set<String> participantIds;
/**
* Creates a Compatible Skygear Record
*
* @param participantIds the participant ids
* @param title the title
* @param metadata the metadata
* @param options the options
* @return the record
*/
static Record newRecord(final Set<String> participantIds,
@Nullable final String title,
@Nullable final Map<String, Object> metadata,
@Nullable final Map<OptionKey, Object> options) {
Record record = new Record(TYPE_KEY);
// set participant ids
JSONArray participantIdArray = new JSONArray(participantIds);
record.set(PARTICIPANT_IDS_KEY, participantIdArray);
// set title (allow null)
if (title != null && title.trim().length() != 0) {
record.set(TITLE_KEY, title.trim());
}
if (metadata != null) {
record.set(METADATA_KEY, new JSONObject(metadata));
}
if (options != null) {
Object adminIds = options.get(OptionKey.ADMIN_IDS);
if (adminIds != null) {
// set admin ids
JSONArray adminIdArray = new JSONArray((Collection<String>) adminIds);
record.set(ADMIN_IDS_KEY, adminIdArray);
}
// set distinctByParticipants
Object distinctByParticipants = options.get(OptionKey.DISTINCT_BY_PARTICIPANTS);
if (distinctByParticipants != null && (boolean)distinctByParticipants) {
record.set(DISTINCT_BY_PARTICIPANTS_KEY, true);
}
}
return record;
}
/**
* Instantiates a Conversation from a Skygear Record.
*
* @param record the record
*/
Conversation(final Record record) {
this.record = record;
JSONArray adminIds = (JSONArray) record.get(ADMIN_IDS_KEY);
if (adminIds != null) {
Set<String> ids = new HashSet<>();
for (int i = 0; i < adminIds.length(); i++) {
String id = adminIds.optString(i);
if (id != null) {
ids.add(id);
}
}
this.adminIds = ids;
}
JSONArray participantIds = (JSONArray) record.get(PARTICIPANT_IDS_KEY);
if (participantIds != null) {
Set<String> ids = new HashSet<>();
for (int i = 0; i < participantIds.length(); i++) {
String id = participantIds.optString(i);
if (id != null) {
ids.add(id);
}
}
this.participantIds = ids;
}
}
/**
* Gets id.
*
* @return the id
*/
@NonNull
public String getId() {
return record.getId();
}
/**
* Gets title.
*
* @return the title
*/
@Nullable
public String getTitle() {
return (String) record.get(TITLE_KEY);
}
/**
* Gets admin ids.
*
* @return the admin ids
*/
@Nullable
public Set<String> getAdminIds() {
return adminIds;
}
/**
* Gets participant ids.
*
* @return the participant ids
*/
@Nullable
public Set<String> getParticipantIds() {
return participantIds;
}
/**
* Gets metadata.
*
* @return the metadata
*/
public Map<String, Object> getMetadata() {
Object metadata = this.record.get(METADATA_KEY);
if (metadata == null) {
return null;
}
if ((metadata instanceof JSONObject)) {
JSONObject metadataObject = (JSONObject) metadata;
Iterator<String> keys = metadataObject.keys();
Map<String, Object> metadataMap = new HashMap<>();
while (keys.hasNext()) {
String eachKey = keys.next();
try {
Object eachValue = metadataObject.get(eachKey);
metadataMap.put(eachKey, eachValue);
} catch (JSONException e) {
throw new IllegalArgumentException(
String.format("Missing value for key %s", eachKey)
);
}
}
return metadataMap;
}
throw new IllegalArgumentException("Metadata is in incorrect format");
}
/**
* Whether the conversation is distinct by participants.
*
* @return the boolean
*/
public boolean isDistinctByParticipants() {
return (boolean) record.get(DISTINCT_BY_PARTICIPANTS_KEY);
}
/**
* Serializes to a JSON Object
*
* @return the JSON object
*/
@Nullable
public JSONObject toJson() {
return record.toJson();
}
/**
* Deserializes from a JSON Object
*
* @param jsonObject the JSON object
* @return the conversation
* @throws JSONException the JSON exception
*/
public static Conversation fromJson(JSONObject jsonObject) throws JSONException {
return new Conversation(Record.fromJson(jsonObject));
}
/**
* The Option Key for Conversation Creation.
*/
public enum OptionKey {
ADMIN_IDS("admin_ids"),
DISTINCT_BY_PARTICIPANTS("distinct_by_participant");
private final String value;
OptionKey(String value) {
this.value = value;
}
/**
* Gets the value.
*
* @return the value
*/
String getValue() {
return this.value;
}
}
} |
package org.openqa.selenium.chrome;
import org.openqa.selenium.Platform;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.Proxy.ProxyType;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class ChromeBinary {
private static final int BACKOFF_INTERVAL = 2500;
private static int linearBackoffCoefficient = 1;
private final ChromeProfile profile;
private final ChromeExtension extension;
Process chromeProcess = null;
/**
* Creates a new instance for managing an instance of Chrome using the given
* {@code profile} and {@code extension}.
*
* @param profile The Chrome profile to use.
* @param extension The extension to launch Chrome with.
*/
public ChromeBinary(ChromeProfile profile, ChromeExtension extension) {
this.profile = profile;
this.extension = extension;
}
/**
* Starts the Chrome process for WebDriver.
* Assumes the passed directories exist.
* @param serverUrl URL from which commands should be requested
* @throws IOException wrapped in WebDriverException if process couldn't be
* started.
*/
public void start(String serverUrl) throws IOException {
try {
List<String> commandline = getCommandline(serverUrl);
chromeProcess = new ProcessBuilder(commandline)
.start();
} catch (IOException e) {
throw new WebDriverException(e);
}
try {
Thread.sleep(BACKOFF_INTERVAL * linearBackoffCoefficient);
} catch (InterruptedException e) {
//Nothing sane to do here
}
}
// Visible for testing.
public List<String> getCommandline(String serverUrl) throws IOException {
ArrayList<String> commandline = new ArrayList<String>(Arrays.asList(
getChromeFile(),
"--user-data-dir=" + profile.getDirectory().getAbsolutePath(),
"--load-extension=" + extension.getDirectory().getAbsolutePath(),
"--activate-on-launch",
"--homepage=about:blank",
"--no-first-run",
"--disable-hang-monitor",
"--disable-popup-blocking",
"--disable-prompt-on-repost",
"--no-default-browser-check"
));
appendProxyArguments(commandline)
.add(serverUrl);
return commandline;
}
private ArrayList<String> appendProxyArguments(ArrayList<String> commandline) {
Proxy proxy = profile.getProxy();
if (proxy == null) {
return commandline;
}
if (proxy.getProxyAutoconfigUrl() != null) {
commandline.add("--proxy-pac-url=" + proxy.getProxyAutoconfigUrl());
} else if (proxy.getHttpProxy() != null) {
commandline.add("--proxy-server=" + proxy.getHttpProxy());
} else if (proxy.isAutodetect()) {
commandline.add("--proxy-auto-detect");
} else if (proxy.getProxyType() == ProxyType.DIRECT) {
commandline.add("--no-proxy-server");
} else if (proxy.getProxyType() != ProxyType.SYSTEM) {
throw new IllegalStateException("Unsupported proxy setting");
}
return commandline;
}
public void kill() {
if (chromeProcess != null) {
chromeProcess.destroy();
chromeProcess = null;
}
}
public void incrementBackoffBy(int diff) {
linearBackoffCoefficient += diff;
}
/**
* Locates the Chrome executable on the current platform.
* First looks in the webdriver.chrome.bin property, then searches
* through the default expected locations.
* @return chrome.exe
* @throws IOException if file could not be found/accessed
*/
protected String getChromeFile() throws IOException {
String chromeFileString = System.getProperty("webdriver.chrome.bin");
if (chromeFileString == null) {
if (Platform.getCurrent().is(Platform.WINDOWS)) {
try {
chromeFileString = getWindowsLocation();
} catch (Exception e) {
chromeFileString = null;
}
} else if (Platform.getCurrent().is(Platform.UNIX)) {
chromeFileString = "/usr/bin/google-chrome";
} else if (Platform.getCurrent().is(Platform.MAC)) {
String[] paths = new String[] {
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/Users/" + System.getProperty("user.name") +
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"};
for (String path : paths) {
File binary = new File(path);
if (binary.exists()) {
chromeFileString = binary.getCanonicalFile().getAbsoluteFile().toString();
break;
}
}
} else {
throw new WebDriverException("Unsupported operating system. " +
"Could not locate Chrome. Set webdriver.chrome.bin");
}
if (chromeFileString == null ||
!new File(chromeFileString.toString()).exists()) {
throw new WebDriverException("Couldn't locate Chrome. " +
"Set webdriver.chrome.bin");
}
}
return chromeFileString;
}
protected static final String getWindowsLocation() throws Exception {
//TODO: Promote org.openqa.selenium.server.browserlaunchers.WindowsUtils
//to common and reuse that to read the registry
if (!Platform.WINDOWS.is(Platform.getCurrent())) {
throw new UnsupportedOperationException("Cannot get registry value on non-Windows systems");
}
Process process = Runtime.getRuntime().exec(
"reg query \"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe\" /v \"\"");
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
process.waitFor();
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(" ")) {
String[] tokens = line.split("REG_SZ");
return tokens[tokens.length - 1].trim();
}
}
throw new Exception("Couldn't read registry value");
}
} |
// Level.java
package ed.log;
import ed.js.*;
import ed.js.func.*;
import ed.js.engine.*;
public enum Level {
DEBUG_7 , DEBUG_6 , DEBUG_5 , DEBUG_4 , DEBUG_3 , DEBUG_2 , DEBUG_1 ,
DEBUG , INFO , WARN , ERROR , FATAL ;
public static Level forDebugId( int id ){
int idx = ( -1 * id ) + DEBUG_LEVELS;
if ( idx < 0 )
idx = 0;
if ( idx >= LEVELS.length )
idx = LEVELS.length - 1;
return LEVELS[ idx ];
}
public static Level forId( int id ){
return LEVELS[ id + DEBUG_LEVELS ];
}
public static Level forName( String name ){
if ( name.equalsIgnoreCase( "debug" ) )
return DEBUG;
if ( name.equalsIgnoreCase( "info" ) )
return INFO;
if ( name.equalsIgnoreCase( "warn" ) )
return WARN;
if ( name.equalsIgnoreCase( "error" ) )
return ERROR;
if ( name.equalsIgnoreCase( "fatal" ) )
return FATAL;
throw new RuntimeException( "unknown level : " + name );
}
static final JSObject me = new JSObjectBase();
static final Level[] LEVELS;
static final int DEBUG_LEVELS;
static {
me.set( "DEBUG" , DEBUG );
me.set( "INFO" , INFO );
me.set( "WARN" , WARN );
me.set( "ERROR" , ERROR );
me.set( "FATAL" , FATAL );
me.set( "ALL" , DEBUG );
LEVELS = Level.values();
int debug = 0;
for ( int i=0; i<LEVELS.length; i++ )
if ( LEVELS[i].name().equalsIgnoreCase( "info" ) )
debug = i;
DEBUG_LEVELS = debug;
}
} |
package edu.cmu.lti.bic.sbs;
public final class Setting {
public static final boolean LOCAL_MODE = false;
} |
package pkApp;
import java.io.IOException;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Phone extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
process(req,resp);
}
private void process(HttpServletRequest req,HttpServletResponse resp)
{
String sPhoneNum=(String)req.getParameter("num");
try
{
if(sPhoneNum==null)
{
resp.getWriter().println("Welcome to Pratima Phone app please provide phone number");
}
else
{
String sPageNum=(String)req.getParameter("page");
if(sPageNum==null)
{
sPageNum=new String("1");
}
//resp.getWriter().println("Welcome to Pratima Phone app");
PhoneCombGen phoneComb= new PhoneCombGen();
Vector<String> list=phoneComb.generate(sPhoneNum);
genHtml(req,resp,list,sPageNum);
}
}
catch(Exception e)
{
}
}
private void genHtml(HttpServletRequest req,HttpServletResponse resp,Vector<String> list,String sPageNum)
{
String sPhoneNum=(String)req.getParameter("num");
int nPage=0;
String sPageToken="";
try
{
String[] sPageTokens=sPageNum.split("-");
if(sPageTokens.length==2)
{
nPage=Integer.parseInt(sPageTokens[0]);
sPageToken=sPageTokens[1];
}
else
nPage=Integer.parseInt(sPageNum);
}
catch(Exception e)
{
nPage=0;
}
//Each page contains 20 data
int nCount=20;
StringBuilder sb=new StringBuilder();
sb.append("<html>");
sb.append("<head>");
sb.append("<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>");
sb.append(" <script> "
+ "$(document).ready(function(){ $(\"button\").click(function(){ "
+ "var phoneNum="+sPhoneNum+";"
+ "var pageNum=$(this).val();"
+ "var url=\"application_phone?num=\" + phoneNum+\"&page=\"+pageNum;"
+ "$('#result').load(url);});});");
sb.append("</script></head>");
sb.append("<body>");
int nStart=(nPage-1)*nCount;
if(nStart==0) nStart=1;
int nComb=list.size()-1;
sb.append("<div id=\"result\">");
sb.append("Total number of combinations: "+ nComb+"<br>");
sb.append("<table>");
int nCountTracker=0;
int idx=0;
for(idx=nStart;idx<list.size();idx++)
{
if(nCountTracker>=nCount) break;
String s=list.elementAt(idx);
sb.append("<tr>");
sb.append("<td>");
sb.append(s);
sb.append("</td>");
sb.append("</tr>");
nCountTracker++;
}
//Add Pagination Logic
float fTotal=list.size();
sb.append("<tr>");
sb.append("<td>");
sb.append("  ");
sb.append("</td>");
sb.append("</tr>");
fTotal/=nCount;
//sb.append(" total: "+fTotal);
int nTotalPage=(int)fTotal;
//sb.append(" total: "+nTotalPage);
if(fTotal>nTotalPage)nTotalPage++;
sb.append("<tr>");
sb.append("<td>");
sb.append(" Page: ");
int nMaxPage=9; //total page displayed as number
int pageStart=1;
int pageEnd=nMaxPage;
//if(sPageToken.equals("N"))
{
pageStart=nPage;
pageEnd=pageStart+nMaxPage;
if(pageEnd>=nTotalPage)
{
pageStart=nTotalPage-nMaxPage;
if(pageStart<1) pageStart=1;
pageEnd=nTotalPage;
}
}
/*if(sPageToken.equals("P"))
{
pageEnd=nPage;
pageStart=pageEnd-nMaxPage;
if(pageStart<=1)
{
pageStart=1;
pageEnd=pageStart+nMaxPage;
}
}*/
if(pageStart!=1) //Need to display Previous
{
int pStart=nPage-1;
sb.append("<button value="+pStart+"-P>previous</button>");
}
for(int i=pageStart;i<=nTotalPage;i++)
{
if(i>pageEnd)
{
//int pStart=nPage+1;
//sb.append("<button value="+pStart+"-N>next</button>");
break;
}
if(i==nPage)
{
sb.append("<button value="+i+"><b>"+i+"</b></button>");
}
else
sb.append("<button value="+i+">"+i+"</button>");
}
if(nPage<nTotalPage)
{
int pStart=nPage+1;
sb.append("<button value="+pStart+"-N>next</button>");
}
sb.append("</td>");
sb.append("</tr>");
sb.append("</table>");
sb.append("</div>");
sb.append("</body>");
sb.append("</html>");
try
{
resp.getWriter().println(sb.toString());
}
catch(Exception e)
{
}
}
} |
package com.wonderpush.sdk;
import junit.framework.Assert;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
public class SyncTest {
private Sync sync;
private static abstract class MockServer implements Sync.Server {
private boolean called = false;
boolean isCalled() {
return called;
}
@Override
public final void patchInstallation(JSONObject diff, Sync.ResponseHandler handler) {
Assert.assertFalse("Server mock object must not be reused", called);
called = true;
_patchInstallation_diff(diff);
try {
_patchInstallation_do();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
_patchInstallation_handler(handler);
}
protected void _patchInstallation_diff(JSONObject diff) {}
protected void _patchInstallation_do() throws Exception {}
protected void _patchInstallation_handler(Sync.ResponseHandler handler) {}
}
private class ServerAssertNotCalled extends MockServer {
@Override
public void _patchInstallation_diff(JSONObject diff) {
Assert.fail("Server.patchInstallation should not be called\nGot diff: " + diff + "\nSync state: " + sync);
}
}
private static class ServerAssertDiffAndSuccess extends MockServer {
private String message;
private JSONObject expectedDiff;
ServerAssertDiffAndSuccess(final String message, final JSONObject expectedDiff) {
this.message = message;
this.expectedDiff = expectedDiff;
}
@Override
public void _patchInstallation_diff(JSONObject diff) {
JSONUtilTest.assertEquals(message, expectedDiff, diff);
}
@Override
public void _patchInstallation_handler(Sync.ResponseHandler handler) {
handler.onSuccess();
}
}
private static class ServerAssertDiffAndFailure extends MockServer {
private final String message;
private final JSONObject expectedDiff;
ServerAssertDiffAndFailure(String message, JSONObject expectedDiff) {
this.message = message;
this.expectedDiff = expectedDiff;
}
@Override
public void _patchInstallation_diff(JSONObject diff) {
JSONUtilTest.assertEquals(message, expectedDiff, diff);
}
@Override
public void _patchInstallation_handler(Sync.ResponseHandler handler) {
handler.onFailure();
}
}
@Before
public void setup() {
sync = new Sync();
}
private void assertSynced() throws JSONException {
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertFalse(sync.hasScheduledPatchCall());
MockServer server = new ServerAssertNotCalled();
Assert.assertFalse(sync.performScheduledPatchCall(server));
Assert.assertFalse(server.isCalled());
}
private void assertSyncedPotentialNoopScheduledPatchCall() throws JSONException {
assertPotentialNoopScheduledPatchCall();
assertSynced();
}
private void assertPotentialNoopScheduledPatchCall() throws JSONException {
if (sync.hasScheduledPatchCall()) {
assertNoopScheduledPatchCall();
} else {
Assert.assertTrue(true);
}
}
private void assertNoopScheduledPatchCall() throws JSONException {
Assert.assertFalse(sync.hasInflightPatchCall());
MockServer server = new ServerAssertNotCalled();
Assert.assertTrue(sync.performScheduledPatchCall(server));
Assert.assertFalse(server.isCalled());
}
private void assertPerformScheduledPatchCallWith(MockServer server) throws JSONException {
Assert.assertTrue(sync.performScheduledPatchCall(server));
Assert.assertTrue(server.isCalled());
}
@Test
public void initialState() throws JSONException {
JSONUtilTest.assertEquals(new JSONObject(), sync.getSdkState());
assertSynced();
JSONUtilTest.assertEquals(new JSONObject(), sync.getSdkState());
}
@Test
public void singlePutSuccess() throws JSONException {
sync.put(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
}
@Test
public void singlePutFailure() throws JSONException {
sync.put(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndFailure(null, new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
}
@Test
public void subsequentSinglePutSuccess() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
sync.put(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
}
@Test
public void subsequentSinglePutFailure() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
sync.put(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndFailure(null, new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
}
@Test
public void pendingPutSuccess() throws JSONException {
sync.put(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
sync.put(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
}
@Test
public void pendingPutFailure() throws JSONException {
sync.put(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
sync.put(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndFailure(null, new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
}
@Test
public void putWhileInflightSuccess() throws JSONException {
sync.put(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}")) {
@Override
protected void _patchInstallation_do() throws Exception {
sync.put(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
}
});
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
}
@Test
public void putWhileInflightFailure() throws JSONException {
sync.put(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndFailure(null, new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}")) {
@Override
protected void _patchInstallation_do() throws Exception {
sync.put(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
}
});
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
}
private void assertSyncedAfterRecvDiff() throws JSONException {
// Be laxer with this final state check
//assertNoopScheduledPatchCall();
//assertSynced();
assertSyncedPotentialNoopScheduledPatchCall();
}
@Test
public void recvDiffFromInitialState() throws JSONException {
assertSynced();
JSONUtilTest.assertEquals(new JSONObject(), sync.getSdkState());
sync.recvDiff(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSyncedAfterRecvDiff();
}
@Test
public void recvDiffFromNonEmptyState() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.recvDiff(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertSyncedAfterRecvDiff();
}
@Test
public void recvDiffPendingPutSuccess() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
// Pending diff is: {"AA":2, "AAA":2, "B":2, "BB":2}
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
sync.recvDiff(new JSONObject("{\"AAA\":3,\"BB\":3,\"C\":3}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
// Pending diff loses "AAA" and "BB" (common keys) when accepting this received diff
// Hence pending diff is now: {"AA":2, "B":2}
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":2,\"B\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
}
@Test
public void recvDiffPendingPutFailure() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
// Pending diff is: {"AA":2, "AAA":2, "B":2, "BB":2}
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
sync.recvDiff(new JSONObject("{\"AAA\":3,\"BB\":3,\"C\":3}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
// Pending diff loses "AAA" and "BB" (common keys) when accepting this received diff
// Hence pending diff is now: {"AA":2, "B":2}
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndFailure(null, new JSONObject("{\"AA\":2,\"B\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":2,\"B\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
}
@Test
public void recvDiffInflightPutSuccess() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
// Pending diff is: {"AA":2, "AAA":2, "B":2, "BB":2}
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}")) {
@Override
protected void _patchInstallation_do() throws Exception {
sync.recvDiff(new JSONObject("{\"AAA\":3,\"BB\":3,\"C\":3}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
// Pending diff becomes: {"AAA":3, "BB":3} (keys common to inflight diff and received diff with values from received diff)
// instead of empty, because the inflight call has overwritten them
}
});
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
// Pending diff is: {"AAA":3, "BB":3} (see previous comment) because call succeeded
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AAA\":3,\"BB\":3}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
assertSyncedAfterRecvDiff();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
}
@Test
public void recvDiffInflightPutFailure() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
// Pending diff is: {"AA":2, "AAA":2, "B":2, "BB":2}
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndFailure(null, new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2}")) {
@Override
protected void _patchInstallation_do() throws Exception {
sync.recvDiff(new JSONObject("{\"AAA\":3,\"BB\":3,\"C\":3}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
// Pending diff becomes: {"AAA":3, "BB":3} (keys common to inflight diff and received diff with values from received diff)
// instead of empty, because the inflight call has overwritten them
// BUT we will fail this call
}
});
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
// Pending diff is: {"AA":2, "B":2}, the previous pending diff minus received keys ("AAA" and "BB")
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":2,\"B\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
}
private void assertSyncedAfterRecvState() throws JSONException {
// Be laxer with this final state check
//assertNoopScheduledPatchCall();
//assertSynced();
assertSyncedPotentialNoopScheduledPatchCall();
}
@Test
public void rectStateFromInitialState() throws JSONException {
assertSynced();
JSONUtilTest.assertEquals(new JSONObject(), sync.getSdkState());
sync.recvState(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSyncedAfterRecvState();
}
@Test
public void recvStateFromNonEmptyState() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.recvState(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertSyncedAfterRecvState();
}
@Test
public void recvStatePendingPutSuccess() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
// Pending diff is: {"AA":2, "AAA":2, "B":2, "BB":2, "BBB":2}
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
sync.recvState(new JSONObject("{\"AAA\":3,\"BBB\":3,\"C\":3}"));
// "A" is removed
// "AA" is not removed because it's part of the pending diff
// "AAA" is not updated because it's part of the pending diff
// "B" is not removed because it's part of the pending diff
// "BB" is not removed because it's part of the pending diff
// "BBB" is not updated because it's part of the pending diff
// "C" is added
// Pending diff is unchanged because it has the priority for conflict resolution
JSONUtilTest.assertEquals(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
}
@Test
public void recvStatePendingPutFailure() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
sync.recvState(new JSONObject("{\"AAA\":3,\"BBB\":3,\"C\":3}"));
// "A" is removed
// "AA" is not removed because it's part of the pending diff
// "AAA" is not updated because it's part of the pending diff
// "B" is not removed because it's part of the pending diff
// "BB" is not removed because it's part of the pending diff
// "BBB" is not updated because it's part of the pending diff
// "C" is added
// Pending diff is unchanged because it has the priority for conflict resolution
JSONUtilTest.assertEquals(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndFailure(null, new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
}
@Test
public void recvStateInflightPutSuccess() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2}")) {
@Override
protected void _patchInstallation_do() throws Exception {
sync.recvState(new JSONObject("{\"AAA\":3,\"BBB\":3,\"C\":3}"));
// "A" is removed
// "AA" is not removed because it's part of the inflight diff
// "AAA" is not updated because it's part of the inflight diff
// "B" is not removed because it's part of the inflight diff
// "BB" is not removed because it's part of the inflight diff
// "BBB" is not updated because it's part of the inflight diff
// "C" is added
JSONUtilTest.assertEquals(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
}
});
JSONUtilTest.assertEquals(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
assertSyncedAfterRecvState();
JSONUtilTest.assertEquals(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
}
@Test
public void recvStateInflightPutFailure() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndFailure(null, new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2}")) {
@Override
protected void _patchInstallation_do() throws Exception {
sync.recvState(new JSONObject("{\"AAA\":3,\"BBB\":3,\"C\":3}"));
// "A" is removed
// "AA" is not removed because it's part of the inflight diff
// "AAA" is not updated because it's part of the inflight diff
// "B" is not removed because it's part of the inflight diff
// "BB" is not removed because it's part of the inflight diff
// "BBB" is not updated because it's part of the inflight diff
// "C" is added
// Pending diff is unchanged because it has the priority for conflict resolution
JSONUtilTest.assertEquals(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
}
});
JSONUtilTest.assertEquals(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"AA\":2,\"AAA\":2,\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
}
} |
package Gui;
import java.sql.*;
/**
*
* @author martin
*/
public class Base {
Connection c = null;
Statement stmt = null;
ResultSet rsNM = null;
ResultSet rsM = null;
public Base() {
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:elementos.sqlite");
c.setAutoCommit(false);
rsNM = stmt.executeQuery("SELECT * FROM NoMetales;");
rsM = stmt.executeQuery("Select * From Metales;");
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
public String[] getElementNameArrayNM() {
String[] arr = new String[64];
int i = 0;
try {
while (this.rsNM.next()) {
String aux = this.rsNM.getString("Nombre");
arr[i] = aux;
i++;
}
return arr;
} catch (SQLException e) {
String[] err = {"no"};
return err;
}
}
public String[] getElementNameArrayM() {
String[] arr = new String[64];
int i = 0;
try {
while (this.rsM.next()) {
String aux = this.rsM.getString("Nombre");
arr[i] = aux;
i++;
}
return arr;
} catch (SQLException e) {
String[] err = {"no"};
return err;
}
}
public int[] getElementStatesArrayNM(int id) {
String strArr = null;
int[] arr = null;
try {
while (this.rsNM.next()) {
if (rsNM.getInt("ID") == id + 1) {
strArr = rsNM.getString("Estados");
break;
}
String[] strings = strArr.replace("[", "").replace("]", "").split(", ");
arr = new int[strings.length];
for (int i = 0; i < arr.length; i++) {
arr[i] = Integer.parseInt(strings[i]);
}
}
} catch (SQLException e) {
arr = null;
}
return arr;
}
public int[] getElementStatesArrayM(int id) {
String strArr = null;
int[] arr = null;
try {
while (this.rsM.next()) {
if (rsM.getInt("ID") == id + 1) {
strArr = rsM.getString("Estados");
break;
}
String[] strings = strArr.replace("[", "").replace("]", "").split(", ");
arr = new int[strings.length];
for (int i = 0; i < arr.length; i++) {
arr[i] = Integer.parseInt(strings[i]);
}
}
} catch (SQLException e) {
arr = null;
}
return arr;
}
public String getElementNomNM(int id) {
String nom = null;
try {
while (this.rsNM.next())
if (rsNM.getInt("ID") == id + 1)
nom = rsNM.getString("Nomencaltura");
} catch (SQLException e) {
nom = null;
}
return nom;
}
public String getElementNomM(int id) {
String nom = null;
try {
while (this.rsM.next())
if (rsM.getInt("ID") == id + 1)
nom = rsM.getString("Nomencaltura");
} catch (SQLException e) {
nom = null;
}
return nom;
}
public String getElementNameNM(int id) {
String name = null;
try {
while (this.rsNM.next())
if (rsNM.getInt("ID") == id + 1)
name = rsNM.getString("Nombre");
} catch (SQLException e) {
name = null;
}
return name;
}
public String getElementNameM(int id) {
String name = null;
try {
while (this.rsM.next())
if (rsM.getInt("ID") == id + 1)
name = rsM.getString("Nombre");
} catch (SQLException e) {
name = null;
}
return name;
}
} |
package serviceResources;
import db.DBConnector;
import serviceRepresentations.User;
import java.sql.*;
import java.util.ArrayList;
public class UserDAO {
private DBConnector connection;
public UserDAO(DBConnector connection){
this.connection = connection;
}
// needs refactoring
public void registerPassword(Long id, String password) {
Connection conn;
Statement stmt = null;
try {
conn = connection.getDBConnection();
stmt = conn.createStatement();
stmt.executeQuery("INSERT INTO logindatacustom VALUES('" + password + "', " + id + ")");
} catch (SQLException e) {
e.printStackTrace();
}
}
public User getUser(String name){
User user = null;
Connection conn;
Statement stmt = null;
try {
conn = connection.getDBConnection();
stmt = conn.createStatement();
try {
// todo : add level
ResultSet rs = stmt.executeQuery("SELECT id, user_role, email, login_type, hints_left, gold_left, avatar_path from USERS where USERS.name ='" + name.replace("'", "\\'") + "'");
rs.next();
long id = rs.getLong("id");
String userRole = rs.getString("user_role");
String email = rs.getString("email");
String loginType = rs.getString("login_type");
int hintsLeft = rs.getInt("hints_left");
int goldLeft = rs.getInt("gold_left");
String avatarPath = rs.getString("avatar_path");
user = new User(id, name, userRole, email, loginType, 0, hintsLeft, goldLeft, avatarPath);
} catch (SQLException e){
e.printStackTrace();
}
}catch (SQLException e) {
e.printStackTrace();
}
return user;
}
public int createUser(User user){
Connection conn;
try {
conn = connection.getDBConnection();
PreparedStatement preparedStatement =
conn.prepareStatement("INSERT INTO users values (?, ?, ?, ?, ?, ?, ?, ?, ?)");
preparedStatement.setInt(1, 0);
preparedStatement.setString(2, user.getName());
preparedStatement.setString(3, user.getUserRole());
preparedStatement.setString(4, user.getEmail());
preparedStatement.setString(5, user.getLoginType());
preparedStatement.setInt(6, user.getHintsLeft());
preparedStatement.setInt(7, user.getGoldLeft());
preparedStatement.setString(8, user.getAvatarPath());
preparedStatement.setInt(9, user.getLevel());
try {
return preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
return -1; // replace with an exception
}
// needs refactoring
public boolean updateUserPassword(User user , String newPassword){
Connection conn;
Statement stmt = null;
try {
conn = connection.getDBConnection();
stmt = conn.createStatement();
try {
stmt.executeQuery("UPDATE LoginDataCustom SET password='" + newPassword + "' where LoginDataCustom.user_id ="+user.getId());
} catch (SQLException e) {
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
return true;
}
public boolean removeUser(User user){
Connection conn;
Statement stmt = null;
try{
conn = connection.getDBConnection();
stmt = conn.createStatement();
try{
stmt.executeQuery("delete from users where id = " + user.getId());
} catch (SQLException e){
e.printStackTrace();
}
} catch(SQLException e) {
e.printStackTrace();
}
return true;
}
public String weakestChapter(Long id){
Connection conn;
Statement stmt = null;
try{
conn = connection.getDBConnection();
stmt = conn.createStatement();
try{
ResultSet rs = stmt.executeQuery("SELECT user_package.weakestChapter("+id+") as WEAKEST from dual");
rs.next();
String ret = rs.getString("WEAKEST");
return ret;
} catch (SQLException e) {
e.printStackTrace();
}
} catch(SQLException e) {
e.printStackTrace();
}
return null;
}
public String checkIfValidUsername(String username){
String suggestion = "";
Connection conn;
Statement stmt = null;
try {
conn = connection.getDBConnection();
stmt = conn.createStatement();
try {
ResultSet queryResult = stmt.executeQuery("SELECT user_package.existsUsername('"+username+"') as EXISTA from dual");
queryResult.next();
int exists = queryResult.getInt("EXISTA");
if(exists == 0)
return null;
else if (exists == 1)
{
ResultSet newUsername = stmt.executeQuery("SELECT user_package.generateSuggestion('"+username+"') as SUGESTIE from dual");
newUsername.next();
suggestion = newUsername.getString("SUGESTIE");
}
} catch (SQLException e) {
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
return suggestion;
}
public int checkPasswordStrengthness(String password){
int returnValue = 0;
Connection conn;
Statement stmt = null;
try {
conn = connection.getDBConnection();
stmt = conn.createStatement();
try {
ResultSet queryResult = stmt.executeQuery("SELECT user_package.isWeak('"+password+"') as VERIFICAREPAROLA from dual");
queryResult.next();
returnValue = queryResult.getInt("VERIFICAREPAROLA");
} catch (SQLException e) {
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
return returnValue;
}
public boolean checkIfUserMatchesPassword(String username, String password) {
User user = getUser(username);
Connection conn;
Statement stmt = null;
try {
conn = connection.getDBConnection();
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select count(password) as valid from logindatacustom where user_id= " + user.getId() + " and password = '" + password + "'");
if (rs == null) {
return false; // the user doesn't even exists
}
rs.next();
Integer matched = rs.getInt("valid");
if (matched == 1) {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public ArrayList<String> getAllUsers() {
ArrayList<String> users = new ArrayList<String>();
Connection conn;
Statement stmt = null;
try {
conn = connection.getDBConnection();
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT name FROM users");
while(rs.next()){
String user = rs.getString("name");
users.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}
return users;
}
} |
package org.jetel.component;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.ByteBuffer;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.data.DataRecord;
import org.jetel.data.Defaults;
import org.jetel.data.FileRecordBuffer;
import org.jetel.data.RecordKey;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.JetelException;
import org.jetel.graph.InputPort;
import org.jetel.graph.Node;
import org.jetel.graph.OutputPort;
import org.jetel.graph.TransformationGraph;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.CodeParser;
import org.jetel.util.ComponentXMLAttributes;
import org.jetel.util.DynamicJavaCode;
import org.jetel.util.StringAproxComparator;
import org.jetel.util.SynchronizeUtils;
/**
* @author avackova
*
*/
public class AproxMergeJoin extends Node {
private static final String XML_SLAVE_OVERWRITE_KEY_ATTRIBUTE = "slaveOverwriteKey";
private static final String XML_JOIN_KEY_ATTRIBUTE = "joinKey";
private static final String XML_REFERENCE_KEY_ATTRIBUTE="referenceKey";
private static final String XML_SLAVE_REF_OVERWRITE_ATTRIBUTE = "slaveRefOverwrite";
private static final String XML_TRANSFORM_CLASS_ATTRIBUTE = "transformClass";
private static final String XML_TRANSFORM_CLASS_FOR_SUSPICIOUS_ATTRIBUTE = "transformClassForSuspicious";
private static final String XML_LIBRARY_PATH_ATTRIBUTE = "libraryPath";
private static final String XML_LIBRARY_PATH_FOR_SUSPICIOUS_ATTRIBUTE = "libraryPathForSuspicious";
private static final String XML_JAVA_SOURCE_ATTRIBUTE = "javaSource";
private static final String XML_JAVA_SOURCE_FOR_SUSPICIOUS_ATTRIBUTE = "javaSourceForSuspicious";
private static final String XML_TRANSFORM_ATTRIBUTE = "transform";
private static final String XML_TRANSFORM_FOR_SUSPICIOUS_ATTRIBUTE = "transformForSuspicious";
private static final String XML_CONFORMITY_ATTRIBUTE = "conformity";
public final static String COMPONENT_TYPE = "APROX_MERGE_JOIN";
private final static int CONFORMING_OUT = 0;
private final static int SUSPICIOUS_OUT = 1;
private final static int NOT_MATCH_DRIVER_OUT = 2;
private final static int NOT_MATCH_SLAVE_OUT = 3;
private final static int DRIVER_ON_PORT = 0;
private final static int SLAVE_ON_PORT = 1;
private final static double DEFAULT_CONFORMITY_LIMIT=0.75;
private final static int CURRENT = 0;
private final static int PREVIOUS = 1;
private final static int TEMPORARY = 1;
private String transformClassName;
private String libraryPath = null;
private String transformSource = null;
private String transformClassNameForSuspicious;
private String libraryPathForSuspicious = null;
private String transformSourceForSuspicious = null;
private RecordTransform transformation = null;
private DynamicJavaCode dynamicTransformation = null;
private RecordTransform transformationForSuspicious = null;
private DynamicJavaCode dynamicTransformationForSuspicious = null;
private String[] joinParameters;
private String[] joinKeys;
private String[] slaveOverwriteKeys = null;
private String[] referenceKey=new String[1];
private String[] slaveReferenceKey=null;
private RecordKey[] recordKey;
private int[][] fieldsToCompare=new int[2][];
private double[] weights;
private StringAproxComparator[] comparator;
private int[] maxDiffrenceLetters;
private double conformityLimit;
private ByteBuffer dataBuffer;
private FileRecordBuffer recordBuffer;
// for passing data records into transform function
private final static DataRecord[] inRecords = new DataRecord[2];
private DataRecord[] outConformingRecords=new DataRecord[1];
private DataRecord[] outSuspiciousRcords = new DataRecord[2];
private Properties transformationParameters;
private Properties transformationParametersForSuspicious;
static Log logger = LogFactory.getLog(MergeJoin.class);
/**
* @param id
*/
public AproxMergeJoin(String id,String[] joinParameters, String referenceKey) throws JetelException{
super(id);
this.joinParameters=joinParameters;
this.referenceKey[0]=referenceKey;
}
public AproxMergeJoin(String id,String[] joinParameters, String referenceKey,
String transformClass) throws JetelException{
this(id,joinParameters,referenceKey);
this.transformClassName = transformClass;
}
public AproxMergeJoin(String id, String[] joinParameters,String referenceKey,
DynamicJavaCode dynaTransCode) throws JetelException{
this(id,joinParameters,referenceKey);
this.dynamicTransformation=dynaTransCode;
}
public AproxMergeJoin(String id, String[] joinParameters,String referenceKey,
String transform, boolean distincter) throws JetelException{
this(id,joinParameters,referenceKey);
this.transformSource = transform;
}
/**
* Sets specific key (string) for slave records<br>
* Can be used if slave record has different names
* for fields composing the key
*
* @param slaveKeys The new slaveOverrideKey value
*/
private void setSlaveOverrideKey(String[] slaveKeys) {
this.slaveOverwriteKeys = slaveKeys;
}
private void setSlaveReferenceKey(String slaveRefKey){
slaveReferenceKey=new String[1];
this.slaveReferenceKey[0]=slaveRefKey;
}
/**
* Populates record buffer with all slave records having the same key
*
* @param port Description of the Parameter
* @param nextRecord next record from slave
* @param key Description of the Parameter
* @param currRecord Description of the Parameter
* @exception IOException Description of the Exception
* @exception InterruptedException Description of the Exception
* @exception JetelException Description of the Exception
*/
private void fillRecordBuffer(InputPort port, DataRecord currRecord, DataRecord nextRecord, RecordKey key)
throws IOException, InterruptedException, JetelException {
recordBuffer.clear();
if (currRecord != null) {
dataBuffer.clear();
currRecord.serialize(dataBuffer);
dataBuffer.flip();
recordBuffer.push(dataBuffer);
while (nextRecord != null) {
nextRecord = port.readRecord(nextRecord);
if (nextRecord != null) {
switch (key.compare(currRecord, nextRecord)) {
case 0:
dataBuffer.clear();
nextRecord.serialize(dataBuffer);
dataBuffer.flip();
recordBuffer.push(dataBuffer);
break;
case -1:
return;
case 1:
throw new JetelException("Slave record out of order!");
}
}
}
}
}
/**
* Finds corresponding slave record for current driver (if there is some)
*
* @param driver Description of the Parameter
* @param slave Description of the Parameter
* @param slavePort Description of the Parameter
* @param key Description of the Parameter
* @return The correspondingRecord value
* @exception IOException Description of the Exception
* @exception InterruptedException Description of the Exception
*/
private int getCorrespondingRecord(DataRecord driver, DataRecord slave,
InputPort slavePort, OutputPort outSlave, RecordKey[] key)
throws IOException, InterruptedException {
while (slave != null) {
switch (key[DRIVER_ON_PORT].compare(key[SLAVE_ON_PORT], driver, slave)) {
case 1:
outSlave.writeRecord(slave);
slave = slavePort.readRecord(slave);
break;
case 0:
return 0;
case -1:
return -1;
}
}
return -1;
// no more records on slave port
}
private double diffrence(DataRecord r1,DataRecord r2,int[][] fieldsToCompare){
double r=0;
int max=0;
for (int i=0;i<fieldsToCompare[DRIVER_ON_PORT].length;i++){
comparator[i].setMaxLettersToChange(maxDiffrenceLetters[i]);
max=(maxDiffrenceLetters[i]+1)*comparator[i].getMaxCostForOneLetter();
int d=comparator[i].distance(
r1.getField(fieldsToCompare[DRIVER_ON_PORT][i]).getValue().toString(),
r2.getField(fieldsToCompare[SLAVE_ON_PORT][i]).getValue().toString());
r+=(double)d/(double)max*weights[i];
}
return r;
}
/**
* Outputs all combinations of current driver record and all slaves with the
* same key
*
* @param driver Description of the Parameter
* @param slave Description of the Parameter
* @param out Description of the Parameter
* @param port Description of the Parameter
* @return Description of the Return Value
* @exception IOException Description of the Exception
* @exception InterruptedException Description of the Exception
*/
private boolean flushCombinations(DataRecord driver, DataRecord slave, DataRecord outConforming,
DataRecord outSuspicious, OutputPort conforming, OutputPort suspicious)
throws IOException, InterruptedException {
recordBuffer.rewind();
dataBuffer.clear();
inRecords[0] = driver;
inRecords[1] = slave;
outConformingRecords[0] = outConforming;
outSuspiciousRcords[1] = outSuspicious;
while (recordBuffer.shift(dataBuffer) != null) {
dataBuffer.flip();
slave.deserialize(dataBuffer);
double conformity=1-diffrence(driver,slave,fieldsToCompare);
if (conformity>=conformityLimit) {
if (!transformation.transform(inRecords, outConformingRecords)) {
resultMsg = transformation.getMessage();
return false;
}
conforming.writeRecord(outConforming);
}else{
if (!transformationForSuspicious.transform(inRecords,outSuspiciousRcords)){
resultMsg = transformation.getMessage();
return false;
}
suspicious.writeRecord(outSuspicious);
}
dataBuffer.clear();
}
return true;
}
/**
* Description of the Method
*
* @param metadata Description of the Parameter
* @param count Description of the Parameter
* @return Description of the Return Value
*/
private DataRecord[] allocateRecords(DataRecordMetadata metadata, int count) {
DataRecord[] data = new DataRecord[count];
for (int i = 0; i < count; i++) {
data[i] = new DataRecord(metadata);
data[i].init();
}
return data;
}
public void run() {
boolean isDriverDifferent;
// get all ports involved
InputPort driverPort = getInputPort(DRIVER_ON_PORT);
InputPort slavePort = getInputPort(SLAVE_ON_PORT);
OutputPort conformingPort = getOutputPort(CONFORMING_OUT);
OutputPort suspiciousPort = getOutputPort(SUSPICIOUS_OUT);
OutputPort notMatchDriverPort = getOutputPort(NOT_MATCH_DRIVER_OUT);
OutputPort notMatchSlavePort = getOutputPort(NOT_MATCH_SLAVE_OUT);
//initialize input records driver & slave
DataRecord[] driverRecords = allocateRecords(driverPort.getMetadata(), 2);
DataRecord[] slaveRecords = allocateRecords(slavePort.getMetadata(), 2);
// initialize output record
DataRecordMetadata outConformingMetadata = conformingPort.getMetadata();
DataRecord outConformingRecord = new DataRecord(outConformingMetadata);
outConformingRecord.init();
DataRecordMetadata outSuspiciousMetadata = suspiciousPort.getMetadata();
DataRecord outSuspiciousRecord = new DataRecord(outSuspiciousMetadata);
outSuspiciousRecord.init();
// tmp record for switching contents
DataRecord tmpRec;
// create file buffer for slave records - system TEMP path
recordBuffer = new FileRecordBuffer(null);
//for the first time (as initialization), we expect that records are different
isDriverDifferent = true;
try {
// first initial load of records
driverRecords[CURRENT] = driverPort.readRecord(driverRecords[CURRENT]);
slaveRecords[CURRENT] = slavePort.readRecord(slaveRecords[CURRENT]);
while (runIt && driverRecords[CURRENT] != null) {
if (isDriverDifferent) {
switch (getCorrespondingRecord(driverRecords[CURRENT], slaveRecords[CURRENT], slavePort, notMatchSlavePort, recordKey)) {
case -1:
// driver lower
// no corresponding slave
notMatchDriverPort.writeRecord(driverRecords[CURRENT]);
driverRecords[CURRENT] = driverPort.readRecord(driverRecords[CURRENT]);
isDriverDifferent = true;
continue;
case 0:
// match
fillRecordBuffer(slavePort, slaveRecords[CURRENT], slaveRecords[TEMPORARY], recordKey[SLAVE_ON_PORT]);
// switch temporary --> current
tmpRec = slaveRecords[CURRENT];
slaveRecords[CURRENT] = slaveRecords[TEMPORARY];
slaveRecords[TEMPORARY] = tmpRec;
isDriverDifferent = false;
break;
}
}
flushCombinations(driverRecords[CURRENT], slaveRecords[TEMPORARY],
outConformingRecord, outSuspiciousRecord,
conformingPort,suspiciousPort);
// get next driver
driverRecords[TEMPORARY] = driverPort.readRecord(driverRecords[TEMPORARY]);
if (driverRecords[TEMPORARY] != null) {
// different driver record ??
switch (recordKey[DRIVER_ON_PORT].compare(driverRecords[CURRENT], driverRecords[TEMPORARY])) {
case 0:
break;
case -1:
// detected change;
isDriverDifferent = true;
break;
case 1:
throw new JetelException("Driver record out of order!");
}
}
// switch temporary --> current
tmpRec = driverRecords[CURRENT];
driverRecords[CURRENT] = driverRecords[TEMPORARY];
driverRecords[TEMPORARY] = tmpRec;
SynchronizeUtils.cloverYield();
}
// if full outer join defined and there are some slave records left, flush them
} catch (IOException ex) {
resultMsg = ex.getMessage();
resultCode = Node.RESULT_ERROR;
closeAllOutputPorts();
return;
} catch (Exception ex) {
resultMsg = ex.getClass().getName()+" : "+ ex.getMessage();
resultCode = Node.RESULT_FATAL_ERROR;
//closeAllOutputPorts();
return;
}
// signal end of records stream to transformation function
transformation.finished();
broadcastEOF();
if (runIt) {
resultMsg = "OK";
} else {
resultMsg = "STOPPED";
}
resultCode = Node.RESULT_OK;
}
public void init() throws ComponentNotReadyException {
Class tClass;
// test that we have at two input ports and four output
if (inPorts.size() != 2) {
throw new ComponentNotReadyException("Two input ports have to be defined!");
} else if (outPorts.size() != 4) {
throw new ComponentNotReadyException("One output port has to be defined!");
}
//Checking transformation for conforming records
if (transformation == null) {
if (transformClassName != null) {
// try to load in transformation class & instantiate
try {
tClass = Class.forName(transformClassName);
} catch (ClassNotFoundException ex) {
// let's try to load in any additional .jar library (if specified)
if(libraryPath == null) {
throw new ComponentNotReadyException("Can't find specified transformation class: " + transformClassName);
}
String urlString = "file:" + libraryPath;
URL[] myURLs;
try {
myURLs = new URL[] { new URL(urlString) };
URLClassLoader classLoader = new URLClassLoader(myURLs, Thread.currentThread().getContextClassLoader());
tClass = Class.forName(transformClassName, true, classLoader);
} catch (MalformedURLException ex1) {
throw new RuntimeException("Malformed URL: " + ex1.getMessage());
} catch (ClassNotFoundException ex1) {
throw new RuntimeException("Can not find class: " + ex1);
}
}
try {
transformation = (RecordTransform) tClass.newInstance();
} catch (Exception ex) {
throw new ComponentNotReadyException(ex.getMessage());
}
} else {
if(dynamicTransformation == null) { //transformSource is set
//creating dynamicTransformation from internal transformation format
CodeParser codeParser = new CodeParser((DataRecordMetadata[]) getInMetadata().toArray(new DataRecordMetadata[0]), (DataRecordMetadata[]) getOutMetadata().toArray(new DataRecordMetadata[0]));
codeParser.setSourceCode(transformSource);
codeParser.parse();
codeParser.addTransformCodeStub("Transform"+this.getId()+"ForConforming");
// DEBUG
// System.out.println(codeParser.getSourceCode());
dynamicTransformation = new DynamicJavaCode(codeParser.getSourceCode());
dynamicTransformation.setCaptureCompilerOutput(true);
}
logger.info(" (compiling dynamic source) ");
// use DynamicJavaCode to instantiate transformation class
Object transObject = null;
try {
transObject = dynamicTransformation.instantiate();
} catch(RuntimeException ex) {
logger.debug(dynamicTransformation.getCompilerOutput());
logger.debug(dynamicTransformation.getSourceCode());
throw new ComponentNotReadyException("Transformation code is not compilable.\n"
+ "reason: " + ex.getMessage());
}
if (transObject instanceof RecordTransform) {
transformation = (RecordTransform) transObject;
} else {
throw new ComponentNotReadyException("Provided transformation class doesn't implement RecordTransform.");
}
}
}
transformation.setGraph(getGraph());
DataRecordMetadata[] inMetadata = new DataRecordMetadata[2];
inMetadata[0]=getInputPort(DRIVER_ON_PORT).getMetadata();
inMetadata[1]=getInputPort(SLAVE_ON_PORT).getMetadata();
// put aside: getOutputPort(WRITE_TO_PORT).getMetadata()
if (!transformation.init(transformationParameters,inMetadata, null)) {
throw new ComponentNotReadyException("Error when initializing reformat function !");
}
//checking transformation for suspicoius records
if (transformationForSuspicious == null) {
if (transformClassNameForSuspicious != null) {
// try to load in transformation class & instantiate
try {
tClass = Class.forName(transformClassNameForSuspicious);
} catch (ClassNotFoundException ex) {
// let's try to load in any additional .jar library (if specified)
if(libraryPathForSuspicious == null) {
throw new ComponentNotReadyException("Can't find specified transformation class: " + transformClassName);
}
String urlString = "file:" + libraryPathForSuspicious;
URL[] myURLs;
try {
myURLs = new URL[] { new URL(urlString) };
URLClassLoader classLoader = new URLClassLoader(myURLs, Thread.currentThread().getContextClassLoader());
tClass = Class.forName(transformClassNameForSuspicious, true, classLoader);
} catch (MalformedURLException ex1) {
throw new RuntimeException("Malformed URL: " + ex1.getMessage());
} catch (ClassNotFoundException ex1) {
throw new RuntimeException("Can not find class: " + ex1);
}
}
try {
transformationForSuspicious = (RecordTransform) tClass.newInstance();
} catch (Exception ex) {
throw new ComponentNotReadyException(ex.getMessage());
}
} else {
if(dynamicTransformationForSuspicious == null) { //transformSource is set
//creating dynamicTransformation from internal transformation format
CodeParser codeParser = new CodeParser((DataRecordMetadata[]) getInMetadata().toArray(new DataRecordMetadata[0]), (DataRecordMetadata[]) getOutMetadata().toArray(new DataRecordMetadata[0]));
codeParser.setSourceCode(transformSourceForSuspicious);
codeParser.parse();
codeParser.addTransformCodeStub("Transform"+this.getId()+"ForSuspicious");
// DEBUG
// System.out.println(codeParser.getSourceCode());
dynamicTransformationForSuspicious = new DynamicJavaCode(codeParser.getSourceCode());
dynamicTransformationForSuspicious.setCaptureCompilerOutput(true);
}
logger.info(" (compiling dynamic source) ");
// use DynamicJavaCode to instantiate transformation class
Object transObject = null;
try {
transObject = dynamicTransformationForSuspicious.instantiate();
} catch(RuntimeException ex) {
logger.debug(dynamicTransformationForSuspicious.getCompilerOutput());
logger.debug(dynamicTransformationForSuspicious.getSourceCode());
throw new ComponentNotReadyException("Transformation code is not compilable.\n"
+ "reason: " + ex.getMessage());
}
if (transObject instanceof RecordTransform) {
transformationForSuspicious = (RecordTransform) transObject;
} else {
throw new ComponentNotReadyException("Provided transformation class doesn't implement RecordTransform.");
}
}
}
transformationForSuspicious.setGraph(getGraph());
if (!transformationForSuspicious.init(transformationParametersForSuspicious,inMetadata, null)) {
throw new ComponentNotReadyException("Error when initializing reformat function !");
}
joinKeys = new String[joinParameters.length];
maxDiffrenceLetters = new int[joinParameters.length];
boolean[][] strenght=new boolean[joinParameters.length][StringAproxComparator.IDENTICAL];
weights = new double[joinParameters.length];
String[] pom=new String[7];
for (int i=0;i<joinParameters.length;i++){
pom=joinParameters[i].split(" ");
joinKeys[i]=pom[0];
maxDiffrenceLetters[i]=Integer.parseInt(pom[1]);
weights[i]=Double.parseDouble(pom[2]);
for (int j=0;j<StringAproxComparator.IDENTICAL;j++){
strenght[i][j] = pom[3+j].equals("true") ? true : false;
}
}
double sumOfWeights=0;
for (int i=0;i<weights.length;i++){
sumOfWeights+=weights[i];
}
for (int i=0;i<weights.length;i++){
weights[i]=weights[i]/sumOfWeights;
}
if (slaveOverwriteKeys == null) {
slaveOverwriteKeys = joinKeys;
}
RecordKey[] rk = new RecordKey[2];
rk[DRIVER_ON_PORT] = new RecordKey(joinKeys, getInputPort(DRIVER_ON_PORT).getMetadata());
rk[SLAVE_ON_PORT] = new RecordKey(slaveOverwriteKeys, getInputPort(SLAVE_ON_PORT).getMetadata());
rk[DRIVER_ON_PORT].init();
rk[SLAVE_ON_PORT].init();
fieldsToCompare[DRIVER_ON_PORT]=rk[DRIVER_ON_PORT].getKeyFields();
fieldsToCompare[SLAVE_ON_PORT]=rk[SLAVE_ON_PORT].getKeyFields();
comparator = new StringAproxComparator[joinParameters.length];
for (int i=0;i<comparator.length;i++){
boolean[] str=strenght[i];
String locale=inMetadata[DRIVER_ON_PORT].getField(fieldsToCompare[DRIVER_ON_PORT][i]).getLocaleStr();
try {
comparator[i] = StringAproxComparator.createComparator(locale,str);
}catch(JetelException ex){
throw new ComponentNotReadyException(ex.getLocalizedMessage());
}
}
if (slaveReferenceKey == null){
slaveReferenceKey=referenceKey;
}
recordKey = new RecordKey[2];
recordKey[DRIVER_ON_PORT] = new RecordKey(referenceKey, getInputPort(DRIVER_ON_PORT).getMetadata());
recordKey[SLAVE_ON_PORT] = new RecordKey(slaveReferenceKey, getInputPort(SLAVE_ON_PORT).getMetadata());
recordKey[DRIVER_ON_PORT].init();
recordKey[SLAVE_ON_PORT].init();
dataBuffer = ByteBuffer.allocateDirect(Defaults.Record.MAX_RECORD_SIZE);
}
/**
* @param transformationParameters The transformationParameters to set.
*/
public void setTransformationParameters(Properties transformationParameters) {
this.transformationParameters = transformationParameters;
}
public void setTransformationParametersForSuspicious(Properties transformationParameters) {
this.transformationParametersForSuspicious = transformationParameters;
}
public static Node fromXML(TransformationGraph graph, org.w3c.dom.Node nodeXML) {
ComponentXMLAttributes xattribs = new ComponentXMLAttributes(nodeXML, graph);
AproxMergeJoin join;
DynamicJavaCode dynaTransCode = null;
try {
if (xattribs.exists(XML_TRANSFORM_CLASS_ATTRIBUTE)){
join = new AproxMergeJoin(xattribs.getString(Node.XML_ID_ATTRIBUTE),
xattribs.getString(XML_JOIN_KEY_ATTRIBUTE).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX),
xattribs.getString(XML_REFERENCE_KEY_ATTRIBUTE),
xattribs.getString(XML_TRANSFORM_CLASS_ATTRIBUTE));
if (xattribs.exists(XML_LIBRARY_PATH_ATTRIBUTE)) {
join.setLibraryPath(xattribs.getString(XML_LIBRARY_PATH_ATTRIBUTE));
}
}else{
if (xattribs.exists(XML_JAVA_SOURCE_ATTRIBUTE)){
dynaTransCode = new DynamicJavaCode(xattribs.getString(XML_JAVA_SOURCE_ATTRIBUTE));
}else{
// do we have child node wich Java source code ?
try {
dynaTransCode = DynamicJavaCode.fromXML(graph, nodeXML);
} catch(Exception ex) {
//do nothing
} }
if (dynaTransCode != null) {
join = new AproxMergeJoin(xattribs.getString(Node.XML_ID_ATTRIBUTE),
xattribs.getString(XML_JOIN_KEY_ATTRIBUTE).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX),
xattribs.getString(XML_REFERENCE_KEY_ATTRIBUTE),
dynaTransCode);
} else { //last chance to find reformat code is in transform attribute
if (xattribs.exists(XML_TRANSFORM_ATTRIBUTE)) {
join = new AproxMergeJoin(xattribs.getString(Node.XML_ID_ATTRIBUTE),
xattribs.getString(XML_JOIN_KEY_ATTRIBUTE).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX),
xattribs.getString(XML_REFERENCE_KEY_ATTRIBUTE),
xattribs.getString(XML_TRANSFORM_ATTRIBUTE), true);
} else {
throw new RuntimeException("Can't create DynamicJavaCode object - source code not found !");
}
}
}
dynaTransCode = null;
if (xattribs.exists(XML_TRANSFORM_CLASS_FOR_SUSPICIOUS_ATTRIBUTE)){
join.setTransformClassNameForSuspicious(xattribs.getString(XML_TRANSFORM_CLASS_FOR_SUSPICIOUS_ATTRIBUTE));
if (xattribs.exists(XML_LIBRARY_PATH_FOR_SUSPICIOUS_ATTRIBUTE)) {
join.setLibraryPathForSuspicious(xattribs.getString(XML_LIBRARY_PATH_FOR_SUSPICIOUS_ATTRIBUTE));
}
}else{
if (xattribs.exists(XML_JAVA_SOURCE_FOR_SUSPICIOUS_ATTRIBUTE)){
dynaTransCode = new DynamicJavaCode(xattribs.getString(XML_JAVA_SOURCE_FOR_SUSPICIOUS_ATTRIBUTE));
}else{
// do we have child node wich Java source code ?
try {
dynaTransCode = DynamicJavaCode.fromXML(graph, nodeXML);
} catch(Exception ex) {
//do nothing
} }
if (dynaTransCode != null) {
join.setDynamicTransformationForSuspicious(dynaTransCode);
} else { //chance to find reformat code is in transform attribute
if (xattribs.exists(XML_TRANSFORM_FOR_SUSPICIOUS_ATTRIBUTE)) {
join.setTransformSourceForSuspicious( xattribs.getString(XML_TRANSFORM_FOR_SUSPICIOUS_ATTRIBUTE), true);
}else{ //get transformation from output por 0
}
}
}
if (xattribs.exists(XML_SLAVE_OVERWRITE_KEY_ATTRIBUTE)) {
join.setSlaveOverrideKey(xattribs.getString(XML_SLAVE_OVERWRITE_KEY_ATTRIBUTE).
split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX));
}
if (xattribs.exists(XML_SLAVE_REF_OVERWRITE_ATTRIBUTE)) {
join.setSlaveReferenceKey(xattribs.getString(XML_SLAVE_REF_OVERWRITE_ATTRIBUTE));
}
join.setConformityLimit(xattribs.getDouble(XML_CONFORMITY_ATTRIBUTE,DEFAULT_CONFORMITY_LIMIT));
join.setTransformationParameters(xattribs.attributes2Properties(
new String[]{XML_TRANSFORM_CLASS_ATTRIBUTE}));
join.setTransformationParametersForSuspicious(xattribs.attributes2Properties(
new String[]{XML_TRANSFORM_CLASS_FOR_SUSPICIOUS_ATTRIBUTE}));
return join;
} catch (Exception ex) {
System.err.println(COMPONENT_TYPE + ":" + ((xattribs.exists(XML_ID_ATTRIBUTE)) ? xattribs.getString(Node.XML_ID_ATTRIBUTE) : " unknown ID ") + ":" + ex.getMessage());
return null;
}
}
private void setLibraryPath(String libraryPath) {
this.libraryPath = libraryPath;
}
public boolean checkConfig() {
return true;
}
public String getType(){
return COMPONENT_TYPE;
}
private void setConformityLimit(double conformityLimit) {
this.conformityLimit = conformityLimit;
}
private void setTransformClassNameForSuspicious(
String transformClassNameForSuspicious) {
this.transformClassNameForSuspicious = transformClassNameForSuspicious;
}
private void setDynamicTransformationForSuspicious(
DynamicJavaCode dynamicTransformationForSuspicious) {
this.dynamicTransformationForSuspicious = dynamicTransformationForSuspicious;
}
private void setTransformSourceForSuspicious(String transformSourceForSuspicious, boolean distincter) {
this.transformSourceForSuspicious = transformSourceForSuspicious;
}
private void setLibraryPathForSuspicious(String libraryPathForSuspicious) {
this.libraryPathForSuspicious = libraryPathForSuspicious;
}
} |
// -*- mode: java -*-
package de.olafdietsche.android.database;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.text.TextUtils;
public class TableHelper {
public TableHelper(SQLiteOpenHelper dbHelper, String tableName) {
dbHelper_ = dbHelper;
tableName_ = tableName;
}
public void close() {
dbHelper_.close();
}
public Cursor rawQuery(String sql, String[] args) {
SQLiteDatabase db = dbHelper_.getReadableDatabase();
return db.rawQuery(sql, args);
}
public Cursor query(String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = dbHelper_.getReadableDatabase();
return db.query(tableName_, projection, selection, selectionArgs, null, null, sortOrder);
}
public Cursor query(String id, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
selection = prefixClause(whereId_, selection);
selectionArgs = insertArg(id, selectionArgs);
return query(projection, selection, selectionArgs, sortOrder);
}
public Cursor query(long id, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
return query(Long.toString(id), projection, selection, selectionArgs, sortOrder);
}
public int delete(String selection, String[] selectionArgs) {
SQLiteDatabase db = dbHelper_.getWritableDatabase();
return db.delete(tableName_, selection, selectionArgs);
}
public int delete(String id, String selection, String[] selectionArgs) {
selection = prefixClause(whereId_, selection);
selectionArgs = insertArg(id, selectionArgs);
return delete(selection, selectionArgs);
}
public int delete(long id, String selection, String[] selectionArgs) {
return delete(Long.toString(id), selection, selectionArgs);
}
public long insert(ContentValues values) {
SQLiteDatabase db = dbHelper_.getWritableDatabase();
long rowId = db.insert(tableName_, null, values);
if (rowId < 0)
throw new SQLException("Failed to insert row");
return rowId;
}
public int update(ContentValues values, String selection, String[] selectionArgs) {
SQLiteDatabase db = dbHelper_.getWritableDatabase();
return db.update(tableName_, values, selection, selectionArgs);
}
public int update(String id, ContentValues values, String selection, String[] selectionArgs) {
selection = prefixClause(whereId_, selection);
selectionArgs = insertArg(id, selectionArgs);
return update(values, selection, selectionArgs);
}
public int update(long id, ContentValues values, String selection, String[] selectionArgs) {
return update(Long.toString(id), values, selection, selectionArgs);
}
private static final String whereId_ = BaseColumns._ID + " = ?";
public static String prefixClause(String prefix, String selection) {
if (TextUtils.isEmpty(selection)) {
return prefix;
} else {
StringBuilder builder = new StringBuilder(prefix.length() + selection.length() + 10);
builder.append("(")
.append(prefix)
.append(") and (")
.append(selection)
.append(")");
return builder.toString();
}
}
public static String[] insertArg(String arg, String[] selectionArgs) {
if (selectionArgs == null)
return new String[]{arg};
int n = selectionArgs.length;
String[] args = new String[n + 1];
args[0] = arg;
if (n > 0)
System.arraycopy(selectionArgs, 0, args, 1, n);
return args;
}
private SQLiteOpenHelper dbHelper_;
private String tableName_;
} |
package hirezapi.endpoints;
import hirezapi.HiRezApi;
import hirezapi.json.DataUsage;
import hirezapi.json.Ping;
import hirezapi.json.SessionCreation;
import hirezapi.json.SessionTest;
import hirezapi.session.EnvironmentalSessionStorage;
import hirezapi.session.SessionCreationException;
import hirezapi.session.SessionStorage;
import lombok.Getter;
import lombok.Setter;
public class SessionEndpoint extends AbstractEndpoint {
@Getter
@Setter
private SessionStorage sessionStorage;
public SessionEndpoint(HiRezApi api, SessionStorage sessionStorage) {
super(api);
this.sessionStorage = sessionStorage;
}
public SessionEndpoint(HiRezApi api) {
super(api);
setSessionStorage(new EnvironmentalSessionStorage());
}
public Ping ping() {
return new Ping(api.getRestController().request(buildUrl("ping"), String.class));
}
public SessionCreation create() {
SessionCreation sessionCreation = api.getRestController().request(buildUrl("createsession"), SessionCreation.class);
if (!sessionCreation.getReturnedMessage().equals("Approved")) {
throw new SessionCreationException(sessionCreation);
} else {
getLog().info("Session Created for {}", api.getConfiguration().getPlatform().toString());
sessionStorage.set(api.getConfiguration().getPlatform(), sessionCreation);
}
return sessionCreation;
}
public SessionTest test() {
return new SessionTest(api.getRestController().request(buildUrl("testsession"), String.class));
}
public DataUsage getDataUsage() {
return api.getRestController().request(buildUrl("getdataused"), DataUsage[].class)[0];
}
} |
package be.ugent.zeus.hydra;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;
import android.widget.Toast;
import be.ugent.zeus.hydra.data.Resto;
import be.ugent.zeus.hydra.data.caches.RestoCache;
import be.ugent.zeus.hydra.data.services.HTTPIntentService;
import be.ugent.zeus.hydra.data.services.RestoService;
import be.ugent.zeus.hydra.ui.map.DirectionMarker;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.widget.SearchView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.HashMap;
import java.util.List;
/**
*
* @author Tom Naessens
*/
public class BuildingMap extends AbstractSherlockFragmentActivity implements GoogleMap.OnMarkerClickListener, GoogleMap.OnInfoWindowClickListener {
private GoogleMap map;
private RestoResultReceiver receiver = new RestoResultReceiver();
private HashMap<String, Marker> markerMap;
private RestoCache restoCache;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.title_restomap);
setContentView(R.layout.restomap);
markerMap = new HashMap<String, Marker>();
setUpMapIfNeeded();
handleIntent(getIntent());
}
@Override
public void onNewIntent(Intent intent) {
setIntent(intent);
handleIntent(intent);
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (map == null) {
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (map != null) {
// The Map is verified. It is now safe to manipulate the map.
setUpMap();
} else {
int result = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (result != ConnectionResult.SUCCESS) {
GooglePlayServicesUtil.getErrorDialog(result, this, 1);
}
}
}
}
public void setUpMap() {
try {
MapsInitializer.initialize(this);
} catch (GooglePlayServicesNotAvailableException ex) {
Log.e("GPS:", "Error" + ex);
}
map.setMyLocationEnabled(true);
map.setOnMarkerClickListener(this);
map.setOnInfoWindowClickListener(this);
// TODO: Fix the map on the users location when he is in Ghent
// LatLng location = new LatLng(map.getMyLocation().getLatitude(), map.getMyLocation().getLongitude());
// LatLngBounds bounds = new LatLngBounds(new LatLng(51.016347, 3.677673), new LatLng(51.072684, 3.746338));
CameraUpdate center;
CameraUpdate zoom;
// Is the user in Ghent?
// if (bounds.contains(location)) {
// center = CameraUpdateFactory.newLatLng(location);
// zoom = CameraUpdateFactory.zoomTo(6);
// } else {
center = CameraUpdateFactory.newLatLng(new LatLng(51.042833, 3.723335));
zoom = CameraUpdateFactory.zoomTo(13);
map.moveCamera(center);
map.animateCamera(zoom);
map.setInfoWindowAdapter(new DirectionMarker(getLayoutInflater()));
restoCache = RestoCache.getInstance(this);
if (!restoCache.exists(RestoService.FEED_NAME)
|| System.currentTimeMillis() - restoCache.lastModified(RestoService.FEED_NAME) > RestoService.REFRESH_TIME) {
addRestos(false);
} else {
addRestos(true);
}
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
@Override
public void onDestroy() {
super.onDestroy();
}
private void addRestos(boolean synced) {
if (!synced) {
Intent intent = new Intent(this, RestoService.class);
intent.putExtra(HTTPIntentService.RESULT_RECEIVER_EXTRA, receiver);
startService(intent);
} else {
Resto[] restos = RestoCache.getInstance(BuildingMap.this).get(RestoService.FEED_NAME);
if (restos != null && restos.length > 0) {
for (Resto resto : restos) {
MarkerOptions markerOptions = new MarkerOptions()
.position(new LatLng(resto.latitude, resto.longitude))
.title(resto.name);
Marker marker = map.addMarker(markerOptions);
markerMap.put(resto.name, marker);
}
} else {
Toast.makeText(BuildingMap.this, R.string.no_restos_found, Toast.LENGTH_SHORT).show();
finish();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// getSupportMenuInflater().inflate(R.menu.building_search, menu);
// SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
// SearchView searchView = new SearchView(getSupportActionBar().getThemedContext());
// searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
onSearchRequested();
return true;
}
return super.onOptionsItemSelected(item);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
doSearch(query);
}
}
private void doSearch(String queryStr) {
if (markerMap.containsKey(queryStr)) {
Marker foundMarker = markerMap.get(queryStr);
updateMarkerDistance(foundMarker);
foundMarker.showInfoWindow();
map.moveCamera(CameraUpdateFactory.newLatLng(foundMarker.getPosition()));
} else {
this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(BuildingMap.this, R.string.no_restos_found, Toast.LENGTH_SHORT).show();
}
});
}
}
public boolean onMarkerClick(Marker marker) {
updateMarkerDistance(marker);
marker.showInfoWindow();
return true;
}
public void updateMarkerDistance(Marker marker) {
if (map.getMyLocation() == null) {
marker.setSnippet("");
} else {
float[] results = new float[1];
Location.distanceBetween(map.getMyLocation().getLatitude(), map.getMyLocation().getLongitude(),
marker.getPosition().latitude, marker.getPosition().longitude, results);
double distance = results[0];
if (distance < 2000) {
marker.setSnippet(String.format("Afstand: %.0f m", results[0]));
} else {
marker.setSnippet(String.format("Afstand: %.1f km", results[0] / 1000.0));
}
}
}
public void onInfoWindowClick(Marker marker) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("http://maps.google.com/maps?q=%s,%s", marker.getPosition().latitude, marker.getPosition().longitude)));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(intent);
}
private class RestoResultReceiver extends ResultReceiver {
public RestoResultReceiver() {
super(null);
}
@Override
protected void onReceiveResult(int code, Bundle data) {
switch (code) {
case RestoService.STATUS_FINISHED:
runOnUiThread(new Runnable() {
public void run() {
addRestos(true);
}
});
break;
case HTTPIntentService.STATUS_ERROR:
Toast.makeText(BuildingMap.this, R.string.resto_update_failed, Toast.LENGTH_SHORT).show();
runOnUiThread(new Runnable() {
public void run() {
addRestos(true);
}
});
break;
}
}
}
} |
package loci.formats.in;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;
import loci.common.DataTools;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.common.xml.BaseHandler;
import loci.common.xml.XMLTools;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import ome.xml.model.primitives.NonNegativeInteger;
import ome.xml.model.primitives.PositiveFloat;
import ome.xml.model.primitives.PositiveInteger;
import ome.xml.model.primitives.Timestamp;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
public class InCellReader extends FormatReader {
// -- Constants --
public static final String INCELL_MAGIC_STRING = "IN Cell Analyzer";
private static final String[] PIXELS_SUFFIXES =
new String[] {"tif", "tiff", "im"};
private static final String[] METADATA_SUFFIXES =
new String[] {"xml", "xlog"};
// -- Fields --
private boolean[][] plateMap;
private Image[][][][] imageFiles;
private MinimalTiffReader tiffReader;
private Vector<Integer> emWaves, exWaves;
private Vector<String> channelNames;
private int totalImages;
private int imageWidth, imageHeight;
private String creationDate;
private String rowName = "A", colName = "1";
private int fieldCount;
private int wellRows, wellCols;
private Hashtable<Integer, int[]> wellCoordinates;
private Vector<Double> posX, posY;
private boolean[][] exclude;
private Vector<Integer> channelsPerTimepoint;
private boolean oneTimepointPerSeries;
private int totalChannels;
private Vector<String> metadataFiles;
// -- Constructor --
/** Constructs a new InCell 1000/2000 reader. */
public InCellReader() {
super("InCell 1000/2000",
new String[] {"xdce", "xml", "tiff", "tif", "xlog", "im"});
suffixSufficient = false;
domains = new String[] {FormatTools.HCS_DOMAIN};
hasCompanionFiles = true;
datasetDescription = "One .xdce file with at least one .tif/.tiff or " +
".im file";
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
if (checkSuffix(name, "xdce") || checkSuffix(name, "xml")) {
return super.isThisType(name, open);
}
return false;
}
/* @see loci.formats.IFormatReader#isSingleFile(String) */
public boolean isSingleFile(String id) throws FormatException, IOException {
return false;
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
final int blockLen = 2048;
if (!FormatTools.validStream(stream, blockLen, false)) return false;
String check = stream.readString(blockLen);
return check.indexOf(INCELL_MAGIC_STRING) >= 0;
}
/* @see loci.formats.IFormatReader#fileGroupOption(String) */
public int fileGroupOption(String id) throws FormatException, IOException {
return FormatTools.MUST_GROUP;
}
/* @see loci.formats.IFormatReader#get8BitLookupTable() */
public byte[][] get8BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
return tiffReader == null ? null : tiffReader.get8BitLookupTable();
}
/* @see loci.formats.IFormatReader#get16BitLookupTable() */
public short[][] get16BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
return tiffReader == null ? null : tiffReader.get16BitLookupTable();
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
int[] coordinates = getZCTCoords(no);
int well = getWellFromSeries(getSeries());
int field = getFieldFromSeries(getSeries());
int timepoint = oneTimepointPerSeries ?
getSeries() % channelsPerTimepoint.size() : coordinates[2];
int image = getIndex(coordinates[0], coordinates[1], 0);
if (imageFiles[well][field][timepoint][image] == null) return buf;
String filename = imageFiles[well][field][timepoint][image].filename;
if (filename == null || !(new Location(filename).exists())) return buf;
if (imageFiles[well][field][timepoint][image].isTiff) {
try {
tiffReader.setId(filename);
return tiffReader.openBytes(0, buf, x, y, w, h);
}
catch (FormatException e) {
LOGGER.debug("", e);
}
catch (IOException e) {
LOGGER.debug("", e);
}
return buf;
}
// pixels are stored in .im files
RandomAccessInputStream s = new RandomAccessInputStream(filename);
if (s.length() > FormatTools.getPlaneSize(this)) {
s.seek(128);
readPlane(s, x, y, w, h, buf);
}
s.close();
return buf;
}
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
Vector<String> files = new Vector<String>();
files.addAll(metadataFiles);
if (!noPixels && imageFiles != null) {
int well = getWellFromSeries(getSeries());
int field = getFieldFromSeries(getSeries());
for (Image[] timepoints : imageFiles[well][field]) {
for (Image plane : timepoints) {
if (plane != null && plane.filename != null) {
if (new Location(plane.filename).exists()) {
files.add(plane.filename);
}
if (new Location(plane.thumbnailFile).exists()) {
files.add(plane.thumbnailFile);
}
}
}
}
}
if (!files.contains(currentId)) {
files.add(currentId);
}
return files.toArray(new String[files.size()]);
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (tiffReader != null) tiffReader.close(fileOnly);
if (!fileOnly) {
imageFiles = null;
tiffReader = null;
totalImages = 0;
emWaves = exWaves = null;
channelNames = null;
wellCoordinates = null;
posX = null;
posY = null;
creationDate = null;
wellRows = wellCols = 0;
fieldCount = 0;
exclude = null;
metadataFiles = null;
imageWidth = imageHeight = 0;
rowName = "A";
colName = "1";
channelsPerTimepoint = null;
oneTimepointPerSeries = false;
totalChannels = 0;
plateMap = null;
}
}
/* @see loci.formats.IFormatReader#getOptimalTileWidth() */
public int getOptimalTileWidth() {
FormatTools.assertId(currentId, true, 1);
for (Image[][][] well : imageFiles) {
for (Image[][] field : well) {
for (Image[] timepoint : field) {
for (Image img : timepoint) {
if (img != null) {
if (img.isTiff && tiffReader != null) {
return tiffReader.getOptimalTileWidth();
}
break;
}
}
}
}
}
return super.getOptimalTileWidth();
}
/* @see loci.formats.IFormatReader#getOptimalTileHeight() */
public int getOptimalTileHeight() {
FormatTools.assertId(currentId, true, 1);
for (Image[][][] well : imageFiles) {
for (Image[][] field : well) {
for (Image[] timepoint : field) {
for (Image img : timepoint) {
if (img != null) {
if (img.isTiff && tiffReader != null) {
return tiffReader.getOptimalTileHeight();
}
break;
}
}
}
}
}
return super.getOptimalTileHeight();
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
// make sure that we have the .xdce (or .xml) file
if (checkSuffix(id, PIXELS_SUFFIXES) || checkSuffix(id, "xlog")) {
Location currentFile = new Location(id).getAbsoluteFile();
Location parent = currentFile.getParentFile();
String[] list = parent.list(true);
for (String f : list) {
if (checkSuffix(f, new String[] {"xdce", "xml"})) {
String path = new Location(parent, f).getAbsolutePath();
if (isThisType(path)) {
// make sure that the .xdce file references the current file
// this ensures that the correct file is chosen if multiple
// .xdce files are the same directory
String data = DataTools.readFile(path);
if (data.indexOf(currentFile.getName()) >= 0) {
id = path;
break;
}
}
}
}
}
super.initFile(id);
in = new RandomAccessInputStream(id);
channelNames = new Vector<String>();
emWaves = new Vector<Integer>();
exWaves = new Vector<Integer>();
channelsPerTimepoint = new Vector<Integer>();
metadataFiles = new Vector<String>();
// build list of companion files
Location directory = new Location(id).getAbsoluteFile().getParentFile();
String[] files = directory.list(true);
for (String file : files) {
if (checkSuffix(file, METADATA_SUFFIXES)) {
metadataFiles.add(new Location(directory, file).getAbsolutePath());
}
}
// parse metadata from the .xdce or .xml file
wellCoordinates = new Hashtable<Integer, int[]>();
posX = new Vector<Double>();
posY = new Vector<Double>();
byte[] b = new byte[(int) in.length()];
in.read(b);
core[0].dimensionOrder = "XYZCT";
MetadataStore store = makeFilterMetadata();
DefaultHandler handler = new MinimalInCellHandler();
XMLTools.parseXML(b, handler);
if (getSizeZ() == 0) core[0].sizeZ = 1;
if (getSizeC() == 0) core[0].sizeC = 1;
if (getSizeT() == 0) core[0].sizeT = 1;
int seriesCount = 0;
if (exclude != null) {
for (int row=0; row<wellRows; row++) {
for (int col=0; col<wellCols; col++) {
if (!exclude[row][col]) {
seriesCount += imageFiles[row*wellCols + col].length;
}
}
}
int expectedSeries = totalImages / (getSizeZ() * getSizeC() * getSizeT());
seriesCount = (int) Math.min(seriesCount, expectedSeries);
}
else seriesCount = totalImages / (getSizeZ() * getSizeC() * getSizeT());
totalChannels = getSizeC();
oneTimepointPerSeries = false;
for (int i=1; i<channelsPerTimepoint.size(); i++) {
if (!channelsPerTimepoint.get(i).equals(channelsPerTimepoint.get(i - 1)))
{
oneTimepointPerSeries = true;
break;
}
}
if (oneTimepointPerSeries) {
int imageCount = 0;
for (Integer timepoint : channelsPerTimepoint) {
imageCount += timepoint.intValue() * getSizeZ();
}
seriesCount = (totalImages / imageCount) * getSizeT();
}
int sizeT = getSizeT();
int sizeC = getSizeC();
int z = getSizeZ();
int t = oneTimepointPerSeries ? 1 : getSizeT();
core = new CoreMetadata[seriesCount];
for (int i=0; i<seriesCount; i++) {
int c = oneTimepointPerSeries ?
channelsPerTimepoint.get(i % sizeT).intValue() : sizeC;
core[i] = new CoreMetadata();
core[i].sizeZ = z;
core[i].sizeC = c;
core[i].sizeT = t;
core[i].imageCount = z * c * t;
core[i].dimensionOrder = "XYZCT";
}
int wellIndex = getWellFromSeries(0);
int fieldIndex = getFieldFromSeries(0);
String filename = imageFiles[wellIndex][fieldIndex][0][0].filename;
boolean isTiff = imageFiles[wellIndex][fieldIndex][0][0].isTiff;
if (isTiff && filename != null) {
tiffReader = new MinimalTiffReader();
tiffReader.setId(filename);
int nextTiming = 0;
for (int i=0; i<seriesCount; i++) {
core[i].sizeX = tiffReader.getSizeX();
core[i].sizeY = tiffReader.getSizeY();
core[i].interleaved = tiffReader.isInterleaved();
core[i].indexed = tiffReader.isIndexed();
core[i].rgb = tiffReader.isRGB();
core[i].pixelType = tiffReader.getPixelType();
core[i].littleEndian = tiffReader.isLittleEndian();
}
}
else {
for (int i=0; i<seriesCount; i++) {
core[i].sizeX = imageWidth;
core[i].sizeY = imageHeight;
core[i].interleaved = false;
core[i].indexed = false;
core[i].rgb = false;
core[i].pixelType = FormatTools.UINT16;
core[i].littleEndian = true;
}
}
MetadataTools.populatePixels(store, this, true);
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
handler = new InCellHandler(store);
XMLTools.parseXML(b, handler);
}
String rowNaming =
Character.isDigit(rowName.charAt(0)) ? "Number" : "Letter";
String colNaming =
Character.isDigit(colName.charAt(0)) ? "Number" : "Letter";
String plateName = currentId;
int begin = plateName.lastIndexOf(File.separator) + 1;
int end = plateName.lastIndexOf(".");
plateName = plateName.substring(begin, end);
store.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
store.setPlateName(plateName, 0);
store.setPlateRowNamingConvention(getNamingConvention(rowNaming), 0);
store.setPlateColumnNamingConvention(getNamingConvention(colNaming), 0);
for (int r=0; r<wellRows; r++) {
for (int c=0; c<wellCols; c++) {
int well = r * wellCols + c;
String wellID = MetadataTools.createLSID("Well", 0, well);
store.setWellID(wellID, 0, well);
store.setWellRow(new NonNegativeInteger(r), 0, well);
store.setWellColumn(new NonNegativeInteger(c), 0, well);
}
}
String plateAcqID = MetadataTools.createLSID("PlateAcquisition", 0, 0);
store.setPlateAcquisitionID(plateAcqID, 0, 0);
if (fieldCount > 0) {
store.setPlateAcquisitionMaximumFieldCount(
new PositiveInteger(fieldCount), 0, 0);
}
else {
LOGGER.warn("Expected positive value for MaximumFieldCount; got {}",
fieldCount);
}
// populate Image data
String instrumentID = MetadataTools.createLSID("Instrument", 0);
String experimentID = MetadataTools.createLSID("Experiment", 0);
store.setInstrumentID(instrumentID, 0);
store.setExperimentID(experimentID, 0);
for (int i=0; i<seriesCount; i++) {
int well = getWellFromSeries(i);
int field = getFieldFromSeries(i) + 1;
int totalTimepoints =
oneTimepointPerSeries ? channelsPerTimepoint.size() : 1;
int timepoint = oneTimepointPerSeries ? (i % totalTimepoints) + 1 : -1;
String imageID = MetadataTools.createLSID("Image", i);
store.setImageID(imageID, i);
store.setImageInstrumentRef(instrumentID, i);
store.setImageExperimentRef(experimentID, i);
int wellRow = well / wellCols;
int wellCol = well % wellCols;
char rowChar = rowName.charAt(rowName.length() - 1);
char colChar = colName.charAt(colName.length() - 1);
String row = rowName.substring(0, rowName.length() - 1);
String col = colName.substring(0, colName.length() - 1);
if (Character.isDigit(rowChar)) {
row += wellRow + Integer.parseInt(String.valueOf(rowChar));
}
else row += (char) (rowChar + wellRow);
if (Character.isDigit(colChar)) {
col += wellCol + Integer.parseInt(String.valueOf(colChar));
}
else col += (char) (colChar + wellCol);
String imageName = "Well " + row + "-" + col + ", Field #" + field;
if (timepoint >= 0) {
imageName += ", Timepoint #" + timepoint;
}
store.setImageName(imageName, i);
if (creationDate != null) {
store.setImageAcquisitionDate(new Timestamp(creationDate), i);
}
timepoint
if (timepoint < 0) timepoint = 0;
int sampleIndex = (field - 1) * totalTimepoints + timepoint;
String wellSampleID =
MetadataTools.createLSID("WellSample", 0, well, sampleIndex);
store.setWellSampleID(wellSampleID, 0, well, sampleIndex);
store.setWellSampleIndex(new NonNegativeInteger(i), 0, well, sampleIndex);
store.setWellSampleImageRef(imageID, 0, well, sampleIndex);
if (field < posX.size()) {
store.setWellSamplePositionX(posX.get(field), 0, well, sampleIndex);
}
if (field < posY.size()) {
store.setWellSamplePositionY(posY.get(field), 0, well, sampleIndex);
}
store.setPlateAcquisitionWellSampleRef(wellSampleID, 0, 0, i);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
// populate PlaneTiming data
for (int i=0; i<seriesCount; i++) {
int well = getWellFromSeries(i);
int field = getFieldFromSeries(i);
int timepoint = oneTimepointPerSeries ?
i % channelsPerTimepoint.size() : 0;
for (int time=0; time<getSizeT(); time++) {
if (!oneTimepointPerSeries) timepoint = time;
int c = channelsPerTimepoint.get(timepoint).intValue();
for (int q=0; q<getSizeZ()*c; q++) {
Image img = imageFiles[well][field][timepoint][q];
if (img == null) continue;
int plane = time * getSizeZ() * c + q;
store.setPlaneDeltaT(img.deltaT, i, plane);
store.setPlaneExposureTime(img.exposure, i, plane);
store.setPlanePositionX(posX.get(field), i, plane);
store.setPlanePositionY(posY.get(field), i, plane);
store.setPlanePositionZ(img.zPosition, i, plane);
}
}
}
// populate LogicalChannel data
for (int i=0; i<seriesCount; i++) {
setSeries(i);
for (int q=0; q<getEffectiveSizeC(); q++) {
if (q < channelNames.size()) {
store.setChannelName(channelNames.get(q), i, q);
}
if (q < emWaves.size()) {
int wave = emWaves.get(q).intValue();
if (wave > 0) {
store.setChannelEmissionWavelength(
new PositiveInteger(wave), i, q);
}
else {
LOGGER.warn(
"Expected positive value for EmissionWavelength; got {}", wave);
}
}
if (q < exWaves.size()) {
int wave = exWaves.get(q).intValue();
if (wave > 0) {
store.setChannelExcitationWavelength(
new PositiveInteger(wave), i, q);
}
else {
LOGGER.warn(
"Expected positive value for ExcitationWavelength; got {}",
wave);
}
}
}
}
setSeries(0);
// populate Plate data
store.setPlateWellOriginX(0.5, 0);
store.setPlateWellOriginY(0.5, 0);
}
}
// -- Helper methods --
private int getFieldFromSeries(int series) {
if (oneTimepointPerSeries) series /= channelsPerTimepoint.size();
return series % fieldCount;
}
private int getWellFromSeries(int series) {
if (oneTimepointPerSeries) series /= channelsPerTimepoint.size();
int well = series / fieldCount;
int counter = -1;
for (int row=0; row<plateMap.length; row++) {
for (int col=0; col<plateMap[row].length; col++) {
if (plateMap[row][col]) {
counter++;
}
if (counter == well) {
return row * wellCols + col;
}
}
}
return -1;
}
// -- Helper classes --
class MinimalInCellHandler extends BaseHandler {
private String currentImageFile;
private String currentThumbnail;
private int wellRow, wellCol;
private int nChannels = 0;
public void endElement(String uri, String localName, String qName) {
if (qName.equals("PlateMap")) {
int sizeT = getSizeT();
if (sizeT == 0) {
// There has been no <TimeSchedule> in the <PlateMap> defined to
// populate channelsPerTimepoint so we have to assume that there is
// only one timepoint otherwise the imageFiles array below will not
// be correctly initialized.
sizeT = 1;
}
if (channelsPerTimepoint.size() == 0) {
// There has been no <TimeSchedule> in the <PlateMap> defined to
// populate channelsPerTimepoint so we have to assume that all
// channels are being acquired.
channelsPerTimepoint.add(core[0].sizeC);
}
imageFiles = new Image[wellRows * wellCols][fieldCount][sizeT][];
for (int well=0; well<wellRows*wellCols; well++) {
for (int field=0; field<fieldCount; field++) {
for (int t=0; t<sizeT; t++) {
int channels = channelsPerTimepoint.get(t).intValue();
imageFiles[well][field][t] = new Image[channels * getSizeZ()];
}
}
}
}
else if (qName.equals("TimePoint")) {
channelsPerTimepoint.add(new Integer(nChannels));
nChannels = 0;
}
else if (qName.equals("Times")) {
if (channelsPerTimepoint.size() == 0) {
channelsPerTimepoint.add(new Integer(getSizeC()));
}
for (int i=0; i<channelsPerTimepoint.size(); i++) {
int c = channelsPerTimepoint.get(i).intValue();
if (c == 0) {
channelsPerTimepoint.setElementAt(new Integer(getSizeC()), i);
}
}
}
}
public void startElement(String uri, String localName, String qName,
Attributes attributes)
{
if (qName.equals("Plate")) {
wellRows = Integer.parseInt(attributes.getValue("rows"));
wellCols = Integer.parseInt(attributes.getValue("columns"));
plateMap = new boolean[wellRows][wellCols];
}
else if (qName.equals("Exclude")) {
if (exclude == null) exclude = new boolean[wellRows][wellCols];
int row = Integer.parseInt(attributes.getValue("row")) - 1;
int col = Integer.parseInt(attributes.getValue("col")) - 1;
exclude[row][col] = true;
}
else if (qName.equals("Images")) {
totalImages = Integer.parseInt(attributes.getValue("number"));
}
else if (qName.equals("Image")) {
String file = attributes.getValue("filename");
String thumb = attributes.getValue("thumbnail");
Location current = new Location(currentId).getAbsoluteFile();
Location imageFile = new Location(current.getParentFile(), file);
currentImageFile = imageFile.getAbsolutePath();
currentThumbnail =
new Location(current.getParentFile(), thumb).getAbsolutePath();
}
else if (qName.equals("Identifier")) {
int field = Integer.parseInt(attributes.getValue("field_index"));
int z = Integer.parseInt(attributes.getValue("z_index"));
int c = Integer.parseInt(attributes.getValue("wave_index"));
int t = Integer.parseInt(attributes.getValue("time_index"));
int channels = channelsPerTimepoint.get(t).intValue();
int index = FormatTools.getIndex("XYZCT", getSizeZ(),
channels, 1, getSizeZ() * channels, z, c, 0);
Image img = new Image();
img.thumbnailFile = currentThumbnail;
Location file = new Location(currentImageFile);
img.filename = file.exists() ? currentImageFile : null;
if (img.filename == null) {
LOGGER.warn("{} does not exist.", currentImageFile);
}
currentImageFile = currentImageFile.toLowerCase();
img.isTiff = currentImageFile.endsWith(".tif") ||
currentImageFile.endsWith(".tiff");
imageFiles[wellRow * wellCols + wellCol][field][t][index] = img;
}
else if (qName.equals("offset_point")) {
fieldCount++;
}
else if (qName.equals("TimePoint")) {
core[0].sizeT++;
}
else if (qName.equals("Wavelength")) {
String fusion = attributes.getValue("fusion_wave");
if (fusion.equals("false")) core[0].sizeC++;
}
else if (qName.equals("AcqWave")) {
nChannels++;
}
else if (qName.equals("ZDimensionParameters")) {
String nz = attributes.getValue("number_of_slices");
if (nz != null) {
core[0].sizeZ = Integer.parseInt(nz);
}
else core[0].sizeZ = 1;
}
else if (qName.equals("Row")) {
wellRow = Integer.parseInt(attributes.getValue("number")) - 1;
}
else if (qName.equals("Column")) {
wellCol = Integer.parseInt(attributes.getValue("number")) - 1;
plateMap[wellRow][wellCol] = true;
}
else if (qName.equals("Size")) {
imageWidth = Integer.parseInt(attributes.getValue("width"));
imageHeight = Integer.parseInt(attributes.getValue("height"));
}
else if (qName.equals("NamingRows")) {
rowName = attributes.getValue("begin");
}
else if (qName.equals("NamingColumns")) {
colName = attributes.getValue("begin");
}
}
}
/** SAX handler for parsing XML. */
class InCellHandler extends BaseHandler {
private String currentQName;
private boolean openImage;
private int nextEmWave = 0;
private int nextExWave = 0;
private MetadataStore store;
private int nextPlate = 0;
private int currentRow = -1, currentCol = -1;
private int currentField = 0;
private int currentImage, currentPlane;
private Double timestamp, exposure, zPosition;
private String channelName = null;
public InCellHandler(MetadataStore store) {
this.store = store;
}
public void characters(char[] ch, int start, int length) {
String value = new String(ch, start, length);
if (currentQName.equals("UserComment")) {
store.setImageDescription(value, 0);
}
}
public void endElement(String uri, String localName, String qName) {
if (qName.equals("Image")) {
wellCoordinates.put(new Integer(currentField),
new int[] {currentRow, currentCol});
openImage = false;
int well = currentRow * wellCols + currentCol;
Image img = imageFiles[well][currentField][currentImage][currentPlane];
if (img != null) {
img.deltaT = timestamp;
img.exposure = exposure;
}
}
else if (qName.equals("Wavelength")) {
channelName = null;
}
}
public void startElement(String uri, String localName, String qName,
Attributes attributes)
{
currentQName = qName;
for (int i=0; i<attributes.getLength(); i++) {
addGlobalMeta(qName + " - " + attributes.getQName(i),
attributes.getValue(i));
}
if (qName.equals("Microscopy")) {
String experimentID = MetadataTools.createLSID("Experiment", 0);
store.setExperimentID(experimentID, 0);
try {
store.setExperimentType(
getExperimentType(attributes.getValue("type")), 0);
}
catch (FormatException e) {
LOGGER.warn("", e);
}
}
else if (qName.equals("Image")) {
openImage = true;
double time =
Double.parseDouble(attributes.getValue("acquisition_time_ms"));
timestamp = new Double(time / 1000);
}
else if (qName.equals("Identifier")) {
currentField = Integer.parseInt(attributes.getValue("field_index"));
int z = Integer.parseInt(attributes.getValue("z_index"));
int c = Integer.parseInt(attributes.getValue("wave_index"));
int t = Integer.parseInt(attributes.getValue("time_index"));
currentImage = t;
currentPlane = z * getSizeC() + c;
int well = currentRow * wellCols + currentCol;
Image img = imageFiles[well][currentField][currentImage][currentPlane];
img.zPosition = zPosition;
}
else if (qName.equals("FocusPosition")) {
zPosition = new Double(attributes.getValue("z"));
}
else if (qName.equals("Creation")) {
String date = attributes.getValue("date"); // yyyy-mm-dd
String time = attributes.getValue("time"); // hh:mm:ss
creationDate = date + "T" + time;
}
else if (qName.equals("ObjectiveCalibration")) {
int mag =
(int) Double.parseDouble(attributes.getValue("magnification"));
if (mag > 0) {
store.setObjectiveNominalMagnification(
new PositiveInteger(mag), 0, 0);
}
else {
LOGGER.warn(
"Expected positive value for NominalMagnification; got {}", mag);
}
store.setObjectiveLensNA(new Double(
attributes.getValue("numerical_aperture")), 0, 0);
try {
store.setObjectiveImmersion(getImmersion("Other"), 0, 0);
}
catch (FormatException e) {
LOGGER.warn("", e);
}
String objective = attributes.getValue("objective_name");
String[] tokens = objective.split("_");
store.setObjectiveManufacturer(tokens[0], 0, 0);
String correction = tokens.length > 2 ? tokens[2] : "Other";
try {
store.setObjectiveCorrection(getCorrection(correction), 0, 0);
}
catch (FormatException e) {
LOGGER.warn("", e);
}
Double pixelSizeX = new Double(attributes.getValue("pixel_width"));
Double pixelSizeY = new Double(attributes.getValue("pixel_height"));
Double refractive = new Double(attributes.getValue("refractive_index"));
// link Objective to Image
String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
store.setObjectiveID(objectiveID, 0, 0);
for (int i=0; i<getSeriesCount(); i++) {
store.setObjectiveSettingsID(objectiveID, i);
store.setObjectiveSettingsRefractiveIndex(refractive, i);
if (pixelSizeX > 0) {
store.setPixelsPhysicalSizeX(new PositiveFloat(pixelSizeX), i);
}
else {
LOGGER.warn("Expected positive value for PhysicalSizeX; got {}",
pixelSizeX);
}
if (pixelSizeY > 0) {
store.setPixelsPhysicalSizeY(new PositiveFloat(pixelSizeY), i);
}
else {
LOGGER.warn("Expected positive value for PhysicalSizeY; got {}",
pixelSizeY);
}
}
}
else if (qName.equals("ExcitationFilter")) {
String wave = attributes.getValue("wavelength");
if (wave != null) exWaves.add(new Integer(wave));
channelName = attributes.getValue("name");
}
else if (qName.equals("EmissionFilter")) {
String wave = attributes.getValue("wavelength");
if (wave != null) emWaves.add(new Integer(wave));
channelNames.add(attributes.getValue("name"));
}
else if (qName.equals("Camera")) {
store.setDetectorModel(attributes.getValue("name"), 0, 0);
try {
store.setDetectorType(getDetectorType("Other"), 0, 0);
}
catch (FormatException e) {
LOGGER.warn("", e);
}
String detectorID = MetadataTools.createLSID("Detector", 0, 0);
store.setDetectorID(detectorID, 0, 0);
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
for (int q=0; q<getSizeC(); q++) {
store.setDetectorSettingsID(detectorID, i, q);
}
}
setSeries(0);
}
else if (qName.equals("Binning")) {
String binning = attributes.getValue("value");
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
for (int q=0; q<getSizeC(); q++) {
try {
store.setDetectorSettingsBinning(getBinning(binning), i, q);
}
catch (FormatException e) { }
}
}
setSeries(0);
}
else if (qName.equals("Gain")) {
String value = attributes.getValue("value");
if (value == null) {
return;
}
try {
Double gain = new Double(value);
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
for (int q=0; q<getSizeC(); q++) {
store.setDetectorSettingsGain(gain, i, q);
}
}
setSeries(0);
}
catch (NumberFormatException e) {
LOGGER.debug("Could not parse gain '" + value + "'", e);
}
}
else if (qName.equals("PlateTemperature")) {
Double temperature = new Double(attributes.getValue("value"));
for (int i=0; i<getSeriesCount(); i++) {
store.setImagingEnvironmentTemperature(temperature, i);
}
}
else if (qName.equals("Plate")) {
nextPlate++;
}
else if (qName.equals("Row")) {
currentRow = Integer.parseInt(attributes.getValue("number")) - 1;
}
else if (qName.equals("Column")) {
currentCol = Integer.parseInt(attributes.getValue("number")) - 1;
}
else if (qName.equals("Exposure") && openImage) {
double exp = Double.parseDouble(attributes.getValue("time"));
exposure = new Double(exp / 1000);
}
else if (qName.equals("offset_point")) {
String x = attributes.getValue("x");
String y = attributes.getValue("y");
posX.add(new Double(x));
posY.add(new Double(y));
addGlobalMeta("X position for position #" + posX.size(), x);
addGlobalMeta("Y position for position #" + posY.size(), y);
}
}
}
class Image {
public String filename;
public String thumbnailFile;
public boolean isTiff;
public Double deltaT, exposure;
public Double zPosition;
}
} |
// LeicaHandler.java
package loci.formats.in;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Vector;
import loci.common.DateTools;
import loci.formats.CoreMetadata;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import ome.xml.model.enums.Correction;
import ome.xml.model.enums.DetectorType;
import ome.xml.model.enums.EnumerationException;
import ome.xml.model.enums.Immersion;
import ome.xml.model.enums.LaserMedium;
import ome.xml.model.enums.LaserType;
import ome.xml.model.enums.MicroscopeType;
import ome.xml.model.enums.handlers.CorrectionEnumHandler;
import ome.xml.model.enums.handlers.DetectorTypeEnumHandler;
import ome.xml.model.enums.handlers.ImmersionEnumHandler;
import ome.xml.model.enums.handlers.LaserMediumEnumHandler;
import ome.xml.model.enums.handlers.LaserTypeEnumHandler;
import ome.xml.model.enums.handlers.MicroscopeTypeEnumHandler;
import ome.xml.model.primitives.NonNegativeInteger;
import ome.xml.model.primitives.PercentFraction;
import ome.xml.model.primitives.PositiveInteger;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
public class LeicaHandler extends DefaultHandler {
// -- Fields --
private Stack<String> nameStack = new Stack<String>();
private String elementName, collection;
private int count = 0, numChannels, extras = 1;
private Vector<String> lutNames;
private Vector<Double> xPos, yPos, zPos;
private double physicalSizeX, physicalSizeY;
private int numDatasets = -1;
private Hashtable globalMetadata;
private MetadataStore store;
private int nextChannel = 0;
private Double zoom, pinhole;
private Vector<Integer> detectorIndices;
private String filterWheelName;
private int nextFilter = 0;
private int nextROI = 0;
private ROI roi;
private boolean alternateCenter = false;
private boolean linkedInstruments = false;
private int detectorChannel = 0;
private Vector<CoreMetadata> core;
private boolean canParse = true;
private long firstStamp = 0;
private Hashtable<Integer, String> bytesPerAxis;
private Vector<MultiBand> multiBands = new Vector<MultiBand>();
private Vector<Detector> detectors = new Vector<Detector>();
private Vector<Laser> lasers = new Vector<Laser>();
private Hashtable<String, Channel> channels =
new Hashtable<String, Channel>();
private MetadataLevel level;
private int laserCount = 0;
// -- Constructor --
public LeicaHandler(MetadataStore store, MetadataLevel level) {
super();
globalMetadata = new Hashtable();
lutNames = new Vector<String>();
this.store = store;
core = new Vector<CoreMetadata>();
detectorIndices = new Vector<Integer>();
xPos = new Vector<Double>();
yPos = new Vector<Double>();
zPos = new Vector<Double>();
bytesPerAxis = new Hashtable<Integer, String>();
this.level = level;
}
// -- LeicaHandler API methods --
public Vector<CoreMetadata> getCoreMetadata() { return core; }
public Hashtable getGlobalMetadata() { return globalMetadata; }
public Vector<String> getLutNames() { return lutNames; }
// -- DefaultHandler API methods --
public void endElement(String uri, String localName, String qName) {
if (!nameStack.empty() && nameStack.peek().equals(qName)) nameStack.pop();
if (qName.equals("ImageDescription")) {
CoreMetadata coreMeta = core.get(numDatasets);
if (numChannels == 0) numChannels = 1;
coreMeta.sizeC = numChannels;
if (extras > 1) {
if (coreMeta.sizeZ == 1) coreMeta.sizeZ = extras;
else {
if (coreMeta.sizeT == 0) coreMeta.sizeT = extras;
else coreMeta.sizeT *= extras;
}
}
if (coreMeta.sizeX == 0 && coreMeta.sizeY == 0) {
if (numDatasets > 0) numDatasets
}
else {
if (coreMeta.sizeX == 0) coreMeta.sizeX = 1;
if (coreMeta.sizeZ == 0) coreMeta.sizeZ = 1;
if (coreMeta.sizeT == 0) coreMeta.sizeT = 1;
coreMeta.orderCertain = true;
coreMeta.metadataComplete = true;
coreMeta.littleEndian = true;
coreMeta.interleaved = coreMeta.rgb;
coreMeta.imageCount = coreMeta.sizeZ * coreMeta.sizeT;
if (!coreMeta.rgb) coreMeta.imageCount *= coreMeta.sizeC;
coreMeta.indexed = !coreMeta.rgb;
coreMeta.falseColor = true;
Integer[] bytes = bytesPerAxis.keySet().toArray(new Integer[0]);
Arrays.sort(bytes);
coreMeta.dimensionOrder = "XY";
for (Integer nBytes : bytes) {
String axis = bytesPerAxis.get(nBytes);
if (coreMeta.dimensionOrder.indexOf(axis) == -1) {
coreMeta.dimensionOrder += axis;
}
}
String[] axes = new String[] {"Z", "C", "T"};
for (String axis : axes) {
if (coreMeta.dimensionOrder.indexOf(axis) == -1) {
coreMeta.dimensionOrder += axis;
}
}
core.setElementAt(coreMeta, numDatasets);
}
if (level != MetadataLevel.MINIMUM) {
int nChannels = coreMeta.rgb ? 0 : numChannels;
for (int c=0; c<nChannels; c++) {
store.setChannelPinholeSize(pinhole, numDatasets, c);
}
for (int i=0; i<xPos.size(); i++) {
for (int image=0; image<coreMeta.imageCount; image++) {
store.setPlanePositionX(xPos.get(i), numDatasets, image);
store.setPlanePositionY(yPos.get(i), numDatasets, image);
store.setPlanePositionZ(zPos.get(i), numDatasets, image);
}
}
for (int c=0; c<nChannels; c++) {
int index = c < detectorIndices.size() ?
detectorIndices.get(c).intValue() : detectorIndices.size() - 1;
if (index < 0 || index >= nChannels || index >= 0) break;
String id = MetadataTools.createLSID("Detector", numDatasets, index);
store.setDetectorSettingsID(id, numDatasets, c);
}
String[] keys = channels.keySet().toArray(new String[0]);
Arrays.sort(keys);
for (int c=0; c<keys.length; c++) {
Channel ch = channels.get(keys[c]);
store.setDetectorSettingsID(ch.detector, numDatasets, c);
store.setChannelExcitationWavelength(ch.exWave, numDatasets, c);
store.setChannelName(ch.name, numDatasets, c);
store.setDetectorSettingsGain(ch.gain, numDatasets, c);
}
}
channels.clear();
xPos.clear();
yPos.clear();
zPos.clear();
detectorIndices.clear();
}
else if (qName.equals("Element") && level != MetadataLevel.MINIMUM) {
multiBands.clear();
nextROI = 0;
if (numDatasets >= 0) {
int nChannels = core.get(numDatasets).rgb ? 1 : numChannels;
for (int c=0; c<detectorIndices.size(); c++) {
int index = detectorIndices.get(c).intValue();
if (c >= nChannels || index >= nChannels || index >= 0) break;
String id = MetadataTools.createLSID("Detector", numDatasets, index);
store.setDetectorSettingsID(id, numDatasets, index);
}
for (int c=0; c<nChannels; c++) {
store.setChannelPinholeSize(pinhole, numDatasets, c);
}
}
}
else if (qName.equals("Image")) {
nextChannel = 0;
}
else if (qName.equals("LDM_Block_Sequential_Master")) {
canParse = true;
}
else if (qName.equals("Annotation") && level != MetadataLevel.MINIMUM) {
roi.storeROI(store, numDatasets, nextROI++);
}
}
public void startElement(String uri, String localName, String qName,
Attributes attributes)
{
if (attributes.getLength() > 0 && !qName.equals("Element") &&
!qName.equals("Attachment") && !qName.equals("LMSDataContainerHeader"))
{
nameStack.push(qName);
}
int oldSeriesCount = numDatasets;
Hashtable h = getSeriesHashtable(numDatasets);
if (qName.equals("LDM_Block_Sequential_Master")) {
canParse = false;
}
else if (qName.startsWith("LDM")) {
linkedInstruments = true;
}
if (!canParse) return;
StringBuffer key = new StringBuffer();
for (String k : nameStack) {
key.append(k);
key.append("|");
}
String suffix = attributes.getValue("Identifier");
String value = attributes.getValue("Variant");
if (suffix == null) suffix = attributes.getValue("Description");
if (level != MetadataLevel.MINIMUM) {
if (suffix != null && value != null) {
storeKeyValue(h, key.toString() + suffix, value);
}
else {
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
storeKeyValue(h, key.toString() + name, attributes.getValue(i));
}
}
}
if (qName.equals("Element")) {
elementName = attributes.getValue("Name");
}
else if (qName.equals("Collection")) {
collection = elementName;
}
else if (qName.equals("Image")) {
if (!linkedInstruments && level != MetadataLevel.MINIMUM) {
int c = 0;
for (Detector d : detectors) {
String id = MetadataTools.createLSID(
"Detector", numDatasets, detectorChannel);
store.setDetectorID(id, numDatasets, detectorChannel);
try {
DetectorTypeEnumHandler handler = new DetectorTypeEnumHandler();
store.setDetectorType((DetectorType) handler.getEnumeration(d.type),
numDatasets, detectorChannel);
}
catch (EnumerationException e) { }
store.setDetectorModel(d.model, numDatasets, detectorChannel);
store.setDetectorZoom(d.zoom, numDatasets, detectorChannel);
store.setDetectorOffset(d.offset, numDatasets, detectorChannel);
store.setDetectorVoltage(d.voltage, numDatasets, detectorChannel);
if (c < numChannels) {
if (d.active) {
store.setDetectorSettingsOffset(d.offset, numDatasets, c);
store.setDetectorSettingsID(id, numDatasets, c);
c++;
}
}
detectorChannel++;
}
int filter = 0;
for (int i=0; i<nextFilter; i++) {
while (filter < detectors.size() && !detectors.get(filter).active) {
filter++;
}
if (filter >= detectors.size() || filter >= nextFilter) break;
String id = MetadataTools.createLSID("Filter", numDatasets, filter);
if (i < numChannels && detectors.get(filter).active) {
String lsid = MetadataTools.createLSID("Channel", numDatasets, i);
store.setChannelID(lsid, numDatasets, i);
store.setLightPathEmissionFilterRef(id, numDatasets, i, 0);
}
filter++;
}
}
core.add(new CoreMetadata());
numDatasets++;
laserCount = 0;
linkedInstruments = false;
detectorChannel = 0;
detectors.clear();
lasers.clear();
nextFilter = 0;
String name = elementName;
if (collection != null) name = collection + "/" + name;
store.setImageName(name, numDatasets);
String instrumentID = MetadataTools.createLSID("Instrument", numDatasets);
store.setInstrumentID(instrumentID, numDatasets);
store.setImageInstrumentRef(instrumentID, numDatasets);
numChannels = 0;
extras = 1;
}
else if (qName.equals("Attachment") && level != MetadataLevel.MINIMUM) {
if ("ContextDescription".equals(attributes.getValue("Name"))) {
store.setImageDescription(attributes.getValue("Content"), numDatasets);
}
}
else if (qName.equals("ChannelDescription")) {
count++;
numChannels++;
lutNames.add(attributes.getValue("LUTName"));
String bytesInc = attributes.getValue("BytesInc");
int bytes = bytesInc == null ? 0 : Integer.parseInt(bytesInc);
if (bytes > 0) {
bytesPerAxis.put(new Integer(bytes), "C");
}
}
else if (qName.equals("DimensionDescription")) {
int len = Integer.parseInt(attributes.getValue("NumberOfElements"));
int id = Integer.parseInt(attributes.getValue("DimID"));
double physicalLen = Double.parseDouble(attributes.getValue("Length"));
String unit = attributes.getValue("Unit");
int nBytes = Integer.parseInt(attributes.getValue("BytesInc"));
physicalLen /= len;
if (unit.equals("Ks")) {
physicalLen /= 1000;
}
else if (unit.equals("m")) {
physicalLen *= 1000000;
}
Double physicalSize = new Double(physicalLen);
CoreMetadata coreMeta = core.get(core.size() - 1);
switch (id) {
case 1: // X axis
coreMeta.sizeX = len;
coreMeta.rgb = (nBytes % 3) == 0;
if (coreMeta.rgb) nBytes /= 3;
switch (nBytes) {
case 1:
coreMeta.pixelType = FormatTools.UINT8;
break;
case 2:
coreMeta.pixelType = FormatTools.UINT16;
break;
case 4:
coreMeta.pixelType = FormatTools.FLOAT;
break;
}
physicalSizeX = physicalSize.doubleValue();
store.setPixelsPhysicalSizeX(physicalSize, numDatasets);
break;
case 2: // Y axis
if (coreMeta.sizeY != 0) {
if (coreMeta.sizeZ == 1) {
coreMeta.sizeZ = len;
bytesPerAxis.put(new Integer(nBytes), "Z");
}
else if (coreMeta.sizeT == 1) {
coreMeta.sizeT = len;
bytesPerAxis.put(new Integer(nBytes), "T");
}
}
else {
coreMeta.sizeY = len;
physicalSizeY = physicalSize.doubleValue();
store.setPixelsPhysicalSizeY(physicalSize, numDatasets);
}
break;
case 3: // Z axis
if (coreMeta.sizeY == 0) {
// XZ scan - swap Y and Z
coreMeta.sizeY = len;
coreMeta.sizeZ = 1;
physicalSizeY = physicalSize.doubleValue();
store.setPixelsPhysicalSizeY(physicalSize, numDatasets);
bytesPerAxis.put(new Integer(nBytes), "Y");
}
else {
coreMeta.sizeZ = len;
bytesPerAxis.put(new Integer(nBytes), "Z");
}
break;
case 4: // T axis
if (coreMeta.sizeY == 0) {
// XT scan - swap Y and T
coreMeta.sizeY = len;
coreMeta.sizeT = 1;
physicalSizeY = physicalSize.doubleValue();
store.setPixelsPhysicalSizeY(physicalSize, numDatasets);
bytesPerAxis.put(new Integer(nBytes), "Y");
}
else {
coreMeta.sizeT = len;
bytesPerAxis.put(new Integer(nBytes), "T");
}
break;
default:
extras *= len;
}
count++;
}
else if (qName.equals("ScannerSettingRecord") &&
level != MetadataLevel.MINIMUM)
{
String id = attributes.getValue("Identifier");
if (id == null) id = "";
if (id.equals("SystemType")) {
store.setMicroscopeModel(value, numDatasets);
store.setMicroscopeType(MicroscopeType.OTHER, numDatasets);
}
else if (id.equals("dblPinhole")) {
pinhole = new Double(Double.parseDouble(value) * 1000000);
}
else if (id.equals("dblZoom")) {
zoom = new Double(value);
}
else if (id.equals("dblStepSize")) {
double zStep = Double.parseDouble(value) * 1000000;
store.setPixelsPhysicalSizeZ(zStep, numDatasets);
}
else if (id.equals("nDelayTime_s")) {
store.setPixelsTimeIncrement(new Double(value), numDatasets);
}
else if (id.equals("CameraName")) {
store.setDetectorModel(value, numDatasets, 0);
}
else if (id.indexOf("WFC") == 1) {
int c = 0;
try {
c = Integer.parseInt(id.replaceAll("\\D", ""));
}
catch (NumberFormatException e) { }
Channel channel = channels.get(numDatasets + "-" + c);
if (channel == null) channel = new Channel();
if (id.endsWith("ExposureTime")) {
store.setPlaneExposureTime(new Double(value), numDatasets, c);
}
else if (id.endsWith("Gain")) {
channel.gain = new Double(value);
String detectorID =
MetadataTools.createLSID("Detector", numDatasets, 0);
channel.detector = detectorID;
store.setDetectorID(detectorID, numDatasets, 0);
store.setDetectorType(DetectorType.CCD, numDatasets, 0);
}
else if (id.endsWith("WaveLength")) {
Integer exWave = new Integer(value);
if (exWave > 0) {
channel.exWave = new PositiveInteger(exWave);
}
}
// NB: "UesrDefName" is not a typo.
else if (id.endsWith("UesrDefName") && !value.equals("None")) {
channel.name = value;
}
channels.put(numDatasets + "-" + c, channel);
}
}
else if (qName.equals("FilterSettingRecord") &&
level != MetadataLevel.MINIMUM)
{
String object = attributes.getValue("ObjectName");
String attribute = attributes.getValue("Attribute");
String objectClass = attributes.getValue("ClassName");
String variant = attributes.getValue("Variant");
CoreMetadata coreMeta = core.get(numDatasets);
if (attribute.equals("NumericalAperture")) {
store.setObjectiveLensNA(new Double(variant), numDatasets, 0);
}
else if (attribute.equals("OrderNumber")) {
store.setObjectiveSerialNumber(variant, numDatasets, 0);
}
else if (objectClass.equals("CDetectionUnit")) {
if (attribute.equals("State")) {
Detector d = new Detector();
String data = attributes.getValue("data");
if (data == null) data = attributes.getValue("Data");
d.channel = data == null ? 0 : Integer.parseInt(data);
d.type = "PMT";
d.model = object;
d.active = variant.equals("Active");
d.zoom = zoom;
detectors.add(d);
}
else if (attribute.equals("HighVoltage")) {
Detector d = detectors.get(detectors.size() - 1);
d.voltage = new Double(variant);
}
else if (attribute.equals("VideoOffset")) {
Detector d = detectors.get(detectors.size() - 1);
d.offset = new Double(variant);
}
}
else if (attribute.equals("Objective")) {
StringTokenizer tokens = new StringTokenizer(variant, " ");
boolean foundMag = false;
StringBuffer model = new StringBuffer();
while (!foundMag) {
String token = tokens.nextToken();
int x = token.indexOf("x");
if (x != -1) {
foundMag = true;
int mag = (int) Double.parseDouble(token.substring(0, x));
String na = token.substring(x + 1);
store.setObjectiveNominalMagnification(
new PositiveInteger(mag), numDatasets, 0);
store.setObjectiveLensNA(new Double(na), numDatasets, 0);
}
else {
model.append(token);
model.append(" ");
}
}
String immersion = "Other";
if (tokens.hasMoreTokens()) {
immersion = tokens.nextToken();
if (immersion == null || immersion.trim().equals("")) {
immersion = "Other";
}
}
try {
ImmersionEnumHandler handler = new ImmersionEnumHandler();
store.setObjectiveImmersion(
(Immersion) handler.getEnumeration(immersion), numDatasets, 0);
}
catch (EnumerationException e) { }
String correction = "Other";
if (tokens.hasMoreTokens()) {
correction = tokens.nextToken();
if (correction == null || correction.trim().equals("")) {
correction = "Other";
}
}
try {
CorrectionEnumHandler handler = new CorrectionEnumHandler();
store.setObjectiveCorrection(
(Correction) handler.getEnumeration(correction), numDatasets, 0);
}
catch (EnumerationException e) { }
store.setObjectiveModel(model.toString().trim(), numDatasets, 0);
}
else if (attribute.equals("RefractionIndex")) {
String id = MetadataTools.createLSID("Objective", numDatasets, 0);
store.setObjectiveID(id, numDatasets, 0);
store.setImageObjectiveSettingsID(id, numDatasets);
store.setImageObjectiveSettingsRefractiveIndex(new Double(variant),
numDatasets);
}
else if (attribute.equals("XPos")) {
int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
int nPlanes = coreMeta.imageCount;
Double posX = new Double(variant);
for (int image=0; image<nPlanes; image++) {
store.setPlanePositionX(posX, numDatasets, image);
}
if (numChannels == 0) xPos.add(posX);
}
else if (attribute.equals("YPos")) {
int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
int nPlanes = coreMeta.imageCount;
Double posY = new Double(variant);
for (int image=0; image<nPlanes; image++) {
store.setPlanePositionY(posY, numDatasets, image);
}
if (numChannels == 0) yPos.add(posY);
}
else if (attribute.equals("ZPos")) {
int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
int nPlanes = coreMeta.imageCount;
Double posZ = new Double(variant);
for (int image=0; image<nPlanes; image++) {
store.setPlanePositionZ(posZ, numDatasets, image);
}
if (numChannels == 0) zPos.add(posZ);
}
else if (objectClass.equals("CSpectrophotometerUnit")) {
Integer v = null;
try {
v = new Integer((int) Double.parseDouble(variant));
}
catch (NumberFormatException e) { }
if (attributes.getValue("Description").endsWith("(left)")) {
String id =
MetadataTools.createLSID("Filter", numDatasets, nextFilter);
store.setFilterID(id, numDatasets, nextFilter);
store.setFilterModel(object, numDatasets, nextFilter);
if (v != null) {
store.setTransmittanceRangeCutIn(
new PositiveInteger(v), numDatasets, nextFilter);
}
}
else if (attributes.getValue("Description").endsWith("(right)")) {
if (v != null) {
store.setTransmittanceRangeCutOut(
new PositiveInteger(v), numDatasets, nextFilter);
nextFilter++;
}
}
}
}
else if (qName.equals("Detector") && level != MetadataLevel.MINIMUM) {
String v = attributes.getValue("Gain");
Double gain = v == null ? null : new Double(v);
v = attributes.getValue("Offset");
Double offset = v == null ? null : new Double(v);
boolean active = "1".equals(attributes.getValue("IsActive"));
if (active) {
// find the corresponding MultiBand and Detector
MultiBand m = null;
Detector detector = null;
Laser laser = lasers.size() == 0 ? null : lasers.get(lasers.size() - 1);
String c = attributes.getValue("Channel");
int channel = c == null ? 0 : Integer.parseInt(c);
for (MultiBand mb : multiBands) {
if (mb.channel == channel) {
m = mb;
break;
}
}
for (Detector d : detectors) {
if (d.channel == channel) {
detector = d;
break;
}
}
String id =
MetadataTools.createLSID("Detector", numDatasets, nextChannel);
if (m != null) {
String channelID = MetadataTools.createLSID(
"Channel", numDatasets, nextChannel);
store.setChannelID(channelID, numDatasets, nextChannel);
store.setChannelName(m.dyeName, numDatasets, nextChannel);
String filter =
MetadataTools.createLSID("Filter", numDatasets, nextFilter);
store.setFilterID(filter, numDatasets, nextFilter);
store.setTransmittanceRangeCutIn(
new PositiveInteger(m.cutIn), numDatasets, nextFilter);
store.setTransmittanceRangeCutOut(
new PositiveInteger(m.cutOut), numDatasets, nextFilter);
store.setLightPathEmissionFilterRef(
filter, numDatasets, nextChannel, 0);
nextFilter++;
store.setDetectorID(id, numDatasets, nextChannel);
store.setDetectorType(DetectorType.PMT, numDatasets, nextChannel);
store.setDetectorSettingsGain(gain, numDatasets, nextChannel);
store.setDetectorSettingsOffset(offset, numDatasets, nextChannel);
store.setDetectorSettingsID(id, numDatasets, nextChannel);
}
store.setDetectorID(id, numDatasets, nextChannel);
if (detector != null) {
store.setDetectorSettingsGain(gain, numDatasets, nextChannel);
store.setDetectorSettingsOffset(offset, numDatasets, nextChannel);
store.setDetectorSettingsID(id, numDatasets, nextChannel);
try {
DetectorTypeEnumHandler handler = new DetectorTypeEnumHandler();
store.setDetectorType(
(DetectorType) handler.getEnumeration(detector.type),
numDatasets, nextChannel);
}
catch (EnumerationException e) { }
store.setDetectorModel(detector.model, numDatasets, nextChannel);
store.setDetectorZoom(detector.zoom, numDatasets, nextChannel);
store.setDetectorOffset(detector.offset, numDatasets, nextChannel);
store.setDetectorVoltage(detector.voltage, numDatasets, nextChannel);
}
if (laser != null && laser.intensity < 100) {
store.setChannelLightSourceSettingsID(laser.id, numDatasets,
nextChannel);
store.setChannelLightSourceSettingsAttenuation(
new PercentFraction((float) laser.intensity / 100f),
numDatasets, nextChannel);
store.setChannelExcitationWavelength(
new PositiveInteger(laser.wavelength), numDatasets, nextChannel);
}
nextChannel++;
}
}
else if (qName.equals("LaserLineSetting") && level != MetadataLevel.MINIMUM)
{
Laser l = new Laser();
String lineIndex = attributes.getValue("LineIndex");
String qual = attributes.getValue("Qualifier");
l.index = lineIndex == null ? 0 : Integer.parseInt(lineIndex);
int qualifier = qual == null ? 0 : Integer.parseInt(qual);
l.index += (2 - (qualifier / 10));
if (l.index < 0) l.index = 0;
l.id = MetadataTools.createLSID("LightSource", numDatasets, l.index);
l.wavelength = new Integer(attributes.getValue("LaserLine"));
while (l.index > laserCount) {
String lsid =
MetadataTools.createLSID("LightSource", numDatasets, laserCount);
store.setLaserID(lsid, numDatasets, laserCount);
laserCount++;
}
store.setLaserID(l.id, numDatasets, l.index);
laserCount++;
if (l.wavelength > 0) {
store.setLaserWavelength(
new PositiveInteger(l.wavelength), numDatasets, l.index);
}
store.setLaserType(LaserType.OTHER, numDatasets, l.index);
store.setLaserLaserMedium(LaserMedium.OTHER, numDatasets, l.index);
String intensity = attributes.getValue("IntensityDev");
l.intensity = intensity == null ? 0d : Double.parseDouble(intensity);
if (l.intensity > 0) {
l.intensity = 100d - l.intensity;
lasers.add(l);
}
}
else if (qName.equals("TimeStamp") && numDatasets >= 0) {
String stampHigh = attributes.getValue("HighInteger");
String stampLow = attributes.getValue("LowInteger");
long high = stampHigh == null ? 0 : Long.parseLong(stampHigh);
long low = stampLow == null ? 0 : Long.parseLong(stampLow);
long ms = DateTools.getMillisFromTicks(high, low);
if (count == 0) {
String date = DateTools.convertDate(ms, DateTools.COBOL);
if (DateTools.getTime(date, DateTools.ISO8601_FORMAT) <
System.currentTimeMillis())
{
store.setImageAcquiredDate(date, numDatasets);
}
firstStamp = ms;
store.setPlaneDeltaT(0.0, numDatasets, count);
}
else if (level != MetadataLevel.MINIMUM) {
CoreMetadata coreMeta = core.get(numDatasets);
int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC;
if (count < nImages) {
ms -= firstStamp;
store.setPlaneDeltaT(ms / 1000.0, numDatasets, count);
}
}
count++;
}
else if (qName.equals("RelTimeStamp") && level != MetadataLevel.MINIMUM) {
CoreMetadata coreMeta = core.get(numDatasets);
int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC;
if (count < nImages) {
Double time = new Double(attributes.getValue("Time"));
store.setPlaneDeltaT(time, numDatasets, count++);
}
}
else if (qName.equals("Annotation") && level != MetadataLevel.MINIMUM) {
roi = new ROI();
String type = attributes.getValue("type");
if (type != null) roi.type = Integer.parseInt(type);
String color = attributes.getValue("color");
if (color != null) roi.color = Integer.parseInt(color);
roi.name = attributes.getValue("name");
roi.fontName = attributes.getValue("fontName");
roi.fontSize = attributes.getValue("fontSize");
roi.transX = parseDouble(attributes.getValue("transTransX"));
roi.transY = parseDouble(attributes.getValue("transTransY"));
roi.scaleX = parseDouble(attributes.getValue("transScalingX"));
roi.scaleY = parseDouble(attributes.getValue("transScalingY"));
roi.rotation = parseDouble(attributes.getValue("transRotation"));
String linewidth = attributes.getValue("linewidth");
if (linewidth != null) roi.linewidth = Integer.parseInt(linewidth);
roi.text = attributes.getValue("text");
}
else if (qName.equals("Vertex") && level != MetadataLevel.MINIMUM) {
String x = attributes.getValue("x");
String y = attributes.getValue("y");
if (x != null) {
x = x.replaceAll(",", ".");
roi.x.add(new Double(x));
}
if (y != null) {
y = y.replaceAll(",", ".");
roi.y.add(new Double(y));
}
}
else if (qName.equals("ROI")) {
alternateCenter = true;
}
else if (qName.equals("MultiBand") && level != MetadataLevel.MINIMUM) {
MultiBand m = new MultiBand();
m.dyeName = attributes.getValue("DyeName");
m.channel = Integer.parseInt(attributes.getValue("Channel"));
m.cutIn = (int)
Math.round(Double.parseDouble(attributes.getValue("LeftWorld")));
m.cutOut = (int)
Math.round(Double.parseDouble(attributes.getValue("RightWorld")));
multiBands.add(m);
}
else if (qName.equals("ChannelInfo")) {
int index = Integer.parseInt(attributes.getValue("Index"));
channels.remove(numDatasets + "-" + index);
}
else count = 0;
if (numDatasets == oldSeriesCount) storeSeriesHashtable(numDatasets, h);
}
// -- Helper methods --
private Hashtable getSeriesHashtable(int series) {
if (series < 0 || series >= core.size()) return new Hashtable();
return core.get(series).seriesMetadata;
}
private void storeSeriesHashtable(int series, Hashtable h) {
if (series < 0) return;
Object[] keys = h.keySet().toArray(new Object[h.size()]);
for (Object key : keys) {
Object value = h.get(key);
if (value instanceof Vector) {
Vector v = (Vector) value;
for (int o=0; o<v.size(); o++) {
h.put(key + " " + (o + 1), v.get(o));
}
h.remove(key);
}
}
CoreMetadata coreMeta = core.get(series);
coreMeta.seriesMetadata = h;
core.setElementAt(coreMeta, series);
}
// -- Helper class --
class ROI {
// -- Constants --
public static final int TEXT = 512;
public static final int SCALE_BAR = 8192;
public static final int POLYGON = 32;
public static final int RECTANGLE = 16;
public static final int LINE = 256;
public static final int ARROW = 2;
// -- Fields --
public int type;
public Vector<Double> x = new Vector<Double>();
public Vector<Double> y = new Vector<Double>();
// center point of the ROI
public double transX, transY;
// transformation parameters
public double scaleX, scaleY;
public double rotation;
public int color;
public int linewidth;
public String text;
public String fontName;
public String fontSize;
public String name;
private boolean normalized = false;
// -- ROI API methods --
public void storeROI(MetadataStore store, int series, int roi) {
if (level == MetadataLevel.NO_OVERLAYS || level == MetadataLevel.MINIMUM)
{
return;
}
// keep in mind that vertices are given relative to the center
// point of the ROI and the transX/transY values are relative to
// the center point of the image
store.setROIID(MetadataTools.createLSID("ROI", roi), roi);
store.setTextID(MetadataTools.createLSID("Shape", roi, 0), roi, 0);
if (text == null) text = "";
store.setTextValue(text, roi, 0);
if (fontSize != null) {
store.setTextFontSize(
new NonNegativeInteger((int) Double.parseDouble(fontSize)), roi, 0);
}
store.setTextStrokeWidth(new Double(linewidth), roi, 0);
if (!normalized) normalize();
double cornerX = x.get(0).doubleValue();
double cornerY = y.get(0).doubleValue();
store.setTextX(cornerX, roi, 0);
store.setTextY(cornerY, roi, 0);
int centerX = (core.get(series).sizeX / 2) - 1;
int centerY = (core.get(series).sizeY / 2) - 1;
double roiX = centerX + transX;
double roiY = centerY + transY;
if (alternateCenter) {
roiX = transX - 2 * cornerX;
roiY = transY - 2 * cornerY;
}
// TODO : rotation/scaling not populated
String shapeID = MetadataTools.createLSID("Shape", roi, 1);
switch (type) {
case POLYGON:
StringBuffer points = new StringBuffer();
for (int i=0; i<x.size(); i++) {
points.append(x.get(i).doubleValue() + roiX);
points.append(",");
points.append(y.get(i).doubleValue() + roiY);
if (i < x.size() - 1) points.append(" ");
}
store.setPolylineID(shapeID, roi, 1);
store.setPolylinePoints(points.toString(), roi, 1);
store.setPolylineClosed(Boolean.TRUE, roi, 1);
break;
case TEXT:
case RECTANGLE:
store.setRectangleID(shapeID, roi, 1);
store.setRectangleX(roiX - Math.abs(cornerX), roi, 1);
store.setRectangleY(roiY - Math.abs(cornerY), roi, 1);
double width = 2 * Math.abs(cornerX);
double height = 2 * Math.abs(cornerY);
store.setRectangleWidth(width, roi, 1);
store.setRectangleHeight(height, roi, 1);
break;
case SCALE_BAR:
case ARROW:
case LINE:
store.setLineID(shapeID, roi, 1);
store.setLineX1(roiX + x.get(0), roi, 1);
store.setLineY1(roiY + y.get(0), roi, 1);
store.setLineX2(roiX + x.get(1), roi, 1);
store.setLineY2(roiY + y.get(1), roi, 1);
break;
}
}
// -- Helper methods --
/**
* Vertices and transformation values are not stored in pixel coordinates.
* We need to convert them from physical coordinates to pixel coordinates
* so that they can be stored in a MetadataStore.
*/
private void normalize() {
if (normalized) return;
// coordinates are in meters
transX *= 1000000;
transY *= 1000000;
transX *= (1 / physicalSizeX);
transY *= (1 / physicalSizeY);
for (int i=0; i<x.size(); i++) {
double coordinate = x.get(i).doubleValue() * 1000000;
coordinate *= (1 / physicalSizeX);
x.setElementAt(coordinate, i);
}
for (int i=0; i<y.size(); i++) {
double coordinate = y.get(i).doubleValue() * 1000000;
coordinate *= (1 / physicalSizeY);
y.setElementAt(coordinate, i);
}
normalized = true;
}
}
private double parseDouble(String number) {
if (number != null) {
number = number.replaceAll(",", ".");
return Double.parseDouble(number);
}
return 0;
}
private void storeKeyValue(Hashtable h, String key, String value) {
if (h.get(key) == null) {
h.put(key, value);
}
else {
Object oldValue = h.get(key);
if (oldValue instanceof Vector) {
Vector values = (Vector) oldValue;
values.add(value);
h.put(key, values);
}
else {
Vector values = new Vector();
values.add(oldValue);
values.add(value);
h.put(key, values);
}
}
}
// -- Helper classes --
class MultiBand {
public int channel;
public int cutIn;
public int cutOut;
public String dyeName;
}
class Detector {
public int channel;
public Double zoom;
public String type;
public String model;
public boolean active;
public Double voltage;
public Double offset;
}
class Laser {
public Integer wavelength;
public double intensity;
public String id;
public int index;
}
class Channel {
public String detector;
public Double gain;
public PositiveInteger exWave;
public String name;
}
} |
package com.vikram.configuration;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.internal.StaticCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.vikram.db.KeyValueStore;
import com.vikram.db.awsdynamodb.AwsDynamoDBKeyValueStore;
import com.vikram.openconnect.login.input.ICredentialInput;
import com.vikram.openconnect.login.input.IOAuthCredentials;
import com.vikram.openconnect.login.input.OAuthCredentials;
import com.vikram.openconnect.login.providers.OAuthProvider;
@Configuration
@ComponentScan("com.vikram.web")
@EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) { |
import gov.nih.nci.system.applicationservice.*;
import java.util.*;
import gov.nih.nci.cabio.domain.*;
import gov.nih.nci.cabio.domain.impl.*;
import gov.nih.nci.common.util.*;
import gov.nih.nci.system.comm.client.*;
import org.hibernate.criterion.*;
/**
* TestClient.java demonstrates various ways to execute searches with and without
* using Application Service Layer (convenience layer that abstracts building criteria
* Uncomment different scenarios below to demonstrate the various types of searches
*/
public class TestSecurity {
public static void main(String[] args) {
System.out.println("*** Test Secured Client...");
try{
ClientSession session = ClientSession.getInstance();
session.startSession("userId", "password");
ApplicationService appService = ApplicationServiceProvider.getApplicationService();
try {
System.out.println("Retrieving all genes based on symbol=IL*");
Gene gene = new GeneImpl();
gene.setSymbol("IL*");
try {
List resultList = appService.search(Gene.class, gene);
for (Iterator resultsIterator = resultList.iterator(); resultsIterator.hasNext();) {
Gene returnedGene = (Gene) resultsIterator.next();
System.out.println(
"Symbol: " + returnedGene.getSymbol() + "\n" +
"\tTaxon:" + returnedGene.getTaxon().getScientificName() + "\n" +
"\tName " + returnedGene.getTitle() + "\n" +
"");
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (RuntimeException e2) {
e2.printStackTrace();
}
}
catch(Exception ex){
ex.printStackTrace();
System.out.println("Test client throws Exception = "+ ex);
}
}
} |
package net.coobird.thumbnailator;
import static org.junit.Assert.*;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.imageio.ImageIO;
import net.coobird.thumbnailator.builders.BufferedImageBuilder;
import net.coobird.thumbnailator.builders.ThumbnailParameterBuilder;
import net.coobird.thumbnailator.name.Rename;
import net.coobird.thumbnailator.resizers.DefaultResizerFactory;
import net.coobird.thumbnailator.resizers.ResizerFactory;
import net.coobird.thumbnailator.tasks.SourceSinkThumbnailTask;
import net.coobird.thumbnailator.tasks.UnsupportedFormatException;
import net.coobird.thumbnailator.tasks.io.BufferedImageSink;
import net.coobird.thumbnailator.tasks.io.BufferedImageSource;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
/**
* Unit tests for the {@link Thumbnailator} class.
*
* @author coobird
*
*/
@SuppressWarnings("deprecation")
public class ThumbnailatorTest
{
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnailCollections_negativeWidth() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png")
);
Thumbnailator.createThumbnailsAsCollection(
files,
Rename.PREFIX_DOT_THUMBNAIL,
-42,
50
);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnailCollections_negativeHeight() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png")
);
Thumbnailator.createThumbnailsAsCollection(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
-42
);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnailCollections_negativeWidthAndHeight() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png")
);
Thumbnailator.createThumbnailsAsCollection(
files,
Rename.PREFIX_DOT_THUMBNAIL,
-42,
-42
);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct, except
* a) The Collection is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnailCollections_nullCollection() throws IOException
{
try
{
Thumbnailator.createThumbnailsAsCollection(
null,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
fail();
}
catch (NullPointerException e)
{
assertEquals("Collection of Files is null.", e.getMessage());
throw e;
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct, except
* a) The Rename is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnailCollections_nullRename() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png"),
new File("test-resources/Thumbnailator/grid.bmp")
);
try
{
Thumbnailator.createThumbnailsAsCollection(
files,
null,
50,
50
);
fail();
}
catch (NullPointerException e)
{
assertEquals("Rename is null.", e.getMessage());
throw e;
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* a) The Collection is an empty List.
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnailCollections_NoErrors_EmptyList() throws IOException
{
/*
* The files to make thumbnails of -- nothing!
*/
List<File> files = Collections.emptyList();
Collection<File> resultingFiles =
Thumbnailator.createThumbnailsAsCollection(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
assertTrue(resultingFiles.isEmpty());
}
/**
* Test for
* {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* a) The Collection is an empty Set.
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnailCollections_NoErrors_EmptySet() throws IOException
{
/*
* The files to make thumbnails of -- nothing!
*/
Set<File> files = Collections.emptySet();
Thumbnailator.createThumbnailsAsCollection(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
}
/**
* Test for
* {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* 2) All data can be processed correctly.
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnailCollections_NoErrors() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png")
);
/*
* Used to perform clean up.
*/
for (File f : files)
{
String fileName = f.getName();
String newFileName =
Rename.PREFIX_DOT_THUMBNAIL.apply(fileName, null);
new File(f.getParent(), newFileName).deleteOnExit();
}
Collection<File> resultingFiles =
Thumbnailator.createThumbnailsAsCollection(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
/*
* Perform post-execution checks.
*/
Iterator<File> iter = resultingFiles.iterator();
BufferedImage img0 = ImageIO.read(iter.next());
assertEquals(50, img0.getWidth());
assertEquals(50, img0.getHeight());
BufferedImage img1 = ImageIO.read(iter.next());
assertEquals(50, img1.getWidth());
assertEquals(50, img1.getHeight());
assertTrue(!iter.hasNext());
}
/**
* Test for
* {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* 2) A file that was specified does not exist
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
*
* @throws IOException
*/
@Test(expected=IOException.class)
public void testCreateThumbnailCollections_ErrorDuringProcessing_FileNotFound() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png"),
new File("test-resources/Thumbnailator/grid.bmp"),
new File("test-resources/Thumbnailator/filenotfound.gif")
);
/*
* Used to perform clean up.
*/
for (File f : files)
{
String fileName = f.getName();
String newFileName =
Rename.PREFIX_DOT_THUMBNAIL.apply(fileName, null);
new File(f.getParent(), newFileName).deleteOnExit();
}
Thumbnailator.createThumbnailsAsCollection(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* 2) The thumbnail cannot be written. (unsupported format)
*
* Expected outcome is,
*
* 1) Processing will stop with an UnsupportedFormatException.
*
* @throws IOException
*/
@Test(expected=UnsupportedFormatException.class)
public void testCreateThumbnailCollections_ErrorDuringProcessing_CantWriteThumbnail() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png"),
new File("test-resources/Thumbnailator/grid.bmp"),
new File("test-resources/Thumbnailator/grid.gif")
);
// This will force a UnsupportedFormatException when trying to output
// a thumbnail whose source was a gif file.
Rename brokenRenamer = new Rename() {
@Override
public String apply(String name, ThumbnailParameter param) {
if (name.endsWith(".gif")) {
return "thumbnail." + name + ".foobar";
}
return "thumbnail." + name;
}
};
/*
* Used to perform clean up.
*/
for (File f : files)
{
String fileName = f.getName();
String newFileName =
brokenRenamer.apply(fileName, null);
new File(f.getParent(), newFileName).deleteOnExit();
}
Thumbnailator.createThumbnailsAsCollection(
files,
brokenRenamer,
50,
50
);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* 2) All data can be processed correctly.
* 3) The Collection is a List of a class extending File.
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnailCollections_NoErrors_CollectionExtendsFile() throws IOException
{
class File2 extends File
{
private static final long serialVersionUID = 1L;
public File2(String pathname)
{
super(pathname);
}
}
/*
* The files to make thumbnails of.
*/
List<File2> files = Arrays.asList(
new File2("test-resources/Thumbnailator/grid.jpg"),
new File2("test-resources/Thumbnailator/grid.png")
);
/*
* Used to perform clean up.
*/
for (File f : files)
{
String fileName = f.getName();
String newFileName =
Rename.PREFIX_DOT_THUMBNAIL.apply(fileName, null);
new File(f.getParent(), newFileName).deleteOnExit();
}
Collection<File> resultingFiles =
Thumbnailator.createThumbnailsAsCollection(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
/*
* Perform post-execution checks.
*/
Iterator<File> iter = resultingFiles.iterator();
BufferedImage img0 = ImageIO.read(iter.next());
assertEquals(50, img0.getWidth());
assertEquals(50, img0.getHeight());
BufferedImage img1 = ImageIO.read(iter.next());
assertEquals(50, img1.getWidth());
assertEquals(50, img1.getHeight());
assertTrue(!iter.hasNext());
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnails_negativeWidth() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png")
);
Thumbnailator.createThumbnails(
files,
Rename.PREFIX_DOT_THUMBNAIL,
-42,
50
);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnails_negativeHeight() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png")
);
Thumbnailator.createThumbnails(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
-42
);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnails_negativeWidthAndHeight() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png")
);
Thumbnailator.createThumbnails(
files,
Rename.PREFIX_DOT_THUMBNAIL,
-42,
-42
);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnails(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct, except
* a) The Collection is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnails_nullCollection() throws IOException
{
try
{
Thumbnailator.createThumbnails(
null,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
fail();
}
catch (NullPointerException e)
{
assertEquals("Collection of Files is null.", e.getMessage());
throw e;
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnails(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct, except
* a) The Rename is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnails_nullRename() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png"),
new File("test-resources/Thumbnailator/grid.bmp")
);
try
{
Thumbnailator.createThumbnails(
files,
null,
50,
50
);
fail();
}
catch (NullPointerException e)
{
assertEquals("Rename is null.", e.getMessage());
throw e;
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnails(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* a) The Collection is an empty List.
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnails_NoErrors_EmptyList() throws IOException
{
/*
* The files to make thumbnails of -- nothing!
*/
List<File> files = Collections.emptyList();
Thumbnailator.createThumbnails(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
}
/**
* Test for
* {@link Thumbnailator#createThumbnails(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* a) The Collection is an empty Set.
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnails_NoErrors_EmptySet() throws IOException
{
/*
* The files to make thumbnails of -- nothing!
*/
Set<File> files = Collections.emptySet();
Thumbnailator.createThumbnails(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
}
/**
* Test for
* {@link Thumbnailator#createThumbnails(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* 2) All data can be processed correctly.
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnails_NoErrors() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png")
);
/*
* Used to perform clean up.
*/
for (File f : files)
{
String fileName = f.getName();
String newFileName =
Rename.PREFIX_DOT_THUMBNAIL.apply(fileName, null);
new File(f.getParent(), newFileName).deleteOnExit();
}
Thumbnailator.createThumbnails(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
/*
* Perform post-execution checks.
*/
BufferedImage img0 =
ImageIO.read(new File("test-resources/Thumbnailator/thumbnail.grid.jpg"));
assertEquals(50, img0.getWidth());
assertEquals(50, img0.getHeight());
BufferedImage img1 =
ImageIO.read(new File("test-resources/Thumbnailator/thumbnail.grid.png"));
assertEquals(50, img1.getWidth());
assertEquals(50, img1.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnails(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* 2) A file that was specified does not exist
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
*
* @throws IOException
*/
@Test(expected=IOException.class)
public void testCreateThumbnails_ErrorDuringProcessing_FileNotFound() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png"),
new File("test-resources/Thumbnailator/grid.bmp"),
new File("test-resources/Thumbnailator/filenotfound.gif")
);
/*
* Used to perform clean up.
*/
for (File f : files)
{
String fileName = f.getName();
String newFileName =
Rename.PREFIX_DOT_THUMBNAIL.apply(fileName, null);
new File(f.getParent(), newFileName).deleteOnExit();
}
Thumbnailator.createThumbnails(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnails(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* 2) The thumbnail cannot be written. (unsupported format)
*
* Expected outcome is,
*
* 1) Processing will stop with an UnsupportedFormatException.
*
* @throws IOException
*/
@Test(expected=UnsupportedFormatException.class)
public void testCreateThumbnails_ErrorDuringProcessing_CantWriteThumbnail() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png"),
new File("test-resources/Thumbnailator/grid.bmp"),
new File("test-resources/Thumbnailator/grid.gif")
);
// This will force a UnsupportedFormatException when trying to output
// a thumbnail whose source was a gif file.
Rename brokenRenamer = new Rename() {
@Override
public String apply(String name, ThumbnailParameter param) {
if (name.endsWith(".gif")) {
return "thumbnail." + name + ".foobar";
}
return "thumbnail." + name;
}
};
/*
* Used to perform clean up.
*/
for (File f : files)
{
String fileName = f.getName();
String newFileName =
brokenRenamer.apply(fileName, null);
new File(f.getParent(), newFileName).deleteOnExit();
}
Thumbnailator.createThumbnails(
files,
brokenRenamer,
50,
50
);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)}
* where,
*
* 1) InputStream is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnail_IOII_nullIS() throws IOException
{
/*
* Actual test
*/
InputStream is = null;
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, 50, 50);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)}
* where,
*
* 1) OutputStream is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnail_IOII_nullOS() throws IOException
{
/*
* Actual test
*/
byte[] bytes = makeImageData("jpg", 200, 200);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = null;
Thumbnailator.createThumbnail(is, os, 50, 50);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)}
* where,
*
* 1) InputStream is null
* 2) OutputStream is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnail_IOII_nullISnullOS() throws IOException
{
Thumbnailator.createThumbnail((InputStream)null, null, 50, 50);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_IOII_negativeWidth() throws IOException
{
/*
* Actual test
*/
byte[] bytes = makeImageData("jpg", 200, 200);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, -42, 50);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_IOII_negativeHeight() throws IOException
{
/*
* Actual test
*/
byte[] bytes = makeImageData("jpg", 200, 200);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, 50, -42);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_IOII_negativeWidthAndHeight() throws IOException
{
/*
* Actual test
*/
byte[] bytes = makeImageData("jpg", 200, 200);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, -42, -42);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input data is a JPEG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOII_Jpg() throws IOException
{
/*
* Actual test
*/
byte[] bytes = makeImageData("jpg", 200, 200);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage thumb = ImageIO.read(thumbIs);
assertEquals(50, thumb.getWidth());
assertEquals(50, thumb.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input data is a PNG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOII_Png() throws IOException
{
/*
* Actual test
*/
byte[] bytes = makeImageData("png", 200, 200);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage thumb = ImageIO.read(thumbIs);
assertEquals(50, thumb.getWidth());
assertEquals(50, thumb.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input data is a BMP image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOII_Bmp() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[40054];
new FileInputStream("test-resources/Thumbnailator/grid.bmp").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage thumb = ImageIO.read(thumbIs);
assertEquals(50, thumb.getWidth());
assertEquals(50, thumb.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input data is a BMP image
* -> writing to a BMP is not supported by default.
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
* On Java 6 and later, this should pass, as it contains a GIF writer.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOII_Gif() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[492];
new FileInputStream("test-resources/Thumbnailator/grid.gif").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try
{
Thumbnailator.createThumbnail(is, os, 50, 50);
// This case should pass on Java 6 and later, as those JREs have a
// GIF writer.
if (System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
}
catch (UnsupportedFormatException e)
{
// This case should pass on Java 6 and later.
if (!System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
assertEquals("No suitable ImageWriter found for gif.", e.getMessage());
assertEquals("gif", e.getFormatName());
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)}
* where,
*
* 1) InputStream throws an IOException during read.
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
*
* @throws IOException
*/
@Test(expected=IOException.class)
public void testCreateThumbnail_IOII_IOExceptionFromIS() throws IOException
{
/*
* Actual test
*/
InputStream is = mock(InputStream.class);
doThrow(new IOException("read error!")).when(is).read();
doThrow(new IOException("read error!")).when(is).read((byte[])any());
doThrow(new IOException("read error!")).when(is).read((byte[])any(), anyInt(), anyInt());
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, 50, 50);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)}
* where,
*
* 1) OutputStream throws an IOException during read.
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
*
* @throws IOException
*/
@Test(expected=IOException.class)
public void testCreateThumbnail_IOII_IOExceptionFromOS() throws IOException
{
/*
* Actual test
*/
byte[] bytes = makeImageData("png", 200, 200);
InputStream is = new ByteArrayInputStream(bytes);
OutputStream os = mock(OutputStream.class);
doThrow(new IOException("write error!")).when(os).write(anyInt());
doThrow(new IOException("write error!")).when(os).write((byte[])any());
doThrow(new IOException("write error!")).when(os).write((byte[])any(), anyInt(), anyInt());
Thumbnailator.createThumbnail(is, os, 50, 50);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a JPEG image
* b) Output file is a PNG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOSII_Transcoding_Jpeg_Png() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[4602];
new FileInputStream("test-resources/Thumbnailator/grid.jpg").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, "png", 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage img = ImageIO.read(thumbIs);
assertEquals(
"png",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(
new ByteArrayInputStream(os.toByteArray()))
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a JPEG image
* b) Output file is a BMP image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOSII_Transcoding_Jpeg_Bmp() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[4602];
new FileInputStream("test-resources/Thumbnailator/grid.jpg").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, "bmp", 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage img = ImageIO.read(thumbIs);
assertEquals(
"bmp",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(
new ByteArrayInputStream(os.toByteArray()))
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
@Test
public void testCreateThumbnail_IOSII_Transcoding_Jpeg_Gif() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[4602];
new FileInputStream("test-resources/Thumbnailator/grid.jpg").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try
{
Thumbnailator.createThumbnail(is, os, "gif", 50, 50);
// This case should pass on Java 6 and later, as those JREs have a
// GIF writer.
if (System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
}
catch (IllegalArgumentException e)
{
// This case should pass on Java 6 and later.
if (!System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
assertTrue(e.getMessage().contains("gif"));
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a PNG image
* b) Output file is a JPEG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOSII_Transcoding_Png_Jpeg() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[287];
new FileInputStream("test-resources/Thumbnailator/grid.png").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, "jpg", 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage img = ImageIO.read(thumbIs);
assertEquals(
"JPEG",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(
new ByteArrayInputStream(os.toByteArray()))
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a PNG image
* b) Output file is a BMP image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOSII_Transcoding_Png_Bmp() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[287];
new FileInputStream("test-resources/Thumbnailator/grid.png").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, "bmp", 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage img = ImageIO.read(thumbIs);
assertEquals(
"bmp",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(
new ByteArrayInputStream(os.toByteArray()))
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
@Test
public void testCreateThumbnail_IOSII_Transcoding_Png_Gif() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[287];
new FileInputStream("test-resources/Thumbnailator/grid.png").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try
{
Thumbnailator.createThumbnail(is, os, "gif", 50, 50);
// This case should pass on Java 6 and later, as those JREs have a
// GIF writer.
if (System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
}
catch (IllegalArgumentException e)
{
// This case should pass on Java 6 and later.
if (!System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
assertTrue(e.getMessage().contains("gif"));
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a BMP image
* b) Output file is a PNG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOSII_Transcoding_Bmp_Png() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[40054];
new FileInputStream("test-resources/Thumbnailator/grid.bmp").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, "png", 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage img = ImageIO.read(thumbIs);
assertEquals(
"png",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(
new ByteArrayInputStream(os.toByteArray()))
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a BMP image
* b) Output file is a JPEG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOSII_Transcoding_Bmp_Jpeg() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[40054];
new FileInputStream("test-resources/Thumbnailator/grid.bmp").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, "jpg", 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage img = ImageIO.read(thumbIs);
assertEquals(
"JPEG",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(
new ByteArrayInputStream(os.toByteArray()))
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
@Test
public void testCreateThumbnail_IOSII_Transcoding_Bmp_Gif() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[40054];
new FileInputStream("test-resources/Thumbnailator/grid.bmp").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try
{
Thumbnailator.createThumbnail(is, os, "gif", 50, 50);
// This case should pass on Java 6 and later, as those JREs have a
// GIF writer.
if (System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
}
catch (IllegalArgumentException e)
{
// This case should pass on Java 6 and later.
if (!System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
assertTrue(e.getMessage().contains("gif"));
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a GIF image
* b) Output file is a PNG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOSII_Transcoding_Gif_Png() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[492];
new FileInputStream("test-resources/Thumbnailator/grid.gif").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, "png", 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage img = ImageIO.read(thumbIs);
assertEquals(
"png",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(
new ByteArrayInputStream(os.toByteArray()))
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a GIF image
* b) Output file is a JPEG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOSII_Transcoding_Gif_Jpeg() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[492];
new FileInputStream("test-resources/Thumbnailator/grid.gif").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, "jpg", 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage img = ImageIO.read(thumbIs);
assertEquals(
"JPEG",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(
new ByteArrayInputStream(os.toByteArray()))
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a GIF image
* b) Output file is a BMP image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOSII_Transcoding_Gif_Bmp() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[492];
new FileInputStream("test-resources/Thumbnailator/grid.gif").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, "bmp", 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage img = ImageIO.read(thumbIs);
assertEquals(
"bmp",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(
new ByteArrayInputStream(os.toByteArray()))
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) InputStream throws an IOException during read.
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
*
* @throws IOException
*/
@Test(expected=IOException.class)
public void testCreateThumbnail_IOSII_IOExceptionFromIS() throws IOException
{
/*
* Actual test
*/
InputStream is = mock(InputStream.class);
doThrow(new IOException("read error!")).when(is).read();
doThrow(new IOException("read error!")).when(is).read((byte[])any());
doThrow(new IOException("read error!")).when(is).read((byte[])any(), anyInt(), anyInt());
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, "png", 50, 50);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) OutputStream throws an IOException during read.
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
*
* @throws IOException
*/
@Test(expected=IOException.class)
public void testCreateThumbnail_IOSII_IOExceptionFromOS() throws IOException
{
/*
* Actual test
*/
byte[] bytes = makeImageData("png", 200, 200);
InputStream is = new ByteArrayInputStream(bytes);
OutputStream os = mock(OutputStream.class);
doThrow(new IOException("write error!")).when(os).write(anyInt());
doThrow(new IOException("write error!")).when(os).write((byte[])any());
doThrow(new IOException("write error!")).when(os).write((byte[])any(), anyInt(), anyInt());
Thumbnailator.createThumbnail(is, os, "png", 50, 50);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Input File is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnail_FFII_nullInputFile() throws IOException
{
/*
* Actual test
*/
File inputFile = null;
File outputFile = new File("bar.jpg");
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Output File is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnail_FFII_nullOutputFile() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("foo.jpg");
File outputFile = null;
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Input File is null
* 2) Output File is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnail_FFII_nullInputAndOutputFiles() throws IOException
{
Thumbnailator.createThumbnail((File)null, null, 50, 50);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_FFII_negativeWidth() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("foo.jpg");
File outputFile = new File("bar.jpg");
Thumbnailator.createThumbnail(inputFile, outputFile, -42, 50);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_FFII_negativeHeight() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("foo.jpg");
File outputFile = new File("bar.jpg");
Thumbnailator.createThumbnail(inputFile, outputFile, 50, -42);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_FFII_negativeWidthAndHeight() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("foo.jpg");
File outputFile = new File("bar.jpg");
Thumbnailator.createThumbnail(inputFile, outputFile, -42, -42);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input file is a JPEG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Jpg() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.jpg");
File outputFile = new File("test-resources/Thumbnailator/tmp.jpg");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input file is a PNG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Png() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.png");
File outputFile = new File("test-resources/Thumbnailator/tmp.png");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input data is a BMP image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Bmp() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.bmp");
File outputFile = new File("test-resources/Thumbnailator/tmp.bmp");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input data is a GIF image
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
* On Java 6 and later, this should pass, as it contains a GIF writer.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Gif() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.gif");
File outputFile = new File("test-resources/Thumbnailator/tmp.gif");
outputFile.deleteOnExit();
try
{
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
// This case should pass on Java 6 and later, as those JREs have a
// GIF writer.
if (System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
}
catch (UnsupportedFormatException e)
{
// This case should pass on Java 6 and later.
if (!System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
assertEquals("No suitable ImageWriter found for gif.", e.getMessage());
assertEquals("gif", e.getFormatName());
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a JPEG image
* b) Output file is a PNG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Jpeg_Png() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.jpg");
File outputFile = File.createTempFile("thumbnailator-testing-", ".png");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(
"png",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(outputFile)
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a JPEG image
* b) Output file is a BMP image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Jpeg_Bmp() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.jpg");
File outputFile = File.createTempFile("thumbnailator-testing-", ".bmp");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(
"bmp",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(outputFile)
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a JPEG image
* b) Output file is a GIF image
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
* On Java 6 and later, this should pass, as it contains a GIF writer.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Jpeg_Gif() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.jpg");
File outputFile = File.createTempFile("thumbnailator-testing-", ".gif");
outputFile.deleteOnExit();
try
{
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
// This case should pass on Java 6 and later, as those JREs have a
// GIF writer.
if (System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
}
catch (UnsupportedFormatException e)
{
// This case should pass on Java 6 and later.
if (!System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
assertEquals("No suitable ImageWriter found for gif.", e.getMessage());
assertEquals("gif", e.getFormatName());
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a PNG image
* b) Output file is a JPEG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Png_Jpeg() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.png");
File outputFile = File.createTempFile("thumbnailator-testing-", ".jpg");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(
"JPEG",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(outputFile)
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a PNG image
* b) Output file is a BMP image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Png_Bmp() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.png");
File outputFile = File.createTempFile("thumbnailator-testing-", ".bmp");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(
"bmp",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(outputFile)
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a PNG image
* b) Output file is a GIF image
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
* On Java 6 and later, this should pass, as it contains a GIF writer.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Png_Gif() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.png");
File outputFile = File.createTempFile("thumbnailator-testing-", ".gif");
outputFile.deleteOnExit();
try
{
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
// This case should pass on Java 6 and later, as those JREs have a
// GIF writer.
if (System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
}
catch (UnsupportedFormatException e)
{
// This case should pass on Java 6 and later.
if (!System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
assertEquals("No suitable ImageWriter found for gif.", e.getMessage());
assertEquals("gif", e.getFormatName());
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a BMP image
* b) Output file is a PNG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Bmp_Png() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.bmp");
File outputFile = File.createTempFile("thumbnailator-testing-", ".png");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(
"png",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(outputFile)
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a BMP image
* b) Output file is a JPEG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Bmp_Jpeg() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.bmp");
File outputFile = File.createTempFile("thumbnailator-testing-", ".jpg");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(
"JPEG",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(outputFile)
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a BMP image
* b) Output file is a GIF image
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
* On Java 6 and later, this should pass, as it contains a GIF writer.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Bmp_Gif() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.bmp");
File outputFile = File.createTempFile("thumbnailator-testing-", ".gif");
outputFile.deleteOnExit();
try
{
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
// This case should pass on Java 6 and later, as those JREs have a
// GIF writer.
if (System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
}
catch (UnsupportedFormatException e)
{
// This case should pass on Java 6 and later.
if (!System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
assertEquals("No suitable ImageWriter found for gif.", e.getMessage());
assertEquals("gif", e.getFormatName());
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a GIF image
* b) Output file is a PNG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Gif_Png() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.gif");
File outputFile = File.createTempFile("thumbnailator-testing-", ".png");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(
"png",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(outputFile)
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a GIF image
* b) Output file is a JPEG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Gif_Jpeg() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.gif");
File outputFile = File.createTempFile("thumbnailator-testing-", ".jpg");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(
"JPEG",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(outputFile)
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a GIF image
* b) Output file is a BMP image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Gif_Bmp() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.gif");
File outputFile = File.createTempFile("thumbnailator-testing-", ".bmp");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(
"bmp",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(outputFile)
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Input File does not exist.
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_nonExistentInputFile() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("foo.jpg");
File outputFile = new File("bar.jpg");
try
{
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
fail();
}
catch (IOException e)
{
assertEquals("Input file does not exist.", e.getMessage());
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) A filename that is invalid
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_invalidOutputFile() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.jpg");
File outputFile = new File("@\\
try
{
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
fail();
}
catch (IOException e)
{
// An IOException is expected. Likely a FileNotFoundException.
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) A problem occurs while writing to the file.
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
*
* @throws IOException
*/
@Ignore
public void testCreateThumbnail_FFII_IOExceptionOnWrite() throws IOException
{
//Cannot craft a test case to test this condition.
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, int, int)}
* where,
*
* 1) Input File is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnail_FII_nullInputFile() throws IOException
{
Thumbnailator.createThumbnail((File)null, 50, 50);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_FII_negativeWidth() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("foo.jpg");
Thumbnailator.createThumbnail(inputFile, -42, 50);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_FII_negativeHeight() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("foo.jpg");
Thumbnailator.createThumbnail(inputFile, 50, -42);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_FII_negativeWidthAndHeight() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("foo.jpg");
Thumbnailator.createThumbnail(inputFile, -42, -42);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input file is a JPEG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FII_Jpg() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.jpg");
BufferedImage img = Thumbnailator.createThumbnail(inputFile, 50, 50);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input file is a PNG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FII_Png() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.png");
BufferedImage img = Thumbnailator.createThumbnail(inputFile, 50, 50);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input data is a BMP image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FII_Bmp() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.bmp");
BufferedImage img = Thumbnailator.createThumbnail(inputFile, 50, 50);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input data is a GIF image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FII_Gif() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.gif");
BufferedImage img = Thumbnailator.createThumbnail(inputFile, 50, 50);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_BII_negativeWidth()
{
/*
* Actual test
*/
BufferedImage img = new BufferedImageBuilder(200, 200).build();
Thumbnailator.createThumbnail(img, -42, 50);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_BII_negativeHeight()
{
/*
* Actual test
*/
BufferedImage img = new BufferedImageBuilder(200, 200).build();
Thumbnailator.createThumbnail(img, 50, -42);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_BII_negativeWidthAndHeight()
{
/*
* Actual test
*/
BufferedImage img = new BufferedImageBuilder(200, 200).build();
Thumbnailator.createThumbnail(img, -42, -42);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(BufferedImage, int, int)}
* where,
*
* 1) Method arguments are correct
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
*/
@Test
public void testCreateThumbnail_BII_CorrectUsage()
{
/*
* Actual test
*/
BufferedImage img =
new BufferedImageBuilder(200, 200, BufferedImage.TYPE_INT_ARGB).build();
BufferedImage thumbnail = Thumbnailator.createThumbnail(img, 50, 50);
assertEquals(50, thumbnail.getWidth());
assertEquals(50, thumbnail.getHeight());
assertEquals(BufferedImage.TYPE_INT_ARGB, thumbnail.getType());
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_III_negativeWidth()
{
/*
* Actual test
*/
BufferedImage img = new BufferedImageBuilder(200, 200).build();
Thumbnailator.createThumbnail((Image)img, -42, 50);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_III_negativeHeight()
{
/*
* Actual test
*/
BufferedImage img = new BufferedImageBuilder(200, 200).build();
Thumbnailator.createThumbnail((Image)img, 50, -42);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_III_negativeWidthAndHeight()
{
/*
* Actual test
*/
BufferedImage img = new BufferedImageBuilder(200, 200).build();
Thumbnailator.createThumbnail((Image)img, -42, -42);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(Image, int, int)}
* where,
*
* 1) Method arguments are correct
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
*/
@Test
public void testCreateThumbnail_III_CorrectUsage()
{
/*
* Actual test
*/
BufferedImage img =
new BufferedImageBuilder(200, 200, BufferedImage.TYPE_INT_ARGB).build();
Image thumbnail = Thumbnailator.createThumbnail((Image)img, 50, 50);
assertEquals(50, thumbnail.getWidth(null));
assertEquals(50, thumbnail.getHeight(null));
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(net.coobird.thumbnailator.tasks.ThumbnailTask)}
* where,
*
* 1) The correct parameters are given.
* 2) The size is specified for the ThumbnailParameter.
*
* Expected outcome is,
*
* 1) The ResizerFactory is being used.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_ThumbnailTask_ResizerFactoryBeingUsed_UsingSize() throws IOException
{
// given
BufferedImageSource source = new BufferedImageSource(
new BufferedImageBuilder(200, 200, BufferedImage.TYPE_INT_ARGB).build()
);
BufferedImageSink sink = new BufferedImageSink();
ResizerFactory resizerFactory = spy(DefaultResizerFactory.getInstance());
ThumbnailParameter param =
new ThumbnailParameterBuilder()
.size(100, 100)
.resizerFactory(resizerFactory)
.build();
// when
Thumbnailator.createThumbnail(
new SourceSinkThumbnailTask<BufferedImage, BufferedImage>(
param, source, sink
)
);
// then
verify(resizerFactory)
.getResizer(new Dimension(200, 200), new Dimension(100, 100));
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(net.coobird.thumbnailator.tasks.ThumbnailTask)}
* where,
*
* 1) The correct parameters are given.
* 2) The scale is specified for the ThumbnailParameter.
*
* Expected outcome is,
*
* 1) The ResizerFactory is being used.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_ThumbnailTask_ResizerFactoryBeingUsed_UsingScale() throws IOException
{
// given
BufferedImageSource source = new BufferedImageSource(
new BufferedImageBuilder(200, 200, BufferedImage.TYPE_INT_ARGB).build()
);
BufferedImageSink sink = new BufferedImageSink();
ResizerFactory resizerFactory = spy(DefaultResizerFactory.getInstance());
ThumbnailParameter param =
new ThumbnailParameterBuilder()
.scale(0.5)
.resizerFactory(resizerFactory)
.build();
// when
Thumbnailator.createThumbnail(
new SourceSinkThumbnailTask<BufferedImage, BufferedImage>(
param, source, sink
)
);
// then
verify(resizerFactory)
.getResizer(new Dimension(200, 200), new Dimension(100, 100));
}
@Test
public void renameGivenThumbnailParameter_createThumbnails() throws IOException
{
// given
Rename rename = mock(Rename.class);
when(rename.apply(anyString(), any(ThumbnailParameter.class)))
.thenReturn("thumbnail.grid.png");
File f = new File("test-resources/Thumbnailator/grid.png");
// when
Thumbnailator.createThumbnails(Arrays.asList(f), rename, 50, 50);
// then
ArgumentCaptor<ThumbnailParameter> ac =
ArgumentCaptor.forClass(ThumbnailParameter.class);
verify(rename).apply(eq(f.getName()), ac.capture());
assertEquals(new Dimension(50, 50), ac.getValue().getSize());
// clean up
new File("test-resources/Thumbnailator/thumbnail.grid.png").deleteOnExit();
}
@Test
public void renameGivenThumbnailParameter_createThumbnailsAsCollection() throws IOException
{
// given
Rename rename = mock(Rename.class);
when(rename.apply(anyString(), any(ThumbnailParameter.class)))
.thenReturn("thumbnail.grid.png");
File f = new File("test-resources/Thumbnailator/grid.png");
// when
Thumbnailator.createThumbnailsAsCollection(Arrays.asList(f), rename, 50, 50);
// then
ArgumentCaptor<ThumbnailParameter> ac =
ArgumentCaptor.forClass(ThumbnailParameter.class);
verify(rename).apply(eq(f.getName()), ac.capture());
assertEquals(new Dimension(50, 50), ac.getValue().getSize());
// clean up
new File("test-resources/Thumbnailator/thumbnail.grid.png").deleteOnExit();
}
/**
* Returns test image data as an array of {@code byte}s.
*
* @param format Image format.
* @param width Image width.
* @param height Image height.
* @return A {@code byte[]} of image data.
* @throws IOException When a problem occurs while making image data.
*/
private byte[] makeImageData(String format, int width, int height)
throws IOException
{
BufferedImage img = new BufferedImageBuilder(200, 200).build();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, format, baos);
return baos.toByteArray();
}
} |
package fr.jayasoft.ivy.conflict;
/**
* @author Anders janmyr
*/
import java.util.Date;
import junit.framework.*;
import fr.jayasoft.ivy.Ivy;
public class RegexpConflictManagerTest extends TestCase
{
private Ivy ivy;
protected void setUp() throws Exception
{
ivy = new Ivy();
ivy.configure( RegexpConflictManagerTest.class
.getResource( "ivyconf-regexp-test.xml" ) );
}
public void testNoApiConflictResolve() throws Exception
{
try
{
ivy.resolve( RegexpConflictManagerTest.class
.getResource( "ivy-no-regexp-conflict.xml" ), null,
new String[] { "*" }, null, new Date(), false );
}
catch ( StrictConflictException e )
{
fail( "Unexpected conflict: " + e );
}
}
public void testConflictResolve() throws Exception
{
try
{
ivy.resolve( RegexpConflictManagerTest.class
.getResource( "ivy-conflict.xml" ), null,
new String[] { "*" }, null, new Date(), false );
fail( "Resolve should have failed with a conflict" );
}
catch ( StrictConflictException e )
{
// this is expected
assertTrue(e.getMessage().indexOf("[ org1 | mod1.2 | 2.0.0 ]:2.0 (needed by [ jayasoft | resolve-noconflict | 1.0 ])")!=-1);
assertTrue(e.getMessage().indexOf("conflicts with")!=-1);
assertTrue(e.getMessage().indexOf("[ org1 | mod1.2 | 2.1.0 ]:2.1 (needed by [ jayasoft | resolve-noconflict | 1.0 ])")!=-1);
}
}
} |
package app;
import db.DBUtils;
import ui.StartFrame;
import javax.swing.*;
public class App {
public static void main(String[] args) {
DBUtils.initDatabase();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new App().startUI();
}
});
}
private void startUI() {
new StartFrame();
}
} |
package org.opencms.staticexport;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsResource;
import org.opencms.file.types.CmsResourceTypeFolder;
import org.opencms.file.types.CmsResourceTypeXmlPage;
import org.opencms.i18n.CmsEncoder;
import org.opencms.main.CmsException;
import org.opencms.main.OpenCms;
import org.opencms.test.OpenCmsTestCase;
import org.opencms.test.OpenCmsTestProperties;
import org.opencms.xml.page.CmsXmlPage;
import java.util.Locale;
import junit.extensions.TestSetup;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
* @since 6.0.0
*/
public class TestCmsLinkManager extends OpenCmsTestCase {
/** Content for a simple test page. */
private static final String PAGE_01 = "<html><body><a href=\"/system/news/test.html?__locale=de\">test</a></body></html>";
/**
* Default JUnit constructor.<p>
*
* @param arg0 JUnit parameters
*/
public TestCmsLinkManager(String arg0) {
super(arg0);
}
/**
* Test suite for this test class.<p>
*
* @return the test suite
*/
public static Test suite() {
OpenCmsTestProperties.initialize(org.opencms.test.AllTests.TEST_PROPERTIES_PATH);
TestSuite suite = new TestSuite();
TestSuite suite1 = new TestSuite();
suite1.setName(TestCmsLinkManager.class.getName());
suite1.addTest(new TestCmsLinkManager("testToAbsolute"));
suite1.addTest(new TestCmsLinkManager("testLinkSubstitution"));
suite1.addTest(new TestCmsLinkManager("testSymmetricSubstitution"));
suite1.addTest(new TestCmsLinkManager("testCustomLinkHandler"));
suite1.addTest(new TestCmsLinkManager("testRootPathAdjustment"));
TestSetup wrapper = new TestSetup(suite1) {
@Override
protected void setUp() {
setupOpenCms("simpletest", "/");
}
@Override
protected void tearDown() {
removeOpenCms();
}
};
suite.addTest(wrapper);
// Test adjustment when OpenCms context is empty
suite.addTest(rootPathAdjustmentWrapped("*", "/data"));
return suite;
}
/**
* Runs testRootPathAdjustment() wrapped in an OpenCms instance where servletName and defaultWebAppName
* are adjusted to test for different OpenCms contexts.
*
* @param servletName the servlet name used for the OpenCms instance
* @param defaultWebAppName the default webapp name used for the OpenCms instance
* @return testRootPathAdjustment() wrapped in an own OpenCms instance.
*/
protected static Test rootPathAdjustmentWrapped(final String servletName, final String defaultWebAppName) {
return new TestSetup(new TestCmsLinkManager("testRootPathAdjustmentCopy")) {
@Override
protected void setUp() {
setupOpenCms("simpletest", "/", null, null, null, servletName, defaultWebAppName, true);
}
@Override
protected void tearDown() {
removeOpenCms();
}
};
}
/**
* Tests symmetric link / root path substitution with a custom link handler.<p>
*
* @throws Exception if test fails
*/
public void testCustomLinkHandler() throws Exception {
CmsObject cms = getCmsObject();
echo("Testing symmetric link / root path substitution with a custom link handler");
CmsLinkManager lm = OpenCms.getLinkManager();
I_CmsLinkSubstitutionHandler lh = new CmsTestLinkSubstitutionHandler();
lm.setLinkSubstitutionHandler(cms, lh);
// create required special "/system/news/" folder with a resource
cms.createResource("/system/news", CmsResourceTypeFolder.getStaticTypeId());
String resName = "/system/news/test.html";
cms.createResource(resName, CmsResourceTypeXmlPage.getStaticTypeId());
OpenCms.getPublishManager().publishResource(cms, "/system/news");
OpenCms.getPublishManager().waitWhileRunning();
CmsResource res = cms.readResource(resName);
// test with default setup
testCustomLinkHandler(cms, res.getRootPath());
// test with "empty" VFS prefix
OpenCms.getStaticExportManager().setVfsPrefix("");
OpenCms.getStaticExportManager().initialize(cms);
testCustomLinkHandler(cms, res.getRootPath());
// test when current URI is in "/system/" folder and current site root is empty
cms.getRequestContext().setUri(resName);
cms.getRequestContext().setSiteRoot("");
testCustomLinkHandler(cms, res.getRootPath());
// test with localized information
testCustomLinkHandler(cms, res.getRootPath() + "?__locale=de");
// now try with some real content on a page
CmsXmlPage page = new CmsXmlPage(Locale.ENGLISH, CmsEncoder.ENCODING_UTF_8);
page.addValue("body", Locale.ENGLISH);
page.setStringValue(cms, "body", Locale.ENGLISH, PAGE_01);
cms.lockResource(resName);
CmsFile file = cms.readFile(res);
file.setContents(page.marshal());
cms.writeFile(file);
}
/**
* Tests the link substitution.<p>
*
* @throws Exception if test fails
*/
public void testLinkSubstitution() throws Exception {
String test;
CmsObject cms = getCmsObject();
echo("Testing link substitution");
cms.getRequestContext().setCurrentProject(cms.readProject("Online"));
CmsLinkManager linkManager = OpenCms.getLinkManager();
test = linkManager.substituteLink(cms, "/folder1/index.html?additionalParam", "/sites/default");
System.out.println(test);
assertEquals("/data/opencms/folder1/index.html?additionalParam", test);
test = linkManager.substituteLink(
cms,
CmsLinkManager.getAbsoluteUri("/", "/folder1/index.html"),
"/sites/default");
System.out.println(test);
assertEquals("/data/opencms/", test);
test = linkManager.substituteLink(
cms,
CmsLinkManager.getAbsoluteUri("./", "/folder1/index.html"),
"/sites/default");
System.out.println(test);
assertEquals("/data/opencms/folder1/", test);
test = CmsLinkManager.getRelativeUri("/index.html", "/index.html");
System.out.println(test);
assertEquals("index.html", test);
test = CmsLinkManager.getRelativeUri("/folder1/index.html", "/folder1/");
System.out.println(test);
assertEquals("./", test);
test = CmsLinkManager.getRelativeUri("/index.html", "/");
System.out.println(test);
assertEquals("./", test);
test = CmsLinkManager.getRelativeUri("/index.html", "./");
System.out.println(test);
assertEquals("./", test);
test = CmsLinkManager.getRelativeUri("/", "/");
System.out.println(test);
assertEquals("./", test);
}
/**
* Test how the OpenCms context is removed from URLs when getting root URLs.
* Intended behavior: if and only if a link starts with "${context}/" the
* context is removed.
*
* Example: with context "/opencms":
* input link: /opencms/path output link: /path
* input link: /opencmswhatever/path output link: /opencmswhatever/path
*
* Assumption: OpenCms context never ends with "/".
*
* @throws CmsException from getCmsObject()
*
*/
public void testRootPathAdjustment() throws CmsException {
echo("Testing root path adjustment / context removement");
String context = OpenCms.getSystemInfo().getOpenCmsContext();
echo("Using OpenCms context \"" + context + "\"");
//Switch to root site
CmsObject cms = getCmsObject();
cms.getRequestContext().setSiteRoot("/");
String link1 = "/test";
CmsLinkManager lm = OpenCms.getLinkManager();
assertEquals(link1, lm.getRootPath(cms, context + link1));
String link2 = context.isEmpty() ? "/test" : "test";
assertEquals(context + link2, lm.getRootPath(cms, context + link2));
}
/**
* Just a copy of the called method - if the same method is called twice,
* the JUnit Eclipse plugin (or JUnit itself?) behaves strange (if the test failed or succeeded is only mentioned
* for the last test occurrence.
*
* @throws CmsException from getCmsObject()
*/
public void testRootPathAdjustmentCopy() throws CmsException {
testRootPathAdjustment();
}
/**
* Tests symmetric link / root path substitution.<p>
*
* @throws Exception if test fails
*/
public void testSymmetricSubstitution() throws Exception {
CmsObject cms = getCmsObject();
echo("Testing symmetric link / root path substitution substitution");
// read the resource to make sure we certainly use an existing root path
CmsResource res = cms.readResource("/xmlcontent/article_0001.html");
CmsLinkManager lm = OpenCms.getLinkManager();
// first try: no server info
String link = lm.substituteLinkForRootPath(cms, res.getRootPath());
String rootPath = lm.getRootPath(cms, link);
assertEquals(res.getRootPath(), rootPath);
// second try: with server and protocol
link = lm.getServerLink(cms, res.getRootPath());
rootPath = lm.getRootPath(cms, link);
assertEquals(res.getRootPath(), rootPath);
}
/**
* Tests the method getAbsoluteUri.<p>
*/
public void testToAbsolute() {
String test;
test = CmsLinkManager.getRelativeUri("/dir1/dir2/index.html", "/dir1/dirB/index.html");
System.out.println(test);
assertEquals(test, "../dirB/index.html");
test = CmsLinkManager.getRelativeUri("/exp/en/test/index.html", "/exp/de/test/index.html");
System.out.println(test);
assertEquals(test, "../../de/test/index.html");
test = CmsLinkManager.getAbsoluteUri("../../index.html", "/dir1/dir2/dir3/");
System.out.println(test);
assertEquals(test, "/dir1/index.html");
test = CmsLinkManager.getAbsoluteUri("./../././.././dir2/./../index.html", "/dir1/dir2/dir3/");
System.out.println(test);
assertEquals(test, "/dir1/index.html");
test = CmsLinkManager.getAbsoluteUri("/dirA/index.html", "/dir1/dir2/dir3/");
System.out.println(test);
assertEquals(test, "/dirA/index.html");
}
/**
* Internal test method for custom link test.<p>
*
* @param cms the current OpenCms context
* @param path the resource path in the VFS to check the links for
*
* @throws Exception in case the test fails
*/
private void testCustomLinkHandler(CmsObject cms, String path) throws Exception {
CmsLinkManager lm = OpenCms.getLinkManager();
// first try: no server info
String link = lm.substituteLinkForRootPath(cms, path);
String rootPath = lm.getRootPath(cms, link);
assertEquals(path, rootPath);
// second try: with server and protocol
link = lm.getServerLink(cms, path);
rootPath = lm.getRootPath(cms, link);
assertEquals(path, rootPath);
}
} |
package org.pentaho.di.ui.i18n.editor;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleFileException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.variables.Variables;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.ui.core.PropsUI;
import org.pentaho.di.ui.core.dialog.EnterStringDialog;
import org.pentaho.di.ui.core.dialog.EnterTextDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.core.gui.WindowProperty;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.i18n.KeyOccurrence;
import org.pentaho.di.ui.i18n.MessagesSourceCrawler;
import org.pentaho.di.ui.i18n.MessagesStore;
import org.pentaho.di.ui.i18n.SourceCrawlerPackageException;
import org.pentaho.di.ui.i18n.SourceCrawlerXMLElement;
import org.pentaho.di.ui.i18n.SourceCrawlerXMLFolder;
import org.pentaho.di.ui.i18n.TranslationsStore;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
public class Translator2
{
public static final String APP_NAME = Messages.getString("i18nDialog.ApplicationName");
private Display display;
private Shell shell;
private LogWriter log;
private PropsUI props;
/** The crawler that can find and contain all the keys in the source code */
private MessagesSourceCrawler crawler;
/** The translations store containing all the translations for all keys, locale, packages */
private TranslationsStore store;
/** derived from the crawler */
private java.util.List<String> messagesPackages;
private SashForm sashform;
private List wLocale;
private TableView wPackages;
private List wTodo;
private String selectedLocale;
private String selectedMessagesPackage;
private Text wKey;
private Text wMain;
private Text wValue;
private Text wSource;
private Button wReload;
private Button wClose;
private Button wApply;
private Button wRevert;
private Button wSave;
private Button wZip;
private Button wSearch;
private Button wNext;
private Button wSearchV;
private Button wNextV;
/*
private Button wSearchG;
private Button wNextG;
*/
private Button wAll;
private String referenceLocale;
private java.util.List<String> rootDirectories;
private java.util.List<String> localeList;
private java.util.List<String> filesToAvoid;
protected String lastValue;
protected boolean lastValueChanged;
protected String selectedKey;
protected String searchString;
protected String lastFoundKey;
private String singleMessagesFile;
private java.util.List<SourceCrawlerXMLFolder> xmlFolders;
public Translator2(Display display)
{
this.display = display;
this.log = LogWriter.getInstance();
this.props = PropsUI.getInstance();
}
public boolean showKey(String key, String messagesPackage) {
return !key.startsWith("System.") || messagesPackage.equals(BaseMessages.class.getPackage().getName());
}
public void readFiles(java.util.List<String> directories) throws KettleFileException
{
log.logBasic(toString(), Messages.getString("i18n.Log.ScanningSourceDirectories"));
try
{
// crawl through the source directories...
crawler = new MessagesSourceCrawler(directories, singleMessagesFile, xmlFolders);
crawler.setFilesToAvoid(filesToAvoid);
crawler.crawl();
// get the packages...
messagesPackages = crawler.getMessagesPackagesList();
store = new TranslationsStore(localeList, messagesPackages, referenceLocale); // en_US : main locale
store.read(directories);
// What are the statistics?
int nrKeys = 0;
int keyCounts[] = new int[localeList.size()];
for (int i=0;i<localeList.size();i++) {
String locale = localeList.get(i);
// Count the number of keys available in that locale...
keyCounts[i]=0;
for (KeyOccurrence keyOccurrence : crawler.getOccurrences()) {
// We don't want the system keys, just the regular ones.
if (showKey(keyOccurrence.getKey(), keyOccurrence.getMessagesPackage())) {
String value = store.lookupKeyValue(locale, keyOccurrence.getMessagesPackage(), keyOccurrence.getKey());
if (!Const.isEmpty(value)) {
keyCounts[i]++;
}
if (locale.equals(referenceLocale)) {
nrKeys++;
}
}
}
}
String[] locales = localeList.toArray(new String[localeList.size()]);
for (int i=0;i<locales.length;i++) {
for (int j=0;j<locales.length-1;j++) {
if (keyCounts[j]<keyCounts[j+1]) {
int c = keyCounts[j];
keyCounts[j] = keyCounts[j+1];
keyCounts[j+1] = c;
String l = locales[j];
locales[j] = locales[j+1];
locales[j+1] = l;
}
}
}
DecimalFormat pctFormat = new DecimalFormat("#00.00");
DecimalFormat nrFormat = new DecimalFormat("00");
System.out.println(Messages.getString("i18n.Log.NumberOfKeysFound",""+nrKeys));
for (int i=0;i<locales.length;i++) {
double donePct = 100 * (double)keyCounts[i] / (double)nrKeys;
int missingKeys = nrKeys - keyCounts[i];
String statusKeys = "# "+nrFormat.format(i+1)+" : "+locales[i]+" : "+pctFormat.format(donePct)+"% complete ("+keyCounts[i]+")" +
(missingKeys!=0 ? ("...missing " + missingKeys) : "");
System.out.println(statusKeys);
}
}
catch(Exception e)
{
throw new KettleFileException(Messages.getString("i18n.Log.UnableToGetFiles",rootDirectories.toString()), e);
}
}
public void loadConfiguration() {
// What are the locale to handle?
localeList = new ArrayList<String>();
rootDirectories = new ArrayList<String>();
filesToAvoid = new ArrayList<String>();
xmlFolders = new ArrayList<SourceCrawlerXMLFolder>();
File file = new File("translator.xml");
if (file.exists()) {
try {
Document doc = XMLHandler.loadXMLFile(file);
Node configNode = XMLHandler.getSubNode(doc, "translator-config");
referenceLocale = XMLHandler.getTagValue(configNode, "reference-locale");
singleMessagesFile = XMLHandler.getTagValue(configNode, "single-messages-file");
Node localeListNode = XMLHandler.getSubNode(configNode, "locale-list");
int nrLocale = XMLHandler.countNodes(localeListNode, "locale");
if (nrLocale>0) localeList.clear();
for (int i=0;i<nrLocale;i++) {
Node localeNode = XMLHandler.getSubNodeByNr(localeListNode, "locale", i);
String locale = XMLHandler.getTagValue(localeNode, "code");
localeList.add(locale);
}
Node rootsNode = XMLHandler.getSubNode(configNode, "source-directories");
int nrRoots = XMLHandler.countNodes(rootsNode, "root");
if (nrRoots>0) rootDirectories.clear();
for (int i=0;i<nrRoots;i++) {
Node rootNode = XMLHandler.getSubNodeByNr(rootsNode, "root", i);
String directory = XMLHandler.getNodeValue(rootNode);
rootDirectories.add(directory);
}
Node filesNode = XMLHandler.getSubNode(configNode, "files-to-avoid");
int nrFiles = XMLHandler.countNodes(filesNode, "filename");
if (nrFiles>0) filesToAvoid.clear();
for (int i=0;i<nrFiles;i++) {
Node fileNode = XMLHandler.getSubNodeByNr(filesNode, "filename", i);
String filename = XMLHandler.getNodeValue(fileNode);
filesToAvoid.add(filename);
}
Node foldersToScanNode = XMLHandler.getSubNode(configNode, "xml-folders-to-scan");
int nrFolders = XMLHandler.countNodes(foldersToScanNode, "xml-folder-to-scan");
if (nrFolders>0) xmlFolders.clear();
for (int i=0;i<nrFolders;i++) {
Node folderToScanNode = XMLHandler.getSubNodeByNr(foldersToScanNode, "xml-folder-to-scan", i);
String folderName = XMLHandler.getTagValue(folderToScanNode, "folder");
String wildcard = XMLHandler.getTagValue(folderToScanNode, "wildcard");
String keyPrefix = XMLHandler.getTagValue(folderToScanNode, "key-prefix");
SourceCrawlerXMLFolder xmlFolder = new SourceCrawlerXMLFolder(folderName, wildcard, keyPrefix);
Node elementsNode = XMLHandler.getSubNode(folderToScanNode, "elements-to-scan");
int nrElements = XMLHandler.countNodes(elementsNode, "element-to-scan");
for (int j=0;j<nrElements;j++) {
Node elementNode = XMLHandler.getSubNodeByNr(elementsNode, "element-to-scan", j);
String element = XMLHandler.getTagValue(elementNode, "element");
String tag = XMLHandler.getTagValue(elementNode, "tag");
String attribute = XMLHandler.getTagValue(elementNode, "attribute");
xmlFolder.getElements().add(new SourceCrawlerXMLElement(element, tag, attribute));
}
String defaultPackage = XMLHandler.getTagValue(folderToScanNode, "package-default");
xmlFolder.setDefaultPackage(defaultPackage);
Node packageExceptionsNode = XMLHandler.getSubNode(folderToScanNode, "package-exceptions");
int nrExceptions = XMLHandler.countNodes(packageExceptionsNode, "package-exception");
for (int j=0;j<nrExceptions;j++) {
Node packageExceptionNode = XMLHandler.getSubNodeByNr(packageExceptionsNode, "package-exception", j);
String startsWith = XMLHandler.getTagValue(packageExceptionNode, "starts-with");
String packageName = XMLHandler.getTagValue(packageExceptionNode, "package");
xmlFolder.getPackageExceptions().add(new SourceCrawlerPackageException(startsWith, packageName));
}
xmlFolders.add(xmlFolder);
}
System.out.println(xmlFolders.size()+" XML folders to scan:");
for (SourceCrawlerXMLFolder xmlFolder : xmlFolders) {
System.out.println("folder ["+xmlFolder.getFolder()+"] : wildcard ["+xmlFolder.getWildcard()+"] with "+xmlFolder.getElements().size()+" elements to scan for");
}
}
catch (Exception e) {
log.logError("Translator", "Error reading translator.xml", e);
}
}
}
public void open()
{
shell = new Shell(display);
shell.setLayout(new FillLayout());
shell.setText(APP_NAME);
shell.setImage(GUIResource.getInstance().getImageLogoSmall());
try
{
readFiles(rootDirectories);
}
catch(Exception e)
{
new ErrorDialog(shell, "Error reading translations", "There was an unexpected error reading the translations", e);
}
// Put something on the screen
sashform = new SashForm(shell, SWT.HORIZONTAL);
sashform.setLayout(new FormLayout());
addLists();
addGrid();
addListeners();
sashform.setWeights(new int[] { 20, 80 });
sashform.setVisible(true);
shell.pack();
refresh();
shell.setSize(1024, 768);
shell.open();
}
private void addListeners()
{
// In case someone dares to press the [X] in the corner ;-)
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { e.doit=quitFile(); } } );
wReload.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
int idx[] = wPackages.table.getSelectionIndices();
reload();
wPackages.table.setSelection(idx);
}
}
);
wZip.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
saveFilesToZip();
}
}
);
wClose.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
quitFile();
}
}
);
}
public void reload()
{
try
{
shell.setCursor(display.getSystemCursor(SWT.CURSOR_WAIT));
readFiles(rootDirectories);
shell.setCursor(null);
refresh();
}
catch(Exception e)
{
new ErrorDialog(shell, "Error loading data", "There was an unexpected error re-loading the data", e);
}
}
public boolean quitFile()
{
java.util.List<MessagesStore> changedMessagesStores = store.getChangedMessagesStores();
if (changedMessagesStores.size()>0) {
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("i18nDialog.ChangedFilesWhenExit",changedMessagesStores.size()+""));
mb.setText(Messages.getString("i18nDialog.Warning"));
int answer = mb.open();
if (answer==SWT.NO) return false;
}
WindowProperty winprop = new WindowProperty(shell);
props.setScreen(winprop);
props.saveProps();
shell.dispose();
display.dispose();
return true;
}
private void addLists()
{
Composite composite = new Composite(sashform, SWT.NONE);
props.setLook(composite);
FormLayout formLayout = new FormLayout();
formLayout.marginHeight = Const.FORM_MARGIN;
formLayout.marginWidth = Const.FORM_MARGIN;
composite.setLayout(formLayout);
wLocale = new List(composite, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
FormData fdLocale = new FormData();
fdLocale.left = new FormAttachment(0, 0);
fdLocale.right = new FormAttachment(100, 0);
fdLocale.top= new FormAttachment(0, 0);
fdLocale.bottom= new FormAttachment(20, 0);
wLocale.setLayoutData(fdLocale);
ColumnInfo[] colinfo=new ColumnInfo[]
{
new ColumnInfo(Messages.getString("i18nDialog.Packagename"), ColumnInfo.COLUMN_TYPE_TEXT, false, true),
};
wPackages = new TableView(new Variables(), composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER, colinfo, 1, true, null, props);
FormData fdPackages = new FormData();
fdPackages.left = new FormAttachment(0, 0);
fdPackages.right = new FormAttachment(100, 0);
fdPackages.top= new FormAttachment(wLocale, Const.MARGIN);
fdPackages.bottom= new FormAttachment(100, 0);
wPackages.setLayoutData(fdPackages);
wPackages.setSortable(false);
FormData fdComposite = new FormData();
fdComposite.left = new FormAttachment(0, 0);
fdComposite.right = new FormAttachment(100, 0);
fdComposite.top= new FormAttachment(0,0);
fdComposite.bottom= new FormAttachment(100, 0);
composite.setLayoutData(fdComposite);
// Add a selection listener.
wLocale.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { refreshGrid(); } } );
wPackages.table.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
refreshGrid();
}
}
);
composite.layout();
}
private void addGrid()
{
Composite composite = new Composite(sashform, SWT.NONE);
props.setLook(composite);
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
composite.setLayout(formLayout);
wReload = new Button(composite, SWT.NONE);
wReload.setText(Messages.getString("i18nDialog.Reload"));
wSave= new Button(composite, SWT.NONE);
wSave.setText(Messages.getString("i18nDialog.Save"));
wZip= new Button(composite, SWT.NONE);
wZip.setText(Messages.getString("i18nDialog.Zip"));
wZip.setToolTipText(Messages.getString("i18nDialog.Zip.Tip"));
wClose = new Button(composite, SWT.NONE);
wClose.setText(Messages.getString("i18nDialog.Close"));
BaseStepDialog.positionBottomButtons(composite, new Button[] { wReload, wSave, wZip, wClose, } , Const.MARGIN*3, null);
/*
wSearchG = new Button(composite, SWT.PUSH);
wSearchG.setText(" Search &key ");
FormData fdSearchG = new FormData();
fdSearchG.left = new FormAttachment(0, 0);
fdSearchG.bottom = new FormAttachment(100, 0);
wSearchG.setLayoutData(fdSearchG);
wNextG = new Button(composite, SWT.PUSH);
wNextG.setText(" Next ke&y ");
FormData fdNextG = new FormData();
fdNextG.left = new FormAttachment(wSearchG, Const.MARGIN);
fdNextG.bottom = new FormAttachment(100, 0);
wNextG.setLayoutData(fdNextG);
*/
int left = 25;
int middle = 40;
wAll = new Button(composite, SWT.CHECK);
wAll.setText(Messages.getString("i18nDialog.ShowAllkeys"));
props.setLook(wAll);
FormData fdAll = new FormData();
fdAll.left = new FormAttachment(0, 0);
fdAll.right = new FormAttachment(left, 0);
fdAll.bottom= new FormAttachment(wClose, -Const.MARGIN);
wAll.setLayoutData(fdAll);
Label wlTodo = new Label(composite, SWT.LEFT);
props.setLook(wlTodo);
wlTodo.setText(Messages.getString("i18nDialog.ToDoList"));
FormData fdlTodo = new FormData();
fdlTodo.left = new FormAttachment(0, 0);
fdlTodo.right = new FormAttachment(left, 0);
fdlTodo.top= new FormAttachment(0, 0);
wlTodo.setLayoutData(fdlTodo);
wTodo = new List(composite, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
FormData fdTodo = new FormData();
fdTodo.left = new FormAttachment(0, 0);
fdTodo.right = new FormAttachment(left, 0);
fdTodo.top= new FormAttachment(wlTodo, Const.MARGIN);
fdTodo.bottom= new FormAttachment(wAll, -Const.MARGIN);
wTodo.setLayoutData(fdTodo);
// The key
Label wlKey = new Label(composite, SWT.RIGHT);
wlKey.setText(Messages.getString("i18nDialog.TranslationKey"));
props.setLook(wlKey);
FormData fdlKey = new FormData();
fdlKey.left = new FormAttachment(left, Const.MARGIN);
fdlKey.right = new FormAttachment(middle, 0);
fdlKey.top= new FormAttachment(wlTodo, Const.MARGIN);
wlKey.setLayoutData(fdlKey);
wKey = new Text(composite, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
props.setLook(wKey);
FormData fdKey = new FormData();
fdKey.left = new FormAttachment(middle, Const.MARGIN);
fdKey.right = new FormAttachment(100, 0);
fdKey.top= new FormAttachment(wlTodo, Const.MARGIN);
wKey.setLayoutData(fdKey);
wKey.setEditable(false);
// The Main translation
Label wlMain = new Label(composite, SWT.RIGHT);
wlMain.setText(Messages.getString("i18nDialog.MainTranslation"));
props.setLook(wlMain);
FormData fdlMain = new FormData();
fdlMain.left = new FormAttachment(left, Const.MARGIN);
fdlMain.right = new FormAttachment(middle, 0);
fdlMain.top= new FormAttachment(wKey, Const.MARGIN);
wlMain.setLayoutData(fdlMain);
wMain = new Text(composite, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
props.setLook(wMain);
FormData fdMain = new FormData();
fdMain.left = new FormAttachment(middle, Const.MARGIN);
fdMain.right = new FormAttachment(100, 0);
fdMain.top= new FormAttachment(wKey, Const.MARGIN);
fdMain.bottom= new FormAttachment(wKey, 150+Const.MARGIN);
wMain.setLayoutData(fdMain);
wMain.setEditable(false);
wSearch = new Button(composite, SWT.PUSH);
wSearch.setText(Messages.getString("i18nDialog.Search"));
FormData fdSearch = new FormData();
fdSearch.right = new FormAttachment(middle, -Const.MARGIN*2);
fdSearch.top = new FormAttachment(wMain, 0, SWT.CENTER);
wSearch.setLayoutData(fdSearch);
wNext = new Button(composite, SWT.PUSH);
wNext.setText(Messages.getString("i18nDialog.Next"));
FormData fdNext = new FormData();
fdNext.right = new FormAttachment(middle, -Const.MARGIN*2);
fdNext.top = new FormAttachment(wSearch, Const.MARGIN*2);
wNext.setLayoutData(fdNext);
// A few lines of source code at the bottom...
Label wlSource = new Label(composite, SWT.RIGHT);
wlSource.setText(Messages.getString("i18nDialog.LineOfSourceCode"));
props.setLook(wlSource);
FormData fdlSource = new FormData();
fdlSource.left = new FormAttachment(left, Const.MARGIN);
fdlSource.right = new FormAttachment(middle, 0);
fdlSource.top = new FormAttachment(wClose, -100-Const.MARGIN);
wlSource.setLayoutData(fdlSource);
wSource = new Text(composite, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
props.setLook(wSource);
FormData fdSource = new FormData();
fdSource.left = new FormAttachment(middle, Const.MARGIN);
fdSource.right = new FormAttachment(100, 0);
fdSource.top = new FormAttachment(wClose, -100-Const.MARGIN);
fdSource.bottom = new FormAttachment(wClose, -Const.MARGIN);
wSource.setLayoutData(fdSource);
wSource.setEditable(false);
// The translation
Label wlValue = new Label(composite, SWT.RIGHT);
wlValue.setText(Messages.getString("i18nDialog.Translation"));
props.setLook(wlValue);
FormData fdlValue = new FormData();
fdlValue.left = new FormAttachment(left, Const.MARGIN);
fdlValue.right = new FormAttachment(middle, 0);
fdlValue.top = new FormAttachment(wMain, Const.MARGIN);
wlValue.setLayoutData(fdlValue);
wValue = new Text(composite, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL );
props.setLook(wValue);
FormData fdValue = new FormData();
fdValue.left = new FormAttachment(middle, Const.MARGIN);
fdValue.right = new FormAttachment(100, 0);
fdValue.top = new FormAttachment(wMain, Const.MARGIN);
fdValue.bottom = new FormAttachment(wSource, -Const.MARGIN);
wValue.setLayoutData(fdValue);
wValue.setEditable(true);
wApply = new Button(composite, SWT.PUSH);
wApply.setText(Messages.getString("i18nDialog.Apply"));
FormData fdApply = new FormData();
fdApply.right = new FormAttachment(middle, -Const.MARGIN*2);
fdApply.top = new FormAttachment(wValue, 0, SWT.CENTER);
wApply.setLayoutData(fdApply);
wApply.setEnabled(false);
wRevert = new Button(composite, SWT.PUSH);
wRevert.setText(Messages.getString("i18nDialog.Revert"));
FormData fdRevert = new FormData();
fdRevert.right = new FormAttachment(middle, -Const.MARGIN*2);
fdRevert.top = new FormAttachment(wApply, Const.MARGIN*2);
wRevert.setLayoutData(fdRevert);
wRevert.setEnabled(false);
wSearchV = new Button(composite, SWT.PUSH);
wSearchV.setText(Messages.getString("i18nDialog.Search"));
FormData fdSearchV = new FormData();
fdSearchV.right = new FormAttachment(middle, -Const.MARGIN*2);
fdSearchV.top = new FormAttachment(wRevert, Const.MARGIN*4);
wSearchV.setLayoutData(fdSearchV);
wNextV = new Button(composite, SWT.PUSH);
wNextV.setText(Messages.getString("i18nDialog.Next"));
FormData fdNextV = new FormData();
fdNextV.right = new FormAttachment(middle, -Const.MARGIN*2);
fdNextV.top = new FormAttachment(wSearchV, Const.MARGIN*2);
wNextV.setLayoutData(fdNextV);
wAll.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
refreshGrid();
}
}
);
wTodo.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
// If someone clicks on the todo list, we set the appropriate values
if (wTodo.getSelectionCount()==1) {
String key = wTodo.getSelection()[0];
showKeySelection(key);
}
}
}
);
wValue.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
// The main value got changed...
// Capture this automatically
lastValueChanged = true;
lastValue = wValue.getText();
wApply.setEnabled(true);
wRevert.setEnabled(true);
}
}
);
wApply.addSelectionListener(
new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
applyChangedValue();
}
}
);
wRevert.addSelectionListener(
new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
revertChangedValue();
}
}
);
wSave.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
saveFiles();
}
}
);
wSearch.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
search(referenceLocale);
}
}
);
wNext.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
searchAgain(referenceLocale);
}
}
);
wSearchV.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
search(selectedLocale);
}
}
);
wNextV.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
searchAgain(selectedLocale);
}
}
);
}
protected boolean saveFiles() {
java.util.List<MessagesStore> changedMessagesStores = store.getChangedMessagesStores();
if (changedMessagesStores.size()>0) {
StringBuffer msg = new StringBuffer();
for (MessagesStore messagesStore : changedMessagesStores) {
// Find the main locale variation for this messages store...
MessagesStore mainLocaleMessagesStore = store.findMainLocaleMessagesStore(messagesStore.getMessagesPackage());
String sourceDirectory = mainLocaleMessagesStore.getSourceDirectory(rootDirectories);
String filename = messagesStore.getSaveFilename(sourceDirectory);
messagesStore.setFilename(filename);
msg.append(filename).append(Const.CR);
}
EnterTextDialog dialog = new EnterTextDialog(shell, Messages.getString("i18nDialog.ChangedFiles"), Messages.getString("i18nDialog.ChangedMessagesFiles"), msg.toString());
if (dialog.open()!=null)
{
try
{
for (MessagesStore messagesStore : changedMessagesStores) {
messagesStore.write();
LogWriter.getInstance().logBasic(toString(), Messages.getString("i18n.Log.SavedMessagesFile",messagesStore.getFilename()));
}
}
catch(KettleException e) {
new ErrorDialog(shell, Messages.getString("i18n.UnexpectedError"), "There was an error saving the changed messages files:", e);
return false;
}
return true;
}
else
{
return false;
}
}
else {
// Nothing was saved.
// TODO: disable the button if nothing changed.
return true;
}
}
protected void saveFilesToZip() {
if (saveFiles()) {
java.util.List<MessagesStore> messagesStores = store.getMessagesStores(selectedLocale, null);
if (messagesStores.size()>0) {
StringBuffer msg = new StringBuffer();
for (MessagesStore messagesStore : messagesStores) {
// Find the main locale variation for this messages store...
MessagesStore mainLocaleMessagesStore = store.findMainLocaleMessagesStore(messagesStore.getMessagesPackage());
String sourceDirectory = mainLocaleMessagesStore.getSourceDirectory(rootDirectories);
String filename = messagesStore.getSaveFilename(sourceDirectory);
messagesStore.setFilename(filename);
msg.append(filename).append(Const.CR);
}
// Ask for the target filename if we're still here...
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String[] {"*.zip", "*"});
dialog.setFilterNames(new String[] {Messages.getString("System.FileType.ZIPFiles"), Messages.getString("System.FileType.AllFiles")});
if (dialog.open()!=null)
{
String zipFilename = dialog.getFilterPath()+System.getProperty("file.separator")+dialog.getFileName();
try
{
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFilename));
byte[] buf = new byte[1024];
for (MessagesStore messagesStore : messagesStores) {
FileInputStream in = new FileInputStream(messagesStore.getFilename());
out.putNextEntry(new ZipEntry(messagesStore.getFilename()));
int len;
while ((len=in.read(buf))>0) {
out.write(buf,0,len);
}
out.closeEntry();
in.close();
}
out.close();
}
catch(Exception e) {
new ErrorDialog(shell, Messages.getString("i18n.UnexpectedError"), "There was an error saving the changed messages files:", e);
}
}
}
}
}
protected void search(String searchLocale) {
// Ask for the search string...
EnterStringDialog dialog = new EnterStringDialog(shell, Const.NVL(searchString, ""), Messages.getString("i18nDialog.SearchKey"),"Search the translated '"+searchLocale+"' strings in this package");
searchString = dialog.open();
lastFoundKey = null;
searchAgain(searchLocale);
}
protected void searchAgain(String searchLocale) {
if (searchString!=null) {
// We want to search for key in the list here...
// That means we'll enter a String to search for in the values
String upperSearchString = searchString.toUpperCase();
boolean lastKeyFound = lastFoundKey==null;
// Search through all the main locale messages stores for the selected package
java.util.List<MessagesStore> mainLocaleMessagesStores = store.getMessagesStores(searchLocale, selectedMessagesPackage);
for (MessagesStore messagesStore : mainLocaleMessagesStores) {
for (String key : messagesStore.getMessagesMap().keySet()) {
String value = messagesStore.getMessagesMap().get(key);
String upperValue = value.toUpperCase();
if (upperValue.indexOf(upperSearchString)>=0) {
// OK, we found a key worthy of our attention...
if (lastKeyFound) {
int index = wTodo.indexOf(key);
if (index>=0) {
lastFoundKey = key;
wTodo.setSelection(index);
showKeySelection(wTodo.getSelection()[0]);
return;
}
}
if (key.equals(lastFoundKey)) {
lastKeyFound=true;
}
}
}
}
}
}
protected void showKeySelection(String key) {
if (!key.equals(selectedKey)) {
applyChangedValue();
}
if (selectedLocale!=null && key!=null && selectedMessagesPackage!=null) {
String mainValue = store.lookupKeyValue(referenceLocale, selectedMessagesPackage, key);
String value = store.lookupKeyValue(selectedLocale, selectedMessagesPackage, key);
KeyOccurrence keyOccurrence = crawler.getKeyOccurrence(key, selectedMessagesPackage);
wKey.setText(key);
wMain.setText(Const.NVL(mainValue, ""));
wValue.setText(Const.NVL(value, ""));
wSource.setText(keyOccurrence.getSourceLine());
// Focus on the entry field
// Put the cursor all the way at the back
wValue.setFocus();
wValue.setSelection(wValue.getText().length());
wValue.showSelection();
wValue.clearSelection();
selectedKey = key;
lastValueChanged=false;
wApply.setEnabled(false);
wRevert.setEnabled(false);
}
}
public void refreshGrid() {
applyChangedValue();
wTodo.removeAll();
wKey.setText("");
wMain.setText("");
wValue.setText("");
wSource.setText("");
selectedLocale = wLocale.getSelectionCount()==0 ? null : wLocale.getSelection()[0];
selectedMessagesPackage = wPackages.table.getSelectionCount()==0 ? null : wPackages.table.getSelection()[0].getText(1);
refreshPackages();
// Only continue with a locale & a messages package, otherwise we won't budge ;-)
if (selectedLocale!=null && selectedMessagesPackage!=null) {
// Get the list of keys that need a translation...
java.util.List<KeyOccurrence> todo = getTodoList(selectedLocale, selectedMessagesPackage, false);
String[] todoItems = new String[todo.size()];
for (int i=0;i<todoItems.length;i++) todoItems[i] = todo.get(i).getKey();
wTodo.setItems(todoItems);
}
}
private java.util.List<KeyOccurrence> getTodoList(String locale, String messagesPackage, boolean strict) {
// Get the list of keys that need a translation...
java.util.List<KeyOccurrence> keys = crawler.getOccurrencesForPackage(messagesPackage);
java.util.List<KeyOccurrence> todo = new ArrayList<KeyOccurrence>();
for (KeyOccurrence keyOccurrence : keys) {
// Avoid the System keys. Those are taken care off in a different package
if (showKey(keyOccurrence.getKey(), keyOccurrence.getMessagesPackage())) {
String value = store.lookupKeyValue(locale, messagesPackage, keyOccurrence.getKey());
if ( Const.isEmpty(value) || ( wAll.getSelection() && !strict) ) {
todo.add(keyOccurrence);
}
}
}
return todo;
}
private void applyChangedValue() {
// Hang on, before we clear it all, did we have a previous value?
int todoIndex = wTodo.getSelectionIndex();
if (selectedKey!=null && selectedLocale!=null && selectedMessagesPackage!=null && lastValueChanged) {
// Store the last modified value
if (!Const.isEmpty(lastValue)) {
store.storeValue(selectedLocale, selectedMessagesPackage, selectedKey, lastValue);
lastValueChanged = false;
if (!wAll.getSelection()) {
wTodo.remove(selectedKey);
if (wTodo.getSelectionIndex()<0) {
// Select the next one in the list...
if (todoIndex>wTodo.getItemCount()) todoIndex=wTodo.getItemCount()-1;
if (todoIndex>=0 && todoIndex<wTodo.getItemCount()) {
wTodo.setSelection(todoIndex);
showKeySelection(wTodo.getSelection()[0]);
} else {
refreshGrid();
}
}
}
}
lastValue = null;
wApply.setEnabled(false);
wRevert.setEnabled(false);
}
}
private void revertChangedValue() {
lastValueChanged = false;
refreshGrid();
}
public void refresh()
{
refreshLocale();
refreshPackages();
refreshGrid();
}
public void refreshPackages()
{
int index = wPackages.getSelectionIndex();
// OK, we have a distinct list of packages to work with...
wPackages.table.removeAll();
for (int i=0;i<messagesPackages.size();i++) {
String messagesPackage = messagesPackages.get(i);
TableItem item = new TableItem(wPackages.table, SWT.NONE);
item.setText(1, messagesPackage);
// count the number of keys for the package that are NOT yet translated...
if (selectedLocale!=null) {
java.util.List<KeyOccurrence> todo = getTodoList(selectedLocale, messagesPackage, true);
if (todo.size()>50) {
item.setBackground(GUIResource.getInstance().getColorRed());
} else if (todo.size()>25) {
item.setBackground(GUIResource.getInstance().getColorOrange());
} else if (todo.size()>10) {
item.setBackground(GUIResource.getInstance().getColorYellow());
} else if (todo.size()>5) {
item.setBackground(GUIResource.getInstance().getColorBlue());
} else if (todo.size()>0) {
item.setBackground(GUIResource.getInstance().getColorGreen());
}
}
}
if (messagesPackages.size()==0) {
new TableItem(wPackages.table, SWT.NONE);
} else {
wPackages.setRowNums();
wPackages.optWidth(true);
}
if (index>=0) {
wPackages.table.setSelection(index);
wPackages.table.showSelection();
}
}
public void refreshLocale()
{
// OK, we have a distinct list of locale to work with...
wLocale.removeAll();
wLocale.setItems(localeList.toArray(new String[localeList.size()]));
}
public String toString()
{
return APP_NAME;
}
public static void main(String[] args)
{
Display display = new Display();
LogWriter log = LogWriter.getInstance();
PropsUI.init(display, Props.TYPE_PROPERTIES_SPOON);
Translator2 translator = new Translator2(display);
translator.loadConfiguration();
translator.open();
try
{
while (!display.isDisposed ())
{
if (!display.readAndDispatch()) display.sleep ();
}
}
catch(Throwable e)
{
log.logError(APP_NAME, Messages.getString("i18n.UnexpectedError",e.getMessage()));
log.logError(APP_NAME, Const.getStackTracker(e));
}
}
} |
package se.ericthelin.fractions;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
public class FractionTest {
@Test(expected = NullPointerException.class)
public void rejectsNullText() {
Fraction.of(null);
}
@Test
public void rejectsTextWithLetters() {
// Given
String textWithLetters = "foo 7/5 bar";
try {
// When
Fraction.of(textWithLetters);
// Then
fail("Nothing thrown");
} catch (InvalidFractionFormatException e) {
assertThat(e.getText(), is(textWithLetters));
}
}
@Test
public void rejectsTextWithMultipleSlashes() {
// Given
String textWithMultipleSlashes = "7/5/3";
try {
// When
Fraction.of(textWithMultipleSlashes);
// Then
fail("Nothing thrown");
} catch (InvalidFractionFormatException e) {
assertThat(e.getText(), is(textWithMultipleSlashes));
}
}
@Test
public void rejectsTextWithZeroDenominator() {
// Given
String textWithZeroDenominator = "7/0";
try {
// When
Fraction.of(textWithZeroDenominator);
// Then
fail("Nothing thrown");
} catch (ZeroDenominatorException e) {
assertThat(e.getNumerator(), is(7));
}
}
@Test
public void rejectsTextWithZeroNumeratorAndDenominator() {
// Given
String textWithZeroNumeratorAndDenominator = "0/0";
try {
// When
Fraction.of(textWithZeroNumeratorAndDenominator);
// Then
fail("Nothing thrown");
} catch (ZeroDenominatorException e) {
assertThat(e.getNumerator(), is(0));
}
}
@Test
public void acceptsTextWithJustDigits() {
Fraction.of("7");
}
@Test
public void acceptsNegativeInteger() {
Fraction.of("-7");
}
@Test
public void hasMeaningfulStringRepresentation() {
assertThat(Fraction.of("7/5").toString(), is("7/5"));
}
@Test
public void simplifiesStringRepresentationWhenDenominatorIsOne() {
assertThat(Fraction.of("7/1").toString(), is("7"));
}
@Test
public void hidesDenominatorOfWholeNumber() {
assertThat(Fraction.of("7").toString(), is("7"));
}
@Test
public void includesMinusSignOfNegativeOfWholeNumberInStringRepresentation() {
assertThat(Fraction.of("-7").toString(), is("-7"));
}
@Test
public void simplifiesStringRepresentationOfZeroFraction() {
assertThat(Fraction.of("0/5").toString(), is("0"));
}
@Test
public void usesGreatestCommonDivisorToSimplifyRepresentation() {
assertThat(Fraction.of("4/6").toString(), is("2/3"));
}
@Test
public void beginsStringRepresentationOfNegativeFractionHavingNegativeNumeratorWithMinusSign() {
assertThat(Fraction.of("-1/3").toString(), is("-1/3"));
}
@Test
public void beginsStringRepresentationOfNegativeFractionHavingNegativeDenominatorWithMinusSign() {
assertThat(Fraction.of("1/-3").toString(), is("-1/3"));
}
@Test
public void removesDoubleMinusSignsFromStringRepresentation() {
assertThat(Fraction.of("-1/-3").toString(), is("1/3"));
}
@Test
public void isEqualToSelf() {
// Given
Fraction instance = Fraction.of("7/5");
// Then
assertTrue(instance.equals(instance));
}
@Test
public void isEqualToFractionWithSimilarValues() {
assertTrue(Fraction.of("7/5").equals(Fraction.of("7/5")));
}
@Test
public void isEqualToZeroWhenNumeratorIsZero() {
assertTrue(Fraction.of("0/5").equals(Fraction.of("0")));
}
@Test
public void isEqualToFractionWithEqualNumericValue() {
assertTrue(Fraction.of("4/6").equals(Fraction.of("2/3")));
}
@Test
public void isEqualToFractionWithNegatedValues() {
assertTrue(Fraction.of("1/3").equals(Fraction.of("-1/-3")));
}
@Test
public void isEqualToOtherNegativeFractionHavingNegatedValues() {
assertTrue(Fraction.of("-1/3").equals(Fraction.of("1/-3")));
}
@Test
public void doestNotCareAboutPlacementOfSignForEquality() {
assertTrue(Fraction.of("1/-3").equals(Fraction.of("-1/3")));
}
@Test
public void isNotEqualToNull() {
assertFalse(Fraction.of("7/5").equals(null));
}
@Test
public void isNotEqualToDifferentType() {
assertFalse(Fraction.of("7/5").equals("7/5"));
}
@Test
public void isNotEqualToFractionWithSimilarNumeratorButDifferentDenominator() {
assertFalse(Fraction.of("7/5").equals(Fraction.of("7/4")));
}
@Test
public void isNotEqualToFractionWithSimilarDenominatorButDifferentNumerator() {
assertFalse(Fraction.of("7/5").equals(Fraction.of("8/5")));
}
@Test
public void canAddZeroToZero() {
assertThat(Fraction.ZERO.plus(Fraction.ZERO), is(Fraction.ZERO));
}
@Test
public void canAddZeroToWholeNumber() {
assertThat(Fraction.of("7").plus(Fraction.ZERO), is(Fraction.of("7")));
}
@Test
public void canAddWholeNumbers() {
assertThat(Fraction.of("7").plus(Fraction.of("5")), is(Fraction.of("12")));
}
@Test
public void canAddWholeNumberToFraction() {
assertThat(Fraction.of("4/3").plus(Fraction.of("5")), is(Fraction.of("19/3")));
}
@Test
public void canAddFractionToWholeNumber() {
assertThat(Fraction.of("5").plus(Fraction.of("4/3")), is(Fraction.of("19/3")));
}
@Test
public void canAddFractionToFraction() {
assertThat(Fraction.of("7/3").plus(Fraction.of("4/5")), is(Fraction.of("47/15")));
}
@Test
public void reducesSumUsingGreatestCommonDivisor() {
assertThat(Fraction.of("3/8").plus(Fraction.of("1/8")), is(Fraction.of("1/2")));
}
} |
package se.ericthelin.fractions;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
public class FractionTest {
@Test(expected = NullPointerException.class)
public void rejectsNullText() {
Fraction.of(null);
}
@Test
public void rejectsTextWithLetters() {
// Given
String textWithLetters = "foo 7/5 bar";
try {
// When
Fraction.of(textWithLetters);
// Then
fail("Nothing thrown");
} catch (InvalidFractionFormatException e) {
assertThat(e.getText(), is(textWithLetters));
}
}
@Test
public void rejectsTextWithMultipleSlashes() {
// Given
String textWithMultipleSlashes = "7/5/3";
try {
// When
Fraction.of(textWithMultipleSlashes);
// Then
fail("Nothing thrown");
} catch (InvalidFractionFormatException e) {
assertThat(e.getText(), is(textWithMultipleSlashes));
}
}
@Test
public void rejectsTextWithZeroDenominator() {
// Given
String textWithZeroDenominator = "7/0";
try {
// When
Fraction.of(textWithZeroDenominator);
// Then
fail("Nothing thrown");
} catch (ZeroDenominatorException e) {
assertThat(e.getNumerator(), is(7));
}
}
@Test
public void rejectsTextWithZeroNumeratorAndDenominator() {
// Given
String textWithZeroNumeratorAndDenominator = "0/0";
try {
// When
Fraction.of(textWithZeroNumeratorAndDenominator);
// Then
fail("Nothing thrown");
} catch (ZeroDenominatorException e) {
assertThat(e.getNumerator(), is(0));
}
}
@Test
public void acceptsTextWithJustDigits() {
Fraction.of("7");
}
@Test
public void hasMeaningfulStringRepresentation() {
assertThat(Fraction.of("7/5").toString(), is("7/5"));
}
@Test
public void simplifiesStringRepresentationWhenDenominatorIsOne() {
assertThat(Fraction.of("7/1").toString(), is("7"));
}
@Test
public void hidesDenominatorOfWholeNumber() {
assertThat(Fraction.of("7").toString(), is("7"));
}
@Test
public void simplifiesStringRepresentationOfZeroFraction() {
assertThat(Fraction.of("0/5").toString(), is("0"));
}
@Test
public void usesGreatestCommonDivisorToSimplifyRepresentation() {
assertThat(Fraction.of("4/6").toString(), is("2/3"));
}
@Test
public void isEqualToSelf() {
// Given
Fraction instance = Fraction.of("7/5");
// Then
assertTrue(instance.equals(instance));
}
@Test
public void isEqualToFractionWithSimilarValues() {
assertTrue(Fraction.of("7/5").equals(Fraction.of("7/5")));
}
@Test
public void isEqualToZeroWhenNumeratorIsZero() {
assertTrue(Fraction.of("0/5").equals(Fraction.of("0")));
}
@Test
public void isEqualToFractionWithEqualNumericalValue() {
assertTrue(Fraction.of("4/6").equals(Fraction.of("2/3")));
}
@Test
public void isNotEqualToNull() {
assertFalse(Fraction.of("7/5").equals(null));
}
@Test
public void isNotEqualToDifferentType() {
assertFalse(Fraction.of("7/5").equals("7/5"));
}
@Test
public void isNotEqualToFractionWithSimilarNumeratorButDifferentDenominator() {
assertFalse(Fraction.of("7/5").equals(Fraction.of("7/4")));
}
@Test
public void isNotEqualToFractionWithSimilarDenominatorButDifferentNumerator() {
assertFalse(Fraction.of("7/5").equals(Fraction.of("8/5")));
}
@Test
public void canAddZeroToZero() {
assertThat(Fraction.ZERO.plus(Fraction.ZERO), is(Fraction.ZERO));
}
@Test
public void canAddZeroToWholeNumber() {
assertThat(Fraction.of("7").plus(Fraction.ZERO), is(Fraction.of("7")));
}
@Test
public void canAddWholeNumbers() {
assertThat(Fraction.of("7").plus(Fraction.of("5")), is(Fraction.of("12")));
}
@Test
public void canAddWholeNumberToFraction() {
assertThat(Fraction.of("4/3").plus(Fraction.of("5")), is(Fraction.of("19/3")));
}
@Test
public void canAddFractionToWholeNumber() {
assertThat(Fraction.of("5").plus(Fraction.of("4/3")), is(Fraction.of("19/3")));
}
@Test
public void canAddFractions() {
assertThat(Fraction.of("7/3").plus(Fraction.of("4/5")), is(Fraction.of("47/15")));
}
} |
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.PolygonRegion;
import com.badlogic.gdx.graphics.g2d.PolygonSpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.utils.Disposable;
public class PolygonRegionTest extends GdxTest {
@Override
public boolean needsGL20 () {
return false;
}
PolygonSpriteBatch batch;
PolygonRegionDebugRenderer debugRenderer;
Texture texture;
OrthographicCamera camera;
PolygonRegion region;
PolygonRegion region2;
boolean usePolygonBatch = true;
@Override
public void create () {
texture = new Texture(Gdx.files.internal("data/tree.png"));
region = new PolygonRegion(new TextureRegion(texture), Gdx.files.internal("data/tree.psh"));
// create a region from an arbitrary set of vertices (a triangle in this case)
region2 = new PolygonRegion(new TextureRegion(texture), new float[] {0,0,100,100,0,100});
camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.position.x = 0;
camera.position.y = 0;
batch = new PolygonSpriteBatch();
debugRenderer = new PolygonRegionDebugRenderer();
Gdx.input.setInputProcessor(this);
}
@Override
public void resize (int width, int height) {
camera.viewportWidth = width;
camera.viewportHeight = height;
camera.update();
}
@Override
public void render () {
GL10 gl = Gdx.gl10;
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
Gdx.gl.glClearColor(0.25f, 0.25f, 0.25f, 1.0f);
camera.apply(Gdx.gl10);
batch.setProjectionMatrix(camera.combined);
batch.begin();
// draw bot regions side-by-side
float width = 256;
float x = -width;
batch.draw(region, x, -128, 256, 256);
batch.draw(region2, x + width + 10, -128, 256, 256);
batch.end();
debugRenderer.setProjectionMatrix(camera.combined);
debugRenderer.draw(region, x, -128, 0, 0, 256, 256, 1, 1, 0);
debugRenderer.draw(region2, x + width + 10, -128, 0, 0, 256, 256, 1, 1, 0);
}
@Override
public void dispose () {
debugRenderer.dispose();
texture.dispose();
batch.dispose();
}
public class PolygonRegionDebugRenderer implements Disposable {
ShapeRenderer renderer;
public PolygonRegionDebugRenderer () {
renderer = new ShapeRenderer();
}
public void draw (PolygonRegion region, float x, float y, float originX, float originY, float width, float height,
float scaleX, float scaleY, float rotation) {
float[] localVertices = region.getLocalVertices();
float[] texCoords = region.getTextureCoords();
// bottom left and top right corner points relative to origin
final float worldOriginX = x + originX;
final float worldOriginY = y + originY;
float sX = width / region.getRegion().getRegionWidth();
float sY = height / region.getRegion().getRegionHeight();
float fx1, fx2, fx3, px1, px2, px3;
float fy1, fy2, fy3, py1, py2, py3;
final float cos = MathUtils.cosDeg(rotation);
final float sin = MathUtils.sinDeg(rotation);
renderer.setColor(Color.RED);
renderer.begin(ShapeType.Line);
for (int i = 0; i < localVertices.length; i += 6) {
fx1 = localVertices[i] * sX;
fy1 = localVertices[i + 1] * sY;
fx2 = localVertices[i + 2] * sX;
fy2 = localVertices[i + 3] * sY;
fx3 = localVertices[i + 4] * sX;
fy3 = localVertices[i + 5] * sY;
fx1 -= originX;
fy1 -= originY;
fx2 -= originX;
fy2 -= originY;
fx3 -= originX;
fy3 -= originY;
if (scaleX != 1 || scaleY != 1) {
fx1 *= scaleX;
fy1 *= scaleY;
fx2 *= scaleX;
fy2 *= scaleY;
fx3 *= scaleX;
fy3 *= scaleY;
}
px1 = cos * fx1 - sin * fy1;
py1 = sin * fx1 + cos * fy1;
px2 = cos * fx2 - sin * fy2;
py2 = sin * fx2 + cos * fy2;
px3 = cos * fx3 - sin * fy3;
py3 = sin * fx3 + cos * fy3;
px1 += worldOriginX;
py1 += worldOriginY;
px2 += worldOriginX;
py2 += worldOriginY;
px3 += worldOriginX;
py3 += worldOriginY;
renderer.line(px1, py1, px2, py2);
renderer.line(px2, py2, px3, py3);
renderer.line(px3, py3, px1, py1);
}
renderer.end();
renderer.setColor(Color.BLUE);
renderer.begin(ShapeType.FilledCircle);
renderer.filledCircle(worldOriginX, worldOriginY, 4);
renderer.end();
// Calculate the bounding rect, is there a better way?!
// bottom left and top right corner points relative to origin
fx1 = -originX;
fy1 = -originY;
fx2 = width - originX;
fy2 = height - originY;
// scale
if (scaleX != 1 || scaleY != 1) {
fx1 *= scaleX;
fy1 *= scaleY;
fx2 *= scaleX;
fy2 *= scaleY;
}
// construct corner points, start from top left and go counter clockwise
final float p1x = fx1;
final float p1y = fy1;
final float p2x = fx1;
final float p2y = fy2;
final float p3x = fx2;
final float p3y = fy2;
final float p4x = fx2;
final float p4y = fy1;
float x1;
float y1;
float x2;
float y2;
float x3;
float y3;
float x4;
float y4;
// rotate
if (rotation != 0) {
x1 = cos * p1x - sin * p1y;
y1 = sin * p1x + cos * p1y;
x2 = cos * p2x - sin * p2y;
y2 = sin * p2x + cos * p2y;
x3 = cos * p3x - sin * p3y;
y3 = sin * p3x + cos * p3y;
x4 = x1 + (x3 - x2);
y4 = y3 - (y2 - y1);
} else {
x1 = p1x;
y1 = p1y;
x2 = p2x;
y2 = p2y;
x3 = p3x;
y3 = p3y;
x4 = p4x;
y4 = p4y;
}
x1 += worldOriginX;
y1 += worldOriginY;
x2 += worldOriginX;
y2 += worldOriginY;
x3 += worldOriginX;
y3 += worldOriginY;
x4 += worldOriginX;
y4 += worldOriginY;
// Draw the bounding rectangle
renderer.setColor(Color.GREEN);
renderer.begin(ShapeType.Line);
renderer.line(x1, y1, x2, y2);
renderer.line(x2, y2, x3, y3);
renderer.line(x3, y3, x4, y4);
renderer.line(x4, y4, x1, y1);
renderer.end();
}
public void setProjectionMatrix (Matrix4 matrix) {
this.renderer.setProjectionMatrix(matrix);
}
@Override
public void dispose () {
renderer.dispose();
}
}
} |
package com.gallatinsystems.survey.domain;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class WebForm {
public static Set<String> unsupportedQuestionTypes(){
Set<String> unsupportedTypes = new HashSet<String>();
unsupportedTypes.add(Question.Type.GEOSHAPE.toString());
unsupportedTypes.add(Question.Type.SIGNATURE.toString());
unsupportedTypes.add(Question.Type.CADDISFLY.toString());
return unsupportedTypes;
}
public static boolean validQuestionGroups(final Survey survey){
return survey.getQuestionGroupMap().values().stream().filter(i -> i.getRepeatable()).collect(Collectors.toList()).size() == 0;
}
public static Boolean validSurveyGroup(final SurveyGroup surveyGroup){
return !surveyGroup.getMonitoringGroup();
}
public static boolean validWebForm(final SurveyGroup surveyGroup, final Survey survey, final List<Question> questions){
boolean validQuestionGroups = validQuestionGroups(survey);
if (!validQuestionGroups) return false;
boolean validSurveyGroup = validSurveyGroup(surveyGroup);
if (!validSurveyGroup) return false;
List<Question> validQuestions = questions.stream().filter(i -> !unsupportedQuestionTypes().contains(i.getType().toString())).collect(Collectors.toList());
return validQuestions.size() == questions.size();
}
} |
package to.etc.domui.sass;
import com.vaadin.sass.internal.*;
import com.vaadin.sass.internal.ScssContext.*;
import com.vaadin.sass.internal.handler.*;
import com.vaadin.sass.internal.parser.*;
import com.vaadin.sass.internal.resolver.*;
import com.vaadin.sass.internal.visitor.*;
import org.w3c.css.sac.*;
import to.etc.domui.server.*;
import to.etc.domui.server.parts.*;
import to.etc.domui.trouble.*;
import to.etc.domui.util.resources.*;
import to.etc.util.*;
import javax.annotation.*;
import java.io.*;
final public class SassPartFactory implements IBufferedPartFactory, IUrlPart {
/**
* Accepts .scss resources as sass stylesheets, and passes them through the
* sass compiler, returning the result as a normal .css stylesheet.
*/
@Override
public boolean accepts(@Nonnull String rurl) {
return rurl.endsWith(".scss");
}
@Nonnull @Override public Object decodeKey(@Nonnull String rurl, @Nonnull IExtendedParameterInfo param) throws Exception {
return rurl;
}
@Override public void generate(@Nonnull PartResponse pr, @Nonnull DomApplication da, @Nonnull Object key, @Nonnull IResourceDependencyList rdl) throws Exception {
String rurl = (String) key;
CapturingErrorHandler errorHandler = new CapturingErrorHandler();
//errorHandler.setWarningsAreErrors(true);
//-- Define resolvers
ScssStylesheet parent = new ScssStylesheet();
parent.addResolver(new WebAppResolver(rdl));
parent.setCharset("utf-8");
// Parse stylesheet
ScssStylesheet scss = ScssStylesheet.get(rurl, parent, new SCSSDocumentHandlerImpl(), errorHandler);
if(scss == null) {
throw new ThingyNotFoundException("The scss file " + rurl + " could not be found.");
}
// Compile scss -> css
compile(scss, UrlMode.RELATIVE);
if(errorHandler.hasError()) {
throw new RuntimeException("SASS compilation failed: " + errorHandler.toString());
}
String s = errorHandler.toString();
if(s != null && s.length() > 0)
System.err.println("SASS error on " + rurl + ":\n" + s);
pr.setMime("text/css");
try(OutputStream outputStream = pr.getOutputStream()) {
OutputStreamWriter osw = new OutputStreamWriter(outputStream, "utf-8");
scss.write(osw, ! DomApplication.get().inDevelopmentMode());
osw.close();
}
}
/**
* Alternative to the compile method from the sass code, this should allow
* adding variables into the compilation context so that theme compilation
* can be done with it.
*
* @param scss
* @param urlMode
* @throws Exception
*/
private void compile(ScssStylesheet scss, UrlMode urlMode) throws Exception {
ScssContext context = new ScssContext(urlMode);
LexicalUnitImpl lxu = LexicalUnitImpl.createIdent(0, 0, "#abc");
Variable var = new Variable("inputColor", lxu);
context.addVariable(var);
scss.traverse(context);
ExtendNodeHandler.modifyTree(context, scss);
}
/**
* Resolves sass resources using DomUI's resolution mechanisms, and tracks
* the resources used for auto recompile.
*/
final private class WebAppResolver implements ScssStylesheetResolver {
@Nonnull
private final IResourceDependencyList m_dependencyList;
public WebAppResolver(IResourceDependencyList dependencyList) {
m_dependencyList = dependencyList;
}
@Override public InputSource resolve(ScssStylesheet parentStylesheet, String identifier) {
DomApplication app = DomApplication.get();
IResourceRef ref = app.getAppFileOrResource(identifier);
m_dependencyList.add(ref);
if(!ref.exists()) {
return null;
}
try {
return new InputSource(new InputStreamReader(ref.getInputStream(), "utf-8"));
} catch(Exception x) {
throw WrappedException.wrap(x);
}
}
}
/**
* Captures all messages in a string.
*/
final private class CapturingErrorHandler extends SCSSErrorHandler {
final private StringBuilder m_sb = new StringBuilder();
private boolean m_hasError;
@Override public void warning(CSSParseException e) throws CSSException {
render("warning", e);
}
private void render(String type, CSSParseException e) {
m_sb.append(e.getURI())
.append("(")
.append(e.getLineNumber())
.append(':')
.append(e.getColumnNumber())
.append(") ")
.append(type)
.append(": ")
.append(e.getMessage())
.append("\n");
}
@Override public void error(CSSParseException e) throws CSSException {
m_hasError = true;
render("error", e);
}
@Override public void fatalError(CSSParseException e) throws CSSException {
m_hasError = true;
render("fatal error", e);
}
public boolean hasError() {
return m_hasError;
}
@Override public String toString() {
return m_sb.toString();
}
}
} |
package org.sakaiproject.evaluation.tool;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.evaluation.constant.EvalConstants;
import org.sakaiproject.evaluation.logic.EvalAuthoringService;
import org.sakaiproject.evaluation.logic.EvalCommonLogic;
import org.sakaiproject.evaluation.logic.EvalEvaluationService;
import org.sakaiproject.evaluation.logic.EvalEvaluationSetupService;
import org.sakaiproject.evaluation.logic.EvalSettings;
import org.sakaiproject.evaluation.logic.exceptions.BlankRequiredFieldException;
import org.sakaiproject.evaluation.logic.exceptions.InvalidDatesException;
import org.sakaiproject.evaluation.logic.exceptions.InvalidEvalCategoryException;
import org.sakaiproject.evaluation.logic.externals.ExternalHierarchyLogic;
import org.sakaiproject.evaluation.logic.model.EvalHierarchyNode;
import org.sakaiproject.evaluation.model.EvalAssignGroup;
import org.sakaiproject.evaluation.model.EvalAssignHierarchy;
import org.sakaiproject.evaluation.model.EvalAssignUser;
import org.sakaiproject.evaluation.model.EvalEmailTemplate;
import org.sakaiproject.evaluation.model.EvalEvaluation;
import org.sakaiproject.evaluation.model.EvalTemplate;
import org.sakaiproject.evaluation.tool.locators.AssignGroupSelectionSettings;
import org.sakaiproject.evaluation.tool.locators.EmailTemplateWBL;
import org.sakaiproject.evaluation.tool.locators.EvaluationBeanLocator;
import org.sakaiproject.evaluation.tool.locators.SelectedEvaluationUsersLocator;
import org.sakaiproject.evaluation.utils.ArrayUtils;
import org.sakaiproject.evaluation.utils.EvalUtils;
import uk.org.ponder.messageutil.TargettedMessage;
import uk.org.ponder.messageutil.TargettedMessageList;
/**
* This action bean helps with the evaluation setup process where needed, this is a pea
*
* @author Aaron Zeckoski (aaron@caret.cam.ac.uk)
*/
public class SetupEvalBean {
private static Log log = LogFactory.getLog(SetupEvalBean.class);
private final String EVENT_EVAL_REOPENED = "eval.evaluation.reopened";
/**
* This should be set to true while we are creating an evaluation
*/
public boolean creatingEval = false;
/**
* This should be set to the evalId we are currently working with
*/
public Long evaluationId;
/**
* This should be set to the templateId we are assigning to the evaluation
*/
public Long templateId;
/**
* This should be set to the emailTemplateId we are assigning to the
* evaluation
*/
public Long emailTemplateId;
/**
* This is set to the type of email template when resetting the evaluation
* to use default templates
*/
public String emailTemplateType;
/**
* Set to true if we are reopening this evaluation
*/
public boolean reOpening = false;
/**
* Whether to navigate to administrate_search view after saving settings
*/
public boolean returnToSearchResults = false;
/**
* The value of searchString needed by AdministrateSearchProducer.fillCommponents()
* to restore administrate_search view after saving settings
*/
public String adminSearchString = null;
/**
* The value of page needed by AdministrateSearchProducer.fillCommponents()
* to restore administrate_search view after saving settings
*/
public int adminSearchPage = 0;
/**
* the selected groups ids to bind to this evaluation when creating it
*/
public String[] selectedGroupIDs = new String[] {};
/**
* the selected hierarchy nodes to bind to this evaluation when creating it
*/
public String[] selectedHierarchyNodeIDs = new String[] {};
/**
* the selected option (eg. for TAs and Instructors) in this evaluation. see
* {@link EvalEvaluation.selectionSettings}
*/
public Map<String, String> selectionOptions = new HashMap<String, String>();
/**
* selection value to populate {@link SetupEvalBean.selectionOptions}
*/
public String selectionInstructors, selectionAssistants;
private EvalEvaluationService evaluationService;
public void setEvaluationService(EvalEvaluationService evaluationService) {
this.evaluationService = evaluationService;
}
private EvalCommonLogic commonLogic;
public void setCommonLogic(EvalCommonLogic commonLogic) {
this.commonLogic = commonLogic;
}
private ExternalHierarchyLogic hierarchyLogic;
public void setExternalHierarchyLogic(ExternalHierarchyLogic logic) {
this.hierarchyLogic = logic;
}
private EvalEvaluationSetupService evaluationSetupService;
public void setEvaluationSetupService(
EvalEvaluationSetupService evaluationSetupService) {
this.evaluationSetupService = evaluationSetupService;
}
private EvalAuthoringService authoringService;
public void setAuthoringService(EvalAuthoringService authoringService) {
this.authoringService = authoringService;
}
private EvaluationBeanLocator evaluationBeanLocator;
public void setEvaluationBeanLocator(
EvaluationBeanLocator evaluationBeanLocator) {
this.evaluationBeanLocator = evaluationBeanLocator;
}
private EmailTemplateWBL emailTemplateWBL;
public void setEmailTemplateWBL(EmailTemplateWBL emailTemplateWBL) {
this.emailTemplateWBL = emailTemplateWBL;
}
private TargettedMessageList messages;
public void setMessages(TargettedMessageList messages) {
this.messages = messages;
}
private Locale locale;
public void setLocale(Locale locale) {
this.locale = locale;
}
private SelectedEvaluationUsersLocator selectedEvaluationUsersLocator;
public void setSelectedEvalautionUsersLocator(SelectedEvaluationUsersLocator selectedEvaluationUsersLocator) {
this.selectedEvaluationUsersLocator = selectedEvaluationUsersLocator;
}
private AssignGroupSelectionSettings assignGroupSelectionSettings;
public void setAssignGroupSelectionSettings(
AssignGroupSelectionSettings assignGroupSelectionSettings) {
this.assignGroupSelectionSettings = assignGroupSelectionSettings;
}
private EvalSettings settings;
public void setSettings(EvalSettings settings) {
this.settings = settings;
}
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
/**
* sets he locale on the date formatter correctly
*/
public void init() {
df = DateFormat.getDateInstance(DateFormat.LONG, locale);
}
// Action bindings
/**
* Handles removal action from the remove eval view
*/
public String removeEvalAction() {
if (evaluationId == null) {
throw new IllegalArgumentException("evaluationId cannot be null");
}
EvalEvaluation eval = evaluationService.getEvaluationById(evaluationId);
evaluationSetupService.deleteEvaluation(evaluationId, commonLogic
.getCurrentUserId());
messages.addMessage(new TargettedMessage(
"controlevaluations.delete.user.message", new Object[] { eval
.getTitle() }, TargettedMessage.SEVERITY_INFO));
return "success";
}
/**
* Handles close eval action from control evaluations view
*/
public String closeEvalAction() {
if (evaluationId == null) {
throw new IllegalArgumentException("evaluationId cannot be null");
}
EvalEvaluation eval = evaluationSetupService.closeEvaluation(
evaluationId, commonLogic.getCurrentUserId());
messages.addMessage(new TargettedMessage(
"controlevaluations.closed.user.message", new Object[] { eval
.getTitle() }, TargettedMessage.SEVERITY_INFO));
return "success";
}
/**
* Handles reopening evaluation action (from eval settings view)
*/
public String reopenEvalAction() {
if (evaluationId == null) {
throw new IllegalArgumentException("evaluationId cannot be null");
}
EvalEvaluation eval = evaluationService.getEvaluationById(evaluationId);
// TODO reopen action
// evaluationSetupService.deleteEvaluation(evaluationId,
// commonLogic.getCurrentUserId());
messages.addMessage(new TargettedMessage(
"controlevaluations.reopen.user.message", new Object[] { eval
.getTitle() }, TargettedMessage.SEVERITY_INFO));
return "success";
}
/**
* Handles saving and assigning email templates to an evaluation, can just
* assign the email template if the emailTemplateId is set or will save and
* assign the one in the locator
*/
public String saveAndAssignEmailTemplate() {
if (evaluationId == null) {
throw new IllegalArgumentException("evaluationId and emailTemplateId cannot be null");
}
EvalEmailTemplate emailTemplate = null;
if (emailTemplateId == null) {
// get it from the locator
emailTemplateWBL.saveAll();
emailTemplate = emailTemplateWBL.getCurrentEmailTemplate();
} else {
// just load up and assign the template and do not save it
emailTemplate = evaluationService.getEmailTemplate(emailTemplateId);
}
// assign to the evaluation
evaluationSetupService.assignEmailTemplate(emailTemplate.getId(), evaluationId, null,
commonLogic.getCurrentUserId());
// user message
EvalEvaluation eval = evaluationService.getEvaluationById(evaluationId);
messages.addMessage(new TargettedMessage("controlemailtemplates.template.assigned.message",
new Object[] { emailTemplate.getType(), emailTemplate.getSubject(),
eval.getTitle() }, TargettedMessage.SEVERITY_INFO));
return "successAssign";
}
/**
* Handles resetting the evaluation to use the default template
*/
public String resetToDefaultEmailTemplate() {
if (evaluationId == null || emailTemplateType == null) {
throw new IllegalArgumentException(
"evaluationId and emailTemplateType cannot be null");
}
// reset to default email template
evaluationSetupService.assignEmailTemplate(null, evaluationId,
emailTemplateType, commonLogic.getCurrentUserId());
return "successReset";
}
// NOTE: these are the simple navigation methods
// 4 steps to create an evaluation: 1) Create -> 2) Settings -> 3) Assign ->
// 4) Confirm/Save
/**
* Completed the initial creation page where the template is chosen
*/
public String completeCreateAction() {
// set the template on the evaluation in the bean locator
if (templateId == null) {
throw new IllegalStateException(
"The templateId is null, it must be set so it can be assigned to the new evaluation");
}
EvalEvaluation eval = evaluationBeanLocator.getCurrentEval();
if (eval == null) {
throw new IllegalStateException(
"The evaluation cannot be retrieved from the bean locator, critical failure");
}
EvalTemplate template = authoringService.getTemplateById(templateId);
eval.setTemplate(template);
// save the new evaluation
try {
setSelectionOptions();
evaluationBeanLocator.saveAll();
} catch (BlankRequiredFieldException e) {
messages.addMessage(new TargettedMessage(e.messageKey,
new Object[] { e.fieldName },
TargettedMessage.SEVERITY_ERROR));
throw new RuntimeException(e); // should not be needed but it is
}
return "evalSettings";
}
/**
* Updated or initially set the evaluation settings
*/
public String completeSettingsAction() {
// set the template on the evaluation in the bean locator if not null
if (templateId != null) {
EvalEvaluation eval = evaluationBeanLocator.getCurrentEval();
if (eval != null) {
EvalTemplate template = authoringService
.getTemplateById(templateId);
eval.setTemplate(template);
}
}
try {
setSelectionOptions();
evaluationBeanLocator.saveAll();
} catch (BlankRequiredFieldException e) {
messages.addMessage(new TargettedMessage(e.messageKey, new Object[] { e.fieldName },
TargettedMessage.SEVERITY_ERROR));
throw new RuntimeException(e); // should not be needed but it is
} catch (InvalidDatesException e) {
messages.addMessage(new TargettedMessage(e.messageKey, new Object[] {},
TargettedMessage.SEVERITY_ERROR));
throw new RuntimeException(e); // should not be needed but it is
} catch (InvalidEvalCategoryException e) {
messages.addMessage(new TargettedMessage(e.messageKey, new Object[] {},
TargettedMessage.SEVERITY_ERROR));
throw new RuntimeException(e); // should not be needed but it is
}
EvalEvaluation eval = evaluationBeanLocator.getCurrentEval();
String destination = "controlEvals";
if(this.returnToSearchResults) {
destination = "adminSearch";
} else if (EvalConstants.EVALUATION_STATE_PARTIAL.equals(eval.getState())) {
destination = "evalAssign";
} else {
if (reOpening) {
// we are reopening the evaluation
commonLogic.registerEntityEvent(EVENT_EVAL_REOPENED, eval);
messages.addMessage(new TargettedMessage(
"controlevaluations.reopen.user.message",
new Object[] { eval.getTitle() },
TargettedMessage.SEVERITY_INFO));
} else {
messages.addMessage(new TargettedMessage(
"evalsettings.updated.message", new Object[] { eval
.getTitle() }, TargettedMessage.SEVERITY_INFO));
}
}
return destination;
}
// NOTE: There is no action for the 3) assign step because that one just passes the data
// straight to the confirm view
// TODO - how do we handle removing assignments? (Currently not supported)
/**
* Complete the creation process for an evaluation (view all the current
* settings and assignments and create eval/assignments), this will save the
* node/group assignments that were submitted and reconcile this list with
* the previous set of nodes/groups and remove any that are now missing
* before adding the new ones
*/
public String completeConfirmAction() {
if (evaluationId == null) {
throw new IllegalArgumentException(
"evaluationId and emailTemplateId cannot be null");
}
// make sure that the submitted nodes are valid and populate the nodes
// list
Set<EvalHierarchyNode> nodes = null;
if (selectedHierarchyNodeIDs.length > 0) {
nodes = hierarchyLogic.getNodesByIds(selectedHierarchyNodeIDs);
if (nodes.size() != selectedHierarchyNodeIDs.length) {
throw new IllegalArgumentException(
"Invalid set of hierarchy node ids submitted which "
+ "includes node Ids which are not in the hierarchy: "
+ ArrayUtils.arrayToString(selectedHierarchyNodeIDs));
}
} else {
nodes = new HashSet<EvalHierarchyNode>();
}
// at least 1 node or group must be selected
if (selectedGroupIDs.length == 0 && nodes.isEmpty()) {
messages.addMessage(new TargettedMessage(
"assigneval.invalid.selection", new Object[] {},
TargettedMessage.SEVERITY_ERROR));
return "fail";
}
EvalEvaluation eval = evaluationService.getEvaluationById(evaluationId);
if (EvalConstants.EVALUATION_STATE_PARTIAL.equals(eval.getState())) {
// save eval and assign groups
// save the new evaluation state (moving from partial), set to true
// should fix up the state automatically
evaluationSetupService.saveEvaluation(eval, commonLogic
.getCurrentUserId(), true);
// NOTE - this allows the evaluation to be saved with zero assign
// groups if this fails
// save all the assignments (hierarchy and group)
List<EvalAssignHierarchy> assignedHierList = evaluationSetupService
.setEvalAssignments(evaluationId, selectedHierarchyNodeIDs,
selectedGroupIDs, false);
// failsafe check (to make sure we are not creating an eval with no
// assigned groups)
if (assignedHierList.isEmpty()) {
evaluationSetupService.deleteEvaluation(evaluationId,
commonLogic.getCurrentUserId());
throw new IllegalStateException(
"Invalid evaluation created with no assignments! Destroying evaluation: "
+ evaluationId);
}
messages.addMessage(new TargettedMessage(
"controlevaluations.create.user.message", new Object[] {
eval.getTitle(), df.format(eval.getStartDate()) },
TargettedMessage.SEVERITY_INFO));
} else {
// just assigning groups
if (EvalUtils.checkStateAfter(eval.getState(),
EvalConstants.EVALUATION_STATE_ACTIVE, false)) {
throw new IllegalStateException(
"User cannot update evaluation assignments after an evaluation is active and complete");
}
// make sure we cannot remove assignments for active evals
boolean append = false;
if (EvalUtils.checkStateAfter(eval.getState(),
EvalConstants.EVALUATION_STATE_INQUEUE, false)) {
append = true; // can only append after active
}
// save all the assignments (hierarchy and group)
evaluationSetupService.setEvalAssignments(evaluationId,
selectedHierarchyNodeIDs, selectedGroupIDs, append);
}
//Work with selection options
if( ((Boolean)settings.get(EvalSettings.ENABLE_INSTRUCTOR_ASSISTANT_SELECTION)).booleanValue() ){
Map<Long, List<EvalAssignGroup>> evalAssignGroupMap = evaluationService.getAssignGroupsForEvals(new Long[] {evaluationId}, true, false);
List<EvalAssignGroup> evalAssignGroups = evalAssignGroupMap.get(evaluationId);
// Query DB only once to get all EvalAssignUsers
List<EvalAssignUser> evalUsers = evaluationService
.getParticipantsForEval(evaluationId, null, null, null, EvalEvaluationService.STATUS_ANY, null, null);
for (EvalAssignGroup assignGroup : evalAssignGroups) {
String currentGroupId = assignGroup.getEvalGroupId();
// Save Assistant/Instructor selections now. EVALSYS-618
String[] deselectedInstructors = selectedEvaluationUsersLocator.getDeselectedInstructors(currentGroupId);
String[] deselectedAssistants = selectedEvaluationUsersLocator.getDeselectedAssistants(currentGroupId);
String[] orderingInstructors = selectedEvaluationUsersLocator.getOrderingForInstructors(currentGroupId);
String[] orderingAssistants = selectedEvaluationUsersLocator.getOrderingForAssistants(currentGroupId);
updateEvalAssignUsers(deselectedInstructors, orderingInstructors, EvalAssignUser.TYPE_EVALUATEE, currentGroupId, evalUsers);
updateEvalAssignUsers(deselectedAssistants, orderingAssistants, EvalAssignUser.TYPE_ASSISTANT,currentGroupId, evalUsers);
// set selection settings for assign group
String settingInstructor = assignGroupSelectionSettings.getInstructorSetting(currentGroupId);
String settingAssistant = assignGroupSelectionSettings.getAssistantSetting(currentGroupId);
if( settingInstructor == null || "".equals(settingInstructor)){
assignGroup.setSelectionOption(EvalAssignGroup.SELECTION_TYPE_INSTRUCTOR, EvalAssignGroup.SELECTION_OPTION_MULTIPLE );
}else{
assignGroup.setSelectionOption(EvalAssignGroup.SELECTION_TYPE_INSTRUCTOR, settingInstructor );
}
if( settingAssistant == null || "".equals(settingAssistant)){
assignGroup.setSelectionOption(EvalAssignGroup.SELECTION_TYPE_ASSISTANT, EvalAssignGroup.SELECTION_OPTION_MULTIPLE );
}else{
assignGroup.setSelectionOption(EvalAssignGroup.SELECTION_TYPE_ASSISTANT, settingAssistant );
}
//Save selection settings
evaluationSetupService.saveAssignGroup(assignGroup, commonLogic.getCurrentUserId());
}
}
return "controlEvals";
}
// NOTE: these are the support methods
/**
* Turn a boolean selection map into an array of the keys
*
* @param booleanSelectionMap
* a map of string -> boolean (from RSF bound booleans)
* @return an array of the keys where boolean is true
*/
public static String[] makeArrayFromBooleanMap(Map<String, Boolean> booleanSelectionMap) {
List<String> hierNodeIdList = new ArrayList<String>();
for (Entry<String, Boolean> entry: booleanSelectionMap.entrySet()) {
if ( EvalUtils.safeBool(entry.getValue()) ) {
hierNodeIdList.add(entry.getKey());
}
}
String[] selectedHierarchyNodeIds = hierNodeIdList.toArray(new String[] {});
return selectedHierarchyNodeIds;
}
/**
* Create {@link Map} object to inject into Eval and set Selection Options
* eg.for {@link EvalAssignGroup.SELECTION_TYPE_INSTRUCTOR} and
* {@link EvalAssignGroup.SELECTION_TYPE_ASSISTANT}
*
* @return selectionOptions {@link Map}
*/
private Map<String, String> setSelectionOptions() {
selectionOptions.put(EvalAssignGroup.SELECTION_TYPE_INSTRUCTOR,
selectionInstructors);
selectionOptions.put(EvalAssignGroup.SELECTION_TYPE_ASSISTANT,
selectionAssistants);
return selectionOptions;
}
/**
* Remove this {@link List} of userIds from being assigned to current
* evaluation
*
* @param deselected
* @param ordering
* @param type either {@link EvalAssignUser.TYPE_EVALUATEE} or {@link EvalAssignUser.TYPE_ASSISTANT}
* @param currentGroupId
* @param evalUsers
*/
private void updateEvalAssignUsers(String[] deselected, String[] ordering, String type, String currentGroupId, List<EvalAssignUser> evalUsers) {
if (deselected != null && deselected.length > 0){
List<String> deselectedList = Arrays.asList(deselected);
List<String> orderingList = Arrays.asList(ordering);
for (EvalAssignUser user : evalUsers) {
String userId = user.getUserId();
if(currentGroupId.equals( user.getEvalGroupId().toString() ) && type.equals( user.getType()) ){
if (deselectedList.contains( userId )) {
user.setStatus(EvalAssignUser.STATUS_REMOVED);
}else{
user.setStatus(EvalAssignUser.STATUS_LINKED);
}
// set users' selection order
if (orderingList.contains( userId )){
int listOrder = orderingList.indexOf(userId) + 1;
user.setListOrder( listOrder );
}
}
}
}
}
} |
package com.cocosw.accessory.utils;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import java.util.ArrayList;
import java.util.List;
/**
* Detects phone shaking. If > 75% of the samples taken in the past 0.5s are
* accelerating, the device is a) shaking, or b) free falling 1.84m (h =
* 1/2*g*t^2*3/4).
*
* @author Bob Lee (bob@squareup.com)
* @author Eric Burke (eric@squareup.com)
*/
public class ShakeDetector implements SensorEventListener {
/**
* When the magnitude of total acceleration exceeds this
* value, the phone is accelerating.
*/
private static final int ACCELERATION_THRESHOLD = 13;
/**
* Listens for shakes.
*/
public interface Listener {
/**
* Called on the main thread when the device is shaken.
*/
void hearShake();
}
private final SampleQueue queue = new SampleQueue();
private final Listener listener;
private SensorManager sensorManager;
private Sensor accelerometer;
public ShakeDetector(Listener listener) {
this.listener = listener;
}
/**
* Starts listening for shakes on devices with appropriate hardware.
*
* @returns true if the device supports shake detection.
*/
public boolean start(SensorManager sensorManager) {
// Already started?
if (accelerometer != null) {
return true;
}
accelerometer = sensorManager.getDefaultSensor(
Sensor.TYPE_ACCELEROMETER);
// If this phone has an accelerometer, listen to it.
if (accelerometer != null) {
this.sensorManager = sensorManager;
sensorManager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_FASTEST);
}
return accelerometer != null;
}
/**
* Stops listening. Safe to call when already stopped. Ignored on devices
* without appropriate hardware.
*/
public void stop() {
if (accelerometer != null) {
sensorManager.unregisterListener(this, accelerometer);
sensorManager = null;
accelerometer = null;
}
}
@Override
public void onSensorChanged(SensorEvent event) {
boolean accelerating = isAccelerating(event);
long timestamp = event.timestamp;
queue.add(timestamp, accelerating);
if (queue.isShaking()) {
queue.clear();
listener.hearShake();
}
}
/**
* Returns true if the device is currently accelerating.
*/
private boolean isAccelerating(SensorEvent event) {
float ax = event.values[0];
float ay = event.values[1];
float az = event.values[2];
// Instead of comparing magnitude to ACCELERATION_THRESHOLD,
// compare their squares. This is equivalent and doesn't need the
// actual magnitude, which would be computed using (expesive) Math.sqrt().
final double magnitudeSquared = ax * ax + ay * ay + az * az;
return magnitudeSquared > ACCELERATION_THRESHOLD * ACCELERATION_THRESHOLD;
}
/**
* Queue of samples. Keeps a running average.
*/
static class SampleQueue {
/**
* Window size in ns. Used to compute the average.
*/
private static final long MAX_WINDOW_SIZE = 500000000; // 0.5s
private static final long MIN_WINDOW_SIZE = MAX_WINDOW_SIZE >> 1; // 0.25s
/**
* Ensure the queue size never falls below this size, even if the device
* fails to deliver this many events during the time window. The LG Ally
* is one such device.
*/
private static final int MIN_QUEUE_SIZE = 4;
private final SamplePool pool = new SamplePool();
private Sample oldest;
private Sample newest;
private int sampleCount;
private int acceleratingCount;
/**
* Adds a sample.
*
* @param timestamp in nanoseconds of sample
* @param accelerating true if > {@link #ACCELERATION_THRESHOLD}.
*/
void add(long timestamp, boolean accelerating) {
// Purge samples that proceed window.
purge(timestamp - MAX_WINDOW_SIZE);
// Add the sample to the queue.
Sample added = pool.acquire();
added.timestamp = timestamp;
added.accelerating = accelerating;
added.next = null;
if (newest != null) {
newest.next = added;
}
newest = added;
if (oldest == null) {
oldest = added;
}
// Update running average.
sampleCount++;
if (accelerating) {
acceleratingCount++;
}
}
/**
* Removes all samples from this queue.
*/
void clear() {
while (oldest != null) {
Sample removed = oldest;
oldest = removed.next;
pool.release(removed);
}
newest = null;
sampleCount = 0;
acceleratingCount = 0;
}
/**
* Purges samples with timestamps older than cutoff.
*/
void purge(long cutoff) {
while (sampleCount >= MIN_QUEUE_SIZE
&& oldest != null && cutoff - oldest.timestamp > 0) {
// Remove sample.
Sample removed = oldest;
if (removed.accelerating) {
acceleratingCount
}
sampleCount
oldest = removed.next;
if (oldest == null) {
newest = null;
}
pool.release(removed);
}
}
/**
* Copies the samples into a list, with the oldest entry at index 0.
*/
List<Sample> asList() {
List<Sample> list = new ArrayList<Sample>();
Sample s = oldest;
while (s != null) {
list.add(s);
s = s.next;
}
return list;
}
/**
* Returns true if we have enough samples and more than 3/4 of those samples
* are accelerating.
*/
boolean isShaking() {
return newest != null
&& oldest != null
&& newest.timestamp - oldest.timestamp >= MIN_WINDOW_SIZE
&& acceleratingCount >= (sampleCount >> 1) + (sampleCount >> 2);
}
}
/**
* An accelerometer sample.
*/
static class Sample {
/**
* Time sample was taken.
*/
long timestamp;
/**
* If acceleration > {@link #ACCELERATION_THRESHOLD}.
*/
boolean accelerating;
/**
* Next sample in the queue or pool.
*/
Sample next;
}
/**
* Pools samples. Avoids garbage collection.
*/
static class SamplePool {
private Sample head;
/**
* Acquires a sample from the pool.
*/
Sample acquire() {
Sample acquired = head;
if (acquired == null) {
acquired = new Sample();
} else {
// Remove instance from pool.
head = acquired.next;
}
return acquired;
}
/**
* Returns a sample to the pool.
*/
void release(Sample sample) {
sample.next = head;
head = sample;
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
} |
package VASSAL.build.module.map;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JComponent;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import VASSAL.build.Buildable;
import VASSAL.build.GameModule;
import VASSAL.build.module.Map;
import VASSAL.counters.ColoredBorder;
import VASSAL.counters.Deck;
import VASSAL.counters.DeckVisitor;
import VASSAL.counters.EventFilter;
import VASSAL.counters.GamePiece;
import VASSAL.counters.Immobilized;
import VASSAL.counters.KeyBuffer;
import VASSAL.counters.PieceFinder;
import VASSAL.counters.PieceVisitorDispatcher;
import VASSAL.counters.Properties;
import VASSAL.counters.Stack;
import VASSAL.tools.swing.SwingUtils;
/**
* This component listens for mouse clicks on a map and draws the selection
* rectangle.
*
* If the user clicks on a {@link GamePiece}, that piece is added to the
* {@link KeyBuffer}. {@link #draw(Graphics, Map)} is responsible for
* drawing the mouse selection rectangle, and
* {@link #mouseDragged(MouseEvent)} is responsible for triggering repaint
* events as the selection rectangle is moved.
*
* @see Map#addLocalMouseListener
*/
public class KeyBufferer extends MouseAdapter implements Buildable, MouseMotionListener, Drawable {
protected Map map;
protected Rectangle selection;
protected Point anchor;
protected Color color = Color.black;
protected int thickness = 3;
protected GamePiece bandSelectPiece = null;
private enum BandSelectType {
NONE,
NORMAL,
SPECIAL
}
@Override
public void addTo(Buildable b) {
map = (Map) b;
map.addLocalMouseListenerFirst(this);
map.getView().addMouseMotionListener(this);
map.addDrawComponent(this);
}
@Override
public void add(Buildable b) {
}
@Override
public Element getBuildElement(Document doc) {
return doc.createElement(getClass().getName());
}
@Override
public void build(Element e) {
}
@Override
public void mousePressed(MouseEvent e) {
if (e.isConsumed()) {
return;
}
final KeyBuffer kbuf = KeyBuffer.getBuffer();
GamePiece p = map.findPiece(e.getPoint(), PieceFinder.PIECE_IN_STACK);
// Don't clear the buffer until we find the clicked-on piece
// Because selecting a piece affects its visibility
EventFilter filter = null;
BandSelectType bandSelect = BandSelectType.NONE;
if (p != null) {
filter = (EventFilter) p.getProperty(Properties.SELECT_EVENT_FILTER);
if (SwingUtils.isVanillaLeftButtonDown(e) && Boolean.TRUE.equals(p.getProperty(Properties.NON_MOVABLE))) {
// Don't "eat" band-selects if unit found is non-movable
bandSelect = BandSelectType.SPECIAL;
}
}
boolean ignoreEvent = filter != null && filter.rejectEvent(e);
if (p != null && !ignoreEvent) {
boolean movingStacksPickupUnits = (Boolean) GameModule.getGameModule().getPrefs().getValue(Map.MOVING_STACKS_PICKUP_UNITS);
if (!kbuf.contains(p)) {
if (!e.isShiftDown() && !SwingUtils.isSelectionToggle(e)) {
kbuf.clear();
}
// RFE 1629255 - If the top piece of an unexpanded stack is left-clicked
// while not selected, then select all of the pieces in the stack
if (movingStacksPickupUnits ||
p.getParent() == null ||
p.getParent().isExpanded() ||
SwingUtils.isSelectionToggle(e) ||
Boolean.TRUE.equals(p.getProperty(Properties.SELECTED))) {
kbuf.add(p);
}
else {
Stack s = p.getParent();
s.asList().forEach(gamePiece -> KeyBuffer.getBuffer().add(gamePiece));
}
// End RFE 1629255
}
else {
// RFE 1659481 Ctrl-click deselects clicked units
if (SwingUtils.isSelectionToggle(e) && Boolean.TRUE.equals(p.getProperty(Properties.SELECTED))) {
Stack s = p.getParent();
if (s == null) {
kbuf.remove(p);
}
else if (!s.isExpanded()) {
s.asList().forEach(gamePiece -> KeyBuffer.getBuffer().remove(gamePiece));
}
else {
kbuf.remove(p);
}
}
// End RFE 1659481
}
final GamePiece to_front = p.getParent() != null ? p.getParent() : p;
map.getPieceCollection().moveToFront(to_front);
}
else {
bandSelect = BandSelectType.NORMAL; //BR// Allowed to band-select
}
if (bandSelect != BandSelectType.NONE) {
bandSelectPiece = null;
if (!e.isShiftDown() && !SwingUtils.isSelectionToggle(e)) { // No deselect if shift key down
kbuf.clear();
//BR// This section allows band-select to be attempted from non-moving pieces w/o preventing click-to-select from working
if (bandSelect == BandSelectType.SPECIAL && p != null && !ignoreEvent) {
kbuf.add(p);
bandSelectPiece = p;
}
}
anchor = map.mapToComponent(e.getPoint());
selection = new Rectangle(anchor.x, anchor.y, 0, 0);
if (map.getHighlighter() instanceof ColoredBorder) {
ColoredBorder b = (ColoredBorder) map.getHighlighter();
color = b.getColor();
thickness = b.getThickness();
}
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (selection == null) {
return;
}
PieceVisitorDispatcher d = createDragSelector(
!SwingUtils.isSelectionToggle(e), e.isAltDown(), map.componentToMap(selection)
);
// If it was a legit band-select drag (not just a click), our special case
// only applies if piece is allowed to be band-selected
if (bandSelectPiece != null) {
final EventFilter bandFilter = (EventFilter) bandSelectPiece.getProperty(Properties.BAND_SELECT_EVENT_FILTER);
final boolean pieceAllowedToBeBandSelected = bandFilter != null && !e.isAltDown() && bandFilter instanceof Immobilized.UseAlt;
if (pieceAllowedToBeBandSelected) {
final Point finish = map.mapToComponent(e.getPoint());
// Open to suggestions about a better way to distinguish "click" from
// "lasso" (not that Vassal doesn't already suck immensely at
// click-vs-drag threshhold). FWIW, this "works".
final boolean isLasso = finish.distance(anchor) >= 10;
if (isLasso) {
bandSelectPiece = null;
}
}
}
// RFE 1659481 Don't clear the entire selection buffer if either shift
// or control is down - we select/deselect lassoed counters instead
if (bandSelectPiece == null && !e.isShiftDown() && !SwingUtils.isSelectionToggle(e)) {
KeyBuffer.getBuffer().clear();
}
map.apply(d);
repaintSelectionRect();
selection = null;
}
/**
* This PieceVisitorDispatcher determines what to do with pieces on the
* map when the player finished dragging a rectangle to select pieces
*
* @return
*/
protected PieceVisitorDispatcher createDragSelector(
boolean selecting,
boolean altDown,
Rectangle mapsel) {
return new PieceVisitorDispatcher(
new KBDeckVisitor(selecting, altDown, mapsel)
);
}
public class KBDeckVisitor implements DeckVisitor {
boolean selecting = false;
boolean altDown = false;
Rectangle mapsel;
public KBDeckVisitor(boolean b, boolean c, Rectangle ms) {
selecting = b;
altDown = c;
mapsel = ms;
}
@Override
public Object visitDeck(Deck d) {
return null;
}
@Override
public Object visitStack(Stack s) {
if (s.topPiece() != null) {
final KeyBuffer kbuf = KeyBuffer.getBuffer();
if (s instanceof Deck) {
s.asList().forEach(kbuf::remove); // Clear any deck *members* out of the KeyBuffer.
return null;
}
if (s.isExpanded()) {
Point[] pos = new Point[s.getPieceCount()];
map.getStackMetrics().getContents(s, pos, null, null, s.getPosition().x, s.getPosition().y);
for (int i = 0; i < pos.length; ++i) {
if (mapsel.contains(pos[i])) {
if (selecting) {
kbuf.add(s.getPieceAt(i));
}
else {
kbuf.remove(s.getPieceAt(i));
}
}
}
}
else if (mapsel.contains(s.getPosition())) {
s.asList().forEach(selecting ? kbuf::add : kbuf::remove);
}
}
return null;
}
// Handle non-stacked units, including Does Not Stack units
// Does Not Stack units deselect normally once selected
@Override
public Object visitDefault(GamePiece p) {
Stack s = p.getParent();
if (s != null && s instanceof Deck) {
// Clear any deck *members* out of the KeyBuffer.
// (yes, members of decks can be does-not-stack)
KeyBuffer.getBuffer().remove(p);
return null;
}
if (mapsel.contains(p.getPosition()) && !Boolean.TRUE.equals(p.getProperty(Properties.INVISIBLE_TO_ME))) {
if (selecting) {
final EventFilter filter = (EventFilter) p.getProperty(Properties.SELECT_EVENT_FILTER);
final EventFilter bandFilter = (EventFilter) p.getProperty(Properties.BAND_SELECT_EVENT_FILTER);
final boolean altSelect = (altDown && filter instanceof Immobilized.UseAlt);
final boolean altBand = (altDown && bandFilter instanceof Immobilized.UseAlt);
if ((filter == null || altSelect) && ((bandFilter == null) || altBand)) { //BR// Band-select filtering support
KeyBuffer.getBuffer().add(p);
}
}
else {
KeyBuffer.getBuffer().remove(p);
}
}
return null;
}
}
protected void repaintSelectionRect() {
final int ht = thickness / 2 + thickness % 2;
final int ht2 = 2*ht;
final JComponent view = map.getView();
// left
view.repaint(selection.x - ht,
selection.y - ht,
ht2,
selection.height + ht2);
// right
view.repaint(selection.x + selection.width - ht,
selection.y - ht,
ht2,
selection.height + ht2);
// top
view.repaint(selection.x - ht,
selection.y - ht,
selection.width + ht2,
ht2);
// bottom
view.repaint(selection.x - ht,
selection.y + selection.width - ht,
selection.width + ht2,
ht2);
}
/**
* Sets the new location of the selection rectangle.
*/
@Override
public void mouseDragged(MouseEvent e) {
if (selection == null || !SwingUtils.isVanillaLeftButtonDown(e)) {
return;
}
repaintSelectionRect();
final int ex = e.getX();
final int ey = e.getY();
selection.x = Math.min(ex, anchor.x);
selection.y = Math.min(ey, anchor.y);
selection.width = Math.abs(ex - anchor.x);
selection.height = Math.abs(ey - anchor.y);
repaintSelectionRect();
}
@Override
public void mouseMoved(MouseEvent e) {
}
@Override
public void draw(Graphics g, Map map) {
if (selection == null) {
return;
}
final Graphics2D g2d = (Graphics2D) g;
final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
final Stroke str = g2d.getStroke();
g2d.setStroke(new BasicStroke((float)(thickness * os_scale)));
g2d.setColor(color);
g2d.drawRect(
(int)(selection.x * os_scale),
(int)(selection.y * os_scale),
(int)(selection.width * os_scale),
(int)(selection.height * os_scale)
);
g2d.setStroke(str);
}
@Override
public boolean drawAboveCounters() {
return true;
}
} |
package org.joml;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.NumberFormat;
/**
* Represents a 2D vector with single-precision.
*
* @author RGreenlees
* @author Kai Burjack
*/
public class Vector2f implements Serializable, Externalizable {
public float x;
public float y;
/**
* Create a new {@link Vector2f} and initialize its components to zero.
*/
public Vector2f() {
}
/**
* Create a new {@link Vector2f} and initialize its components to the given values.
*
* @param x
* the x value
* @param y
* the y value
*/
public Vector2f(float x, float y) {
this.x = x;
this.y = y;
}
/**
* Create a new {@link Vector2f} and initialize its components to the one of the given vector.
*
* @param v
* the {@link Vector2f} to copy the values from
*/
public Vector2f(Vector2f v) {
x = v.x;
y = v.y;
}
/**
* Set the x and y attributes to the supplied values.
*
* @param x
* the x value to set
* @param y
* the y value to set
* @return this
*/
public Vector2f set(float x, float y) {
this.x = x;
this.y = y;
return this;
}
/**
* Set this {@link Vector2f} to the values of v.
*
* @param v
* the vector to copy from
* @return this
*/
public Vector2f set(Vector2f v) {
x = v.x;
y = v.y;
return this;
}
/**
* Store one perpendicular vector of <code>v</code> in <code>dest</code>.
*
* @param v
* the vector to build one perpendicular vector of
* @param dest
* will hold the result
*/
public static void perpendicular(Vector2f v, Vector2f dest) {
dest.x = v.y;
dest.y = v.x * -1;
}
/**
* Set this vector to be one of its perpendicular vectors.
*
* @return this
*/
public Vector2f perpendicular() {
return set(y, x * -1);
}
/**
* Subtract <code>b</code> from <code>a</code> and store the result in <code>dest</code>.
*
* @param a
* the first operand
* @param b
* the second operand
* @param dest
* will hold the result of <code>a - b</code>
*/
public static void sub(Vector2f a, Vector2f b, Vector2f dest) {
dest.x = a.x - b.x;
dest.y = a.y - b.y;
}
/**
* Subtract <code>v</code> from this vector.
*
* @param v
* the vector to subtract from this
* @return this
*/
public Vector2f sub(Vector2f v) {
x -= v.x;
y -= v.y;
return this;
}
/**
* Subtract <tt>(x, y)</tt> from this vector.
*
* @return this
*/
public Vector2f sub(float x, float y) {
this.x -= x;
this.y -= y;
return this;
}
/**
* Return the dot product of <code>a</code> and <code>b</code>.
*/
public static float dot(Vector2f a, Vector2f b) {
return a.x * b.x + a.y * b.y;
}
/**
* Return the dot product of this vector and <code>v</code>
*/
public float dot(Vector2f v) {
return x * v.x + y * v.y;
}
/**
* Return the cosinus of the angle between this vector and the supplied vector. Use this instead of Math.cos(this.angle(v)).
* @return the cosinus of the angle
* @see #angle(Vector2f)
*/
public float angleCos(Vector2f v) {
return angleCos(this, v);
}
/**
* Return the cosinus of the angle between the supplied vectors. Use this instead of Math.cos(angle(v1, v2)).
* @return the cosinus of the angle
* @see #angle(Vector2f, Vector2f)
*/
public static float angleCos(Vector2f v1, Vector2f v2) {
float length1 = (float) Math.sqrt((v1.x * v1.x) + (v1.y * v1.y));
float length2 = (float) Math.sqrt((v2.x * v2.x) + (v2.y * v2.y));
float dot = (v1.x * v2.x) + (v1.y * v2.y);
return dot / (length1 * length2);
}
/**
* Return the angle between this vector and the supplied vector.
* @return the angle, in radians
* @see #angleCos(Vector2f)
*/
public float angle(Vector2f v) {
return angle(this, v);
}
/**
* Return the angle between the supplied vectors.
* @return the angle, in radians
* @see #angleCos(Vector2f, Vector2f)
*/
public static float angle(Vector2f v1, Vector2f v2) {
float cos = angleCos(v1, v2);
// This is because sometimes cos goes above 1 or below -1 because of lost precision
cos = Math.min(cos, 1);
cos = Math.max(cos, -1);
return (float) Math.acos(cos);
}
/**
* Return the length of a.
*/
public static float length(Vector2f a) {
return (float) Math.sqrt((a.x * a.x) + (a.y * a.y));
}
/**
* Return the length of this vector.
*/
public float length() {
return (float) Math.sqrt((x * x) + (y * y));
}
/**
* Return the length squared of this vector.
*/
public float lengthSquared() {
return x * x + y * y;
}
/**
* Return the distance between <code>start</code> and <code>end</code>.
*/
public static float distance(Vector2f start, Vector2f end) {
return (float) Math.sqrt((end.x - start.x) * (end.x - start.x)
+ (end.y - start.y) * (end.y - start.y));
}
/**
* Return the distance between this and <code>v</code>.
*/
public float distance(Vector2f v) {
return (float) Math.sqrt((v.x - x) * (v.x - x)
+ (v.y - y) * (v.y - y));
}
/**
* Normalize <code>a</code> and store the result in <code>dest</code>.
*/
public static void normalize(Vector2f a, Vector2f dest) {
float length = (float) Math.sqrt((a.x * a.x) + (a.y * a.y));
dest.x = a.x / length;
dest.y = a.y / length;
}
/**
* Normalize this vector.
*
* @return this
*/
public Vector2f normalize() {
float length = (float) Math.sqrt((x * x) + (y * y));
x /= length;
y /= length;
return this;
}
/**
* Add <code>v</code> to this vector.
*
* @return this
*/
public Vector2f add(Vector2f v) {
x += v.x;
y += v.y;
return this;
}
/**
* Add <code>a</code> to <code>b</code> and store the result in <code>dest</code>.
*/
public static void add(Vector2f a, Vector2f b, Vector2f dest) {
dest.x = a.x + b.x;
dest.y = a.y + b.y;
}
/**
* Set all components to zero.
*
* @return this
*/
public Vector2f zero() {
this.x = 0.0f;
this.y = 0.0f;
return this;
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeFloat(x);
out.writeFloat(y);
}
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
x = in.readFloat();
y = in.readFloat();
}
/**
* Negate this vector.
*
* @return this
*/
public Vector2f negate() {
x = -x;
y = -y;
return this;
}
/**
* Negate original and store the result in dest.
*/
public static void negate(Vector2f original, Vector2f dest) {
dest.x = -original.x;
dest.y = -original.y;
}
/**
* Multiply the components of this vector by the given scalar.
*
* @param scalar
* the value to multiply this vector's components by
* @return this
*/
public Vector2f mul(float scalar) {
this.x *= scalar;
this.y *= scalar;
return this;
}
/**
* Multiply the components of this vector by the given scalar and store the result in <code>dest</code>.
*
* @param scalar
* the value to multiply this vector's components by
* @param dest
* will hold the result
* @return this
*/
public Vector2f mul(float scalar, Vector2f dest) {
dest.x *= scalar;
dest.y *= scalar;
return this;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Float.floatToIntBits(x);
result = prime * result + Float.floatToIntBits(y);
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Vector2f other = (Vector2f) obj;
if (Float.floatToIntBits(x) != Float.floatToIntBits(other.x))
return false;
if (Float.floatToIntBits(y) != Float.floatToIntBits(other.y))
return false;
return true;
}
/**
* Return a string representation of this vector.
* <p>
* This method creates a new {@link DecimalFormat} on every invocation with the format string "<tt> 0.000E0;-</tt>".
*
* @return the string representation
*/
public String toString() {
DecimalFormat formatter = new DecimalFormat(" 0.000E0;-");
return toString(formatter).replaceAll("E(\\d+)", "E+$1");
}
/**
* Return a string representation of this vector by formatting the vector components with the given {@link NumberFormat}.
*
* @param formatter
* the {@link NumberFormat} used to format the vector components with
* @return the string representation
*/
public String toString(NumberFormat formatter) {
return "(" + formatter.format(x) + " " + formatter.format(y) + ")";
}
} |
package edu.tamu.weaver.response;
/**
*
* @author <a href="mailto:jmicah@library.tamu.edu">Micah Cooper</a>
* @author <a href="mailto:jcreel@library.tamu.edu">James Creel</a>
* @author <a href="mailto:huff@library.tamu.edu">Jeremy Huff</a>
* @author <a href="mailto:jsavell@library.tamu.edu">Jason Savell</a>
* @author <a href="mailto:wwelling@library.tamu.edu">William Welling</a>
*
*/
public enum ApiAction {
CREATE, READ, UPDATE, DELETE, REMOVE, REORDER, SORT, BROADCAST, CHANGE
} |
package nl.mpi.yams.client.ui;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.text.shared.Renderer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.MultiWordSuggestOracle;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.SuggestOracle;
import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;
import com.google.gwt.user.client.ui.ValueListBox;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import nl.mpi.yams.client.SearchHandler;
import nl.mpi.yams.client.SearchOptionsServiceAsync;
import nl.mpi.yams.client.SearchSuggestionsStorage;
import nl.mpi.yams.client.controllers.MetadataFileTypeListener;
import nl.mpi.yams.client.controllers.MetadataFileTypeLoader;
import nl.mpi.yams.common.data.MetadataFileType;
import nl.mpi.yams.common.data.QueryDataStructures;
public class SearchCriterionPanel extends HorizontalPanel {
private static final Logger logger = Logger.getLogger("");
final private SearchOptionsServiceAsync searchOptionsService;
static private boolean requestInProgress = false;
final private ValueListBox<MetadataFileType> typesOptionsListBox;
private MetadataFileType[] knownFileTypes = null;
final private ValueListBox<MetadataFileType> fieldsOptionsListBox;
private MetadataFileType[] knownFieldTypes = null;
final private ValueListBox<QueryDataStructures.SearchOption> searchOptionsListBox;
final private SuggestBox searchTextBox;
private MultiWordSuggestOracle oracle;
final private Image loadingTypesImage;
final private Image loadingPathsImage;
final private Image valuesPathsImage;
final private Label hintLabel;
private String databaseName = null;
private MetadataFileType defaultFileType = null;
private MetadataFileType defaultPathType = null;
private final SearchSuggestionsStorage searchSuggestionsStorage;
public SearchCriterionPanel(final SearchWidgetsPanel searchPanel, SearchOptionsServiceAsync searchOptionsService) {
this.setStyleName("yams-SearchCriterionPanel");
this.searchOptionsService = searchOptionsService;
searchSuggestionsStorage = new SearchSuggestionsStorage();
Button removeRowButton = new Button("remove", new ClickHandler() {
public void onClick(ClickEvent event) {
searchPanel.removeSearchCriterionPanel(SearchCriterionPanel.this);
}
});
this.add(removeRowButton);
searchTextBox = getSearchTextBox(searchPanel.getSearchHandler());
fieldsOptionsListBox = getFieldsOptionsListBox();
typesOptionsListBox = getTypesOptionsListBox();
loadingTypesImage = new Image("./loader.gif");
loadingPathsImage = new Image("./loader.gif");
hintLabel = new Label();
valuesPathsImage = new Image("./loader.gif");
this.add(typesOptionsListBox);
add(loadingTypesImage);
loadingTypesImage.setVisible(false);
this.add(fieldsOptionsListBox);
add(loadingPathsImage);
loadingPathsImage.setVisible(false);
searchOptionsListBox = searchPanel.getSearchOptionsListBox();
this.add(searchOptionsListBox);
this.add(searchTextBox);
this.add(valuesPathsImage);
this.add(hintLabel);
valuesPathsImage.setVisible(false);
}
public void setDatabase(String databaseName) {
this.databaseName = databaseName;
loadTypesOptions();
}
public void setDefaultValues(MetadataFileType defaultFileType, MetadataFileType defaultPathType, QueryDataStructures.SearchNegator negatorType, QueryDataStructures.SearchType searchType, String defaultSearchString) {
this.defaultFileType = defaultFileType;
this.defaultPathType = defaultPathType;
setDefaultFileTypeSelection();
setDefaultFieldTypeSelection();
searchTextBox.setText(defaultSearchString);
// set the search type
for (QueryDataStructures.SearchOption currentSearchType : QueryDataStructures.SearchOption.values()) {
if (currentSearchType.getSearchNegator().equals(negatorType) && currentSearchType.getSearchType().equals(searchType)) {
searchOptionsListBox.setValue(currentSearchType);
}
}
}
public MetadataFileType getMetadataFileType() {
return typesOptionsListBox.getValue();
}
public MetadataFileType getMetadataFieldType() {
return fieldsOptionsListBox.getValue();
}
public QueryDataStructures.SearchOption getSearchOption() {
return searchOptionsListBox.getValue();
}
public QueryDataStructures.SearchNegator getSearchNegator() {
return getSearchOption().getSearchNegator();
}
public QueryDataStructures.SearchType getSearchType() {
return getSearchOption().getSearchType();
}
private SuggestBox getSearchTextBox(SearchHandler searchHandler) {
final SuggestBox suggestBox = createTextBox();
suggestBox.addKeyUpHandler(searchHandler);
return suggestBox;
}
public String getSearchText() {
return searchTextBox.getText();
}
private void loadTypesOptions() {
loadingTypesImage.setVisible(true);
new MetadataFileTypeLoader(searchOptionsService).loadTypesOptions(databaseName, new MetadataFileTypeListener() {
public void metadataFileTypesLoaded(MetadataFileType[] result) {
if (result != null && result.length > 0) {
knownFileTypes = result;
typesOptionsListBox.setAcceptableValues(Arrays.asList(result));
setDefaultFileTypeSelection();
loadPathsOptions(typesOptionsListBox.getValue());
}
loadingTypesImage.setVisible(false);
}
public void metadataFileTypesLoadFailed(Throwable caught) {
loadingTypesImage.setVisible(false);
}
});
}
private void setDefaultFileTypeSelection() {
if (knownFileTypes != null) {
if (defaultFileType == null || defaultFileType.getType() == null || defaultFileType.getType().equals("")) {
typesOptionsListBox.setValue(knownFileTypes[0]);
} else {
for (MetadataFileType fileType : knownFileTypes) {
if (fileType.getType() != null) {
if (defaultFileType.getType().equals(fileType.getType())) {
typesOptionsListBox.setValue(fileType);
break;
}
}
}
}
}
}
private void setDefaultFieldTypeSelection() {
if (knownFieldTypes != null) {
if (defaultPathType == null || defaultPathType.getPath() == null || defaultPathType.getPath().equals("")) {
fieldsOptionsListBox.setValue(knownFieldTypes[0]);
} else {
for (MetadataFileType fieldType : knownFieldTypes) {
if (fieldType.getPath() != null) {
if (defaultPathType.getPath().equals(fieldType.getPath())) {
fieldsOptionsListBox.setValue(fieldType);
break;
}
}
}
}
}
}
private void loadPathsOptions(MetadataFileType type) {
loadingPathsImage.setVisible(true);
new MetadataFileTypeLoader(searchOptionsService).loadPathOptions(databaseName, type, new MetadataFileTypeListener() {
public void metadataFileTypesLoaded(MetadataFileType[] result) {
if (result != null && result.length > 0) {
knownFieldTypes = result;
fieldsOptionsListBox.setAcceptableValues(Arrays.asList(result));
setDefaultFieldTypeSelection();
}
loadingPathsImage.setVisible(false);
}
public void metadataFileTypesLoadFailed(Throwable caught) {
loadingPathsImage.setVisible(false);
}
});
}
private ValueListBox getFieldsOptionsListBox() {
final ValueListBox<MetadataFileType> widget = new ValueListBox<MetadataFileType>(new Renderer<MetadataFileType>() {
public String render(MetadataFileType object) {
if (object == null) {
return "<no value>";
} else {
return object.toString();
}
}
public void render(MetadataFileType object, Appendable appendable) throws IOException {
if (object != null) {
appendable.append(object.toString());
}
}
});
return widget;
}
private ValueListBox getTypesOptionsListBox() {
final ValueListBox<MetadataFileType> widget = new ValueListBox<MetadataFileType>(new Renderer<MetadataFileType>() {
public String render(MetadataFileType object) {
if (object == null) {
return "<no value>";
} else {
return object.toString();
}
}
public void render(MetadataFileType object, Appendable appendable) throws IOException {
if (object != null) {
appendable.append(object.toString());
}
}
});
widget.addValueChangeHandler(new ValueChangeHandler<MetadataFileType>() {
public void onValueChange(ValueChangeEvent<MetadataFileType> event) {
loadPathsOptions(event.getValue());
}
});
return widget;
}
private void updateSuggestOracle(final SuggestOracle.Request request, final SuggestOracle.Callback callback) {
// oracle.clear();
final String path = getMetadataFieldType().getPath();
final String type = getMetadataFileType().getType();
final String searchText = getSearchText();
logger.info("loading stored suggestions");
final String[] values = searchSuggestionsStorage.getValues(databaseName, type, path);
// oracle.addAll(Arrays.asList(values));
ArrayList<Suggestion> suggestionList = new ArrayList<Suggestion>();
for (final String entry : values) {
if (entry.toLowerCase().contains(searchText.toLowerCase())) {
suggestionList.add(new Suggestion() {
public String getDisplayString() {
return entry;
}
public String getReplacementString() {
return entry;
}
});
// logger.log(Level.INFO, entry);
}
}
SuggestOracle.Response response = new SuggestOracle.Response(suggestionList);
callback.onSuggestionsReady(request, response);
}
private SuggestBox createTextBox() {
oracle = new MultiWordSuggestOracle() {
@Override
public void requestSuggestions(final Request request, final Callback callback) {
// logger.info(request.getQuery());
final String searchText = getSearchText();
final String path = getMetadataFieldType().getPath();
final String type = getMetadataFileType().getType();
updateSuggestOracle(request, callback);
if (searchSuggestionsStorage.isDone(databaseName, type, path, searchText) || requestInProgress) {
logger.info("relying on old suggestions");
} else {
requestInProgress = true;
logger.info("requesting new suggestions");
searchSuggestionsStorage.setDone(databaseName, type, path, searchText);
valuesPathsImage.setVisible(true);
final MetadataFileType typeSelection = fieldsOptionsListBox.getValue();
final MetadataFileType options = new MetadataFileType(typeSelection.getType(), typeSelection.getPath(), request.getQuery());
new MetadataFileTypeLoader(searchOptionsService).loadValueOptions(databaseName, options, new MetadataFileTypeListener() {
public void metadataFileTypesLoaded(MetadataFileType[] result) {
requestInProgress = false;
hintLabel.setText("");
HashSet<String> suggestions = new HashSet();
if (result != null) {
// logger.info(result.length + "new suggestions");
for (final MetadataFileType type : result) {
// logger.info(type.getValue());
suggestions.add(type.getValue());
}
searchSuggestionsStorage.addValues(databaseName, type, path, suggestions);
} else {
logger.info("no new suggestions");
}
updateSuggestOracle(request, callback);
valuesPathsImage.setVisible(false);
}
public void metadataFileTypesLoadFailed(Throwable caught) {
requestInProgress = false;
valuesPathsImage.setVisible(false);
hintLabel.setText("hint: try specifying a type and or path before typing");
}
});
}
}
};
final SuggestBox suggestBox = new SuggestBox(oracle);
suggestBox.setAutoSelectEnabled(false);
return suggestBox;
}
} |
package uk.ac.ebi.phenotype.service;
import org.apache.commons.collections.CollectionUtils;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.mousephenotype.cda.solr.imits.StatusConstants;
import org.mousephenotype.cda.solr.service.GeneService;
import org.mousephenotype.cda.solr.service.MpService;
import org.mousephenotype.cda.solr.service.PhenodigmService;
import org.mousephenotype.cda.solr.service.dto.AnatomyDTO;
import org.mousephenotype.cda.solr.service.dto.DiseaseDTO;
import org.mousephenotype.cda.solr.service.dto.GeneDTO;
import org.mousephenotype.cda.solr.service.dto.MpDTO;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.security.task.DelegatingSecurityContextAsyncTaskExecutor;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.apache.commons.lang3.StringUtils.join;
import static org.apache.commons.lang3.StringUtils.split;
public class BatchQueryForm {
private Map<String, String> datatypeField = new HashMap<>();
private Map<String, List<String>> qryIdRow = new HashMap<>();
public JSONObject j = new JSONObject();
public List<String> rows = new ArrayList<>();
String NA = "info not available";
private String hostName;
private String baseUrl;
public BatchQueryForm(String mode, HttpServletRequest request, SolrDocumentList results, String fllist, String dataType, List<String> queryIds, MpService mpService, PhenodigmService phenodigmService) throws JSONException, IOException, SolrServerException {
Map<String, String> qidMap = new HashMap<>();
// users query id(s)
List<String> queryIdsNoQuotes = new ArrayList<>();
for (String id : queryIds) {
id = id.replaceAll("\"", "");
String idlc = id.toLowerCase();
//System.out.println("search qid: " + id + " --> " + idlc);
queryIdsNoQuotes.add(idlc);
qidMap.put(idlc, id);
}
// field of dataType that shows as hyperlink
datatypeField.put("gene", GeneDTO.MGI_ACCESSION_ID);
datatypeField.put("ensembl", GeneDTO.ENSEMBL_GENE_ID);
datatypeField.put("mouse_marker_symbol", GeneDTO.MARKER_SYMBOL);
datatypeField.put("human_marker_symbol", GeneDTO.HUMAN_GENE_SYMBOL);
datatypeField.put("mp", MpDTO.MP_ID);
datatypeField.put("hp", MpDTO.HP_ID);
datatypeField.put("disease", DiseaseDTO.DISEASE_ID);
datatypeField.put("anatomy", AnatomyDTO.ANATOMY_ID);
System.out.println("datatype: " + dataType);
hostName = "http:" + request.getAttribute("mappedHostname").toString();
baseUrl = request.getAttribute("baseUrl").toString();
List<String> checkedFields = null;
if (mode.equals("export")) {
String idlink = "id_link";
fllist = idlink + "," + fllist;
checkedFields = Arrays.asList(fllist.split(","));
checkedFields.set(0, checkedFields.get(1));
checkedFields.set(1, idlink);
} else {
checkedFields = Arrays.asList(fllist.split(","));
}
j.put("aaData", new JSONArray());
j.put("iTotalRecords", results.size());
j.put("iTotalDisplayRecords", results.size());
if (mode.equals("export")) {
rows.add(join(checkedFields, "\t"));
}
System.out.println("Found " + results.size() + " out of " + queryIds.size() + " in user's query list");
for (int i = 0; i < results.size(); ++i) {
SolrDocument doc = results.get(i);
// Unwrap the data if this document is a gene document and has phenotype data
List<GeneService.MinimalGeneDataset> datasetsRawData = new ArrayList<>();
List<GeneService.MinimalGeneDataset> significantPhenotypes = new ArrayList<>();
if (doc.containsKey("datasets_raw_data")) {
// populate the mp term json object
datasetsRawData = GeneService.unwrapGeneMinimalDataset(doc.get("datasets_raw_data").toString());
significantPhenotypes = datasetsRawData.stream()
.filter(x -> x.getSignificance().equalsIgnoreCase("Significant"))
.filter(x -> x.getPhenotypeTermId() != null)
.sorted(Comparator.comparing(GeneService.MinimalGeneDataset::getPhenotypeTermId))
.collect(Collectors.toList());
significantPhenotypes.forEach(m -> {
if(m.getPValue() == null) {
m.setPValue(0.0);
}
});
}
//System.out.println("doc: "+doc.toString());
List<String> rowData = new ArrayList<String>();
HashMap<String, MpDTO> mpTerms = new HashMap<>();
int count = 0;
for (String field : checkedFields) {
count++;
if (doc.containsKey(field)) {
if (mode.equals("onPage")) {
populateCells(rowData, doc, field, dataType);
} else if (mode.equals("export")) {
populateExportCells(rowData, doc, field, dataType);
}
} else if (field.equals("id_link")) {
continue;
} else {
if (doc.containsKey("phenotype_status")
&& (doc.getFieldValue("phenotype_status").equals(StatusConstants.PHENOTYPING_DATA_AVAILABLE) || doc.getFieldValue("phenotype_status").equals(StatusConstants.PHENOTYPING_COMPLETE))
&& datasetsRawData.size() > 0
&& (field.startsWith("mp_") || field.equals("p_value") || field.startsWith("hp_"))) {
String val = "";
// Unwrap the significant phenotypes from the datasets_raw_data field and populate the
// significant terms in the
if (field.equalsIgnoreCase("mp_id")) {
val = significantPhenotypes.stream()
.map(GeneService.MinimalGeneDataset::getPhenotypeTermId)
.distinct()
.collect(Collectors.joining(", "));
} else if (field.equalsIgnoreCase("mp_term")) {
val = significantPhenotypes.stream()
.map(GeneService.MinimalGeneDataset::getPhenotypeTermName)
.distinct()
.collect(Collectors.joining(", "));
} else if (field.equalsIgnoreCase("mp_term_definition")) {
List<String> definitions = new ArrayList<>();
for (String mpId : significantPhenotypes.stream().map(GeneService.MinimalGeneDataset::getPhenotypeTermId).distinct().collect(Collectors.toList())) {
MpDTO mp = null;
if (mpTerms.containsKey(mpId)) {
mp = mpTerms.get(mpId);
} else {
mp = mpService.getPhenotype(mpId);
mpTerms.put(mpId, mp);
}
if (mp != null && mp.getMpDefinition() != null) {
definitions.add(mp.getMpDefinition());
} else {
definitions.add("N/A");
}
}
val = definitions.stream().collect(Collectors.joining(" | "));
} else if (field.equalsIgnoreCase("mp_term_synonym")) {
List<String> synonyms = new ArrayList<>();
for (String mpId : significantPhenotypes.stream().map(GeneService.MinimalGeneDataset::getPhenotypeTermId).distinct().collect(Collectors.toList())) {
MpDTO mp = null;
if (mpTerms.containsKey(mpId)) {
mp = mpTerms.get(mpId);
} else {
mp = mpService.getPhenotype(mpId);
mpTerms.put(mpId, mp);
}
if (mp != null && mp.getMpTermSynonym() != null) {
synonyms.add(mp.getMpTermSynonym().stream().collect(Collectors.joining(", ")));
} else {
synonyms.add("N/A");
}
}
val = synonyms.stream().collect(Collectors.joining(" | "));
} else if (field.equalsIgnoreCase("p_value")) {
try{
Map<String, GeneService.MinimalGeneDataset> mostSignificants = significantPhenotypes.stream().filter(d -> d.getPhenotypeTermName() != null)
.collect(Collectors.toMap(GeneService.MinimalGeneDataset::getPhenotypeTermName, Function.identity(),
BinaryOperator.minBy(Comparator.comparing(GeneService.MinimalGeneDataset::getPValue))));
val = mostSignificants.values().stream().map(GeneService.MinimalGeneDataset::getPValue).map(String::valueOf).collect(Collectors.joining(", "));
} catch (NullPointerException e) {
System.out.println("Broke the thing");
}
}
rowData.add(val);
} else if (doc.containsKey("phenotype_status")
&& doc.getFieldValue("phenotype_status").equals(StatusConstants.PHENOTYPING_COMPLETE)
&& field.startsWith("mp_")
&& !field.equals("mp_term_definition")) {
String val = "no abnormal phenotype detected";
rowData.add(val);
} else if (field.startsWith("disease_")) {
String mgiAcc = (String) doc.getFieldValue("mgi_accession_id");
Set<String> diseases = field.equalsIgnoreCase("disease_id") ? phenodigmService.getDiseaseIdsByGene(mgiAcc) : phenodigmService.getDiseaseTermsByGene(mgiAcc);
String val = String.join(", ", diseases.stream().filter(Objects::nonNull).collect(Collectors.toList()));
rowData.add(val);
} else {
rowData.add(NA);
}
}
}
// so that we could output result per user's order of search input
String keystr = doc.getFieldValue(datatypeField.get(dataType)).toString().toLowerCase().replace("[", "").replace("]", "");
if (!keystr.contains(",")) {
qryIdRow.put(keystr, rowData);
} else {
// some mouse symbol are mapped to multiple human gene symbol: we only need to fetch the ones that are in user's query
//System.out.println("symbol: " +keystr);
List<String> keys = Arrays.asList(split(keystr, ","));
for (String key : keys) {
key = key.trim();
if (queryIdsNoQuotes.contains(key)) {
qryIdRow.put(key, rowData);
}
}
}
}
//System.out.println("rows: "+ qryIdRow.toString());
// ids used in query that have results
List<String> foundQryIds = new ArrayList<>();
for (String qid : qryIdRow.keySet()) {
//System.out.println("found qid: "+ qid);
foundQryIds.add(qid.toLowerCase());
}
// find the ids that are not found and displays them to users
ArrayList nonFoundIds = (java.util.ArrayList) CollectionUtils.disjunction(queryIdsNoQuotes, new ArrayList(foundQryIds));
//System.out.println("non found: " + nonFoundIds);
// find index of the field in field list for the dataType
int fieldIndex = 0;
if (nonFoundIds.size() > 0) {
String fname = datatypeField.get(dataType);
int fc = 0;
for (String fn : checkedFields) {
if (fname.equals(fn)) {
fieldIndex = fc;
break;
}
fc++;
}
}
// fill in NA for the fields for the search query not found
for (Object nf : nonFoundIds) {
String nfs = nf.toString();
if (!qryIdRow.containsKey(nf)) {
List<String> rowData = new ArrayList<String>();
for (int i = 0; i < checkedFields.size(); i++) {
if (i == fieldIndex) {
rowData.add(qidMap.get(nfs));
} else {
rowData.add(NA);
}
}
qryIdRow.put(nfs.toLowerCase(), rowData);
} else {
queryIdsNoQuotes.add(nfs);
}
}
// output as the order of input queries
for (String lcQryId : queryIdsNoQuotes) {
//System.out.println("checking " + lcQryId);
if (mode.equals("onPage")) {
j.getJSONArray("aaData").put(new JSONArray(qryIdRow.get(lcQryId)));
} else {
// export result
rows.add(join(qryIdRow.get(lcQryId), "\t"));
}
}
}
public void populateCells(List<String> rowData, SolrDocument doc, String field, String dataType) {
String valtype = doc.getFieldValue(field).getClass().getTypeName();
String val = doc.getFieldValue(field).toString();
if (valtype.equals("java.util.ArrayList")) {
rowData.add(val.replace("[", "").replace("]", ""));
} else {
if ((dataType.equals("gene") || dataType.equals("ensembl") || dataType.equals("mouse_marker_symbol") || dataType.equals("human_marker_symbol"))
&& field.equals("mgi_accession_id")) {
rowData.add("<a target='_blank' href='" + baseUrl + "/genes/" + val + "'>" + val + "</a>");
} else if (dataType.equals("mp") && field.equals("mp_id")) {
rowData.add("<a target='_blank' href='" + baseUrl + "/phenotypes/" + val + "'>" + val + "</a>");
} else if (dataType.equals("anatomy") && field.equals("anatomy_id")) {
rowData.add("<a target='_blank' href='" + baseUrl + "/anatomy/" + val + "'>" + val + "</a>");
} else if (dataType.equals("disease") && field.equals("disease_id")) {
rowData.add("<a target='_blank' href='" + baseUrl + "/disease/" + val + "'>" + val + "</a>");
} else {
rowData.add(val); // hp and other fields
}
}
}
public void populateExportCells(List<String> rowData, SolrDocument doc, String field, String dataType) {
String valtype = doc.getFieldValue(field).getClass().getTypeName();
String val = doc.getFieldValue(field).toString();
if (valtype.equals("java.util.ArrayList")) {
rowData.add(val.replace("[", "").replace("]", ""));
if (dataType.equals("hp") && field.equals("hp_id")) {
rowData.add(NA);
}
} else {
if ((dataType.equals("gene") || dataType.equals("ensembl") || dataType.equals("mouse_marker_symbol") || dataType.equals("human_marker_symbol"))
&& field.equals("mgi_accession_id")) {
rowData.add(val);
String link = generateBaseLink(hostName, baseUrl) + "/genes/" + val;
rowData.add(link);
} else if (dataType.equals("mp") && field.equals("mp_id")) {
rowData.add(val);
String link = generateBaseLink(hostName, baseUrl) + "/phenotypes/" + val;
rowData.add(link);
} else if (dataType.equals("anatomy") && field.equals("anatomy_id")) {
rowData.add(val);
String link = generateBaseLink(hostName, baseUrl) + "/anatomy/" + val;
rowData.add(link);
} else if (dataType.equals("disease") && field.equals("disease_id")) {
rowData.add(val);
String link = generateBaseLink(hostName, baseUrl) + "/disease/" + val;
rowData.add(link);
} else {
rowData.add(val); // other fields
}
}
}
private String generateBaseLink(String hostName, String baseUrl){
String baseLink = "";
if(baseUrl.startsWith("/")){
baseLink = hostName + baseUrl;
}else {
baseLink = hostName + "/" + baseUrl;
}
return baseLink;
}
} |
package org.jfree.chart.title.junit;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jfree.chart.title.TextTitle;
import org.jfree.chart.util.HorizontalAlignment;
/**
* Tests for the {@link TextTitle} class.
*/
public class TextTitleTests extends TestCase {
/**
* Returns the tests as a test suite.
*
* @return The test suite.
*/
public static Test suite() {
return new TestSuite(TextTitleTests.class);
}
/**
* Constructs a new set of tests.
*
* @param name the name of the tests.
*/
public TextTitleTests(String name) {
super(name);
}
/**
* Check that the equals() method distinguishes all fields.
*/
public void testEquals() {
TextTitle t1 = new TextTitle();
TextTitle t2 = new TextTitle();
assertEquals(t1, t2);
t1.setText("Test 1");
assertFalse(t1.equals(t2));
t2.setText("Test 1");
assertTrue(t1.equals(t2));
Font f = new Font("SansSerif", Font.PLAIN, 15);
t1.setFont(f);
assertFalse(t1.equals(t2));
t2.setFont(f);
assertTrue(t1.equals(t2));
t1.setTextAlignment(HorizontalAlignment.RIGHT);
assertFalse(t1.equals(t2));
t2.setTextAlignment(HorizontalAlignment.RIGHT);
assertTrue(t1.equals(t2));
// paint
t1.setPaint(new GradientPaint(1.0f, 2.0f, Color.red,
3.0f, 4.0f, Color.blue));
assertFalse(t1.equals(t2));
t2.setPaint(new GradientPaint(1.0f, 2.0f, Color.red,
3.0f, 4.0f, Color.blue));
assertTrue(t1.equals(t2));
// backgroundPaint
t1.setBackgroundPaint(new GradientPaint(4.0f, 3.0f, Color.red,
2.0f, 1.0f, Color.blue));
assertFalse(t1.equals(t2));
t2.setBackgroundPaint(new GradientPaint(4.0f, 3.0f, Color.red,
2.0f, 1.0f, Color.blue));
assertTrue(t1.equals(t2));
// maximumLinesToDisplay
t1.setMaximumLinesToDisplay(3);
assertFalse(t1.equals(t2));
t2.setMaximumLinesToDisplay(3);
assertTrue(t1.equals(t2));
// toolTipText
t1.setToolTipText("TTT");
assertFalse(t1.equals(t2));
t2.setToolTipText("TTT");
assertTrue(t1.equals(t2));
// urlText
t1.setURLText(("URL"));
assertFalse(t1.equals(t2));
t2.setURLText(("URL"));
assertTrue(t1.equals(t2));
// expandToFitSpace
t1.setExpandToFitSpace(!t1.getExpandToFitSpace());
assertFalse(t1.equals(t2));
t2.setExpandToFitSpace(!t2.getExpandToFitSpace());
assertTrue(t1.equals(t2));
}
/**
* Two objects that are equal are required to return the same hashCode.
*/
public void testHashcode() {
TextTitle t1 = new TextTitle();
TextTitle t2 = new TextTitle();
assertTrue(t1.equals(t2));
int h1 = t1.hashCode();
int h2 = t2.hashCode();
assertEquals(h1, h2);
}
/**
* Confirm that cloning works.
*/
public void testCloning() {
TextTitle t1 = new TextTitle();
TextTitle t2 = null;
try {
t2 = (TextTitle) t1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(t1 != t2);
assertTrue(t1.getClass() == t2.getClass());
assertTrue(t1.equals(t2));
}
/**
* Serialize an instance, restore it, and check for equality.
*/
public void testSerialization() {
TextTitle t1 = new TextTitle("Test");
TextTitle t2 = null;
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(t1);
out.close();
ObjectInput in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray()));
t2 = (TextTitle) in.readObject();
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
assertEquals(t1, t2);
}
} |
package org.opencms.setup.xml;
import org.opencms.i18n.CmsEncoder;
import org.opencms.i18n.CmsMessageContainer;
import org.opencms.main.CmsLog;
import org.opencms.util.CmsCollectionsGenericWrapper;
import org.opencms.util.CmsStringUtil;
import org.opencms.xml.CmsXmlEntityResolver;
import org.opencms.xml.CmsXmlException;
import org.opencms.xml.CmsXmlUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
public class CmsSetupXmlHelper {
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsSetupXmlHelper.class);
/** Entity resolver to skip dtd validation. */
private static final EntityResolver NO_ENTITY_RESOLVER = new EntityResolver() {
/**
* @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String)
*/
public InputSource resolveEntity(String publicId, String systemId) {
return new InputSource(new StringReader(""));
}
};
/** Optional base path. */
private String m_basePath;
/** Document cache. */
private Map<String, Document> m_cache = new HashMap<String, Document>();
/**
* Default constructor.<p>
*
* Uses no base path.<p>
*/
public CmsSetupXmlHelper() {
// ignore
}
/**
* Uses an optional base file path.<p>
*
* @param basePath the base file path to use;
*/
public CmsSetupXmlHelper(String basePath) {
m_basePath = basePath;
}
/**
* Unmarshals (reads) an XML string into a new document.<p>
*
* @param xml the XML code to unmarshal
*
* @return the generated document
*
* @throws CmsXmlException if something goes wrong
*/
public static String format(String xml) throws CmsXmlException {
return CmsXmlUtils.marshal((Node)CmsXmlUtils.unmarshalHelper(xml, null), CmsEncoder.ENCODING_UTF_8);
}
/**
* Returns the value in the given xpath of the given xml file.<p>
*
* @param document the xml document
* @param xPath the xpath to read (should select a single node or attribute)
*
* @return the value in the given xpath of the given xml file, or <code>null</code> if no matching node
*/
public static String getValue(Document document, String xPath) {
Node node = document.selectSingleNode(xPath);
if (node != null) {
// return the value
return node.getText();
} else {
return null;
}
}
/**
* Replaces a attibute's value in the given node addressed by the xPath.<p>
*
* @param document the document to replace the node attribute
* @param xPath the xPath to the node
* @param attribute the attribute to replace the value of
* @param value the new value to set
*
* @return <code>true</code> if successful <code>false</code> otherwise
*/
public static boolean setAttribute(Document document, String xPath, String attribute, String value) {
Node node = document.selectSingleNode(xPath);
Element e = (Element)node;
@SuppressWarnings("unchecked")
List<Attribute> attributes = e.attributes();
for (Attribute a : attributes) {
if (a.getName().equals(attribute)) {
a.setValue(value);
return true;
}
}
return false;
}
/**
* Sets the given value in all nodes identified by the given xpath of the given xml file.<p>
*
* If value is <code>null</code>, all nodes identified by the given xpath will be deleted.<p>
*
* If the node identified by the given xpath does not exists, the missing nodes will be created
* (if <code>value</code> not <code>null</code>).<p>
*
* @param document the xml document
* @param xPath the xpath to set
* @param value the value to set (can be <code>null</code> for deletion)
*
* @return the number of successful changed or deleted nodes
*/
public static int setValue(Document document, String xPath, String value) {
return setValue(document, xPath, value, null);
}
/**
* Sets the given value in all nodes identified by the given xpath of the given xml file.<p>
*
* If value is <code>null</code>, all nodes identified by the given xpath will be deleted.<p>
*
* If the node identified by the given xpath does not exists, the missing nodes will be created
* (if <code>value</code> not <code>null</code>).<p>
*
* @param document the xml document
* @param xPath the xpath to set
* @param value the value to set (can be <code>null</code> for deletion)
* @param nodeToInsert optional, if given it will be inserted after xPath with the given value
*
* @return the number of successful changed or deleted nodes
*/
public static int setValue(Document document, String xPath, String value, String nodeToInsert) {
int changes = 0;
// be naive and try to find the node
Iterator<Node> itNodes = CmsCollectionsGenericWrapper.<Node> list(document.selectNodes(xPath)).iterator();
// if not found
if (!itNodes.hasNext()) {
if (value == null) {
// if no node found for deletion
return 0;
}
// find the node creating missing nodes in the way
Iterator<String> it = CmsStringUtil.splitAsList(xPath, "/", false).iterator();
Node currentNode = document;
while (it.hasNext()) {
String nodeName = it.next();
// if a string condition contains '/'
while ((nodeName.indexOf("='") > 0) && (nodeName.indexOf("']") < 0)) {
nodeName += "/" + it.next();
}
Node node = currentNode.selectSingleNode(nodeName);
if (node != null) {
// node found
currentNode = node;
if (!it.hasNext()) {
currentNode.setText(value);
}
} else if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
Element elem = (Element)currentNode;
if (!nodeName.startsWith("@")) {
elem = handleNode(elem, nodeName);
if (!it.hasNext() && CmsStringUtil.isNotEmptyOrWhitespaceOnly(value)) {
elem.setText(value);
}
} else {
// if node is attribute create it with given value
elem.addAttribute(nodeName.substring(1), value);
}
currentNode = elem;
} else {
// should never happen
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.ERR_XML_SET_VALUE_2, xPath, value));
}
break;
}
}
if (nodeToInsert == null) {
// if not inserting we are done
return 1;
}
// if inserting, we just created the insertion point, so continue
itNodes = CmsCollectionsGenericWrapper.<Node> list(document.selectNodes(xPath)).iterator();
}
// if found
while (itNodes.hasNext()) {
Node node = itNodes.next();
if (nodeToInsert == null) {
// if not inserting
if (value != null) {
// if found, change the value
node.setText(value);
} else {
// if node for deletion is found
node.getParent().remove(node);
}
} else {
// first create the node to insert
Element parent = node.getParent();
Element elem = handleNode(parent, nodeToInsert);
if (value != null) {
elem.setText(value);
}
// get the parent element list
List<Node> list = CmsCollectionsGenericWrapper.<Node> list(parent.content());
// remove the just created element
list.remove(list.size() - 1);
// insert it back to the right position
int pos = list.indexOf(node);
list.add(pos + 1, elem); // insert after
}
changes++;
}
return changes;
}
/**
* Handles the xpath name, by creating the given node and its children.<p>
*
* @param parent the parent node to use
* @param xpathName the xpathName, ie <code>a[@b='c'][d='e'][text()='f']</code>
*
* @return the new created element
*/
private static Element handleNode(Element parent, String xpathName) {
// if node is no attribute, create a new node
String childrenPart = null;
String nodeName;
int pos = xpathName.indexOf("[");
if (pos > 0) {
childrenPart = xpathName.substring(pos + 1, xpathName.length() - 1);
nodeName = xpathName.substring(0, pos);
} else {
nodeName = xpathName;
}
// create node
Element elem = parent.addElement(nodeName);
if (childrenPart != null) {
pos = childrenPart.indexOf("[");
if ((pos > 0) && (childrenPart.indexOf("]") > pos)) {
handleNode(elem, childrenPart);
return elem;
}
if (childrenPart.contains("=")) {
Map<String, String> children = CmsStringUtil.splitAsMap(childrenPart, "][", "=");
// handle child nodes
for (Map.Entry<String, String> child : children.entrySet()) {
String childName = child.getKey();
String childValue = child.getValue();
if (childValue.startsWith("'")) {
childValue = childValue.substring(1);
}
if (childValue.endsWith("'")) {
childValue = childValue.substring(0, childValue.length() - 1);
}
if (childName.startsWith("@")) {
elem.addAttribute(childName.substring(1), childValue);
} else if (childName.equals("text()")) {
elem.setText(childValue);
} else if (!childName.contains("(")) {
Element childElem = elem.addElement(childName);
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(childValue)) {
childElem.addText(childValue);
}
}
}
}
}
return elem;
}
/**
* Discards the changes in the given file.<p>
*
* @param xmlFilename the xml config file (could be relative to the base path)
*/
public void flush(String xmlFilename) {
m_cache.remove(xmlFilename);
}
/**
* Discards the changes in all files.<p>
*/
public void flushAll() {
m_cache.clear();
}
/**
* Returns the base file Path.<p>
*
* @return the base file Path
*/
public String getBasePath() {
return m_basePath;
}
/**
* Returns the document for the given filename.<p>
* It can be new read or come from the document cache.<p>
*
* @param xmlFilename the filename to read
*
* @return the document for the given filename
*
* @throws CmsXmlException if something goes wrong while reading
*/
public Document getDocument(String xmlFilename) throws CmsXmlException {
// try to get it from the cache
Document document = m_cache.get(xmlFilename);
if (document == null) {
try {
document = CmsXmlUtils.unmarshalHelper(
new InputSource(new FileReader(getFile(xmlFilename))),
NO_ENTITY_RESOLVER);
} catch (FileNotFoundException e) {
throw new CmsXmlException(new CmsMessageContainer(null, e.toString()));
}
// cache the doc
m_cache.put(xmlFilename, document);
}
return document;
}
/**
* Returns the value in the given xpath of the given xml file.<p>
*
* @param xmlFilename the xml config file (could be relative to the base path)
* @param xPath the xpath to read (should select a single node or attribute)
*
* @return the value in the given xpath of the given xml file, or <code>null</code> if no matching node
*
* @throws CmsXmlException if something goes wrong while reading
*/
public String getValue(String xmlFilename, String xPath) throws CmsXmlException {
return getValue(getDocument(xmlFilename), xPath);
}
/**
* Replaces a attibute's value in the given node addressed by the xPath.<p>
*
* @param xmlFilename the xml file name to get the document from
* @param xPath the xPath to the node
* @param attribute the attribute to replace the value of
* @param value the new value to set
*
* @return <code>true</code> if successful <code>false</code> otherwise
*
* @throws CmsXmlException if the xml document coudn't be read
*/
public boolean setAttribute(String xmlFilename, String xPath, String attribute, String value)
throws CmsXmlException {
return setAttribute(getDocument(xmlFilename), xPath, attribute, value);
}
/**
* Sets the given value in all nodes identified by the given xpath of the given xml file.<p>
*
* If value is <code>null</code>, all nodes identified by the given xpath will be deleted.<p>
*
* If the node identified by the given xpath does not exists, the missing nodes will be created
* (if <code>value</code> not <code>null</code>).<p>
*
* @param xmlFilename the xml config file (could be relative to the base path)
* @param xPath the xpath to set
* @param value the value to set (can be <code>null</code> for deletion)
*
* @return the number of successful changed or deleted nodes
*
* @throws CmsXmlException if something goes wrong
*/
public int setValue(String xmlFilename, String xPath, String value) throws CmsXmlException {
return setValue(getDocument(xmlFilename), xPath, value, null);
}
/**
* Sets the given value in all nodes identified by the given xpath of the given xml file.<p>
*
* If value is <code>null</code>, all nodes identified by the given xpath will be deleted.<p>
*
* If the node identified by the given xpath does not exists, the missing nodes will be created
* (if <code>value</code> not <code>null</code>).<p>
*
* @param xmlFilename the xml config file (could be relative to the base path)
* @param xPath the xpath to set
* @param value the value to set (can be <code>null</code> for deletion)
* @param nodeToInsert optional, if given it will be inserted after xPath with the given value
*
* @return the number of successful changed or deleted nodes
*
* @throws CmsXmlException if something goes wrong
*/
public int setValue(String xmlFilename, String xPath, String value, String nodeToInsert) throws CmsXmlException {
return setValue(getDocument(xmlFilename), xPath, value, nodeToInsert);
}
/**
* Writes the given file back to disk.<p>
*
* @param xmlFilename the xml config file (could be relative to the base path)
*
* @throws CmsXmlException if something wrong while writing
*/
public void write(String xmlFilename) throws CmsXmlException {
// try to get it from the cache
Document document = m_cache.get(xmlFilename);
if (document != null) {
try {
CmsXmlUtils.validateXmlStructure(document, CmsEncoder.ENCODING_UTF_8, new CmsXmlEntityResolver(null));
OutputStream out = new FileOutputStream(getFile(xmlFilename));
CmsXmlUtils.marshal(document, out, CmsEncoder.ENCODING_UTF_8);
} catch (FileNotFoundException e) {
throw new CmsXmlException(new CmsMessageContainer(null, e.toString()));
}
}
}
/**
* Flushes all cached documents.<p>
*
* @throws CmsXmlException if something wrong while writing
*/
public void writeAll() throws CmsXmlException {
Iterator<String> it = new ArrayList<String>(m_cache.keySet()).iterator();
while (it.hasNext()) {
String filename = it.next();
write(filename);
}
}
/**
* Returns a file from a given filename.<p>
*
* @param xmlFilename the file name
*
* @return the file
*/
private File getFile(String xmlFilename) {
File file = new File(m_basePath + xmlFilename);
if (!file.exists() || !file.canRead()) {
file = new File(xmlFilename);
}
return file;
}
} |
package org.pentaho.di.ui.trans.dialog;
import java.util.ArrayList;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.database.Database;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.database.PartitionDatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.core.gui.WindowProperty;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.partition.PartitionSchema;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.RepositoryDirectory;
import org.pentaho.di.trans.TransDependency;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.ui.trans.dialog.Messages;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.steps.databaselookup.DatabaseLookupMeta;
import org.pentaho.di.trans.steps.tableinput.TableInputMeta;
import org.pentaho.di.ui.core.PropsUI;
import org.pentaho.di.ui.core.database.dialog.DatabaseDialog;
import org.pentaho.di.ui.core.database.dialog.SQLEditor;
import org.pentaho.di.ui.core.dialog.EnterSelectionDialog;
import org.pentaho.di.ui.core.dialog.EnterStringDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.core.widget.TextVar;
import org.pentaho.di.ui.repository.dialog.SelectDirectoryDialog;
public class TransDialog extends Dialog
{
private LogWriter log;
private CTabFolder wTabFolder;
private FormData fdTabFolder;
private CTabItem wTransTab, wLogTab, wDateTab, wDepTab, wMiscTab, wPartTab, wMonitorTab;
private Text wTransname;
private Text wTransFilename;
// Trans description
private Text wTransdescription;
private Label wlExtendeddescription;
private Text wExtendeddescription;
// Trans Status
private Label wlTransstatus;
private CCombo wTransstatus;
private FormData fdlTransstatus, fdTransstatus;
//Trans version
private Text wTransversion;
private FormData fdlExtendeddescription, fdExtendeddescription;
private Text wDirectory;
private Button wbDirectory;
private Text wCreateUser;
private Text wCreateDate;
private Text wModUser;
private Text wModDate;
private CCombo wReadStep;
private CCombo wInputStep;
private CCombo wWriteStep;
private CCombo wOutputStep;
private CCombo wUpdateStep;
private Button wbLogconnection;
private CCombo wLogconnection;
private Text wLogtable;
private Text wStepLogtable;
private Button wBatch;
private Button wLogfield;
private CCombo wMaxdateconnection;
private Text wMaxdatetable;
private Text wMaxdatefield;
private Text wMaxdateoffset;
private Text wMaxdatediff;
private TableView wFields;
private Text wSizeRowset;
private Button wUniqueConnections;
// Partitions tab
private List wSchemaList;
private TableView wPartitions;
private java.util.List<PartitionSchema> schemas;
private Text wSchemaName;
private Button wOK, wGet, wSQL, wCancel;
private FormData fdGet;
private Listener lsOK, lsGet, lsSQL, lsCancel;
private TransMeta transMeta;
private Shell shell;
private SelectionAdapter lsDef;
private ModifyListener lsMod;
private boolean changed;
private Repository rep;
private PropsUI props;
private RepositoryDirectory newDirectory;
private int middle;
private int margin;
private String[] connectionNames;
private int previousSchemaIndex;
private Button wGetPartitions;
private Button wShowFeedback;
private Text wFeedbackSize;
private TextVar wSharedObjectsFile;
private boolean sharedObjectsFileChanged;
private Button wManageThreads;
private CCombo wRejectedStep;
private boolean directoryChangeAllowed;
private Label wlDirectory;
private Button wEnableStepPerfMonitor;
private Text wEnableStepPerfInterval;
private Label wlStepLogtable;
public TransDialog(Shell parent, int style, TransMeta transMeta, Repository rep)
{
super(parent, style);
this.log = LogWriter.getInstance();
this.props = PropsUI.getInstance();
this.transMeta = transMeta;
this.rep = rep;
this.newDirectory = null;
schemas = new ArrayList<PartitionSchema>();
for (int i=0;i<transMeta.getPartitionSchemas().size();i++)
{
schemas.add( (PartitionSchema) transMeta.getPartitionSchemas().get(i).clone() );
}
previousSchemaIndex = -1;
directoryChangeAllowed=true;
}
public TransMeta open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
props.setLook(shell);
shell.setImage((Image) GUIResource.getInstance().getImageTransGraph());
lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
transMeta.setChanged();
}
};
changed = transMeta.hasChanged();
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(Messages.getString("TransDialog.Shell.Title")); //$NON-NLS-1$
middle = props.getMiddlePct();
margin = Const.MARGIN;
wTabFolder = new CTabFolder(shell, SWT.BORDER);
props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB);
wTabFolder.setSimple(false);
addTransTab();
addLogTab();
addDateTab();
addDepTab();
addMiscTab();
addPartTab();
addMonitoringTab();
fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment(0, 0);
fdTabFolder.top = new FormAttachment(0, 0);
fdTabFolder.right = new FormAttachment(100, 0);
fdTabFolder.bottom= new FormAttachment(100, -50);
wTabFolder.setLayoutData(fdTabFolder);
// THE BUTTONS
wOK=new Button(shell, SWT.PUSH);
wOK.setText(Messages.getString("System.Button.OK")); //$NON-NLS-1$
wSQL=new Button(shell, SWT.PUSH);
wSQL.setText(Messages.getString("System.Button.SQL")); //$NON-NLS-1$
wCancel=new Button(shell, SWT.PUSH);
wCancel.setText(Messages.getString("System.Button.Cancel")); //$NON-NLS-1$
BaseStepDialog.positionBottomButtons(shell, new Button[] { wOK, wSQL, wCancel }, Const.MARGIN, null);
// Add listeners
lsOK = new Listener() { public void handleEvent(Event e) { ok(); } };
lsGet = new Listener() { public void handleEvent(Event e) { get(); } };
lsSQL = new Listener() { public void handleEvent(Event e) { sql(); } };
lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } };
wOK.addListener (SWT.Selection, lsOK );
wGet.addListener (SWT.Selection, lsGet );
wSQL.addListener (SWT.Selection, lsSQL );
wCancel.addListener(SWT.Selection, lsCancel);
lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } };
wTransname.addSelectionListener( lsDef );
wTransdescription.addSelectionListener( lsDef );
wTransversion.addSelectionListener( lsDef );
wMaxdatetable.addSelectionListener( lsDef );
wMaxdatefield.addSelectionListener( lsDef );
wMaxdateoffset.addSelectionListener( lsDef );
wMaxdatediff.addSelectionListener( lsDef );
wLogtable.addSelectionListener( lsDef );
wStepLogtable.addSelectionListener( lsDef );
wSizeRowset.addSelectionListener( lsDef );
wUniqueConnections.addSelectionListener( lsDef );
wFeedbackSize.addSelectionListener( lsDef );
wEnableStepPerfInterval.addSelectionListener( lsDef );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );
wTabFolder.setSelection(0);
getData();
BaseStepDialog.setSize(shell);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
return transMeta;
}
private void addTransTab()
{
// START OF TRANS TAB///
wTransTab=new CTabItem(wTabFolder, SWT.NONE);
wTransTab.setText(Messages.getString("TransDialog.TransTab.Label")); //$NON-NLS-1$
Composite wTransComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wTransComp);
FormLayout transLayout = new FormLayout();
transLayout.marginWidth = Const.FORM_MARGIN;
transLayout.marginHeight = Const.FORM_MARGIN;
wTransComp.setLayout(transLayout);
// Transformation name:
Label wlTransname = new Label(wTransComp, SWT.RIGHT);
wlTransname.setText(Messages.getString("TransDialog.Transname.Label")); //$NON-NLS-1$
props.setLook(wlTransname);
FormData fdlTransname = new FormData();
fdlTransname.left = new FormAttachment(0, 0);
fdlTransname.right= new FormAttachment(middle, -margin);
fdlTransname.top = new FormAttachment(0, margin);
wlTransname.setLayoutData(fdlTransname);
wTransname=new Text(wTransComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wTransname);
wTransname.addModifyListener(lsMod);
FormData fdTransname = new FormData();
fdTransname.left = new FormAttachment(middle, 0);
fdTransname.top = new FormAttachment(0, margin);
fdTransname.right= new FormAttachment(100, 0);
wTransname.setLayoutData(fdTransname);
// Transformation name:
Label wlTransFilename = new Label(wTransComp, SWT.RIGHT);
wlTransFilename.setText(Messages.getString("TransDialog.TransFilename.Label")); //$NON-NLS-1$
props.setLook(wlTransFilename);
FormData fdlTransFilename = new FormData();
fdlTransFilename.left = new FormAttachment(0, 0);
fdlTransFilename.right= new FormAttachment(middle, -margin);
fdlTransFilename.top = new FormAttachment(wTransname, margin);
wlTransFilename.setLayoutData(fdlTransFilename);
wTransFilename=new Text(wTransComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wTransFilename);
wTransFilename.addModifyListener(lsMod);
FormData fdTransFilename = new FormData();
fdTransFilename.left = new FormAttachment(middle, 0);
fdTransFilename.top = new FormAttachment(wTransname, margin);
fdTransFilename.right= new FormAttachment(100, 0);
wTransFilename.setLayoutData(fdTransFilename);
wTransFilename.setEditable(false);
// Transformation description:
Label wlTransdescription = new Label(wTransComp, SWT.RIGHT);
wlTransdescription.setText(Messages.getString("TransDialog.Transdescription.Label")); //$NON-NLS-1$
props.setLook(wlTransdescription);
FormData fdlTransdescription = new FormData();
fdlTransdescription.left = new FormAttachment(0, 0);
fdlTransdescription.right= new FormAttachment(middle, -margin);
fdlTransdescription.top = new FormAttachment(wTransFilename, margin);
wlTransdescription.setLayoutData(fdlTransdescription);
wTransdescription=new Text(wTransComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wTransdescription);
wTransdescription.addModifyListener(lsMod);
FormData fdTransdescription = new FormData();
fdTransdescription.left = new FormAttachment(middle, 0);
fdTransdescription.top = new FormAttachment(wTransFilename, margin);
fdTransdescription.right= new FormAttachment(100, 0);
wTransdescription.setLayoutData(fdTransdescription);
// Transformation Extended description
wlExtendeddescription = new Label(wTransComp, SWT.RIGHT);
wlExtendeddescription.setText(Messages.getString("TransDialog.Extendeddescription.Label"));
props.setLook(wlExtendeddescription);
fdlExtendeddescription = new FormData();
fdlExtendeddescription.left = new FormAttachment(0, 0);
fdlExtendeddescription.top = new FormAttachment(wTransdescription, margin);
fdlExtendeddescription.right = new FormAttachment(middle, -margin);
wlExtendeddescription.setLayoutData(fdlExtendeddescription);
wExtendeddescription = new Text(wTransComp, SWT.MULTI | SWT.LEFT | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
props.setLook(wExtendeddescription,Props.WIDGET_STYLE_FIXED);
wExtendeddescription.addModifyListener(lsMod);
fdExtendeddescription = new FormData();
fdExtendeddescription.left = new FormAttachment(middle, 0);
fdExtendeddescription.top = new FormAttachment(wTransdescription, margin);
fdExtendeddescription.right = new FormAttachment(100, 0);
fdExtendeddescription.bottom =new FormAttachment(50, -margin);
wExtendeddescription.setLayoutData(fdExtendeddescription);
//Trans Status
wlTransstatus = new Label(wTransComp, SWT.RIGHT);
wlTransstatus.setText(Messages.getString("TransDialog.Transstatus.Label"));
props.setLook(wlTransstatus);
fdlTransstatus = new FormData();
fdlTransstatus.left = new FormAttachment(0, 0);
fdlTransstatus.right = new FormAttachment(middle, 0);
fdlTransstatus.top = new FormAttachment(wExtendeddescription, margin*2);
wlTransstatus.setLayoutData(fdlTransstatus);
wTransstatus = new CCombo(wTransComp, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER);
wTransstatus.add(Messages.getString("TransDialog.Draft_Transstatus.Label"));
wTransstatus.add(Messages.getString("TransDialog.Production_Transstatus.Label"));
wTransstatus.add("");
wTransstatus.select(-1); // +1: starts at -1
props.setLook(wTransstatus);
fdTransstatus= new FormData();
fdTransstatus.left = new FormAttachment(middle, 0);
fdTransstatus.top = new FormAttachment(wExtendeddescription, margin*2);
fdTransstatus.right = new FormAttachment(100, 0);
wTransstatus.setLayoutData(fdTransstatus);
Label wlTransversion = new Label(wTransComp, SWT.RIGHT);
wlTransversion.setText(Messages.getString("TransDialog.Transversion.Label")); //$NON-NLS-1$
props.setLook(wlTransversion);
FormData fdlTransversion = new FormData();
fdlTransversion.left = new FormAttachment(0, 0);
fdlTransversion.right= new FormAttachment(middle, -margin);
fdlTransversion.top = new FormAttachment(wTransstatus, margin);
wlTransversion.setLayoutData(fdlTransversion);
wTransversion=new Text(wTransComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wTransversion);
wTransversion.addModifyListener(lsMod);
FormData fdTransversion = new FormData();
fdTransversion.left = new FormAttachment(middle, 0);
fdTransversion.top = new FormAttachment(wTransstatus, margin);
fdTransversion.right= new FormAttachment(100, 0);
wTransversion.setLayoutData(fdTransversion);
// Directory:
wlDirectory = new Label(wTransComp, SWT.RIGHT);
wlDirectory.setText(Messages.getString("TransDialog.Directory.Label")); //$NON-NLS-1$
props.setLook(wlDirectory);
FormData fdlDirectory = new FormData();
fdlDirectory.left = new FormAttachment(0, 0);
fdlDirectory.right= new FormAttachment(middle, -margin);
fdlDirectory.top = new FormAttachment(wTransversion, margin);
wlDirectory.setLayoutData(fdlDirectory);
wbDirectory=new Button(wTransComp, SWT.PUSH);
wbDirectory.setText("..."); //$NON-NLS-1$
props.setLook(wbDirectory);
FormData fdbDirectory = new FormData();
fdbDirectory.right= new FormAttachment(100, 0);
fdbDirectory.top = new FormAttachment(wTransversion, margin);
wbDirectory.setLayoutData(fdbDirectory);
wbDirectory.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
if (rep!=null)
{
RepositoryDirectory directoryFrom = transMeta.getDirectory();
long idDirectoryFrom = directoryFrom.getID();
SelectDirectoryDialog sdd = new SelectDirectoryDialog(shell, SWT.NONE, rep);
RepositoryDirectory rd = sdd.open();
if (rd!=null)
{
if (idDirectoryFrom!=rd.getID())
{
// We need to change this in the repository as well!!
// We do this when the user pressed OK
newDirectory = rd;
wDirectory.setText(rd.getPath());
}
else
{
// Same directory!
}
}
}
else
{
}
}
});
wDirectory=new Text(wTransComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wDirectory);
wDirectory.setEditable(false);
wDirectory.setEnabled(false);
FormData fdDirectory = new FormData();
fdDirectory.left = new FormAttachment(middle, 0);
fdDirectory.top = new FormAttachment(wTransversion, margin);
fdDirectory.right= new FormAttachment(wbDirectory, 0);
wDirectory.setLayoutData(fdDirectory);
// Create User:
Label wlCreateUser = new Label(wTransComp, SWT.RIGHT);
wlCreateUser.setText(Messages.getString("TransDialog.CreateUser.Label")); //$NON-NLS-1$
props.setLook(wlCreateUser);
FormData fdlCreateUser = new FormData();
fdlCreateUser.left = new FormAttachment(0, 0);
fdlCreateUser.right= new FormAttachment(middle, -margin);
fdlCreateUser.top = new FormAttachment(wDirectory, margin);
wlCreateUser.setLayoutData(fdlCreateUser);
wCreateUser=new Text(wTransComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wCreateUser);
wCreateUser.setEditable(false);
wCreateUser.addModifyListener(lsMod);
FormData fdCreateUser = new FormData();
fdCreateUser.left = new FormAttachment(middle, 0);
fdCreateUser.top = new FormAttachment(wDirectory, margin);
fdCreateUser.right= new FormAttachment(100, 0);
wCreateUser.setLayoutData(fdCreateUser);
Label wlCreateDate = new Label(wTransComp, SWT.RIGHT);
wlCreateDate.setText(Messages.getString("TransDialog.CreateDate.Label")); //$NON-NLS-1$
props.setLook(wlCreateDate);
FormData fdlCreateDate = new FormData();
fdlCreateDate.left = new FormAttachment(0, 0);
fdlCreateDate.right= new FormAttachment(middle, -margin);
fdlCreateDate.top = new FormAttachment(wCreateUser, margin);
wlCreateDate.setLayoutData(fdlCreateDate);
wCreateDate=new Text(wTransComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wCreateDate);
wCreateDate.setEditable(false);
wCreateDate.addModifyListener(lsMod);
FormData fdCreateDate = new FormData();
fdCreateDate.left = new FormAttachment(middle, 0);
fdCreateDate.top = new FormAttachment(wCreateUser, margin);
fdCreateDate.right= new FormAttachment(100, 0);
wCreateDate.setLayoutData(fdCreateDate);
// Modified User:
Label wlModUser = new Label(wTransComp, SWT.RIGHT);
wlModUser.setText(Messages.getString("TransDialog.LastModifiedUser.Label")); //$NON-NLS-1$
props.setLook(wlModUser);
FormData fdlModUser = new FormData();
fdlModUser.left = new FormAttachment(0, 0);
fdlModUser.right= new FormAttachment(middle, -margin);
fdlModUser.top = new FormAttachment(wCreateDate, margin);
wlModUser.setLayoutData(fdlModUser);
wModUser=new Text(wTransComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wModUser);
wModUser.setEditable(false);
wModUser.addModifyListener(lsMod);
FormData fdModUser = new FormData();
fdModUser.left = new FormAttachment(middle, 0);
fdModUser.top = new FormAttachment(wCreateDate, margin);
fdModUser.right= new FormAttachment(100, 0);
wModUser.setLayoutData(fdModUser);
Label wlModDate = new Label(wTransComp, SWT.RIGHT);
wlModDate.setText(Messages.getString("TransDialog.LastModifiedDate.Label")); //$NON-NLS-1$
props.setLook(wlModDate);
FormData fdlModDate = new FormData();
fdlModDate.left = new FormAttachment(0, 0);
fdlModDate.right= new FormAttachment(middle, -margin);
fdlModDate.top = new FormAttachment(wModUser, margin);
wlModDate.setLayoutData(fdlModDate);
wModDate=new Text(wTransComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wModDate);
wModDate.setEditable(false);
wModDate.addModifyListener(lsMod);
FormData fdModDate = new FormData();
fdModDate.left = new FormAttachment(middle, 0);
fdModDate.top = new FormAttachment(wModUser, margin);
fdModDate.right= new FormAttachment(100, 0);
wModDate.setLayoutData(fdModDate);
FormData fdTransComp = new FormData();
fdTransComp.left = new FormAttachment(0, 0);
fdTransComp.top = new FormAttachment(0, 0);
fdTransComp.right = new FormAttachment(100, 0);
fdTransComp.bottom= new FormAttachment(100, 0);
wTransComp.setLayoutData(fdTransComp);
wTransComp.layout();
wTransTab.setControl(wTransComp);
/// END OF TRANS TAB
}
private void addLogTab()
{
// START OF LOG TAB///
wLogTab=new CTabItem(wTabFolder, SWT.NONE);
wLogTab.setText(Messages.getString("TransDialog.LogTab.Label")); //$NON-NLS-1$
FormLayout LogLayout = new FormLayout ();
LogLayout.marginWidth = Const.MARGIN;
LogLayout.marginHeight = Const.MARGIN;
Composite wLogComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wLogComp);
wLogComp.setLayout(LogLayout);
// Log step: lines read...
Label wlReadStep = new Label(wLogComp, SWT.RIGHT);
wlReadStep.setText(Messages.getString("TransDialog.ReadStep.Label")); //$NON-NLS-1$
props.setLook(wlReadStep);
FormData fdlReadStep = new FormData();
fdlReadStep.left = new FormAttachment(0, 0);
fdlReadStep.right= new FormAttachment(middle, -margin);
fdlReadStep.top = new FormAttachment(0, 0);
wlReadStep.setLayoutData(fdlReadStep);
wReadStep=new CCombo(wLogComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wReadStep);
wReadStep.addModifyListener(lsMod);
FormData fdReadStep = new FormData();
fdReadStep.left = new FormAttachment(middle, 0);
fdReadStep.top = new FormAttachment(0, 0);
fdReadStep.right= new FormAttachment(100, 0);
wReadStep.setLayoutData(fdReadStep);
// Log step: lines input...
Label wlInputStep = new Label(wLogComp, SWT.RIGHT);
wlInputStep.setText(Messages.getString("TransDialog.InputStep.Label")); //$NON-NLS-1$
props.setLook(wlInputStep);
FormData fdlInputStep = new FormData();
fdlInputStep.left = new FormAttachment(0, 0);
fdlInputStep.right= new FormAttachment(middle, -margin);
fdlInputStep.top = new FormAttachment(wReadStep, margin*2);
wlInputStep.setLayoutData(fdlInputStep);
wInputStep=new CCombo(wLogComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wInputStep);
wInputStep.addModifyListener(lsMod);
FormData fdInputStep = new FormData();
fdInputStep.left = new FormAttachment(middle, 0);
fdInputStep.top = new FormAttachment(wReadStep, margin*2);
fdInputStep.right= new FormAttachment(100, 0);
wInputStep.setLayoutData(fdInputStep);
// Log step: lines written...
Label wlWriteStep = new Label(wLogComp, SWT.RIGHT);
wlWriteStep.setText(Messages.getString("TransDialog.WriteStep.Label")); //$NON-NLS-1$
props.setLook(wlWriteStep);
FormData fdlWriteStep = new FormData();
fdlWriteStep.left = new FormAttachment(0, 0);
fdlWriteStep.right= new FormAttachment(middle, -margin);
fdlWriteStep.top = new FormAttachment(wInputStep, margin*2);
wlWriteStep.setLayoutData(fdlWriteStep);
wWriteStep=new CCombo(wLogComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wWriteStep);
wWriteStep.addModifyListener(lsMod);
FormData fdWriteStep = new FormData();
fdWriteStep.left = new FormAttachment(middle, 0);
fdWriteStep.top = new FormAttachment(wInputStep, margin*2);
fdWriteStep.right= new FormAttachment(100, 0);
wWriteStep.setLayoutData(fdWriteStep);
// Log step: lines to output...
Label wlOutputStep = new Label(wLogComp, SWT.RIGHT);
wlOutputStep.setText(Messages.getString("TransDialog.OutputStep.Label")); //$NON-NLS-1$
props.setLook(wlOutputStep);
FormData fdlOutputStep = new FormData();
fdlOutputStep.left = new FormAttachment(0, 0);
fdlOutputStep.right= new FormAttachment(middle, -margin);
fdlOutputStep.top = new FormAttachment(wWriteStep, margin*2);
wlOutputStep.setLayoutData(fdlOutputStep);
wOutputStep=new CCombo(wLogComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wOutputStep);
wOutputStep.addModifyListener(lsMod);
FormData fdOutputStep = new FormData();
fdOutputStep.left = new FormAttachment(middle, 0);
fdOutputStep.top = new FormAttachment(wWriteStep, margin*2);
fdOutputStep.right= new FormAttachment(100, 0);
wOutputStep.setLayoutData(fdOutputStep);
// Log step: update...
Label wlUpdateStep = new Label(wLogComp, SWT.RIGHT);
wlUpdateStep.setText(Messages.getString("TransDialog.UpdateStep.Label")); //$NON-NLS-1$
props.setLook(wlUpdateStep);
FormData fdlUpdateStep = new FormData();
fdlUpdateStep.left = new FormAttachment(0, 0);
fdlUpdateStep.right= new FormAttachment(middle, -margin);
fdlUpdateStep.top = new FormAttachment(wOutputStep, margin*2);
wlUpdateStep.setLayoutData(fdlUpdateStep);
wUpdateStep=new CCombo(wLogComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wUpdateStep);
wUpdateStep.addModifyListener(lsMod);
FormData fdUpdateStep = new FormData();
fdUpdateStep.left = new FormAttachment(middle, 0);
fdUpdateStep.top = new FormAttachment(wOutputStep, margin*2);
fdUpdateStep.right= new FormAttachment(100, 0);
wUpdateStep.setLayoutData(fdUpdateStep);
// Log step: update...
Label wlRejectedStep = new Label(wLogComp, SWT.RIGHT);
wlRejectedStep.setText(Messages.getString("TransDialog.RejectedStep.Label")); //$NON-NLS-1$
props.setLook(wlRejectedStep);
FormData fdlRejectedStep = new FormData();
fdlRejectedStep.left = new FormAttachment(0, 0);
fdlRejectedStep.right= new FormAttachment(middle, -margin);
fdlRejectedStep.top = new FormAttachment(wUpdateStep, margin*2);
wlRejectedStep.setLayoutData(fdlRejectedStep);
wRejectedStep=new CCombo(wLogComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wRejectedStep);
wRejectedStep.addModifyListener(lsMod);
FormData fdRejectedStep = new FormData();
fdRejectedStep.left = new FormAttachment(middle, 0);
fdRejectedStep.top = new FormAttachment(wUpdateStep, margin*2);
fdRejectedStep.right= new FormAttachment(100, 0);
wRejectedStep.setLayoutData(fdRejectedStep);
for (int i=0;i<transMeta.nrSteps();i++)
{
StepMeta stepMeta = transMeta.getStep(i);
wReadStep.add(stepMeta.getName());
wWriteStep.add(stepMeta.getName());
wInputStep.add(stepMeta.getName());
wOutputStep.add(stepMeta.getName());
wUpdateStep.add(stepMeta.getName());
wRejectedStep.add(stepMeta.getName());
}
// Log table connection...
Label wlLogconnection = new Label(wLogComp, SWT.RIGHT);
wlLogconnection.setText(Messages.getString("TransDialog.LogConnection.Label")); //$NON-NLS-1$
props.setLook(wlLogconnection);
FormData fdlLogconnection = new FormData();
fdlLogconnection.left = new FormAttachment(0, 0);
fdlLogconnection.right= new FormAttachment(middle, -margin);
fdlLogconnection.top = new FormAttachment(wRejectedStep, margin*4);
wlLogconnection.setLayoutData(fdlLogconnection);
wbLogconnection=new Button(wLogComp, SWT.PUSH);
wbLogconnection.setText(Messages.getString("TransDialog.LogconnectionButton.Label")); //$NON-NLS-1$
wbLogconnection.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
DatabaseMeta databaseMeta = new DatabaseMeta();
databaseMeta.shareVariablesWith(transMeta);
DatabaseDialog cid = new DatabaseDialog(shell, databaseMeta);
if (cid.open()!=null)
{
transMeta.addDatabase(databaseMeta);
wLogconnection.add(databaseMeta.getName());
wLogconnection.select(wLogconnection.getItemCount()-1);
}
}
});
FormData fdbLogconnection = new FormData();
fdbLogconnection.right= new FormAttachment(100, 0);
fdbLogconnection.top = new FormAttachment(wRejectedStep, margin*4);
wbLogconnection.setLayoutData(fdbLogconnection);
wLogconnection=new CCombo(wLogComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wLogconnection);
wLogconnection.addModifyListener(lsMod);
FormData fdLogconnection = new FormData();
fdLogconnection.left = new FormAttachment(middle, 0);
fdLogconnection.top = new FormAttachment(wRejectedStep, margin*4);
fdLogconnection.right= new FormAttachment(wbLogconnection, -margin);
wLogconnection.setLayoutData(fdLogconnection);
// Log table...:
Label wlLogtable = new Label(wLogComp, SWT.RIGHT);
wlLogtable.setText(Messages.getString("TransDialog.Logtable.Label")); //$NON-NLS-1$
props.setLook(wlLogtable);
FormData fdlLogtable = new FormData();
fdlLogtable.left = new FormAttachment(0, 0);
fdlLogtable.right= new FormAttachment(middle, -margin);
fdlLogtable.top = new FormAttachment(wLogconnection, margin);
wlLogtable.setLayoutData(fdlLogtable);
wLogtable=new Text(wLogComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wLogtable);
wLogtable.addModifyListener(lsMod);
FormData fdLogtable = new FormData();
fdLogtable.left = new FormAttachment(middle, 0);
fdLogtable.top = new FormAttachment(wLogconnection, margin);
fdLogtable.right= new FormAttachment(100, 0);
wLogtable.setLayoutData(fdLogtable);
// step Log table...:
wlStepLogtable = new Label(wLogComp, SWT.RIGHT);
wlStepLogtable.setText(Messages.getString("TransDialog.StepLogtable.Label")); //$NON-NLS-1$
props.setLook(wlStepLogtable);
FormData fdlStepLogtable = new FormData();
fdlStepLogtable.left = new FormAttachment(0, 0);
fdlStepLogtable.right= new FormAttachment(middle, -margin);
fdlStepLogtable.top = new FormAttachment(wLogtable, margin);
wlStepLogtable.setLayoutData(fdlStepLogtable);
wStepLogtable=new Text(wLogComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wStepLogtable);
wStepLogtable.addModifyListener(lsMod);
FormData fdStepLogtable = new FormData();
fdStepLogtable.left = new FormAttachment(middle, 0);
fdStepLogtable.top = new FormAttachment(wLogtable, margin);
fdStepLogtable.right= new FormAttachment(100, 0);
wStepLogtable.setLayoutData(fdStepLogtable);
Label wlBatch = new Label(wLogComp, SWT.RIGHT);
wlBatch.setText(Messages.getString("TransDialog.LogBatch.Label")); //$NON-NLS-1$
props.setLook(wlBatch);
FormData fdlBatch = new FormData();
fdlBatch.left = new FormAttachment(0, 0);
fdlBatch.top = new FormAttachment(wStepLogtable, margin);
fdlBatch.right= new FormAttachment(middle, -margin);
wlBatch.setLayoutData(fdlBatch);
wBatch=new Button(wLogComp, SWT.CHECK);
props.setLook(wBatch);
FormData fdBatch = new FormData();
fdBatch.left = new FormAttachment(middle, 0);
fdBatch.top = new FormAttachment(wStepLogtable, margin);
fdBatch.right= new FormAttachment(100, 0);
wBatch.setLayoutData(fdBatch);
Label wlLogfield = new Label(wLogComp, SWT.RIGHT);
wlLogfield.setText(Messages.getString("TransDialog.Logfield.Label")); //$NON-NLS-1$
props.setLook(wlLogfield);
FormData fdlLogfield = new FormData();
fdlLogfield.left = new FormAttachment(0, 0);
fdlLogfield.top = new FormAttachment(wBatch, margin);
fdlLogfield.right= new FormAttachment(middle, -margin);
wlLogfield.setLayoutData(fdlLogfield);
wLogfield=new Button(wLogComp, SWT.CHECK);
props.setLook(wLogfield);
FormData fdLogfield = new FormData();
fdLogfield.left = new FormAttachment(middle, 0);
fdLogfield.top = new FormAttachment(wBatch, margin);
fdLogfield.right= new FormAttachment(100, 0);
wLogfield.setLayoutData(fdLogfield);
FormData fdLogComp = new FormData();
fdLogComp.left = new FormAttachment(0, 0);
fdLogComp.top = new FormAttachment(0, 0);
fdLogComp.right = new FormAttachment(100, 0);
fdLogComp.bottom= new FormAttachment(100, 0);
wLogComp.setLayoutData(fdLogComp);
wLogComp.layout();
wLogTab.setControl(wLogComp);
/// END OF LOG TAB
}
private void addDateTab()
{
// START OF DATE TAB///
wDateTab=new CTabItem(wTabFolder, SWT.NONE);
wDateTab.setText(Messages.getString("TransDialog.DateTab.Label")); //$NON-NLS-1$
FormLayout DateLayout = new FormLayout ();
DateLayout.marginWidth = Const.MARGIN;
DateLayout.marginHeight = Const.MARGIN;
Composite wDateComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wDateComp);
wDateComp.setLayout(DateLayout);
// Max date table connection...
Label wlMaxdateconnection = new Label(wDateComp, SWT.RIGHT);
wlMaxdateconnection.setText(Messages.getString("TransDialog.MaxdateConnection.Label")); //$NON-NLS-1$
props.setLook(wlMaxdateconnection);
FormData fdlMaxdateconnection = new FormData();
fdlMaxdateconnection.left = new FormAttachment(0, 0);
fdlMaxdateconnection.right= new FormAttachment(middle, -margin);
fdlMaxdateconnection.top = new FormAttachment(0, 0);
wlMaxdateconnection.setLayoutData(fdlMaxdateconnection);
wMaxdateconnection=new CCombo(wDateComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wMaxdateconnection);
wMaxdateconnection.addModifyListener(lsMod);
FormData fdMaxdateconnection = new FormData();
fdMaxdateconnection.left = new FormAttachment(middle, 0);
fdMaxdateconnection.top = new FormAttachment(0, 0);
fdMaxdateconnection.right= new FormAttachment(100, 0);
wMaxdateconnection.setLayoutData(fdMaxdateconnection);
// Maxdate table...:
Label wlMaxdatetable = new Label(wDateComp, SWT.RIGHT);
wlMaxdatetable.setText(Messages.getString("TransDialog.MaxdateTable.Label")); //$NON-NLS-1$
props.setLook(wlMaxdatetable);
FormData fdlMaxdatetable = new FormData();
fdlMaxdatetable.left = new FormAttachment(0, 0);
fdlMaxdatetable.right= new FormAttachment(middle, -margin);
fdlMaxdatetable.top = new FormAttachment(wMaxdateconnection, margin);
wlMaxdatetable.setLayoutData(fdlMaxdatetable);
wMaxdatetable=new Text(wDateComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wMaxdatetable);
wMaxdatetable.addModifyListener(lsMod);
FormData fdMaxdatetable = new FormData();
fdMaxdatetable.left = new FormAttachment(middle, 0);
fdMaxdatetable.top = new FormAttachment(wMaxdateconnection, margin);
fdMaxdatetable.right= new FormAttachment(100, 0);
wMaxdatetable.setLayoutData(fdMaxdatetable);
// Maxdate field...:
Label wlMaxdatefield = new Label(wDateComp, SWT.RIGHT);
wlMaxdatefield.setText(Messages.getString("TransDialog.MaxdateField.Label")); //$NON-NLS-1$
props.setLook(wlMaxdatefield);
FormData fdlMaxdatefield = new FormData();
fdlMaxdatefield.left = new FormAttachment(0, 0);
fdlMaxdatefield.right= new FormAttachment(middle, -margin);
fdlMaxdatefield.top = new FormAttachment(wMaxdatetable, margin);
wlMaxdatefield.setLayoutData(fdlMaxdatefield);
wMaxdatefield=new Text(wDateComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wMaxdatefield);
wMaxdatefield.addModifyListener(lsMod);
FormData fdMaxdatefield = new FormData();
fdMaxdatefield.left = new FormAttachment(middle, 0);
fdMaxdatefield.top = new FormAttachment(wMaxdatetable, margin);
fdMaxdatefield.right= new FormAttachment(100, 0);
wMaxdatefield.setLayoutData(fdMaxdatefield);
// Maxdate offset...:
Label wlMaxdateoffset = new Label(wDateComp, SWT.RIGHT);
wlMaxdateoffset.setText(Messages.getString("TransDialog.MaxdateOffset.Label")); //$NON-NLS-1$
props.setLook(wlMaxdateoffset);
FormData fdlMaxdateoffset = new FormData();
fdlMaxdateoffset.left = new FormAttachment(0, 0);
fdlMaxdateoffset.right= new FormAttachment(middle, -margin);
fdlMaxdateoffset.top = new FormAttachment(wMaxdatefield, margin);
wlMaxdateoffset.setLayoutData(fdlMaxdateoffset);
wMaxdateoffset=new Text(wDateComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wMaxdateoffset);
wMaxdateoffset.addModifyListener(lsMod);
FormData fdMaxdateoffset = new FormData();
fdMaxdateoffset.left = new FormAttachment(middle, 0);
fdMaxdateoffset.top = new FormAttachment(wMaxdatefield, margin);
fdMaxdateoffset.right= new FormAttachment(100, 0);
wMaxdateoffset.setLayoutData(fdMaxdateoffset);
// Maxdate diff...:
Label wlMaxdatediff = new Label(wDateComp, SWT.RIGHT);
wlMaxdatediff.setText(Messages.getString("TransDialog.Maxdatediff.Label")); //$NON-NLS-1$
props.setLook(wlMaxdatediff);
FormData fdlMaxdatediff = new FormData();
fdlMaxdatediff.left = new FormAttachment(0, 0);
fdlMaxdatediff.right= new FormAttachment(middle, -margin);
fdlMaxdatediff.top = new FormAttachment(wMaxdateoffset, margin);
wlMaxdatediff.setLayoutData(fdlMaxdatediff);
wMaxdatediff=new Text(wDateComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wMaxdatediff);
wMaxdatediff.addModifyListener(lsMod);
FormData fdMaxdatediff = new FormData();
fdMaxdatediff.left = new FormAttachment(middle, 0);
fdMaxdatediff.top = new FormAttachment(wMaxdateoffset, margin);
fdMaxdatediff.right= new FormAttachment(100, 0);
wMaxdatediff.setLayoutData(fdMaxdatediff);
connectionNames = new String[transMeta.nrDatabases()];
for (int i=0;i<transMeta.nrDatabases();i++)
{
DatabaseMeta ci = transMeta.getDatabase(i);
wLogconnection.add(ci.getName());
wMaxdateconnection.add(ci.getName());
connectionNames[i] = ci.getName();
}
FormData fdDateComp = new FormData();
fdDateComp.left = new FormAttachment(0, 0);
fdDateComp.top = new FormAttachment(0, 0);
fdDateComp.right = new FormAttachment(100, 0);
fdDateComp.bottom= new FormAttachment(100, 0);
wDateComp.setLayoutData(fdDateComp);
wDateComp.layout();
wDateTab.setControl(wDateComp);
/// END OF DATE TAB
}
private void addDepTab()
{
// START OF Dep TAB///
wDepTab=new CTabItem(wTabFolder, SWT.NONE);
wDepTab.setText(Messages.getString("TransDialog.DepTab.Label")); //$NON-NLS-1$
FormLayout DepLayout = new FormLayout ();
DepLayout.marginWidth = Const.MARGIN;
DepLayout.marginHeight = Const.MARGIN;
Composite wDepComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wDepComp);
wDepComp.setLayout(DepLayout);
Label wlFields = new Label(wDepComp, SWT.RIGHT);
wlFields.setText(Messages.getString("TransDialog.Fields.Label")); //$NON-NLS-1$
props.setLook(wlFields);
FormData fdlFields = new FormData();
fdlFields.left = new FormAttachment(0, 0);
fdlFields.top = new FormAttachment(0, 0);
wlFields.setLayoutData(fdlFields);
final int FieldsCols=3;
final int FieldsRows=transMeta.nrDependencies();
ColumnInfo[] colinf=new ColumnInfo[FieldsCols];
colinf[0]=new ColumnInfo(Messages.getString("TransDialog.ColumnInfo.Connection.Label"), ColumnInfo.COLUMN_TYPE_CCOMBO, connectionNames); //$NON-NLS-1$
colinf[1]=new ColumnInfo(Messages.getString("TransDialog.ColumnInfo.Table.Label"), ColumnInfo.COLUMN_TYPE_TEXT, false); //$NON-NLS-1$
colinf[2]=new ColumnInfo(Messages.getString("TransDialog.ColumnInfo.Field.Label"), ColumnInfo.COLUMN_TYPE_TEXT, false); //$NON-NLS-1$
wFields=new TableView(transMeta, wDepComp,
SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI,
colinf,
FieldsRows,
lsMod,
props
);
wGet=new Button(wDepComp, SWT.PUSH);
wGet.setText(Messages.getString("TransDialog.GetDependenciesButton.Label")); //$NON-NLS-1$
fdGet = new FormData();
fdGet.bottom = new FormAttachment(100, 0);
fdGet.left = new FormAttachment(50, 0);
wGet.setLayoutData(fdGet);
FormData fdFields = new FormData();
fdFields.left = new FormAttachment(0, 0);
fdFields.top = new FormAttachment(wlFields, margin);
fdFields.right = new FormAttachment(100, 0);
fdFields.bottom= new FormAttachment(wGet, 0);
wFields.setLayoutData(fdFields);
FormData fdDepComp = new FormData();
fdDepComp.left = new FormAttachment(0, 0);
fdDepComp.top = new FormAttachment(0, 0);
fdDepComp.right = new FormAttachment(100, 0);
fdDepComp.bottom= new FormAttachment(100, 0);
wDepComp.setLayoutData(fdDepComp);
wDepComp.layout();
wDepTab.setControl(wDepComp);
/// END OF DEP TAB
}
private void addMiscTab()
{
// START OF PERFORMANCE TAB///
wMiscTab=new CTabItem(wTabFolder, SWT.NONE);
wMiscTab.setText(Messages.getString("TransDialog.MiscTab.Label")); //$NON-NLS-1$
Composite wMiscComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wMiscComp);
FormLayout perfLayout = new FormLayout();
perfLayout.marginWidth = Const.FORM_MARGIN;
perfLayout.marginHeight = Const.FORM_MARGIN;
wMiscComp.setLayout(perfLayout);
// Rows in Rowset:
Label wlSizeRowset = new Label(wMiscComp, SWT.RIGHT);
wlSizeRowset.setText(Messages.getString("TransDialog.SizeRowset.Label")); //$NON-NLS-1$
props.setLook(wlSizeRowset);
FormData fdlSizeRowset = new FormData();
fdlSizeRowset.left = new FormAttachment(0, 0);
fdlSizeRowset.right= new FormAttachment(middle, -margin);
fdlSizeRowset.top = new FormAttachment(0, margin);
wlSizeRowset.setLayoutData(fdlSizeRowset);
wSizeRowset=new Text(wMiscComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wSizeRowset);
wSizeRowset.addModifyListener(lsMod);
FormData fdSizeRowset = new FormData();
fdSizeRowset.left = new FormAttachment(middle, 0);
fdSizeRowset.top = new FormAttachment(0, margin);
fdSizeRowset.right= new FormAttachment(100, 0);
wSizeRowset.setLayoutData(fdSizeRowset);
// Show feedback in transformations steps?
Label wlShowFeedback = new Label(wMiscComp, SWT.RIGHT);
wlShowFeedback.setText(Messages.getString("TransDialog.ShowFeedbackRow.Label"));
props.setLook(wlShowFeedback);
FormData fdlShowFeedback = new FormData();
fdlShowFeedback.left = new FormAttachment(0, 0);
fdlShowFeedback.top = new FormAttachment(wSizeRowset, margin);
fdlShowFeedback.right= new FormAttachment(middle, -margin);
wlShowFeedback.setLayoutData(fdlShowFeedback);
wShowFeedback=new Button(wMiscComp, SWT.CHECK);
props.setLook(wShowFeedback);
FormData fdShowFeedback = new FormData();
fdShowFeedback.left = new FormAttachment(middle, 0);
fdShowFeedback.top = new FormAttachment(wSizeRowset, margin);
fdShowFeedback.right= new FormAttachment(100, 0);
wShowFeedback.setLayoutData(fdShowFeedback);
// Feedback size
Label wlFeedbackSize = new Label(wMiscComp, SWT.RIGHT);
wlFeedbackSize.setText(Messages.getString("TransDialog.FeedbackSize.Label"));
props.setLook(wlFeedbackSize);
FormData fdlFeedbackSize = new FormData();
fdlFeedbackSize.left = new FormAttachment(0, 0);
fdlFeedbackSize.right= new FormAttachment(middle, -margin);
fdlFeedbackSize.top = new FormAttachment(wShowFeedback, margin);
wlFeedbackSize.setLayoutData(fdlFeedbackSize);
wFeedbackSize=new Text(wMiscComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wFeedbackSize);
FormData fdFeedbackSize = new FormData();
fdFeedbackSize.left = new FormAttachment(middle, 0);
fdFeedbackSize.right= new FormAttachment(100, -margin);
fdFeedbackSize.top = new FormAttachment(wShowFeedback, margin);
wFeedbackSize.setLayoutData(fdFeedbackSize);
// Unique connections
Label wlUniqueConnections = new Label(wMiscComp, SWT.RIGHT);
wlUniqueConnections.setText(Messages.getString("TransDialog.UniqueConnections.Label")); //$NON-NLS-1$
props.setLook(wlUniqueConnections);
FormData fdlUniqueConnections = new FormData();
fdlUniqueConnections.left = new FormAttachment(0, 0);
fdlUniqueConnections.right= new FormAttachment(middle, -margin);
fdlUniqueConnections.top = new FormAttachment(wFeedbackSize, margin);
wlUniqueConnections.setLayoutData(fdlUniqueConnections);
wUniqueConnections=new Button(wMiscComp, SWT.CHECK);
props.setLook(wUniqueConnections);
FormData fdUniqueConnections = new FormData();
fdUniqueConnections.left = new FormAttachment(middle, 0);
fdUniqueConnections.top = new FormAttachment(wFeedbackSize, margin);
fdUniqueConnections.right= new FormAttachment(100, 0);
wUniqueConnections.setLayoutData(fdUniqueConnections);
// Shared objects file
Label wlSharedObjectsFile = new Label(wMiscComp, SWT.RIGHT);
wlSharedObjectsFile.setText(Messages.getString("TransDialog.SharedObjectsFile.Label")); //$NON-NLS-1$
props.setLook(wlSharedObjectsFile);
FormData fdlSharedObjectsFile = new FormData();
fdlSharedObjectsFile.left = new FormAttachment(0, 0);
fdlSharedObjectsFile.right= new FormAttachment(middle, -margin);
fdlSharedObjectsFile.top = new FormAttachment(wUniqueConnections, margin);
wlSharedObjectsFile.setLayoutData(fdlSharedObjectsFile);
wSharedObjectsFile=new TextVar(transMeta, wMiscComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wlSharedObjectsFile.setToolTipText(Messages.getString("TransDialog.SharedObjectsFile.Tooltip")); //$NON-NLS-1$
wSharedObjectsFile.setToolTipText(Messages.getString("TransDialog.SharedObjectsFile.Tooltip")); //$NON-NLS-1$
props.setLook(wSharedObjectsFile);
FormData fdSharedObjectsFile = new FormData();
fdSharedObjectsFile.left = new FormAttachment(middle, 0);
fdSharedObjectsFile.top = new FormAttachment(wUniqueConnections, margin);
fdSharedObjectsFile.right= new FormAttachment(100, 0);
wSharedObjectsFile.setLayoutData(fdSharedObjectsFile);
wSharedObjectsFile.addModifyListener(new ModifyListener()
{
public void modifyText(ModifyEvent arg0)
{
sharedObjectsFileChanged = true;
}
}
);
// Show feedback in transformations steps?
Label wlManageThreads = new Label(wMiscComp, SWT.RIGHT);
wlManageThreads.setText(Messages.getString("TransDialog.ManageThreadPriorities.Label"));
props.setLook(wlManageThreads);
FormData fdlManageThreads = new FormData();
fdlManageThreads.left = new FormAttachment(0, 0);
fdlManageThreads.top = new FormAttachment(wSharedObjectsFile, margin);
fdlManageThreads.right= new FormAttachment(middle, -margin);
wlManageThreads.setLayoutData(fdlManageThreads);
wManageThreads=new Button(wMiscComp, SWT.CHECK);
props.setLook(wManageThreads);
FormData fdManageThreads = new FormData();
fdManageThreads.left = new FormAttachment(middle, 0);
fdManageThreads.top = new FormAttachment(wSharedObjectsFile, margin);
fdManageThreads.right= new FormAttachment(100, 0);
wManageThreads.setLayoutData(fdManageThreads);
FormData fdMiscComp = new FormData();
fdMiscComp.left = new FormAttachment(0, 0);
fdMiscComp.top = new FormAttachment(0, 0);
fdMiscComp.right = new FormAttachment(100, 0);
fdMiscComp.bottom= new FormAttachment(100, 0);
wMiscComp.setLayoutData(fdMiscComp);
wMiscComp.layout();
wMiscTab.setControl(wMiscComp);
/// END OF PERF TAB
}
private void addPartTab()
{
// START OF PARTITION TAB///
wPartTab=new CTabItem(wTabFolder, SWT.NONE);
wPartTab.setText(Messages.getString("TransDialog.PartitioningTab.Label")); //$NON-NLS-1$
Composite wPartComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wPartComp);
FormLayout partLayout = new FormLayout();
partLayout.marginWidth = Const.FORM_MARGIN;
partLayout.marginHeight = Const.FORM_MARGIN;
wPartComp.setLayout(partLayout);
// Buttons new / delete
Button wNew = new Button(wPartComp, SWT.PUSH);
wNew.setText(Messages.getString("System.Button.New"));
props.setLook(wNew);
wNew.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { newSchema(); } });
Button wDelete = new Button(wPartComp, SWT.PUSH);
wDelete.setText(Messages.getString("System.Button.Delete"));
props.setLook(wDelete);
wDelete.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { deleteSchema(); } });
wGetPartitions = new Button(wPartComp, SWT.PUSH);
wGetPartitions.setText(Messages.getString("TransDialog.GetPartitionsButton.Label"));
props.setLook(wGetPartitions);
wGetPartitions.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { getPartitions(); } });
// put the buttons centered at the bottom of the tab
BaseStepDialog.positionBottomButtons(wPartComp, new Button[] { wNew, wGetPartitions, wDelete, } , margin, null);
// Schema list:
Label wlSchemaList = new Label(wPartComp, SWT.LEFT);
wlSchemaList.setText(Messages.getString("TransDialog.SchemaList.Label")); //$NON-NLS-1$
props.setLook(wlSchemaList);
FormData fdlSchemaList=new FormData();
fdlSchemaList.left = new FormAttachment(0, 0);
fdlSchemaList.top = new FormAttachment(0, margin);
wlSchemaList.setLayoutData(fdlSchemaList);
wSchemaList=new List(wPartComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
props.setLook(wSchemaList);
FormData fdSchemaList=new FormData();
fdSchemaList.left = new FormAttachment(0, 0);
fdSchemaList.right = new FormAttachment(middle, 0);
fdSchemaList.top = new FormAttachment(wlSchemaList, margin);
fdSchemaList.bottom = new FormAttachment(wNew, -margin*2);
wSchemaList.setLayoutData(fdSchemaList);
wSchemaList.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { applySchema(); refreshPartitions(); } });
// Partition name:
Label wlSchemaName = new Label(wPartComp, SWT.LEFT);
wlSchemaName.setText(Messages.getString("TransDialog.PartitionName.Label")); //$NON-NLS-1$
props.setLook(wlSchemaName);
FormData fdlSchemaName=new FormData();
fdlSchemaName.left = new FormAttachment(middle, margin*2);
fdlSchemaName.top = new FormAttachment(0, margin);
wlSchemaName.setLayoutData(fdlSchemaName);
wSchemaName=new Text(wPartComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook(wSchemaName);
FormData fdSchemaName=new FormData();
fdSchemaName.left = new FormAttachment(middle, margin*2);
fdSchemaName.right = new FormAttachment(100, 0);
fdSchemaName.top = new FormAttachment(wlSchemaName, margin);
wSchemaName.setLayoutData(fdSchemaName);
// Schema list:
Label wlPartitions = new Label(wPartComp, SWT.LEFT);
wlPartitions.setText(Messages.getString("TransDialog.Partitions.Label")); //$NON-NLS-1$
props.setLook(wlPartitions);
FormData fdlPartitions=new FormData();
fdlPartitions.left = new FormAttachment(middle, margin*2);
fdlPartitions.top = new FormAttachment(wSchemaName, margin);
wlPartitions.setLayoutData(fdlPartitions);
ColumnInfo[] partitionColumns=new ColumnInfo[]
{
new ColumnInfo(Messages.getString("TransDialog.ColumnInfo.PartitionID.Label"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
};
wPartitions=new TableView(transMeta, wPartComp,
SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI,
partitionColumns,
1,
lsMod,
props
);
props.setLook(wPartitions);
FormData fdPartitions=new FormData();
fdPartitions.left = new FormAttachment(middle, margin*2);
fdPartitions.right = new FormAttachment(100, 0);
fdPartitions.top = new FormAttachment(wlPartitions, margin);
fdPartitions.bottom = new FormAttachment(wNew, -margin*2);
wPartitions.setLayoutData(fdPartitions);
// TransDialog.SchemaPartitions.Label
FormData fdPartComp = new FormData();
fdPartComp.left = new FormAttachment(0, 0);
fdPartComp.top = new FormAttachment(0, 0);
fdPartComp.right = new FormAttachment(100, 0);
fdPartComp.bottom= new FormAttachment(100, 0);
wPartComp.setLayoutData(fdPartComp);
wPartComp.layout();
wPartTab.setControl(wPartComp);
/// END OF PARTITIONING TAB
}
private void addMonitoringTab()
{
// START OF MONITORING TAB///
wMonitorTab=new CTabItem(wTabFolder, SWT.NONE);
wMonitorTab.setText(Messages.getString("TransDialog.MonitorTab.Label")); //$NON-NLS-1$
Composite wMonitorComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wMonitorComp);
FormLayout monitorLayout = new FormLayout();
monitorLayout.marginWidth = Const.FORM_MARGIN;
monitorLayout.marginHeight = Const.FORM_MARGIN;
wMonitorComp.setLayout(monitorLayout);
// Enable step performance monitoring?
Label wlEnableStepPerfMonitor = new Label(wMonitorComp, SWT.LEFT);
wlEnableStepPerfMonitor.setText(Messages.getString("TransDialog.StepPerformanceMonitoring.Label")); //$NON-NLS-1$
props.setLook(wlEnableStepPerfMonitor);
FormData fdlSchemaName=new FormData();
fdlSchemaName.left = new FormAttachment(0, 0);
fdlSchemaName.right = new FormAttachment(middle, -margin);
fdlSchemaName.top = new FormAttachment(0, 0);
wlEnableStepPerfMonitor.setLayoutData(fdlSchemaName);
wEnableStepPerfMonitor=new Button(wMonitorComp, SWT.CHECK);
props.setLook(wEnableStepPerfMonitor);
FormData fdEnableStepPerfMonitor=new FormData();
fdEnableStepPerfMonitor.left = new FormAttachment(middle, 0);
fdEnableStepPerfMonitor.right = new FormAttachment(100, 0);
fdEnableStepPerfMonitor.top = new FormAttachment(0, 0);
wEnableStepPerfMonitor.setLayoutData(fdEnableStepPerfMonitor);
wEnableStepPerfMonitor.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent selectionEvent) {
setFlags();
}
});
// Step performance interval
Label wlEnableStepPerfInterval = new Label(wMonitorComp, SWT.LEFT);
wlEnableStepPerfInterval.setText(Messages.getString("TransDialog.StepPerformanceInterval.Label")); //$NON-NLS-1$
props.setLook(wlEnableStepPerfInterval);
FormData fdlEnableStepPerfInterval=new FormData();
fdlEnableStepPerfInterval.left = new FormAttachment(0, 0);
fdlEnableStepPerfInterval.right = new FormAttachment(middle, -margin);
fdlEnableStepPerfInterval.top = new FormAttachment(wEnableStepPerfMonitor, margin);
wlEnableStepPerfInterval.setLayoutData(fdlEnableStepPerfInterval);
wEnableStepPerfInterval=new Text(wMonitorComp, SWT.LEFT | SWT.BORDER | SWT.SINGLE);
props.setLook(wEnableStepPerfInterval);
FormData fdEnableStepPerfInterval=new FormData();
fdEnableStepPerfInterval.left = new FormAttachment(middle, 0);
fdEnableStepPerfInterval.right = new FormAttachment(100, 0);
fdEnableStepPerfInterval.top = new FormAttachment(wEnableStepPerfMonitor, margin);
wEnableStepPerfInterval.setLayoutData(fdEnableStepPerfInterval);
// TransDialog.SchemaMonitoritions.Label
FormData fdMonitorComp = new FormData();
fdMonitorComp.left = new FormAttachment(0, 0);
fdMonitorComp.top = new FormAttachment(0, 0);
fdMonitorComp.right = new FormAttachment(100, 0);
fdMonitorComp.bottom= new FormAttachment(100, 0);
wMonitorComp.setLayoutData(fdMonitorComp);
wMonitorComp.layout();
wMonitorTab.setControl(wMonitorComp);
/// END OF MONITORING TAB
}
protected void getPartitions()
{
java.util.List<String> partitionedDatabaseNames = new ArrayList<String>();
for (int i=0;i<transMeta.getDatabases().size();i++)
{
DatabaseMeta databaseMeta = transMeta.getDatabase(i);
if (databaseMeta.isPartitioned())
{
partitionedDatabaseNames.add(databaseMeta.getName());
}
}
String dbNames[] = (String[]) partitionedDatabaseNames.toArray(new String[partitionedDatabaseNames.size()]);
if (dbNames.length>0)
{
EnterSelectionDialog dialog = new EnterSelectionDialog(shell, dbNames,
Messages.getString("TransDialog.SelectPartitionedDatabase.Title"),
Messages.getString("TransDialog.SelectPartitionedDatabase.Message"));
String dbName = dialog.open();
if (dbName!=null)
{
DatabaseMeta databaseMeta = transMeta.findDatabase(dbName);
PartitionDatabaseMeta[] partitioningInformation = databaseMeta.getPartitioningInformation();
if (partitioningInformation!=null)
{
// Here we are...
wPartitions.clearAll(false);
for (int i = 0; i < partitioningInformation.length; i++)
{
PartitionDatabaseMeta meta = partitioningInformation[i];
wPartitions.add(new String[] { meta.getPartitionId() } );
}
wPartitions.removeEmptyRows();
wPartitions.setRowNums();
wPartitions.optWidth(true);
}
}
}
}
protected void deleteSchema()
{
if (previousSchemaIndex>=0)
{
int idx = wSchemaList.getSelectionIndex();
schemas.remove( idx );
wSchemaList.remove( idx );
idx
if (idx<0) idx=0;
if (idx<schemas.size())
{
wSchemaList.select(idx);
previousSchemaIndex=idx;
}
else
{
previousSchemaIndex=-1;
}
refreshPartitions();
}
}
protected void applySchema()
{
if (previousSchemaIndex>=0)
{
PartitionSchema partitionSchema = (PartitionSchema)schemas.get(previousSchemaIndex);
partitionSchema.setName(wSchemaName.getText());
java.util.List<String> ids = new ArrayList<String>();
int nrNonEmptyPartitions = wPartitions.nrNonEmpty();
for (int i=0;i<nrNonEmptyPartitions;i++)
{
ids.add( wPartitions.getNonEmpty(i).getText(1) );
}
partitionSchema.setPartitionIDs(ids);
}
previousSchemaIndex=wSchemaList.getSelectionIndex();
}
protected void newSchema()
{
String name = Messages.getString("TransDialog.NewPartitionSchema.Name", Integer.toString(schemas.size() + 1));
EnterStringDialog askName = new EnterStringDialog(shell, name,
Messages.getString("TransDialog.NewPartitionSchema.Title"),
Messages.getString("TransDialog.NewPartitionSchema.Message"));
name = askName.open();
if (name!=null)
{
PartitionSchema schema = new PartitionSchema(name, new ArrayList<String>());
schemas.add(schema);
wSchemaList.add(name);
previousSchemaIndex = schemas.size()-1;
wSchemaList.select( previousSchemaIndex );
refreshPartitions();
}
}
public void dispose()
{
shell.dispose();
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData()
{
log.logDebug(toString(), Messages.getString("TransDialog.Log.GettingTransformationInfo")); //$NON-NLS-1$
wTransname.setText( Const.NVL(transMeta.getName(), "") );
wTransFilename.setText(Const.NVL(transMeta.getFilename(), "") );
wTransdescription.setText( Const.NVL(transMeta.getDescription(), "") );
wExtendeddescription.setText( Const.NVL(transMeta.getExtendedDescription(), "") );
wTransversion.setText( Const.NVL(transMeta.getTransversion(), "") );
wTransstatus.select( transMeta.getTransstatus()-1 );
if (transMeta.getCreatedUser()!=null) wCreateUser.setText ( transMeta.getCreatedUser() );
if (transMeta.getCreatedDate()!=null ) wCreateDate.setText ( transMeta.getCreatedDate().toString() );
if (transMeta.getModifiedUser()!=null) wModUser.setText ( transMeta.getModifiedUser() );
if (transMeta.getModifiedDate()!=null) wModDate.setText ( transMeta.getModifiedDate().toString() );
if (transMeta.getReadStep()!=null) wReadStep.setText ( transMeta.getReadStep().getName() );
if (transMeta.getWriteStep()!=null) wWriteStep.setText ( transMeta.getWriteStep().getName() );
if (transMeta.getInputStep()!=null) wInputStep.setText ( transMeta.getInputStep().getName() );
if (transMeta.getOutputStep()!=null) wOutputStep.setText ( transMeta.getOutputStep().getName() );
if (transMeta.getUpdateStep()!=null) wUpdateStep.setText ( transMeta.getUpdateStep().getName() );
if (transMeta.getRejectedStep()!=null) wRejectedStep.setText ( transMeta.getRejectedStep().getName() );
if (transMeta.getLogConnection()!=null) wLogconnection.setText ( transMeta.getLogConnection().getName());
wLogtable.setText( Const.NVL(transMeta.getLogTable(),"") );
wStepLogtable.setText( Const.NVL(transMeta.getStepPerformanceLogTable(),"") );
wBatch.setSelection(transMeta.isBatchIdUsed());
wLogfield.setSelection(transMeta.isLogfieldUsed());
if (transMeta.getMaxDateConnection()!=null) wMaxdateconnection.setText( transMeta.getMaxDateConnection().getName());
if (transMeta.getMaxDateTable()!=null) wMaxdatetable.setText ( transMeta.getMaxDateTable());
if (transMeta.getMaxDateField()!=null) wMaxdatefield.setText ( transMeta.getMaxDateField());
wMaxdateoffset.setText(Double.toString(transMeta.getMaxDateOffset()));
wMaxdatediff.setText(Double.toString(transMeta.getMaxDateDifference()));
for (int i=0;i<transMeta.nrDependencies();i++)
{
TableItem item = wFields.table.getItem(i);
TransDependency td = transMeta.getDependency(i);
DatabaseMeta conn = td.getDatabase();
String table = td.getTablename();
String field = td.getFieldname();
if (conn !=null) item.setText(1, conn.getName() );
if (table!=null) item.setText(2, table);
if (field!=null) item.setText(3, field);
}
wSizeRowset.setText(Integer.toString(transMeta.getSizeRowset()));
wUniqueConnections.setSelection(transMeta.isUsingUniqueConnections());
wShowFeedback.setSelection(transMeta.isFeedbackShown());
wFeedbackSize.setText(Integer.toString(transMeta.getFeedbackSize()));
wSharedObjectsFile.setText(Const.NVL(transMeta.getSharedObjectsFile(), ""));
wManageThreads.setSelection(transMeta.isUsingThreadPriorityManagment());
wFields.setRowNums();
wFields.optWidth(true);
// The partitions?
for (PartitionSchema schema : schemas)
{
wSchemaList.add(schema.getName());
}
if (schemas.size()>0)
{
wSchemaList.setSelection(0);
}
refreshPartitions();
// Directory:
if (transMeta.getDirectory()!=null && transMeta.getDirectory().getPath()!=null)
wDirectory.setText(transMeta.getDirectory().getPath());
// Performance monitoring tab:
wEnableStepPerfMonitor.setSelection(transMeta.isCapturingStepPerformanceSnapShots());
wEnableStepPerfInterval.setText(Long.toString(transMeta.getStepPerformanceCapturingDelay()));
wTransname.selectAll();
wTransname.setFocus();
setFlags();
}
private void refreshPartitions()
{
wPartitions.clearAll(false);
if (wSchemaList.getSelectionCount()==1)
{
wSchemaName.setEnabled(true);
wPartitions.table.setEnabled(true);
wGetPartitions.setEnabled(true);
PartitionSchema partitionSchema = (PartitionSchema)schemas.get(wSchemaList.getSelectionIndex());
wSchemaName.setText(partitionSchema.getName());
java.util.List<String> partitionIDs = partitionSchema.getPartitionIDs();
for (int i=0;i<partitionIDs.size();i++)
{
TableItem tableItem = new TableItem(wPartitions.table, SWT.NONE);
tableItem.setText(1, partitionIDs.get(i));
}
wPartitions.removeEmptyRows();
wPartitions.setRowNums();
wPartitions.optWidth(true);
}
else
{
wSchemaName.setEnabled(false);
wPartitions.table.setEnabled(false);
wGetPartitions.setEnabled(false);
}
}
public void setFlags()
{
wbDirectory.setEnabled(rep!=null);
// wDirectory.setEnabled(rep!=null);
wlDirectory.setEnabled(rep!=null);
wlStepLogtable.setEnabled(wEnableStepPerfMonitor.getSelection());
wStepLogtable.setEnabled(wEnableStepPerfMonitor.getSelection());
}
private void cancel()
{
props.setScreen(new WindowProperty(shell));
transMeta.setChanged(changed);
transMeta=null;
dispose();
}
private void ok()
{
boolean OK = true;
transMeta.setReadStep( transMeta.findStep( wReadStep.getText() ) );
transMeta.setWriteStep( transMeta.findStep( wWriteStep.getText() ) );
transMeta.setInputStep( transMeta.findStep( wInputStep.getText() ) );
transMeta.setOutputStep( transMeta.findStep( wOutputStep.getText() ) );
transMeta.setUpdateStep( transMeta.findStep( wUpdateStep.getText() ) );
transMeta.setRejectedStep( transMeta.findStep( wRejectedStep.getText() ) );
transMeta.setLogConnection( transMeta.findDatabase(wLogconnection.getText()) );
transMeta.setLogTable( wLogtable.getText() );
transMeta.setStepPerformanceLogTable( wStepLogtable.getText());
transMeta.setMaxDateConnection( transMeta.findDatabase(wMaxdateconnection.getText()) );
transMeta.setMaxDateTable( wMaxdatetable.getText() );
transMeta.setMaxDateField( wMaxdatefield.getText() );
transMeta.setBatchIdUsed( wBatch.getSelection() );
transMeta.setLogfieldUsed( wLogfield.getSelection() );
transMeta.setName( wTransname.getText() );
transMeta.setDescription( wTransdescription.getText() );
transMeta.setExtendedDescription( wExtendeddescription.getText() );
transMeta.setTransversion( wTransversion.getText() );
if ( wTransstatus.getSelectionIndex() != 2 )
{
transMeta.setTransstatus( wTransstatus.getSelectionIndex() + 1 );
}
else
{
transMeta.setTransstatus( -1 );
}
try
{
transMeta.setMaxDateOffset( Double.parseDouble(wMaxdateoffset.getText()) ) ;
}
catch(Exception e)
{
MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
mb.setText(Messages.getString("TransDialog.InvalidOffsetNumber.DialogTitle")); //$NON-NLS-1$
mb.setMessage(Messages.getString("TransDialog.InvalidOffsetNumber.DialogMessage")); //$NON-NLS-1$
mb.open();
wMaxdateoffset.setFocus();
wMaxdateoffset.selectAll();
OK=false;
}
try
{
transMeta.setMaxDateDifference( Double.parseDouble(wMaxdatediff.getText()) );
}
catch(Exception e)
{
MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
mb.setText(Messages.getString("TransDialog.InvalidDateDifferenceNumber.DialogTitle")); //$NON-NLS-1$
mb.setMessage(Messages.getString("TransDialog.InvalidDateDifferenceNumber.DialogMessage")); //$NON-NLS-1$
mb.open();
wMaxdatediff.setFocus();
wMaxdatediff.selectAll();
OK=false;
}
transMeta.removeAllDependencies();
int nrNonEmptyFields = wFields.nrNonEmpty();
for (int i=0;i<nrNonEmptyFields;i++)
{
TableItem item = wFields.getNonEmpty(i);
DatabaseMeta db = transMeta.findDatabase(item.getText(1));
String tablename = item.getText(2);
String fieldname = item.getText(3);
TransDependency td = new TransDependency(db, tablename, fieldname);
transMeta.addDependency(td);
}
transMeta.setSizeRowset( Const.toInt( wSizeRowset.getText(), Const.ROWS_IN_ROWSET) );
transMeta.setUsingUniqueConnections( wUniqueConnections.getSelection() );
transMeta.setFeedbackShown( wShowFeedback.getSelection() );
transMeta.setFeedbackSize( Const.toInt( wFeedbackSize.getText(), Const.ROWS_UPDATE ) );
transMeta.setSharedObjectsFile( wSharedObjectsFile.getText() );
transMeta.setUsingThreadPriorityManagment( wManageThreads.getSelection() );
if (directoryChangeAllowed) {
if (newDirectory!=null)
{
RepositoryDirectory dirFrom = transMeta.getDirectory();
long idDirFrom = dirFrom==null?-1L:dirFrom.getID();
try
{
rep.moveTransformation(transMeta.getName(), idDirFrom, newDirectory.getID() );
log.logDetailed(getClass().getName(), Messages.getString("TransDialog.Log.MovedDirectoryTo",newDirectory.getPath())); //$NON-NLS-1$ //$NON-NLS-2$
transMeta.setDirectory( newDirectory );
}
catch(KettleException ke)
{
transMeta.setDirectory( dirFrom );
OK=false;
new ErrorDialog(shell, Messages.getString("TransDialog.ErrorMovingTransformation.DialogTitle"), Messages.getString("TransDialog.ErrorMovingTransformation.DialogMessage"), ke); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
else
{
// Just update to the new selected directory...
if (newDirectory!=null) transMeta.setDirectory(newDirectory);
}
// Performance monitoring tab:
transMeta.setCapturingStepPerformanceSnapShots(wEnableStepPerfMonitor.getSelection());
transMeta.setStepPerformanceCapturingDelay(Long.parseLong(wEnableStepPerfInterval.getText()));
// Also get the partition schemas...
applySchema(); // get last changes too...
transMeta.setPartitionSchemas(schemas);
if (OK) dispose();
}
// Get the dependencies
private void get()
{
Table table = wFields.table;
for (int i=0;i<transMeta.nrSteps();i++)
{
StepMeta stepMeta = transMeta.getStep(i);
String con=null;
String tab=null;
TableItem item=null;
StepMetaInterface sii = stepMeta.getStepMetaInterface();
if (sii instanceof TableInputMeta)
{
TableInputMeta tii = (TableInputMeta)stepMeta.getStepMetaInterface();
if (tii.getDatabaseMeta()==null)
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("TransDialog.DatabaseMetaNotSet.Text"));
mb.open();
return;
}
con = tii.getDatabaseMeta().getName();
tab = getTableFromSQL(tii.getSQL());
if (tab==null) tab=stepMeta.getName();
}
if (sii instanceof DatabaseLookupMeta)
{
DatabaseLookupMeta dvli = (DatabaseLookupMeta)stepMeta.getStepMetaInterface();
con = dvli.getDatabaseMeta().getName();
tab = dvli.getTablename();
if (tab==null) tab=stepMeta.getName();
break;
}
if (tab!=null || con!=null)
{
item = new TableItem(table, SWT.NONE);
if (con!=null) item.setText(1, con);
if (tab!=null) item.setText(2, tab);
}
}
wFields.setRowNums();
}
private String getTableFromSQL(String sql)
{
if (sql==null) return null;
int idxfrom = sql.toUpperCase().indexOf("FROM"); //$NON-NLS-1$
int idxto = sql.toUpperCase().indexOf("WHERE"); //$NON-NLS-1$
if (idxfrom==-1) return null;
if (idxto==-1) idxto=sql.length();
return sql.substring(idxfrom+5, idxto);
}
// Generate code for create table...
// Conversions done by Database
private void sql()
{
DatabaseMeta ci = transMeta.findDatabase(wLogconnection.getText());
if (ci!=null)
{
String tablename = wLogtable.getText();
String stepTablename = wStepLogtable.getText();
if (!Const.isEmpty(tablename) || !Const.isEmpty(stepTablename) )
{
Database db = new Database(ci);
db.shareVariablesWith(transMeta);
try
{
db.connect();
RowMetaInterface r;
String createTable = "";
if (!Const.isEmpty(tablename)) {
r = Database.getTransLogrecordFields(false, wBatch.getSelection(), wLogfield.getSelection());
createTable += db.getDDL(tablename, r);
}
if (!Const.isEmpty(stepTablename)) {
r = Database.getStepPerformanceLogrecordFields();
createTable += db.getDDL(stepTablename, r);
}
if (!Const.isEmpty(createTable))
{
log.logBasic(toString(), createTable);
SQLEditor sqledit = new SQLEditor(shell, SWT.NONE, ci, transMeta.getDbCache(), createTable);
sqledit.open();
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION );
mb.setText(Messages.getString("TransDialog.NoSqlNedds.DialogTitle")); //$NON-NLS-1$
mb.setMessage(Messages.getString("TransDialog.NoSqlNedds.DialogMessage")); //$NON-NLS-1$
mb.open();
}
}
catch(KettleException e)
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setText(Messages.getString("TransDialog.ErrorOccurred.DialogTitle")); //$NON-NLS-1$
mb.setMessage(Messages.getString("TransDialog.ErrorOccurred.DialogMessage")+Const.CR+e.getMessage()); //$NON-NLS-1$
mb.open();
}
finally
{
db.disconnect();
}
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setText(Messages.getString("TransDialog.NeedLogtableName.DialogTitle")); //$NON-NLS-1$
mb.setMessage(Messages.getString("TransDialog.NeedLogtableName.DialogMessage")); //$NON-NLS-1$
mb.open();
}
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setText(Messages.getString("TransDialog.NeedValidLogtableConnection.DialogTitle")); //$NON-NLS-1$
mb.setMessage(Messages.getString("TransDialog.NeedValidLogtableConnection.DialogMessage")); //$NON-NLS-1$
mb.open();
}
}
public String toString()
{
return this.getClass().getName();
}
public boolean isSharedObjectsFileChanged()
{
return sharedObjectsFileChanged;
}
public void setDirectoryChangeAllowed(boolean directoryChangeAllowed) {
this.directoryChangeAllowed = directoryChangeAllowed;
}
} |
/*
* $Log: ClassUtils.java,v $
* Revision 1.14 2007-12-10 10:22:30 europe\L190409
* void NPE in classOf
*
* Revision 1.13 2007/09/13 12:39:05 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* cosmetic improvement
*
* Revision 1.12 2007/09/10 11:20:15 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added default getResourceURL()
*
* Revision 1.11 2007/07/18 13:35:30 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* try to get a resource as a URL
* no replacemen of space to %20 for jar-entries
*
* Revision 1.10 2007/05/09 09:25:54 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added nameOf()
*
* Revision 1.9 2007/02/12 14:09:05 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* Logger from LogUtil
*
* Revision 1.8 2006/09/14 11:44:51 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* correctede logger definition
*
* Revision 1.7 2005/09/26 15:29:33 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* change %20 to space and back
*
* Revision 1.6 2005/08/30 16:06:27 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* escape spaces in URL using %20
*
* Revision 1.5 2005/08/18 13:34:19 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* try to prefix resource with 'java:comp/env/', for TomCat compatibility
*
* Revision 1.4 2004/11/08 08:31:17 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added log-keyword in comments
*
*/
package nl.nn.adapterframework.util;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.log4j.Logger;
/**
* A collection of class management utility methods.
* @version Id
* @author Johan Verrips
*
*/
public class ClassUtils {
public static final String version = "$RCSfile: ClassUtils.java,v $ $Revision: 1.14 $ $Date: 2007-12-10 10:22:30 $";
private static Logger log = LogUtil.getLogger(ClassUtils.class);
/**
* Return the context classloader.
* BL: if this is command line operation, the classloading issues
* are more sane. During servlet execution, we explicitly set
* the ClassLoader.
*
* @return The context classloader.
*/
public static ClassLoader getClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
/**
* Retrieves the constructor of a class, based on the parameters
*
**/
public static Constructor getConstructorOnType(Class clas,Class[] parameterTypes) {
Constructor theConstructor=null;
try {
theConstructor=clas.getDeclaredConstructor(parameterTypes);
} catch (java.lang.NoSuchMethodException E)
{System.err.println(E);
System.err.println("Class: "+clas.getName());
for(int i=0;i<parameterTypes.length;i++) System.err.println("Parameter "+i+" type "+parameterTypes[i].getName());
}
return theConstructor;
}
/**
* Return a resource URL.
* BL: if this is command line operation, the classloading issues
* are more sane. During servlet execution, we explicitly set
* the ClassLoader.
*
* @return The context classloader.
* @deprecated Use getResourceURL().openStream instead.
*/
public static InputStream getResourceAsStream(Class klass, String resource) throws IOException {
InputStream stream=null;
URL url=getResourceURL(klass, resource);
stream=url.openStream();
return stream;
}
static public URL getResourceURL(String resource) {
return getResourceURL(null,resource);
}
/**
* Get a resource-URL, first from Class then from ClassLoader
* if not found with class.
*
* @deprecated Use getResourceURL(Object, resource) instead.
*
*/
static public URL getResourceURL(Class klass, String resource)
{
resource=Misc.replace(resource,"%20"," ");
URL url = null;
if (klass == null) {
klass = ClassUtils.class;
}
// first try to get the resoure as a resource
url = klass.getResource(resource);
if (url == null) {
url = klass.getClassLoader().getResource(resource);
}
// then try to get it as a URL
if (url == null) {
try {
url = new URL(resource);
} catch(MalformedURLException e) {
log.debug("Could not find resource as URL ["+resource+"]: "+e.getMessage());
}
}
// then try to get it in java:comp/env
if (url == null && resource!=null && !resource.startsWith("java:comp/env/")) {
log.debug("cannot find URL for resource ["+resource+"], now trying [java:comp/env/"+resource+"] (e.g. for TomCat)");
String altResource = "java:comp/env/"+resource;
url = klass.getResource(altResource); // to make things work under tomcat
if (url == null) {
url = klass.getClassLoader().getResource(altResource);
}
}
if (url==null)
log.warn("cannot find URL for resource ["+resource+"]");
else {
// Spaces must be escaped to %20. But ClassLoader.getResource(String)
// has a bug in Java 1.3 and 1.4 and doesn't do this escaping.
// See also:
// Escaping spaces to %20 if spaces are found.
String urlString = url.toString();
if (urlString.indexOf(' ')>=0 && !urlString.startsWith("jar:")) {
urlString=Misc.replace(urlString," ","%20");
try {
URL escapedURL = new URL(urlString);
log.debug("resolved resource-string ["+resource+"] to URL ["+escapedURL.toString()+"]");
return escapedURL;
} catch(MalformedURLException e) {
log.warn("Could not find URL from space-escaped url ["+urlString+"], will use unescaped original version ["+url.toString()+"] ");
}
}
}
return url;
}
/**
* Get a resource-URL, first from Class then from ClassLoader
* if not found with class.
*
*/
static public URL getResourceURL(Object obj, String resource)
{
return getResourceURL(obj.getClass(), resource);
}
/**
* Tests if a class implements a given interface
*
* @return true if class implements given interface.
*/
public static boolean implementsInterface(Class class1, Class iface) {
return iface.isAssignableFrom (class1);
}
/**
* Tests if a class implements a given interface
*
* @return true if class implements given interface.
*/
public static boolean implementsInterface(String className, String iface) throws Exception {
Class class1 = ClassUtils.loadClass (className);
Class class2 = ClassUtils.loadClass (iface);
return ClassUtils.implementsInterface(class1, class2);
}
public static long lastModified(Class aClass)
throws IOException, IllegalArgumentException {
URL url = aClass.getProtectionDomain().getCodeSource().getLocation();
if (!url.getProtocol().equals("file")) {
throw new IllegalArgumentException("Class was not loaded from a file url");
}
File directory = new File(url.getFile());
if (!directory.isDirectory()) {
throw new IllegalArgumentException("Class was not loaded from a directory");
}
String className = aClass.getName();
String basename = className.substring(className.lastIndexOf(".") + 1);
File file = new File(directory, basename + ".class");
return file.lastModified();
}
/**
* Load a class given its name.
* BL: We wan't to use a known ClassLoader--hopefully the heirarchy
* is set correctly.
*
* @param className A class name
* @return The class pointed to by <code>className</code>
* @exception ClassNotFoundException If a loading error occurs
*/
public static Class loadClass(String className) throws ClassNotFoundException {
return ClassUtils.getClassLoader().loadClass(className);
}
/**
* Create a new instance given a class name. The constructor of the class
* does NOT have parameters.
*
* @param className A class name
* @return A new instance
* @exception Exception If an instantiation error occurs
*/
public static Object newInstance(String className) throws Exception {
return ClassUtils.loadClass(className).newInstance();
}
/**
* creates a new instance of an object, based on the classname as string, the classes
* and the actual parameters.
*/
public static Object newInstance(String className, Class[] parameterClasses, Object[] parameterObjects) {
// get a class object
Class clas = null;
try {
clas=ClassUtils.loadClass(className);
} catch (java.lang.ClassNotFoundException C) {System.err.println(C);}
Constructor con;
con= ClassUtils.getConstructorOnType(clas, parameterClasses);
Object theObject=null;
try {
theObject=con.newInstance(parameterObjects);
} catch(java.lang.InstantiationException E) {System.err.println(E);}
catch(java.lang.IllegalAccessException A) {System.err.println(A);}
catch(java.lang.reflect.InvocationTargetException T) {System.err.println(T);}
return theObject;
}
/**
* Creates a new instance from a class, while it looks for a constructor
* that matches the parameters, and initializes the object (by calling the constructor)
* Notice: this does not work when the instantiated object uses an interface class
* as a parameter, as the class names are, in that case, not the same..
*
* @param className a class Name
* @param parameterObjects the parameters for the constructor
* @return A new Instance
*
**/
public static Object newInstance(String className, Object[] parameterObjects) {
Class parameterClasses[] = new Class[parameterObjects.length];
for (int i = 0; i < parameterObjects.length; i++)
parameterClasses[i] = parameterObjects[i].getClass();
return newInstance(className, parameterClasses, parameterObjects);
}
/**
* Gets the absolute pathname of the class file
* containing the specified class name, as prescribed
* by the current classpath.
*
* @param aClass A class
*/
public static String which(Class aClass) {
String path = null;
try {
path = aClass.getProtectionDomain().getCodeSource().getLocation().toString();
} catch (Throwable t){
}
return path;
}
/**
* returns the classname of the object, without the pacakge name.
*/
public static String nameOf(Object o) {
if (o==null) {
return "<null>";
}
String name=o.getClass().getName();
int pos=name.lastIndexOf('.');
if (pos<0) {
return name;
} else {
return name.substring(pos+1);
}
}
} |
package com.pylonproducts.wifiwizard;
import org.apache.cordova.*;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiEnterpriseConfig;
import android.content.Context;
import android.util.Log;
public class WifiWizard extends CordovaPlugin {
private static final String ADD_NETWORK = "addNetwork";
private static final String REMOVE_NETWORK = "removeNetwork";
private static final String CONNECT_NETWORK = "connectNetwork";
private static final String DISCONNECT_NETWORK = "disconnectNetwork";
private static final String LIST_NETWORKS = "listNetworks";
private static final String TAG = "WifiWizard";
private WifiManager wifiManager;
private CallbackContext callbackContext;
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
this.wifiManager = (WifiManager) cordova.getActivity().getSystemService(Context.WIFI_SERVICE);
}
@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext)
throws JSONException {
this.callbackContext = callbackContext;
if (!wifiManager.isWifiEnabled()) {
callbackContext.error("Wifi is not enabled.");
return false;
}
if (action.equals(ADD_NETWORK)) {
return this.addNetwork(callbackContext, data);
}
else if (action.equals(REMOVE_NETWORK)) {
return this.removeNetwork(callbackContext, data);
}
else if (action.equals(CONNECT_NETWORK)) {
return this.connectNetwork(callbackContext, data);
}
else if (action.equals(DISCONNECT_NETWORK)) {
return this.disconnectNetwork(callbackContext, data);
}
else if (action.equals(LIST_NETWORKS)) {
return this.listNetworks(callbackContext);
}
callbackContext.error("Incorrect action parameter: " + action);
return false;
}
// Them helper methods!
/**
* This methods adds a network to the list of available WiFi networks.
* If the network already exists, then it updates it.
*
* @params callbackContext A Cordova callback context.
* @params data JSON Array with [0] == SSID, [1] == password
* @return true if add successful, false if add fails
*/
private boolean addNetwork(CallbackContext callbackContext, JSONArray data) {
// Initialize the WifiConfiguration object
WifiConfiguration wifi = new WifiConfiguration();
Log.d(TAG, "WifiWizard: addNetwork entered.");
try {
String authType = data.getString(2);
// TODO: Check if network exists, if so, then do an update instead.
if (authType.equals("WPA")) {
// TODO: connect/configure for WPA
}
else if (authType.equals("WEP")) {
// TODO: connect/configure for WEP
// or not? screw wep
Log.d(TAG, "WEP unsupported.");
callbackContext.error("WEP unsupported");
return false;
}
// TODO: Add more authentications as necessary
else {
Log.d(TAG, "Wifi Authentication Type Not Supported.");
callbackContext.error("Wifi Authentication Type Not Supported: " + authType);
return false;
}
// Currently, just assuming WPA, as that is the only one that is supported.
wifi.SSID = data.getString(0);
wifi.preSharedKey = data.getString(1);
wifi.status = WifiConfiguration.Status.ENABLED;
wifi.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wifi.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wifi.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wifi.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wifi.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wifi.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wifiManager.addNetwork(wifi);
wifiManager.saveConfiguration();
return true;
}
catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG,e.getMessage());
return false;
}
}
/**
* This method removes a network from the list of configured networks.
*
* @param callbackContext A Cordova callback context
* @param data JSON Array, with [0] being SSID to remove
* @return true if network removed, false if failed
*/
private boolean removeNetwork(CallbackContext callbackContext, JSONArray data) {
Log.d(TAG, "WifiWizard: removeNetwork entered.");
if(!validateData(data)) {
callbackContext.error("WifiWizard: removeNetwork data invalid");
Log.d(TAG, "WifiWizard: removeNetwork data invalid");
return false;
}
// TODO: Verify the type of data!
try {
String ssidToDisconnect = data.getString(0);
int networkIdToRemove = ssidToNetworkId(ssidToDisconnect);
if (networkIdToRemove > 0) {
wifiManager.removeNetwork(networkIdToRemove);
wifiManager.saveConfiguration();
callbackContext.success("Network removed.");
return true;
}
else {
callbackContext.error("Network not found.");
Log.d(TAG, "WifiWizard: Network not found, can't remove.");
return false;
}
}
catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG, e.getMessage());
return false;
}
}
/**
* This method connects a network.
*
* @param callbackContext A Cordova callback context
* @param data JSON Array, with [0] being SSID to connect
* @return true if network connected, false if failed
*/
private boolean connectNetwork(CallbackContext callbackContext, JSONArray data) {
Log.d(TAG, "WifiWizard: connectNetwork entered.");
if(!validateData(data)) {
callbackContext.error("WifiWizard: connectNetwork invalid data");
Log.d(TAG, "WifiWizard: connectNetwork invalid data.");
return false;
}
String ssidToConnect = "";
try {
ssidToConnect = data.getString(0);
}
catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG, e.getMessage());
return false;
}
int networkIdToConnect = ssidToNetworkId(ssidToConnect);
if (networkIdToConnect > 0) {
wifiManager.enableNetwork(networkIdToConnect, true);
callbackContext.success("Network " + ssidToConnect + " connected!");
return true;
}
else {
callbackContext.error("Network " + ssidToConnect + " not found!");
Log.d(TAG, "WifiWizard: Network not found to connect.");
return false;
}
}
/**
* This method disconnects a network.
*
* @param callbackContext A Cordova callback context
* @param data JSON Array, with [0] being SSID to connect
* @return true if network disconnected, false if failed
*/
private boolean disconnectNetwork(CallbackContext callbackContext, JSONArray data) {
Log.d(TAG, "WifiWizard: disconnectNetwork entered.");
if(!validateData(data)) {
callbackContext.error("WifiWizard: disconnectNetwork invalid data");
Log.d(TAG, "WifiWizard: disconnectNetwork invalid data");
return false;
}
String ssidToDisconnect = "";
// TODO: Verify type of data here!
try {
ssidToDisconnect = data.getString(0);
}
catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG, e.getMessage());
return false;
}
int networkIdToDisconnect = ssidToNetworkId(ssidToDisconnect);
if (networkIdToDisconnect > 0) {
wifiManager.disableNetwork(networkIdToDisconnect);
callbackContext.success("Network " + ssidToDisconnect + " disconnected!");
return true;
}
else {
callbackContext.error("Network " + ssidToDisconnect + " not found!");
Log.d(TAG, "WifiWizard: Network not found to disconnect.");
return false;
}
}
/**
* This method uses the callbackContext.success method to send a JSONArray
* of the currently configured networks.
*
* @param callbackContext A Cordova callback context
* @param data JSON Array, with [0] being SSID to connect
* @return true if network disconnected, false if failed
*/
private boolean listNetworks(CallbackContext callbackContext) {
Log.d(TAG, "WifiWizard: listNetworks entered.");
List<WifiConfiguration> wifiList = wifiManager.getConfiguredNetworks();
JSONArray returnList = new JSONArray();
for (WifiConfiguration wifi : wifiList) {
returnList.put(wifi.SSID);
}
callbackContext.success(returnList);
return true;
}
/**
* This method takes a given String, searches the current list of configured WiFi
* networks, and returns the networkId for the netowrk if the SSID matches. If not,
* it returns -1.
*/
private int ssidToNetworkId(String ssid) {
List<WifiConfiguration> currentNetworks = wifiManager.getConfiguredNetworks();
int numberOfNetworks = currentNetworks.size();
int networkId = -1;
WifiConfiguration test;
// For each network in the list, compare the SSID with the given one
for (int i = 0; i < numberOfNetworks; i++) {
test = currentNetworks.get(i);
if (test.SSID.equals(ssid)) {
networkId = test.networkId;
}
}
return networkId;
}
private boolean validateData(JSONArray data) {
try {
if (data == null || data.get(0) == null) {
callbackContext.error("Data is null.");
return false;
}
return true;
}
catch (Exception e) {
callbackContext.error(e.getMessage());
}
return false;
}
} |
package org.jpos.ee;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.hibernate.*;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.spi.CollectionKey;
import org.hibernate.engine.spi.EntityKey;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.resource.transaction.spi.TransactionStatus;
import org.hibernate.stat.SessionStatistics;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.jpos.core.ConfigurationException;
import org.jpos.ee.support.ModuleUtils;
import org.jpos.util.Log;
import org.jpos.util.LogEvent;
import org.jpos.util.Logger;
import java.io.Closeable;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.*;
@SuppressWarnings({"UnusedDeclaration"})
public class DB implements Closeable
{
Session session;
Log log;
private static volatile SessionFactory sessionFactory = null;
private static String propFile;
/**
* Creates DB Object using default Hibernate instance
*/
public DB()
{
super();
}
/**
* Creates DB Object using default Hibernate instance
*
* @param log Log object
*/
public DB(Log log)
{
super();
setLog(log);
}
/**
* @return Hibernate's session factory
*/
public SessionFactory getSessionFactory()
{
if (sessionFactory == null)
{
synchronized (DB.class)
{
if (sessionFactory == null)
{
try
{
sessionFactory = newSessionFactory();
}
catch (IOException | ConfigurationException | DocumentException e)
{
throw new RuntimeException("Could not configure session factory", e);
}
}
}
}
return sessionFactory;
}
public static synchronized void invalidateSessionFactory()
{
sessionFactory = null;
}
private SessionFactory newSessionFactory() throws IOException, ConfigurationException, DocumentException {
String hibCfg = System.getProperty("HIBERNATE_CFG","/hibernate.cfg.xml");
if (hibCfg != null) {
Configuration configuration = new Configuration().configure(hibCfg);
configureProperties(configuration);
configureMappings(configuration);
return configuration.buildSessionFactory();
}
return getMetadata().buildSessionFactory();
}
private void configureProperties(Configuration cfg) throws IOException
{
String propFile = System.getProperty("DB_PROPERTIES", "cfg/db.properties");
Properties dbProps = loadProperties(propFile);
if (dbProps != null)
{
cfg.addProperties(dbProps);
}
}
private void configureMappings(Configuration cfg) throws ConfigurationException, IOException {
try {
List<String> moduleConfigs = ModuleUtils.getModuleEntries("META-INF/org/jpos/ee/modules/");
for (String moduleConfig : moduleConfigs) {
addMappings(cfg, moduleConfig);
}
} catch (DocumentException e) {
throw new ConfigurationException("Could not parse mappings document", e);
}
}
private void addMappings(Configuration cfg, String moduleConfig) throws ConfigurationException, DocumentException
{
Element module = readMappingElements(moduleConfig);
if (module != null)
{
for (Iterator l = module.elementIterator("mapping"); l.hasNext(); )
{
Element mapping = (Element) l.next();
parseMapping(cfg, mapping, moduleConfig);
}
}
}
private void parseMapping(Configuration cfg, Element mapping, String moduleName) throws ConfigurationException
{
final String resource = mapping.attributeValue("resource");
final String clazz = mapping.attributeValue("class");
if (resource != null)
{
cfg.addResource(resource);
}
else if (clazz != null)
{
try
{
cfg.addAnnotatedClass(ReflectHelper.classForName(clazz));
}
catch (ClassNotFoundException e)
{
throw new ConfigurationException("Class " + clazz + " specified in mapping for module " + moduleName + " cannot be found");
}
}
else
{
throw new ConfigurationException("<mapping> element in configuration specifies no known attributes at module " + moduleName);
}
}
private Element readMappingElements(String moduleConfig) throws DocumentException
{
SAXReader reader = new SAXReader();
final URL url = getClass().getClassLoader().getResource(moduleConfig);
assert url != null;
final Document doc = reader.read(url);
return doc.getRootElement().element("mappings");
}
private Properties loadProperties(String filename) throws IOException
{
Properties props = new Properties();
final String s = filename.replaceAll("/", "\\" + File.separator);
final File f = new File(s);
if (f.exists())
{
props.load(new FileReader(f));
}
return props;
}
/**
* Creates database schema
*
* @param outputFile optional output file (may be null)
* @param create true to actually issue the create statements
*/
public void createSchema(String outputFile, boolean create) throws HibernateException, DocumentException {
try
{
SchemaExport export = new SchemaExport(getMetadata());
if (outputFile != null)
{
export.setOutputFile(outputFile);
export.setDelimiter(";");
}
export.create(true, create);
}
catch (IOException | ConfigurationException e)
{
throw new HibernateException("Could not create schema", e);
}
}
/**
* open a new HibernateSession if none exists
*
* @return HibernateSession associated with this DB object
* @throws HibernateException
*/
public synchronized Session open() throws HibernateException
{
if (session == null)
{
session = getSessionFactory().openSession();
}
return session;
}
/**
* close hibernate session
*
* @throws HibernateException
*/
public synchronized void close() throws HibernateException
{
if (session != null)
{
session.close();
session = null;
}
}
/**
* @return session hibernate Session
*/
public Session session()
{
return session;
}
/**
* handy method used to avoid having to call db.session().save (xxx)
*
* @param obj to save
*/
public void save(Object obj) throws HibernateException
{
session.save(obj);
}
/**
* handy method used to avoid having to call db.session().saveOrUpdate (xxx)
*
* @param obj to save or update
*/
public void saveOrUpdate(Object obj) throws HibernateException
{
session.saveOrUpdate(obj);
}
public void delete(Object obj)
{
session.delete(obj);
}
/**
* @return newly created Transaction
* @throws HibernateException
*/
public synchronized Transaction beginTransaction() throws HibernateException
{
return session.beginTransaction();
}
public synchronized void commit()
{
if (session() != null)
{
Transaction tx = session().getTransaction();
if (tx != null && tx.getStatus().isOneOf(TransactionStatus.ACTIVE))
{
tx.commit();
}
}
}
public synchronized void rollback()
{
if (session() != null)
{
Transaction tx = session().getTransaction();
if (tx != null && tx.getStatus().canRollback())
{
tx.rollback();
}
}
}
/**
* @param timeout in seconds
* @return newly created Transaction
* @throws HibernateException
*/
public synchronized Transaction beginTransaction(int timeout) throws HibernateException
{
Transaction tx = session.beginTransaction();
if (timeout > 0)
{
tx.setTimeout(timeout);
}
return tx;
}
public synchronized Log getLog()
{
if (log == null)
{
log = Log.getLog("Q2", "DB"); // Q2 standard Logger
}
return log;
}
public synchronized void setLog(Log log)
{
this.log = log;
}
public static Object exec(DBAction action)
{
try (DB db = new DB())
{
db.open();
return action.exec(db);
}
}
public static Object execWithTransaction(DBAction action)
{
try (DB db = new DB())
{
db.open();
db.beginTransaction();
Object obj = action.exec(db);
db.commit();
return obj;
}
}
@SuppressWarnings("unchecked")
public static <T> T unwrap (T proxy) {
Hibernate.getClass(proxy);
Hibernate.initialize(proxy);
return (proxy instanceof HibernateProxy) ?
(T) ((HibernateProxy) proxy).getHibernateLazyInitializer().getImplementation() : proxy;
}
@SuppressWarnings({"unchecked"})
public void printStats()
{
if (getLog() != null)
{
LogEvent info = getLog().createInfo();
if (session != null)
{
info.addMessage("==== STATISTICS ====");
SessionStatistics statistics = session().getStatistics();
info.addMessage("==== ENTITIES ====");
Set<EntityKey> entityKeys = statistics.getEntityKeys();
for (EntityKey ek : entityKeys)
{
info.addMessage(String.format("[%s] %s", ek.getIdentifier(), ek.getEntityName()));
}
info.addMessage("==== COLLECTIONS ====");
Set<CollectionKey> collectionKeys = statistics.getCollectionKeys();
for (CollectionKey ck : collectionKeys)
{
info.addMessage(String.format("[%s] %s", ck.getKey(), ck.getRole()));
}
info.addMessage("=====================");
}
else
{
info.addMessage("Session is not open");
}
Logger.log(info);
}
}
private MetadataImplementor getMetadata() throws IOException, ConfigurationException, DocumentException {
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder();
String propFile = System.getProperty("DB_PROPERTIES", "cfg/db.properties");
Properties dbProps = loadProperties(propFile);
if (dbProps != null) {
for (Map.Entry entry : dbProps.entrySet()) {
ssrb.applySetting((String) entry.getKey(), entry.getValue());
}
}
MetadataSources mds = new MetadataSources(ssrb.build());
List<String> moduleConfigs = ModuleUtils.getModuleEntries("META-INF/org/jpos/ee/modules/");
for (String moduleConfig : moduleConfigs) {
addMappings(mds, moduleConfig);
}
return (MetadataImplementor) mds.buildMetadata();
}
private void addMappings(MetadataSources mds, String moduleConfig) throws ConfigurationException, DocumentException
{
Element module = readMappingElements(moduleConfig);
if (module != null)
{
for (Iterator l = module.elementIterator("mapping"); l.hasNext(); )
{
Element mapping = (Element) l.next();
parseMapping(mds, mapping, moduleConfig);
}
}
}
private void parseMapping (MetadataSources mds, Element mapping, String moduleName) throws ConfigurationException
{
final String resource = mapping.attributeValue("resource");
final String clazz = mapping.attributeValue("class");
if (resource != null)
mds.addResource(resource);
else if (clazz != null)
mds.addAnnotatedClassName(clazz);
else
throw new ConfigurationException("<mapping> element in configuration specifies no known attributes at module " + moduleName);
}
} |
import java.io.*;
import java.lang.*;
import lcm.lcm.*;
public class AffordanceFullStateCoder implements drake.util.LCMCoder
{
String m_otdf_type;
int m_uid;
int m_num_floating_joints;
int m_num_states;
java.util.TreeMap<String,Integer> m_state_map;
String m_robot_name;
java.util.TreeMap<String,Integer> m_floating_joint_map;
drc.robot_state_t msg;
public AffordanceFullStateCoder(String otdf_type,Integer uid, String[] state_names)
{
m_otdf_type = otdf_type;
if(uid != null) {
m_uid = uid;
} else {
m_uid = -1;
}
m_num_floating_joints = 6;
m_state_map = new java.util.TreeMap<String,Integer>();
m_num_states = 0;
if(state_names != null && state_names.length > 0) {
for (int i=0; i<state_names.length; i++) {
m_state_map.put(state_names[i],i);
m_num_states+=1;
}
}
}
public int dim()
{
return 2*(m_num_states+m_num_floating_joints);
}
public drake.util.CoordinateFrameData decode(byte[] data)
{
try {
drc.affordance_collection_t msg = new drc.affordance_collection_t(data);
return decode(msg);
} catch (IOException ex) {
System.out.println("Exception: " + ex);
}
return null;
}
public drake.util.CoordinateFrameData decode(drc.affordance_collection_t msg)
{
for (int i=0;i<msg.naffs;i++) {
if (msg.affs[i].otdf_type.equals(m_otdf_type) && (m_uid == -1 || m_uid == msg.affs[i].uid)) {
drake.util.CoordinateFrameData fdata = new drake.util.CoordinateFrameData();
fdata.val = new double[(m_num_floating_joints+m_num_states)];
fdata.t = (double)msg.utime / 1000000.0;
fdata.val[0] = msg.affs[i].origin_xyz[0];
fdata.val[1] = msg.affs[i].origin_xyz[1];
fdata.val[2] = msg.affs[i].origin_xyz[2];
fdata.val[3] = msg.affs[i].origin_rpy[0];
fdata.val[4] = msg.affs[i].origin_rpy[1];
fdata.val[5] = msg.affs[i].origin_rpy[2];
Integer k;
int index;
for (int j=0; j<m_num_states; j++) {
k = m_state_map.get(msg.affs[j].state_names[j]);
if (k!=null) {
index = k.intValue();
fdata.val[index+m_num_floating_joints] = msg.affs[j].states[j];
fdata.val[index+m_num_states+2*m_num_floating_joints] = 0.0;
}
}
return fdata;
}
}
return null;
}
public LCMEncodable encode(drake.util.CoordinateFrameData d)
{
// don't need to go in this direction
return null;
}
public String timestampName()
{
return "utime";
}
} |
// RMG - Reaction Mechanism Generator
// RMG Team (rmg_dev@mit.edu)
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// 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:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
package jing.rxnSys;
import java.io.*;
import jing.rxnSys.ReactionSystem;
import jing.rxn.*;
import jing.chem.*;
import java.util.*;
import jing.mathTool.UncertainDouble;
import jing.param.*;
import jing.chemUtil.*;
import jing.chemParser.*;
//## package jing::rxnSys
// jing\rxnSys\ReactionModelGenerator.java
//## class ReactionModelGenerator
public class ReactionModelGenerator {
protected LinkedList timeStep; //## attribute timeStep
protected ReactionModel reactionModel; //gmagoon 9/24/07
protected String workingDirectory; //## attribute workingDirectory
// protected ReactionSystem reactionSystem;
protected LinkedList reactionSystemList; //10/24/07 gmagoon: changed from reactionSystem to reactionSystemList
protected int paraInfor;//svp
protected boolean error;//svp
protected boolean sensitivity;//svp
protected LinkedList species;//svp
// protected InitialStatus initialStatus;//svp
protected LinkedList initialStatusList; //10/23/07 gmagoon: changed from initialStatus to initialStatusList
protected double rtol;//svp
protected static double atol;
protected PrimaryKineticLibrary primaryKineticLibrary;//9/24/07 gmagoon
protected ReactionLibrary ReactionLibrary;
protected ReactionModelEnlarger reactionModelEnlarger;//9/24/07 gmagoon
protected LinkedHashSet speciesSeed;//9/24/07 gmagoon;
protected ReactionGenerator reactionGenerator;//9/24/07 gmagoon
protected LibraryReactionGenerator lrg;// = new LibraryReactionGenerator();//9/24/07 gmagoon: moved from ReactionSystem.java;10/4/07 gmagoon: postponed initialization of lrg til later
//10/23/07 gmagoon: added additional variables
protected LinkedList tempList;
protected LinkedList presList;
protected LinkedList validList;//10/24/07 gmagoon: added
//10/25/07 gmagoon: moved variables from modelGeneration()
protected LinkedList initList = new LinkedList();
protected LinkedList beginList = new LinkedList();
protected LinkedList endList = new LinkedList();
protected LinkedList lastTList = new LinkedList();
protected LinkedList currentTList = new LinkedList();
protected LinkedList lastPList = new LinkedList();
protected LinkedList currentPList = new LinkedList();
protected LinkedList conditionChangedList = new LinkedList();
protected LinkedList reactionChangedList = new LinkedList();
protected int numConversions;//5/6/08 gmagoon: moved from initializeReactionSystem() to be an attribute so it can be accessed by modelGenerator()
protected String equationOfState;
// 24Jun2009 MRH: variable stores the first temperature encountered in the condition.txt file
// This temperature is used to select the "best" kinetics from the rxn library
protected static Temperature temp4BestKinetics;
// Added by AJ on July 12, 2010
protected static boolean useDiffusion;
protected SeedMechanism seedMechanism = null;
protected PrimaryThermoLibrary primaryThermoLibrary;
protected PrimaryTransportLibrary primaryTransportLibrary;
protected boolean readrestart = false;
protected boolean writerestart = false;
protected LinkedHashSet restartCoreSpcs = new LinkedHashSet();
protected LinkedHashSet restartEdgeSpcs = new LinkedHashSet();
protected LinkedHashSet restartCoreRxns = new LinkedHashSet();
protected LinkedHashSet restartEdgeRxns = new LinkedHashSet();
// Constructors
private HashSet specs = new HashSet();
//public static native long getCpuTime();
//static {System.loadLibrary("cpuTime");}
public static boolean rerunFame = false;
protected static double tolerance;//can be interpreted as "coreTol" (vs. edgeTol)
protected static double termTol;
protected static double edgeTol;
protected static int minSpeciesForPruning;
protected static int maxEdgeSpeciesAfterPruning;
public int limitingReactantID = 1;
//## operation ReactionModelGenerator()
public ReactionModelGenerator() {
workingDirectory = System.getProperty("RMG.workingDirectory");
}
//## operation initializeReactionSystem()
//10/24/07 gmagoon: changed name to initializeReactionSystems
public void initializeReactionSystems() throws InvalidSymbolException, IOException {
//#[ operation initializeReactionSystem()
try {
String initialConditionFile = System.getProperty("jing.rxnSys.ReactionModelGenerator.conditionFile");
if (initialConditionFile == null) {
System.out.println("undefined system property: jing.rxnSys.ReactionModelGenerator.conditionFile");
System.exit(0);
}
//double sandeep = getCpuTime();
//System.out.println(getCpuTime()/1e9/60);
FileReader in = new FileReader(initialConditionFile);
BufferedReader reader = new BufferedReader(in);
//TemperatureModel temperatureModel = null;//10/27/07 gmagoon: commented out
//PressureModel pressureModel = null;//10/27/07 gmagoon: commented out
// ReactionModelEnlarger reactionModelEnlarger = null;//10/9/07 gmagoon: commented out: unneeded now and causes scope problems
FinishController finishController = null;
//DynamicSimulator dynamicSimulator = null;//10/27/07 gmagoon: commented out and replaced with following line
LinkedList dynamicSimulatorList = new LinkedList();
setPrimaryKineticLibrary(null);//10/14/07 gmagoon: changed to use setPrimaryReactionLibrary
double [] conversionSet = new double[50];
String line = ChemParser.readMeaningfulLine(reader, true);
/*if (line.startsWith("Restart")){
StringTokenizer st = new StringTokenizer(line);
String token = st.nextToken();
token = st.nextToken();
if (token.equalsIgnoreCase("true")) {
//Runtime.getRuntime().exec("cp Restart/allSpecies.txt Restart/allSpecies1.txt");
//Runtime.getRuntime().exec("echo >> allSpecies.txt");
restart = true;
}
else if (token.equalsIgnoreCase("false")) {
Runtime.getRuntime().exec("rm Restart/allSpecies.txt");
restart = false;
}
else throw new InvalidSymbolException("UnIdentified Symbol "+token+" after Restart:");
}
else throw new InvalidSymbolException("Can't find Restart!");*/
//line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Database")){//svp
line = ChemParser.readMeaningfulLine(reader, true);
}
else throw new InvalidSymbolException("Can't find database!");
// if (line.startsWith("PrimaryThermoLibrary")){//svp
// line = ChemParser.readMeaningfulLine(reader);
// else throw new InvalidSymbolException("Can't find primary thermo library!");
/*
* Added by MRH on 15-Jun-2009
* Give user the option to change the maximum carbon, oxygen,
* and/or radical number for all species. These lines will be
* optional in the condition.txt file. Values are hard-
* coded into RMG (in ChemGraph.java), but any user-
* defined input will override these values.
*/
/*
* Moved from before InitialStatus to before PrimaryThermoLibary
* by MRH on 27-Oct-2009
* Overriding default values of maximum number of "X" per
* chemgraph should come before RMG attempts to make any
* chemgraph. The first instance RMG will attempt to make a
* chemgraph is in reading the primary thermo library.
*/
line = readMaxAtomTypes(line,reader);
// if (line.startsWith("MaxCarbonNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxCarbonNumberPerSpecies:"
// int maxCNum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxCarbonNumber(maxCNum);
// System.out.println("Note: Overriding RMG-defined MAX_CARBON_NUM with user-defined value: " + maxCNum);
// line = ChemParser.readMeaningfulLine(reader);
// if (line.startsWith("MaxOxygenNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxOxygenNumberPerSpecies:"
// int maxONum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxOxygenNumber(maxONum);
// System.out.println("Note: Overriding RMG-defined MAX_OXYGEN_NUM with user-defined value: " + maxONum);
// line = ChemParser.readMeaningfulLine(reader);
// if (line.startsWith("MaxRadicalNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxRadicalNumberPerSpecies:"
// int maxRadNum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxRadicalNumber(maxRadNum);
// System.out.println("Note: Overriding RMG-defined MAX_RADICAL_NUM with user-defined value: " + maxRadNum);
// line = ChemParser.readMeaningfulLine(reader);
// if (line.startsWith("MaxSulfurNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxSulfurNumberPerSpecies:"
// int maxSNum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxSulfurNumber(maxSNum);
// System.out.println("Note: Overriding RMG-defined MAX_SULFUR_NUM with user-defined value: " + maxSNum);
// line = ChemParser.readMeaningfulLine(reader);
// if (line.startsWith("MaxSiliconNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxSiliconNumberPerSpecies:"
// int maxSiNum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxSiliconNumber(maxSiNum);
// System.out.println("Note: Overriding RMG-defined MAX_SILICON_NUM with user-defined value: " + maxSiNum);
// line = ChemParser.readMeaningfulLine(reader);
// if (line.startsWith("MaxHeavyAtom")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxHeavyAtomPerSpecies:"
// int maxHANum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxHeavyAtomNumber(maxHANum);
// System.out.println("Note: Overriding RMG-defined MAX_HEAVYATOM_NUM with user-defined value: " + maxHANum);
// line = ChemParser.readMeaningfulLine(reader);
/*
* Read in the Primary Thermo Library
* MRH 7-Jul-2009
*/
if (line.startsWith("PrimaryThermoLibrary:")) {
/*
* MRH 27Feb2010:
* Changing the "read in Primary Thermo Library information" code
* into it's own method.
*
* Other modules (e.g. PopulateReactions) will be utilizing the exact code.
* Rather than copying and pasting code into other modules, just have
* everything call this new method: readAndMakePTL
*/
readAndMakePTL(reader);
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate PrimaryThermoLibrary field");
line = ChemParser.readMeaningfulLine(reader, true);
/*
* MRH 17-May-2010:
* Added primary transport library field
*/
if (line.toLowerCase().startsWith("primarytransportlibrary")) {
readAndMakePTransL(reader);
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate PrimaryTransportLibrary field.");
line = ChemParser.readMeaningfulLine(reader, true);
// Extra forbidden structures may be specified after the Primary Thermo Library
if (line.startsWith("ForbiddenStructures:")) {
readExtraForbiddenStructures(reader);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.toLowerCase().startsWith("readrestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "ReadRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes")) {
readrestart = true;
readRestartSpecies();
readRestartReactions();
} else readrestart = false;
line = ChemParser.readMeaningfulLine(reader, true);
} else throw new InvalidSymbolException("Cannot locate ReadRestart field");
if (line.toLowerCase().startsWith("writerestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "WriteRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes"))
writerestart = true;
else writerestart = false;
line = ChemParser.readMeaningfulLine(reader, true);
} else throw new InvalidSymbolException("Cannot locate WriteRestart field");
// read temperature model
//gmagoon 10/23/07: modified to handle multiple temperatures; note that this requires different formatting of units in condition.txt
if (line.startsWith("TemperatureModel:")) {
createTModel(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String modelType = st.nextToken();
// //String t = st.nextToken();
// String unit = st.nextToken();
// unit = ChemParser.removeBrace(unit);
// if (modelType.equals("Constant")) {
// tempList = new LinkedList();
// //read first temperature
// double t = Double.parseDouble(st.nextToken());
// tempList.add(new ConstantTM(t, unit));
// Temperature temp = new Temperature(t, unit);//10/29/07 gmagoon: added this line and next two lines to set Global.lowTemperature and Global.highTemperature
// Global.lowTemperature = (Temperature)temp.clone();
// Global.highTemperature = (Temperature)temp.clone();
// //read remaining temperatures
// while (st.hasMoreTokens()) {
// t = Double.parseDouble(st.nextToken());
// tempList.add(new ConstantTM(t, unit));
// temp = new Temperature(t,unit);//10/29/07 gmagoon: added this line and next two "if" statements to set Global.lowTemperature and Global.highTemperature
// if(temp.getK() < Global.lowTemperature.getK())
// Global.lowTemperature = (Temperature)temp.clone();
// if(temp.getK() > Global.highTemperature.getK())
// Global.highTemperature = (Temperature)temp.clone();
// // Global.temperature = new Temperature(t,unit);
//10/23/07 gmagoon: commenting out; further updates needed to get this to work
//else if (modelType.equals("Curved")) {
// String t = st.nextToken();
// // add reading curved temperature function here
// temperatureModel = new CurvedTM(new LinkedList());
// else {
// throw new InvalidSymbolException("condition.txt: Unknown TemperatureModel = " + modelType);
}
else throw new InvalidSymbolException("condition.txt: can't find TemperatureModel!");
// read in pressure model
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("PressureModel:")) {
createPModel(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String modelType = st.nextToken();
// //String p = st.nextToken();
// String unit = st.nextToken();
// unit = ChemParser.removeBrace(unit);
// if (modelType.equals("Constant")) {
// presList = new LinkedList();
// //read first pressure
// double p = Double.parseDouble(st.nextToken());
// Pressure pres = new Pressure(p, unit);
// Global.lowPressure = (Pressure)pres.clone();
// Global.highPressure = (Pressure)pres.clone();
// presList.add(new ConstantPM(p, unit));
// //read remaining temperatures
// while (st.hasMoreTokens()) {
// p = Double.parseDouble(st.nextToken());
// presList.add(new ConstantPM(p, unit));
// pres = new Pressure(p, unit);
// if(pres.getBar() < Global.lowPressure.getBar())
// Global.lowPressure = (Pressure)pres.clone();
// if(pres.getBar() > Global.lowPressure.getBar())
// Global.highPressure = (Pressure)pres.clone();
// //Global.pressure = new Pressure(p, unit);
// //10/23/07 gmagoon: commenting out; further updates needed to get this to work
// //else if (modelType.equals("Curved")) {
// // // add reading curved pressure function here
// // pressureModel = new CurvedPM(new LinkedList());
// else {
// throw new InvalidSymbolException("condition.txt: Unknown PressureModel = " + modelType);
}
else throw new InvalidSymbolException("condition.txt: can't find PressureModel!");
// after PressureModel comes an optional line EquationOfState
// if "EquationOfState: Liquid" is found then initial concentrations are assumed to be correct
// if it is ommited, then initial concentrations are normalised to ensure PV=NRT (ideal gas law)
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("EquationOfState")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String eosType = st.nextToken();
if (eosType.equals("Liquid")) {
equationOfState="Liquid";
System.out.println("Equation of state: Liquid. Relying on concentrations in input file to get density correct; not checking PV=NRT");
}
line = ChemParser.readMeaningfulLine(reader, true);
}
// Read in InChI generation
if (line.startsWith("InChIGeneration:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String inchiOnOff = st.nextToken().toLowerCase();
if (inchiOnOff.equals("on")) {
Species.useInChI = true;
} else if (inchiOnOff.equals("off")) {
Species.useInChI = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown InChIGeneration flag: " + inchiOnOff);
line = ChemParser.readMeaningfulLine(reader, true);
}
// Read in Solvation effects
if (line.startsWith("Solvation:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String solvationOnOff = st.nextToken().toLowerCase();
if (solvationOnOff.equals("on")) {
Species.useSolvation = true;
} else if (solvationOnOff.equals("off")) {
Species.useSolvation = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
line = ChemParser.readMeaningfulLine(reader, true);
}
// Read in Diffusion effects
// If 'Diffusion' is 'on' then override the settings made by the solvation flag and sets solvation 'on'
if (line.startsWith("Diffusion:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String diffusionOnOff = st.nextToken().toLowerCase();
if (diffusionOnOff.equals("on")) {
//Species.useSolvation = true;
setUseDiffusion(true);
} else if (diffusionOnOff.equals("off")) {
setUseDiffusion(false);
}
else throw new InvalidSymbolException("condition.txt: Unknown diffusion flag: " + diffusionOnOff);
line = ChemParser.readMeaningfulLine(reader,true);//read in reactants or thermo line
}
/* AJ 12JULY2010:
* Right now we do not want RMG to throw an exception if it cannot find a diffusion flag
*/
//else throw new InvalidSymbolException("condition.txt: Cannot find diffusion flag.");
//line = ChemParser.readMeaningfulLine(reader);//read in reactants or thermo line
// Read in optional QM thermo generation
if (line.startsWith("ThermoMethod:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String thermoMethod = st.nextToken().toLowerCase();
if (thermoMethod.equals("qm")) {
ChemGraph.useQM = true;
if(st.hasMoreTokens()){//override the default qmprogram ("both") if there are more; current options: "gaussian03" and "mopac" and of course, "both"
QMTP.qmprogram = st.nextToken().toLowerCase();
}
line=ChemParser.readMeaningfulLine(reader, true);
if(line.startsWith("QMForCyclicsOnly:")){
StringTokenizer st2 = new StringTokenizer(line);
String nameCyc = st2.nextToken();
String option = st2.nextToken().toLowerCase();
if (option.equals("on")) {
ChemGraph.useQMonCyclicsOnly = true;
}
}
else{
System.out.println("condition.txt: Can't find 'QMForCyclicsOnly:' field");
System.exit(0);
}
line=ChemParser.readMeaningfulLine(reader, true);
if(line.startsWith("MaxRadNumForQM:")){
StringTokenizer st3 = new StringTokenizer(line);
String nameRadNum = st3.nextToken();
Global.maxRadNumForQM = Integer.parseInt(st3.nextToken());
}
else{
System.out.println("condition.txt: Can't find 'MaxRadNumForQM:' field");
System.exit(0);
}
}//otherwise, the flag useQM will remain false by default and the traditional group additivity approach will be used
line = ChemParser.readMeaningfulLine(reader, true);//read in reactants
}
// // Read in Solvation effects
// if (line.startsWith("Solvation:")) {
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String solvationOnOff = st.nextToken().toLowerCase();
// if (solvationOnOff.equals("on")) {
// Species.useSolvation = true;
// } else if (solvationOnOff.equals("off")) {
// Species.useSolvation = false;
// else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
// else throw new InvalidSymbolException("condition.txt: Cannot find solvation flag.");
// read in reactants
//10/4/07 gmagoon: moved to initializeCoreEdgeReactionModel
//LinkedHashSet p_speciesSeed = new LinkedHashSet();//gmagoon 10/4/07: changed to p_speciesSeed
//setSpeciesSeed(p_speciesSeed);//gmagoon 10/4/07: added
LinkedHashMap speciesSet = new LinkedHashMap();
/*
* 7/Apr/2010: MRH
* Neither of these variables are utilized
*/
// LinkedHashMap speciesStatus = new LinkedHashMap();
// int speciesnum = 1;
//System.out.println(line);
if (line.startsWith("InitialStatus")) {
speciesSet = populateInitialStatusListWithReactiveSpecies(reader);
// line = ChemParser.readMeaningfulLine(reader);
// while (!line.equals("END")) {
// StringTokenizer st = new StringTokenizer(line);
// String index = st.nextToken();
// String name = null;
// if (!index.startsWith("(")) name = index;
// else name = st.nextToken();
// //if (restart) name += "("+speciesnum+")";
// // 24Jun2009: MRH
// // Check if the species name begins with a number.
// // If so, terminate the program and inform the user to choose
// // a different name. This is implemented so that the chem.inp
// // file generated will be valid when run in Chemkin
// try {
// int doesNameBeginWithNumber = Integer.parseInt(name.substring(0,1));
// System.out.println("\nA species name should not begin with a number." +
// " Please rename species: " + name + "\n");
// System.exit(0);
// } catch (NumberFormatException e) {
// // We're good
// speciesnum ++;
// if (!(st.hasMoreTokens())) throw new InvalidSymbolException("Couldn't find concentration of species: "+name);
// String conc = st.nextToken();
// double concentration = Double.parseDouble(conc);
// String unit = st.nextToken();
// unit = ChemParser.removeBrace(unit);
// if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
// concentration /= 1000;
// unit = "mol/cm3";
// else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
// concentration /= 1000000;
// unit = "mol/cm3";
// else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
// concentration /= 6.022e23;
// else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
// throw new InvalidUnitException("Species Concentration in condition.txt!");
// //GJB to allow "unreactive" species that only follow user-defined library reactions.
// // They will not react according to RMG reaction families
// boolean IsReactive = true;
// boolean IsConstantConcentration = false;
// while (st.hasMoreTokens()) {
// String reactive = st.nextToken().trim();
// if (reactive.equalsIgnoreCase("unreactive"))
// IsReactive = false;
// if (reactive.equalsIgnoreCase("constantconcentration"))
// IsConstantConcentration=true;
// Graph g = ChemParser.readChemGraph(reader);
// ChemGraph cg = null;
// try {
// cg = ChemGraph.make(g);
// catch (ForbiddenStructureException e) {
// System.out.println("Forbidden Structure:\n" + e.getMessage());
// throw new InvalidSymbolException("A species in the input file has a forbidden structure.");
// //System.out.println(name);
// Species species = Species.make(name,cg);
// species.setReactivity(IsReactive); // GJB
// species.setConstantConcentration(IsConstantConcentration);
// speciesSet.put(name, species);
// getSpeciesSeed().add(species);
// double flux = 0;
// int species_type = 1; // reacted species
// SpeciesStatus ss = new SpeciesStatus(species,species_type,concentration,flux);
// speciesStatus.put(species, ss);
// line = ChemParser.readMeaningfulLine(reader);
// ReactionTime initial = new ReactionTime(0,"S");
// //10/23/07 gmagoon: modified for handling multiple temperature, pressure conditions; note: concentration within speciesStatus (and list of conversion values) should not need to be modified for each T,P since this is done within isTPCconsistent in ReactionSystem
// initialStatusList = new LinkedList();
// for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
// TemperatureModel tm = (TemperatureModel)iter.next();
// for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
// PressureModel pm = (PressureModel)iter2.next();
// // LinkedHashMap speStat = (LinkedHashMap)speciesStatus.clone();//10/31/07 gmagoon: trying creating multiple instances of speciesStatus to address issues with concentration normalization (last normalization seems to apply to all)
// Set ks = speciesStatus.keySet();
// LinkedHashMap speStat = new LinkedHashMap();
// for (Iterator iter3 = ks.iterator(); iter3.hasNext();){//11/1/07 gmagoon: perform deep copy; (is there an easier or more elegant way to do this?)
// SpeciesStatus ssCopy = (SpeciesStatus)speciesStatus.get(iter3.next());
// speStat.put(ssCopy.getSpecies(),new SpeciesStatus(ssCopy.getSpecies(),ssCopy.getSpeciesType(),ssCopy.getConcentration(),ssCopy.getFlux()));
// initialStatusList.add(new InitialStatus(speStat,tm.getTemperature(initial),pm.getPressure(initial)));
}
else throw new InvalidSymbolException("condition.txt: can't find InitialStatus!");
// read in inert gas concentration
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("InertGas:")) {
populateInitialStatusListWithInertSpecies(reader);
// line = ChemParser.readMeaningfulLine(reader);
// while (!line.equals("END")) {
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken().trim();
// String conc = st.nextToken();
// double inertConc = Double.parseDouble(conc);
// String unit = st.nextToken();
// unit = ChemParser.removeBrace(unit);
// if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
// inertConc /= 1000;
// unit = "mol/cm3";
// else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
// inertConc /= 1000000;
// unit = "mol/cm3";
// else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
// inertConc /= 6.022e23;
// unit = "mol/cm3";
// else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
// throw new InvalidUnitException("Inert Gas Concentration not recognized: " + unit);
// //SystemSnapshot.putInertGas(name,inertConc);
// for(Iterator iter=initialStatusList.iterator();iter.hasNext(); ){//6/23/09 gmagoon: needed to change this to accommodate non-static inertConc
// ((InitialStatus)iter.next()).putInertGas(name,inertConc);
// line = ChemParser.readMeaningfulLine(reader);
}
else throw new InvalidSymbolException("condition.txt: can't find Inert gas concentration!");
// read in spectroscopic data estimator
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("SpectroscopicDataEstimator:")) {
setSpectroscopicDataMode(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String sdeType = st.nextToken().toLowerCase();
// if (sdeType.equals("frequencygroups") || sdeType.equals("default")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
// else if (sdeType.equals("therfit") || sdeType.equals("threefrequencymodel")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
// else if (sdeType.equals("off") || sdeType.equals("none")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.OFF;
// else throw new InvalidSymbolException("condition.txt: Unknown SpectroscopicDataEstimator = " + sdeType);
}
else throw new InvalidSymbolException("condition.txt: can't find SpectroscopicDataEstimator!");
// pressure dependence and related flags
line = ChemParser.readMeaningfulLine(reader, true);
if (line.toLowerCase().startsWith("pressuredependence:"))
line = setPressureDependenceOptions(line,reader);
else
throw new InvalidSymbolException("condition.txt: can't find PressureDependence flag!");
if (readrestart) if (PDepNetwork.generateNetworks) readPDepNetworks();
// include species (optional)
/*
*
* MRH 3-APR-2010:
* This if statement is no longer necessary and was causing an error
* when the PressureDependence field was set to "off"
*/
// if (!PDepRateConstant.getMode().name().equals("CHEBYSHEV") &&
// !PDepRateConstant.getMode().name().equals("PDEPARRHENIUS"))
// line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("IncludeSpecies")) {
StringTokenizer st = new StringTokenizer(line);
String iS = st.nextToken();
String fileName = st.nextToken();
HashSet includeSpecies = readIncludeSpecies(fileName);
((RateBasedRME)reactionModelEnlarger).addIncludeSpecies(includeSpecies);
line = ChemParser.readMeaningfulLine(reader, true);
}
// read in finish controller
if (line.startsWith("FinishController")) {
line = ChemParser.readMeaningfulLine(reader, true);
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String goal = st.nextToken();
String type = st.nextToken();
TerminationTester tt;
if (type.startsWith("Conversion")) {
LinkedList spc = new LinkedList();
while (st.hasMoreTokens()) {
String name = st.nextToken();
Species spe = (Species)speciesSet.get(name);
setLimitingReactantID(spe.getID());
if (spe == null) throw new InvalidConversionException("Unknown reactant: " + name);
String conv = st.nextToken();
double conversion;
try {
if (conv.endsWith("%")) {
conversion = Double.parseDouble(conv.substring(0,conv.length()-1))/100;
}
else {
conversion = Double.parseDouble(conv);
}
conversionSet[49] = conversion;
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
SpeciesConversion sc = new SpeciesConversion(spe, conversion);
spc.add(sc);
}
tt = new ConversionTT(spc);
}
else if (type.startsWith("ReactionTime")) {
double time = Double.parseDouble(st.nextToken());
String unit = ChemParser.removeBrace(st.nextToken());
ReactionTime rt = new ReactionTime(time, unit);
tt = new ReactionTimeTT(rt);
}
else {
throw new InvalidSymbolException("condition.txt: Unknown FinishController = " + type);
}
line = ChemParser.readMeaningfulLine(reader, true);
st = new StringTokenizer(line, ":");
String temp = st.nextToken();
String tol = st.nextToken();
try {
if (tol.endsWith("%")) {
tolerance = Double.parseDouble(tol.substring(0,tol.length()-1))/100;
}
else {
tolerance = Double.parseDouble(tol);
}
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
ValidityTester vt = null;
if (reactionModelEnlarger instanceof RateBasedRME) vt = new RateBasedVT(tolerance);
else if (reactionModelEnlarger instanceof RateBasedPDepRME) vt = new RateBasedPDepVT(tolerance);
else throw new InvalidReactionModelEnlargerException();
finishController = new FinishController(tt, vt);
}
else throw new InvalidSymbolException("condition.txt: can't find FinishController!");
// read in dynamic simulator
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("DynamicSimulator")) {
StringTokenizer st = new StringTokenizer(line,":");
String temp = st.nextToken();
String simulator = st.nextToken().trim();
//read in non-negative option if it exists: syntax would be something like this: "DynamicSimulator: DASSL: non-negative"
if (st.hasMoreTokens()){
if (st.nextToken().trim().toLowerCase().equals("non-negative")){
if(simulator.toLowerCase().equals("dassl")) JDAS.nonnegative = true;
else{
System.err.println("Non-negative option is currently only supported for DASSL. Switch to DASSL solver or remove non-negative option.");
System.exit(0);
}
}
}
numConversions = 0;//5/6/08 gmagoon: moved declaration from initializeReactionSystem() to be an attribute so it can be accessed by modelGenerator()
//int numConversions = 0;
boolean autoflag = false;//5/2/08 gmagoon: updating the following if/else-if block to consider input where we want to check model validity within the ODE solver at each time step; this will be indicated by the use of a string beginning with "AUTO" after the "TimeStep" or "Conversions" line
// read in time step
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("TimeStep:") && finishController.terminationTester instanceof ReactionTimeTT) {
st = new StringTokenizer(line);
temp = st.nextToken();
while (st.hasMoreTokens()) {
temp = st.nextToken();
if (temp.startsWith("AUTO")){//note potential opportunity for making case insensitive by using: temp.toUpperCase().startsWith("AUTO")
autoflag=true;
}
else if (!autoflag){//use "else if" to make sure additional numbers are not read in case numbers are erroneously used following AUTO; note that there could still be a problem if numbers come before "AUTO"
double tStep = Double.parseDouble(temp);
String unit = "sec";
setTimeStep(new ReactionTime(tStep, unit));
}
}
((ReactionTimeTT)finishController.terminationTester).setTimeSteps(timeStep);
}
else if (line.startsWith("Conversions:") && finishController.terminationTester instanceof ConversionTT){
st = new StringTokenizer(line);
temp = st.nextToken();
int i=0;
SpeciesConversion sc = (SpeciesConversion)((ConversionTT)finishController.terminationTester).speciesGoalConversionSet.get(0);
Species convSpecies = sc.species;
Iterator iter = ((InitialStatus)(initialStatusList.get(0))).getSpeciesStatus();//10/23/07 gmagoon: changed to use first element of initialStatusList, as subsequent operations should not be affected by which one is chosen
double initialConc = 0;
while (iter.hasNext()){
SpeciesStatus sps = (SpeciesStatus)iter.next();
if (sps.species.equals(convSpecies)) initialConc = sps.concentration;
}
while (st.hasMoreTokens()){
temp=st.nextToken();
if (temp.startsWith("AUTO")){
autoflag=true;
}
else if (!autoflag){
double conv = Double.parseDouble(temp);
conversionSet[i] = (1-conv) * initialConc;
i++;
}
}
conversionSet[i] = (1 - conversionSet[49])* initialConc;
numConversions = i+1;
}
else throw new InvalidSymbolException("condition.txt: can't find time step for dynamic simulator!");
if (temp.startsWith("AUTOPRUNE")){//for the AUTOPRUNE case, read in additional lines for termTol and edgeTol
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("TerminationTolerance:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
termTol = Double.parseDouble(st.nextToken());
}
else {
System.out.println("Cannot find TerminationTolerance in condition.txt");
System.exit(0);
}
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("PruningTolerance:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
edgeTol = Double.parseDouble(st.nextToken());
}
else {
System.out.println("Cannot find PruningTolerance in condition.txt");
System.exit(0);
}
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("MinSpeciesForPruning:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
minSpeciesForPruning = Integer.parseInt(st.nextToken());
}
else {
System.out.println("Cannot find MinSpeciesForPruning in condition.txt");
System.exit(0);
}
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("MaxEdgeSpeciesAfterPruning:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
maxEdgeSpeciesAfterPruning = Integer.parseInt(st.nextToken());
}
else {
System.out.println("Cannot find MaxEdgeSpeciesAfterPruning in condition.txt");
System.exit(0);
}
//print header for pruning log (based on restart format)
BufferedWriter bw = null;
try {
File f = new File("Pruning/edgeReactions.txt");
bw = new BufferedWriter(new FileWriter("Pruning/edgeReactions.txt", true));
String EaUnits = ArrheniusKinetics.getEaUnits();
bw.write("UnitsOfEa: " + EaUnits);
bw.newLine();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
else if (temp.startsWith("AUTO")){//in the non-autoprune case (i.e. original AUTO functionality), we set the new parameters to values that should reproduce original functionality
termTol = tolerance;
edgeTol = 0;
minSpeciesForPruning = 999999;//arbitrary high number (actually, the value here should not matter, since pruning should not be done)
maxEdgeSpeciesAfterPruning = 999999;
}
// read in atol
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Atol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
atol = Double.parseDouble(st.nextToken());
}
else throw new InvalidSymbolException("condition.txt: can't find Atol for dynamic simulator!");
// read in rtol
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Rtol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
String rel_tol = st.nextToken();
if (rel_tol.endsWith("%"))
rtol = Double.parseDouble(rel_tol.substring(0,rel_tol.length()-1));
else
rtol = Double.parseDouble(rel_tol);
}
else throw new InvalidSymbolException("condition.txt: can't find Rtol for dynamic simulator!");
if (simulator.equals("DASPK")) {
paraInfor = 0;//svp
// read in SA
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Error bars")) {//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0) {
paraInfor = 1;
error = true;
}
else if (sa.compareToIgnoreCase("off")==0) {
paraInfor = 0;
error = false;
}
else throw new InvalidSymbolException("condition.txt: can't find error on/off information!");
}
else throw new InvalidSymbolException("condition.txt: can't find SA information!");
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Display sensitivity coefficients")){//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0){
paraInfor = 1;
sensitivity = true;
}
else if (sa.compareToIgnoreCase("off")==0){
if (paraInfor != 1){
paraInfor = 0;
}
sensitivity = false;
}
else throw new InvalidSymbolException("condition.txt: can't find SA on/off information!");
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
//6/25/08 gmagoon: changed loop to use i index, and updated DASPK constructor to pass i (mirroring changes to DASSL
//6/25/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i,finishController.getValidityTester(), autoflag, termTol, tolerance));
}
}
species = new LinkedList();
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Display sensitivity information") ){
line = ChemParser.readMeaningfulLine(reader, true);
System.out.println(line);
while (!line.equals("END")){
st = new StringTokenizer(line);
String name = st.nextToken();
if (name.toUpperCase().equals("ALL")) ReactionSystem.printAllSens = true; //gmagoon 12/22/09: if the line contains the word "all", turn on the flag to print out sensitivity information for everything
species.add(name);
line = ChemParser.readMeaningfulLine(reader, true);
}
}
}
else if (simulator.equals("DASSL")) {
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
// for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
// dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)iter.next()));
//11/1/07 gmagoon: changed loop to use i index, and updated DASSL constructor to pass i
//5/5/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i, finishController.getValidityTester(), autoflag, termTol, tolerance));
}
}
else if (simulator.equals("Chemkin")) {
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("ReactorType")) {
st = new StringTokenizer(line, ":");
temp = st.nextToken();
String reactorType = st.nextToken().trim();
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
//dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)iter.next()));
dynamicSimulatorList.add(new Chemkin(rtol, atol, reactorType));//11/4/07 gmagoon: fixing apparent cut/paste error
}
}
}
else throw new InvalidSymbolException("condition.txt: Unknown DynamicSimulator = " + simulator);
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList; note: although conversionSet should actually be different for each T,P condition, it will be modified in isTPCconsistent within ReactionSystem
for (Iterator iter = dynamicSimulatorList.iterator(); iter.hasNext(); ) {
double [] cs = conversionSet.clone();//11/1/07 gmagoon: trying to make sure multiple instances of conversionSet are used
((DynamicSimulator)(iter.next())).addConversion(cs, numConversions);
}
}
else throw new InvalidSymbolException("condition.txt: can't find DynamicSimulator!");
// read in reaction model enlarger
/* Read in the Primary Kinetic Library
* The user can specify as many PKLs,
* including none, as they like.
*/
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("PrimaryKineticLibrary:")) {
readAndMakePKL(reader);
} else throw new InvalidSymbolException("condition.txt: can't find PrimaryKineticLibrary");
// Reaction Library
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("ReactionLibrary:")) {
readAndMakeReactionLibrary(reader);
} else throw new InvalidSymbolException("condition.txt: can't find ReactionLibrary");
/*
* Added by MRH 12-Jun-2009
*
* The SeedMechanism acts almost exactly as the old
* PrimaryKineticLibrary did. Whatever is in the SeedMechanism
* will be placed in the core at the beginning of the simulation.
* The user can specify as many seed mechanisms as they like, with
* the priority (in the case of duplicates) given to the first
* instance. There is no on/off flag.
*/
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("SeedMechanism:")) {
line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
String[] tempString = line.split("Name: ");
String name = tempString[tempString.length-1].trim();
line = ChemParser.readMeaningfulLine(reader, true);
tempString = line.split("Location: ");
String location = tempString[tempString.length-1].trim();
line = ChemParser.readMeaningfulLine(reader, true);
tempString = line.split("GenerateReactions: ");
String generateStr = tempString[tempString.length-1].trim();
boolean generate = true;
if (generateStr.equalsIgnoreCase("yes") ||
generateStr.equalsIgnoreCase("on") ||
generateStr.equalsIgnoreCase("true")){
generate = true;
System.out.println("Will generate cross-reactions between species in seed mechanism " + name);
} else if(generateStr.equalsIgnoreCase("no") ||
generateStr.equalsIgnoreCase("off") ||
generateStr.equalsIgnoreCase("false")) {
generate = false;
System.out.println("Will NOT initially generate cross-reactions between species in seed mechanism "+ name);
System.out.println("This may have unintended consequences");
}
else {
System.err.println("Input file invalid");
System.err.println("Please include a 'GenerateReactions: yes/no' line for seed mechanism "+name);
System.exit(0);
}
String path = System.getProperty("jing.rxn.ReactionLibrary.pathName");
path += "/" + location;
if (getSeedMechanism() == null)
setSeedMechanism(new SeedMechanism(name, path, generate, false));
else
getSeedMechanism().appendSeedMechanism(name, path, generate, false);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (getSeedMechanism() != null) System.out.println("Seed Mechanisms in use: " + getSeedMechanism().getName());
else setSeedMechanism(null);
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate SeedMechanism field");
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("ChemkinUnits")) {
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Verbose:")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken();
String OnOff = st.nextToken().toLowerCase();
if (OnOff.equals("off")) {
ArrheniusKinetics.setVerbose(false);
} else if (OnOff.equals("on")) {
ArrheniusKinetics.setVerbose(true);
}
line = ChemParser.readMeaningfulLine(reader, true);
}
/*
* MRH 3MAR2010:
* Adding user option regarding chemkin file
*
* New field: If user would like the empty SMILES string
* printed with each species in the thermochemistry portion
* of the generated chem.inp file
*/
if (line.toUpperCase().startsWith("SMILES")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // Should be "SMILES:"
String OnOff = st.nextToken().toLowerCase();
if (OnOff.equals("off")) {
Chemkin.setSMILES(false);
} else if (OnOff.equals("on")) {
Chemkin.setSMILES(true);
/*
* MRH 9MAR2010:
* MRH decided not to generate an InChI for every new species
* during an RMG simulation (especially since it is not used
* for anything). Instead, they will only be generated in the
* post-processing, if the user asked for InChIs.
*/
//Species.useInChI = true;
}
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.startsWith("A")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // Should be "A:"
String units = st.nextToken();
if (units.equals("moles") || units.equals("molecules"))
ArrheniusKinetics.setAUnits(units);
else {
System.err.println("Units for A were not recognized: " + units);
System.exit(0);
}
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate Chemkin units A field.");
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Ea")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // Should be "Ea:"
String units = st.nextToken();
if (units.equals("kcal/mol") || units.equals("cal/mol") ||
units.equals("kJ/mol") || units.equals("J/mol") || units.equals("Kelvins"))
ArrheniusKinetics.setEaUnits(units);
else {
System.err.println("Units for Ea were not recognized: " + units);
System.exit(0);
}
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate Chemkin units Ea field.");
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate ChemkinUnits field.");
in.close();
// LinkedList temperatureArray = new LinkedList();
// LinkedList pressureArray = new LinkedList();
// Iterator iterIS = initialStatusList.iterator();
// for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
// TemperatureModel tm = (TemperatureModel)iter.next();
// for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
// PressureModel pm = (PressureModel)iter2.next();
// InitialStatus is = (InitialStatus)iterIS.next();
// temperatureArray.add(tm.getTemperature(is.getTime()));
// pressureArray.add(pm.getPressure(is.getTime()));
// PDepNetwork.setTemperatureArray(temperatureArray);
// PDepNetwork.setPressureArray(pressureArray);
//10/4/07 gmagoon: moved to modelGeneration()
//ReactionGenerator p_reactionGenerator = new TemplateReactionGenerator();//10/4/07 gmagoon: changed to p_reactionGenerator from reactionGenerator
// setReactionGenerator(p_reactionGenerator);//10/4/07 gmagoon: added
/*
* MRH 12-Jun-2009
* A TemplateReactionGenerator now requires a Temperature be passed to it.
* This allows RMG to determine the "best" kinetic parameters to use
* in the mechanism generation. For now, I choose to pass the first
* temperature in the list of temperatures. RMG only outputs one mechanism,
* even for multiple temperature/pressure systems, so we can only have one
* set of kinetics.
*/
Temperature t = new Temperature(300,"K");
for (Iterator iter = tempList.iterator(); iter.hasNext();) {
TemperatureModel tm = (TemperatureModel)iter.next();
t = tm.getTemperature(new ReactionTime(0,"sec"));
setTemp4BestKinetics(t);
break;
}
setReactionGenerator(new TemplateReactionGenerator()); //11/4/07 gmagoon: moved from modelGeneration; mysteriously, moving this later moves "Father" lines up in output at runtime, immediately after condition file (as in original code); previously, these Father lines were just before "Can't read primary kinetic library files!"
lrg = new LibraryReactionGenerator(ReactionLibrary);//10/10/07 gmagoon: moved from modelGeneration (sequence lrg increases species id, and the different sequence was causing problems as main species id was 6 instead of 1); //10/31/07 gmagoon: restored this line from 10/10/07 backup: somehow it got lost along the way; 11/5/07 gmagoon: changed to use "lrg =" instead of setLibraryReactionGenerator
//10/24/07 gmagoon: updated to use multiple reactionSystem variables
reactionSystemList = new LinkedList();
// LinkedList temperatureArray = new LinkedList();//10/30/07 gmagoon: added temperatureArray variable for passing to PDepNetwork; 11/6/07 gmagoon: moved before initialization of lrg;
Iterator iter3 = initialStatusList.iterator();
Iterator iter4 = dynamicSimulatorList.iterator();
int i = 0;//10/30/07 gmagoon: added
for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
TemperatureModel tm = (TemperatureModel)iter.next();
//InitialStatus is = (InitialStatus)iter3.next();//10/31/07 gmagoon: fixing apparent bug by moving these inside inner "for loop"
//DynamicSimulator ds = (DynamicSimulator)iter4.next();
for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
PressureModel pm = (PressureModel)iter2.next();
InitialStatus is = (InitialStatus)iter3.next();//10/31/07 gmagoon: moved from outer "for loop""
DynamicSimulator ds = (DynamicSimulator)iter4.next();
// temperatureArray.add(tm.getTemperature(is.getTime()));//10/30/07 gmagoon: added; //10/31/07 added .getTemperature(is.getTime()); 11/6/07 gmagoon: moved before initialization of lrg;
//11/1/07 gmagoon: trying to make a deep copy of terminationTester when it is instance of ConversionTT
// TerminationTester termTestCopy;
// if (finishController.getTerminationTester() instanceof ConversionTT){
// ConversionTT termTest = (ConversionTT)finishController.getTerminationTester();
// LinkedList spcCopy = (LinkedList)(termTest.getSpeciesGoalConversionSetList().clone());
// termTestCopy = new ConversionTT(spcCopy);
// else{
// termTestCopy = finishController.getTerminationTester();
FinishController fc = new FinishController(finishController.getTerminationTester(), finishController.getValidityTester());//10/31/07 gmagoon: changed to create new finishController instance in each case (apparently, the finish controller becomes associated with reactionSystem in setFinishController within ReactionSystem); alteratively, could use clone, but might need to change FinishController to be "cloneable"
// FinishController fc = new FinishController(termTestCopy, finishController.getValidityTester());
reactionSystemList.add(new ReactionSystem(tm, pm, reactionModelEnlarger, fc, ds, getPrimaryKineticLibrary(), getReactionGenerator(), getSpeciesSeed(), is, getReactionModel(),lrg, i, equationOfState));
i++;//10/30/07 gmagoon: added
System.out.println("Created reaction system "+i+"\n");
}
}
// PDepNetwork.setTemperatureArray(temperatureArray);//10/30/07 gmagoon: passing temperatureArray to PDepNetwork; 11/6/07 gmagoon: moved before initialization of lrg;
}
catch (IOException e) {
System.err.println("Error reading reaction system initialization file.");
throw new IOException("Input file error: " + e.getMessage());
}
}
public void setReactionModel(ReactionModel p_ReactionModel) {
reactionModel = p_ReactionModel;
}
public void modelGeneration() {
//long begin_t = System.currentTimeMillis();
try{
ChemGraph.readForbiddenStructure();
setSpeciesSeed(new LinkedHashSet());//10/4/07 gmagoon moved from initializeCoreEdgeReactionModel
// setReactionGenerator(new TemplateReactionGenerator());//10/4/07 gmagoon: moved inside initializeReactionSystem; 11/3-4/07 gmagoon: probably reverted on or before 10/10/07 (although I have not investigated this change in detail); //11/4/07 gmagoon: moved inside initializeReactionSystems
// setLibraryReactionGenerator(new LibraryReactionGenerator());//10/10/07 gmagoon: moved after initializeReactionSystem
// initializeCoreEdgeReactionModel();//10/4/07 gmagoon moved from below to run initializeCoreEdgeReactionModel before initializeReactionSystem; 11/3-4/07 gmagoon: probably reverted on or before 10/10/07
initializeReactionSystems();
}
catch (IOException e) {
System.err.println(e.getMessage());
System.exit(0);
}
catch (InvalidSymbolException e) {
System.err.println(e.getMessage());
System.exit(0);
}
//10/31/07 gmagoon: initialize validList (to false) before initializeCoreEdgeReactionModel is called
validList = new LinkedList();
for (Integer i = 0; i<reactionSystemList.size();i++) {
validList.add(false);
}
initializeCoreEdgeReactionModel();//10/4/07 gmagoon: moved before initializeReactionSystem; 11/3-4/07 gmagoon: probably reverted on or before 10/10/07
//10/24/07 gmagoon: changed to use reactionSystemList
// LinkedList initList = new LinkedList();//10/25/07 gmagoon: moved these variables to apply to entire class
// LinkedList beginList = new LinkedList();
// LinkedList endList = new LinkedList();
// LinkedList lastTList = new LinkedList();
// LinkedList currentTList = new LinkedList();
// LinkedList lastPList = new LinkedList();
// LinkedList currentPList = new LinkedList();
// LinkedList conditionChangedList = new LinkedList();
// LinkedList reactionChangedList = new LinkedList();
//5/6/08 gmagoon: determine whether there are intermediate time/conversion steps, type of termination tester is based on characteristics of 1st reaction system (it is assumed that they are all identical in terms of type of termination tester)
boolean intermediateSteps = true;
ReactionSystem rs0 = (ReactionSystem)reactionSystemList.get(0);
if (rs0.finishController.terminationTester instanceof ReactionTimeTT){
if (timeStep == null){
intermediateSteps = false;
}
}
else if (numConversions==1){ //if we get to this block, we presumably have a conversion terminationTester; this required moving numConversions to be attribute...alternative to using numConversions is to access one of the DynamicSimulators and determine conversion length
intermediateSteps=false;
}
//10/24/07 gmagoon: note: each element of for loop could be done in parallel if desired; some modifications would be needed
for (Iterator iter = reactionSystemList.iterator(); iter.hasNext(); ) {
ReactionSystem rs = (ReactionSystem)iter.next();
if ((reactionModelEnlarger instanceof RateBasedPDepRME)) {//1/2/09 gmagoon and rwest: only call initializePDepNetwork for P-dep cases
if (!readrestart) rs.initializePDepNetwork();
}
ReactionTime init = rs.getInitialReactionTime();
initList.add(init);
ReactionTime begin = init;
beginList.add(begin);
ReactionTime end;
if (rs.finishController.terminationTester instanceof ReactionTimeTT){
//5/5/08 gmagoon: added below if statement to avoid null pointer exception in cases where there are no intermediate time steps specified
if (!(timeStep==null)){
end = (ReactionTime)timeStep.get(0);
}
else{
end= ((ReactionTimeTT)rs.finishController.terminationTester).finalTime;
}
//end = (ReactionTime)timeStep.get(0);
endList.add(end);
}
else{
end = new ReactionTime(1e6,"sec");
endList.add(end);
}
// int iterationNumber = 1;
lastTList.add(rs.getTemperature(init));
currentTList.add(rs.getTemperature(init));
lastPList.add(rs.getPressure(init));
currentPList.add(rs.getPressure(init));
conditionChangedList.add(false);
reactionChangedList.add(false);//10/31/07 gmagoon: added
//Chemkin.writeChemkinInputFile(reactionSystem.getReactionModel(),reactionSystem.getPresentStatus());
}
int iterationNumber = 1;
LinkedList terminatedList = new LinkedList();//10/24/07 gmagoon: this may not be necessary, as if one reactionSystem is terminated, I think all should be terminated
//validList = new LinkedList();//10/31/07 gmagoon: moved before initializeCoreEdgeReactionModel
//10/24/07 gmagoon: initialize allTerminated and allValid to true; these variables keep track of whether all the reactionSystem variables satisfy termination and validity, respectively
boolean allTerminated = true;
boolean allValid = true;
// IF RESTART IS TURNED ON
// Update the systemSnapshot for each ReactionSystem in the reactionSystemList
if (readrestart) {
for (Integer i=0; i<reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
InitialStatus is = rs.getInitialStatus();
putRestartSpeciesInInitialStatus(is,i);
rs.appendUnreactedSpeciesStatus((InitialStatus)initialStatusList.get(i), rs.getPresentTemperature());
}
}
//10/24/07 gmagoon: note: each element of for loop could be done in parallel if desired; some modifications would be needed
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
ReactionTime begin = (ReactionTime)beginList.get(i);
ReactionTime end = (ReactionTime)endList.get(i);
endList.set(i,rs.solveReactionSystem(begin, end, true, true, true, iterationNumber-1));
Chemkin.writeChemkinInputFile(rs);
boolean terminated = rs.isReactionTerminated();
terminatedList.add(terminated);
if(!terminated)
allTerminated = false;
boolean valid = rs.isModelValid();
//validList.add(valid);
validList.set(i, valid);//10/31/07 gmagoon: validList initialization moved before initializeCoreEdgeReactionModel
if(!valid)
allValid = false;
reactionChangedList.set(i,false);
}
//9/1/09 gmagoon: if we are using QM, output a file with the CHEMKIN name, the RMG name, the (modified) InChI, and the (modified) InChIKey
if (ChemGraph.useQM){
writeInChIs(getReactionModel());
}
writeDictionary(getReactionModel());
//System.exit(0);
printModelSize();
StringBuilder print_info = Global.diagnosticInfo;
print_info.append("\nMolecule \t Flux\t\tTime\t \t\t \t Core \t \t Edge \t \t memory\n");
print_info.append(" \t moleular \t characteristic \t findspecies \t moveUnreactedToReacted \t enlarger \t restart1 \t totalEnlarger \t resetSystem \t readSolverFile\t writeSolverFile \t justSolver \t SolverIterations \t solverSpeciesStatus \t Totalsolver \t gc \t restart+diagnosis \t chemkin thermo \t chemkin reactions \t validitytester \t Species \t Reactions\t Species\t Reactions \t memory used \t allSpecies \t TotalTime \t findRateConstant\t identifyReactedSites \t reactChemGraph \t makespecies\t CheckReverseReaction \t makeTemplateReaction \t getReactionfromStruc \t genReverseFromReac");
print_info.append("\t\t\t\t\t\t\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size()+ "\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedReactionSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSetIncludingReverseSize() + "\t"+Global.makeSpecies+"\n");
double solverMin = 0;
double vTester = 0;
/*if (!restart){
writeRestartFile();
writeCoreReactions();
writeAllReactions();
}*/
//System.exit(0);
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
System.out.println("Species dictionary size: "+dictionary.size());
double tAtInitialization = Global.tAtInitialization;
//10/24/07: changed to use allTerminated and allValid
// step 2: iteratively grow reaction system
while (!allTerminated || !allValid) {
while (!allValid) {
//writeCoreSpecies();
double pt = System.currentTimeMillis();
// Grab all species from primary kinetics / reaction libraries
// WE CANNOT PRUNE THESE SPECIES
HashMap unprunableSpecies = new HashMap();
if (getPrimaryKineticLibrary() != null) {
unprunableSpecies.putAll(getPrimaryKineticLibrary().speciesSet);
}
if (getReactionLibrary() != null) {
unprunableSpecies.putAll(getReactionLibrary().getDictionary());
}
//prune the reaction model (this will only do something in the AUTO case)
pruneReactionModel(unprunableSpecies);
garbageCollect();
//System.out.println("After pruning:");
//printModelSize();
// ENLARGE THE MODEL!!! (this is where the good stuff happens)
enlargeReactionModel();
double totalEnlarger = (System.currentTimeMillis() - pt)/1000/60;
//PDepNetwork.completeNetwork(reactionSystem.reactionModel.getSpeciesSet());
//10/24/07 gmagoon: changed to use reactionSystemList
if ((reactionModelEnlarger instanceof RateBasedPDepRME)) {//1/2/09 gmagoon and rwest: only call initializePDepNetwork for P-dep cases
for (Iterator iter = reactionSystemList.iterator(); iter.hasNext(); ) {
ReactionSystem rs = (ReactionSystem)iter.next();
rs.initializePDepNetwork();
}
//reactionSystem.initializePDepNetwork();
}
pt = System.currentTimeMillis();
//10/24/07 gmagoon: changed to use reactionSystemList
for (Iterator iter = reactionSystemList.iterator(); iter.hasNext(); ) {
ReactionSystem rs = (ReactionSystem)iter.next();
rs.resetSystemSnapshot();
}
//reactionSystem.resetSystemSnapshot();
double resetSystem = (System.currentTimeMillis() - pt)/1000/60;
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
//reactionChanged = true;
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
reactionChangedList.set(i,true);
// begin = init;
beginList.set(i, (ReactionTime)initList.get(i));
if (rs.finishController.terminationTester instanceof ReactionTimeTT){
//5/5/08 gmagoon: added below if statement to avoid null pointer exception in cases where there are no intermediate time steps specified
if (!(timeStep==null)){
endList.set(i,(ReactionTime)timeStep.get(0));
}
else{
endList.set(i, ((ReactionTimeTT)rs.finishController.terminationTester).finalTime);
}
// endList.set(i, (ReactionTime)timeStep.get(0));
//end = (ReactionTime)timeStep.get(0);
}
else
endList.set(i, new ReactionTime(1e6,"sec"));
//end = new ReactionTime(1e6,"sec");
// iterationNumber = 1;//10/24/07 gmagoon: moved outside of loop
currentTList.set(i,rs.getTemperature((ReactionTime)beginList.get(i)));
currentPList.set(i,rs.getPressure((ReactionTime)beginList.get(i)));
conditionChangedList.set(i,!(((Temperature)currentTList.get(i)).equals((Temperature)lastTList.get(i))) || !(((Pressure)currentPList.get(i)).equals((Pressure)lastPList.get(i))));
//currentT = reactionSystem.getTemperature(begin);
//currentP = reactionSystem.getPressure(begin);
//conditionChanged = (!currentT.equals(lastT) || !currentP.equals(lastP));
}
iterationNumber = 1;
double startTime = System.currentTimeMillis();
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean reactionChanged = (Boolean)reactionChangedList.get(i);
boolean conditionChanged = (Boolean)conditionChangedList.get(i);
ReactionTime begin = (ReactionTime)beginList.get(i);
ReactionTime end = (ReactionTime)endList.get(i);
endList.set(i,rs.solveReactionSystem(begin, end, false, reactionChanged, conditionChanged, iterationNumber-1));
//end = reactionSystem.solveReactionSystem(begin, end, false, reactionChanged, conditionChanged, iterationNumber-1);
}
solverMin = solverMin + (System.currentTimeMillis()-startTime)/1000/60;
startTime = System.currentTimeMillis();
for (Integer i = 0; i<reactionSystemList.size();i++) {
// we over-write the chemkin file each time, so only the LAST reaction system is saved
// i.e. if you are using RATE for pdep, only the LAST pressure is used.
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
Chemkin.writeChemkinInputFile(rs);
}
//9/1/09 gmagoon: if we are using QM, output a file with the CHEMKIN name, the RMG name, the (modified) InChI, and the (modified) InChIKey
if (ChemGraph.useQM){
writeInChIs(getReactionModel());
}
writeDictionary(getReactionModel());
double chemkint = (System.currentTimeMillis()-startTime)/1000/60;
if (writerestart) {
/*
* Rename current restart files:
* In the event RMG fails while writing the restart files,
* user won't lose any information
*/
String[] restartFiles = {"Restart/coreReactions.txt", "Restart/coreSpecies.txt",
"Restart/edgeReactions.txt", "Restart/edgeSpecies.txt",
"Restart/pdepnetworks.txt", "Restart/pdepreactions.txt"};
writeBackupRestartFiles(restartFiles);
writeCoreSpecies();
writeCoreReactions();
writeEdgeSpecies();
writeEdgeReactions();
if (PDepNetwork.generateNetworks == true) writePDepNetworks();
/*
* Remove backup restart files from Restart folder
*/
removeBackupRestartFiles(restartFiles);
}
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
System.out.println("For reaction system: "+(i+1)+" out of "+reactionSystemList.size());
System.out.println("At this time: " + ((ReactionTime)endList.get(i)).toString());
Species spe = SpeciesDictionary.getSpeciesFromID(getLimitingReactantID());
double conv = rs.getPresentConversion(spe);
System.out.print("Conversion of " + spe.getName() + " is:");
System.out.println(conv);
}
System.out.println("Running Time is: " + String.valueOf((System.currentTimeMillis()-tAtInitialization)/1000/60) + " minutes.");
printModelSize();
startTime = System.currentTimeMillis();
double mU = memoryUsed();
double gc = (System.currentTimeMillis()-startTime)/1000/60;
startTime = System.currentTimeMillis();
//10/24/07 gmagoon: updating to use reactionSystemList
allValid = true;
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean valid = rs.isModelValid();
if(!valid)
allValid = false;
validList.set(i,valid);
//valid = reactionSystem.isModelValid();
}
vTester = vTester + (System.currentTimeMillis()-startTime)/1000/60;
startTime = System.currentTimeMillis();
writeDiagnosticInfo();
writeEnlargerInfo();
double restart2 = (System.currentTimeMillis()-startTime)/1000/60;
int allSpecies, allReactions;
allSpecies = SpeciesDictionary.getInstance().size();
print_info.append(totalEnlarger + "\t" + resetSystem + "\t" + Global.readSolverFile + "\t" + Global.writeSolverFile + "\t" + Global.solvertime + "\t" + Global.solverIterations + "\t" + Global.speciesStatusGenerator + "\t" + solverMin + "\t" + gc + "\t" + restart2 + "\t" + Global.chemkinThermo + '\t' + Global.chemkinReaction + "\t" + vTester + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size()+ "\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedReactionSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSetIncludingReverseSize() + "\t" + mU + "\t" + allSpecies + "\t" + (System.currentTimeMillis()-Global.tAtInitialization)/1000/60 + "\t"+ String.valueOf(Global.RT_findRateConstant)+"\t"+Global.RT_identifyReactedSites+"\t"+Global.RT_reactChemGraph+"\t"+Global.makeSpecies+"\t"+Global.checkReactionReverse+"\t"+Global.makeTR+ "\t" + Global.getReacFromStruc + "\t" + Global.generateReverse+"\n");
}
//5/6/08 gmagoon: in order to handle cases where no intermediate time/conversion steps are used, only evaluate the next block of code when there are intermediate time/conversion steps
double startTime = System.currentTimeMillis();
if(intermediateSteps){
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
reactionChangedList.set(i, false);
//reactionChanged = false;
Temperature currentT = (Temperature)currentTList.get(i);
Pressure currentP = (Pressure)currentPList.get(i);
lastTList.set(i,(Temperature)currentT.clone()) ;
lastPList.set(i,(Pressure)currentP.clone());
//lastT = (Temperature)currentT.clone();
//lastP = (Pressure)currentP.clone();
currentTList.set(i,rs.getTemperature((ReactionTime)beginList.get(i)));
currentPList.set(i,rs.getPressure((ReactionTime)beginList.get(i)));
conditionChangedList.set(i,!(((Temperature)currentTList.get(i)).equals((Temperature)lastTList.get(i))) || !(((Pressure)currentPList.get(i)).equals((Pressure)lastPList.get(i))));
//currentP = reactionSystem.getPressure(begin);
//conditionChanged = (!currentT.equals(lastT) || !currentP.equals(lastP));
beginList.set(i,((SystemSnapshot)(rs.getSystemSnapshotEnd().next())).time);
// begin=((SystemSnapshot)(reactionSystem.getSystemSnapshotEnd().next())).time;
if (rs.finishController.terminationTester instanceof ReactionTimeTT){
if (iterationNumber < timeStep.size()){
endList.set(i,(ReactionTime)timeStep.get(iterationNumber));
//end = (ReactionTime)timeStep.get(iterationNumber);
}
else
endList.set(i, ((ReactionTimeTT)rs.finishController.terminationTester).finalTime);
//end = ((ReactionTimeTT)reactionSystem.finishController.terminationTester).finalTime;
}
else
endList.set(i,new ReactionTime(1e6,"sec"));
//end = new ReactionTime(1e6,"sec");
}
iterationNumber++;
startTime = System.currentTimeMillis();//5/6/08 gmagoon: moved declaration outside of if statement so it can be accessed in subsequent vTester line; previous steps are probably so fast that I could eliminate this line without much effect on normal operation with intermediate steps
//double startTime = System.currentTimeMillis();
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean reactionChanged = (Boolean)reactionChangedList.get(i);
boolean conditionChanged = (Boolean)conditionChangedList.get(i);
ReactionTime begin = (ReactionTime)beginList.get(i);
ReactionTime end = (ReactionTime)endList.get(i);
endList.set(i,rs.solveReactionSystem(begin, end, false, reactionChanged, false, iterationNumber-1));
// end = reactionSystem.solveReactionSystem(begin, end, false, reactionChanged, false, iterationNumber-1);
}
solverMin = solverMin + (System.currentTimeMillis()-startTime)/1000/60;
startTime = System.currentTimeMillis();
//5/6/08 gmagoon: changed to separate validity and termination testing, and termination testing is done last...termination testing should be done even if there are no intermediate conversions; however, validity is guaranteed if there are no intermediate conversions based on previous conditional if statement
allValid = true;
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean valid = rs.isModelValid();
validList.set(i,valid);
if(!valid)
allValid = false;
}
}//5/6/08 gmagoon: end of block for intermediateSteps
allTerminated = true;
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean terminated = rs.isReactionTerminated();
terminatedList.set(i,terminated);
if(!terminated){
allTerminated = false;
System.out.println("Reaction System "+(i+1)+" has not reached its termination criterion");
if (rs.isModelValid()&& runKillableToPreventInfiniteLoop(intermediateSteps, iterationNumber)) {
System.out.println("although it seems to be valid (complete), so it was not interrupted for being invalid.");
System.out.println("This probably means there was an error with the ODE solver, and we risk entering an endless loop.");
System.out.println("Stopping.");
throw new Error();
}
}
}
// //10/24/07 gmagoon: changed to use reactionSystemList
// allTerminated = true;
// allValid = true;
// for (Integer i = 0; i<reactionSystemList.size();i++) {
// ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
// boolean terminated = rs.isReactionTerminated();
// terminatedList.set(i,terminated);
// if(!terminated)
// allTerminated = false;
// boolean valid = rs.isModelValid();
// validList.set(i,valid);
// if(!valid)
// allValid = false;
// //terminated = reactionSystem.isReactionTerminated();
// //valid = reactionSystem.isModelValid();
//10/24/07 gmagoon: changed to use reactionSystemList, allValid
if (allValid) {
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
System.out.println("For reaction system: "+(i+1)+" out of "+reactionSystemList.size());
System.out.println("At this reaction time: " + ((ReactionTime)endList.get(i)).toString());
Species spe = SpeciesDictionary.getSpeciesFromID(getLimitingReactantID());
double conv = rs.getPresentConversion(spe);
System.out.print("Conversion of " + spe.getName() + " is:");
System.out.println(conv);
}
//System.out.println("At this time: " + end.toString());
//Species spe = SpeciesDictionary.getSpeciesFromID(1);
//double conv = reactionSystem.getPresentConversion(spe);
//System.out.print("current conversion = ");
//System.out.println(conv);
Runtime runTime = Runtime.getRuntime();
System.out.print("Memory used: ");
System.out.println(runTime.totalMemory());
System.out.print("Free memory: ");
System.out.println(runTime.freeMemory());
//runTime.gc();
/* if we're not calling runTime.gc() then don't bother printing this:
System.out.println("After garbage collection:");
System.out.print("Memory used: ");
System.out.println(runTime.totalMemory());
System.out.print("Free memory: ");
System.out.println(runTime.freeMemory());
*/
printModelSize();
}
vTester = vTester + (System.currentTimeMillis()-startTime)/1000/60;//5/6/08 gmagoon: for case where intermediateSteps = false, this will use startTime declared just before intermediateSteps loop, and will only include termination testing, but no validity testing
}
//System.out.println("Performing model reduction");
if (paraInfor != 0){
System.out.println("Model Generation performed. Now generating sensitivity data.");
//10/24/07 gmagoon: updated to use reactionSystemList
LinkedList dynamicSimulator2List = new LinkedList();
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
//6/25/08 gmagoon: updated to pass index i
//6/25/08 gmagoon: updated to pass (dummy) finishController and autoflag (set to false here);
dynamicSimulator2List.add(new JDASPK(rtol, atol, paraInfor, (InitialStatus)initialStatusList.get(i),i));
//DynamicSimulator dynamicSimulator2 = new JDASPK(rtol, atol, paraInfor, initialStatus);
((DynamicSimulator)dynamicSimulator2List.get(i)).addConversion(((JDASPK)rs.dynamicSimulator).conversionSet, ((JDASPK)rs.dynamicSimulator).conversionSet.length);
//dynamicSimulator2.addConversion(((JDASPK)reactionSystem.dynamicSimulator).conversionSet, ((JDASPK)reactionSystem.dynamicSimulator).conversionSet.length);
rs.setDynamicSimulator((DynamicSimulator)dynamicSimulator2List.get(i));
//reactionSystem.setDynamicSimulator(dynamicSimulator2);
int numSteps = rs.systemSnapshot.size() -1;
rs.resetSystemSnapshot();
beginList.set(i, (ReactionTime)initList.get(i));
//begin = init;
if (rs.finishController.terminationTester instanceof ReactionTimeTT){
endList.set(i,((ReactionTimeTT)rs.finishController.terminationTester).finalTime);
//end = ((ReactionTimeTT)reactionSystem.finishController.terminationTester).finalTime;
}
else{
ReactionTime end = (ReactionTime)endList.get(i);
endList.set(i, end.add(end));
//end = end.add(end);
}
terminatedList.set(i, false);
//terminated = false;
ReactionTime begin = (ReactionTime)beginList.get(i);
ReactionTime end = (ReactionTime)endList.get(i);
rs.solveReactionSystemwithSEN(begin, end, true, false, false);
//reactionSystem.solveReactionSystemwithSEN(begin, end, true, false, false);
}
}
for (Integer i = 0; i<reactionSystemList.size();i++) {
// chemkin files are overwritten each loop - only the last gets saved
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
Chemkin.writeChemkinInputFile(getReactionModel(),rs.getPresentStatus());
}
//9/1/09 gmagoon: if we are using QM, output a file with the CHEMKIN name, the RMG name, the (modified) InChI, and the (modified) InChIKey
if (ChemGraph.useQM){
writeInChIs(getReactionModel());
}
writeDictionary(getReactionModel());
System.out.println("Model Generation Completed");
return;
}
//9/1/09 gmagoon: this function writes a "dictionary" with Chemkin name, RMG name, (modified) InChI, and InChIKey
//this is based off of writeChemkinFile in ChemkinInputFile.java
private void writeInChIs(ReactionModel p_reactionModel) {
StringBuilder result=new StringBuilder();
for (Iterator iter = ((CoreEdgeReactionModel)p_reactionModel).core.getSpecies(); iter.hasNext(); ) {
Species species = (Species) iter.next();
result.append(species.getChemkinName() + "\t"+species.getName() + "\t" + species.getChemGraph().getModifiedInChIAnew() + "\t" + species.getChemGraph().getModifiedInChIKeyAnew()+ "\n");
}
String file = "inchiDictionary.txt";
try {
FileWriter fw = new FileWriter(file);
fw.write(result.toString());
fw.close();
}
catch (Exception e) {
System.out.println("Error in writing InChI file inchiDictionary.txt!");
System.out.println(e.getMessage());
System.exit(0);
}
}
//9/14/09 gmagoon: function to write dictionary, based on code copied from RMG.java
private void writeDictionary(ReactionModel rm){
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)rm;
//Write core species to RMG_Dictionary.txt
String coreSpecies ="";
Iterator iter = cerm.getSpecies();
if (Species.useInChI) {
while (iter.hasNext()){
int i=1;
Species spe = (Species) iter.next();
coreSpecies = coreSpecies + spe.getChemkinName() + " " + spe.getInChI() + "\n"+spe.getChemGraph().toString(i)+"\n\n";
}
} else {
while (iter.hasNext()){
int i=1;
Species spe = (Species) iter.next();
coreSpecies = coreSpecies + spe.getChemkinName() + "\n"+spe.getChemGraph().toString(i)+"\n\n";
}
}
try{
File rmgDictionary = new File("RMG_Dictionary.txt");
FileWriter fw = new FileWriter(rmgDictionary);
fw.write(coreSpecies);
fw.close();
}
catch (IOException e) {
System.out.println("Could not write RMG_Dictionary.txt");
System.exit(0);
}
// If we have solvation on, then every time we write the dictionary, also write the solvation properties
if (Species.useSolvation) {
writeSolvationProperties(rm);
}
}
private void writeSolvationProperties(ReactionModel rm){
//Write core species to RMG_Solvation_Properties.txt
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)rm;
StringBuilder result = new StringBuilder();
result.append("ChemkinName\tChemicalFormula\tMolecularWeight\tRadius\tDiffusivity\tAbrahamS\tAbrahamB\tAbrahamE\tAbrahamL\tAbrahamA\tAbrahamV\tChemkinName\n\n");
Iterator iter = cerm.getSpecies();
while (iter.hasNext()){
Species spe = (Species)iter.next();
result.append(spe.getChemkinName() + "\t");
result.append(spe.getChemGraph().getChemicalFormula()+ "\t");
result.append(spe.getMolecularWeight() + "\t");
result.append(spe.getChemGraph().getRadius()+ "\t");
result.append(spe.getChemGraph().getDiffusivity()+ "\t");
result.append(spe.getChemGraph().getAbramData().toString()+ "\t");
result.append(spe.getChemkinName() + "\n");
}
try{
File rmgSolvationProperties = new File("RMG_Solvation_Properties.txt");
FileWriter fw = new FileWriter(rmgSolvationProperties);
fw.write(result.toString() );
fw.close();
}
catch (IOException e) {
System.out.println("Could not write RMG_Solvation_Properties.txt");
System.exit(0);
}
}
/*
* MRH 23MAR2010:
* Commenting out deprecated parseRestartFiles method
*/
// private void parseRestartFiles() {
// parseAllSpecies();
// parseCoreSpecies();
// parseEdgeSpecies();
// parseAllReactions();
// parseCoreReactions();
/*
* MRH 23MAR2010:
* Commenting out deprecated parseEdgeReactions method
*/
// private void parseEdgeReactions() {
// SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
// //HasMap speciesMap = dictionary.dictionary;
// try{
// File coreReactions = new File("Restart/edgeReactions.txt");
// FileReader fr = new FileReader(coreReactions);
// BufferedReader reader = new BufferedReader(fr);
// String line = ChemParser.readMeaningfulLine(reader);
// boolean found = false;
// LinkedHashSet reactionSet = new LinkedHashSet();
// while (line != null){
// Reaction reaction = ChemParser.parseEdgeArrheniusReaction(dictionary,line,1,1);
// boolean added = reactionSet.add(reaction);
// if (!added){
// if (reaction.hasResonanceIsomerAsReactant()){
// //Structure reactionStructure = reaction.getStructure();
// found = getResonanceStructure(reaction,"reactants", reactionSet);
// if (reaction.hasResonanceIsomerAsProduct() && !found){
// //Structure reactionStructure = reaction.getStructure();
// found = getResonanceStructure(reaction,"products", reactionSet);
// if (!found){
// System.out.println("Cannot add reaction "+line+" to the Reaction Edge. All resonance isomers have already been added");
// System.exit(0);
// else found = false;
// //Reaction reverse = reaction.getReverseReaction();
// //if (reverse != null) reactionSet.add(reverse);
// line = ChemParser.readMeaningfulLine(reader);
// ((CoreEdgeReactionModel)getReactionModel()).addReactionSet(reactionSet);
// catch (IOException e){
// System.out.println("Could not read the corespecies restart file");
// System.exit(0);
/*
* MRH 23MAR2010:
* Commenting out deprecated parseAllSpecies method
*/
// public void parseCoreReactions() {
// SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
// int i=1;
// //HasMap speciesMap = dictionary.dictionary;
// try{
// File coreReactions = new File("Restart/coreReactions.txt");
// FileReader fr = new FileReader(coreReactions);
// BufferedReader reader = new BufferedReader(fr);
// String line = ChemParser.readMeaningfulLine(reader);
// boolean found = false;
// LinkedHashSet reactionSet = new LinkedHashSet();
// while (line != null){
// Reaction reaction = ChemParser.parseCoreArrheniusReaction(dictionary,line,1,1);//,((CoreEdgeReactionModel)reactionSystem.reactionModel));
// boolean added = reactionSet.add(reaction);
// if (!added){
// if (reaction.hasResonanceIsomerAsReactant()){
// //Structure reactionStructure = reaction.getStructure();
// found = getResonanceStructure(reaction,"reactants", reactionSet);
// if (reaction.hasResonanceIsomerAsProduct() && !found){
// //Structure reactionStructure = reaction.getStructure();
// found = getResonanceStructure(reaction,"products", reactionSet);
// if (!found){
// System.out.println("Cannot add reaction "+line+" to the Reaction Core. All resonance isomers have already been added");
// //System.exit(0);
// else found = false;
// Reaction reverse = reaction.getReverseReaction();
// if (reverse != null) {
// reactionSet.add(reverse);
// //System.out.println(2 + "\t " + line);
// //else System.out.println(1 + "\t" + line);
// line = ChemParser.readMeaningfulLine(reader);
// i=i+1;
// ((CoreEdgeReactionModel)getReactionModel()).addReactedReactionSet(reactionSet);
// catch (IOException e){
// System.out.println("Could not read the coreReactions restart file");
// System.exit(0);
/*
* MRH 23MAR2010:
* Commenting out deprecated parseAllSpecies method
*/
// private void parseAllReactions() {
// SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
// int i=1;
// //HasMap speciesMap = dictionary.dictionary;
// try{
// File allReactions = new File("Restart/allReactions.txt");
// FileReader fr = new FileReader(allReactions);
// BufferedReader reader = new BufferedReader(fr);
// String line = ChemParser.readMeaningfulLine(reader);
// boolean found = false;
// LinkedHashSet reactionSet = new LinkedHashSet();
// OuterLoop:
// while (line != null){
// Reaction reaction = ChemParser.parseArrheniusReaction(dictionary,line,1,1,((CoreEdgeReactionModel)getReactionModel()));
// if (((CoreEdgeReactionModel)getReactionModel()).categorizeReaction(reaction)==-1){
// boolean added = reactionSet.add(reaction);
// if (!added){
// found = false;
// if (reaction.hasResonanceIsomerAsReactant()){
// //Structure reactionStructure = reaction.getStructure();
// found = getResonanceStructure(reaction,"reactants", reactionSet);
// if (reaction.hasResonanceIsomerAsProduct() && !found){
// //Structure reactionStructure = reaction.getStructure();
// found = getResonanceStructure(reaction,"products", reactionSet);
// if (!found){
// Iterator iter = reactionSet.iterator();
// while (iter.hasNext()){
// Reaction reacTemp = (Reaction)iter.next();
// if (reacTemp.equals(reaction)){
// reactionSet.remove(reacTemp);
// reactionSet.add(reaction);
// break;
// //System.out.println("Cannot add reaction "+line+" to the Reaction Core. All resonance isomers have already been added");
// //System.exit(0);
// //else found = false;
// /*Reaction reverse = reaction.getReverseReaction();
// if (reverse != null && ((CoreEdgeReactionModel)reactionSystem.reactionModel).isReactedReaction(reaction)) {
// reactionSet.add(reverse);
// //System.out.println(2 + "\t " + line);
// }*/
// //else System.out.println(1 + "\t" + line);
// i=i+1;
// line = ChemParser.readMeaningfulLine(reader);
// ((CoreEdgeReactionModel)getReactionModel()).addReactionSet(reactionSet);
// catch (IOException e){
// System.out.println("Could not read the corespecies restart file");
// System.exit(0);
private boolean getResonanceStructure(Reaction p_Reaction, String rOrP, LinkedHashSet reactionSet) {
Structure reactionStructure = p_Reaction.getStructure();
//Structure tempreactionStructure = new Structure(reactionStructure.getReactantList(),reactionStructure.getProductList());
boolean found = false;
if (rOrP.equals("reactants")){
Iterator originalreactants = reactionStructure.getReactants();
HashSet tempHashSet = new HashSet();
while(originalreactants.hasNext()){
tempHashSet.add(originalreactants.next());
}
Iterator reactants = tempHashSet.iterator();
while(reactants.hasNext() && !found){
ChemGraph reactant = (ChemGraph)reactants.next();
if (reactant.getSpecies().hasResonanceIsomers()){
Iterator chemGraphIterator = reactant.getSpecies().getResonanceIsomers();
ChemGraph newChemGraph ;//= (ChemGraph)chemGraphIterator.next();
while(chemGraphIterator.hasNext() && !found){
newChemGraph = (ChemGraph)chemGraphIterator.next();
reactionStructure.removeReactants(reactant);
reactionStructure.addReactants(newChemGraph);
reactant = newChemGraph;
if (reactionSet.add(p_Reaction)){
found = true;
}
}
}
}
}
else{
Iterator originalproducts = reactionStructure.getProducts();
HashSet tempHashSet = new HashSet();
while(originalproducts.hasNext()){
tempHashSet.add(originalproducts.next());
}
Iterator products = tempHashSet.iterator();
while(products.hasNext() && !found){
ChemGraph product = (ChemGraph)products.next();
if (product.getSpecies().hasResonanceIsomers()){
Iterator chemGraphIterator = product.getSpecies().getResonanceIsomers();
ChemGraph newChemGraph ;//= (ChemGraph)chemGraphIterator.next();
while(chemGraphIterator.hasNext() && !found){
newChemGraph = (ChemGraph)chemGraphIterator.next();
reactionStructure.removeProducts(product);
reactionStructure.addProducts(newChemGraph);
product = newChemGraph;
if (reactionSet.add(p_Reaction)){
found = true;
}
}
}
}
}
return found;
}
public void parseCoreSpecies() {
// String restartFileContent ="";
//int speciesCount = 0;
//boolean added;
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
try{
File coreSpecies = new File ("Restart/coreSpecies.txt");
FileReader fr = new FileReader(coreSpecies);
BufferedReader reader = new BufferedReader(fr);
String line = ChemParser.readMeaningfulLine(reader, true);
//HashSet speciesSet = new HashSet();
// if (reactionSystem == null){//10/24/07 gmagoon: commenting out since contents of if was already commented out anyway
// //ReactionSystem reactionSystem = new ReactionSystem();
setReactionModel(new CoreEdgeReactionModel());//10/4/07 gmagoon:changed to setReactionModel
while (line!=null) {
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
int ID = Integer.parseInt(index);
Species spe = dictionary.getSpeciesFromID(ID);
if (spe == null)
System.out.println("There was no species with ID "+ID +" in the species dictionary");
((CoreEdgeReactionModel)getReactionModel()).addReactedSpecies(spe);
line = ChemParser.readMeaningfulLine(reader, true);
}
}
catch (IOException e){
System.out.println("Could not read the corespecies restart file");
System.exit(0);
}
}
public static void garbageCollect(){
System.gc();
}
public static long memoryUsed(){
garbageCollect();
Runtime rT = Runtime.getRuntime();
long uM, tM, fM;
tM = rT.totalMemory();
fM = rT.freeMemory();
uM = tM - fM;
System.out.println("After garbage collection:");
System.out.print("Memory used: ");
System.out.println(tM);
System.out.print("Free memory: ");
System.out.println(fM);
return uM;
}
private HashSet readIncludeSpecies(String fileName) {
HashSet speciesSet = new HashSet();
try {
File includeSpecies = new File (fileName);
FileReader fr = new FileReader(includeSpecies);
BufferedReader reader = new BufferedReader(fr);
String line = ChemParser.readMeaningfulLine(reader, true);
while (line!=null) {
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String name = null;
if (!index.startsWith("(")) name = index;
else name = st.nextToken().trim();
Graph g = ChemParser.readChemGraph(reader);
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
}
catch (ForbiddenStructureException e) {
System.out.println("Forbidden Structure:\n" + e.getMessage());
System.out.println("Included species file "+fileName+" contains a forbidden structure.");
System.exit(0);
}
Species species = Species.make(name,cg);
//speciesSet.put(name, species);
speciesSet.add(species);
line = ChemParser.readMeaningfulLine(reader, true);
System.out.println(line);
}
}
catch (IOException e){
System.out.println("Could not read the included species file" + fileName);
System.exit(0);
}
return speciesSet;
}
/*
* MRH 23MAR2010:
* Commenting out deprecated parseAllSpecies method
*/
// public LinkedHashSet parseAllSpecies() {
// // String restartFileContent ="";
// int speciesCount = 0;
// LinkedHashSet speciesSet = new LinkedHashSet();
// boolean added;
// try{
// long initialTime = System.currentTimeMillis();
// File coreSpecies = new File ("allSpecies.txt");
// BufferedReader reader = new BufferedReader(new FileReader(coreSpecies));
// String line = ChemParser.readMeaningfulLine(reader);
// int i=0;
// while (line!=null) {
// StringTokenizer st = new StringTokenizer(line);
// String index = st.nextToken();
// String name = null;
// if (!index.startsWith("(")) name = index;
// else name = st.nextToken().trim();
// int ID = getID(name);
// name = getName(name);
// Graph g = ChemParser.readChemGraph(reader);
// ChemGraph cg = null;
// try {
// cg = ChemGraph.make(g);
// catch (ForbiddenStructureException e) {
// System.out.println("Forbidden Structure:\n" + e.getMessage());
// System.exit(0);
// Species species;
// if (ID == 0)
// species = Species.make(name,cg);
// else
// species = Species.make(name,cg,ID);
// speciesSet.add(species);
// double flux = 0;
// int species_type = 1;
// line = ChemParser.readMeaningfulLine(reader);
// System.out.println(line);
// catch (IOException e){
// System.out.println("Could not read the allSpecies restart file");
// System.exit(0);
// return speciesSet;
private String getName(String name) {
//int id;
String number = "";
int index=0;
if (!name.endsWith(")")) return name;
else {
char [] nameChars = name.toCharArray();
String temp = String.copyValueOf(nameChars);
int i=name.length()-2;
//char test = "(";
while (i>0){
if (name.charAt(i)== '(') {
index=i;
i=0;
}
else i = i-1;
}
}
number = name.substring(0,index);
return number;
}
private int getID(String name) {
int id;
String number = "";
if (!name.endsWith(")")) return 0;
else {
char [] nameChars = name.toCharArray();
int i=name.length()-2;
//char test = "(";
while (i>0){
if (name.charAt(i)== '(') i=0;
else{
number = name.charAt(i)+number;
i = i-1;
}
}
}
id = Integer.parseInt(number);
return id;
}
/*
* MRH 23MAR2010:
* Commenting out deprecated parseAllSpecies method
*/
// private void parseEdgeSpecies() {
// // String restartFileContent ="";
// SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
// try{
// File edgeSpecies = new File ("Restart/edgeSpecies.txt");
// FileReader fr = new FileReader(edgeSpecies);
// BufferedReader reader = new BufferedReader(fr);
// String line = ChemParser.readMeaningfulLine(reader);
// //HashSet speciesSet = new HashSet();
// while (line!=null) {
// StringTokenizer st = new StringTokenizer(line);
// String index = st.nextToken();
// int ID = Integer.parseInt(index);
// Species spe = dictionary.getSpeciesFromID(ID);
// if (spe == null)
// System.out.println("There was no species with ID "+ID +" in the species dictionary");
// //reactionSystem.reactionModel = new CoreEdgeReactionModel();
// ((CoreEdgeReactionModel)getReactionModel()).addUnreactedSpecies(spe);
// line = ChemParser.readMeaningfulLine(reader);
// catch (IOException e){
// System.out.println("Could not read the edgepecies restart file");
// System.exit(0);
/*private int calculateAllReactionsinReactionTemplate() {
int totalnum = 0;
TemplateReactionGenerator trg = (TemplateReactionGenerator)reactionSystem.reactionGenerator;
Iterator iter = trg.getReactionTemplateLibrary().getReactionTemplate();
while (iter.hasNext()){
ReactionTemplate rt = (ReactionTemplate)iter.next();
totalnum += rt.getNumberOfReactions();
}
return totalnum;
}*/
private void writeEnlargerInfo() {
try {
File diagnosis = new File("enlarger.xls");
FileWriter fw = new FileWriter(diagnosis);
fw.write(Global.enlargerInfo.toString());
fw.close();
}
catch (IOException e) {
System.out.println("Cannot write enlarger file");
System.exit(0);
}
}
private void writeDiagnosticInfo() {
try {
File diagnosis = new File("diagnosis.xls");
FileWriter fw = new FileWriter(diagnosis);
fw.write(Global.diagnosticInfo.toString());
fw.close();
}
catch (IOException e) {
System.out.println("Cannot write diagnosis file");
System.exit(0);
}
}
//10/25/07 gmagoon: I don't think this is used, but I will update to use reactionSystem and reactionTime as parameter to access temperature; commented-out usage of writeRestartFile will need to be modified
//Is still incomplete.
public void writeRestartFile(ReactionSystem p_rs, ReactionTime p_time ) {
//writeCoreSpecies(p_rs);
//writeCoreReactions(p_rs, p_time);
//writeEdgeSpecies();
//writeAllReactions(p_rs, p_time);
//writeEdgeReactions(p_rs, p_time);
//String restartFileName;
//String restartFileContent="";
}
/*
* MRH 25MAR2010
* This method is no longer used
*/
/*Only write the forward reactions in the model core.
The reverse reactions are generated from the forward reactions.*/
//10/25/07 gmagoon: added reaction system and reaction time as parameters and eliminated use of Global.temperature
// private void writeEdgeReactions(ReactionSystem p_rs, ReactionTime p_time) {
// StringBuilder restartFileContent =new StringBuilder();
// int reactionCount = 1;
// try{
// File coreSpecies = new File ("Restart/edgeReactions.txt");
// FileWriter fw = new FileWriter(coreSpecies);
// for(Iterator iter=((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().iterator();iter.hasNext();){
// Reaction reaction = (Reaction) iter.next();
// //if (reaction.getDirection()==1){
// //restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
// restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n");
// reactionCount = reactionCount + 1;
// //restartFileContent += "\nEND";
// fw.write(restartFileContent.toString());
// fw.close();
// catch (IOException e){
// System.out.println("Could not write the restart edgereactions file");
// System.exit(0);
/*
* MRH 25MAR2010:
* This method is no longer used
*/
//10/25/07 gmagoon: added reaction system and reaction time as parameters and eliminated use of Global.temperature
// private void writeAllReactions(ReactionSystem p_rs, ReactionTime p_time) {
// StringBuilder restartFileContent = new StringBuilder();
// int reactionCount = 1;
// try{
// File allReactions = new File ("Restart/allReactions.txt");
// FileWriter fw = new FileWriter(allReactions);
// for(Iterator iter=getReactionModel().getReaction();iter.hasNext();){
// Reaction reaction = (Reaction) iter.next();
// //restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
// restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n");
// for(Iterator iter=((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().iterator();iter.hasNext();){
// Reaction reaction = (Reaction) iter.next();
// //if (reaction.getDirection()==1){
// //restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
// restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n");
// //restartFileContent += "\nEND";
// fw.write(restartFileContent.toString());
// fw.close();
// catch (IOException e){
// System.out.println("Could not write the restart edgereactions file");
// System.exit(0);
private void writeEdgeSpecies() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Restart/edgeSpecies.txt"));
for(Iterator iter=((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().iterator();iter.hasNext();){
Species species = (Species) iter.next();
bw.write(species.getName()+"("+species.getID()+")");
bw.newLine();
int dummyInt = 0;
bw.write(species.getChemGraph().toString(dummyInt));
bw.newLine();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private void writePrunedEdgeSpecies(Species species) {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Pruning/edgeSpecies.txt", true));
bw.write(species.getChemkinName());
bw.newLine();
int dummyInt = 0;
bw.write(species.getChemGraph().toString(dummyInt));
bw.newLine();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/*
* MRH 25MAR2010:
* This method is no longer used
*/
//10/25/07 gmagoon: added reaction system and reaction time as parameters and eliminated use of Global.temperature
// private void writeCoreReactions(ReactionSystem p_rs, ReactionTime p_time) {
// StringBuilder restartFileContent = new StringBuilder();
// int reactionCount = 0;
// try{
// File coreSpecies = new File ("Restart/coreReactions.txt");
// FileWriter fw = new FileWriter(coreSpecies);
// for(Iterator iter=getReactionModel().getReaction();iter.hasNext();){
// Reaction reaction = (Reaction) iter.next();
// if (reaction.getDirection()==1){
// //restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
// restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n");
// reactionCount = reactionCount + 1;
// //restartFileContent += "\nEND";
// fw.write(restartFileContent.toString());
// fw.close();
// catch (IOException e){
// System.out.println("Could not write the restart corereactions file");
// System.exit(0);
private void writeCoreSpecies() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Restart/coreSpecies.txt"));
for(Iterator iter=getReactionModel().getSpecies();iter.hasNext();){
Species species = (Species) iter.next();
bw.write(species.getName()+"("+species.getID()+")");
bw.newLine();
int dummyInt = 0;
bw.write(species.getChemGraph().toString(dummyInt));
bw.newLine();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private void writeCoreReactions() {
BufferedWriter bw_rxns = null;
BufferedWriter bw_pdeprxns = null;
try {
bw_rxns = new BufferedWriter(new FileWriter("Restart/coreReactions.txt"));
bw_pdeprxns = new BufferedWriter(new FileWriter("Restart/pdepreactions.txt"));
String EaUnits = ArrheniusKinetics.getEaUnits();
String AUnits = ArrheniusKinetics.getAUnits();
bw_rxns.write("UnitsOfEa: " + EaUnits);
bw_rxns.newLine();
bw_pdeprxns.write("Unit:\nA: mol/cm3/s\nE: " + EaUnits + "\n\nReactions:");
bw_pdeprxns.newLine();
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)getReactionModel();
LinkedHashSet allcoreRxns = cerm.core.reaction;
for(Iterator iter=allcoreRxns.iterator(); iter.hasNext();){
Reaction reaction = (Reaction) iter.next();
if (reaction.isForward()) {
if (reaction instanceof TROEReaction) {
TROEReaction troeRxn = (TROEReaction) reaction;
bw_pdeprxns.write(troeRxn.toRestartString(new Temperature(298,"K")));
bw_pdeprxns.newLine();
}
else if (reaction instanceof LindemannReaction) {
LindemannReaction lindeRxn = (LindemannReaction) reaction;
bw_pdeprxns.write(lindeRxn.toRestartString(new Temperature(298,"K")));
bw_pdeprxns.newLine();
}
else if (reaction instanceof ThirdBodyReaction) {
ThirdBodyReaction tbRxn = (ThirdBodyReaction) reaction;
bw_pdeprxns.write(tbRxn.toRestartString(new Temperature(298,"K")));
bw_pdeprxns.newLine();
}
else {
//bw.write(reaction.toChemkinString(new Temperature(298,"K")));
bw_rxns.write(reaction.toRestartString(new Temperature(298,"K"),false));
bw_rxns.newLine();
}
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw_rxns != null) {
bw_rxns.flush();
bw_rxns.close();
}
if (bw_pdeprxns != null) {
bw_pdeprxns.flush();
bw_pdeprxns.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private void writeEdgeReactions() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Restart/edgeReactions.txt"));
String EaUnits = ArrheniusKinetics.getEaUnits();
bw.write("UnitsOfEa: " + EaUnits);
bw.newLine();
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)getReactionModel();
LinkedHashSet alledgeRxns = cerm.edge.reaction;
for(Iterator iter=alledgeRxns.iterator(); iter.hasNext();){
Reaction reaction = (Reaction) iter.next();
if (reaction.isForward()) {
//bw.write(reaction.toChemkinString(new Temperature(298,"K")));
bw.write(reaction.toRestartString(new Temperature(298,"K"),false));
bw.newLine();
} else if (reaction.getReverseReaction().isForward()) {
//bw.write(reaction.getReverseReaction().toChemkinString(new Temperature(298,"K")));
bw.write(reaction.getReverseReaction().toRestartString(new Temperature(298,"K"),false));
bw.newLine();
} else
System.out.println("Could not determine forward direction for following rxn: " + reaction.toString());
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
//gmagoon 4/5/10: based on Mike's writeEdgeReactions
private void writePrunedEdgeReaction(Reaction reaction) {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Pruning/edgeReactions.txt", true));
if (reaction.isForward()) {
bw.write(reaction.toChemkinString(new Temperature(298,"K")));
// bw.write(reaction.toRestartString(new Temperature(298,"K")));
bw.newLine();
} else if (reaction.getReverseReaction().isForward()) {
bw.write(reaction.getReverseReaction().toChemkinString(new Temperature(298,"K")));
//bw.write(reaction.getReverseReaction().toRestartString(new Temperature(298,"K")));
bw.newLine();
} else
System.out.println("Could not determine forward direction for following rxn: " + reaction.toString());
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private void writePDepNetworks() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Restart/pdepnetworks.txt"));
int numFameTemps = PDepRateConstant.getTemperatures().length;
int numFamePress = PDepRateConstant.getPressures().length;
int numChebyTemps = ChebyshevPolynomials.getNT();
int numChebyPress = ChebyshevPolynomials.getNP();
int numPlog = PDepArrheniusKinetics.getNumPressures();
String EaUnits = ArrheniusKinetics.getEaUnits();
bw.write("UnitsOfEa: " + EaUnits);
bw.newLine();
bw.write("NumberOfFameTemps: " + numFameTemps);
bw.newLine();
bw.write("NumberOfFamePress: " + numFamePress);
bw.newLine();
bw.write("NumberOfChebyTemps: " + numChebyTemps);
bw.newLine();
bw.write("NumberOfChebyPress: " + numChebyPress);
bw.newLine();
bw.write("NumberOfPLogs: " + numPlog);
bw.newLine();
bw.newLine();
LinkedList allNets = PDepNetwork.getNetworks();
int netCounter = 0;
for(Iterator iter=allNets.iterator(); iter.hasNext();){
PDepNetwork pdepnet = (PDepNetwork) iter.next();
++netCounter;
bw.write("PDepNetwork #" + netCounter);
bw.newLine();
// Write netReactionList
LinkedList netRxns = pdepnet.getNetReactions();
bw.write("netReactionList:");
bw.newLine();
for (Iterator iter2=netRxns.iterator(); iter2.hasNext();) {
PDepReaction currentPDepRxn = (PDepReaction)iter2.next();
bw.write(currentPDepRxn.toString());
bw.newLine();
bw.write(writeRatesAndParameters(currentPDepRxn,numFameTemps,
numFamePress,numChebyTemps,numChebyPress,numPlog));
PDepReaction currentPDepReverseRxn = currentPDepRxn.getReverseReaction();
// Not all netReactions are reversible
if (currentPDepReverseRxn != null) {
bw.write(currentPDepReverseRxn.toString());
bw.newLine();
bw.write(writeRatesAndParameters(currentPDepReverseRxn,numFameTemps,
numFamePress,numChebyTemps,numChebyPress,numPlog));
}
}
// Write nonincludedReactionList
LinkedList nonIncludeRxns = pdepnet.getNonincludedReactions();
bw.write("nonIncludedReactionList:");
bw.newLine();
for (Iterator iter2=nonIncludeRxns.iterator(); iter2.hasNext();) {
PDepReaction currentPDepRxn = (PDepReaction)iter2.next();
bw.write(currentPDepRxn.toString());
bw.newLine();
bw.write(writeRatesAndParameters(currentPDepRxn,numFameTemps,
numFamePress,numChebyTemps,numChebyPress,numPlog));
PDepReaction currentPDepReverseRxn = currentPDepRxn.getReverseReaction();
// Not all nonIncludedReactions are reversible
if (currentPDepReverseRxn != null) {
bw.write(currentPDepReverseRxn.toString());
bw.newLine();
bw.write(writeRatesAndParameters(currentPDepReverseRxn,numFameTemps,
numFamePress,numChebyTemps,numChebyPress,numPlog));
}
}
// Write pathReactionList
LinkedList pathRxns = pdepnet.getPathReactions();
bw.write("pathReactionList:");
bw.newLine();
for (Iterator iter2=pathRxns.iterator(); iter2.hasNext();) {
PDepReaction currentPDepRxn = (PDepReaction)iter2.next();
bw.write(currentPDepRxn.getDirection() + "\t" + currentPDepRxn.toRestartString(new Temperature(298,"K")));
bw.newLine();
}
bw.newLine();
bw.newLine();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public String writeRatesAndParameters(PDepReaction pdeprxn, int numFameTemps,
int numFamePress, int numChebyTemps, int numChebyPress, int numPlog) {
StringBuilder sb = new StringBuilder();
// Write the rate coefficients
double[][] rateConstants = pdeprxn.getPDepRate().getRateConstants();
for (int i=0; i<numFameTemps; i++) {
for (int j=0; j<numFamePress; j++) {
sb.append(rateConstants[i][j] + "\t");
}
sb.append("\n");
}
sb.append("\n");
// If chebyshev polynomials are present, write them
if (numChebyTemps != 0) {
ChebyshevPolynomials chebyPolys = pdeprxn.getPDepRate().getChebyshev();
for (int i=0; i<numChebyTemps; i++) {
for (int j=0; j<numChebyPress; j++) {
sb.append(chebyPolys.getAlpha(i,j) + "\t");
}
sb.append("\n");
}
sb.append("\n");
}
// If plog parameters are present, write them
else if (numPlog != 0) {
PDepArrheniusKinetics kinetics = pdeprxn.getPDepRate().getPDepArrheniusKinetics();
for (int i=0; i<numPlog; i++) {
double Hrxn = pdeprxn.calculateHrxn(new Temperature(298,"K"));
sb.append(kinetics.pressures[i].getPa() + "\t" + kinetics.getKinetics(i).toChemkinString(Hrxn,new Temperature(298,"K"),false) + "\n");
}
sb.append("\n");
}
return sb.toString();
}
public LinkedList getTimeStep() {
return timeStep;
}
public static boolean getUseDiffusion() {
return useDiffusion;
}
public void setUseDiffusion(Boolean p_boolean) {
useDiffusion = p_boolean;
}
public void setTimeStep(ReactionTime p_timeStep) {
if (timeStep == null)
timeStep = new LinkedList();
timeStep.add(p_timeStep);
}
public String getWorkingDirectory() {
return workingDirectory;
}
public void setWorkingDirectory(String p_workingDirectory) {
workingDirectory = p_workingDirectory;
}
//svp
public boolean getError(){
return error;
}
//svp
public boolean getSensitivity(){
return sensitivity;
}
public LinkedList getSpeciesList() {
return species;
}
//gmagoon 10/24/07: commented out getReactionSystem and setReactionSystem
// public ReactionSystem getReactionSystem() {
// return reactionSystem;
//11/2/07 gmagoon: adding accessor method for reactionSystemList
public LinkedList getReactionSystemList(){
return reactionSystemList;
}
//added by gmagoon 9/24/07
// public void setReactionSystem(ReactionSystem p_ReactionSystem) {
// reactionSystem = p_ReactionSystem;
//copied from ReactionSystem.java by gmagoon 9/24/07
public ReactionModel getReactionModel() {
return reactionModel;
}
public void readRestartSpecies() {
System.out.println("Reading in species from Restart folder");
// Read in core species -- NOTE code is almost duplicated in Read in edge species (second part of procedure)
try {
FileReader in = new FileReader("Restart/coreSpecies.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader, true);
while (line != null) {
// The first line of a new species is the user-defined name
String totalSpeciesName = line;
String[] splitString1 = totalSpeciesName.split("[(]");
String[] splitString2 = splitString1[splitString1.length-1].split("[)]");
// The remaining lines are the graph
Graph g = ChemParser.readChemGraph(reader);
// Make the ChemGraph, assuming it does not contain a forbidden structure
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
} catch (ForbiddenStructureException e) {
System.out.println("Error reading graph: Graph contains a forbidden structure.\n" + g.toString());
System.exit(0);
}
// Make the species
int intLocation = totalSpeciesName.indexOf("(" + splitString2[0] + ")");
Species species = Species.make(totalSpeciesName.substring(0,intLocation),cg,Integer.parseInt(splitString2[0]));
// Add the new species to the set of species
restartCoreSpcs.add(species);
/*int species_type = 1; // reacted species
for (int i=0; i<numRxnSystems; i++) {
SpeciesStatus ss = new SpeciesStatus(species,species_type,y[i],yprime[i]);
speciesStatus[i].put(species, ss);
}*/
line = ChemParser.readMeaningfulLine(reader, true);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Read in edge species
try {
FileReader in = new FileReader("Restart/edgeSpecies.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader, true);
while (line != null) {
// The first line of a new species is the user-defined name
String totalSpeciesName = line;
String[] splitString1 = totalSpeciesName.split("[(]");
String[] splitString2 = splitString1[splitString1.length-1].split("[)]"); // Change JDM to reflect MRH 2-11-2010
// The remaining lines are the graph
Graph g = ChemParser.readChemGraph(reader);
// Make the ChemGraph, assuming it does not contain a forbidden structure
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
} catch (ForbiddenStructureException e) {
System.out.println("Error reading graph: Graph contains a forbidden structure.\n" + g.toString());
System.exit(0);
}
// Rewrite the species name ... with the exception of the (
String speciesName = splitString1[0];
for (int numTokens=1; numTokens<splitString1.length-1; ++numTokens) {
speciesName += "(" + splitString1[numTokens];
}
// Make the species
Species species = Species.make(speciesName,cg,Integer.parseInt(splitString2[0]));
// Add the new species to the set of species
restartEdgeSpcs.add(species);
line = ChemParser.readMeaningfulLine(reader, true);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void readRestartReactions() {
// Grab the IDs from the core species
int[] coreSpcsIds = new int[restartCoreSpcs.size()];
int i = 0;
for (Iterator iter = restartCoreSpcs.iterator(); iter.hasNext();) {
Species spcs = (Species)iter.next();
coreSpcsIds[i] = spcs.getID();
++i;
}
System.out.println("Reading reactions from Restart folder");
// Read in core reactions
try {
FileReader in = new FileReader("Restart/coreReactions.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader, true);
// Determine units of Ea
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken();
String EaUnits = st.nextToken();
line = ChemParser.readMeaningfulLine(reader, true);
while (line != null) {
if (!line.trim().equals("DUP")) {
Reaction r = ChemParser.parseRestartReaction(line,coreSpcsIds,"core",EaUnits);
Iterator rxnIter = restartCoreRxns.iterator();
boolean foundRxn = false;
while (rxnIter.hasNext()) {
Reaction old = (Reaction)rxnIter.next();
if (old.equals(r)) {
old.addAdditionalKinetics(r.getKinetics()[0],1);
foundRxn = true;
break;
}
}
if (!foundRxn) {
if (r.hasReverseReaction()) r.generateReverseReaction();
restartCoreRxns.add(r);
}
}
line = ChemParser.readMeaningfulLine(reader, true);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/*
* Read in the pdepreactions.txt file:
* This file contains third-body, lindemann, and troe reactions
* A RMG mechanism would only have these reactions if a user specified
* them in a Seed Mechanism, meaning they are core species &
* reactions.
* Place these reactions in a new Seed Mechanism, using the
* coreSpecies.txt file as the species.txt file.
*/
try {
String path = System.getProperty("user.dir") + "/Restart";
if (getSeedMechanism() == null)
setSeedMechanism(new SeedMechanism("Restart", path, false, true));
else
getSeedMechanism().appendSeedMechanism("Restart", path, false, true);
} catch (IOException e1) {
e1.printStackTrace();
}
restartCoreRxns.addAll(getSeedMechanism().getReactionSet());
// Read in edge reactions
try {
FileReader in = new FileReader("Restart/edgeReactions.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader, true);
// Determine units of Ea
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken();
String EaUnits = st.nextToken();
line = ChemParser.readMeaningfulLine(reader, true);
while (line != null) {
if (!line.trim().equals("DUP")) {
Reaction r = ChemParser.parseRestartReaction(line,coreSpcsIds,"edge",EaUnits);
Iterator rxnIter = restartEdgeRxns.iterator();
boolean foundRxn = false;
while (rxnIter.hasNext()) {
Reaction old = (Reaction)rxnIter.next();
if (old.equals(r)) {
old.addAdditionalKinetics(r.getKinetics()[0],1);
foundRxn = true;
break;
}
}
if (!foundRxn) {
r.generateReverseReaction();
restartEdgeRxns.add(r);
}
}
line = ChemParser.readMeaningfulLine(reader, true);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public LinkedHashMap getRestartSpeciesStatus(int i) {
LinkedHashMap speciesStatus = new LinkedHashMap();
try {
FileReader in = new FileReader("Restart/coreSpecies.txt");
BufferedReader reader = new BufferedReader(in);
Integer numRxnSystems = Integer.parseInt(ChemParser.readMeaningfulLine(reader, true));
String line = ChemParser.readMeaningfulLine(reader, true);
while (line != null) {
// The first line of a new species is the user-defined name
String totalSpeciesName = line;
String[] splitString1 = totalSpeciesName.split("[(]");
String[] splitString2 = splitString1[1].split("[)]");
double y = 0.0;
double yprime = 0.0;
for (int j=0; j<numRxnSystems; j++) {
StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
if (j == i) {
y = Double.parseDouble(st.nextToken());
yprime = Double.parseDouble(st.nextToken());
}
}
// The remaining lines are the graph
Graph g = ChemParser.readChemGraph(reader);
// Make the ChemGraph, assuming it does not contain a forbidden structure
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
} catch (ForbiddenStructureException e) {
System.out.println("Error reading graph: Graph contains a forbidden structure.\n" + g.toString());
System.exit(0);
}
// Make the species
Species species = Species.make(splitString1[0],cg);
// Add the new species to the set of species
//restartCoreSpcs.add(species);
int species_type = 1; // reacted species
SpeciesStatus ss = new SpeciesStatus(species,species_type,y,yprime);
speciesStatus.put(species, ss);
line = ChemParser.readMeaningfulLine(reader, true);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return speciesStatus;
}
public void putRestartSpeciesInInitialStatus(InitialStatus is, int i) {
try {
FileReader in = new FileReader("Restart/coreSpecies.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader, true);
while (line != null) {
// The first line of a new species is the user-defined name
String totalSpeciesName = line;
String[] splitString1 = totalSpeciesName.split("[(]");
String[] splitString2 = splitString1[1].split("[)]");
// The remaining lines are the graph
Graph g = ChemParser.readChemGraph(reader);
// Make the ChemGraph, assuming it does not contain a forbidden structure
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
} catch (ForbiddenStructureException e) {
System.out.println("Error reading graph: Graph contains a forbidden structure.\n" + g.toString());
System.exit(0);
}
// Make the species
Species species = Species.make(splitString1[0],cg);
// Add the new species to the set of species
//restartCoreSpcs.add(species);
if (is.getSpeciesStatus(species) == null) {
SpeciesStatus ss = new SpeciesStatus(species,1,0.0,0.0);
is.putSpeciesStatus(ss);
}
line = ChemParser.readMeaningfulLine(reader, true);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void readPDepNetworks() {
LinkedList allNetworks = PDepNetwork.getNetworks();
try {
FileReader in = new FileReader("Restart/pdepnetworks.txt");
BufferedReader reader = new BufferedReader(in);
StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
String tempString = st.nextToken();
String EaUnits = st.nextToken();
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
tempString = st.nextToken();
int numFameTs = Integer.parseInt(st.nextToken());
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
tempString = st.nextToken();
int numFamePs = Integer.parseInt(st.nextToken());
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
tempString = st.nextToken();
int numChebyTs = Integer.parseInt(st.nextToken());
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
tempString = st.nextToken();
int numChebyPs = Integer.parseInt(st.nextToken());
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
tempString = st.nextToken();
int numPlogs = Integer.parseInt(st.nextToken());
double[][] rateCoefficients = new double[numFameTs][numFamePs];
double[][] chebyPolys = new double[numChebyTs][numChebyPs];
Kinetics[] plogKinetics = new Kinetics[numPlogs];
String line = ChemParser.readMeaningfulLine(reader, true); // line should be "PDepNetwork
while (line != null) {
line = ChemParser.readMeaningfulLine(reader, true); // line should now be "netReactionList:"
PDepNetwork newNetwork = new PDepNetwork();
LinkedList netRxns = newNetwork.getNetReactions();
LinkedList nonincludeRxns = newNetwork.getNonincludedReactions();
line = ChemParser.readMeaningfulLine(reader, true); // line is either data or "nonIncludedReactionList"
// If line is "nonincludedreactionlist", we need to skip over this while loop
if (!line.toLowerCase().startsWith("nonincludedreactionlist")) {
while (!line.toLowerCase().startsWith("nonincludedreactionlist")) {
// Read in the forward rxn
String[] reactsANDprods = line.split("\\
/*
* Determine if netReaction is reversible or irreversible
*/
boolean reactionIsReversible = true;
if (reactsANDprods.length == 2)
reactionIsReversible = false;
else
reactsANDprods = line.split("\\<=>");
PDepIsomer Reactants = parseIsomerFromRestartFile(reactsANDprods[0].trim());
PDepIsomer Products = parseIsomerFromRestartFile(reactsANDprods[1].trim());
newNetwork.addIsomer(Reactants);
newNetwork.addIsomer(Products);
rateCoefficients = parseRateCoeffsFromRestartFile(numFameTs,numFamePs,reader);
PDepRateConstant pdepk = parsePDepRateConstantFromRestartFile(reader,numChebyTs,numChebyPs,rateCoefficients,numPlogs,EaUnits);
PDepReaction forward = new PDepReaction(Reactants, Products, pdepk);
// Read in the reverse reaction
if (reactionIsReversible) {
line = ChemParser.readMeaningfulLine(reader, true);
rateCoefficients = parseRateCoeffsFromRestartFile(numFameTs,numFamePs,reader);
pdepk = parsePDepRateConstantFromRestartFile(reader,numChebyTs,numChebyPs,rateCoefficients,numPlogs,EaUnits);
PDepReaction reverse = new PDepReaction(Products, Reactants, pdepk);
reverse.setReverseReaction(forward);
forward.setReverseReaction(reverse);
}
else {
PDepReaction reverse = null;
forward.setReverseReaction(reverse);
}
netRxns.add(forward);
line = ChemParser.readMeaningfulLine(reader, true);
}
}
// This loop ends once line == "nonIncludedReactionList"
line = ChemParser.readMeaningfulLine(reader, true); // line is either data or "pathReactionList"
if (!line.toLowerCase().startsWith("pathreactionList")) {
while (!line.toLowerCase().startsWith("pathreactionlist")) {
// Read in the forward rxn
String[] reactsANDprods = line.split("\\
/*
* Determine if nonIncludedReaction is reversible or irreversible
*/
boolean reactionIsReversible = true;
if (reactsANDprods.length == 2)
reactionIsReversible = false;
else
reactsANDprods = line.split("\\<=>");
PDepIsomer Reactants = parseIsomerFromRestartFile(reactsANDprods[0].trim());
PDepIsomer Products = parseIsomerFromRestartFile(reactsANDprods[1].trim());
newNetwork.addIsomer(Reactants);
newNetwork.addIsomer(Products);
rateCoefficients = parseRateCoeffsFromRestartFile(numFameTs,numFamePs,reader);
PDepRateConstant pdepk = parsePDepRateConstantFromRestartFile(reader,numChebyTs,numChebyPs,rateCoefficients,numPlogs,EaUnits);
PDepReaction forward = new PDepReaction(Reactants, Products, pdepk);
// Read in the reverse reaction
if (reactionIsReversible) {
line = ChemParser.readMeaningfulLine(reader, true);
rateCoefficients = parseRateCoeffsFromRestartFile(numFameTs,numFamePs,reader);
pdepk = parsePDepRateConstantFromRestartFile(reader,numChebyTs,numChebyPs,rateCoefficients,numPlogs,EaUnits);
PDepReaction reverse = new PDepReaction(Products, Reactants, pdepk);
reverse.setReverseReaction(forward);
forward.setReverseReaction(reverse);
}
else {
PDepReaction reverse = null;
forward.setReverseReaction(reverse);
}
nonincludeRxns.add(forward);
line = ChemParser.readMeaningfulLine(reader, true);
}
}
// This loop ends once line == "pathReactionList"
line = ChemParser.readMeaningfulLine(reader, true); // line is either data or "PDepNetwork #_" or null (end of file)
while (line != null && !line.toLowerCase().startsWith("pdepnetwork")) {
st = new StringTokenizer(line);
int direction = Integer.parseInt(st.nextToken());
// First token is the rxn structure: A+B=C+D
// Note: Up to 3 reactants/products allowed
// : Either "=" or "=>" will separate reactants and products
String structure = st.nextToken();
// Separate the reactants from the products
boolean generateReverse = false;
String[] reactsANDprods = structure.split("\\=>");
if (reactsANDprods.length == 1) {
reactsANDprods = structure.split("[=]");
generateReverse = true;
}
SpeciesDictionary sd = SpeciesDictionary.getInstance();
LinkedList r = ChemParser.parseReactionSpecies(sd, reactsANDprods[0]);
LinkedList p = ChemParser.parseReactionSpecies(sd, reactsANDprods[1]);
Structure s = new Structure(r,p);
s.setDirection(direction);
// Next three tokens are the modified Arrhenius parameters
double rxn_A = Double.parseDouble(st.nextToken());
double rxn_n = Double.parseDouble(st.nextToken());
double rxn_E = Double.parseDouble(st.nextToken());
if (EaUnits.equals("cal/mol"))
rxn_E = rxn_E / 1000;
else if (EaUnits.equals("J/mol"))
rxn_E = rxn_E / 4.184 / 1000;
else if (EaUnits.equals("kJ/mol"))
rxn_E = rxn_E / 4.184;
else if (EaUnits.equals("Kelvins"))
rxn_E = rxn_E * 1.987;
UncertainDouble uA = new UncertainDouble(rxn_A,0.0,"A");
UncertainDouble un = new UncertainDouble(rxn_n,0.0,"A");
UncertainDouble uE = new UncertainDouble(rxn_E,0.0,"A");
// The remaining tokens are comments
String comments = "";
if (st.hasMoreTokens()) {
String beginningOfComments = st.nextToken();
int startIndex = line.indexOf(beginningOfComments);
comments = line.substring(startIndex);
}
if (comments.startsWith("!")) comments = comments.substring(1);
// while (st.hasMoreTokens()) {
// comments += st.nextToken();
ArrheniusKinetics[] k = new ArrheniusKinetics[1];
k[0] = new ArrheniusKinetics(uA,un,uE,"",1,"",comments);
Reaction pathRxn = new Reaction();
// if (direction == 1)
// pathRxn = Reaction.makeReaction(s,k,generateReverse);
// else
// pathRxn = Reaction.makeReaction(s.generateReverseStructure(),k,generateReverse);
pathRxn = Reaction.makeReaction(s,k,generateReverse);
PDepIsomer Reactants = new PDepIsomer(r);
PDepIsomer Products = new PDepIsomer(p);
PDepReaction pdeppathrxn = new PDepReaction(Reactants,Products,pathRxn);
newNetwork.addReaction(pdeppathrxn,true);
newNetwork.addIsomer(Reactants);
newNetwork.addIsomer(Products);
line = ChemParser.readMeaningfulLine(reader, true);
}
newNetwork.setAltered(false);
PDepNetwork.getNetworks().add(newNetwork);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public PDepIsomer parseIsomerFromRestartFile(String p_string) {
SpeciesDictionary sd = SpeciesDictionary.getInstance();
PDepIsomer isomer = null;
if (p_string.contains("+")) {
String[] indivReacts = p_string.split("[+]");
String name = indivReacts[0].trim();
Species spc1 = sd.getSpeciesFromNameID(name);
if (spc1 == null) {
spc1 = getSpeciesBySPCName(name,sd);
}
name = indivReacts[1].trim();
String[] nameANDincluded = name.split("\\(included =");
Species spc2 = sd.getSpeciesFromNameID(nameANDincluded[0].trim());
if (spc2 == null) {
spc2 = getSpeciesBySPCName(name,sd);
}
boolean isIncluded = Boolean.parseBoolean(nameANDincluded[1].substring(0,nameANDincluded[1].length()-1));
isomer = new PDepIsomer(spc1,spc2,isIncluded);
} else {
String name = p_string.trim();
/*
* Separate the (included =boolean) portion of the string
* from the name of the Isomer
*/
String[] nameANDincluded = name.split("\\(included =");
Species spc = sd.getSpeciesFromNameID(nameANDincluded[0].trim());
if (spc == null) {
spc = getSpeciesBySPCName(name,sd);
}
boolean isIncluded = Boolean.parseBoolean(nameANDincluded[1].substring(0,nameANDincluded[1].length()-1));
isomer = new PDepIsomer(spc,isIncluded);
}
return isomer;
}
public double[][] parseRateCoeffsFromRestartFile(int numFameTs, int numFamePs, BufferedReader reader) {
double[][] rateCoefficients = new double[numFameTs][numFamePs];
for (int i=0; i<numFameTs; i++) {
StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
for (int j=0; j<numFamePs; j++) {
rateCoefficients[i][j] = Double.parseDouble(st.nextToken());
}
}
return rateCoefficients;
}
public PDepRateConstant parsePDepRateConstantFromRestartFile(BufferedReader reader,
int numChebyTs, int numChebyPs, double[][] rateCoefficients,
int numPlogs, String EaUnits) {
PDepRateConstant pdepk = null;
if (numChebyTs > 0) {
double chebyPolys[][] = new double[numChebyTs][numChebyPs];
for (int i=0; i<numChebyTs; i++) {
StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
for (int j=0; j<numChebyPs; j++) {
chebyPolys[i][j] = Double.parseDouble(st.nextToken());
}
}
ChebyshevPolynomials chebyshev = new ChebyshevPolynomials(numChebyTs,
ChebyshevPolynomials.getTlow(), ChebyshevPolynomials.getTup(),
numChebyPs, ChebyshevPolynomials.getPlow(), ChebyshevPolynomials.getPup(),
chebyPolys);
pdepk = new PDepRateConstant(rateCoefficients,chebyshev);
} else if (numPlogs > 0) {
PDepArrheniusKinetics pdepAK = new PDepArrheniusKinetics(numPlogs);
for (int i=0; i<numPlogs; i++) {
StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
Pressure p = new Pressure(Double.parseDouble(st.nextToken()),"Pa");
UncertainDouble dA = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
UncertainDouble dn = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
double Ea = Double.parseDouble(st.nextToken());
if (EaUnits.equals("cal/mol"))
Ea = Ea / 1000;
else if (EaUnits.equals("J/mol"))
Ea = Ea / 4.184 / 1000;
else if (EaUnits.equals("kJ/mol"))
Ea = Ea / 4.184;
else if (EaUnits.equals("Kelvins"))
Ea = Ea * 1.987;
UncertainDouble dE = new UncertainDouble(Ea,0.0,"A");
ArrheniusKinetics k = new ArrheniusKinetics(dA, dn, dE, "", 1, "", "");
pdepAK.setKinetics(i, p, k);
pdepk = new PDepRateConstant(rateCoefficients,pdepAK);
}
}
return pdepk;
}
/**
* MRH 14Jan2010
*
* getSpeciesBySPCName
*
* Input: String name - Name of species, normally chemical formula followed
* by "J"s for radicals, and then (#)
* SpeciesDictionary sd
*
* This method was originally written as a complement to the method readPDepNetworks.
* jdmo found a bug with the readrestart option. The bug was that the method was
* attempting to add a null species to the Isomer list. The null species resulted
* from searching the SpeciesDictionary by chemkinName (e.g. C4H8OJJ(48)), when the
* chemkinName present in the dictionary was SPC(48).
*
*/
public Species getSpeciesBySPCName(String name, SpeciesDictionary sd) {
String[] nameFromNumber = name.split("\\(");
String newName = "SPC(" + nameFromNumber[1];
return sd.getSpeciesFromChemkinName(newName);
}
/**
* MRH 12-Jun-2009
*
* Function initializes the model's core and edge.
* The initial core species always consists of the species contained
* in the condition.txt file. If seed mechanisms exist, those species
* (and the reactions given in the seed mechanism) are also added to
* the core.
* The initial edge species/reactions are determined by reacting the core
* species by one full iteration.
*/
public void initializeCoreEdgeModel() {
LinkedHashSet allInitialCoreSpecies = new LinkedHashSet();
LinkedHashSet allInitialCoreRxns = new LinkedHashSet();
if (readrestart) {
allInitialCoreSpecies.addAll(restartCoreSpcs);
allInitialCoreRxns.addAll(restartCoreRxns);
}
// Add the species from the condition.txt (input) file
allInitialCoreSpecies.addAll(getSpeciesSeed());
// Add the species from the seed mechanisms, if they exist
if (hasSeedMechanisms()) {
allInitialCoreSpecies.addAll(getSeedMechanism().getSpeciesSet());
allInitialCoreRxns.addAll(getSeedMechanism().getReactionSet());
}
CoreEdgeReactionModel cerm = new CoreEdgeReactionModel(allInitialCoreSpecies, allInitialCoreRxns);
if (readrestart) {
cerm.addUnreactedSpeciesSet(restartEdgeSpcs);
cerm.addUnreactedReactionSet(restartEdgeRxns);
}
setReactionModel(cerm);
PDepNetwork.reactionModel = getReactionModel();
PDepNetwork.reactionSystem = (ReactionSystem) getReactionSystemList().get(0);
// Determine initial set of reactions and edge species using only the
// species enumerated in the input file and the seed mechanisms as the core
if (!readrestart) {
LinkedHashSet reactionSet_withdup;
LinkedHashSet reactionSet;
// If Seed Mechanism is present and Generate Reaction is set on
if (hasSeedMechanisms() && getSeedMechanism().shouldGenerateReactions()) {
reactionSet_withdup = getLibraryReactionGenerator().react(allInitialCoreSpecies);
reactionSet_withdup.addAll(getReactionGenerator().react(allInitialCoreSpecies));
// Removing Duplicates instances of reaction if present
reactionSet = getLibraryReactionGenerator().RemoveDuplicateReac(reactionSet_withdup);
// shamel 6/22/2010 Suppressed output , line is only for debugging
//System.out.println("Current Reaction Set after RModG + LRG and Removing Dups"+reactionSet);
}
else {
reactionSet_withdup = new LinkedHashSet();
//System.out.println("Initial Core Species RModG"+allInitialCoreSpecies);
LinkedHashSet tempnewReactionSet = getLibraryReactionGenerator().react(allInitialCoreSpecies);
if(!tempnewReactionSet.isEmpty()){
System.out.println("Reaction Set Found from Reaction Library "+tempnewReactionSet);
}
// Adds Reactions Found in Library Reaction Generator to Reaction Set
reactionSet_withdup.addAll(getLibraryReactionGenerator().react(allInitialCoreSpecies));
// shamel 6/22/2010 Suppressed output , line is only for debugging
//System.out.println("Current Reaction Set after LRG"+reactionSet_withdup);
// Generates Reaction from the Reaction Generator and adds them to Reaction Set
for (Iterator iter = speciesSeed.iterator(); iter.hasNext(); ) {
Species spec = (Species) iter.next();
reactionSet_withdup.addAll(getReactionGenerator().react(allInitialCoreSpecies, spec,"All"));
}
reactionSet = getLibraryReactionGenerator().RemoveDuplicateReac(reactionSet_withdup);
// shamel 6/22/2010 Suppressed output , line is only for debugging
//System.out.println("Current Reaction Set after RModG + LRG and Removing Dups"+reactionSet);
}
// Set initial core-edge reaction model based on above results
if (reactionModelEnlarger instanceof RateBasedRME) {
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
cerm.addReaction(r);
}
}
else {
// Only keep the reactions involving bimolecular reactants and bimolecular products
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
if (r.getReactantNumber() > 1 && r.getProductNumber() > 1){
cerm.addReaction(r);
}
else {
cerm.categorizeReaction(r.getStructure());
PDepNetwork.addReactionToNetworks(r);
}
}
}
}
/*
* 22-SEPT-2010
* ELSE:
* If reading in restart files, at the very least, we should react
* all species present in the input file (speciesSeed) with all of
* the coreSpecies. Before, when the following else statement was
* not present, we would completely skip this step. Thus, RMG would
* come to the first ODE solve, integrate to a very large time, and
* conclude that the model was both valid and terminated, thereby
* not adding any new reactions to the core regardless of the
* conditions stated in the input file.
* EXAMPLE:
* A user runs RMG for iso-octane with Restart turned on. The
* simulation converges and now the user would like to add a small
* amount of 1-butanol to the input file, while reading in from the
* Restart files. What should happen, at the very least, is 1-butanol
* reacts with the other species present in the input file and with
* the already-known coreSpecies. This will, at a minimum, add these
* reactions to the core. Whether the model remains validated and
* terminated depends on the conditions stated in the input file.
* MRH (mrharper@mit.edu)
*/
else {
LinkedHashSet reactionSet_withdup;
LinkedHashSet reactionSet;
/*
* If the user has specified a Seed Mechanism, and that the cross reactions
* should be generated, generate those here
* NOTE: Since the coreSpecies from the Restart files are treated as a Seed
* Mechanism, MRH is inclined to comment out the following lines. Depending
* on how large the Seed Mechanism and/or Restart files are, RMG could get
* "stuck" cross-reacting hundreds of species against each other.
*/
// if (hasSeedMechanisms() && getSeedMechanism().shouldGenerateReactions()) {
// reactionSet_withdup = getLibraryReactionGenerator().react(getSeedMechanism().getSpeciesSet());
// reactionSet_withdup.addAll(getReactionGenerator().react(getSeedMechanism().getSpeciesSet()));
// reactionSet = getLibraryReactionGenerator().RemoveDuplicateReac(reactionSet_withdup);
/*
* If not, react the species present in the input file against any
* reaction libraries, and then against all RMG-defined reaction
* families
*/
// else {
reactionSet_withdup = new LinkedHashSet();
LinkedHashSet tempnewReactionSet = getLibraryReactionGenerator().react(speciesSeed);
if (!tempnewReactionSet.isEmpty()) {
System.out.println("Reaction Set Found from Reaction Library "+tempnewReactionSet);
}
// Adds Reactions Found in Library Reaction Generator to Reaction Set
reactionSet_withdup.addAll(tempnewReactionSet);
// Generates Reaction from the Reaction Generator and adds them to Reaction Set
for (Iterator iter = speciesSeed.iterator(); iter.hasNext(); ) {
Species spec = (Species) iter.next();
reactionSet_withdup.addAll(getReactionGenerator().react(allInitialCoreSpecies,spec,"All"));
}
reactionSet = getLibraryReactionGenerator().RemoveDuplicateReac(reactionSet_withdup);
// Set initial core-edge reaction model based on above results
if (reactionModelEnlarger instanceof RateBasedRME) {
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
cerm.addReaction(r);
}
}
else {
// Only keep the reactions involving bimolecular reactants and bimolecular products
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
if (r.getReactantNumber() > 1 && r.getProductNumber() > 1){
cerm.addReaction(r);
}
else {
cerm.categorizeReaction(r.getStructure());
PDepNetwork.addReactionToNetworks(r);
}
}
}
}
for (Integer i = 0; i < reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i);
rs.setReactionModel(getReactionModel());
}
// We cannot return a system with no core reactions, so if this is a case we must add to the core
while (getReactionModel().isEmpty() && !PDepNetwork.hasCoreReactions((CoreEdgeReactionModel) getReactionModel())) {
for (Integer i = 0; i < reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i);
if (reactionModelEnlarger instanceof RateBasedPDepRME)
rs.initializePDepNetwork();
rs.appendUnreactedSpeciesStatus((InitialStatus)initialStatusList.get(i), rs.getPresentTemperature());
}
enlargeReactionModel();
}
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
rs.setReactionModel(getReactionModel());
}
return;
}
//9/24/07 gmagoon: moved from ReactionSystem.java
public void initializeCoreEdgeModelWithPKL() {
initializeCoreEdgeModelWithoutPKL();
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)getReactionModel();
LinkedHashSet primarySpeciesSet = getPrimaryKineticLibrary().getSpeciesSet(); //10/14/07 gmagoon: changed to use getPrimaryReactionLibrary
LinkedHashSet primaryKineticSet = getPrimaryKineticLibrary().getReactionSet();
cerm.addReactedSpeciesSet(primarySpeciesSet);
cerm.addPrimaryKineticSet(primaryKineticSet);
LinkedHashSet newReactions = getReactionGenerator().react(cerm.getReactedSpeciesSet());
if (reactionModelEnlarger instanceof RateBasedRME)
cerm.addReactionSet(newReactions);
else {
Iterator iter = newReactions.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
if (r.getReactantNumber() == 2 && r.getProductNumber() == 2){
cerm.addReaction(r);
}
}
}
return;
//
}
//9/24/07 gmagoon: moved from ReactionSystem.java
protected void initializeCoreEdgeModelWithoutPKL() {
CoreEdgeReactionModel cerm = new CoreEdgeReactionModel(new LinkedHashSet(getSpeciesSeed()));
setReactionModel(cerm);
PDepNetwork.reactionModel = getReactionModel();
PDepNetwork.reactionSystem = (ReactionSystem) getReactionSystemList().get(0);
// Determine initial set of reactions and edge species using only the
// species enumerated in the input file as the core
LinkedHashSet reactionSet = getReactionGenerator().react(getSpeciesSeed());
reactionSet.addAll(getLibraryReactionGenerator().react(getSpeciesSeed()));
// Set initial core-edge reaction model based on above results
if (reactionModelEnlarger instanceof RateBasedRME) {
// Only keep the reactions involving bimolecular reactants and bimolecular products
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
cerm.addReaction(r);
}
}
else {
// Only keep the reactions involving bimolecular reactants and bimolecular products
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
if (r.getReactantNumber() > 1 && r.getProductNumber() > 1){
cerm.addReaction(r);
}
else {
cerm.categorizeReaction(r.getStructure());
PDepNetwork.addReactionToNetworks(r);
}
}
}
//10/9/07 gmagoon: copy reactionModel to reactionSystem; there may still be scope problems, particularly in above elseif statement
//10/24/07 gmagoon: want to copy same reaction model to all reactionSystem variables; should probably also make similar modifications elsewhere; may or may not need to copy in ...WithPRL function
for (Integer i = 0; i < reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i);
rs.setReactionModel(getReactionModel());
}
//reactionSystem.setReactionModel(getReactionModel());
// We cannot return a system with no core reactions, so if this is a case we must add to the core
while (getReactionModel().isEmpty()&&!PDepNetwork.hasCoreReactions((CoreEdgeReactionModel) getReactionModel())) {
for (Integer i = 0; i < reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i);
if (reactionModelEnlarger instanceof RateBasedPDepRME)
rs.initializePDepNetwork();
rs.appendUnreactedSpeciesStatus((InitialStatus)initialStatusList.get(i), rs.getPresentTemperature());
}
enlargeReactionModel();
}
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
rs.setReactionModel(getReactionModel());
}
return;
//
}
//## operation initializeCoreEdgeReactionModel()
//9/24/07 gmagoon: moved from ReactionSystem.java
public void initializeCoreEdgeReactionModel() {
System.out.println("\nInitializing core-edge reaction model");
// setSpeciesSeed(new LinkedHashSet());//10/4/07 gmagoon:moved from initializeReactionSystem; later moved to modelGeneration()
//#[ operation initializeCoreEdgeReactionModel()
// if (hasPrimaryKineticLibrary()) initializeCoreEdgeModelWithPKL();
// else initializeCoreEdgeModelWithoutPKL();
/*
* MRH 12-Jun-2009
*
* I've lumped the initializeCoreEdgeModel w/ and w/o a seed mechanism
* (which used to be the PRL) into one function. Before, RMG would
* complete one iteration (construct the edge species/rxns) before adding
* the seed mechanism to the rxn, thereby possibly estimating kinetic
* parameters for a rxn that exists in a seed mechanism
*/
initializeCoreEdgeModel();
//
}
//9/24/07 gmagoon: copied from ReactionSystem.java
public ReactionGenerator getReactionGenerator() {
return reactionGenerator;
}
//10/4/07 gmagoon: moved from ReactionSystem.java
public void setReactionGenerator(ReactionGenerator p_ReactionGenerator) {
reactionGenerator = p_ReactionGenerator;
}
//9/25/07 gmagoon: moved from ReactionSystem.java
//10/24/07 gmagoon: changed to use reactionSystemList
//## operation enlargeReactionModel()
public void enlargeReactionModel() {
//#[ operation enlargeReactionModel()
if (reactionModelEnlarger == null) throw new NullPointerException("ReactionModelEnlarger");
System.out.println("\nEnlarging reaction model");
reactionModelEnlarger.enlargeReactionModel(reactionSystemList, reactionModel, validList);
return;
//
}
public void pruneReactionModel(HashMap unprunableSpecies) {
HashMap prunableSpeciesMap = new HashMap();
//check whether all the reaction systems reached target conversion/time
boolean allReachedTarget = true;
for (Integer i = 0; i < reactionSystemList.size(); i++) {
JDAS ds = (JDAS)((ReactionSystem) reactionSystemList.get(i)).getDynamicSimulator();
if (!ds.targetReached) allReachedTarget = false;
}
JDAS ds0 = (JDAS)((ReactionSystem) reactionSystemList.get(0)).getDynamicSimulator(); //get the first reactionSystem dynamic simulator
//prune the reaction model if AUTO is being used, and all reaction systems have reached target time/conversion, and edgeTol is non-zero (and positive, obviously), and if there are a sufficient number of species in the reaction model (edge + core)
if ( JDAS.autoflag &&
allReachedTarget &&
edgeTol>0 &&
(((CoreEdgeReactionModel)reactionModel).getEdge().getSpeciesNumber()+reactionModel.getSpeciesNumber())>= minSpeciesForPruning){
int numberToBePruned = ((CoreEdgeReactionModel)reactionModel).getEdge().getSpeciesNumber() - maxEdgeSpeciesAfterPruning;
System.out.println("PDep Pruning DEBUG:\nThe number of species in the model's edge, before pruning: " + ((CoreEdgeReactionModel)reactionModel).getEdge().getSpeciesNumber());
System.out.println("PDep Pruning DEBUG:\nRMG thinks the following number of species" +
" needs to be pruned: " + numberToBePruned);
Iterator iter = JDAS.edgeID.keySet().iterator();//determine the maximum edge flux ratio for each edge species
while(iter.hasNext()){
Species spe = (Species)iter.next();
Integer id = (Integer)JDAS.edgeID.get(spe);
double maxmaxRatio = ds0.maxEdgeFluxRatio[id-1];
boolean prunable = ds0.prunableSpecies[id-1];
for (Integer i = 1; i < reactionSystemList.size(); i++) {//go through the rest of the reaction systems to see if there are higher max flux ratios
JDAS ds = (JDAS)((ReactionSystem) reactionSystemList.get(i)).getDynamicSimulator();
if(ds.maxEdgeFluxRatio[id-1] > maxmaxRatio) maxmaxRatio = ds.maxEdgeFluxRatio[id-1];
if(prunable && !ds.prunableSpecies[id-1]) prunable = false;//I can't imagine a case where this would occur (if the conc. is zero at one condition, it should be zero at all conditions), but it is included for completeness
}
//if the maximum max edge flux ratio is less than the edge inclusion threshhold and the species is "prunable" (i.e. it doesn't have any reactions producing it with zero flux), schedule the species for pruning
if( prunable){ // && maxmaxRatio < edgeTol
prunableSpeciesMap.put(spe, maxmaxRatio);
// at this point prunableSpecies includes ALL prunable species, no matter how large their flux
}
}
System.out.println("PDep Pruning DEBUG:\nRMG has marked the following number of species" +
" to be pruned, before checking against explored (included) species: " + prunableSpeciesMap.size());
// Pressure dependence only: Species that are included in any
// PDepNetwork are not eligible for pruning, so they must be removed
// from the map of prunable species
if (reactionModelEnlarger instanceof RateBasedPDepRME) {
LinkedList speciesToRemove = new LinkedList();
for (iter = prunableSpeciesMap.keySet().iterator(); iter.hasNext(); ) {
Species spec = (Species) iter.next();
if (PDepNetwork.isSpeciesIncludedInAnyNetwork(spec))
speciesToRemove.add(spec);
}
for (iter = speciesToRemove.iterator(); iter.hasNext(); ) {
prunableSpeciesMap.remove(iter.next());
}
}
System.out.println("PDep Pruning DEBUG:\nRMG now has marked the following number of species" +
" to be pruned, after checking against explored (included) species: " + prunableSpeciesMap.size());
// sort the prunableSpecies by maxmaxRatio
// i.e. sort the map by values
List prunableSpeciesList = new LinkedList(prunableSpeciesMap.entrySet());
Collections.sort(prunableSpeciesList, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o1)).getValue())
.compareTo(((Map.Entry) (o2)).getValue());
}
});
List speciesToPrune = new LinkedList();
int belowThreshold = 0;
int lowMaxFlux = 0;
for (Iterator it = prunableSpeciesList.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
Species spe = (Species)entry.getKey();
double maxmaxRatio = (Double)entry.getValue();
if (maxmaxRatio < edgeTol)
{
System.out.println("Edge species "+spe.getChemkinName() +" has a maximum flux ratio ("+maxmaxRatio+") lower than edge inclusion threshhold and will be pruned.");
speciesToPrune.add(spe);
++belowThreshold;
}
else if ( numberToBePruned - speciesToPrune.size() > 0 ) {
System.out.println("Edge species "+spe.getChemkinName() +" has a low maximum flux ratio ("+maxmaxRatio+") and will be pruned to reduce the edge size to the maximum ("+maxEdgeSpeciesAfterPruning+").");
speciesToPrune.add(spe);
++lowMaxFlux;
}
else break; // no more to be pruned
}
System.out.println("PDep Pruning DEBUG:\nRMG has marked the following number of species" +
" to be pruned due to max flux ratio lower than threshold: " + belowThreshold);
System.out.println("PDep Pruning DEBUG:\nRMG has marked the following number of species" +
" to be pruned due to low max flux ratio : " + lowMaxFlux);
//now, speciesToPrune has been filled with species that should be pruned from the edge
System.out.println("Pruning...");
//prune species from the edge
//remove species from the edge and from the species dictionary and from edgeID
iter = speciesToPrune.iterator();
while(iter.hasNext()){
Species spe = (Species)iter.next();
writePrunedEdgeSpecies(spe);
((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().remove(spe);
//SpeciesDictionary.getInstance().getSpeciesSet().remove(spe);
if (!unprunableSpecies.containsValue(spe))
SpeciesDictionary.getInstance().remove(spe);
else System.out.println("Pruning Message: Not removing the following species " +
"from the SpeciesDictionary\nas it is present in a Primary Kinetic / Reaction" +
" Library\nThe species will still be removed from the Edge of the " +
"Reaction Mechanism\n" + spe.toString());
JDAS.edgeID.remove(spe);
}
//remove reactions from the edge involving pruned species
iter = ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().iterator();
HashSet toRemove = new HashSet();
while(iter.hasNext()){
Reaction reaction = (Reaction)iter.next();
if (reactionPrunableQ(reaction, speciesToPrune)) toRemove.add(reaction);
}
iter = toRemove.iterator();
while(iter.hasNext()){
Reaction reaction = (Reaction)iter.next();
writePrunedEdgeReaction(reaction);
Reaction reverse = reaction.getReverseReaction();
((CoreEdgeReactionModel)reactionModel).removeFromUnreactedReactionSet(reaction);
((CoreEdgeReactionModel)reactionModel).removeFromUnreactedReactionSet(reverse);
ReactionTemplate rt = reaction.getReactionTemplate();
ReactionTemplate rtr = null;
if(reverse!=null){
rtr = reverse.getReactionTemplate();
}
if(rt!=null){
rt.removeFromReactionDictionaryByStructure(reaction.getStructure());//remove from ReactionTemplate's reactionDictionaryByStructure
}
if(rtr!=null){
rtr.removeFromReactionDictionaryByStructure(reverse.getStructure());
}
if ((reaction.isForward() && reaction.getKineticsSource(0).contains("Library")) ||
(reaction.isBackward() && reaction.getReverseReaction().getKineticsSource(0).contains("Library")))
continue;
reaction.setStructure(null);
if(reverse!=null){
reverse.setStructure(null);
}
}
//remove reactions from PDepNetworks in PDep cases
if (reactionModelEnlarger instanceof RateBasedPDepRME) {
iter = PDepNetwork.getNetworks().iterator();
HashSet pdnToRemove = new HashSet();
HashSet toRemovePath;
HashSet toRemoveNet;
HashSet toRemoveNonincluded;
HashSet toRemoveIsomer;
while (iter.hasNext()){
PDepNetwork pdn = (PDepNetwork)iter.next();
//identify path reactions to remove
Iterator rIter = pdn.getPathReactions().iterator();
toRemovePath = new HashSet();
while(rIter.hasNext()){
Reaction reaction = (Reaction)rIter.next();
if (reactionPrunableQ(reaction, speciesToPrune)) toRemovePath.add(reaction);
}
//identify net reactions to remove
rIter = pdn.getNetReactions().iterator();
toRemoveNet = new HashSet();
while(rIter.hasNext()){
Reaction reaction = (Reaction)rIter.next();
if (reactionPrunableQ(reaction, speciesToPrune)) toRemoveNet.add(reaction);
}
//identify nonincluded reactions to remove
rIter = pdn.getNonincludedReactions().iterator();
toRemoveNonincluded = new HashSet();
while(rIter.hasNext()){
Reaction reaction = (Reaction)rIter.next();
if (reactionPrunableQ(reaction, speciesToPrune)) toRemoveNonincluded.add(reaction);
}
//identify isomers to remove
Iterator iIter = pdn.getIsomers().iterator();
toRemoveIsomer = new HashSet();
while(iIter.hasNext()){
PDepIsomer pdi = (PDepIsomer)iIter.next();
Iterator isIter = pdi.getSpeciesListIterator();
while(isIter.hasNext()){
Species spe = (Species)isIter.next();
if (speciesToPrune.contains(spe)&&!toRemove.contains(pdi)) toRemoveIsomer.add(pdi);
}
if(pdi.getSpeciesList().size()==0 && !toRemove.contains(pdi)) toRemoveIsomer.add(pdi);//if the pdi doesn't contain any species, schedule it for removal
}
//remove path reactions
Iterator iterRem = toRemovePath.iterator();
while(iterRem.hasNext()){
Reaction reaction = (Reaction)iterRem.next();
Reaction reverse = reaction.getReverseReaction();
pdn.removeFromPathReactionList((PDepReaction)reaction);
pdn.removeFromPathReactionList((PDepReaction)reverse);
ReactionTemplate rt = reaction.getReactionTemplate();
ReactionTemplate rtr = null;
if(reverse!=null){
rtr = reverse.getReactionTemplate();
}
if(rt!=null){
rt.removeFromReactionDictionaryByStructure(reaction.getStructure());//remove from ReactionTemplate's reactionDictionaryByStructure
}
if(rtr!=null){
rtr.removeFromReactionDictionaryByStructure(reverse.getStructure());
}
if ((reaction.isForward() && reaction.getKineticsSource(0).contains("Library")) ||
(reaction.isBackward() && reaction.getReverseReaction().getKineticsSource(0).contains("Library")))
continue;
reaction.setStructure(null);
if(reverse!=null){
reverse.setStructure(null);
}
}
//remove net reactions
iterRem = toRemoveNet.iterator();
while(iterRem.hasNext()){
Reaction reaction = (Reaction)iterRem.next();
Reaction reverse = reaction.getReverseReaction();
pdn.removeFromNetReactionList((PDepReaction)reaction);
pdn.removeFromNetReactionList((PDepReaction)reverse);
ReactionTemplate rt = reaction.getReactionTemplate();
ReactionTemplate rtr = null;
if(reverse!=null){
rtr = reverse.getReactionTemplate();
}
if(rt!=null){
rt.removeFromReactionDictionaryByStructure(reaction.getStructure());//remove from ReactionTemplate's reactionDictionaryByStructure
}
if(rtr!=null){
rtr.removeFromReactionDictionaryByStructure(reverse.getStructure());
}
reaction.setStructure(null);
if(reverse!=null){
reverse.setStructure(null);
}
}
//remove nonincluded reactions
iterRem = toRemoveNonincluded.iterator();
while(iterRem.hasNext()){
Reaction reaction = (Reaction)iterRem.next();
Reaction reverse = reaction.getReverseReaction();
pdn.removeFromNonincludedReactionList((PDepReaction)reaction);
pdn.removeFromNonincludedReactionList((PDepReaction)reverse);
ReactionTemplate rt = reaction.getReactionTemplate();
ReactionTemplate rtr = null;
if(reverse!=null){
rtr = reverse.getReactionTemplate();
}
if(rt!=null){
rt.removeFromReactionDictionaryByStructure(reaction.getStructure());//remove from ReactionTemplate's reactionDictionaryByStructure
}
if(rtr!=null){
rtr.removeFromReactionDictionaryByStructure(reverse.getStructure());
}
reaction.setStructure(null);
if(reverse!=null){
reverse.setStructure(null);
}
}
//remove isomers
iterRem = toRemoveIsomer.iterator();
while(iterRem.hasNext()){
PDepIsomer pdi = (PDepIsomer)iterRem.next();
pdn.removeFromIsomerList(pdi);
}
//remove the entire network if the network has no path or net reactions
if(pdn.getPathReactions().size()==0&&pdn.getNetReactions().size()==0) pdnToRemove.add(pdn);
}
iter = pdnToRemove.iterator();
while (iter.hasNext()){
PDepNetwork pdn = (PDepNetwork)iter.next();
PDepNetwork.getNetworks().remove(pdn);
}
}
}
System.out.println("PDep Pruning DEBUG:\nThe number of species in the model's edge, after pruning: " + ((CoreEdgeReactionModel)reactionModel).getEdge().getSpeciesNumber());
return;
}
//determines whether a reaction can be removed; returns true ; cf. categorizeReaction() in CoreEdgeReactionModel
//returns true if the reaction involves reactants or products that are in p_prunableSpecies; otherwise returns false
public boolean reactionPrunableQ(Reaction p_reaction, Collection p_prunableSpecies){
Iterator iter = p_reaction.getReactants();
while (iter.hasNext()) {
Species spe = (Species)iter.next();
if (p_prunableSpecies.contains(spe))
return true;
}
iter = p_reaction.getProducts();
while (iter.hasNext()) {
Species spe = (Species)iter.next();
if (p_prunableSpecies.contains(spe))
return true;
}
return false;
}
public boolean hasPrimaryKineticLibrary() {
if (primaryKineticLibrary == null) return false;
return (primaryKineticLibrary.size() > 0);
}
public boolean hasSeedMechanisms() {
if (getSeedMechanism() == null) return false;
return (seedMechanism.size() > 0);
}
//9/25/07 gmagoon: moved from ReactionSystem.java
public PrimaryKineticLibrary getPrimaryKineticLibrary() {
return primaryKineticLibrary;
}
//9/25/07 gmagoon: moved from ReactionSystem.java
public void setPrimaryKineticLibrary(PrimaryKineticLibrary p_PrimaryKineticLibrary) {
primaryKineticLibrary = p_PrimaryKineticLibrary;
}
public ReactionLibrary getReactionLibrary() {
return ReactionLibrary;
}
public void setReactionLibrary(ReactionLibrary p_ReactionLibrary) {
ReactionLibrary = p_ReactionLibrary;
}
//10/4/07 gmagoon: added
public LinkedHashSet getSpeciesSeed() {
return speciesSeed;
}
//10/4/07 gmagoon: added
public void setSpeciesSeed(LinkedHashSet p_speciesSeed) {
speciesSeed = p_speciesSeed;
}
//10/4/07 gmagoon: added
public LibraryReactionGenerator getLibraryReactionGenerator() {
return lrg;
}
//10/4/07 gmagoon: added
public void setLibraryReactionGenerator(LibraryReactionGenerator p_lrg) {
lrg = p_lrg;
}
public static Temperature getTemp4BestKinetics() {
return temp4BestKinetics;
}
public static void setTemp4BestKinetics(Temperature firstSysTemp) {
temp4BestKinetics = firstSysTemp;
}
public SeedMechanism getSeedMechanism() {
return seedMechanism;
}
public void setSeedMechanism(SeedMechanism p_seedMechanism) {
seedMechanism = p_seedMechanism;
}
public PrimaryThermoLibrary getPrimaryThermoLibrary() {
return primaryThermoLibrary;
}
public void setPrimaryThermoLibrary(PrimaryThermoLibrary p_primaryThermoLibrary) {
primaryThermoLibrary = p_primaryThermoLibrary;
}
public static double getAtol(){
return atol;
}
public boolean runKillableToPreventInfiniteLoop(boolean intermediateSteps, int iterationNumber) {
ReactionSystem rs0 = (ReactionSystem)reactionSystemList.get(0);
if (!intermediateSteps)//if there are no intermediate steps (for example when using AUTO method), return true;
return true;
//if there are intermediate steps, the run is killable if the iteration number exceeds the number of time steps / conversions
else if (rs0.finishController.terminationTester instanceof ReactionTimeTT){
if (iterationNumber - 1 > timeStep.size()){ //-1 correction needed since when this is called, iteration number has been incremented
return true;
}
}
else //the case where intermediate conversions are specified
if (iterationNumber - 1 > numConversions){ //see above; it is possible there is an off-by-one error here, so further testing will be needed
return true;
}
return false; //return false if none of the above criteria are met
}
public void readAndMakePKL(BufferedReader reader) throws IOException {
int Ilib = 0;
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
String[] tempString = line.split("Name: ");
String name = tempString[tempString.length-1].trim();
line = ChemParser.readMeaningfulLine(reader, true);
tempString = line.split("Location: ");
String location = tempString[tempString.length-1].trim();
String path = System.getProperty("jing.rxn.ReactionLibrary.pathName");
path += "/" + location;
if (Ilib==0) {
setPrimaryKineticLibrary(new PrimaryKineticLibrary(name, path));
Ilib++;
}
else {
getPrimaryKineticLibrary().appendPrimaryKineticLibrary(name, path);
Ilib++;
}
line = ChemParser.readMeaningfulLine(reader, true);
}
if (Ilib==0) {
setPrimaryKineticLibrary(null);
}
else System.out.println("Primary Kinetic Libraries in use: " + getPrimaryKineticLibrary().getName());
}
public void readAndMakeReactionLibrary(BufferedReader reader) throws IOException {
int Ilib = 0;
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
String[] tempString = line.split("Name: ");
String name = tempString[tempString.length-1].trim();
line = ChemParser.readMeaningfulLine(reader, true);
tempString = line.split("Location: ");
String location = tempString[tempString.length-1].trim();
String path = System.getProperty("jing.rxn.ReactionLibrary.pathName");
path += "/" + location;
if (Ilib==0) {
setReactionLibrary(new ReactionLibrary(name, path));
Ilib++;
}
else {
getReactionLibrary().appendReactionLibrary(name, path);
Ilib++;
}
line = ChemParser.readMeaningfulLine(reader, true);
}
if (Ilib==0) {
setReactionLibrary(null);
}
else System.out.println("Reaction Libraries in use: " + getReactionLibrary().getName());
}
public void readAndMakePTL(BufferedReader reader) {
int numPTLs = 0;
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
String[] tempString = line.split("Name: ");
String name = tempString[tempString.length-1].trim();
line = ChemParser.readMeaningfulLine(reader, true);
tempString = line.split("Location: ");
String path = tempString[tempString.length-1].trim();
if (numPTLs==0) {
setPrimaryThermoLibrary(new PrimaryThermoLibrary(name,path));
++numPTLs;
}
else {
getPrimaryThermoLibrary().appendPrimaryThermoLibrary(name,path);
++numPTLs;
}
line = ChemParser.readMeaningfulLine(reader, true);
}
if (numPTLs == 0) setPrimaryThermoLibrary(null);
}
public void readExtraForbiddenStructures(BufferedReader reader) throws IOException {
System.out.println("Reading extra forbidden structures from input file.");
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
StringTokenizer token = new StringTokenizer(line);
String fgname = token.nextToken();
Graph fgGraph = null;
try {
fgGraph = ChemParser.readFGGraph(reader);
}
catch (InvalidGraphFormatException e) {
System.out.println("Invalid functional group in "+fgname);
throw new InvalidFunctionalGroupException(fgname + ": " + e.getMessage());
}
if (fgGraph == null) throw new InvalidFunctionalGroupException(fgname);
FunctionalGroup fg = FunctionalGroup.makeForbiddenStructureFG(fgname, fgGraph);
ChemGraph.addForbiddenStructure(fg);
line = ChemParser.readMeaningfulLine(reader, true);
System.out.println(" Forbidden structure: "+fgname);
}
}
public void setSpectroscopicDataMode(String line) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String sdeType = st.nextToken().toLowerCase();
if (sdeType.equals("frequencygroups") || sdeType.equals("default")) {
SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
}
else if (sdeType.equals("therfit") || sdeType.equals("threefrequencymodel")) {
SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
}
else if (sdeType.equals("off") || sdeType.equals("none")) {
SpectroscopicData.mode = SpectroscopicData.Mode.OFF;
}
else throw new InvalidSymbolException("condition.txt: Unknown SpectroscopicDataEstimator = " + sdeType);
}
/**
* Sets the pressure dependence options to on or off. If on, checks for
* more options and sets them as well.
* @param line The current line in the condition file; should start with "PressureDependence:"
* @param reader The reader currently being used to parse the condition file
*/
public String setPressureDependenceOptions(String line, BufferedReader reader) throws InvalidSymbolException {
// Determine pressure dependence mode
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken(); // Should be "PressureDependence:"
String pDepType = st.nextToken();
if (pDepType.toLowerCase().equals("off")) {
// No pressure dependence
reactionModelEnlarger = new RateBasedRME();
PDepNetwork.generateNetworks = false;
/*
* If the Spectroscopic Data Estimator field is set to "Frequency Groups,"
* terminate the RMG job and inform the user to either:
* a) Set the Spectroscopic Data Estimator field to "off," OR
* b) Select a pressure-dependent model
*
* Before, RMG would read in "Frequency Groups" with no pressure-dependence
* and carry on. However, the calculated frequencies would not be stored /
* reported (plus increase the runtime), so no point in calculating them.
*/
if (SpectroscopicData.mode != SpectroscopicData.mode.OFF) {
System.err.println("Terminating RMG simulation: User requested frequency estimation, " +
"yet no pressure-dependence.\nSUGGESTION: Set the " +
"SpectroscopicDataEstimator field in the input file to 'off'.");
System.exit(0);
}
line = ChemParser.readMeaningfulLine(reader, true);
}
else if (pDepType.toLowerCase().equals("modifiedstrongcollision") ||
pDepType.toLowerCase().equals("reservoirstate") ||
pDepType.toLowerCase().equals("chemdis")) {
reactionModelEnlarger = new RateBasedPDepRME();
PDepNetwork.generateNetworks = true;
// Set pressure dependence method
if (pDepType.toLowerCase().equals("reservoirstate"))
((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new FastMasterEqn(FastMasterEqn.Mode.RESERVOIRSTATE));
else if (pDepType.toLowerCase().equals("modifiedstrongcollision"))
((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new FastMasterEqn(FastMasterEqn.Mode.STRONGCOLLISION));
//else if (pDepType.toLowerCase().equals("chemdis"))
// ((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new Chemdis());
else
throw new InvalidSymbolException("condition.txt: Unknown PressureDependence mode = " + pDepType);
RateBasedPDepRME pdepModelEnlarger = (RateBasedPDepRME) reactionModelEnlarger;
// Turn on spectroscopic data estimation if not already on
if (pdepModelEnlarger.getPDepKineticsEstimator() instanceof FastMasterEqn && SpectroscopicData.mode == SpectroscopicData.Mode.OFF) {
System.out.println("Warning: Spectroscopic data needed for pressure dependence; switching SpectroscopicDataEstimator to FrequencyGroups.");
SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
}
else if (pdepModelEnlarger.getPDepKineticsEstimator() instanceof Chemdis && SpectroscopicData.mode != SpectroscopicData.Mode.THREEFREQUENCY) {
System.out.println("Warning: Switching SpectroscopicDataEstimator to three-frequency model.");
SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
}
// Next line must be PDepKineticsModel
line = ChemParser.readMeaningfulLine(reader, true);
if (line.toLowerCase().startsWith("pdepkineticsmodel:")) {
st = new StringTokenizer(line);
name = st.nextToken();
String pDepKinType = st.nextToken();
if (pDepKinType.toLowerCase().equals("chebyshev")) {
PDepRateConstant.setMode(PDepRateConstant.Mode.CHEBYSHEV);
// Default is to cubic order for basis functions
FastMasterEqn.setNumTBasisFuncs(4);
FastMasterEqn.setNumPBasisFuncs(4);
}
else if (pDepKinType.toLowerCase().equals("pdeparrhenius"))
PDepRateConstant.setMode(PDepRateConstant.Mode.PDEPARRHENIUS);
else if (pDepKinType.toLowerCase().equals("rate"))
PDepRateConstant.setMode(PDepRateConstant.Mode.RATE);
else
throw new InvalidSymbolException("condition.txt: Unknown PDepKineticsModel = " + pDepKinType);
// For Chebyshev polynomials, optionally specify the number of
// temperature and pressure basis functions
// Such a line would read, e.g.: "PDepKineticsModel: Chebyshev 4 4"
if (st.hasMoreTokens() && PDepRateConstant.getMode() == PDepRateConstant.Mode.CHEBYSHEV) {
try {
int numTBasisFuncs = Integer.parseInt(st.nextToken());
int numPBasisFuncs = Integer.parseInt(st.nextToken());
FastMasterEqn.setNumTBasisFuncs(numTBasisFuncs);
FastMasterEqn.setNumPBasisFuncs(numPBasisFuncs);
}
catch (NoSuchElementException e) {
throw new InvalidSymbolException("condition.txt: Missing number of pressure basis functions for Chebyshev polynomials.");
}
}
}
else
throw new InvalidSymbolException("condition.txt: Missing PDepKineticsModel after PressureDependence line.");
// Determine temperatures and pressures to use
// These can be specified automatically using TRange and PRange or
// manually using Temperatures and Pressures
Temperature[] temperatures = null;
Pressure[] pressures = null;
String Tunits = "K";
Temperature Tmin = new Temperature(300.0, "K");
Temperature Tmax = new Temperature(2000.0, "K");
int Tnumber = 8;
String Punits = "bar";
Pressure Pmin = new Pressure(0.01, "bar");
Pressure Pmax = new Pressure(100.0, "bar");
int Pnumber = 5;
// Read next line of input
line = ChemParser.readMeaningfulLine(reader, true);
boolean done = !(line.toLowerCase().startsWith("trange:") ||
line.toLowerCase().startsWith("prange:") ||
line.toLowerCase().startsWith("temperatures:") ||
line.toLowerCase().startsWith("pressures:"));
// Parse lines containing pressure dependence options
// Possible options are "TRange:", "PRange:", "Temperatures:", and "Pressures:"
// You must specify either TRange or Temperatures and either PRange or Pressures
// The order does not matter
while (!done) {
st = new StringTokenizer(line);
name = st.nextToken();
if (line.toLowerCase().startsWith("trange:")) {
Tunits = ChemParser.removeBrace(st.nextToken());
Tmin = new Temperature(Double.parseDouble(st.nextToken()), Tunits);
Tmax = new Temperature(Double.parseDouble(st.nextToken()), Tunits);
Tnumber = Integer.parseInt(st.nextToken());
}
else if (line.toLowerCase().startsWith("prange:")) {
Punits = ChemParser.removeBrace(st.nextToken());
Pmin = new Pressure(Double.parseDouble(st.nextToken()), Punits);
Pmax = new Pressure(Double.parseDouble(st.nextToken()), Punits);
Pnumber = Integer.parseInt(st.nextToken());
}
else if (line.toLowerCase().startsWith("temperatures:")) {
Tnumber = Integer.parseInt(st.nextToken());
Tunits = ChemParser.removeBrace(st.nextToken());
temperatures = new Temperature[Tnumber];
for (int i = 0; i < Tnumber; i++) {
temperatures[i] = new Temperature(Double.parseDouble(st.nextToken()), Tunits);
}
Tmin = temperatures[0];
Tmax = temperatures[Tnumber-1];
}
else if (line.toLowerCase().startsWith("pressures:")) {
Pnumber = Integer.parseInt(st.nextToken());
Punits = ChemParser.removeBrace(st.nextToken());
pressures = new Pressure[Pnumber];
for (int i = 0; i < Pnumber; i++) {
pressures[i] = new Pressure(Double.parseDouble(st.nextToken()), Punits);
}
Pmin = pressures[0];
Pmax = pressures[Pnumber-1];
}
// Read next line of input
line = ChemParser.readMeaningfulLine(reader, true);
done = !(line.toLowerCase().startsWith("trange:") ||
line.toLowerCase().startsWith("prange:") ||
line.toLowerCase().startsWith("temperatures:") ||
line.toLowerCase().startsWith("pressures:"));
}
// Set temperatures and pressures (if not already set manually)
if (temperatures == null) {
temperatures = new Temperature[Tnumber];
if (PDepRateConstant.getMode() == PDepRateConstant.Mode.CHEBYSHEV) {
// Use the Gauss-Chebyshev points
// The formula for the Gauss-Chebyshev points was taken from
// the Chemkin theory manual
for (int i = 1; i <= Tnumber; i++) {
double T = -Math.cos((2 * i - 1) * Math.PI / (2 * Tnumber));
T = 2.0 / ((1.0/Tmax.getK() - 1.0/Tmin.getK()) * T + 1.0/Tmax.getK() + 1.0/Tmin.getK());
temperatures[i-1] = new Temperature(T, "K");
}
}
else {
// Distribute equally on a 1/T basis
double slope = (1.0/Tmax.getK() - 1.0/Tmin.getK()) / (Tnumber - 1);
for (int i = 0; i < Tnumber; i++) {
double T = 1.0/(slope * i + 1.0/Tmin.getK());
temperatures[i] = new Temperature(T, "K");
}
}
}
if (pressures == null) {
pressures = new Pressure[Pnumber];
if (PDepRateConstant.getMode() == PDepRateConstant.Mode.CHEBYSHEV) {
// Use the Gauss-Chebyshev points
// The formula for the Gauss-Chebyshev points was taken from
// the Chemkin theory manual
for (int i = 1; i <= Pnumber; i++) {
double P = -Math.cos((2 * i - 1) * Math.PI / (2 * Pnumber));
P = Math.pow(10, 0.5 * ((Math.log10(Pmax.getBar()) - Math.log10(Pmin.getBar())) * P + Math.log10(Pmax.getBar()) + Math.log10(Pmin.getBar())));
pressures[i-1] = new Pressure(P, "bar");
}
}
else {
// Distribute equally on a log P basis
double slope = (Math.log10(Pmax.getBar()) - Math.log10(Pmin.getBar())) / (Pnumber - 1);
for (int i = 0; i < Pnumber; i++) {
double P = Math.pow(10, slope * i + Math.log10(Pmin.getBar()));
pressures[i] = new Pressure(P, "bar");
}
}
}
FastMasterEqn.setTemperatures(temperatures);
PDepRateConstant.setTemperatures(temperatures);
PDepRateConstant.setTMin(Tmin);
PDepRateConstant.setTMax(Tmax);
ChebyshevPolynomials.setTlow(Tmin);
ChebyshevPolynomials.setTup(Tmax);
FastMasterEqn.setPressures(pressures);
PDepRateConstant.setPressures(pressures);
PDepRateConstant.setPMin(Pmin);
PDepRateConstant.setPMax(Pmax);
ChebyshevPolynomials.setPlow(Pmin);
ChebyshevPolynomials.setPup(Pmax);
/*
* New option for input file: DecreaseGrainSize
* User now has the option to re-run fame with additional grains
* (smaller grain size) when the p-dep rate exceeds the
* high-P-limit rate.
* Default value: off
*/
if (line.toLowerCase().startsWith("decreasegrainsize")) {
st = new StringTokenizer(line);
String tempString = st.nextToken(); // "DecreaseGrainSize:"
tempString = st.nextToken().trim().toLowerCase();
if (tempString.equals("on") || tempString.equals("yes") ||
tempString.equals("true")) {
rerunFame = true;
} else rerunFame = false;
line = ChemParser.readMeaningfulLine(reader, true);
}
}
else {
throw new InvalidSymbolException("condition.txt: Unknown PressureDependence = " + pDepType);
}
return line;
}
public void createTModel(String line) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String modelType = st.nextToken();
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (modelType.equals("Constant")) {
tempList = new LinkedList();
//read first temperature
double t = Double.parseDouble(st.nextToken());
tempList.add(new ConstantTM(t, unit));
Temperature temp = new Temperature(t, unit);//10/29/07 gmagoon: added this line and next two lines to set Global.lowTemperature and Global.highTemperature
Global.lowTemperature = (Temperature)temp.clone();
Global.highTemperature = (Temperature)temp.clone();
//read remaining temperatures
while (st.hasMoreTokens()) {
t = Double.parseDouble(st.nextToken());
tempList.add(new ConstantTM(t, unit));
temp = new Temperature(t,unit);//10/29/07 gmagoon: added this line and next two "if" statements to set Global.lowTemperature and Global.highTemperature
if(temp.getK() < Global.lowTemperature.getK())
Global.lowTemperature = (Temperature)temp.clone();
if(temp.getK() > Global.highTemperature.getK())
Global.highTemperature = (Temperature)temp.clone();
}
}
else {
throw new InvalidSymbolException("condition.txt: Unknown TemperatureModel = " + modelType);
}
}
public void createPModel(String line) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String modelType = st.nextToken();
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (modelType.equals("Constant")) {
presList = new LinkedList();
//read first pressure
double p = Double.parseDouble(st.nextToken());
Pressure pres = new Pressure(p, unit);
Global.lowPressure = (Pressure)pres.clone();
Global.highPressure = (Pressure)pres.clone();
presList.add(new ConstantPM(p, unit));
//read remaining temperatures
while (st.hasMoreTokens()) {
p = Double.parseDouble(st.nextToken());
presList.add(new ConstantPM(p, unit));
pres = new Pressure(p, unit);
if(pres.getBar() < Global.lowPressure.getBar())
Global.lowPressure = (Pressure)pres.clone();
if(pres.getBar() > Global.lowPressure.getBar())
Global.highPressure = (Pressure)pres.clone();
}
}
else {
throw new InvalidSymbolException("condition.txt: Unknown PressureModel = " + modelType);
}
}
public LinkedHashMap populateInitialStatusListWithReactiveSpecies(BufferedReader reader) throws IOException {
LinkedHashMap speciesSet = new LinkedHashMap();
LinkedHashMap speciesStatus = new LinkedHashMap();
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String name = null;
if (!index.startsWith("(")) name = index;
else name = st.nextToken();
//if (restart) name += "("+speciesnum+")";
// 24Jun2009: MRH
// Check if the species name begins with a number.
// If so, terminate the program and inform the user to choose
// a different name. This is implemented so that the chem.inp
// file generated will be valid when run in Chemkin
try {
int doesNameBeginWithNumber = Integer.parseInt(name.substring(0,1));
System.out.println("\nA species name should not begin with a number." +
" Please rename species: " + name + "\n");
System.exit(0);
} catch (NumberFormatException e) {
// We're good
}
if (!(st.hasMoreTokens())) throw new InvalidSymbolException("Couldn't find concentration of species: "+name);
String conc = st.nextToken();
double concentration = Double.parseDouble(conc);
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
concentration /= 1000;
unit = "mol/cm3";
}
else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
concentration /= 1000000;
unit = "mol/cm3";
}
else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
concentration /= 6.022e23;
}
else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
throw new InvalidUnitException("Species Concentration in condition.txt!");
}
//GJB to allow "unreactive" species that only follow user-defined library reactions.
// They will not react according to RMG reaction families
boolean IsReactive = true;
boolean IsConstantConcentration = false;
while (st.hasMoreTokens()) {
String reactive = st.nextToken().trim();
if (reactive.equalsIgnoreCase("unreactive"))
IsReactive = false;
if (reactive.equalsIgnoreCase("constantconcentration"))
IsConstantConcentration=true;
}
Graph g = ChemParser.readChemGraph(reader);
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
}
catch (ForbiddenStructureException e) {
System.out.println("Forbidden Structure:\n" + e.getMessage());
throw new InvalidSymbolException("A species in the input file has a forbidden structure.");
}
//System.out.println(name);
Species species = Species.make(name,cg);
species.setReactivity(IsReactive); // GJB
species.setConstantConcentration(IsConstantConcentration);
speciesSet.put(name, species);
getSpeciesSeed().add(species);
double flux = 0;
int species_type = 1; // reacted species
SpeciesStatus ss = new SpeciesStatus(species,species_type,concentration,flux);
speciesStatus.put(species, ss);
line = ChemParser.readMeaningfulLine(reader, true);
}
ReactionTime initial = new ReactionTime(0,"S");
//10/23/07 gmagoon: modified for handling multiple temperature, pressure conditions; note: concentration within speciesStatus (and list of conversion values) should not need to be modified for each T,P since this is done within isTPCconsistent in ReactionSystem
initialStatusList = new LinkedList();
for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
TemperatureModel tm = (TemperatureModel)iter.next();
for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
PressureModel pm = (PressureModel)iter2.next();
// LinkedHashMap speStat = (LinkedHashMap)speciesStatus.clone();//10/31/07 gmagoon: trying creating multiple instances of speciesStatus to address issues with concentration normalization (last normalization seems to apply to all)
Set ks = speciesStatus.keySet();
LinkedHashMap speStat = new LinkedHashMap();
for (Iterator iter3 = ks.iterator(); iter3.hasNext();){//11/1/07 gmagoon: perform deep copy; (is there an easier or more elegant way to do this?)
SpeciesStatus ssCopy = (SpeciesStatus)speciesStatus.get(iter3.next());
speStat.put(ssCopy.getSpecies(),new SpeciesStatus(ssCopy.getSpecies(),ssCopy.getSpeciesType(),ssCopy.getConcentration(),ssCopy.getFlux()));
}
initialStatusList.add(new InitialStatus(speStat,tm.getTemperature(initial),pm.getPressure(initial)));
}
}
return speciesSet;
}
public void populateInitialStatusListWithInertSpecies(BufferedReader reader) {
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken().trim();
String conc = st.nextToken();
double inertConc = Double.parseDouble(conc);
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
inertConc /= 1000;
unit = "mol/cm3";
}
else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
inertConc /= 1000000;
unit = "mol/cm3";
}
else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
inertConc /= 6.022e23;
unit = "mol/cm3";
}
else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
throw new InvalidUnitException("Inert Gas Concentration not recognized: " + unit);
}
//SystemSnapshot.putInertGas(name,inertConc);
for(Iterator iter=initialStatusList.iterator();iter.hasNext(); ){//6/23/09 gmagoon: needed to change this to accommodate non-static inertConc
((InitialStatus)iter.next()).putInertGas(name,inertConc);
}
line = ChemParser.readMeaningfulLine(reader, true);
}
}
public String readMaxAtomTypes(String line, BufferedReader reader) {
if (line.startsWith("MaxCarbonNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxCarbonNumberPerSpecies:"
int maxCNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxCarbonNumber(maxCNum);
System.out.println("Note: Overriding RMG-defined MAX_CARBON_NUM with user-defined value: " + maxCNum);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.startsWith("MaxOxygenNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxOxygenNumberPerSpecies:"
int maxONum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxOxygenNumber(maxONum);
System.out.println("Note: Overriding RMG-defined MAX_OXYGEN_NUM with user-defined value: " + maxONum);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.startsWith("MaxRadicalNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxRadicalNumberPerSpecies:"
int maxRadNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxRadicalNumber(maxRadNum);
System.out.println("Note: Overriding RMG-defined MAX_RADICAL_NUM with user-defined value: " + maxRadNum);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.startsWith("MaxSulfurNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxSulfurNumberPerSpecies:"
int maxSNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxSulfurNumber(maxSNum);
System.out.println("Note: Overriding RMG-defined MAX_SULFUR_NUM with user-defined value: " + maxSNum);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.startsWith("MaxSiliconNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxSiliconNumberPerSpecies:"
int maxSiNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxSiliconNumber(maxSiNum);
System.out.println("Note: Overriding RMG-defined MAX_SILICON_NUM with user-defined value: " + maxSiNum);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.startsWith("MaxHeavyAtom")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxHeavyAtomPerSpecies:"
int maxHANum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxHeavyAtomNumber(maxHANum);
System.out.println("Note: Overriding RMG-defined MAX_HEAVYATOM_NUM with user-defined value: " + maxHANum);
line = ChemParser.readMeaningfulLine(reader, true);
}
return line;
}
public ReactionModelEnlarger getReactionModelEnlarger() {
return reactionModelEnlarger;
}
public LinkedList getTempList() {
return tempList;
}
public LinkedList getPressList() {
return presList;
}
public LinkedList getInitialStatusList() {
return initialStatusList;
}
public void writeBackupRestartFiles(String[] listOfFiles) {
for (int i=0; i<listOfFiles.length; i++) {
File temporaryRestartFile = new File(listOfFiles[i]);
if (temporaryRestartFile.exists()) temporaryRestartFile.renameTo(new File(listOfFiles[i]+"~"));
}
}
public void removeBackupRestartFiles(String[] listOfFiles) {
for (int i=0; i<listOfFiles.length; i++) {
File temporaryRestartFile = new File(listOfFiles[i]+"~");
temporaryRestartFile.delete();
}
}
public static boolean rerunFameWithAdditionalGrains() {
return rerunFame;
}
public void setLimitingReactantID(int id) {
limitingReactantID = id;
}
public int getLimitingReactantID() {
return limitingReactantID;
}
public void readAndMakePTransL(BufferedReader reader) {
int numPTLs = 0;
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
String[] tempString = line.split("Name: ");
String name = tempString[tempString.length-1].trim();
line = ChemParser.readMeaningfulLine(reader, true);
tempString = line.split("Location: ");
String path = tempString[tempString.length-1].trim();
if (numPTLs==0) {
setPrimaryTransportLibrary(new PrimaryTransportLibrary(name,path));
++numPTLs;
}
else {
getPrimaryTransportLibrary().appendPrimaryTransportLibrary(name,path);
++numPTLs;
}
line = ChemParser.readMeaningfulLine(reader, true);
}
if (numPTLs == 0) setPrimaryTransportLibrary(null);
}
public PrimaryTransportLibrary getPrimaryTransportLibrary() {
return primaryTransportLibrary;
}
public void setPrimaryTransportLibrary(PrimaryTransportLibrary p_primaryTransportLibrary) {
primaryTransportLibrary = p_primaryTransportLibrary;
}
/**
* Print the current numbers of core and edge species and reactions to the
* console.
*/
public void printModelSize() {
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel) getReactionModel();
int numberOfCoreSpecies = cerm.getReactedSpeciesSet().size();
int numberOfEdgeSpecies = cerm.getUnreactedSpeciesSet().size();
int numberOfCoreReactions = 0;
int numberOfEdgeReactions = 0;
double count = 0.0;
for (Iterator iter = cerm.getReactedReactionSet().iterator(); iter.hasNext(); ) {
Reaction rxn = (Reaction) iter.next();
if (rxn.hasReverseReaction()) count += 0.5;
else count += 1;
}
numberOfCoreReactions = (int) Math.round(count);
count = 0.0;
for (Iterator iter = cerm.getUnreactedReactionSet().iterator(); iter.hasNext(); ) {
Reaction rxn = (Reaction) iter.next();
if (rxn.hasReverseReaction()) count += 0.5;
else count += 1;
}
numberOfEdgeReactions = (int) Math.round(count);
if (reactionModelEnlarger instanceof RateBasedPDepRME) {
numberOfCoreReactions += PDepNetwork.getNumCoreReactions(cerm);
numberOfEdgeReactions += PDepNetwork.getNumEdgeReactions(cerm);
}
System.out.println("The model core has " + Integer.toString(numberOfCoreReactions) + " reactions and "+ Integer.toString(numberOfCoreSpecies) + " species.");
System.out.println("The model edge has " + Integer.toString(numberOfEdgeReactions) + " reactions and "+ Integer.toString(numberOfEdgeSpecies) + " species.");
}
} |
package org.ccnx.ccn.test.impl;
import java.util.TreeSet;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import org.ccnx.ccn.CCNFilterListener;
import org.ccnx.ccn.CCNInterestListener;
import org.ccnx.ccn.impl.CCNNetworkManager.NetworkProtocol;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.io.CCNWriter;
import org.ccnx.ccn.profiles.SegmentationProfile;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.Interest;
import org.ccnx.ccn.test.CCNTestBase;
import org.ccnx.ccn.test.CCNTestHelper;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Test CCNNetworkManager.
*
* This should eventually have more tests
*
* Note - this test requires ccnd to be running
*
*/
public class NetworkTest extends CCNTestBase {
protected static final int WAIT_MILLIS = 8000;
protected static final int FLOOD_ITERATIONS = 1000;
private Semaphore sema = new Semaphore(0);
private Semaphore filterSema = new Semaphore(0);
private boolean gotData = false;
private boolean gotInterest = false;
Interest testInterest = null;
// Fix test so it doesn't use static names.
static CCNTestHelper testHelper = new CCNTestHelper(NetworkTest.class);
static ContentName testPrefix = testHelper.getClassChildName("networkTest");
@BeforeClass
public static void setUpBeforeClass() throws Exception {
CCNTestBase.setUpBeforeClass();
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
CCNTestBase.tearDownAfterClass();
}
@Before
public void setUp() throws Exception {
}
/**
* Partially test prefix registration/deregistration
* @throws Exception
*/
@Test
public void testRegisteredPrefix() throws Exception {
Log.setLevel(Log.FAC_NETMANAGER, Level.FINEST);
TestFilterListener tfl = new TestFilterListener();
TestListener tl = new TestListener();
ContentName testName1 = ContentName.fromNative(testPrefix, "foo");
Interest interest1 = new Interest(testName1);
ContentName testName2 = ContentName.fromNative(testName1, "bar"); // /foo/bar
Interest interest2 = new Interest(testName2);
ContentName testName3 = ContentName.fromNative(testName2, "blaz"); // /foo/bar/blaz
ContentName testName4 = ContentName.fromNative(testName2, "xxx"); // /foo/bar/xxx
Interest interest4 = new Interest(testName4);
ContentName testName5 = ContentName.fromNative(testPrefix, "zoo"); // /zoo
ContentName testName6 = ContentName.fromNative(testName1, "zoo"); // /foo/zoo
ContentName testName7 = ContentName.fromNative(testName2, "spaz"); // /foo/bar/spaz
Interest interest6 = new Interest(testName6);
// Test that we don't receive interests above what we registered
gotInterest = false;
putHandle.getNetworkManager().setInterestFilter(this, testName2, tfl);
Thread.sleep(1000);
Assert.assertFalse(gotInterest);
getHandle.cancelInterest(interest1, tl);
getHandle.expressInterest(interest2, tl);
filterSema.tryAcquire(WAIT_MILLIS, TimeUnit.MILLISECONDS);
Assert.assertTrue(gotInterest);
getHandle.cancelInterest(interest2, tl);
// Test that an "in-between" prefix gets registered properly
gotInterest = false;
putHandle.getNetworkManager().cancelInterestFilter(this, testName2, tfl);
putHandle.getNetworkManager().setInterestFilter(this, testName3, tfl);
putHandle.getNetworkManager().setInterestFilter(this, testName4, tfl);
putHandle.getNetworkManager().setInterestFilter(this, testName5, tfl);
putHandle.getNetworkManager().setInterestFilter(this, testName2, tfl);
putHandle.getNetworkManager().setInterestFilter(this, testName1, tfl);
// The following is to make sure that a filter that is a prefix of a registered filter
// doesn't get registered separately. There's no good way to test this directly (I don't think)
// currently but we can see that it is done by checking out the log
putHandle.getNetworkManager().setInterestFilter(this, testName7, tfl);
getHandle.expressInterest(interest4, tl);
filterSema.tryAcquire(WAIT_MILLIS, TimeUnit.MILLISECONDS);
Assert.assertTrue(gotInterest);
getHandle.cancelInterest(interest4, tl);
gotInterest = false;
filterSema.drainPermits();
getHandle.expressInterest(interest6, tl);
filterSema.tryAcquire(WAIT_MILLIS, TimeUnit.MILLISECONDS);
Assert.assertTrue(gotInterest);
getHandle.cancelInterest(interest6, tl);
putHandle.getNetworkManager().cancelInterestFilter(this, testName1, tfl);
putHandle.getNetworkManager().cancelInterestFilter(this, testName2, tfl);
putHandle.getNetworkManager().cancelInterestFilter(this, testName3, tfl);
putHandle.getNetworkManager().cancelInterestFilter(this, testName5, tfl);
// Test that nothing after / is registered. Need to examine logs to ensure this is
// done correctly.
ContentName slashName = ContentName.fromNative("/");
putHandle.getNetworkManager().setInterestFilter(this, testName1, tfl);
putHandle.getNetworkManager().setInterestFilter(this, slashName, tfl);
putHandle.getNetworkManager().setInterestFilter(this, testName5, tfl);
putHandle.getNetworkManager().cancelInterestFilter(this, testName1, tfl);
putHandle.getNetworkManager().cancelInterestFilter(this, slashName, tfl);
putHandle.getNetworkManager().cancelInterestFilter(this, testName5, tfl);
}
@Test
public void testNetworkManager() throws Exception {
/*
* Test re-expression of interest
*/
CCNWriter writer = new CCNWriter(testPrefix, putHandle);
ContentName testName = ContentName.fromNative(testPrefix, "aaa");
testInterest = new Interest(testName);
TestListener tl = new TestListener();
getHandle.expressInterest(testInterest, tl);
Thread.sleep(80);
writer.put(testName, "aaa");
sema.tryAcquire(WAIT_MILLIS, TimeUnit.MILLISECONDS);
Assert.assertTrue(gotData);
writer.close();
}
@Test
public void testNetworkManagerFixedPrefix() throws Exception {
CCNWriter writer = new CCNWriter(putHandle);
ContentName testName = ContentName.fromNative(testPrefix, "ddd");
testInterest = new Interest(testName);
TestListener tl = new TestListener();
getHandle.expressInterest(testInterest, tl);
Thread.sleep(80);
writer.put(testName, "ddd");
sema.tryAcquire(WAIT_MILLIS, TimeUnit.MILLISECONDS);
Assert.assertTrue(gotData);
writer.close();
}
@Test
public void testNetworkManagerBackwards() throws Exception {
CCNWriter writer = new CCNWriter(testPrefix, putHandle);
// Shouldn't have to do this -- need to refactor test. Had to add it after
// fixing CCNWriter to do proper flow control.
writer.disableFlowControl();
ContentName testName = ContentName.fromNative(testPrefix, "bbb");
testInterest = new Interest(testName);
TestListener tl = new TestListener();
writer.put(testName, "bbb");
Thread.sleep(80);
getHandle.expressInterest(testInterest, tl);
sema.tryAcquire(WAIT_MILLIS, TimeUnit.MILLISECONDS);
Assert.assertTrue(gotData);
writer.close();
}
@Test
public void testFreshnessSeconds() throws Exception {
CCNWriter writer = new CCNWriter(testPrefix, putHandle);
writer.disableFlowControl();
ContentName testName = ContentName.fromNative(testPrefix, "freshnessTest");
writer.put(testName, "freshnessTest", 3);
Thread.sleep(80);
ContentObject co = getHandle.get(testName, 1000);
Assert.assertFalse(co == null);
Thread.sleep(WAIT_MILLIS);
co = getHandle.get(testName, 1000);
Assert.assertTrue(co == null);
writer.close();
}
@Test
public void testInterestReexpression() throws Exception {
/*
* Test re-expression of interest
*/
CCNWriter writer = new CCNWriter(testPrefix, putHandle);
ContentName testName = ContentName.fromNative(testPrefix, "ccc");
testInterest = new Interest(testName);
TestListener tl = new TestListener();
getHandle.expressInterest(testInterest, tl);
// Sleep long enough that the interest must be re-expressed
Thread.sleep(WAIT_MILLIS);
writer.put(testName, "ccc");
sema.tryAcquire(WAIT_MILLIS, TimeUnit.MILLISECONDS);
Assert.assertTrue(gotData);
writer.close();
}
/**
* Test flooding the system with a bunch of content. Only works for TCP
* @throws Exception
*/
@Test
public void testFlood() throws Exception {
if (getHandle.getNetworkManager().getProtocol() == NetworkProtocol.TCP) {
System.out.println("Testing TCP flooding");
TreeSet<ContentObject> cos = new TreeSet<ContentObject>();
for (int i = 0; i < FLOOD_ITERATIONS; i++) {
ContentName name = ContentName.fromNative(testPrefix, (new Integer(i)).toString());
cos.add(ContentObject.buildContentObject(name, new byte[]{(byte)i}));
}
for (ContentObject co : cos)
putHandle.put(co);
for (int i = 0; i < FLOOD_ITERATIONS; i++) {
ContentObject co = getHandle.get(ContentName.fromNative(testPrefix, new Integer(i).toString()), 2000);
Assert.assertNotNull(co);
}
}
}
class TestFilterListener implements CCNFilterListener {
public boolean handleInterest(Interest interest) {
gotInterest = true;
filterSema.release();
return true;
}
}
class TestListener implements CCNInterestListener {
public Interest handleContent(ContentObject co,
Interest interest) {
Assert.assertFalse(co == null);
ContentName nameBase = SegmentationProfile.segmentRoot(co.name());
Assert.assertEquals(nameBase.stringComponent(nameBase.count()-1), new String(co.content()));
gotData = true;
sema.release();
/*
* Test call of cancel in handler doesn't hang
*/
getHandle.cancelInterest(testInterest, this);
return null;
}
}
} |
// %Z%%M%, %I%, %G%
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.strangeberry.jmdns.tools;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.io.IOException;
import java.util.Enumeration;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceInfo;
import javax.jmdns.ServiceListener;
import javax.jmdns.ServiceTypeListener;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
/**
* User Interface for browsing JmDNS services.
*
* @author Arthur van Hoff, Werner Randelshofer
* @version %I%, %G%
*/
public class Browser extends JFrame implements ServiceListener, ServiceTypeListener, ListSelectionListener
{
private static final long serialVersionUID = 5750114542524415107L;
JmDNS jmdns;
// Vector headers;
String type;
DefaultListModel types;
JList typeList;
DefaultListModel services;
JList serviceList;
JTextArea info;
/**
* @param mDNS
* @throws IOException
*/
Browser(JmDNS mDNS) throws IOException
{
super("JmDNS Browser");
this.jmdns = mDNS;
Color bg = new Color(230, 230, 230);
EmptyBorder border = new EmptyBorder(5, 5, 5, 5);
Container content = getContentPane();
content.setLayout(new GridLayout(1, 3));
types = new DefaultListModel();
typeList = new JList(types);
typeList.setBorder(border);
typeList.setBackground(bg);
typeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
typeList.addListSelectionListener(this);
JPanel typePanel = new JPanel();
typePanel.setLayout(new BorderLayout());
typePanel.add("North", new JLabel("Types"));
typePanel.add("Center", new JScrollPane(typeList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));
content.add(typePanel);
services = new DefaultListModel();
serviceList = new JList(services);
serviceList.setBorder(border);
serviceList.setBackground(bg);
serviceList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
serviceList.addListSelectionListener(this);
JPanel servicePanel = new JPanel();
servicePanel.setLayout(new BorderLayout());
servicePanel.add("North", new JLabel("Services"));
servicePanel.add("Center", new JScrollPane(serviceList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));
content.add(servicePanel);
info = new JTextArea();
info.setBorder(border);
info.setBackground(bg);
info.setEditable(false);
info.setLineWrap(true);
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new BorderLayout());
infoPanel.add("North", new JLabel("Details"));
infoPanel.add("Center", new JScrollPane(info, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));
content.add(infoPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(100, 100);
setSize(600, 400);
mDNS.addServiceTypeListener(this);
// register some well known types
String list[] = new String[] { "_http._tcp.local.", "_ftp._tcp.local.", "_tftp._tcp.local.", "_ssh._tcp.local.", "_smb._tcp.local.", "_printer._tcp.local.", "_airport._tcp.local.", "_afpovertcp._tcp.local.", "_ichat._tcp.local.",
"_eppc._tcp.local.", "_presence._tcp.local.", "_rfb._tcp.local.", "_daap._tcp.local.", "_touchcs._tcp.local." };
for (int i = 0; i < list.length; i++)
{
mDNS.registerServiceType(list[i]);
}
this.setVisible(true);
}
/**
* Add a service.
*
* @param event
*/
public void serviceAdded(ServiceEvent event)
{
final String name = event.getName();
System.out.println("ADD: " + name);
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
insertSorted(services, name);
}
});
}
/**
* Remove a service.
*
* @param event
*/
public void serviceRemoved(ServiceEvent event)
{
final String name = event.getName();
System.out.println("REMOVE: " + name);
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
services.removeElement(name);
}
});
}
/**
* A new service type was <discovered.
*
* @param event
*/
public void serviceTypeAdded(ServiceEvent event)
{
final String aType = event.getType();
System.out.println("TYPE: " + aType);
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
insertSorted(types, aType);
}
});
}
void insertSorted(DefaultListModel model, String value)
{
for (int i = 0, n = model.getSize(); i < n; i++)
{
if (value.compareToIgnoreCase((String) model.elementAt(i)) < 0)
{
model.insertElementAt(value, i);
return;
}
}
model.addElement(value);
}
/**
* Resolve a service.
*
* @param event
*/
public void serviceResolved(ServiceEvent event)
{
if (event.getName().equals(serviceList.getSelectedValue()))
{
this.dislayInfo(event.getInfo());
}
}
/**
* List selection changed.
*
* @param e
*/
public void valueChanged(ListSelectionEvent e)
{
if (!e.getValueIsAdjusting())
{
if (e.getSource() == typeList)
{
type = (String) typeList.getSelectedValue();
System.out.println("VALUE CHANGED: type: " + type);
jmdns.removeServiceListener(type, this);
services.setSize(0);
info.setText("");
if (type != null)
{
jmdns.addServiceListener(type, this);
}
}
else if (e.getSource() == serviceList)
{
String name = (String) serviceList.getSelectedValue();
System.out.println("VALUE CHANGED: type: " + type + " service: " + name);
if (name == null)
{
info.setText("");
}
else
{
ServiceInfo service = jmdns.getServiceInfo(type, name, 1000);
this.dislayInfo(service);
}
}
}
}
private void dislayInfo(ServiceInfo service)
{
if (service == null)
{
info.setText("service not found");
}
else
{
StringBuffer buf = new StringBuffer();
buf.append(service.getName());
buf.append('.');
buf.append(service.getType());
buf.append('\n');
buf.append(service.getServer());
buf.append(':');
buf.append(service.getPort());
buf.append('\n');
buf.append(service.getInetAddress());
buf.append(':');
buf.append(service.getPort());
buf.append('\n');
for (Enumeration<String> names = service.getPropertyNames(); names.hasMoreElements();)
{
String prop = names.nextElement();
buf.append(prop);
buf.append('=');
buf.append(service.getPropertyString(prop));
buf.append('\n');
}
this.info.setText(buf.toString());
}
}
/**
* Table data.
*/
class ServiceTableModel extends AbstractTableModel
{
private static final long serialVersionUID = 5607994569609827570L;
@Override
public String getColumnName(int column)
{
switch (column)
{
case 0:
return "service";
case 1:
return "address";
case 2:
return "port";
case 3:
return "text";
}
return null;
}
public int getColumnCount()
{
return 1;
}
public int getRowCount()
{
return services.size();
}
public Object getValueAt(int row, int col)
{
return services.elementAt(row);
}
}
@Override
public String toString()
{
return "RVBROWSER";
}
/**
* Main program.
*
* @param argv
* @throws IOException
*/
public static void main(String argv[]) throws IOException
{
new Browser(JmDNS.create());
}
} |
package org.xbill.DNS;
import java.util.*;
import java.io.*;
import java.net.*;
/**
* The Lookup object issues queries to caching DNS servers. The input consists
* of a name, an optional type, and an optional class. Caching is enabled
* by default and used when possible to reduce the number of DNS requests.
* A Resolver, which defaults to an ExtendedResolver initialized with the
* resolvers located by the ResolverConfig class, performs the queries. A
* search path of domain suffixes is used to resolve relative names, and is
* also determined by the ResolverConfig class.
*
* A Lookup object may be reused, but should not be used by multiple threads.
*
* @see Cache
* @see Resolver
* @see ResolverConfig
*
* @author Brian Wellington
*/
public final class Lookup {
private static Resolver defaultResolver;
private static Name [] defaultSearchPath;
private static Map defaultCaches;
private Resolver resolver;
private Name [] searchPath;
private Cache cache;
private boolean temporary_cache;
private int credibility;
private Name name;
private int type;
private int dclass;
private boolean verbose;
private int iterations;
private boolean foundAlias;
private boolean done;
private boolean doneCurrent;
private List aliases;
private Record [] answers;
private int result;
private String error;
private boolean nxdomain;
private boolean badresponse;
private String badresponse_error;
private boolean networkerror;
private boolean timedout;
private boolean nametoolong;
private boolean referral;
private static final Name [] noAliases = new Name[0];
/** The lookup was successful. */
public static final int SUCCESSFUL = 0;
/**
* The lookup failed due to a data or server error. Repeating the lookup
* would not be helpful.
*/
public static final int UNRECOVERABLE = 1;
/**
* The lookup failed due to a network error. Repeating the lookup may be
* helpful.
*/
public static final int TRY_AGAIN = 2;
/** The host does not exist. */
public static final int HOST_NOT_FOUND = 3;
/** The host exists, but has no records associated with the queried type. */
public static final int TYPE_NOT_FOUND = 4;
public static synchronized void
refreshDefault() {
try {
defaultResolver = new ExtendedResolver();
}
catch (UnknownHostException e) {
throw new RuntimeException("Failed to initialize resolver");
}
defaultSearchPath = ResolverConfig.getCurrentConfig().searchPath();
defaultCaches = new HashMap();
}
static {
refreshDefault();
}
/**
* Gets the Resolver that will be used as the default by future Lookups.
* @return The default resolver.
*/
public static synchronized Resolver
getDefaultResolver() {
return defaultResolver;
}
/**
* Sets the default Resolver to be used as the default by future Lookups.
* @param resolver The default resolver.
*/
public static synchronized void
setDefaultResolver(Resolver resolver) {
defaultResolver = resolver;
}
/**
* Gets the Cache that will be used as the default for the specified
* class by future Lookups.
* @param dclass The class whose cache is being retrieved.
* @return The default cache for the specified class.
*/
public static synchronized Cache
getDefaultCache(int dclass) {
DClass.check(dclass);
Cache c = (Cache) defaultCaches.get(Mnemonic.toInteger(dclass));
if (c == null) {
c = new Cache(dclass);
defaultCaches.put(Mnemonic.toInteger(dclass), c);
}
return c;
}
/**
* Sets the Cache to be used as the default for the specified class by future
* Lookups.
* @param cache The default cache for the specified class.
* @param dclass The class whose cache is being set.
*/
public static synchronized void
setDefaultCache(Cache cache, int dclass) {
DClass.check(dclass);
defaultCaches.put(Mnemonic.toInteger(dclass), cache);
}
/**
* Gets the search path that will be used as the default by future Lookups.
* @return The default search path.
*/
public static synchronized Name []
getDefaultSearchPath() {
return defaultSearchPath;
}
/**
* Sets the search path to be used as the default by future Lookups.
* @param domains The default search path.
*/
public static synchronized void
setDefaultSearchPath(Name [] domains) {
defaultSearchPath = domains;
}
/**
* Sets the search path that will be used as the default by future Lookups.
* @param domains The default search path.
* @throws TextParseException A name in the array is not a valid DNS name.
*/
public static synchronized void
setDefaultSearchPath(String [] domains) throws TextParseException {
if (domains == null) {
defaultSearchPath = null;
return;
}
Name [] newdomains = new Name[domains.length];
for (int i = 0; i < domains.length; i++)
newdomains[i] = Name.fromString(domains[i], Name.root);
defaultSearchPath = newdomains;
}
private final void
reset() {
iterations = 0;
foundAlias = false;
done = false;
doneCurrent = false;
aliases = null;
answers = null;
result = -1;
error = null;
nxdomain = false;
badresponse = false;
badresponse_error = null;
networkerror = false;
timedout = false;
nametoolong = false;
referral = false;
if (temporary_cache)
cache.clearCache();
}
public
Lookup(Name name, int type, int dclass) {
Type.check(type);
DClass.check(dclass);
if (!Type.isRR(type) && type != Type.ANY)
throw new IllegalArgumentException("Cannot query for " +
"meta-types other than ANY");
this.name = name;
this.type = type;
this.dclass = dclass;
synchronized (Lookup.class) {
this.resolver = getDefaultResolver();
this.searchPath = getDefaultSearchPath();
this.cache = getDefaultCache(dclass);
}
this.credibility = Credibility.NORMAL;
this.verbose = Options.check("verbose");
this.result = -1;
}
public
Lookup(Name name, int type) {
this(name, type, DClass.IN);
}
/**
* Create a Lookup object that will find records of type A at the given name
* in the IN class.
* @param name The name of the desired records
* @see #Lookup(Name,int,int)
*/
public
Lookup(Name name) {
this(name, Type.A, DClass.IN);
}
public
Lookup(String name, int type, int dclass) throws TextParseException {
this(Name.fromString(name), type, dclass);
}
public
Lookup(String name, int type) throws TextParseException {
this(Name.fromString(name), type, DClass.IN);
}
/**
* Create a Lookup object that will find records of type A at the given name
* in the IN class.
* @param name The name of the desired records
* @throws TextParseException The name is not a valid DNS name
* @see #Lookup(Name,int,int)
*/
public
Lookup(String name) throws TextParseException {
this(Name.fromString(name), Type.A, DClass.IN);
}
/**
* Sets the resolver to use when performing this lookup. This overrides the
* default value.
* @param resolver The resolver to use.
*/
public void
setResolver(Resolver resolver) {
this.resolver = resolver;
}
/**
* Sets the search path to use when performing this lookup. This overrides the
* default value.
* @param domains An array of names containing the search path.
*/
public void
setSearchPath(Name [] domains) {
this.searchPath = domains;
}
/**
* Sets the search path to use when performing this lookup. This overrides the
* default value.
* @param domains An array of names containing the search path.
* @throws TextParseException A name in the array is not a valid DNS name.
*/
public void
setSearchPath(String [] domains) throws TextParseException {
if (domains == null) {
this.searchPath = null;
return;
}
Name [] newdomains = new Name[domains.length];
for (int i = 0; i < domains.length; i++)
newdomains[i] = Name.fromString(domains[i], Name.root);
this.searchPath = newdomains;
}
/**
* Sets the cache to use when performing this lookup. This overrides the
* default value. If the results of this lookup should not be permanently
* cached, null can be provided here.
* @param cache The cache to use.
*/
public void
setCache(Cache cache) {
if (cache == null) {
this.cache = new Cache(dclass);
this.temporary_cache = true;
} else {
this.cache = cache;
this.temporary_cache = false;
}
}
/**
* Sets the minimum credibility level that will be accepted when performing
* the lookup. This defaults to Credibility.NORMAL.
* @param credibility The minimum credibility level.
*/
public void
setCredibility(int credibility) {
this.credibility = credibility;
}
private void
follow(Name name, Name oldname) {
foundAlias = true;
badresponse = false;
networkerror = false;
timedout = false;
nxdomain = false;
referral = false;
iterations++;
if (iterations >= 6 || name.equals(oldname)) {
result = UNRECOVERABLE;
error = "CNAME loop";
done = true;
return;
}
if (aliases == null)
aliases = new ArrayList();
aliases.add(oldname);
lookup(name);
}
private void
processResponse(Name name, SetResponse response) {
if (response.isSuccessful()) {
RRset [] rrsets = response.answers();
List l = new ArrayList();
Iterator it;
int i;
for (i = 0; i < rrsets.length; i++) {
it = rrsets[i].rrs();
while (it.hasNext())
l.add(it.next());
}
result = SUCCESSFUL;
answers = (Record []) l.toArray(new Record[l.size()]);
done = true;
} else if (response.isNXDOMAIN()) {
nxdomain = true;
doneCurrent = true;
if (iterations > 0) {
result = HOST_NOT_FOUND;
done = true;
}
} else if (response.isNXRRSET()) {
result = TYPE_NOT_FOUND;
answers = null;
done = true;
} else if (response.isCNAME()) {
CNAMERecord cname = response.getCNAME();
follow(cname.getTarget(), name);
} else if (response.isDNAME()) {
DNAMERecord dname = response.getDNAME();
Name newname = null;
try {
follow(name.fromDNAME(dname), name);
} catch (NameTooLongException e) {
result = UNRECOVERABLE;
error = "Invalid DNAME target";
done = true;
}
} else if (response.isDelegation()) {
// We shouldn't get a referral. Ignore it.
referral = true;
}
}
private void
lookup(Name current) {
SetResponse sr = cache.lookupRecords(current, type, credibility);
if (verbose) {
System.err.println("lookup " + current + " " +
Type.string(type));
System.err.println(sr);
}
processResponse(current, sr);
if (done || doneCurrent)
return;
Record question = Record.newRecord(current, type, dclass);
Message query = Message.newQuery(question);
Message response = null;
try {
response = resolver.send(query);
}
catch (IOException e) {
// A network error occurred. Press on.
if (e instanceof InterruptedIOException)
timedout = true;
else
networkerror = true;
return;
}
int rcode = response.getHeader().getRcode();
if (rcode != Rcode.NOERROR && rcode != Rcode.NXDOMAIN) {
// The server we contacted is broken or otherwise unhelpful.
// Press on.
badresponse = true;
badresponse_error = Rcode.string(rcode);
return;
}
if (!query.getQuestion().equals(response.getQuestion())) {
// The answer doesn't match the question. That's not good.
badresponse = true;
badresponse_error = "response does not match query";
return;
}
sr = cache.addMessage(response);
if (sr == null)
sr = cache.lookupRecords(current, type, credibility);
if (verbose) {
System.err.println("queried " + current + " " +
Type.string(type));
System.err.println(sr);
}
processResponse(current, sr);
}
private void
resolve(Name current, Name suffix) {
doneCurrent = false;
Name tname = null;
if (suffix == null)
tname = current;
else {
try {
tname = Name.concatenate(current, suffix);
}
catch (NameTooLongException e) {
nametoolong = true;
return;
}
}
lookup(tname);
}
/**
* Performs the lookup, using the specified Cache, Resolver, and search path.
* @return The answers, or null if none are found.
*/
public Record []
run() {
if (done)
reset();
if (name.isAbsolute())
resolve(name, null);
else if (searchPath == null)
resolve(name, Name.root);
else {
if (name.labels() > 1)
resolve(name, Name.root);
if (done)
return answers;
for (int i = 0; i < searchPath.length; i++) {
resolve(name, searchPath[i]);
if (done)
return answers;
else if (foundAlias)
break;
}
}
if (!done) {
if (badresponse) {
result = TRY_AGAIN;
error = badresponse_error;
done = true;
} else if (timedout) {
result = TRY_AGAIN;
error = "timed out";
done = true;
} else if (networkerror) {
result = TRY_AGAIN;
error = "network error";
done = true;
} else if (nxdomain) {
result = HOST_NOT_FOUND;
done = true;
} else if (referral) {
result = UNRECOVERABLE;
error = "referral";
done = true;
} else if (nametoolong) {
result = UNRECOVERABLE;
error = "name too long";
done = true;
}
}
return answers;
}
private void
checkDone() {
if (done && result != -1)
return;
StringBuffer sb = new StringBuffer("Lookup of " + name + " ");
if (dclass != DClass.IN)
sb.append(DClass.string(dclass) + " ");
sb.append(Type.string(type) + " isn't done");
throw new IllegalStateException(sb.toString());
}
public Record []
getAnswers() {
checkDone();
return answers;
}
public Name []
getAliases() {
checkDone();
if (aliases == null)
return noAliases;
return (Name []) aliases.toArray(new Name[aliases.size()]);
}
public int
getResult() {
checkDone();
return result;
}
public String
getErrorString() {
checkDone();
if (error != null)
return error;
switch (result) {
case SUCCESSFUL: return "successful";
case UNRECOVERABLE: return "unrecoverable error";
case TRY_AGAIN: return "try again";
case HOST_NOT_FOUND: return "host not found";
case TYPE_NOT_FOUND: return "type not found";
}
throw new IllegalStateException("unknown result");
}
} |
package org.xbill.DNS;
import java.io.*;
import java.text.*;
import java.lang.reflect.*;
import java.util.*;
import org.xbill.DNS.utils.*;
/**
* A generic DNS resource record. The specific record types extend this class.
* A record contains a name, type, class, and rdata.
*
* @author Brian Wellington
*/
public abstract class Record implements Cloneable, Comparable {
protected Name name;
protected int type, dclass;
protected long ttl;
private boolean empty;
private static final Record [] knownRecords = new Record[256];
private static final Record unknownRecord = new UNKRecord();
private static final Class [] emptyClassArray = new Class[0];
private static final Object [] emptyObjectArray = new Object[0];
private static final DecimalFormat byteFormat = new DecimalFormat();
static {
byteFormat.setMinimumIntegerDigits(3);
}
protected
Record() {}
Record(Name name, int type, int dclass, long ttl) {
if (!name.isAbsolute())
throw new RelativeNameException(name);
Type.check(type);
DClass.check(dclass);
TTL.check(ttl);
this.name = name;
this.type = type;
this.dclass = dclass;
this.ttl = ttl;
}
/**
* Creates an empty record of the correct type; must be overriden
*/
abstract Record
getObject();
private static final Record
getTypedObject(int type) {
if (type < 0 || type > knownRecords.length)
return unknownRecord.getObject();
if (knownRecords[type] != null)
return knownRecords[type];
/* Construct the class name by putting the type before "Record". */
String s = Record.class.getPackage().getName() + "." +
Type.string(type).replace('-', '_') + "Record";
try {
Class c = Class.forName(s);
Constructor m = c.getDeclaredConstructor(emptyClassArray);
knownRecords[type] = (Record) m.newInstance(emptyObjectArray);
}
catch (ClassNotFoundException e) {
/* This is normal; do nothing */
}
catch (Exception e) {
if (Options.check("verbose"))
System.err.println(e);
}
if (knownRecords[type] == null)
knownRecords[type] = unknownRecord.getObject();
return knownRecords[type];
}
private static final Record
getEmptyRecord(Name name, int type, int dclass, long ttl) {
Record rec = getTypedObject(type);
rec = rec.getObject();
rec.name = name;
rec.type = type;
rec.dclass = dclass;
rec.ttl = ttl;
return rec;
}
/**
* Converts the type-specific RR to wire format - must be overriden
*/
abstract void
rrFromWire(DNSInput in) throws IOException;
private static Record
newRecord(Name name, int type, int dclass, long ttl, int length, DNSInput in)
throws IOException
{
Record rec;
int recstart;
rec = getEmptyRecord(name, type, dclass, ttl);
if (in != null) {
if (in.remaining() < length)
throw new WireParseException("truncated record");
in.setActive(length);
} else
rec.empty = true;
rec.rrFromWire(in);
if (in != null) {
if (in.remaining() > 0)
throw new WireParseException("invalid record length");
in.clearActive();
}
return rec;
}
/**
* Creates a new record, with the given parameters.
* @param name The owner name of the record.
* @param type The record's type.
* @param dclass The record's class.
* @param ttl The record's time to live.
* @param length The length of the record's data.
* @param data The rdata of the record, in uncompressed DNS wire format. Only
* the first length bytes are used.
*/
public static Record
newRecord(Name name, int type, int dclass, long ttl, int length, byte [] data) {
if (!name.isAbsolute())
throw new RelativeNameException(name);
Type.check(type);
DClass.check(dclass);
TTL.check(ttl);
DNSInput in;
if (data != null)
in = new DNSInput(data);
else
in = null;
try {
return newRecord(name, type, dclass, ttl, length, in);
}
catch (IOException e) {
return null;
}
}
/**
* Creates a new record, with the given parameters.
* @param name The owner name of the record.
* @param type The record's type.
* @param dclass The record's class.
* @param ttl The record's time to live.
* @param data The complete rdata of the record, in uncompressed DNS wire
* format.
*/
public static Record
newRecord(Name name, int type, int dclass, long ttl, byte [] data) {
return newRecord(name, type, dclass, ttl, data.length, data);
}
/**
* Creates a new empty record, with the given parameters.
* @param name The owner name of the record.
* @param type The record's type.
* @param dclass The record's class.
* @param ttl The record's time to live.
* @return An object of a subclass of Record
*/
public static Record
newRecord(Name name, int type, int dclass, long ttl) {
if (!name.isAbsolute())
throw new RelativeNameException(name);
Type.check(type);
DClass.check(dclass);
TTL.check(ttl);
Record rec = getEmptyRecord(name, type, dclass, ttl);
rec.empty = true;
return rec;
}
/**
* Creates a new empty record, with the given parameters. This method is
* designed to create records that will be added to the QUERY section
* of a message.
* @param name The owner name of the record.
* @param type The record's type.
* @param dclass The record's class.
* @return An object of a subclass of Record
*/
public static Record
newRecord(Name name, int type, int dclass) {
return newRecord(name, type, dclass, 0);
}
static Record
fromWire(DNSInput in, int section, boolean isUpdate) throws IOException {
int type, dclass;
long ttl;
int length;
Name name;
Record rec;
name = new Name(in);
type = in.readU16();
dclass = in.readU16();
if (section == Section.QUESTION)
return newRecord(name, type, dclass);
ttl = in.readU32();
length = in.readU16();
if (length == 0 && isUpdate)
return newRecord(name, type, dclass, ttl);
rec = newRecord(name, type, dclass, ttl, length, in);
return rec;
}
static Record
fromWire(DNSInput in, int section) throws IOException {
return fromWire(in, section, false);
}
/**
* Builds a Record from DNS uncompressed wire format.
*/
public static Record
fromWire(byte [] b, int section) throws IOException {
return fromWire(new DNSInput(b), section, false);
}
void
toWire(DNSOutput out, int section, Compression c) {
int start = out.current();
name.toWire(out, c);
out.writeU16(type);
out.writeU16(dclass);
if (section == Section.QUESTION)
return;
out.writeU32(ttl);
int lengthPosition = out.current();
out.writeU16(0); /* until we know better */
if (!empty)
rrToWire(out, c, false);
int rrlength = out.current() - lengthPosition - 2;
out.save();
out.jump(lengthPosition);
out.writeU16(rrlength);
out.restore();
}
/**
* Converts a Record into DNS uncompressed wire format.
*/
public byte []
toWire(int section) {
DNSOutput out = new DNSOutput();
toWire(out, section, null);
return out.toByteArray();
}
private void
toWireCanonical(DNSOutput out, boolean noTTL) {
name.toWireCanonical(out);
out.writeU16(type);
out.writeU16(dclass);
if (noTTL) {
out.writeU32(0);
} else {
out.writeU32(ttl);
}
int lengthPosition = out.current();
out.writeU16(0); /* until we know better */
if (!empty)
rrToWire(out, null, true);
int rrlength = out.current() - lengthPosition - 2;
out.save();
out.jump(lengthPosition);
out.writeU16(rrlength);
out.restore();
}
/*
* Converts a Record into canonical DNS uncompressed wire format (all names are
* converted to lowercase), optionally ignoring the TTL.
*/
private byte []
toWireCanonical(boolean noTTL) {
DNSOutput out = new DNSOutput();
toWireCanonical(out, noTTL);
return out.toByteArray();
}
/**
* Converts a Record into canonical DNS uncompressed wire format (all names are
* converted to lowercase).
*/
public byte []
toWireCanonical() {
return toWireCanonical(false);
}
/**
* Converts the rdata in a Record into canonical DNS uncompressed wire format
* (all names are converted to lowercase).
*/
public byte []
rdataToWireCanonical() {
if (empty)
return new byte[0];
DNSOutput out = new DNSOutput();
rrToWire(out, null, true);
return out.toByteArray();
}
/**
* Converts the type-specific RR to text format - must be overriden
*/
abstract String rrToString();
/**
* Converts the rdata portion of a Record into a String representation
*/
public String
rdataToString() {
if (empty)
return "";
return rrToString();
}
/**
* Converts a Record into a String representation
*/
public String
toString() {
StringBuffer sb = new StringBuffer();
sb.append(name);
if (sb.length() < 8)
sb.append("\t");
if (sb.length() < 16)
sb.append("\t");
sb.append("\t");
if (Options.check("BINDTTL"))
sb.append(TTL.format(ttl));
else
sb.append(ttl);
sb.append("\t");
if (dclass != DClass.IN || !Options.check("noPrintIN")) {
sb.append(DClass.string(dclass));
sb.append("\t");
}
sb.append(Type.string(type));
if (!empty) {
sb.append("\t");
sb.append(rrToString());
}
return sb.toString();
}
/**
* Converts the text format of an RR to the internal format - must be overriden
*/
abstract void
rdataFromString(Tokenizer st, Name origin) throws IOException;
/**
* Converts a String into a byte array.
*/
protected static byte []
byteArrayFromString(String s) throws TextParseException {
byte [] array = s.getBytes();
boolean escaped = false;
boolean hasEscapes = false;
for (int i = 0; i < array.length; i++) {
if (array[i] == '\\') {
hasEscapes = true;
break;
}
}
if (!hasEscapes) {
if (array.length > 255) {
throw new TextParseException("text string too long");
}
return array;
}
ByteArrayOutputStream os = new ByteArrayOutputStream();
int digits = 0;
int intval = 0;
for (int i = 0; i < array.length; i++) {
byte b = array[i];
if (escaped) {
if (b >= '0' && b <= '9' && digits < 3) {
digits++;
intval *= 10;
intval += (b - '0');
if (intval > 255)
throw new TextParseException
("bad escape");
if (digits < 3)
continue;
b = (byte) intval;
}
else if (digits > 0 && digits < 3)
throw new TextParseException("bad escape");
os.write(b);
escaped = false;
}
else if (array[i] == '\\') {
escaped = true;
digits = 0;
intval = 0;
}
else
os.write(array[i]);
}
if (digits > 0 && digits < 3)
throw new TextParseException("bad escape");
array = os.toByteArray();
if (array.length > 255) {
throw new TextParseException("text string too long");
}
return os.toByteArray();
}
/**
* Converts a byte array into a String.
*/
protected static String
byteArrayToString(byte [] array, boolean quote) {
StringBuffer sb = new StringBuffer();
if (quote)
sb.append('"');
for (int i = 0; i < array.length; i++) {
short b = (short)(array[i] & 0xFF);
if (b < 0x20 || b >= 0x7f) {
sb.append('\\');
sb.append(byteFormat.format(b));
} else if (b == '"' || b == ';' || b == '\\') {
sb.append('\\');
sb.append((char)b);
} else
sb.append((char)b);
}
if (quote)
sb.append('"');
return sb.toString();
}
/**
* Converts a byte array into the unknown RR format.
*/
protected static String
unknownToString(byte [] data) {
StringBuffer sb = new StringBuffer();
sb.append("\\
sb.append(data.length);
sb.append(" ");
sb.append(base16.toString(data));
return sb.toString();
}
/**
* Builds a new Record from its textual representation
* @param name The owner name of the record.
* @param type The record's type.
* @param dclass The record's class.
* @param ttl The record's time to live.
* @param st A tokenizer containing the textual representation of the rdata.
* @param origin The default origin to be appended to relative domain names.
* @return The new record
* @throws IOException The text format was invalid.
*/
public static Record
fromString(Name name, int type, int dclass, long ttl, Tokenizer st, Name origin)
throws IOException
{
Record rec;
if (!name.isAbsolute())
throw new RelativeNameException(name);
Type.check(type);
DClass.check(dclass);
TTL.check(ttl);
Tokenizer.Token t = st.get();
if (t.type == Tokenizer.IDENTIFIER && t.value.equals("\\
int length = st.getUInt16();
byte [] data = st.getHex();
if (data == null) {
data = new byte[0];
}
if (length != data.length)
throw st.exception("invalid unknown RR encoding: " +
"length mismatch");
DNSInput in = new DNSInput(data);
return newRecord(name, type, dclass, ttl, length, in);
}
st.unget();
rec = getEmptyRecord(name, type, dclass, ttl);
rec.rdataFromString(st, origin);
t = st.get();
if (t.type != Tokenizer.EOL && t.type != Tokenizer.EOF) {
throw st.exception("unexpected tokens at end of record");
}
return rec;
}
/**
* Builds a new Record from its textual representation
* @param name The owner name of the record.
* @param type The record's type.
* @param dclass The record's class.
* @param ttl The record's time to live.
* @param s The textual representation of the rdata.
* @param origin The default origin to be appended to relative domain names.
* @return The new record
* @throws IOException The text format was invalid.
*/
public static Record
fromString(Name name, int type, int dclass, long ttl, String s, Name origin)
throws IOException
{
return fromString(name, type, dclass, ttl, new Tokenizer(s), origin);
}
/**
* Returns the record's name
* @see Name
*/
public Name
getName() {
return name;
}
/**
* Returns the record's type
* @see Type
*/
public int
getType() {
return type;
}
/**
* Returns the type of RRset that this record would belong to. For all types
* except SIGRecord, this is equivalent to getType().
* @return The type of record, if not SIGRecord. If the type is SIGRecord,
* the type covered is returned.
* @see Type
* @see RRset
* @see SIGRecord
*/
public int
getRRsetType() {
if (type == Type.SIG || type == Type.RRSIG) {
SIGBase sig = (SIGBase) this;
return sig.getTypeCovered();
}
return type;
}
/**
* Returns the record's class
*/
public int
getDClass() {
return dclass;
}
/**
* Returns the record's TTL
*/
public long
getTTL() {
return ttl;
}
/**
* Converts the type-specific RR to wire format - must be overriden
*/
abstract void
rrToWire(DNSOutput out, Compression c, boolean canonical);
/**
* Determines if two Records are identical. This compares the name, type,
* class, and rdata (with names canonicalized). The TTLs are not compared.
* @param arg The record to compare to
* @return true if the records are equal, false otherwise.
*/
public boolean
equals(Object arg) {
if (arg == null || !(arg instanceof Record))
return false;
Record r = (Record) arg;
if (type != r.type || dclass != r.dclass || !name.equals(r.name))
return false;
if (empty && r.empty)
return true;
else if (empty || r.empty)
return false;
byte [] array1 = rdataToWireCanonical();
byte [] array2 = r.rdataToWireCanonical();
return Arrays.equals(array1, array2);
}
/**
* Generates a hash code based on the Record's data.
*/
public int
hashCode() {
byte [] array = toWireCanonical(true);
int code = 0;
for (int i = 0; i < array.length; i++)
code += ((code << 3) + (array[i] & 0xFF));
return code;
}
private Record
cloneRecord() {
try {
return (Record) clone();
}
catch (CloneNotSupportedException e) {
throw new IllegalStateException();
}
}
/**
* Creates a new record identical to the current record, but with a different
* name. This is most useful for replacing the name of a wildcard record.
*/
public Record
withName(Name name) {
if (!name.isAbsolute())
throw new RelativeNameException(name);
Record rec = cloneRecord();
rec.name = name;
return rec;
}
/**
* Creates a new record identical to the current record, but with a different
* class and ttl. This is most useful for dynamic update.
*/
Record
withDClass(int dclass, long ttl) {
Record rec = cloneRecord();
rec.dclass = dclass;
rec.ttl = ttl;
return rec;
}
/**
* Compares this Record to another Object.
* @param o The Object to be compared.
* @return The value 0 if the argument is a record equivalent to this record;
* a value less than 0 if the argument is less than this record in the
* canonical ordering, and a value greater than 0 if the argument is greater
* than this record in the canonical ordering. The canonical ordering
* is defined to compare by name, class, type, and rdata.
* @throws ClassCastException if the argument is not a Record.
*/
public int
compareTo(Object o) {
Record arg = (Record) o;
if (this == arg)
return (0);
int n = name.compareTo(arg.name);
if (n != 0)
return (n);
n = dclass - arg.dclass;
if (n != 0)
return (n);
n = type - arg.type;
if (n != 0)
return (n);
if (empty && arg.empty)
return 0;
else if (empty)
return -1;
else if (arg.empty)
return 1;
byte [] rdata1 = rdataToWireCanonical();
byte [] rdata2 = arg.rdataToWireCanonical();
for (int i = 0; i < rdata1.length && i < rdata2.length; i++) {
n = (rdata1[i] & 0xFF) - (rdata2[i] & 0xFF);
if (n != 0)
return (n);
}
return (rdata1.length - rdata2.length);
}
/**
* Returns the name for which additional data processing should be done
* for this record. This can be used both for building responses and
* parsing responses.
* @return The name to used for additional data processing, or null if this
* record type does not require additional data processing.
*/
public Name
getAdditionalName() {
return null;
}
/* Checks that an int contains an unsigned 8 bit value */
static int
checkU8(String field, int val) {
if (val < 0 || val > 0xFF)
throw new IllegalArgumentException("\"" + field + "\" " + val +
"must be an unsigned 8 " +
"bit value");
return val;
}
/* Checks that an int contains an unsigned 16 bit value */
static int
checkU16(String field, int val) {
if (val < 0 || val > 0xFFFF)
throw new IllegalArgumentException("\"" + field + "\" " + val +
"must be an unsigned 16 " +
"bit value");
return val;
}
/* Checks that a long contains an unsigned 32 bit value */
static long
checkU32(String field, long val) {
if (val < 0 || val > 0xFFFFFFFFL)
throw new IllegalArgumentException("\"" + field + "\" " + val +
"must be an unsigned 32 " +
"bit value");
return val;
}
/* Checks that a name is absolute */
static Name
checkName(String field, Name name) {
if (!name.isAbsolute())
throw new RelativeNameException(name);
return name;
}
} |
package org.xbill.DNS;
import java.io.*;
import java.text.*;
import java.lang.reflect.*;
import java.util.*;
import org.xbill.DNS.utils.*;
/**
* A generic DNS resource record. The specific record types extend this class.
* A record contains a name, type, class, and rdata.
*
* @author Brian Wellington
*/
public abstract class Record implements Cloneable, Comparable {
protected Name name;
protected int type, dclass;
protected long ttl;
private static final Record [] knownRecords = new Record[256];
private static final Record unknownRecord = new UNKRecord();
private static final Class [] emptyClassArray = new Class[0];
private static final Object [] emptyObjectArray = new Object[0];
private static final DecimalFormat byteFormat = new DecimalFormat();
static {
byteFormat.setMinimumIntegerDigits(3);
}
protected
Record() {}
Record(Name name, int type, int dclass, long ttl) {
if (!name.isAbsolute())
throw new RelativeNameException(name);
Type.check(type);
DClass.check(dclass);
TTL.check(ttl);
this.name = name;
this.type = type;
this.dclass = dclass;
this.ttl = ttl;
}
/**
* Creates an empty record of the correct type; must be overriden
*/
abstract Record
getObject();
private static final Record
getTypedObject(int type) {
if (type < 0 || type > knownRecords.length)
return unknownRecord.getObject();
if (knownRecords[type] != null)
return knownRecords[type];
/* Construct the class name by putting the type before "Record". */
String s = Record.class.getPackage().getName() + "." +
Type.string(type).replace('-', '_') + "Record";
try {
Class c = Class.forName(s);
Constructor m = c.getDeclaredConstructor(emptyClassArray);
knownRecords[type] = (Record) m.newInstance(emptyObjectArray);
}
catch (ClassNotFoundException e) {
/* This is normal; do nothing */
}
catch (Exception e) {
if (Options.check("verbose"))
System.err.println(e);
}
if (knownRecords[type] == null)
knownRecords[type] = unknownRecord.getObject();
return knownRecords[type];
}
private static final Record
getEmptyRecord(Name name, int type, int dclass, long ttl, boolean hasData) {
Record rec;
if (hasData)
rec = getTypedObject(type).getObject();
else
rec = new EmptyRecord();
rec.name = name;
rec.type = type;
rec.dclass = dclass;
rec.ttl = ttl;
return rec;
}
/**
* Converts the type-specific RR to wire format - must be overriden
*/
abstract void
rrFromWire(DNSInput in) throws IOException;
private static Record
newRecord(Name name, int type, int dclass, long ttl, int length, DNSInput in)
throws IOException
{
Record rec;
int recstart;
rec = getEmptyRecord(name, type, dclass, ttl, in != null);
if (in != null) {
if (in.remaining() < length)
throw new WireParseException("truncated record");
in.setActive(length);
rec.rrFromWire(in);
if (in.remaining() > 0)
throw new WireParseException("invalid record length");
in.clearActive();
}
return rec;
}
/**
* Creates a new record, with the given parameters.
* @param name The owner name of the record.
* @param type The record's type.
* @param dclass The record's class.
* @param ttl The record's time to live.
* @param length The length of the record's data.
* @param data The rdata of the record, in uncompressed DNS wire format. Only
* the first length bytes are used.
*/
public static Record
newRecord(Name name, int type, int dclass, long ttl, int length, byte [] data) {
if (!name.isAbsolute())
throw new RelativeNameException(name);
Type.check(type);
DClass.check(dclass);
TTL.check(ttl);
DNSInput in;
if (data != null)
in = new DNSInput(data);
else
in = null;
try {
return newRecord(name, type, dclass, ttl, length, in);
}
catch (IOException e) {
return null;
}
}
/**
* Creates a new record, with the given parameters.
* @param name The owner name of the record.
* @param type The record's type.
* @param dclass The record's class.
* @param ttl The record's time to live.
* @param data The complete rdata of the record, in uncompressed DNS wire
* format.
*/
public static Record
newRecord(Name name, int type, int dclass, long ttl, byte [] data) {
return newRecord(name, type, dclass, ttl, data.length, data);
}
/**
* Creates a new empty record, with the given parameters.
* @param name The owner name of the record.
* @param type The record's type.
* @param dclass The record's class.
* @param ttl The record's time to live.
* @return An object of a subclass of Record
*/
public static Record
newRecord(Name name, int type, int dclass, long ttl) {
if (!name.isAbsolute())
throw new RelativeNameException(name);
Type.check(type);
DClass.check(dclass);
TTL.check(ttl);
return getEmptyRecord(name, type, dclass, ttl, false);
}
/**
* Creates a new empty record, with the given parameters. This method is
* designed to create records that will be added to the QUERY section
* of a message.
* @param name The owner name of the record.
* @param type The record's type.
* @param dclass The record's class.
* @return An object of a subclass of Record
*/
public static Record
newRecord(Name name, int type, int dclass) {
return newRecord(name, type, dclass, 0);
}
static Record
fromWire(DNSInput in, int section, boolean isUpdate) throws IOException {
int type, dclass;
long ttl;
int length;
Name name;
Record rec;
name = new Name(in);
type = in.readU16();
dclass = in.readU16();
if (section == Section.QUESTION)
return newRecord(name, type, dclass);
ttl = in.readU32();
length = in.readU16();
if (length == 0 && isUpdate)
return newRecord(name, type, dclass, ttl);
rec = newRecord(name, type, dclass, ttl, length, in);
return rec;
}
static Record
fromWire(DNSInput in, int section) throws IOException {
return fromWire(in, section, false);
}
/**
* Builds a Record from DNS uncompressed wire format.
*/
public static Record
fromWire(byte [] b, int section) throws IOException {
return fromWire(new DNSInput(b), section, false);
}
void
toWire(DNSOutput out, int section, Compression c) {
int start = out.current();
name.toWire(out, c);
out.writeU16(type);
out.writeU16(dclass);
if (section == Section.QUESTION)
return;
out.writeU32(ttl);
int lengthPosition = out.current();
out.writeU16(0); /* until we know better */
rrToWire(out, c, false);
int rrlength = out.current() - lengthPosition - 2;
out.save();
out.jump(lengthPosition);
out.writeU16(rrlength);
out.restore();
}
/**
* Converts a Record into DNS uncompressed wire format.
*/
public byte []
toWire(int section) {
DNSOutput out = new DNSOutput();
toWire(out, section, null);
return out.toByteArray();
}
private void
toWireCanonical(DNSOutput out, boolean noTTL) {
name.toWireCanonical(out);
out.writeU16(type);
out.writeU16(dclass);
if (noTTL) {
out.writeU32(0);
} else {
out.writeU32(ttl);
}
int lengthPosition = out.current();
out.writeU16(0); /* until we know better */
rrToWire(out, null, true);
int rrlength = out.current() - lengthPosition - 2;
out.save();
out.jump(lengthPosition);
out.writeU16(rrlength);
out.restore();
}
/*
* Converts a Record into canonical DNS uncompressed wire format (all names are
* converted to lowercase), optionally ignoring the TTL.
*/
private byte []
toWireCanonical(boolean noTTL) {
DNSOutput out = new DNSOutput();
toWireCanonical(out, noTTL);
return out.toByteArray();
}
/**
* Converts a Record into canonical DNS uncompressed wire format (all names are
* converted to lowercase).
*/
public byte []
toWireCanonical() {
return toWireCanonical(false);
}
/**
* Converts the rdata in a Record into canonical DNS uncompressed wire format
* (all names are converted to lowercase).
*/
public byte []
rdataToWireCanonical() {
DNSOutput out = new DNSOutput();
rrToWire(out, null, true);
return out.toByteArray();
}
/**
* Converts the type-specific RR to text format - must be overriden
*/
abstract String rrToString();
/**
* Converts the rdata portion of a Record into a String representation
*/
public String
rdataToString() {
return rrToString();
}
/**
* Converts a Record into a String representation
*/
public String
toString() {
StringBuffer sb = new StringBuffer();
sb.append(name);
if (sb.length() < 8)
sb.append("\t");
if (sb.length() < 16)
sb.append("\t");
sb.append("\t");
if (Options.check("BINDTTL"))
sb.append(TTL.format(ttl));
else
sb.append(ttl);
sb.append("\t");
if (dclass != DClass.IN || !Options.check("noPrintIN")) {
sb.append(DClass.string(dclass));
sb.append("\t");
}
sb.append(Type.string(type));
String rdata = rrToString();
if (!rdata.equals("")) {
sb.append("\t");
sb.append(rdata);
}
return sb.toString();
}
/**
* Converts the text format of an RR to the internal format - must be overriden
*/
abstract void
rdataFromString(Tokenizer st, Name origin) throws IOException;
/**
* Converts a String into a byte array.
*/
protected static byte []
byteArrayFromString(String s) throws TextParseException {
byte [] array = s.getBytes();
boolean escaped = false;
boolean hasEscapes = false;
for (int i = 0; i < array.length; i++) {
if (array[i] == '\\') {
hasEscapes = true;
break;
}
}
if (!hasEscapes) {
if (array.length > 255) {
throw new TextParseException("text string too long");
}
return array;
}
ByteArrayOutputStream os = new ByteArrayOutputStream();
int digits = 0;
int intval = 0;
for (int i = 0; i < array.length; i++) {
byte b = array[i];
if (escaped) {
if (b >= '0' && b <= '9' && digits < 3) {
digits++;
intval *= 10;
intval += (b - '0');
if (intval > 255)
throw new TextParseException
("bad escape");
if (digits < 3)
continue;
b = (byte) intval;
}
else if (digits > 0 && digits < 3)
throw new TextParseException("bad escape");
os.write(b);
escaped = false;
}
else if (array[i] == '\\') {
escaped = true;
digits = 0;
intval = 0;
}
else
os.write(array[i]);
}
if (digits > 0 && digits < 3)
throw new TextParseException("bad escape");
array = os.toByteArray();
if (array.length > 255) {
throw new TextParseException("text string too long");
}
return os.toByteArray();
}
/**
* Converts a byte array into a String.
*/
protected static String
byteArrayToString(byte [] array, boolean quote) {
StringBuffer sb = new StringBuffer();
if (quote)
sb.append('"');
for (int i = 0; i < array.length; i++) {
int b = array[i] & 0xFF;
if (b < 0x20 || b >= 0x7f) {
sb.append('\\');
sb.append(byteFormat.format(b));
} else if (b == '"' || b == ';' || b == '\\') {
sb.append('\\');
sb.append((char)b);
} else
sb.append((char)b);
}
if (quote)
sb.append('"');
return sb.toString();
}
/**
* Converts a byte array into the unknown RR format.
*/
protected static String
unknownToString(byte [] data) {
StringBuffer sb = new StringBuffer();
sb.append("\\
sb.append(data.length);
sb.append(" ");
sb.append(base16.toString(data));
return sb.toString();
}
/**
* Builds a new Record from its textual representation
* @param name The owner name of the record.
* @param type The record's type.
* @param dclass The record's class.
* @param ttl The record's time to live.
* @param st A tokenizer containing the textual representation of the rdata.
* @param origin The default origin to be appended to relative domain names.
* @return The new record
* @throws IOException The text format was invalid.
*/
public static Record
fromString(Name name, int type, int dclass, long ttl, Tokenizer st, Name origin)
throws IOException
{
Record rec;
if (!name.isAbsolute())
throw new RelativeNameException(name);
Type.check(type);
DClass.check(dclass);
TTL.check(ttl);
Tokenizer.Token t = st.get();
if (t.type == Tokenizer.IDENTIFIER && t.value.equals("\\
int length = st.getUInt16();
byte [] data = st.getHex();
if (data == null) {
data = new byte[0];
}
if (length != data.length)
throw st.exception("invalid unknown RR encoding: " +
"length mismatch");
DNSInput in = new DNSInput(data);
return newRecord(name, type, dclass, ttl, length, in);
}
st.unget();
rec = getEmptyRecord(name, type, dclass, ttl, true);
rec.rdataFromString(st, origin);
t = st.get();
if (t.type != Tokenizer.EOL && t.type != Tokenizer.EOF) {
throw st.exception("unexpected tokens at end of record");
}
return rec;
}
/**
* Builds a new Record from its textual representation
* @param name The owner name of the record.
* @param type The record's type.
* @param dclass The record's class.
* @param ttl The record's time to live.
* @param s The textual representation of the rdata.
* @param origin The default origin to be appended to relative domain names.
* @return The new record
* @throws IOException The text format was invalid.
*/
public static Record
fromString(Name name, int type, int dclass, long ttl, String s, Name origin)
throws IOException
{
return fromString(name, type, dclass, ttl, new Tokenizer(s), origin);
}
/**
* Returns the record's name
* @see Name
*/
public Name
getName() {
return name;
}
/**
* Returns the record's type
* @see Type
*/
public int
getType() {
return type;
}
/**
* Returns the type of RRset that this record would belong to. For all types
* except SIGRecord, this is equivalent to getType().
* @return The type of record, if not SIGRecord. If the type is SIGRecord,
* the type covered is returned.
* @see Type
* @see RRset
* @see SIGRecord
*/
public int
getRRsetType() {
if (type == Type.SIG || type == Type.RRSIG) {
SIGBase sig = (SIGBase) this;
return sig.getTypeCovered();
}
return type;
}
/**
* Returns the record's class
*/
public int
getDClass() {
return dclass;
}
/**
* Returns the record's TTL
*/
public long
getTTL() {
return ttl;
}
/**
* Converts the type-specific RR to wire format - must be overriden
*/
abstract void
rrToWire(DNSOutput out, Compression c, boolean canonical);
/**
* Determines if two Records could be part of the same RRset.
* This compares the name, type, and class of the Records; the ttl and
* rdata are not compared.
*/
public boolean
sameRRset(Record rec) {
return (getRRsetType() == rec.getRRsetType() &&
dclass == rec.dclass &&
name.equals(rec.name));
}
/**
* Determines if two Records are identical. This compares the name, type,
* class, and rdata (with names canonicalized). The TTLs are not compared.
* @param arg The record to compare to
* @return true if the records are equal, false otherwise.
*/
public boolean
equals(Object arg) {
if (arg == null || !(arg instanceof Record))
return false;
Record r = (Record) arg;
if (type != r.type || dclass != r.dclass || !name.equals(r.name))
return false;
byte [] array1 = rdataToWireCanonical();
byte [] array2 = r.rdataToWireCanonical();
return Arrays.equals(array1, array2);
}
/**
* Generates a hash code based on the Record's data.
*/
public int
hashCode() {
byte [] array = toWireCanonical(true);
int code = 0;
for (int i = 0; i < array.length; i++)
code += ((code << 3) + (array[i] & 0xFF));
return code;
}
private Record
cloneRecord() {
try {
return (Record) clone();
}
catch (CloneNotSupportedException e) {
throw new IllegalStateException();
}
}
/**
* Creates a new record identical to the current record, but with a different
* name. This is most useful for replacing the name of a wildcard record.
*/
public Record
withName(Name name) {
if (!name.isAbsolute())
throw new RelativeNameException(name);
Record rec = cloneRecord();
rec.name = name;
return rec;
}
/**
* Creates a new record identical to the current record, but with a different
* class and ttl. This is most useful for dynamic update.
*/
Record
withDClass(int dclass, long ttl) {
Record rec = cloneRecord();
rec.dclass = dclass;
rec.ttl = ttl;
return rec;
}
/* Sets the TTL to the specified value. This is intentionally not public. */
void
setTTL(long ttl) {
this.ttl = ttl;
}
/**
* Compares this Record to another Object.
* @param o The Object to be compared.
* @return The value 0 if the argument is a record equivalent to this record;
* a value less than 0 if the argument is less than this record in the
* canonical ordering, and a value greater than 0 if the argument is greater
* than this record in the canonical ordering. The canonical ordering
* is defined to compare by name, class, type, and rdata.
* @throws ClassCastException if the argument is not a Record.
*/
public int
compareTo(Object o) {
Record arg = (Record) o;
if (this == arg)
return (0);
int n = name.compareTo(arg.name);
if (n != 0)
return (n);
n = dclass - arg.dclass;
if (n != 0)
return (n);
n = type - arg.type;
if (n != 0)
return (n);
byte [] rdata1 = rdataToWireCanonical();
byte [] rdata2 = arg.rdataToWireCanonical();
for (int i = 0; i < rdata1.length && i < rdata2.length; i++) {
n = (rdata1[i] & 0xFF) - (rdata2[i] & 0xFF);
if (n != 0)
return (n);
}
return (rdata1.length - rdata2.length);
}
/**
* Returns the name for which additional data processing should be done
* for this record. This can be used both for building responses and
* parsing responses.
* @return The name to used for additional data processing, or null if this
* record type does not require additional data processing.
*/
public Name
getAdditionalName() {
return null;
}
/* Checks that an int contains an unsigned 8 bit value */
static int
checkU8(String field, int val) {
if (val < 0 || val > 0xFF)
throw new IllegalArgumentException("\"" + field + "\" " + val +
"must be an unsigned 8 " +
"bit value");
return val;
}
/* Checks that an int contains an unsigned 16 bit value */
static int
checkU16(String field, int val) {
if (val < 0 || val > 0xFFFF)
throw new IllegalArgumentException("\"" + field + "\" " + val +
"must be an unsigned 16 " +
"bit value");
return val;
}
/* Checks that a long contains an unsigned 32 bit value */
static long
checkU32(String field, long val) {
if (val < 0 || val > 0xFFFFFFFFL)
throw new IllegalArgumentException("\"" + field + "\" " + val +
"must be an unsigned 32 " +
"bit value");
return val;
}
/* Checks that a name is absolute */
static Name
checkName(String field, Name name) {
if (!name.isAbsolute())
throw new RelativeNameException(name);
return name;
}
} |
package com.sunteam.ebook.util;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.os.Handler;
import android.os.Message;
/**
* MediaPlayer
*
* @author wzp
*/
public class MediaPlayerUtils
{
private static final int MSG_PLAY_COMPLETION = 100;
private static final int MSG_PLAY_PROGRESS = 200;
private static MediaPlayerUtils instance = null;
private MediaPlayer mMediaPlayer = null;
private OnMediaPlayerListener mOnMediaPlayerListener = null;
private PlayStatus mPlayStatus = PlayStatus.STOP;
private android.os.CountDownTimer mCountDownTimer = null;
public interface OnMediaPlayerListener
{
public void onPlayCompleted();
public void onPlayError();
public void onSpeakProgress(int percent);
}
public enum PlayStatus
{
STOP,
PAUSE,
PLAY,
}
public void OnMediaPlayerListener( OnMediaPlayerListener listener )
{
mOnMediaPlayerListener = listener;
}
public PlayStatus getPlayStatus()
{
return mPlayStatus;
}
public static MediaPlayerUtils getInstance()
{
if( null == instance )
{
instance = new MediaPlayerUtils();
}
return instance;
}
public void init()
{
if( null == mMediaPlayer )
{
mMediaPlayer = new MediaPlayer();
}
}
public void destroy()
{
stop();
if( mMediaPlayer != null )
{
mMediaPlayer.release();
mMediaPlayer = null;
}
}
public void pause()
{
if( mMediaPlayer != null )
{
if( PlayStatus.PLAY == mPlayStatus )
{
mMediaPlayer.pause();
mPlayStatus = PlayStatus.PAUSE;
}
}
}
public void resume()
{
if( mMediaPlayer != null )
{
if( PlayStatus.PAUSE == mPlayStatus )
{
mMediaPlayer.start();
mPlayStatus = PlayStatus.PLAY;
}
}
}
public void stop()
{
if( mCountDownTimer != null )
{
mCountDownTimer.cancel();
mCountDownTimer = null;
}
if( mMediaPlayer != null )
{
if( PlayStatus.STOP != mPlayStatus )
{
mMediaPlayer.stop();
mPlayStatus = PlayStatus.STOP;
}
}
}
/**
*
*
* @param text
*/
public void play( final String audioPath, final long startTime, final long endTime )
{
if( ( null == audioPath ) || ( ( endTime - startTime ) <= 0 ) )
{
//mHandler.sendEmptyMessage(MSG_PLAY_COMPLETION);
return;
}
stop();
if( mMediaPlayer != null )
{
try
{
mMediaPlayer.reset();
mMediaPlayer.setDataSource(audioPath);
mMediaPlayer.prepare();
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer m) {
// TODO Auto-generated method stub
mMediaPlayer.seekTo((int)startTime);
}
});
mMediaPlayer.setOnSeekCompleteListener(new OnSeekCompleteListener(){
@Override
public void onSeekComplete(MediaPlayer m)
{
// TODO Auto-generated method stub
mMediaPlayer.start();
mPlayStatus = PlayStatus.PLAY;
final long time = endTime-startTime;
mCountDownTimer = new android.os.CountDownTimer( time, time/100 )
{
@Override
public void onTick(long millisUntilFinished)
{
// TODO Auto-generated method stub
if( mMediaPlayer != null && mMediaPlayer.isPlaying() )
{
Message msg = mHandler.obtainMessage();
msg.what = MSG_PLAY_PROGRESS;
msg.arg1 = (int)((time-millisUntilFinished)*100/time);
mHandler.sendMessage(msg);
}
}
@Override
public void onFinish()
{
// TODO Auto-generated method stub
if( mMediaPlayer != null && mMediaPlayer.isPlaying() )
{
mHandler.sendEmptyMessage(MSG_PLAY_COMPLETION);
}
}
};
mCountDownTimer.start();
}
});
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp)
{
// TODO Auto-generated method stub
mPlayStatus = PlayStatus.STOP;
if( mOnMediaPlayerListener != null )
{
mOnMediaPlayerListener.onPlayCompleted();
}
}
});
mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
mPlayStatus = PlayStatus.STOP;
if( mOnMediaPlayerListener != null )
{
mOnMediaPlayerListener.onPlayError();
}
return false;
}
});
}
catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SecurityException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalStateException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
*
*
* @param text
*/
public void play( final String audioPath )
{
stop();
if( mMediaPlayer != null )
{
try
{
mMediaPlayer.reset();
mMediaPlayer.setDataSource(audioPath);
mMediaPlayer.prepare();
mMediaPlayer.setLooping(true);
mMediaPlayer.start();
mPlayStatus = PlayStatus.PLAY;
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp)
{
// TODO Auto-generated method stub
mPlayStatus = PlayStatus.STOP;
if( mOnMediaPlayerListener != null )
{
mOnMediaPlayerListener.onPlayCompleted();
}
}
});
mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
mPlayStatus = PlayStatus.STOP;
if( mOnMediaPlayerListener != null )
{
mOnMediaPlayerListener.onPlayError();
}
return false;
}
});
}
catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SecurityException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalStateException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(android.os.Message msg)
{
switch (msg.what)
{
case MSG_PLAY_COMPLETION:
mCountDownTimer = null;
stop();
if( mOnMediaPlayerListener != null )
{
mOnMediaPlayerListener.onPlayCompleted();
}
break;
case MSG_PLAY_PROGRESS:
if ( mOnMediaPlayerListener != null )
{
mOnMediaPlayerListener.onSpeakProgress(msg.arg1);
}
break;
default:
break;
}
return false;
}
});
} |
package com.jbooktrader.platform.report;
import com.jbooktrader.platform.startup.*;
import java.io.*;
public abstract class Report {
protected static final String FIELD_START = "<td>";
protected static final String FIELD_END = "</td>";
protected static final String HEADER_START = "<th>";
protected static final String HEADER_END = "</th>";
protected static final String ROW_START = "<tr>";
protected static final String ROW_END = "</tr>";
protected static final String FIELD_BREAK = "<br>";
private static final String REPORT_DIR;
private final PrintWriter writer;
static {
String fileSeparator = System.getProperty("file.separator");
REPORT_DIR = JBookTrader.getAppPath() + fileSeparator + "reports" + fileSeparator;
File reportDir = new File(REPORT_DIR);
if (!reportDir.exists()) {
reportDir.mkdir();
}
}
protected Report(String reportName) throws IOException {
String fullFileName = REPORT_DIR + reportName + ".htm";
File reportFile = new File(fullFileName);
boolean reportExisted = reportFile.exists();
writer = new PrintWriter(new BufferedWriter(new FileWriter(fullFileName, true)));
StringBuilder sb = new StringBuilder();
if (reportExisted) {
sb.append("</table><br>"); // close the previously created table
} else {
sb.append("<html>");
}
sb.append("<table border=\"1\" cellpadding=\"2\" cellspacing=\"0\" width=100%>");
write(sb);
}
protected synchronized void write(StringBuilder sb) {
writer.println(sb);
writer.flush();
}
} |
package VASSAL.build.module;
import VASSAL.tools.ProblemDialog;
import static java.lang.Math.round;
import java.awt.AWTEventMulticaster;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Component;
import java.awt.Composite;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.ActionListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.OverlayLayout;
import javax.swing.RootPaneContainer;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.lang3.SystemUtils;
import org.jdesktop.animation.timing.Animator;
import org.jdesktop.animation.timing.TimingTargetAdapter;
import org.w3c.dom.Element;
import VASSAL.build.AbstractConfigurable;
import VASSAL.build.AutoConfigurable;
import VASSAL.build.Buildable;
import VASSAL.build.Configurable;
import VASSAL.build.GameModule;
import VASSAL.build.IllegalBuildException;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.build.module.map.BoardPicker;
import VASSAL.build.module.map.CounterDetailViewer;
import VASSAL.build.module.map.DefaultPieceCollection;
import VASSAL.build.module.map.DrawPile;
import VASSAL.build.module.map.Drawable;
import VASSAL.build.module.map.Flare;
import VASSAL.build.module.map.ForwardToChatter;
import VASSAL.build.module.map.ForwardToKeyBuffer;
import VASSAL.build.module.map.GlobalMap;
import VASSAL.build.module.map.HidePiecesButton;
import VASSAL.build.module.map.HighlightLastMoved;
import VASSAL.build.module.map.ImageSaver;
import VASSAL.build.module.map.KeyBufferer;
import VASSAL.build.module.map.LOS_Thread;
import VASSAL.build.module.map.LayeredPieceCollection;
import VASSAL.build.module.map.MapCenterer;
import VASSAL.build.module.map.MapShader;
import VASSAL.build.module.map.MassKeyCommand;
import VASSAL.build.module.map.MenuDisplayer;
import VASSAL.build.module.map.PieceCollection;
import VASSAL.build.module.map.PieceMover;
import VASSAL.build.module.map.PieceRecenterer;
import VASSAL.build.module.map.Scroller;
import VASSAL.build.module.map.SelectionHighlighters;
import VASSAL.build.module.map.SetupStack;
import VASSAL.build.module.map.StackExpander;
import VASSAL.build.module.map.StackMetrics;
import VASSAL.build.module.map.TextSaver;
import VASSAL.build.module.map.Zoomer;
import VASSAL.build.module.map.boardPicker.Board;
import VASSAL.build.module.map.boardPicker.board.MapGrid;
import VASSAL.build.module.map.boardPicker.board.Region;
import VASSAL.build.module.map.boardPicker.board.RegionGrid;
import VASSAL.build.module.map.boardPicker.board.ZonedGrid;
import VASSAL.build.module.map.boardPicker.board.HexGrid;
import VASSAL.build.module.map.boardPicker.board.SquareGrid;
import VASSAL.build.module.map.boardPicker.board.mapgrid.Zone;
import VASSAL.build.module.properties.ChangePropertyCommandEncoder;
import VASSAL.build.module.properties.GlobalProperties;
import VASSAL.build.module.properties.MutablePropertiesContainer;
import VASSAL.build.module.properties.MutableProperty;
import VASSAL.build.module.properties.PropertySource;
import VASSAL.build.widget.MapWidget;
import VASSAL.command.AddPiece;
import VASSAL.command.Command;
import VASSAL.command.MoveTracker;
import VASSAL.configure.BooleanConfigurer;
import VASSAL.configure.ColorConfigurer;
import VASSAL.configure.CompoundValidityChecker;
import VASSAL.configure.Configurer;
import VASSAL.configure.ConfigurerFactory;
import VASSAL.configure.IconConfigurer;
import VASSAL.configure.IntConfigurer;
import VASSAL.configure.MandatoryComponent;
import VASSAL.configure.NamedHotKeyConfigurer;
import VASSAL.configure.PlayerIdFormattedStringConfigurer;
import VASSAL.configure.VisibilityCondition;
import VASSAL.counters.ColoredBorder;
import VASSAL.counters.Deck;
import VASSAL.counters.DeckVisitor;
import VASSAL.counters.DeckVisitorDispatcher;
import VASSAL.counters.DragBuffer;
import VASSAL.counters.GamePiece;
import VASSAL.counters.GlobalCommand;
import VASSAL.counters.Highlighter;
import VASSAL.counters.KeyBuffer;
import VASSAL.counters.PieceFinder;
import VASSAL.counters.PieceVisitorDispatcher;
import VASSAL.counters.Properties;
import VASSAL.counters.ReportState;
import VASSAL.counters.Stack;
import VASSAL.i18n.Resources;
import VASSAL.i18n.TranslatableConfigurerFactory;
import VASSAL.preferences.PositionOption;
import VASSAL.preferences.Prefs;
import VASSAL.tools.AdjustableSpeedScrollPane;
import VASSAL.tools.ComponentSplitter;
import VASSAL.tools.KeyStrokeSource;
import VASSAL.tools.LaunchButton;
import VASSAL.tools.NamedKeyStroke;
import VASSAL.tools.ToolBarComponent;
import VASSAL.tools.UniqueIdManager;
import VASSAL.tools.WrapLayout;
import VASSAL.tools.menu.MenuManager;
import VASSAL.tools.swing.SplitPane;
import VASSAL.tools.swing.SwingUtils;
/**
* The Map is the main component for displaying and containing {@link GamePiece}s during play. Pieces are displayed on
* the map's {@link Board}(s) and moved by clicking and dragging. Keyboard events are forwarded to selected pieces. Multiple
* map windows are supported in a single game, with dragging between windows allowed.
*
* To a map's {@link Board} subcomponent(s), various forms of grid can be added: ({@link ZonedGrid} (aka Multi-zone Grid),
* {@link HexGrid}, {@link SquareGrid} (aka Rectangular Grid), and {@link RegionGrid} (aka Irregular Grid). These can be used
* to determine where pieces are allowed to move, and also for filling properties (e.g. LocationName, CurrentZone, CurrentBoard,
* CurrentMap) to allow the module to keep track of pieces and react to their movements.
*
* A Map may contain many different {@link Buildable} subcomponents. Components which are addable <i>uniquely</i> to a Map are
* contained in the <code>VASSAL.build.module.map</code> package. Some of the most common Map subcomponents include
* {@link Zoomer} for Zoom Capability, {@link CounterDetailViewer} aka Mouse-over Stack Viewer, {@link HidePiecesButton},
* and {@link SelectionHighlighters}.
*
* Map also contain several critical subcomponents which are automatically added and are not configurable at the module level.
* These include {@link PieceMover} which handles dragging and dropping of pieces, {@link KeyBufferer} which tracks which pieces
* are currently "selected" and forwards key commands to them, {@link MenuDisplayer} which listens for "right clicks" and provides
* "context menu" services, and {@link StackMetrics} which handles the "stacking" of game pieces.
*/
public class Map extends AbstractConfigurable implements GameComponent, MouseListener, MouseMotionListener, DropTargetListener, Configurable,
UniqueIdManager.Identifyable, ToolBarComponent, MutablePropertiesContainer, PropertySource, PlayerRoster.SideChangeListener {
protected static boolean changeReportingEnabled = true;
protected String mapID = ""; //$NON-NLS-1$
protected String mapName = ""; //$NON-NLS-1$
protected static final String MAIN_WINDOW_HEIGHT = "mainWindowHeight"; //$NON-NLS-1$
protected static final UniqueIdManager idMgr = new UniqueIdManager("Map"); //$NON-NLS-1$
protected JPanel theMap; // Our main visual interface component
protected ArrayList<Drawable> drawComponents = new ArrayList<>();
protected JLayeredPane layeredPane = new JLayeredPane();
protected JScrollPane scroll;
/**
* @deprecated type will change to {@link SplitPane}
*/
@Deprecated(since = "2020-08-05", forRemoval = true)
protected ComponentSplitter.SplitPane mainWindowDock;
protected BoardPicker picker;
protected JToolBar toolBar = new JToolBar();
protected Zoomer zoom;
protected StackMetrics metrics;
protected Dimension edgeBuffer = new Dimension(0, 0);
protected Color bgColor = Color.white;
protected LaunchButton launchButton;
protected boolean useLaunchButton = false;
protected boolean useLaunchButtonEdit = false;
protected String markMovedOption = GlobalOptions.ALWAYS;
protected String markUnmovedIcon = "/images/unmoved.gif"; //$NON-NLS-1$
protected String markUnmovedText = ""; //$NON-NLS-1$
protected String markUnmovedTooltip = Resources.getString("Map.mark_unmoved"); //$NON-NLS-1$
protected MouseListener multicaster = null;
protected ArrayList<MouseListener> mouseListenerStack = new ArrayList<>();
protected List<Board> boards = new CopyOnWriteArrayList<>();
protected int[][] boardWidths; // Cache of board widths by row/column
protected int[][] boardHeights; // Cache of board heights by row/column
protected PieceCollection pieces = new DefaultPieceCollection();
protected Highlighter highlighter = new ColoredBorder();
protected ArrayList<Highlighter> highlighters = new ArrayList<>();
protected boolean clearFirst = false; // Whether to clear the display before
// drawing the map
protected boolean hideCounters = false; // Option to hide counters to see
// map
protected float pieceOpacity = 1.0f;
protected boolean allowMultiple = false;
protected VisibilityCondition visibilityCondition;
protected DragGestureListener dragGestureListener;
protected String moveWithinFormat;
protected String moveToFormat;
protected String createFormat;
protected String changeFormat = "$" + MESSAGE + "$"; //$NON-NLS-1$ //$NON-NLS-2$
protected NamedKeyStroke moveKey;
protected String tooltip = ""; //$NON-NLS-1$
protected MutablePropertiesContainer propsContainer = new MutablePropertiesContainer.Impl();
protected PropertyChangeListener repaintOnPropertyChange = evt -> repaint();
protected PieceMover pieceMover;
protected KeyListener[] saveKeyListeners = null;
public Map() {
getView();
theMap.addMouseListener(this);
if (shouldDockIntoMainWindow()) {
final String constraints =
(SystemUtils.IS_OS_MAC_OSX ? "ins 1 0 1 0" : "ins 0") +
",gapx 0,hidemode 3";
toolBar.setLayout(new MigLayout(constraints));
}
else {
toolBar.setLayout(new WrapLayout(WrapLayout.LEFT, 0, 0));
}
toolBar.setAlignmentX(0.0F);
toolBar.setFloatable(false);
}
/**
* @return Map's main visual interface swing component (its JPanel)
*/
public Component getComponent() {
return theMap;
}
/**
* Global Change Reporting control - used by Global Key Commands (see {@link GlobalCommand}) to
* temporarily disable reporting while they run, if their "Suppress individual reports" option is selected.
* @param b true to turn global change reporting on, false to turn it off.
*/
public static void setChangeReportingEnabled(boolean b) {
changeReportingEnabled = b;
}
/**
* @return true if change reporting is currently enabled, false if it is presently being suppressed by a Global Key Command.
*/
public static boolean isChangeReportingEnabled() {
return changeReportingEnabled;
}
public static final String NAME = "mapName"; //$NON-NLS-1$
public static final String MARK_MOVED = "markMoved"; //$NON-NLS-1$
public static final String MARK_UNMOVED_ICON = "markUnmovedIcon"; //$NON-NLS-1$
public static final String MARK_UNMOVED_TEXT = "markUnmovedText"; //$NON-NLS-1$
public static final String MARK_UNMOVED_TOOLTIP = "markUnmovedTooltip"; //$NON-NLS-1$
public static final String EDGE_WIDTH = "edgeWidth"; //$NON-NLS-1$
public static final String EDGE_HEIGHT = "edgeHeight"; //$NON-NLS-1$
public static final String BACKGROUND_COLOR = "backgroundcolor";
public static final String HIGHLIGHT_COLOR = "color"; //$NON-NLS-1$
public static final String HIGHLIGHT_THICKNESS = "thickness"; //$NON-NLS-1$
public static final String ALLOW_MULTIPLE = "allowMultiple"; //$NON-NLS-1$
public static final String USE_LAUNCH_BUTTON = "launch"; //$NON-NLS-1$
public static final String BUTTON_NAME = "buttonName"; //$NON-NLS-1$
public static final String TOOLTIP = "tooltip"; //$NON-NLS-1$
public static final String ICON = "icon"; //$NON-NLS-1$
public static final String HOTKEY = "hotkey"; //$NON-NLS-1$
public static final String SUPPRESS_AUTO = "suppressAuto"; //$NON-NLS-1$
public static final String MOVE_WITHIN_FORMAT = "moveWithinFormat"; //$NON-NLS-1$
public static final String MOVE_TO_FORMAT = "moveToFormat"; //$NON-NLS-1$
public static final String CREATE_FORMAT = "createFormat"; //$NON-NLS-1$
public static final String CHANGE_FORMAT = "changeFormat"; //$NON-NLS-1$
public static final String MOVE_KEY = "moveKey"; //$NON-NLS-1$
public static final String MOVING_STACKS_PICKUP_UNITS = "movingStacksPickupUnits"; //$NON-NLS-1$
/**
* Sets a buildFile (XML) attribute value for this component.
* @param key the name of the attribute. Will be one of those listed in {@link #getAttributeNames}
* @param value If the <code>value</code> parameter is a String, it will be the value returned by {@link #getAttributeValueString} for the same
* <code>key</code>. Since Map extends {@link AbstractConfigurable}, then <code>value</code> can also be an instance of
* the corresponding Class listed in {@link #getAttributeTypes}.
*/
@Override
public void setAttribute(String key, Object value) {
if (NAME.equals(key)) {
setMapName((String) value);
}
else if (MARK_MOVED.equals(key)) {
markMovedOption = (String) value;
}
else if (MARK_UNMOVED_ICON.equals(key)) {
markUnmovedIcon = (String) value;
if (pieceMover != null) {
pieceMover.setAttribute(key, value);
}
}
else if (MARK_UNMOVED_TEXT.equals(key)) {
markUnmovedText = (String) value;
if (pieceMover != null) {
pieceMover.setAttribute(key, value);
}
}
else if (MARK_UNMOVED_TOOLTIP.equals(key)) {
markUnmovedTooltip = (String) value;
}
else if ("edge".equals(key)) { // Backward-compatible //$NON-NLS-1$
String s = (String) value;
int i = s.indexOf(','); //$NON-NLS-1$
if (i > 0) {
edgeBuffer = new Dimension(Integer.parseInt(s.substring(0, i)), Integer.parseInt(s.substring(i + 1)));
}
}
else if (EDGE_WIDTH.equals(key)) {
if (value instanceof String) {
value = Integer.valueOf((String) value);
}
try {
edgeBuffer = new Dimension((Integer) value, edgeBuffer.height);
}
catch (NumberFormatException ex) {
throw new IllegalBuildException(ex);
}
}
else if (EDGE_HEIGHT.equals(key)) {
if (value instanceof String) {
value = Integer.valueOf((String) value);
}
try {
edgeBuffer = new Dimension(edgeBuffer.width, (Integer) value);
}
catch (NumberFormatException ex) {
throw new IllegalBuildException(ex);
}
}
else if (BACKGROUND_COLOR.equals(key)) {
if (value instanceof String) {
value = ColorConfigurer.stringToColor((String)value);
}
bgColor = (Color)value;
}
else if (ALLOW_MULTIPLE.equals(key)) {
if (value instanceof String) {
value = Boolean.valueOf((String) value);
}
allowMultiple = (Boolean) value;
if (picker != null) {
picker.setAllowMultiple(allowMultiple);
}
}
else if (HIGHLIGHT_COLOR.equals(key)) {
if (value instanceof String) {
value = ColorConfigurer.stringToColor((String) value);
}
if (value != null) {
((ColoredBorder) highlighter).setColor((Color) value);
}
}
else if (HIGHLIGHT_THICKNESS.equals(key)) {
if (value instanceof String) {
value = Integer.valueOf((String) value);
}
if (highlighter instanceof ColoredBorder) {
((ColoredBorder) highlighter).setThickness((Integer) value);
}
}
else if (USE_LAUNCH_BUTTON.equals(key)) {
if (value instanceof String) {
value = Boolean.valueOf((String) value);
}
useLaunchButtonEdit = (Boolean) value;
launchButton.setVisible(useLaunchButton);
}
else if (SUPPRESS_AUTO.equals(key)) {
if (value instanceof String) {
value = Boolean.valueOf((String) value);
}
if (Boolean.TRUE.equals(value)) {
moveWithinFormat = ""; //$NON-NLS-1$
}
}
else if (MOVE_WITHIN_FORMAT.equals(key)) {
moveWithinFormat = (String) value;
}
else if (MOVE_TO_FORMAT.equals(key)) {
moveToFormat = (String) value;
}
else if (CREATE_FORMAT.equals(key)) {
createFormat = (String) value;
}
else if (CHANGE_FORMAT.equals(key)) {
changeFormat = (String) value;
}
else if (MOVE_KEY.equals(key)) {
if (value instanceof String) {
value = NamedHotKeyConfigurer.decode((String) value);
}
moveKey = (NamedKeyStroke) value;
}
else if (TOOLTIP.equals(key)) {
tooltip = (String) value;
launchButton.setAttribute(key, value);
}
else {
launchButton.setAttribute(key, value);
}
}
/**
* @return a String representation of the XML buildFile attribute with the given name. When initializing a module,
* this String value will loaded from the XML and passed to {@link #setAttribute}. It is also frequently used for
* checking the current value of an attribute.
*
* @param key the name of the attribute. Will be one of those listed in {@link #getAttributeNames}
*/
@Override
public String getAttributeValueString(String key) {
if (NAME.equals(key)) {
return getMapName();
}
else if (MARK_MOVED.equals(key)) {
return markMovedOption;
}
else if (MARK_UNMOVED_ICON.equals(key)) {
return markUnmovedIcon;
}
else if (MARK_UNMOVED_TEXT.equals(key)) {
return markUnmovedText;
}
else if (MARK_UNMOVED_TOOLTIP.equals(key)) {
return markUnmovedTooltip;
}
else if (EDGE_WIDTH.equals(key)) {
return String.valueOf(edgeBuffer.width); //$NON-NLS-1$
}
else if (EDGE_HEIGHT.equals(key)) {
return String.valueOf(edgeBuffer.height); //$NON-NLS-1$
}
else if (BACKGROUND_COLOR.equals(key)) {
return ColorConfigurer.colorToString(bgColor);
}
else if (ALLOW_MULTIPLE.equals(key)) {
return String.valueOf(picker.isAllowMultiple()); //$NON-NLS-1$
}
else if (HIGHLIGHT_COLOR.equals(key)) {
if (highlighter instanceof ColoredBorder) {
return ColorConfigurer.colorToString(
((ColoredBorder) highlighter).getColor());
}
else {
return null;
}
}
else if (HIGHLIGHT_THICKNESS.equals(key)) {
if (highlighter instanceof ColoredBorder) {
return String.valueOf(
((ColoredBorder) highlighter).getThickness()); //$NON-NLS-1$
}
else {
return null;
}
}
else if (USE_LAUNCH_BUTTON.equals(key)) {
return String.valueOf(useLaunchButtonEdit);
}
else if (MOVE_WITHIN_FORMAT.equals(key)) {
return getMoveWithinFormat();
}
else if (MOVE_TO_FORMAT.equals(key)) {
return getMoveToFormat();
}
else if (CREATE_FORMAT.equals(key)) {
return getCreateFormat();
}
else if (CHANGE_FORMAT.equals(key)) {
return getChangeFormat();
}
else if (MOVE_KEY.equals(key)) {
return NamedHotKeyConfigurer.encode(moveKey);
}
else if (TOOLTIP.equals(key)) {
return (tooltip == null || tooltip.length() == 0)
? launchButton.getAttributeValueString(name) : tooltip;
}
else {
return launchButton.getAttributeValueString(key);
}
}
/**
* Builds the map's component hierarchy from a given XML element, or a null one is given initializes
* a brand new default "new map" hierarchy.
* @param e XML element to build from, or null to build the default hierarchy for a brand new Map
*/
@Override
public void build(Element e) {
ActionListener al = e1 -> {
if (mainWindowDock == null && launchButton.isEnabled() && theMap.getTopLevelAncestor() != null) {
theMap.getTopLevelAncestor().setVisible(!theMap.getTopLevelAncestor().isVisible());
}
};
launchButton = new LaunchButton(Resources.getString("Editor.Map.map"), TOOLTIP, BUTTON_NAME, HOTKEY, ICON, al);
launchButton.setEnabled(false);
launchButton.setVisible(false);
if (e != null) {
super.build(e);
getBoardPicker();
getStackMetrics();
}
else {
getBoardPicker();
getStackMetrics();
addChild(new ForwardToKeyBuffer());
addChild(new Scroller());
addChild(new ForwardToChatter());
addChild(new MenuDisplayer());
addChild(new MapCenterer());
addChild(new StackExpander());
addChild(new PieceMover());
addChild(new KeyBufferer());
addChild(new ImageSaver());
addChild(new CounterDetailViewer());
addChild(new Flare());
setMapName(Resources.getString("Map.main_map"));
}
if (getComponentsOf(GlobalProperties.class).isEmpty()) {
addChild(new GlobalProperties());
}
if (getComponentsOf(SelectionHighlighters.class).isEmpty()) {
addChild(new SelectionHighlighters());
}
if (getComponentsOf(HighlightLastMoved.class).isEmpty()) {
addChild(new HighlightLastMoved());
}
if (getComponentsOf(Flare.class).isEmpty()) {
addChild(new Flare());
}
setup(false);
}
/**
* Adds a child component to this map. Used by {@link #build} to create "default components" for a new map object
* @param b {@link Buildable} component to add
*/
private void addChild(Buildable b) {
add(b);
b.addTo(this);
}
/**
* Every map must include a single {@link BoardPicker} as one of its build components. This will contain
* the map's {@link Board} (or Boards), which will in turn contain any grids, zones, and location
* information.
* @param picker BoardPicker to register to the map. This method unregisters any previous BoardPicker.
*/
public void setBoardPicker(BoardPicker picker) {
if (this.picker != null) {
GameModule.getGameModule().removeCommandEncoder(picker);
GameModule.getGameModule().getGameState().addGameComponent(picker);
}
this.picker = picker;
if (picker != null) {
picker.setAllowMultiple(allowMultiple);
GameModule.getGameModule().addCommandEncoder(picker);
GameModule.getGameModule().getGameState().addGameComponent(picker);
}
}
/**
* Every map must include a {@link BoardPicker} as one of its build components. This contains
* the map's {@link Board} (or Boards), which will in turn contain any grids, zones, and location
* information.
* @return the BoardPicker for this map (if none exist, this method will add one and return it)
*/
public BoardPicker getBoardPicker() {
if (picker == null) {
picker = new BoardPicker();
picker.build(null);
add(picker);
picker.addTo(this);
}
return picker;
}
/**
* A map may include a single {@link Zoomer} as one of its build components. This adds zoom in/out capability to the map.
* @param z {@link Zoomer} to register
*/
public void setZoomer(Zoomer z) {
zoom = z;
}
/**
* A map may include a {@link Zoomer} as one of its build components. This adds zoom in/out capability to the map.
* @return the Zoomer for this map, if one is registered, or null if none.
*/
public Zoomer getZoomer() {
return zoom;
}
/**
* If the map has a {@link Zoomer} (see {@link #setZoomer}), then returns the Zoomer's current zoom factor. If no
* Zoomer exists, returns 1.0 as the zoom factor.
* @return the current zoom factor for the map
*/
public double getZoom() {
return zoom == null ? 1.0 : zoom.getZoomFactor();
}
/**
* Every map must include a single {@link StackMetrics} as one of its build components, which governs the stacking behavior
* of GamePieces on the map.
* @param sm {@link StackMetrics} component to register
*/
public void setStackMetrics(StackMetrics sm) {
metrics = sm;
}
/**
* Every map must include a single {@link StackMetrics} object as one of its build
* components, which governs the stacking behavior of GamePieces on the map
*
* @return the StackMetrics for this map
*/
public StackMetrics getStackMetrics() {
if (metrics == null) {
metrics = new StackMetrics();
metrics.build(null);
add(metrics);
metrics.addTo(this);
}
return metrics;
}
/**
* Every map must include a single {@link PieceMover} component as one of its build
* components, which handles drag-and-drop behavior for the map.
* @param mover {@link PieceMover} component to register
*/
public void setPieceMover(PieceMover mover) {
pieceMover = mover;
}
/**
* Every map window has a toolbar, and this method returns swing toolbar component for this map.
* @return the swing toolbar component ({@link JToolBar} for this map's window.
*/
@Override
public JToolBar getToolBar() {
return toolBar;
}
/**
* Registers a {@link Drawable} component to this map. Components can implement the {@link Drawable} interface (and register
* themselves here) if they have a graphical component that should be drawn whenever the Map is drawn. Standard examples
* include {@link CounterDetailViewer}s (aka Mouse-over Stack Viewers), {@link GlobalMap}s (aka Overview Maps), {@link LOS_Thread}s,
* {@link MapShader}s, and the {@link KeyBufferer} (to show which pieces are selected).
*/
public void addDrawComponent(Drawable theComponent) {
drawComponents.add(theComponent);
}
/**
* Unregister a {@link Drawable} component from this map
*/
public void removeDrawComponent(Drawable theComponent) {
drawComponents.remove(theComponent);
}
/**
* Registers this Map as a child of another buildable component, usually the {@link GameModule}. Determines a unique id for
* this Map. Registers itself as {@link KeyStrokeSource}. Registers itself as a {@link GameComponent}. Registers itself as
* a drop target and drag source. If the map is to be removed or otherwise shutdown, it can be deregistered, reversing this
* process, by {@link #removeFrom}
*
* @see #getId
* @see DragBuffer
*/
@Override
public void addTo(Buildable b) {
useLaunchButton = useLaunchButtonEdit;
idMgr.add(this);
final GameModule g = GameModule.getGameModule();
g.addCommandEncoder(new ChangePropertyCommandEncoder(this));
validator = new CompoundValidityChecker(
new MandatoryComponent(this, BoardPicker.class),
new MandatoryComponent(this, StackMetrics.class)).append(idMgr);
final DragGestureListener dgl = dge -> {
if (dragGestureListener != null &&
mouseListenerStack.isEmpty() &&
SwingUtils.isDragTrigger(dge)) {
dragGestureListener.dragGestureRecognized(dge);
}
};
DragSource.getDefaultDragSource().createDefaultDragGestureRecognizer(
theMap, DnDConstants.ACTION_MOVE, dgl);
theMap.setDropTarget(PieceMover.DragHandler.makeDropTarget(
theMap, DnDConstants.ACTION_MOVE, this));
g.getGameState().addGameComponent(this);
g.getToolBar().add(launchButton);
if (shouldDockIntoMainWindow()) {
final IntConfigurer config =
new IntConfigurer(MAIN_WINDOW_HEIGHT, null, -1);
Prefs.getGlobalPrefs().addOption(null, config);
mainWindowDock = g.getPlayerWindow().splitControlPanel(layeredPane, SplitPane.HIDE_BOTTOM, true);
mainWindowDock.setResizeWeight(0.0);
g.addKeyStrokeSource(
new KeyStrokeSource(theMap, JComponent.WHEN_FOCUSED));
}
else {
g.addKeyStrokeSource(
new KeyStrokeSource(theMap, JComponent.WHEN_IN_FOCUSED_WINDOW));
}
// Fix for bug 1630993: toolbar buttons not appearing
toolBar.addHierarchyListener(new HierarchyListener() {
@Override
public void hierarchyChanged(HierarchyEvent e) {
Window w;
if ((w = SwingUtilities.getWindowAncestor(toolBar)) != null) {
w.validate();
}
if (toolBar.getSize().width > 0) {
toolBar.removeHierarchyListener(this);
}
}
});
GameModule.getGameModule().addSideChangeListenerToPlayerRoster(this);
g.getPrefs().addOption(
Resources.getString("Prefs.general_tab"), //$NON-NLS-1$
new IntConfigurer(
PREFERRED_EDGE_DELAY,
Resources.getString("Map.scroll_delay_preference"), //$NON-NLS-1$
PREFERRED_EDGE_SCROLL_DELAY
)
);
g.getPrefs().addOption(
Resources.getString("Prefs.compatibility_tab"), //$NON-NLS-1$
new BooleanConfigurer(
MOVING_STACKS_PICKUP_UNITS,
Resources.getString("Map.moving_stacks_preference"), //$NON-NLS-1$
Boolean.FALSE
)
);
}
/**
* Unregisters this Map from its {@link Buildable} parent (usually a {@link GameModule}), reversing
* the process of {@link #addTo}.
* @param b parent {@link Buildable} to deregister from
*/
@Override
public void removeFrom(Buildable b) {
GameModule.getGameModule().getGameState().removeGameComponent(this);
Window w = SwingUtilities.getWindowAncestor(theMap);
if (w != null) {
w.dispose();
}
GameModule.getGameModule().getToolBar().remove(launchButton);
idMgr.remove(this);
if (picker != null) {
GameModule.getGameModule().removeCommandEncoder(picker);
GameModule.getGameModule().getGameState().addGameComponent(picker);
}
PlayerRoster.removeSideChangeListener(this);
}
/**
* Takes action when the local player has switched sides. Because Map implements {@link PlayerRoster.SideChangeListener},
* this method will automatically be called whenever the local player switches sides.
* @param oldSide side the local player is switching away from
* @param newSide side the local player is switching to
*/
@Override
public void sideChanged(String oldSide, String newSide) {
repaint();
}
/**
* Set the boards for this map. Each map may contain more than one
* {@link Board}.
* @param c Collection of Boards to be used.
*/
public synchronized void setBoards(Collection<Board> c) {
boards.clear();
for (Board b : c) {
b.setMap(this);
boards.add(b);
}
setBoardBoundaries();
}
/**
* Set the boards for this map. Each map may contain more than one
* {@link Board}.
* @deprecated Use {@link #setBoards(Collection)} instead.
*/
@Deprecated(since = "2020-08-05", forRemoval = true)
public synchronized void setBoards(Enumeration<Board> boardList) {
ProblemDialog.showDeprecated ("2020-08-05");
setBoards(Collections.list(boardList));
}
/**
* Since a map can have multiple boards in use at once (laid out above and beside each other), this
* method accepts a {@link Point} in the map's coordinate space and will return the {@link Board} which
* contains that point, or null if none.
* @return the {@link Board} on this map containing the argument point
*/
public Board findBoard(Point p) {
for (Board b : boards) {
if (b.bounds().contains(p))
return b;
}
return null;
}
/**
* If the given point in the map's coordinate space is within a {@link Zone} on a board with a
* {@link ZonedGrid} (aka Multi-zoned Grid), returns the Zone. Otherwise returns null.
* @return the {@link Zone} on this map containing the argument point
*/
public Zone findZone(Point p) {
Board b = findBoard(p);
if (b != null) {
MapGrid grid = b.getGrid();
if (grid instanceof ZonedGrid) {
Rectangle r = b.bounds();
Point pos = new Point(p);
pos.translate(-r.x, -r.y); // Translate to Board co-ords
return ((ZonedGrid) grid).findZone(pos);
}
}
return null;
}
/**
* Search on all boards for a Zone with the given name
* @param name Zone Name
* @return Located zone, or null if not found
*/
public Zone findZone(String name) {
for (Board b : boards) {
for (ZonedGrid zg : b.getAllDescendantComponentsOf(ZonedGrid.class)) {
Zone z = zg.findZone(name);
if (z != null) {
return z;
}
}
}
return null;
}
/**
* Search on all boards for a Region (location on an Irregular Grid) with the given name
* @param name Region name
* @return Located region, or null if none
*/
public Region findRegion(String name) {
for (Board b : boards) {
for (RegionGrid rg : b.getAllDescendantComponentsOf(RegionGrid.class)) {
Region r = rg.findRegion(name);
if (r != null) {
return r;
}
}
}
return null;
}
/**
* Searches our list of boards for one with the given name
* @param name Board Name
* @return located board, or null if no such board found
*/
public Board getBoardByName(String name) {
if (name != null) {
for (Board b : boards) {
if (name.equals(b.getName())) {
return b;
}
}
}
return null;
}
/**
* @return Dimension for map window's "preferred size"
*/
public Dimension getPreferredSize() {
final Dimension size = mapSize();
size.width *= getZoom();
size.height *= getZoom();
return size;
}
/**
* @return the size of the map in pixels at 100% zoom,
* including the edge buffer
*/
// FIXME: why synchronized?
public synchronized Dimension mapSize() {
final Rectangle r = new Rectangle(0, 0);
for (Board b : boards) r.add(b.bounds());
r.width += edgeBuffer.width;
r.height += edgeBuffer.height;
return r.getSize();
}
public boolean isLocationRestricted(Point p) {
Board b = findBoard(p);
if (b != null) {
Rectangle r = b.bounds();
Point snap = new Point(p);
snap.translate(-r.x, -r.y);
return b.isLocationRestricted(snap);
}
else {
return false;
}
}
/**
* @return the nearest allowable point according to the {@link VASSAL.build.module.map.boardPicker.board.MapGrid} on
* the {@link Board} at this point
*
* @see Board#snapTo
* @see VASSAL.build.module.map.boardPicker.board.MapGrid#snapTo
*/
public Point snapTo(Point p) {
Point snap = new Point(p);
final Board b = findBoard(p);
if (b == null) return snap;
final Rectangle r = b.bounds();
snap.translate(-r.x, -r.y);
snap = b.snapTo(snap);
snap.translate(r.x, r.y);
// RFE 882378
// If we have snapped to a point 1 pixel off the edge of the map, move
// back
// onto the map.
if (findBoard(snap) == null) {
snap.translate(-r.x, -r.y);
if (snap.x == r.width) {
snap.x = r.width - 1;
}
else if (snap.x == -1) {
snap.x = 0;
}
if (snap.y == r.height) {
snap.y = r.height - 1;
}
else if (snap.y == -1) {
snap.y = 0;
}
snap.translate(r.x, r.y);
}
return snap;
}
/**
* @return The buffer of empty space around the boards in the Map window,
* in component coordinates at 100% zoom
*/
public Dimension getEdgeBuffer() {
return new Dimension(edgeBuffer);
}
/**
* Translate a point from component coordinates (i.e., x,y position on
* the JPanel) to map coordinates (i.e., accounting for zoom factor).
*
* @see #componentCoordinates
* @deprecated Use {@link #componentToMap(Point)}
*/
@Deprecated(since = "2020-08-05", forRemoval = true)
public Point mapCoordinates(Point p) {
ProblemDialog.showDeprecated ("2020-08-05");
return componentToMap(p);
}
/** @deprecated Use {@link #componentToMap(Rectangle)} */
@Deprecated(since = "2020-08-05", forRemoval = true)
public Rectangle mapRectangle(Rectangle r) {
ProblemDialog.showDeprecated ("2020-08-05");
return componentToMap(r);
}
/**
* Translate a point from map coordinates to component coordinates
*
* @see #mapCoordinates
* @deprecated {@link #mapToComponent(Point)}
*/
@Deprecated(since = "2020-08-05", forRemoval = true)
public Point componentCoordinates(Point p) {
ProblemDialog.showDeprecated ("2020-08-05");
return mapToComponent(p);
}
/** @deprecated Use {@link #mapToComponent(Rectangle)} */
@Deprecated(since = "2020-08-05", forRemoval = true)
public Rectangle componentRectangle(Rectangle r) {
ProblemDialog.showDeprecated ("2020-08-05");
return mapToComponent(r);
}
/**
* Scales an integer value to a zoom factor
* @param c value to be scaled
* @param zoom zoom factor
* @return scaled value result
*/
protected int scale(int c, double zoom) {
return (int)(c * zoom);
}
/**
* Scales a point to a zoom factor
* @param p point to be scaled
* @param zoom zoom factor
* @return scaled point result
*/
protected Point scale(Point p, double zoom) {
return new Point((int)(p.x * zoom), (int)(p.y * zoom));
}
/**
* Scales a Rectangle to a zoom factor
* @param r Rectangle to be zoomed
* @param zoom zoom factor
* @return scaled Rectangle result
*/
protected Rectangle scale(Rectangle r, double zoom) {
return new Rectangle(
(int)(r.x * zoom),
(int)(r.y * zoom),
(int)(r.width * zoom),
(int)(r.height * zoom)
);
}
/**
* Converts an integer value from the Map's coordinate system to Drawing coordinates for rendering. Takes into
* account the operating system's scale factor (needed to deal with HiDPI monitors) as well as the Map's zoom
* factor. Although Drawing coordinates may <i>sometimes</i> have the traditional 1-to-1 relationship with component
* coordinates, on HiDPI monitors it will not.
*
* Examples: Drawing a line between two points on a map (see {@link LOS_Thread#draw}. Drawing a piece on the map
* (see {@link StackMetrics#draw}.
*
* @param c value in Map coordinate space to be scaled
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled value in Drawing coordinate space
*/
public int mapToDrawing(int c, double os_scale) {
return scale(c, getZoom() * os_scale);
}
/**
* Converts a point from the Map's coordinate system to Drawing coordinates for rendering. Takes into
* account the operating system's scale factor (needed to deal with HiDPI monitors) as well as the Map's zoom
* factor. Although Drawing coordinates may <i>sometimes</i> have the traditional 1-to-1 relationship with component
* coordinates, on HiDPI monitors it will not.
*
* Examples: Drawing a line between two points on a map (see {@link LOS_Thread#draw}. Drawing a piece on the map
* (see {@link StackMetrics#draw}.
*
* @param p point in Map coordinates to be scaled
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled point in Drawing coordinates
*/
public Point mapToDrawing(Point p, double os_scale) {
return scale(p, getZoom() * os_scale);
}
/**
* Converts a rectangle from the Map's coordinate system to Drawing coordinates for rendering. Takes into
* account the operating system's scale factor (needed to deal with HiDPI monitors) as well as the Map's zoom
* factor. Although Drawing coordinates may <i>sometimes</i> have the traditional 1-to-1 relationship with component
* coordinates, on HiDPI monitors it will not.
*
* Examples: Drawing a line between two points on a map (see {@link LOS_Thread#draw}. Drawing a piece on the map
* (see {@link StackMetrics#draw}.
*
* @param r rectangle in Map coordinates to be scaled
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled rectangle in Drawing coordinates
*/
public Rectangle mapToDrawing(Rectangle r, double os_scale) {
return scale(r, getZoom() * os_scale);
}
/**
* Converts an integer value from the Map's coordinate system to Component coordinates used for interactions between
* swing components. Basically this scales by the map's zoom factor. Note that although drawing coordinates may
* sometimes have the traditional 1-to-1 relationship with component coordinates, on HiDPI monitors it will not.
*
* Examples: activating a popup menu at a piece's location on a map (see MenuDisplayer#maybePopup). Drag and
* drop operations (see dragGestureRecognizedPrep in {@link PieceMover}).
*
* @param c value in Map coordinate system to scale
* @return scaled value in Component coordinate system
*/
public int mapToComponent(int c) {
return scale(c, getZoom());
}
/**
* Converts a Point from the Map's coordinate system to Component coordinates used for interactions between
* swing components. Basically this scales by the map's zoom factor. Note that although drawing coordinates may
* sometimes have the traditional 1-to-1 relationship with component coordinates, on HiDPI monitors it will not.
*
* Examples: activating a popup menu at a piece's location on a map (see MenuDisplayer#maybePopup). Drag and
* drop operations (see dragGestureRecognizedPrep in {@link PieceMover}).
*
* @param p Point in Map coordinates to scale
* @return scaled Point in Component coordinates
*/
public Point mapToComponent(Point p) {
return scale(p, getZoom());
}
/**
* Converts a Rectangle from the Map's coordinate system to Component coordinates used for interactions between
* swing components. Basically this scales by the map's zoom factor. Note that although drawing coordinates may
* sometimes have the traditional 1-to-1 relationship with component coordinates, on HiDPI monitors it will not.
*
* Examples: activating a popup menu at a piece's location on a map (see MenuDisplayer#maybePopup). Drag and
* drop operations (see dragGestureRecognizedPrep in {@link PieceMover}).
*
* @param r Rectangle in Map coordinates to scale
* @return scaled Rectangle in Component coordinates
*/
public Rectangle mapToComponent(Rectangle r) {
return scale(r, getZoom());
}
/**
* Converts an integer value from Component coordinates system to Drawing coordinates for rendering. Takes into
* account the operating system's scale factor (needed to deal with HiDPI monitors), which accounts entirely for
* the difference in these two coordinate systems. Although Drawing coordinates may <i>sometimes</i> have the
* traditional 1-to-1 relationship with Component coordinates, on HiDPI monitors it will not.
*
* Examples: see {@link VASSAL.counters.Footprint#draw} - checking a map component's "visible" clipping rect, and
* using it in the context of drawing move trails.
*
* @param c value in Component coordinate space to be scaled
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled value in Drawing coordinate space
*/
public int componentToDrawing(int c, double os_scale) {
return scale(c, os_scale);
}
/**
* Converts a Point from Component coordinates to Drawing coordinates for rendering. Takes into
* account the operating system's scale factor (needed to deal with HiDPI monitors), which accounts entirely for
* the difference in these two coordinate systems. Although Drawing coordinates may <i>sometimes</i> have the
* traditional 1-to-1 relationship with Component coordinates, on HiDPI monitors it will not.
*
* Examples: see {@link VASSAL.counters.Footprint#draw} - checking a map component's "visible" clipping rect, and
* using it in the context of drawing move trails.
*
* @param p Point in Component coordinate space to be scaled
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled Point in Drawing coordinate space
*/
public Point componentToDrawing(Point p, double os_scale) {
return scale(p, os_scale);
}
/**
* Converts a Rectangle from Component coordinates to Drawing coordinates for rendering. Takes into
* account the operating system's scale factor (needed to deal with HiDPI monitors), which accounts entirely for
* the difference in these two coordinate systems. Although Drawing coordinates may <i>sometimes</i> have the
* traditional 1-to-1 relationship with Component coordinates, on HiDPI monitors it will not.
*
* Examples: see {@link VASSAL.counters.Footprint#draw} - checking a map component's "visible" clipping rect, and
* using it in the context of drawing move trails.
*
* @param r Rectangle in Component coordinate space to be scaled
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled Rectangle in Drawing coordinate space
*/
public Rectangle componentToDrawing(Rectangle r, double os_scale) {
return scale(r, os_scale);
}
/**
* Converts an integer value from swing Component coordinates to the Map's coordinate system. Basically this scales by the
* inverse of the map's zoom factor. Note that although drawing coordinates may sometimes have the traditional 1-to-1 relationship
* with component coordinates, on HiDPI monitors it will not.
*
* Examples: Checking if the mouse is currently overlapping a game piece {@link KeyBufferer#mouseReleased(MouseEvent)},
* CounterDetailViewer#getDisplayablePieces.
*
* @param c value in Component coordinates to scale
* @return scaled value in Map coordinates
*/
public int componentToMap(int c) {
return scale(c, 1.0 / getZoom());
}
/**
* Converts a Point from swing Component coordinates to the Map's coordinate system. Basically this scales by the
* inverse of the map's zoom factor. Note that although drawing coordinates may sometimes have the traditional 1-to-1 relationship
* with component coordinates, on HiDPI monitors it will not.
*
* Examples: Checking if the mouse is currently overlapping a game piece {@link KeyBufferer#mouseReleased(MouseEvent)},
* CounterDetailViewer#getDisplayablePieces.
*
* @param p Point in Component coordinates to scale
* @return scaled Point in Map coordinates
*/
public Point componentToMap(Point p) {
return scale(p, 1.0 / getZoom());
}
/**
* Converts a Rectangle from swing Component coordinates to the Map's coordinate system. Basically this scales by the
* inverse of the map's zoom factor. Note that although drawing coordinates may sometimes have the traditional 1-to-1 relationship
* with component coordinates, on HiDPI monitors it will not.
*
* Examples: Checking if the mouse is currently overlapping a game piece {@link KeyBufferer#mouseReleased(MouseEvent)},
* CounterDetailViewer#getDisplayablePieces.
*
* @param r Rectangle in Component coordinates to scale
* @return scaled Rectangle in Map coordinates
*/
public Rectangle componentToMap(Rectangle r) {
return scale(r, 1.0 / getZoom());
}
/**
* Converts an integer value from Drawing coordinates to the Map's coordinate system. Takes into
* account the operating system's scale factor (needed to deal with HiDPI monitors) as well as the Map's zoom
* factor, scaling by the inverse of both of these scale factors. Although Drawing coordinates may <i>sometimes</i>
* have the traditional 1-to-1 relationship with component coordinates, on HiDPI monitors it will not.
*
* @param c value in Drawing coordinate space to be scaled
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled value in Map coordinates
*/
@SuppressWarnings("unused")
public int drawingToMap(int c, double os_scale) {
return scale(c, 1.0 / (getZoom() * os_scale));
}
/**
* Converts a Point from Drawing coordinates to the Map's coordinate system. Takes into
* account the operating system's scale factor (needed to deal with HiDPI monitors) as well as the Map's zoom
* factor, scaling by the inverse of both of these scale factors. Although Drawing coordinates may <i>sometimes</i>
* have the traditional 1-to-1 relationship with component coordinates, on HiDPI monitors it will not.
*
* @param p Point in Drawing coordinate space to be scaled
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled point in Map coordinates
*/
public Point drawingToMap(Point p, double os_scale) {
return scale(p, 1.0 / (getZoom() * os_scale));
}
/**
* Converts a Rectangle from Drawing coordinates to the Map's coordinate system. Takes into
* account the operating system's scale factor (needed to deal with HiDPI monitors) as well as the Map's zoom
* factor, scaling by the inverse of both of these scale factors. Although Drawing coordinates may <i>sometimes</i>
* have the traditional 1-to-1 relationship with component coordinates, on HiDPI monitors it will not.
*
* @param r Rectangle in Drawing coordinate space to be scaled
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled Rectangle in Map coordinates
*/
public Rectangle drawingToMap(Rectangle r, double os_scale) {
return scale(r, 1.0 / (getZoom() * os_scale));
}
/**
* Converts an integer value from Drawing coordinates to swing Component coordinates. Takes into account the inverse
* of the operating system's scale factor (needed to deal with HiDPI monitors), which accounts entirely for the
* difference in these two coordinate systems. Although Drawing coordinates may <i>sometimes</i> have the traditional
* 1-to-1 relationship with Component coordinates, on HiDPI monitors it will not.
*
* @param c value in Drawing coordinates
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled value in Component coordinates
*/
@SuppressWarnings("unused")
public int drawingToComponent(int c, double os_scale) {
return scale(c, 1.0 / os_scale);
}
/**
* Converts a Point from Drawing coordinates to swing Component coordinates. Takes into account the inverse
* of the operating system's scale factor (needed to deal with HiDPI monitors), which accounts entirely for the
* difference in these two coordinate systems. Although Drawing coordinates may <i>sometimes</i> have the traditional
* 1-to-1 relationship with Component coordinates, on HiDPI monitors it will not.
*
* @param p Point in Drawing coordinates
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled Point in Component coordinates
*/
@SuppressWarnings("unused")
public Point drawingToComponent(Point p, double os_scale) {
return scale(p, 1.0 / os_scale);
}
/**
* Converts a Rectangle from Drawing coordinates to swing Component coordinates. Takes into account the inverse
* of the operating system's scale factor (needed to deal with HiDPI monitors), which accounts entirely for the
* difference in these two coordinate systems. Although Drawing coordinates may <i>sometimes</i> have the traditional
* 1-to-1 relationship with Component coordinates, on HiDPI monitors it will not.
*
* @param r Rectangle in Drawing coordinates
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled Rectangle in Component coordinates
*/
@SuppressWarnings("unused")
public Rectangle drawingToComponent(Rectangle r, double os_scale) {
return scale(r, 1.0 / os_scale);
}
/**
* @return a String name for the given location on the map. Checks first for a {@link Deck}, then for a {@link Board} that
* is able to provide a name from one of its grids. If no matches, returns "offboard" string.
*
* @see Board#locationName
*/
public String locationName(Point p) {
String loc = getDeckNameAt(p);
if (loc == null) {
Board b = findBoard(p);
if (b != null) {
loc = b.locationName(new Point(p.x - b.bounds().x, p.y - b.bounds().y));
}
}
if (loc == null) {
loc = Resources.getString("Map.offboard"); //$NON-NLS-1$
}
return loc;
}
/**
* @return a translated-if-available String name for the given location on the map. Checks first for a {@link Deck},
* then for a {@link Board} that is able to provide a name from one of its grids. If no matches, returns "offboard" string.
*
* @see Board#locationName
*/
public String localizedLocationName(Point p) {
String loc = getLocalizedDeckNameAt(p);
if (loc == null) {
Board b = findBoard(p);
if (b != null) {
loc = b.localizedLocationName(new Point(p.x - b.bounds().x, p.y - b.bounds().y));
}
}
if (loc == null) {
loc = Resources.getString("Map.offboard"); //$NON-NLS-1$
}
return loc;
}
/**
* Is this map visible to all players?
* @return true if this map either (a) isn't a {@link PrivateMap} or (b) does have its visible-to-all flag set
*/
@SuppressWarnings("unused")
public boolean isVisibleToAll() {
return !(this instanceof PrivateMap) || getAttributeValueString(PrivateMap.VISIBLE).equals("true"); //$NON-NLS-1$
}
/**
* @return the name of the {@link Deck} whose bounding box contains point p
*/
@SuppressWarnings("unused")
public String getDeckNameContaining(Point p) {
String deck = null;
if (p != null) {
for (DrawPile d : getComponentsOf(DrawPile.class)) {
Rectangle box = d.boundingBox();
if (box != null && box.contains(p)) {
deck = d.getConfigureName();
break;
}
}
}
return deck;
}
/**
* Return the name of the {@link Deck} whose position is precisely p
*
* @param p Point to look for Deck
* @return Name of {@link Deck whose position is precisely p
*/
public String getDeckNameAt(Point p) {
String deck = null;
if (p != null) {
for (DrawPile d : getComponentsOf(DrawPile.class)) {
if (d.getPosition().equals(p)) {
deck = d.getConfigureName();
break;
}
}
}
return deck;
}
/**
* Return the localized name of the {@link Deck} whose position is precisely p
*
* @param p Point to look for Deck
* @return Name of {@link Deck whose position is precisely p
*/
public String getLocalizedDeckNameAt(Point p) {
String deck = null;
if (p != null) {
for (DrawPile d : getComponentsOf(DrawPile.class)) {
if (d.getPosition().equals(p)) {
deck = d.getLocalizedConfigureName();
break;
}
}
}
return deck;
}
/**
* Because MouseEvents are received in Component coordinates, it is
* inconvenient for MouseListeners on the map to have to translate to Map
* coordinates. MouseListeners added with this method will receive mouse
* events with points already translated into Map coordinates.
* addLocalMouseListenerFirst inserts the new listener at the start of the
* chain.
* @param l MouseListener to add
*/
public void addLocalMouseListener(MouseListener l) {
multicaster = AWTEventMulticaster.add(multicaster, l);
}
/**
* Because MouseEvents are received in Component coordinates, it is
* inconvenient for MouseListeners on the map to have to translate to Map
* coordinates. MouseListeners added with this method will receive mouse
* events with points already translated into Map coordinates.
* addLocalMouseListenerFirst inserts the new listener at the start of the
* chain.
* @param l MouseListener to add
*/
public void addLocalMouseListenerFirst(MouseListener l) {
multicaster = AWTEventMulticaster.add(l, multicaster);
}
/**
* Because MouseEvents are received in Component coordinates, it is
* inconvenient for MouseListeners on the map to have to translate to Map
* coordinates. MouseListeners added with this method will receive mouse
* events with points already translated into Map coordinates.
* addLocalMouseListenerFirst inserts the new listener at the start of the
* chain.
* @param l MouseListener to add
*/
public void removeLocalMouseListener(MouseListener l) {
multicaster = AWTEventMulticaster.remove(multicaster, l);
}
/**
* MouseListeners on a map may be pushed and popped onto a stack.
* Only the top listener on the stack receives mouse events.
* @param l MouseListener to push onto stack.
*/
public void pushMouseListener(MouseListener l) {
mouseListenerStack.add(l);
}
/**
* MouseListeners on a map may be pushed and popped onto a stack. Only the top listener on the stack receives mouse
* events. The pop method removes the most recently pushed mouse listener.
*/
public void popMouseListener() {
mouseListenerStack.remove(mouseListenerStack.size() - 1);
}
/**
* @param e MouseEvent
*/
@Override
public void mouseEntered(MouseEvent e) {
}
/**
* @param e MouseEvent
*/
@Override
public void mouseExited(MouseEvent e) {
}
/**
* Because MouseEvents are received in Component coordinates, it is
* inconvenient for MouseListeners on the map to have to translate to Map
* coordinates. MouseListeners added with this method will receive mouse
* events with points already translated into Map coordinates.
* addLocalMouseListenerFirst inserts the new listener at the start of the
* chain.
* @param e MouseEvent in Component coordinates
* @return MouseEvent translated into Map coordinates
*/
public MouseEvent translateEvent(MouseEvent e) {
// don't write over Java's mouse event
final MouseEvent mapEvent = new MouseEvent(
e.getComponent(), e.getID(), e.getWhen(), e.getModifiersEx(),
e.getX(), e.getY(), e.getXOnScreen(), e.getYOnScreen(),
e.getClickCount(), e.isPopupTrigger(), e.getButton()
);
final Point p = componentToMap(mapEvent.getPoint());
mapEvent.translatePoint(p.x - mapEvent.getX(), p.y - mapEvent.getY());
return mapEvent;
}
/**
* Mouse events are first translated into map coordinates. Then the event is forwarded to the top MouseListener in the
* stack, if any, otherwise forwarded to all LocalMouseListeners
* @param e MouseEvent from system
*
* @see #pushMouseListener
* @see #popMouseListener
* @see #addLocalMouseListener
*/
@Override
public void mouseClicked(MouseEvent e) {
if (!mouseListenerStack.isEmpty()) {
mouseListenerStack.get(mouseListenerStack.size() - 1).mouseClicked(translateEvent(e));
}
else if (multicaster != null) {
multicaster.mouseClicked(translateEvent(e));
}
}
public static Map activeMap = null;
/**
* Marks an ActiveMap for certain drag and drop operations, so that the map can be repainted when the operation is
* complete.
* @param m Map to be considered active.
*/
public static void setActiveMap(Map m) {
activeMap = m;
}
/**
* Repaints the current ActiveMap (see {@link #setActiveMap}) and unmarks it.
*/
public static void clearActiveMap() {
if (activeMap != null) {
activeMap.repaint();
setActiveMap(null);
}
}
/**
* Mouse events are first translated into map coordinates. Then the event is forwarded to the top MouseListener in the
* stack, if any, otherwise forwarded to all LocalMouseListeners
* @param e MouseEvent from system
*
* @see #pushMouseListener
* @see #popMouseListener
* @see #addLocalMouseListener
*/
@Override
public void mousePressed(MouseEvent e) {
// Deselect any counters on the last Map with focus
if (!this.equals(activeMap)) {
boolean dirty = false;
final KeyBuffer kbuf = KeyBuffer.getBuffer();
final ArrayList<GamePiece> l = new ArrayList<>(kbuf.asList());
for (GamePiece p : l) {
if (p.getMap() == activeMap) {
kbuf.remove(p);
dirty = true;
}
}
if (dirty && activeMap != null) {
activeMap.repaint();
}
}
setActiveMap(this);
if (!mouseListenerStack.isEmpty()) {
mouseListenerStack.get(mouseListenerStack.size() - 1).mousePressed(translateEvent(e));
}
else if (multicaster != null) {
multicaster.mousePressed(translateEvent(e));
}
}
/**
* Mouse events are first translated into map coordinates. Then the event is forwarded to the top MouseListener in the
* stack, if any, otherwise forwarded to all LocalMouseListeners
* @param e MouseEvent from system
*
* @see #pushMouseListener
* @see #popMouseListener
* @see #addLocalMouseListener
*/
@Override
public void mouseReleased(MouseEvent e) {
// don't write over Java's mouse event
Point p = e.getPoint();
p.translate(theMap.getX(), theMap.getY());
if (theMap.getBounds().contains(p)) {
if (!mouseListenerStack.isEmpty()) {
mouseListenerStack.get(mouseListenerStack.size() - 1).mouseReleased(translateEvent(e));
}
else if (multicaster != null) {
multicaster.mouseReleased(translateEvent(e));
}
// Request Focus so that keyboard input will be recognized
theMap.requestFocus();
}
// Clicking with mouse always repaints the map
clearFirst = true;
theMap.repaint();
activeMap = this;
}
/**
* Save all current Key Listeners and remove them from the
* map. Used by Traits that need to prevent Key Commands
* at certain times.
*/
public void enableKeyListeners() {
if (saveKeyListeners == null) return;
for (KeyListener kl : saveKeyListeners) {
theMap.addKeyListener(kl);
}
saveKeyListeners = null;
}
/**
* Restore the previously disabled KeyListeners
*/
public void disableKeyListeners() {
if (saveKeyListeners != null) return;
saveKeyListeners = theMap.getKeyListeners();
for (KeyListener kl : saveKeyListeners) {
theMap.removeKeyListener(kl);
}
}
/**
* This listener will be notified when a drag event is initiated, assuming
* that no MouseListeners are on the stack.
*
* @see #pushMouseListener
* @param dragGestureListener Listener
*/
public void setDragGestureListener(DragGestureListener dragGestureListener) {
this.dragGestureListener = dragGestureListener;
}
/**
* @return current dragGestureListener that handles normal drag events (assuming no MouseListeners are on the stack)
* @see #pushMouseListener
*/
public DragGestureListener getDragGestureListener() {
return dragGestureListener;
}
/**
* @param dtde DropTargetDragEvent
*/
@Override
public void dragEnter(DropTargetDragEvent dtde) {
}
/**
* Handles scrolling when dragging an gamepiece to the edge of the window
* @param dtde DropTargetDragEvent
*/
@Override
public void dragOver(DropTargetDragEvent dtde) {
scrollAtEdge(dtde.getLocation(), SCROLL_ZONE);
}
/**
* @param dtde DropTargetDragEvent
*/
@Override
public void dropActionChanged(DropTargetDragEvent dtde) {
}
/*
* Cancel final scroll and repaint map
* @param dtde DropTargetDragEvent
*/
@Override
public void dragExit(DropTargetEvent dte) {
if (scroller.isRunning()) scroller.stop();
repaint();
}
/**
* We put the "drop" in drag-n-drop!
* @param dtde DropTargetDragEvent
*/
@Override
public void drop(DropTargetDropEvent dtde) {
if (dtde.getDropTargetContext().getComponent() == theMap) {
final MouseEvent evt = new MouseEvent(
theMap,
MouseEvent.MOUSE_RELEASED,
System.currentTimeMillis(),
0,
dtde.getLocation().x,
dtde.getLocation().y,
1,
false,
MouseEvent.NOBUTTON
);
theMap.dispatchEvent(evt);
dtde.dropComplete(true);
}
if (scroller.isRunning()) scroller.stop();
}
/**
* Mouse motion events are not forwarded to LocalMouseListeners or to listeners on the stack
* @param e MouseEvent from system
*/
@Override
public void mouseMoved(MouseEvent e) {
}
/**
* Mouse motion events are not forwarded to LocalMouseListeners or to
* listeners on the stack.
*
* The map scrolls when dragging the mouse near the edge.
* @param e MouseEvent from system
*/
@Override
public void mouseDragged(MouseEvent e) {
if (!SwingUtils.isContextMouseButtonDown(e)) {
scrollAtEdge(e.getPoint(), SCROLL_ZONE);
}
else {
if (scroller.isRunning()) scroller.stop();
}
}
/*
* Delay before starting scroll at edge
*/
public static final int PREFERRED_EDGE_SCROLL_DELAY = 200;
public static final String PREFERRED_EDGE_DELAY = "PreferredEdgeDelay"; //$NON-NLS-1$
/** The width of the hot zone for triggering autoscrolling. */
public static final int SCROLL_ZONE = 30;
/** The horizontal component of the autoscrolling vector, -1, 0, or 1. */
protected int sx;
/** The vertical component of the autoscrolling vector, -1, 0, or 1. */
protected int sy;
protected int dx, dy;
/**
* Begin autoscrolling the map if the given point is within the given
* distance from a viewport edge.
*
* @param evtPt Point to check
* @param dist Distance to check
*/
public void scrollAtEdge(Point evtPt, int dist) {
final Rectangle vrect = scroll.getViewport().getViewRect();
final int px = evtPt.x - vrect.x;
final int py = evtPt.y - vrect.y;
// determine scroll vector
sx = 0;
if (px < dist && px >= 0) {
sx = -1;
dx = dist - px;
}
else if (px < vrect.width && px >= vrect.width - dist) {
sx = 1;
dx = dist - (vrect.width - px);
}
sy = 0;
if (py < dist && py >= 0) {
sy = -1;
dy = dist - py;
}
else if (py < vrect.height && py >= vrect.height - dist) {
sy = 1;
dy = dist - (vrect.height - py);
}
dx /= 2;
dy /= 2;
// start autoscrolling if we have a nonzero scroll vector
if (sx != 0 || sy != 0) {
if (!scroller.isRunning()) {
scroller.setStartDelay((Integer)
GameModule.getGameModule().getPrefs().getValue(PREFERRED_EDGE_DELAY));
scroller.start();
}
}
else {
if (scroller.isRunning()) scroller.stop();
}
}
/** The animator which controls autoscrolling. */
protected Animator scroller = new Animator(Animator.INFINITE,
new TimingTargetAdapter() {
private long t0;
/**
* Continue to scroll the map as animator instructs us
* @param fraction not used
*/
@Override
public void timingEvent(float fraction) {
// Constant velocity along each axis, 0.5px/ms
final long t1 = System.currentTimeMillis();
final int dt = (int)((t1 - t0) / 2);
t0 = t1;
scroll(sx * dt, sy * dt);
// Check whether we have hit an edge
final Rectangle vrect = scroll.getViewport().getViewRect();
if ((sx == -1 && vrect.x == 0) ||
(sx == 1 && vrect.x + vrect.width >= theMap.getWidth())) sx = 0;
if ((sy == -1 && vrect.y == 0) ||
(sy == 1 && vrect.y + vrect.height >= theMap.getHeight())) sy = 0;
// Stop if the scroll vector is zero
if (sx == 0 && sy == 0) scroller.stop();
}
/**
* Get ready to scroll
*/
@Override
public void begin() {
t0 = System.currentTimeMillis();
}
}
);
/**
* Repaints the map. Accepts parameter about whether to clear the display first.
* @param cf true if display should be cleared before drawing the map
*/
public void repaint(boolean cf) {
clearFirst = cf;
theMap.repaint();
}
/**
* Repaints the map.
*/
public void repaint() {
theMap.repaint();
}
/**
* Paints a specific region of the map, denoted by a Rectangle.
* @param g Graphics object where map should be painted
* @param visibleRect region of map to repaint
*/
public void paintRegion(Graphics g, Rectangle visibleRect) {
paintRegion(g, visibleRect, theMap);
}
/**
* Paints a specific region of the map, denoted by a Rectangle.
* @param g Graphics object where map should be painted
* @param visibleRect region of map to repaint
* @param c observer component
*/
public void paintRegion(Graphics g, Rectangle visibleRect, Component c) {
clearMapBorder(g); // To avoid ghost pieces around the edge
drawBoardsInRegion(g, visibleRect, c);
drawDrawable(g, false);
drawPiecesInRegion(g, visibleRect, c);
drawDrawable(g, true);
}
/**
* For each Board overlapping the given region, update the appropriate section of the board image.
* @param g Graphics object where map should be painted
* @param visibleRect region of map to repaint
* @param c observer component
*/
public void drawBoardsInRegion(Graphics g,
Rectangle visibleRect,
Component c) {
final Graphics2D g2d = (Graphics2D) g;
final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
final double dzoom = getZoom() * os_scale;
for (Board b : boards) {
b.drawRegion(g, getLocation(b, dzoom), visibleRect, dzoom, c);
}
}
/**
* For each Board overlapping the given region, update the appropriate section of the board image.
* @param g Graphics object where map should be painted
* @param visibleRect region of map to repaint
*/
public void drawBoardsInRegion(Graphics g, Rectangle visibleRect) {
drawBoardsInRegion(g, visibleRect, theMap);
}
/**
* Draws all pieces visible in a rectangular area of the map
* @param g Graphics object where map should be painted
* @param visibleRect region of map to repaint
* @param c observer component
*/
public void drawPiecesInRegion(Graphics g,
Rectangle visibleRect,
Component c) {
if (hideCounters) {
return;
}
final Graphics2D g2d = (Graphics2D) g;
final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
final double dzoom = getZoom() * os_scale;
Composite oldComposite = g2d.getComposite();
g2d.setComposite(
AlphaComposite.getInstance(AlphaComposite.SRC_OVER, pieceOpacity));
final GamePiece[] stack = pieces.getPieces();
for (GamePiece gamePiece : stack) {
final Point pt = mapToDrawing(gamePiece.getPosition(), os_scale);
if (gamePiece.getClass() == Stack.class) {
getStackMetrics().draw(
(Stack) gamePiece, pt, g, this, dzoom, visibleRect
);
}
else {
gamePiece.draw(g, pt.x, pt.y, c, dzoom);
if (Boolean.TRUE.equals(gamePiece.getProperty(Properties.SELECTED))) {
highlighter.draw(gamePiece, g, pt.x, pt.y, c, dzoom);
}
}
/*
// draw bounding box for debugging
final Rectangle bb = stack[i].boundingBox();
g.drawRect(pt.x + bb.x, pt.y + bb.y, bb.width, bb.height);
*/
}
g2d.setComposite(oldComposite);
}
/**
* Draws all pieces visible in a rectangular area of the map
* @param g Graphics object where map should be painted
* @param visibleRect region of map to repaint
*/
public void drawPiecesInRegion(Graphics g, Rectangle visibleRect) {
drawPiecesInRegion(g, visibleRect, theMap);
}
/**
* Draws the map pieces at a given offset
* @param g Target graphics object
* @param xOffset x offset
* @param yOffset y offset
*/
public void drawPieces(Graphics g, int xOffset, int yOffset) {
if (hideCounters) {
return;
}
Graphics2D g2d = (Graphics2D) g;
final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
Composite oldComposite = g2d.getComposite();
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, pieceOpacity));
GamePiece[] stack = pieces.getPieces();
for (GamePiece gamePiece : stack) {
Point pt = mapToDrawing(gamePiece.getPosition(), os_scale);
gamePiece.draw(g, pt.x + xOffset, pt.y + yOffset, theMap, getZoom());
if (Boolean.TRUE.equals(gamePiece.getProperty(Properties.SELECTED))) {
highlighter.draw(gamePiece, g, pt.x - xOffset, pt.y - yOffset, theMap, getZoom());
}
}
g2d.setComposite(oldComposite);
}
/**
* Draws all of our "Drawable" components. Standard examples include {@link CounterDetailViewer}s (aka Mouse-over Stack Viewers),
* {@link GlobalMap}s (aka Overview Maps), {@link LOS_Thread}s, {@link MapShader}s, and the {@link KeyBufferer} (to show which
* pieces are selected).
* @param g target graphics object
* @param aboveCounters true means we should draw only the drawables that go above the counters; false means we should draw only the ones that go below
*/
public void drawDrawable(Graphics g, boolean aboveCounters) {
for (Drawable drawable : drawComponents) {
if (aboveCounters == drawable.drawAboveCounters()) {
drawable.draw(g, this);
}
}
}
public Highlighter getHighlighter() {
return highlighter;
}
public void setHighlighter(Highlighter h) {
highlighter = h;
}
public void addHighlighter(Highlighter h) {
highlighters.add(h);
}
public void removeHighlighter(Highlighter h) {
highlighters.remove(h);
}
public Iterator<Highlighter> getHighlighters() {
return highlighters.iterator();
}
/**
* @return a Collection of all {@link Board}s on the Map
*/
public Collection<Board> getBoards() {
return Collections.unmodifiableCollection(boards);
}
/**
* @return an Enumeration of all {@link Board}s on the map
* @deprecated Use {@link #getBoards()} instead.
*/
@Deprecated(since = "2020-08-05", forRemoval = true)
public Enumeration<Board> getAllBoards() {
ProblemDialog.showDeprecated ("2020-08-05");
return Collections.enumeration(boards);
}
public int getBoardCount() {
return boards.size();
}
/**
* Returns the boundingBox of a GamePiece accounting for the offset of a piece within its parent stack. Return null if
* this piece is not on the map
*
* @see GamePiece#boundingBox
*/
public Rectangle boundingBoxOf(GamePiece p) {
Rectangle r = null;
if (p.getMap() == this) {
r = p.boundingBox();
final Point pos = p.getPosition();
r.translate(pos.x, pos.y);
if (Boolean.TRUE.equals(p.getProperty(Properties.SELECTED))) {
r.add(highlighter.boundingBox(p));
for (Iterator<Highlighter> i = getHighlighters(); i.hasNext();) {
r.add(i.next().boundingBox(p));
}
}
if (p.getParent() != null) {
final Point pt = getStackMetrics().relativePosition(p.getParent(), p);
r.translate(pt.x, pt.y);
}
}
return r;
}
/**
* Returns the selection bounding box of a GamePiece accounting for the offset of a piece within a stack
*
* @see GamePiece#getShape
*/
public Rectangle selectionBoundsOf(GamePiece p) {
if (p.getMap() != this) {
throw new IllegalArgumentException(
Resources.getString("Map.piece_not_on_map")); //$NON-NLS-1$
}
final Rectangle r = p.getShape().getBounds();
r.translate(p.getPosition().x, p.getPosition().y);
if (p.getParent() != null) {
Point pt = getStackMetrics().relativePosition(p.getParent(), p);
r.translate(pt.x, pt.y);
}
return r;
}
/**
* Returns the position of a GamePiece accounting for the offset within a parent stack, if any
*/
public Point positionOf(GamePiece p) {
if (p.getMap() != this) {
throw new IllegalArgumentException(
Resources.getString("Map.piece_not_on_map")); //$NON-NLS-1$
}
final Point point = p.getPosition();
if (p.getParent() != null) {
final Point pt = getStackMetrics().relativePosition(p.getParent(), p);
point.translate(pt.x, pt.y);
}
return point;
}
/**
* @return an array of all GamePieces on the map. This is a read-only copy.
* Altering the array does not alter the pieces on the map.
*/
public GamePiece[] getPieces() {
return pieces.getPieces();
}
public GamePiece[] getAllPieces() {
return pieces.getAllPieces();
}
public void setPieceCollection(PieceCollection pieces) {
this.pieces = pieces;
}
public PieceCollection getPieceCollection() {
return pieces;
}
protected void clearMapBorder(Graphics g) {
final Graphics2D g2d = (Graphics2D) g.create();
final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
if (clearFirst || boards.isEmpty()) {
g.setColor(bgColor);
g.fillRect(
0,
0,
componentToDrawing(theMap.getWidth(), os_scale),
componentToDrawing(theMap.getHeight(), os_scale)
);
clearFirst = false;
}
else {
final int mw = componentToDrawing(theMap.getWidth(), os_scale);
final int mh = componentToDrawing(theMap.getHeight(), os_scale);
final int ew = mapToDrawing(edgeBuffer.width, os_scale);
final int eh = mapToDrawing(edgeBuffer.height, os_scale);
g.setColor(bgColor);
g.fillRect(0, 0, ew, mh);
g.fillRect(0, 0, mw, eh);
g.fillRect(mw - ew, 0, ew, mh);
g.fillRect(0, mh - eh, mw, eh);
}
}
/**
* Adjusts the bounds() rectangle to account for the Board's relative
* position to other boards. In other words, if Board A is N pixels wide
* and Board B is to the right of Board A, then the origin of Board B
* will be adjusted N pixels to the right.
*/
protected void setBoardBoundaries() {
int maxX = 0;
int maxY = 0;
for (Board b : boards) {
Point relPos = b.relativePosition();
maxX = Math.max(maxX, relPos.x);
maxY = Math.max(maxY, relPos.y);
}
boardWidths = new int[maxX + 1][maxY + 1];
boardHeights = new int[maxX + 1][maxY + 1];
for (Board b : boards) {
Point relPos = b.relativePosition();
boardWidths[relPos.x][relPos.y] = b.bounds().width;
boardHeights[relPos.x][relPos.y] = b.bounds().height;
}
Point offset = new Point(edgeBuffer.width, edgeBuffer.height);
for (Board b : boards) {
Point relPos = b.relativePosition();
Point location = getLocation(relPos.x, relPos.y, 1.0);
b.setLocation(location.x, location.y);
b.translate(offset.x, offset.y);
}
theMap.revalidate();
}
protected Point getLocation(Board b, double zoom) {
Point p;
if (zoom == 1.0) {
p = b.bounds().getLocation();
}
else {
Point relPos = b.relativePosition();
p = getLocation(relPos.x, relPos.y, zoom);
p.translate((int) (zoom * edgeBuffer.width), (int) (zoom * edgeBuffer.height));
}
return p;
}
protected Point getLocation(int column, int row, double zoom) {
Point p = new Point();
for (int x = 0; x < column; ++x) {
p.translate((int) Math.floor(zoom * boardWidths[x][row]), 0);
}
for (int y = 0; y < row; ++y) {
p.translate(0, (int) Math.floor(zoom * boardHeights[column][y]));
}
return p;
}
/**
* Draw the boards of the map at the given point and zoom factor onto
* the given Graphics object
*/
public void drawBoards(Graphics g, int xoffset, int yoffset, double zoom, Component obs) {
for (Board b : boards) {
Point p = getLocation(b, zoom);
p.translate(xoffset, yoffset);
b.draw(g, p.x, p.y, zoom, obs);
}
}
/**
* Repaint the given area, specified in map coordinates
*/
public void repaint(Rectangle r) {
r.setLocation(mapToComponent(new Point(r.x, r.y)));
r.setSize((int) (r.width * getZoom()), (int) (r.height * getZoom()));
theMap.repaint(r.x, r.y, r.width, r.height);
}
/**
* @param show
* if true, enable drawing of GamePiece. If false, don't draw GamePiece when painting the map
*/
public void setPiecesVisible(boolean show) {
hideCounters = !show;
}
public boolean isPiecesVisible() {
return !hideCounters && pieceOpacity != 0;
}
public float getPieceOpacity() {
return pieceOpacity;
}
public void setPieceOpacity(float pieceOpacity) {
this.pieceOpacity = pieceOpacity;
}
@Override
public Object getProperty(Object key) {
Object value;
MutableProperty p = propsContainer.getMutableProperty(String.valueOf(key));
if (p != null) {
value = p.getPropertyValue();
}
else {
value = GameModule.getGameModule().getProperty(key);
}
return value;
}
@Override
public Object getLocalizedProperty(Object key) {
Object value = null;
MutableProperty p = propsContainer.getMutableProperty(String.valueOf(key));
if (p != null) {
value = p.getPropertyValue();
}
if (value == null) {
value = GameModule.getGameModule().getLocalizedProperty(key);
}
return value;
}
/**
* Return the auto-move key. It may be named, so just return
* the allocated KeyStroke.
* @return auto move keystroke
*/
public KeyStroke getMoveKey() {
return moveKey == null ? null : moveKey.getKeyStroke();
}
/**
* @return the top-level window containing this map
*/
protected Window createParentFrame() {
if (GlobalOptions.getInstance().isUseSingleWindow()) {
JDialog d = new JDialog(GameModule.getGameModule().getPlayerWindow());
d.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
d.setTitle(getDefaultWindowTitle());
return d;
}
else {
JFrame d = new JFrame();
d.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
d.setTitle(getDefaultWindowTitle());
d.setJMenuBar(MenuManager.getInstance().getMenuBarFor(d));
return d;
}
}
public boolean shouldDockIntoMainWindow() {
// set to show via a button, or no combined window at all, don't dock
if (useLaunchButton || !GlobalOptions.getInstance().isUseSingleWindow()) {
return false;
}
// otherwise dock if this map is the first not to show via a button
for (Map m : GameModule.getGameModule().getComponentsOf(Map.class)) {
if (m == this) {
return true;
}
else if (m.shouldDockIntoMainWindow()) {
return false;
}
}
// Module isn't fully built yet, and/or no maps at all in module yet (perhaps THIS map will soon be the first one)
return true;
}
/**
* When a game is started, create a top-level window, if none exists.
* When a game is ended, remove all boards from the map.
*
* @see GameComponent
*/
@Override
public void setup(boolean show) {
if (show) {
final GameModule g = GameModule.getGameModule();
if (shouldDockIntoMainWindow()) {
if (mainWindowDock != null) { // This is protected from null elsewhere, and crashed null here, so I'm thinking protect here too.
mainWindowDock.showComponent();
final int height = (Integer)
Prefs.getGlobalPrefs().getValue(MAIN_WINDOW_HEIGHT);
if (height > 0) {
final Container top = mainWindowDock.getTopLevelAncestor();
top.setSize(top.getWidth(), height);
}
}
if (toolBar.getParent() == null) {
g.getToolBar().addSeparator();
g.getToolBar().add(toolBar);
}
toolBar.setVisible(true);
}
else {
if (SwingUtilities.getWindowAncestor(theMap) == null) {
final Window topWindow = createParentFrame();
topWindow.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
if (useLaunchButton) {
topWindow.setVisible(false);
}
else {
g.getGameState().setup(false);
}
}
});
((RootPaneContainer) topWindow).getContentPane().add("North", getToolBar()); //$NON-NLS-1$
((RootPaneContainer) topWindow).getContentPane().add("Center", layeredPane); //$NON-NLS-1$
topWindow.setSize(600, 400);
final PositionOption option =
new PositionOption(PositionOption.key + getIdentifier(), topWindow);
g.getPrefs().addOption(option);
}
theMap.getTopLevelAncestor().setVisible(!useLaunchButton);
theMap.revalidate();
}
}
else {
pieces.clear();
boards.clear();
if (mainWindowDock != null) {
if (mainWindowDock.getHideableComponent().isShowing()) {
Prefs.getGlobalPrefs().getOption(MAIN_WINDOW_HEIGHT)
.setValue(mainWindowDock.getTopLevelAncestor().getHeight());
}
mainWindowDock.hideComponent();
toolBar.setVisible(false);
}
else if (theMap.getTopLevelAncestor() != null) {
theMap.getTopLevelAncestor().setVisible(false);
}
}
launchButton.setEnabled(show);
launchButton.setVisible(useLaunchButton);
}
/**
* As a {@link GameComponent}, Map does not have any action inherently needing to be taken for "restoring" itself for load/save and
* network play purposes (the locations of pieces, etc, are stored in the pieces). Map's interest in GameComponent is entirely for
* game start/stop purposes (see {@link #setup}, above)
* @return null since no restore command needed.
*/
@Override
public Command getRestoreCommand() {
return null;
}
public void appendToTitle(String s) {
if (mainWindowDock == null) {
Component c = theMap.getTopLevelAncestor();
if (s == null) {
if (c instanceof JFrame) {
((JFrame) c).setTitle(getDefaultWindowTitle());
}
if (c instanceof JDialog) {
((JDialog) c).setTitle(getDefaultWindowTitle());
}
}
else {
if (c instanceof JFrame) {
((JFrame) c).setTitle(((JFrame) c).getTitle() + s);
}
if (c instanceof JDialog) {
((JDialog) c).setTitle(((JDialog) c).getTitle() + s);
}
}
}
}
protected String getDefaultWindowTitle() {
return getLocalizedMapName().length() > 0 ? getLocalizedMapName() : Resources.getString("Map.window_title", GameModule.getGameModule().getLocalizedGameName()); //$NON-NLS-1$
}
/**
* Use the provided {@link PieceFinder} instance to locate a visible piece at the given location
*/
public GamePiece findPiece(Point pt, PieceFinder finder) {
GamePiece[] stack = pieces.getPieces();
for (int i = stack.length - 1; i >= 0; --i) {
GamePiece p = finder.select(this, stack[i], pt);
if (p != null) {
return p;
}
}
return null;
}
/**
* Use the provided {@link PieceFinder} instance to locate any piece at the given location, regardless of whether it
* is visible or not
*/
public GamePiece findAnyPiece(Point pt, PieceFinder finder) {
GamePiece[] stack = pieces.getAllPieces();
for (int i = stack.length - 1; i >= 0; --i) {
GamePiece p = finder.select(this, stack[i], pt);
if (p != null) {
return p;
}
}
return null;
}
/**
* Place a piece at the destination point. If necessary, remove the piece from its parent Stack or Map
*
* @return a {@link Command} that reproduces this action
*/
public Command placeAt(GamePiece piece, Point pt) {
Command c;
if (GameModule.getGameModule().getGameState().getPieceForId(piece.getId()) == null) {
piece.setPosition(pt);
addPiece(piece);
GameModule.getGameModule().getGameState().addPiece(piece);
c = new AddPiece(piece);
}
else {
MoveTracker tracker = new MoveTracker(piece);
piece.setPosition(pt);
addPiece(piece);
c = tracker.getMoveCommand();
}
return c;
}
/**
* Apply the provided {@link PieceVisitorDispatcher} to all pieces on this map. Returns the first non-null
* {@link Command} returned by <code>commandFactory</code>
*
* @param commandFactory Command Factory
*
*/
public Command apply(PieceVisitorDispatcher commandFactory) {
GamePiece[] stack = pieces.getPieces();
Command c = null;
for (int i = 0; i < stack.length && c == null; ++i) {
c = (Command) commandFactory.accept(stack[i]);
}
return c;
}
/**
* Move a piece to the destination point. If a piece is at the point (i.e. has a location exactly equal to it), merge
* with the piece by forwarding to {@link StackMetrics#merge}. Otherwise, place by forwarding to placeAt()
*
* @see StackMetrics#merge
*/
public Command placeOrMerge(final GamePiece p, final Point pt) {
Command c = apply(new DeckVisitorDispatcher(new Merger(this, pt, p)));
if (c == null || c.isNull()) {
c = placeAt(p, pt);
// If no piece at destination and this is a stacking piece, create
// a new Stack containing the piece
if (!(p instanceof Stack) &&
!Boolean.TRUE.equals(p.getProperty(Properties.NO_STACK))) {
final Stack parent = getStackMetrics().createStack(p);
if (parent != null) {
c = c.append(placeAt(parent, pt));
}
}
}
return c;
}
/**
* Adds a GamePiece to this map. Removes the piece from its parent Stack and from its current map, if different from
* this map
*/
public void addPiece(GamePiece p) {
if (indexOf(p) < 0) {
if (p.getParent() != null) {
p.getParent().remove(p);
p.setParent(null);
}
if (p.getMap() != null && p.getMap() != this) {
p.getMap().removePiece(p);
}
pieces.add(p);
p.setMap(this);
theMap.repaint();
}
}
/**
* Reorder the argument GamePiece to the new index. When painting the map, pieces are drawn in order of index
*
* @deprecated use {@link PieceCollection#moveToFront}
*/
@SuppressWarnings("unused")
@Deprecated(since = "2020-08-05", forRemoval = true)
public void reposition(GamePiece s, int pos) {
ProblemDialog.showDeprecated ("2020-08-05");
}
/**
* Returns the index of a piece. When painting the map, pieces are drawn in order of index Return -1 if the piece is
* not on this map
*/
public int indexOf(GamePiece s) {
return pieces.indexOf(s);
}
/**
* Removes a piece from the map
*/
public void removePiece(GamePiece p) {
pieces.remove(p);
theMap.repaint();
}
/**
* Center the map at given map coordinates within its JScrollPane container
*/
public void centerAt(Point p) {
centerAt(p, 0, 0);
}
/**
* Center the map at the given map coordinates, if the point is not
* already within (dx,dy) of the center.
*/
public void centerAt(Point p, int dx, int dy) {
if (scroll != null) {
p = mapToComponent(p);
final Rectangle r = theMap.getVisibleRect();
r.x = p.x - r.width / 2;
r.y = p.y - r.height / 2;
final Dimension d = getPreferredSize();
if (r.x + r.width > d.width) r.x = d.width - r.width;
if (r.y + r.height > d.height) r.y = d.height - r.height;
r.width = dx > r.width ? 0 : r.width - dx;
r.height = dy > r.height ? 0 : r.height - dy;
theMap.scrollRectToVisible(r);
}
}
/** Ensure that the given region (in map coordinates) is visible */
public void ensureVisible(Rectangle r) {
if (scroll != null) {
boolean bTriggerRecenter = false;
final Point p = mapToComponent(r.getLocation());
final Rectangle rCurrent = theMap.getVisibleRect();
Rectangle rNorecenter = new Rectangle(0, 0);
// If r is already visible decide if unit is close enough to
// border to justify a recenter
// Close enough means a strip of the window along the edges whose
// width is a % of the edge to center of the window
// The % is defined in GlobalOptions.CENTER_ON_MOVE_SENSITIVITY
final double noRecenterPct = (100.0 - GlobalOptions.getInstance().centerOnOpponentsMoveSensitivity()) / 100.0;
// if r is within a band of n%width/height of border, trigger recenter
rNorecenter.width = (int) round(rCurrent.width * noRecenterPct);
rNorecenter.height = (int) round(rCurrent.height * noRecenterPct);
rNorecenter.x = rCurrent.x + (int) round(rCurrent.width - rNorecenter.width) / 2;
rNorecenter.y = rCurrent.y + (int) round(rCurrent.height - rNorecenter.height) / 2;
bTriggerRecenter = p.x < rNorecenter.x || p.x > (rNorecenter.x + rNorecenter.width) ||
p.y < rNorecenter.y || p.y > (rNorecenter.y + rNorecenter.height);
if (bTriggerRecenter) {
r.x = p.x - rCurrent.width / 2;
r.y = p.y - rCurrent.height / 2;
r.width = rCurrent.width;
r.height = rCurrent.height;
final Dimension d = getPreferredSize();
if (r.x + r.width > d.width) r.x = d.width - r.width;
if (r.y + r.height > d.height) r.y = d.height - r.height;
theMap.scrollRectToVisible(r);
}
}
}
/**
* Scrolls the map in the containing JScrollPane.
*
* @param dx number of pixels to scroll horizontally
* @param dy number of pixels to scroll vertically
*/
public void scroll(int dx, int dy) {
Rectangle r = scroll.getViewport().getViewRect();
r.translate(dx, dy);
r = r.intersection(new Rectangle(getPreferredSize()));
theMap.scrollRectToVisible(r);
}
public static String getConfigureTypeName() {
return Resources.getString("Editor.Map.component_type"); //$NON-NLS-1$
}
public String getMapName() {
return getConfigureName();
}
public String getLocalizedMapName() {
return getLocalizedConfigureName();
}
public void setMapName(String s) {
mapName = s;
setConfigureName(mapName);
if (tooltip == null || tooltip.length() == 0) {
launchButton.setToolTipText(s != null ? Resources.getString("Map.show_hide", s) : Resources.getString("Map.show_hide", Resources.getString("Map.map"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
@Override
public HelpFile getHelpFile() {
return HelpFile.getReferenceManualPage("Map.html"); //$NON-NLS-1$
}
@Override
public String[] getAttributeDescriptions() {
return new String[] {
Resources.getString("Editor.Map.map_name"), //$NON-NLS-1$
Resources.getString("Editor.Map.mark_pieces_moved"), //$NON-NLS-1$
Resources.getString("Editor.Map.mark_unmoved_button_text"), //$NON-NLS-1$
Resources.getString("Editor.Map.mark_unmoved_tooltip_text"), //$NON-NLS-1$
Resources.getString("Editor.Map.mark_unmoved_button_icon"), //$NON-NLS-1$
Resources.getString("Editor.Map.horizontal"), //$NON-NLS-1$
Resources.getString("Editor.Map.vertical"), //$NON-NLS-1$
Resources.getString("Editor.Map.bkgdcolor"), //$NON-NLS-1$
Resources.getString("Editor.Map.multiboard"), //$NON-NLS-1$
Resources.getString("Editor.Map.bc_selected_counter"), //$NON-NLS-1$
Resources.getString("Editor.Map.bt_selected_counter"), //$NON-NLS-1$
Resources.getString("Editor.Map.show_hide"), //$NON-NLS-1$
Resources.getString(Resources.BUTTON_TEXT),
Resources.getString(Resources.TOOLTIP_TEXT),
Resources.getString(Resources.BUTTON_ICON),
Resources.getString(Resources.HOTKEY_LABEL),
Resources.getString("Editor.Map.report_move_within"), //$NON-NLS-1$
Resources.getString("Editor.Map.report_move_to"), //$NON-NLS-1$
Resources.getString("Editor.Map.report_created"), //$NON-NLS-1$
Resources.getString("Editor.Map.report_modified"), //$NON-NLS-1$
Resources.getString("Editor.Map.key_applied_all") //$NON-NLS-1$
};
}
@Override
public String[] getAttributeNames() {
return new String[] {
NAME,
MARK_MOVED,
MARK_UNMOVED_TEXT,
MARK_UNMOVED_TOOLTIP,
MARK_UNMOVED_ICON,
EDGE_WIDTH,
EDGE_HEIGHT,
BACKGROUND_COLOR,
ALLOW_MULTIPLE,
HIGHLIGHT_COLOR,
HIGHLIGHT_THICKNESS,
USE_LAUNCH_BUTTON,
BUTTON_NAME,
TOOLTIP,
ICON,
HOTKEY,
MOVE_WITHIN_FORMAT,
MOVE_TO_FORMAT,
CREATE_FORMAT,
CHANGE_FORMAT,
MOVE_KEY
};
}
@Override
public Class<?>[] getAttributeTypes() {
return new Class<?>[] {
String.class,
GlobalOptions.Prompt.class,
String.class,
String.class,
UnmovedIconConfig.class,
Integer.class,
Integer.class,
Color.class,
Boolean.class,
Color.class,
Integer.class,
Boolean.class,
String.class,
String.class,
IconConfig.class,
NamedKeyStroke.class,
MoveWithinFormatConfig.class,
MoveToFormatConfig.class,
CreateFormatConfig.class,
ChangeFormatConfig.class,
NamedKeyStroke.class
};
}
public static final String LOCATION = "location"; //$NON-NLS-1$
public static final String OLD_LOCATION = "previousLocation"; //$NON-NLS-1$
public static final String OLD_MAP = "previousMap"; //$NON-NLS-1$
public static final String MAP_NAME = "mapName"; //$NON-NLS-1$
public static final String PIECE_NAME = "pieceName"; //$NON-NLS-1$
public static final String MESSAGE = "message"; //$NON-NLS-1$
public static class IconConfig implements ConfigurerFactory {
@Override
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new IconConfigurer(key, name, "/images/map.gif"); //$NON-NLS-1$
}
}
public static class UnmovedIconConfig implements ConfigurerFactory {
@Override
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new IconConfigurer(key, name, "/images/unmoved.gif"); //$NON-NLS-1$
}
}
public static class MoveWithinFormatConfig implements TranslatableConfigurerFactory {
@Override
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new PlayerIdFormattedStringConfigurer(key, name, new String[] { PIECE_NAME, LOCATION, MAP_NAME, OLD_LOCATION });
}
}
public static class MoveToFormatConfig implements TranslatableConfigurerFactory {
@Override
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new PlayerIdFormattedStringConfigurer(key, name, new String[] { PIECE_NAME, LOCATION, OLD_MAP, MAP_NAME, OLD_LOCATION });
}
}
public static class CreateFormatConfig implements TranslatableConfigurerFactory {
@Override
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new PlayerIdFormattedStringConfigurer(key, name, new String[] { PIECE_NAME, MAP_NAME, LOCATION });
}
}
public static class ChangeFormatConfig implements TranslatableConfigurerFactory {
@Override
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new PlayerIdFormattedStringConfigurer(key, name, new String[] {
MESSAGE,
ReportState.COMMAND_NAME,
ReportState.OLD_UNIT_NAME,
ReportState.NEW_UNIT_NAME,
ReportState.MAP_NAME,
ReportState.LOCATION_NAME });
}
}
public String getCreateFormat() {
if (createFormat != null) {
return createFormat;
}
else {
String val = "$" + PIECE_NAME + "$ created in $" + LOCATION + "$"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
if (!boards.isEmpty()) {
Board b = boards.get(0);
if (b.getGrid() == null || b.getGrid().getGridNumbering() == null) {
val = ""; //$NON-NLS-1$
}
}
return val;
}
}
public String getChangeFormat() {
return isChangeReportingEnabled() ? changeFormat : "";
}
public String getMoveToFormat() {
if (moveToFormat != null) {
return moveToFormat;
}
else {
String val = "$" + PIECE_NAME + "$" + " moves $" + OLD_LOCATION + "$ -> $" + LOCATION + "$ *"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
if (!boards.isEmpty()) {
Board b = boards.get(0);
if (b.getGrid() == null || b.getGrid().getGridNumbering() != null) {
val = ""; //$NON-NLS-1$
}
}
return val;
}
}
public String getMoveWithinFormat() {
if (moveWithinFormat != null) {
return moveWithinFormat;
}
else {
String val = "$" + PIECE_NAME + "$" + " moves $" + OLD_LOCATION + "$ -> $" + LOCATION + "$ *"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
if (!boards.isEmpty()) {
Board b = boards.get(0);
if (b.getGrid() == null) {
val = ""; //$NON-NLS-1$
}
}
return val;
}
}
@Override
public Class<?>[] getAllowableConfigureComponents() {
return new Class<?>[]{ GlobalMap.class, LOS_Thread.class, ToolbarMenu.class, MultiActionButton.class, HidePiecesButton.class, Zoomer.class,
CounterDetailViewer.class, HighlightLastMoved.class, LayeredPieceCollection.class, ImageSaver.class, TextSaver.class, DrawPile.class, SetupStack.class,
MassKeyCommand.class, MapShader.class, PieceRecenterer.class, Flare.class };
}
@Override
public VisibilityCondition getAttributeVisibility(String name) {
if (visibilityCondition == null) {
visibilityCondition = () -> useLaunchButton;
}
if (List.of(HOTKEY, BUTTON_NAME, TOOLTIP, ICON).contains(name)) {
return visibilityCondition;
}
else if (List.of(MARK_UNMOVED_TEXT, MARK_UNMOVED_ICON, MARK_UNMOVED_TOOLTIP).contains(name)) {
return () -> !GlobalOptions.NEVER.equals(markMovedOption);
}
else {
return super.getAttributeVisibility(name);
}
}
/**
* Each Map must have a unique String id
*/
@Override
public void setId(String id) {
mapID = id;
}
public static Map getMapById(String id) {
return (Map) idMgr.findInstance(id);
}
/**
* Utility method to return a {@link List} of all map components in the
* module.
*
* @return the list of <code>Map</code>s
*/
public static List<Map> getMapList() {
final GameModule g = GameModule.getGameModule();
final List<Map> l = g.getComponentsOf(Map.class);
for (ChartWindow cw : g.getComponentsOf(ChartWindow.class)) {
for (MapWidget mw : cw.getAllDescendantComponentsOf(MapWidget.class)) {
l.add(mw.getMap());
}
}
return l;
}
/**
* Utility method to return a list of all map components in the module
*
* @return Iterator over all maps
* @deprecated Use {@link #getMapList()} instead.
*/
@Deprecated(since = "2020-08-05", forRemoval = true)
public static Iterator<Map> getAllMaps() {
ProblemDialog.showDeprecated ("2020-08-05");
return getMapList().iterator();
}
/**
* Find a contained Global Variable by name
*/
@Override
public MutableProperty getMutableProperty(String name) {
return propsContainer.getMutableProperty(name);
}
@Override
public void addMutableProperty(String key, MutableProperty p) {
propsContainer.addMutableProperty(key, p);
p.addMutablePropertyChangeListener(repaintOnPropertyChange);
}
@Override
public MutableProperty removeMutableProperty(String key) {
MutableProperty p = propsContainer.removeMutableProperty(key);
if (p != null) {
p.removeMutablePropertyChangeListener(repaintOnPropertyChange);
}
return p;
}
@Override
public String getMutablePropertiesContainerId() {
return getMapName();
}
/**
* Each Map must have a unique String id
*
* @return the id for this map
*/
@Override
public String getId() {
return mapID;
}
/**
* Make a best guess for a unique identifier for the target. Use
* {@link VASSAL.tools.UniqueIdManager.Identifyable#getConfigureName} if non-null, otherwise use
* {@link VASSAL.tools.UniqueIdManager.Identifyable#getId}
*
* @return Unique Identifier
*/
public String getIdentifier() {
return UniqueIdManager.getIdentifier(this);
}
/** @return the Swing component representing the map */
public JComponent getView() {
if (theMap == null) {
theMap = new View(this);
scroll = new AdjustableSpeedScrollPane(
theMap,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.unregisterKeyboardAction(
KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0));
scroll.unregisterKeyboardAction(
KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0));
scroll.setAlignmentX(0.0f);
scroll.setAlignmentY(0.0f);
layeredPane.setLayout(new InsetLayout(layeredPane, scroll));
layeredPane.add(scroll, JLayeredPane.DEFAULT_LAYER);
}
return theMap;
}
/** @return the JLayeredPane holding map insets */
public JLayeredPane getLayeredPane() {
return layeredPane;
}
/**
* The Layout responsible for arranging insets which overlay the Map
* InsetLayout currently is responsible for keeping the {@link GlobalMap}
* in the upper-left corner of the {@link Map.View}.
*/
public static class InsetLayout extends OverlayLayout {
private static final long serialVersionUID = 1L;
private final JScrollPane base;
public InsetLayout(Container target, JScrollPane base) {
super(target);
this.base = base;
}
@Override
public void layoutContainer(Container target) {
super.layoutContainer(target);
base.getLayout().layoutContainer(base);
final Dimension viewSize = base.getViewport().getSize();
final Insets insets = base.getInsets();
viewSize.width += insets.left;
viewSize.height += insets.top;
// prevent non-base components from overlapping the base's scrollbars
final int n = target.getComponentCount();
for (int i = 0; i < n; ++i) {
Component c = target.getComponent(i);
if (c != base && c.isVisible()) {
final Rectangle b = c.getBounds();
b.width = Math.min(b.width, viewSize.width);
b.height = Math.min(b.height, viewSize.height);
c.setBounds(b);
}
}
}
}
/**
* Implements default logic for merging pieces at a given location within
* a map Returns a {@link Command} that merges the input {@link GamePiece}
* with an existing piece at the input position, provided the pieces are
* stackable, visible, in the same layer, etc.
*/
public static class Merger implements DeckVisitor {
private final Point pt;
private final Map map;
private final GamePiece p;
public Merger(Map map, Point pt, GamePiece p) {
this.map = map;
this.pt = pt;
this.p = p;
}
@Override
public Object visitDeck(Deck d) {
if (d.getPosition().equals(pt)) {
return map.getStackMetrics().merge(d, p);
}
else {
return null;
}
}
@Override
public Object visitStack(Stack s) {
if (s.getPosition().equals(pt) && map.getStackMetrics().isStackingEnabled() && !Boolean.TRUE.equals(p.getProperty(Properties.NO_STACK))
&& s.topPiece() != null && map.getPieceCollection().canMerge(s, p)) {
return map.getStackMetrics().merge(s, p);
}
else {
return null;
}
}
@Override
public Object visitDefault(GamePiece piece) {
if (piece.getPosition().equals(pt) && map.getStackMetrics().isStackingEnabled() && !Boolean.TRUE.equals(p.getProperty(Properties.NO_STACK))
&& !Boolean.TRUE.equals(piece.getProperty(Properties.INVISIBLE_TO_ME)) && !Boolean.TRUE.equals(piece.getProperty(Properties.NO_STACK))
&& map.getPieceCollection().canMerge(piece, p)) {
return map.getStackMetrics().merge(piece, p);
}
else {
return null;
}
}
}
/**
* The component that represents the map itself
*/
public static class View extends JPanel {
private static final long serialVersionUID = 1L;
protected Map map;
public View(Map m) {
setFocusTraversalKeysEnabled(false);
map = m;
}
@Override
public void paint(Graphics g) {
// Don't draw the map until the game is updated.
if (GameModule.getGameModule().getGameState().isUpdating()) {
return;
}
final Graphics2D g2d = (Graphics2D) g;
g2d.addRenderingHints(SwingUtils.FONT_HINTS);
final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
// HDPI: We may get a transform where scale != 1. This means we
// are running on an HDPI system. We want to draw at the effective
// scale factor to prevent poor quality upscaling, so reset the
// transform to scale of 1 and multiply the map zoom by the OS scaling.
final AffineTransform orig_t = g2d.getTransform();
g2d.setTransform(SwingUtils.descaleTransform(orig_t));
final Rectangle r = map.componentToDrawing(getVisibleRect(), os_scale);
g2d.setColor(map.bgColor);
g2d.fillRect(r.x, r.y, r.width, r.height);
map.paintRegion(g2d, r);
g2d.setTransform(orig_t);
}
@Override
public void update(Graphics g) {
// To avoid flicker, don't clear the display first
paint(g);
}
@Override
public Dimension getPreferredSize() {
return map.getPreferredSize();
}
public Map getMap() {
return map;
}
}
} |
package com.datdo.mobilib.util;
import java.util.Vector;
import junit.framework.Assert;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.ImageView;
import android.widget.ListView;
/**
* <pre>
* Smart loader to display images for child views in a {@link ViewGroup}.
* Features of this loader:
* 1. Load images sequentially.
* 2. Automatically scale images to match sizes of {@link ImageView}.
* 3. Cache images using {@link LruCache}.
* 4. Prioritize loading by last-recently-displayed, which means {@link ImageView} being displayed has higher priority than {@link ImageView} which is no longer displayed.
* This feature is very useful when user scrolls a {@link ListView}.
* Override abstract methods use customize this loader.
*
* Here is sample usage of this loader:
*
* <code>
* public class MyAdapter extends BaseAdapter {
*
* private MblImageLoader{@literal <}Item> mItemImageLoader = new MblImageLoader{@literal <}Item>() {
* // override all abstract methods
* // ...
* };
*
* {@literal @}Override
* public View getView(int pos, View convertView, ViewGroup parent) {
* // create or update view
* // ...
*
* mItemImageLoader.loadImage(view);
*
* return view;
* }
* }
* </code>
* </pre>
* @param <T> class of object bound with an child views of {@link ViewGroup}
*/
public abstract class MblImageLoader<T> {
/**
* <pre>
* Check condition to load image for an item.
* </pre>
* @return true if should load image for item
*/
protected abstract boolean shouldLoadImageForItem(T item);
/**
* <pre>
* Get resource id of default image for items those are not necessary to load image
* </pre>
* @see #shouldLoadImageForItem(Object)
*/
protected abstract int getDefaultImageResource(T item);
/**
* <pre>
* Get resource id of default image for items those fails to load image
* </pre>
*/
protected abstract int getErrorImageResource(T item);
/**
* <pre>
* Get resource id of default image for items those are being loaded
* </pre>
*/
protected abstract int getLoadingIndicatorImageResource(T item);
/**
* <pre>
* Get data object bound with each child view.
* </pre>
*/
protected abstract T getItemBoundWithView(View view);
/**
* <pre>
* Extract {@link ImageView} used to display image from each child view
* </pre>
*/
protected abstract ImageView getImageViewFromView(View view);
/**
* <pre>
* Specify an ID for each data object. The ID is used for caching so please make it unique throughout the app.
* </pre>
*/
protected abstract String getItemId(T item);
/**
* <pre>
* Do your own image loading here (from HTTP/HTTPS, from file, etc...).
* This method is always invoked in main thread. Therefore, it is strongly recommended to do the loading asynchronously.
* </pre>
* @param item
* @param cb call method of this callback when you finished the loading
*/
protected abstract void retrieveImage(T item, MblRetrieveImageCallback cb);
/**
* <pre>
* Callback class for {@link MblImageLoader#retrieveImage(Object, MblRetrieveImageCallback)}
* When loading image finished, call 1 of 2 methods depending on returned data.
* If loading image failed, call any method with NULL argument.
* </pre>
*/
public static interface MblRetrieveImageCallback {
public void onRetrievedByteArray(byte[] bmData);
public void onRetrievedBitmap(Bitmap bm);
public void onRetrievedFile(String path);
}
private static final String TAG = MblUtils.getTag(MblImageLoader.class);
private static final int DEFAULT_CACHE_SIZE = 2 * 1024 * 1024; // 2MB
private static final String CACHE_KEY_SEPARATOR = "
private static final class MblCachedImageData {
public int resId = 0;
public Bitmap bitmap;
protected MblCachedImageData(int resId, Bitmap bitmap) {
Assert.assertTrue(resId > 0 || bitmap != null);
Assert.assertFalse(resId > 0 && bitmap != null);
this.resId = resId;
this.bitmap = bitmap;
}
}
private final Vector<Pair<T, View>> mQueue = new Vector<Pair<T,View>>();
private boolean mLoadingImage = false;
private static LruCache<String, MblCachedImageData> sStringPictureLruCache;
private static boolean sDoubleCacheSize = false;
private static void initCacheIfNeeded() {
if (sStringPictureLruCache == null) {
Context context = MblUtils.getCurrentContext();
int cacheSize = DEFAULT_CACHE_SIZE;
if (context != null) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
int memoryClassBytes = am.getMemoryClass() * 1024 * 1024;
cacheSize = memoryClassBytes / 8;
}
if (sDoubleCacheSize) {
cacheSize = cacheSize * 2;
}
sStringPictureLruCache = new LruCache<String, MblCachedImageData>(cacheSize) {
@Override
protected void entryRemoved(boolean evicted, String key, MblCachedImageData oldValue, MblCachedImageData newValue) {
Log.v(TAG, "Image cache size: " + size());
}
@Override
protected int sizeOf(String key, MblCachedImageData value) {
if (value.bitmap != null) {
Bitmap bm = value.bitmap;
return bm.getRowBytes() * bm.getHeight();
} else if (value.resId > 0) {
return 4;
}
return 0;
}
};
}
}
private static MblCachedImageData remove(String key) {
synchronized (sStringPictureLruCache) {
return sStringPictureLruCache.remove(key);
}
}
private static void put(String key, MblCachedImageData val) {
synchronized (sStringPictureLruCache) {
sStringPictureLruCache.put(key, val);
Log.v(TAG, "Image cache size: " + sStringPictureLruCache.size());
}
}
private static MblCachedImageData get(String key) {
return sStringPictureLruCache.get(key);
}
public MblImageLoader() {
initCacheIfNeeded();
}
/**
* <pre>
* Double memory-cache 's size to increase number of bitmap being kept in memory.
* Call this method before creating any instance.
* </pre>
*/
public static void doubleCacheSize() {
if (sStringPictureLruCache != null) {
throw new RuntimeException("doubleCacheSize() must be called before first instance of this class being created");
}
sDoubleCacheSize = true;
}
/**
* <pre>
* Stop loading. This methods should be called when the view did disappear.
* </pre>
*/
public void stop() {
synchronized (mQueue) {
mQueue.clear();
}
}
/**
* <pre>
* Request loading for a child view.
* The loading request is put into a queue and executed sequentially.
* </pre>
* @param view the child view for which you want to load image
*/
public void loadImage(final View view) {
MblUtils.executeOnMainThread(new Runnable() {
@Override
public void run() {
T item = getItemBoundWithView(view);
final ImageView imageView = getImageViewFromView(view);
if (item == null || imageView == null) return;
if (!shouldLoadImageForItem(item)) {
setImageViewResource(imageView, getDefaultImageResource(item));
return;
}
int w = getImageViewWidth(imageView);
int h = getImageViewHeight(imageView);
if (w == 0 && h == 0) {
final Runnable[] timeoutAction = new Runnable[] { null };
final OnGlobalLayoutListener globalLayoutListener = new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
MblUtils.removeOnGlobalLayoutListener(imageView, this);
MblUtils.getMainThreadHandler().removeCallbacks(timeoutAction[0]);
loadImage(view);
}
};
timeoutAction[0] = new Runnable() {
@Override
public void run() {
MblUtils.removeOnGlobalLayoutListener(imageView, globalLayoutListener);
loadImage(view);
}
};
imageView.getViewTreeObserver().addOnGlobalLayoutListener(globalLayoutListener);
MblUtils.getMainThreadHandler().postDelayed(timeoutAction[0], 500l);
return;
}
String fullCacheKey = getFullCacheKey(item, w, h);
MblCachedImageData pic = get(fullCacheKey);
if(pic != null) {
if (pic.bitmap != null) {
Bitmap bm = pic.bitmap;
if (!bm.isRecycled()) {
imageView.setImageBitmap(bm);
} else {
remove(fullCacheKey);
handleBitmapUnavailable(view, imageView, item);
}
} else if (pic.resId > 0) {
setImageViewResource(imageView, pic.resId);
}
} else {
handleBitmapUnavailable(view, imageView, item);
}
}
});
}
private void handleBitmapUnavailable(View view, ImageView imageView, T item) {
setImageViewResource(imageView, getLoadingIndicatorImageResource(item));
synchronized (mQueue) {
mQueue.add(new Pair<T, View>(item, view));
}
loadNextImage();
}
private Pair<T, View> getNextPair() {
synchronized (mQueue) {
if (mQueue.isEmpty()) {
return null;
} else {
return mQueue.remove(0);
}
}
}
private boolean isItemBoundWithView(T item, View view) {
return item != null && item == getItemBoundWithView(view);
}
private void loadNextImage() {
if (mLoadingImage) return;
Pair<T, View> pair = getNextPair();
if (pair == null) return;
final T item = pair.first;
final View view = pair.second;
final ImageView imageView = getImageViewFromView(view);
if (!isItemBoundWithView(item, view)) {
MblUtils.getMainThreadHandler().post(new Runnable() {
@Override
public void run() {
loadNextImage();
}
});
return;
}
if (!shouldLoadImageForItem(item)) {
setImageViewResource(imageView, getDefaultImageResource(item));
MblUtils.getMainThreadHandler().post(new Runnable() {
@Override
public void run() {
loadNextImage();
}
});
return;
}
final String fullCacheKey = getFullCacheKey(
item,
getImageViewWidth(imageView),
getImageViewHeight(imageView));
MblCachedImageData pic = get(fullCacheKey);
if(pic != null) {
boolean isSet = false;
if (pic.bitmap != null) {
Bitmap bm = pic.bitmap;
if (!bm.isRecycled()) {
imageView.setImageBitmap(bm);
isSet = true;
} else {
remove(fullCacheKey);
}
} else if (pic.resId > 0) {
setImageViewResource(imageView, pic.resId);
isSet = true;
}
if (isSet) {
MblUtils.getMainThreadHandler().post(new Runnable() {
@Override
public void run() {
loadNextImage();
}
});
return;
}
}
mLoadingImage = true;
final boolean isNetworkConnected = MblUtils.isNetworkConnected();
retrieveImage(item, new MblRetrieveImageCallback() {
@Override
public void onRetrievedByteArray(final byte[] bmData) {
if (MblUtils.isEmpty(bmData)) {
handleBadReturnedBitmap(item, view, fullCacheKey, !isNetworkConnected);
} else {
MblUtils.executeOnAsyncThread(new Runnable() {
@Override
public void run() {
try {
int w = getImageViewWidth(imageView);
int h = getImageViewHeight(imageView);
Bitmap bm = MblUtils.loadBitmapMatchSpecifiedSize(w, h, bmData);
if (bm == null) {
handleBadReturnedBitmap(item, view, fullCacheKey, !isNetworkConnected);
} else {
Log.d(TAG, "Scale bitmap: w=" + w + ", h=" + h +
", bm.w=" + bm.getWidth() + ", bm.h=" + bm.getHeight());
handleGoodReturnedBitmap(item, view, fullCacheKey, bm);
}
} catch (OutOfMemoryError e) {
Log.e(TAG, "OutOfMemoryError", e);
handleOutOfMemory(item, view, fullCacheKey);
}
}
});
}
}
@Override
public void onRetrievedFile(final String path) {
if (MblUtils.isEmpty(path)) {
handleBadReturnedBitmap(item, view, fullCacheKey, !isNetworkConnected);
} else {
MblUtils.executeOnAsyncThread(new Runnable() {
@Override
public void run() {
try {
int w = getImageViewWidth(imageView);
int h = getImageViewHeight(imageView);
Bitmap bm = MblUtils.loadBitmapMatchSpecifiedSize(w, h, path);
if (bm == null) {
handleBadReturnedBitmap(item, view, fullCacheKey, !isNetworkConnected);
} else {
Log.d(TAG, "Scale bitmap: w=" + w + ", h=" + h +
", bm.w=" + bm.getWidth() + ", bm.h=" + bm.getHeight());
handleGoodReturnedBitmap(item, view, fullCacheKey, bm);
}
} catch (OutOfMemoryError e) {
Log.e(TAG, "OutOfMemoryError", e);
handleOutOfMemory(item, view, fullCacheKey);
}
}
});
}
}
@Override
public void onRetrievedBitmap(Bitmap bm) {
if (bm == null) {
handleBadReturnedBitmap(item, view, fullCacheKey, !isNetworkConnected);
} else {
handleGoodReturnedBitmap(item, view, fullCacheKey, bm);
}
}
});
}
private void handleGoodReturnedBitmap(final T item, final View view, final String fullCacheKey, final Bitmap bm) {
MblUtils.executeOnMainThread(new Runnable() {
@Override
public void run() {
put(fullCacheKey, new MblCachedImageData(0, bm));
postLoadImageForItem(item, view);
}
});
}
private void handleBadReturnedBitmap(final T item, final View view, final String fullCacheKey, final boolean shouldRetry) {
MblUtils.executeOnMainThread(new Runnable() {
@Override
public void run() {
int errorImageRes = getErrorImageResource(item);
if (errorImageRes > 0) {
put(fullCacheKey, new MblCachedImageData(errorImageRes, null));
}
postLoadImageForItem(item, view);
// failed due to network disconnect -> should try to load later
if (shouldRetry) {
MblUtils.getMainThreadHandler().post(new Runnable() {
@Override
public void run() {
remove(fullCacheKey);
}
});
}
}
});
}
private void handleOutOfMemory(final T item, final View view, final String fullCacheKey) {
MblUtils.executeOnMainThread(new Runnable() {
@Override
public void run() {
// release 1/2 of cache size for memory
synchronized (sStringPictureLruCache) {
sStringPictureLruCache.trimToSize(sStringPictureLruCache.size()/2);
}
System.gc();
handleBadReturnedBitmap(item, view, fullCacheKey, true);
}
});
}
private void postLoadImageForItem(final T item, final View view) {
if (isItemBoundWithView(item, view)) {
loadImage(view);
}
// run loadNextImage() using "post" to prevent deep recursion
MblUtils.getMainThreadHandler().post(new Runnable() {
@Override
public void run() {
mLoadingImage = false;
loadNextImage();
}
});
}
private void setImageViewResource(ImageView imageView, int resId) {
if (resId <= 0) {
imageView.setImageBitmap(null);
} else {
imageView.setImageResource(resId);
}
}
private String getFullCacheKey(T item, int w, int h) {
String key = TextUtils.join(CACHE_KEY_SEPARATOR, new Object[] {
item.getClass().getSimpleName(),
MblUtils.md5(getItemId(item)),
w,
h
});
return key;
}
private int getImageViewWidth(ImageView imageView) {
LayoutParams lp = imageView.getLayoutParams();
if (lp.width == LayoutParams.WRAP_CONTENT) {
return -1; // do not care
} else if (lp.width == LayoutParams.MATCH_PARENT){
return imageView.getWidth(); // 0 or parent 's width
} else {
return lp.width; // specified width
}
}
private int getImageViewHeight(ImageView imageView) {
LayoutParams lp = imageView.getLayoutParams();
if (lp.height == LayoutParams.WRAP_CONTENT) {
return -1; // do not care
} else if (lp.height == LayoutParams.MATCH_PARENT){
return imageView.getHeight(); // 0 or parent 's height
} else {
return lp.height; // specified height
}
}
} |
package motocitizen.Activity;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import motocitizen.app.general.user.Role;
import motocitizen.content.Content;
import motocitizen.main.R;
import motocitizen.startup.Preferences;
import motocitizen.startup.Startup;
public class AuthActivity extends ActionBarActivity/* implements View.OnClickListener*/ {
private Button logoutBtn;
private Button loginBtn;
private Button cancelBtn;
private EditText login;
private EditText password;
private CheckBox anonim;
private static Context context;
private void enableLoginBtn() {
Boolean logPasReady = login.getText().toString().length() > 0 && password.getText().toString().length() > 0;
loginBtn.setEnabled(anonim.isChecked() || logPasReady);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.auth);
context = this;
login = (EditText) findViewById(R.id.mc_auth_login);
login.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
enableLoginBtn();
}
});
password = (EditText) findViewById(R.id.mc_auth_password);
password.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
enableLoginBtn();
}
});
anonim = (CheckBox) findViewById(R.id.mc_auth_anonim);
anonim.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CheckBox checkBox = (CheckBox) view;
login.setEnabled(!checkBox.isChecked());
password.setEnabled(!checkBox.isChecked());
enableLoginBtn();
}
});
cancelBtn = (Button) findViewById(R.id.cancel_button);
cancelBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
logoutBtn = (Button) findViewById(R.id.logout_button);
logoutBtn.setOnClickListener(new View.OnClickListener() {
@SuppressLint("CommitPrefEdits")
@Override
public void onClick(View v) {
Preferences.resetAuth();
Preferences.setAnonim(true);
Content.auth.logoff();
fillCtrls();
}
});
loginBtn = (Button) findViewById(R.id.login_button);
loginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (anonim.isChecked()) {
Preferences.setAnonim(true);
((TextView) findViewById(R.id.auth_error_helper)).setText("");
finish();
} else {
if (Startup.isOnline(context)) {
if (Content.auth.auth(context, login.getText().toString(), password.getText().toString())) {
Preferences.setAnonim(false);
finish();
} else {
TextView authErrorHelper = (TextView) findViewById(R.id.auth_error_helper);
authErrorHelper.setText(R.string.auth_password_error);
}
} else {
Toast.makeText(context, R.string.auth_not_available, Toast.LENGTH_LONG).show();
}
}
}
});
TextView accListYesterdayLine = (TextView) findViewById(R.id.accListYesterdayLine);
accListYesterdayLine.setMovementMethod(LinkMovementMethod.getInstance());
fillCtrls();
}
private void fillCtrls() {
login.setText(Preferences.getLogin());
password.setText(Preferences.getPassword());
anonim.setChecked(Preferences.isAnonim());
View accListYesterdayLine = findViewById(R.id.accListYesterdayLine);
TextView roleView = (TextView) findViewById(R.id.role);
if (Content.auth.isAuthorized()) {
loginBtn.setEnabled(false);
logoutBtn.setEnabled(true);
anonim.setEnabled(false);
accListYesterdayLine.setVisibility(View.GONE);
String format = getString(R.string.mc_auth_role);
roleView.setText(String.format(format, Role.getName(this)));
roleView.setVisibility(View.VISIBLE);
login.setEnabled(false);
password.setEnabled(false);
} else {
// if (prefs.isAnonim()) {
loginBtn.setEnabled(true);
logoutBtn.setEnabled(false);
anonim.setEnabled(true);
login.setEnabled(!anonim.isChecked());
password.setEnabled(!anonim.isChecked());
accListYesterdayLine.setVisibility(View.VISIBLE);
roleView.setVisibility(View.GONE);
enableLoginBtn();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
} |
package com.feedhenry.sdk;
import android.content.Context;
import com.feedhenry.sdk.api.*;
import com.feedhenry.sdk.api.FHCloudRequest.Methods;
import com.feedhenry.sdk.exceptions.FHNotReadyException;
import com.feedhenry.sdk.utils.DataManager;
import com.feedhenry.sdk.utils.FHLog;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.jboss.aerogear.android.core.Callback;
import org.jboss.aerogear.android.unifiedpush.RegistrarManager;
import org.jboss.aerogear.android.unifiedpush.gcm.AeroGearGCMPushConfiguration;
import org.jboss.aerogear.android.unifiedpush.gcm.AeroGearGCMPushRegistrar;
import org.jboss.aerogear.android.unifiedpush.metrics.UnifiedPushMetricsMessage;
import org.json.fh.JSONObject;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
/**
* The FH class provides static methods to initialize the library, create new instances of all the
* API request objects, and configure global settings.
*/
public class FH {
private static boolean mReady = false;
private static final String LOG_TAG = "com.feedhenry.sdk.FH";
private static final String FH_API_ACT = "act";
private static final String FH_API_AUTH = "auth";
private static final String FH_API_CLOUD = "cloud";
private static final String FH_PUSH_NAME = "FH";
public static final int LOG_LEVEL_VERBOSE = 1;
public static final int LOG_LEVEL_DEBUG = 2;
public static final int LOG_LEVEL_INFO = 3;
public static final int LOG_LEVEL_WARNING = 4;
public static final int LOG_LEVEL_ERROR = 5;
public static final int LOG_LEVEL_NONE = Integer.MAX_VALUE;
private static int mLogLevel = LOG_LEVEL_ERROR;
public static final String VERSION = "2.1.0"; // DO NOT CHANGE, the ant build task will automatically update this value. Update it in VERSION.txt
private static boolean mInitCalled = false;
private static Context mContext;
private FH() throws Exception {
throw new Exception("Not Supported");
}
/**
* Initializes the application.
* This must be called before the application can use the FH library.
* The initialization process happens in a background thread so that the UI thread won't be blocked.
* If you need to call other FH API methods, you need to make sure they are called after the init
* finishes. The best way to do it is to provide a FHActCallback instance and implement the success method.
* The callback functions are invoked on the main UI thread.
* For example, in your main activity class's onCreate method, you can do this:
*
* <pre>
* {@code
* FH.init(this, new FHActCallback() {
* public void success(FHResponse pRes) {
* //pRes will be null for init call if it succeeds, don't use it to access response data
* FHActRequest request = FH.buildActRequest("readData", new JSONObject());
* request.executeAsync(new FHActCallback(){
* public void success(FHResponse pResp){
* //process response data
* }
*
* public void fail(FHResponse pResp){
* //process error data
* }
* })
* }
*
* public void fail(FHResponse pRes) {
* Log.e("FHInit", pRes.getErrorMessage(), pRes.getError());
* }
* });
* }
* </pre>
*
* @param pContext your application's context
* @param pCallback the callback function to be executed after initialization is finished
*/
public static void init(Context pContext, FHActCallback pCallback) {
mContext = pContext;
if (!mInitCalled) {
DataManager.init(mContext).migrateLegacyData();
checkNetworkStatus();
try {
AppProps.load(mContext);
} catch (IOException e) {
mReady = false;
FHLog.e(LOG_TAG, "Can not load property file.", e);
}
mInitCalled = true;
}
if (mReady) {
if (pCallback != null) {
pCallback.success(null);
}
return;
}
final FHActCallback cb = pCallback;
if (AppProps.getInstance().isLocalDevelopment()) {
FHLog.i(
LOG_TAG,
"Local development mode enabled, loading properties from assets/fhconfig.local.properties file");
CloudProps.initDev();
mReady = true;
if (cb != null) {
cb.success(null);
}
return;
}
FHInitializeRequest initRequest = new FHInitializeRequest(mContext);
try {
initRequest.executeAsync(
new FHActCallback() {
@Override
public void success(FHResponse pResponse) {
mReady = true;
FHLog.v(LOG_TAG, "FH init response = " + pResponse.getJson().toString());
JSONObject cloudProps = pResponse.getJson();
CloudProps.init(cloudProps);
CloudProps.getInstance().save();
if (cb != null) {
cb.success(null);
}
}
@Override
public void fail(FHResponse pResponse) {
FHLog.e(
LOG_TAG,
"FH init failed with error = " + pResponse.getErrorMessage(),
pResponse.getError());
CloudProps props = CloudProps.load();
if (props != null) {
mReady = true;
FHLog.i(LOG_TAG, "Cached CloudProps data found");
if (cb != null) {
cb.success(null);
}
} else {
mReady = false;
FHLog.i(LOG_TAG, "No cache data found for CloudProps");
if (cb != null) {
cb.fail(pResponse);
}
}
}
});
} catch (Exception e) {
FHLog.e(LOG_TAG, "FH init exception = " + e.getMessage(), e);
}
}
private static void checkNetworkStatus() {
NetworkManager networkManager = NetworkManager.init(mContext);
networkManager.registerNetworkListener();
networkManager.checkNetworkStatus();
if (networkManager.isOnline() && !mReady && mInitCalled) {
init(mContext, null);
}
}
private static FHAct buildAction(String pAction) throws FHNotReadyException {
if (!mInitCalled) {
throw new FHNotReadyException();
}
FHAct action = null;
if (FH_API_ACT.equalsIgnoreCase(pAction)) {
action = new FHActRequest(mContext);
} else if (FH_API_AUTH.equalsIgnoreCase(pAction)) {
action = new FHAuthRequest(mContext);
} else if (FH_API_CLOUD.equalsIgnoreCase(pAction)) {
action = new FHCloudRequest(mContext);
} else {
FHLog.w(LOG_TAG, "Invalid action : " + pAction);
}
return action;
}
public static boolean isOnline() {
return NetworkManager.getInstance().isOnline();
}
public static void stop() {
NetworkManager.getInstance().unregisterNetworkListener();
}
/**
* Checks if FH is ready.
*
* @return whether FH has finished initialization
*/
public static boolean isReady() {
return mReady;
}
@Deprecated
/**
* Builds an instance of {@link FHActRequest} to perform an act request.
* @param pRemoteAction the name of the cloud side function
* @param pParams the parameters for the cloud side function
* @return an instance of FHActRequest
* @throws FHNotReadyException
*/
public static FHActRequest buildActRequest(String pRemoteAction, JSONObject pParams) throws FHNotReadyException {
FHActRequest request = (FHActRequest) buildAction(FH_API_ACT);
request.setRemoteAction(pRemoteAction);
request.setArgs(pParams);
return request;
}
/**
* Builds an instance of FHAuthRequest object to perform an authentication request.
*
* @return an instance of FHAuthRequest
* @throws FHNotReadyException if init has not been called
*/
public static FHAuthRequest buildAuthRequest() throws FHNotReadyException {
return (FHAuthRequest) buildAction(FH_API_AUTH);
}
/**
* Builds an instance of FHAuthRequest object to perform an authentication request with an auth policy id set.
*
* @param pPolicyId the auth policy id used by this auth request
* @return an instance of FHAuthRequest
* @throws FHNotReadyException if init has not been called
*/
public static FHAuthRequest buildAuthRequest(String pPolicyId) throws FHNotReadyException {
FHAuthRequest request = (FHAuthRequest) buildAction(FH_API_AUTH);
request.setAuthPolicyId(pPolicyId);
return request;
}
/**
* Builds an instance of FHAuthRequest to perform an authentication request with an auth policy id,
* user name, and password set.
*
* @param pPolicyId the auth policy id used by this auth request
* @param pUserName the required user name for the auth request
* @param pPassword the required password for the auth request
* @return an instance of FHAuthRequest
* @throws FHNotReadyException if init has not been called
*/
public static FHAuthRequest buildAuthRequest(String pPolicyId, String pUserName, String pPassword)
throws FHNotReadyException {
FHAuthRequest request = (FHAuthRequest) buildAction(FH_API_AUTH);
request.setAuthUser(pPolicyId, pUserName, pPassword);
return request;
}
/**
* Builds an instance of FHCloudRequest to call cloud APIs.
*
* @param pPath the path of the cloud API
* @param pMethod currently supports GET, POST, PUT and DELETE
* @param pHeaders headers need to be set, can be null
* @param pParams the request params, can be null
* @return an instance of FHCloudRequest
* @throws FHNotReadyException if init has not been called
* @throws Exception if pMethod is not one of GET, POST, PUT and DELETE
*/
public static FHCloudRequest buildCloudRequest(String pPath, String pMethod, Header[] pHeaders, JSONObject pParams)
throws Exception {
FHCloudRequest request = (FHCloudRequest) buildAction(FH_API_CLOUD);
request.setPath(pPath);
request.setHeaders(pHeaders);
request.setMethod(Methods.parse(pMethod));
request.setRequestArgs(pParams);
return request;
}
/**
* Gets the cloud host.
*
* @return the cloud host of the app
* @throws FHNotReadyException if init has not been called
*/
public static String getCloudHost() throws FHNotReadyException {
if (CloudProps.getInstance() == null) {
throw new FHNotReadyException();
}
return CloudProps.getInstance().getCloudHost();
}
/**
* Gets the default params for customised HTTP Requests.
* These params will be required to enable app analytics on the FH platform.
* You can either add the params to your request body as a JSONObject with the key "__fh", or use the
* {@link #getDefaultParamsAsHeaders(Header[]) getDefaultParamsAsHeaders} method to add them as HTTP request
* headers.
*
* @return a JSONObject contains the default params
* @throws Exception if the app property file is not loaded
*/
public static JSONObject getDefaultParams() throws Exception {
AppProps appProps = AppProps.getInstance();
JSONObject defaultParams = new JSONObject();
defaultParams.put("appid", appProps.getAppId());
defaultParams.put("appkey", appProps.getAppApiKey());
defaultParams.put("cuid", Device.getDeviceId(mContext));
defaultParams.put("destination", "android");
defaultParams.put("sdk_version", "FH_ANDROID_SDK/" + FH.VERSION);
String projectId = appProps.getProjectId();
if (projectId != null && !projectId.isEmpty()) {
defaultParams.put("projectid", projectId);
}
String connectionTag = appProps.getConnectionTag();
if (connectionTag != null && !connectionTag.isEmpty()) {
defaultParams.put("connectiontag", connectionTag);
}
// Load init
String init = CloudProps.getInitValue();
if (init != null) {
JSONObject initObj = new JSONObject(init);
defaultParams.put("init", initObj);
}
if (FHAuthSession.exists()) {
defaultParams.put(FHAuthSession.SESSION_TOKEN_KEY, FHAuthSession.getToken());
}
return defaultParams;
}
/**
* Similar to {@link #getDefaultParams() getDefaultParams}, but returns HTTP headers instead.
*
* @param pHeaders existing headers
* @return new headers by combining existing headers and default headers
* @throws Exception if the app property file is not loaded
*/
public static Header[] getDefaultParamsAsHeaders(Header[] pHeaders) throws Exception {
ArrayList<Header> headers = new ArrayList<Header>();
JSONObject defaultParams = FH.getDefaultParams();
for (Iterator<String> it = defaultParams.keys(); it.hasNext(); ) {
String key = it.next();
headers.add(new BasicHeader("X-FH-" + key, defaultParams.getString(key)));
}
if (pHeaders != null) {
headers.ensureCapacity(pHeaders.length + 1);
Collections.addAll(headers, pHeaders);
}
return headers.toArray(new Header[headers.size()]);
}
/**
* Calls cloud APIs asynchronously.
*
* @param pPath the path to the cloud API
* @param pMethod currently supports GET, POST, PUT and DELETE
* @param pHeaders headers need to be set, can be null
* @param pParams the request params, can be null. Will be converted to query strings depending
* on the HTTP method
* @param pCallback the callback to be executed when the cloud call is finished
* @throws FHNotReadyException if init has not been called
* @throws Exception if pMethod is not one of GET, POST, PUT and DELETE OR if the cloud request
* fails
*/
public static void cloud(
String pPath,
String pMethod,
Header[] pHeaders,
JSONObject pParams,
FHActCallback pCallback)
throws Exception {
FHCloudRequest cloudRequest = buildCloudRequest(pPath, pMethod, pHeaders, pParams);
cloudRequest.executeAsync(pCallback);
}
/**
* Sets the log level for the library.
* The default level is {@link #LOG_LEVEL_ERROR}. Please make sure this is set to {@link #LOG_LEVEL_ERROR}
* or {@link #LOG_LEVEL_NONE} before releasing the application.
* The log level can be one of
* <ul>
* <li>{@link #LOG_LEVEL_VERBOSE}</li>
* <li>{@link #LOG_LEVEL_DEBUG}</li>
* <li>{@link #LOG_LEVEL_INFO}</li>
* <li>{@link #LOG_LEVEL_WARNING}</li>
* <li>{@link #LOG_LEVEL_ERROR}</li>
* <li>{@link #LOG_LEVEL_NONE}</li>
* </ul>
*
* @param pLogLevel The level of logging for the FH library
*/
public static void setLogLevel(int pLogLevel) {
mLogLevel = pLogLevel;
}
/**
* Gets the current log level for the FH library.
*
* @return The current log level
*/
public static int getLogLevel() {
return mLogLevel;
}
/**
* Gets the customized user-agent string for the SDK.
*
* @return customized user-agent string
*/
public static String getUserAgent() {
return Device.getUserAgent();
}
/**
* Registers a device on a push network.
* The push information will be loaded from fhconfig.properties.
*
* This method need to be called <b>after</b> an {@link #init(android.content.Context, FHActCallback)} success
* callback.
*
* @param pCallback the pCallback function to be executed after the device registration is finished
*/
public static void pushRegister(FHActCallback pCallback) {
pushRegister(new PushConfig(), pCallback);
}
/**
* Registers a device on a push network.
* The push information will be loaded from fhconfig.properties.
*
* This method need to be called <b>after</b> an {@link #init(android.content.Context, FHActCallback)} success
* callback.
*
* @param pPushConfig extra configuration for push
* @param pCallback the pCallback function to be executed after the device registration is finished
*/
public static void pushRegister(final PushConfig pPushConfig, final FHActCallback pCallback) {
RegistrarManager.config(FH_PUSH_NAME, AeroGearGCMPushConfiguration.class)
.setPushServerURI(URI.create(AppProps.getInstance().getPushServerUrl()))
.setSenderIds(AppProps.getInstance().getPushSenderId())
.setVariantID(AppProps.getInstance().getPushVariant())
.setSecret(AppProps.getInstance().getPushSecret())
.setAlias(pPushConfig.getAlias())
.setCategories(pPushConfig.getCategories())
.asRegistrar()
.register(
mContext, new Callback<Void>() {
@Override
public void onSuccess(Void aVoid) {
pCallback.success(new FHResponse(null, null, null, null));
}
@Override
public void onFailure(Exception e) {
pCallback.fail(new FHResponse(null, null, e, e.getMessage()));
}
});
}
/**
* Sends confirmation a message was opened.
*
* @param pMessageId Id of the message received
* @param pCallback the pCallback function to be executed after the metrics sent
*/
public static void sendPushMetrics(String pMessageId, final FHActCallback pCallback) {
AeroGearGCMPushRegistrar registrar = (AeroGearGCMPushRegistrar) RegistrarManager.getRegistrar(FH_PUSH_NAME);
registrar.sendMetrics(
new UnifiedPushMetricsMessage(pMessageId), new Callback<UnifiedPushMetricsMessage>() {
@Override
public void onSuccess(UnifiedPushMetricsMessage data) {
pCallback.success(new FHResponse(null, null, null, null));
}
@Override
public void onFailure(Exception e) {
pCallback.fail(new FHResponse(null, null, e, e.getMessage()));
}
});
}
} |
package edu.umd.cs.findbugs;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.CodeException;
import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantClass;
import org.apache.bcel.classfile.ConstantDouble;
import org.apache.bcel.classfile.ConstantFloat;
import org.apache.bcel.classfile.ConstantInteger;
import org.apache.bcel.classfile.ConstantLong;
import org.apache.bcel.classfile.ConstantString;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.LocalVariable;
import org.apache.bcel.classfile.LocalVariableTable;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.BasicType;
import org.apache.bcel.generic.Type;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.AnalysisFeatures;
import edu.umd.cs.findbugs.ba.ClassMember;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.visitclass.Constants2;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
import edu.umd.cs.findbugs.visitclass.LVTHelper;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;
/**
* tracks the types and numbers of objects that are currently on the operand stack
* throughout the execution of method. To use, a detector should instantiate one for
* each method, and call <p>stack.sawOpcode(this,seen);</p> at the bottom of their sawOpcode method.
* at any point you can then inspect the stack and see what the types of objects are on
* the stack, including constant values if they were pushed. The types described are of
* course, only the static types.
* There are some outstanding opcodes that have yet to be implemented, I couldn't
* find any code that actually generated these, so i didn't put them in because
* I couldn't test them:
* <ul>
* <li>dup2_x2</li>
* <li>jsr_w</li>
* <li>wide</li>
* </ul>
*/
public class OpcodeStack implements Constants2
{
private static final boolean DEBUG
= SystemProperties.getBoolean("ocstack.debug");
private static final boolean DEBUG2 = DEBUG;
private List<Item> stack;
private List<Item> lvValues;
private List<Integer> lastUpdate;
private boolean top;
private boolean seenTransferOfControl = false;
private boolean useIterativeAnalysis
= AnalysisContext.currentAnalysisContext().getBoolProperty(AnalysisFeatures.INTERATIVE_OPCODE_STACK_ANALYSIS);
public static class ItemBase {
public ItemBase() {};
}
public static class Item extends ItemBase
{
public static final int SIGNED_BYTE = 1;
public static final int RANDOM_INT = 2;
public static final int LOW_8_BITS_CLEAR = 3;
public static final int HASHCODE_INT = 4;
public static final int INTEGER_SUM = 5;
public static final int AVERAGE_COMPUTED_USING_DIVISION = 6;
public static final int FLOAT_MATH = 7;
public static final int RANDOM_INT_REMAINDER = 8;
public static final int HASHCODE_INT_REMAINDER = 9;
public static final int FILE_SEPARATOR_STRING = 10;
public static final int MATH_ABS = 11;
public static final int MASKED_NON_NEGATIVE = 12;
public static final int NASTY_FLOAT_MATH = 13;
private static final int IS_INITIAL_PARAMETER_FLAG=1;
private static final int COULD_BE_ZERO_FLAG = 2;
private static final int IS_NULL_FLAG = 4;
public static final Object UNKNOWN = null;
private int specialKind;
private String signature;
private Object constValue = UNKNOWN;
private @CheckForNull ClassMember source;
private int flags;
// private boolean isNull = false;
private int registerNumber = -1;
// private boolean isInitialParameter = false;
// private boolean couldBeZero = false;
private Object userValue = null;
private int fieldLoadedFromRegister = -1;
public int getSize() {
if (signature.equals("J") || signature.equals("D")) return 2;
return 1;
}
public boolean isWide() {
return getSize() == 2;
}
private static boolean equals(Object o1, Object o2) {
if (o1 == o2) return true;
if (o1 == null || o2 == null) return false;
return o1.equals(o2);
}
@Override
public int hashCode() {
int r = 42 + specialKind;
if (signature != null)
r+= signature.hashCode();
r *= 31;
if (constValue != null)
r+= constValue.hashCode();
r *= 31;
if (source != null)
r+= source.hashCode();
r *= 31;
r += flags;
r *= 31;
r += registerNumber;
return r;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Item)) return false;
Item that = (Item) o;
return equals(this.signature, that.signature)
&& equals(this.constValue, that.constValue)
&& equals(this.source, that.source)
&& this.specialKind == that.specialKind
&& this.registerNumber == that.registerNumber
&& this.flags == that.flags
&& this.userValue == that.userValue
&& this.fieldLoadedFromRegister == that.fieldLoadedFromRegister;
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer("< ");
buf.append(signature);
switch(specialKind) {
case SIGNED_BYTE:
buf.append(", byte_array_load");
break;
case RANDOM_INT:
buf.append(", random_int");
break;
case LOW_8_BITS_CLEAR:
buf.append(", low8clear");
break;
case HASHCODE_INT:
buf.append(", hashcode_int");
break;
case INTEGER_SUM:
buf.append(", int_sum");
break;
case AVERAGE_COMPUTED_USING_DIVISION:
buf.append(", averageComputingUsingDivision");
break;
case FLOAT_MATH:
buf.append(", floatMath");
break;
case NASTY_FLOAT_MATH:
buf.append(", nastyFloatMath");
break;
case HASHCODE_INT_REMAINDER:
buf.append(", hashcode_int_rem");
break;
case RANDOM_INT_REMAINDER:
buf.append(", random_int_rem");
break;
case FILE_SEPARATOR_STRING:
buf.append(", file_separator_string");
break;
case MATH_ABS:
buf.append(", Math.abs");
break;
case MASKED_NON_NEGATIVE:
buf.append(", masked_non_negative");
break;
case 0 :
break;
default:
buf.append(", #" + specialKind);
break;
}
if (constValue != UNKNOWN) {
buf.append(", ");
buf.append(constValue);
}
if (source instanceof XField) {
buf.append(", ");
if (fieldLoadedFromRegister != -1)
buf.append(fieldLoadedFromRegister).append(':');
buf.append(source);
}
if (source instanceof XMethod) {
buf.append(", return value from ");
buf.append(source);
}
if (isInitialParameter()) {
buf.append(", IP");
}
if (isNull()) {
buf.append(", isNull");
}
if (registerNumber != -1) {
buf.append(", r");
buf.append(registerNumber);
}
if (isCouldBeZero()) buf.append(", cbz");
buf.append(" >");
return buf.toString();
}
public static Item merge(Item i1, Item i2) {
if (i1 == null) return i2;
if (i2 == null) return i1;
if (i1.equals(i2)) return i1;
Item m = new Item();
m.flags = i1.flags & i2.flags;
m.setCouldBeZero(i1.isCouldBeZero() || i2.isCouldBeZero());
if (equals(i1.signature,i2.signature))
m.signature = i1.signature;
if (equals(i1.constValue,i2.constValue))
m.constValue = i1.constValue;
if (equals(i1.source,i2.source)) {
m.source = i1.source;
}
if (i1.registerNumber == i2.registerNumber)
m.registerNumber = i1.registerNumber;
if (i1.fieldLoadedFromRegister == i2.fieldLoadedFromRegister)
m.fieldLoadedFromRegister = i1.fieldLoadedFromRegister;
if (i1.specialKind == i2.specialKind)
m.specialKind = i1.specialKind;
else if (i1.specialKind == NASTY_FLOAT_MATH || i2.specialKind == NASTY_FLOAT_MATH)
m.specialKind = NASTY_FLOAT_MATH;
else if (i1.specialKind == FLOAT_MATH || i2.specialKind == FLOAT_MATH)
m.specialKind = FLOAT_MATH;
if (DEBUG) System.out.println("Merge " + i1 + " and " + i2 + " gives " + m);
return m;
}
public Item(String signature, int constValue) {
this(signature, (Object)(Integer)constValue);
}
public Item(String signature) {
this(signature, UNKNOWN);
}
public Item(Item it) {
this.signature = it.signature;
this.constValue = it.constValue;
this.source = it.source;
this.registerNumber = it.registerNumber;
this.userValue = it.userValue;
this.flags = it.flags;
this.specialKind = it.specialKind;
}
public Item(Item it, int reg) {
this(it);
this.registerNumber = reg;
}
public Item(String signature, FieldAnnotation f) {
this.signature = signature;
if (f != null)
source = XFactory.createXField(f);
fieldLoadedFromRegister = -1;
}
public Item(String signature, FieldAnnotation f, int fieldLoadedFromRegister) {
this.signature = signature;
if (f != null)
source = XFactory.createXField(f);
this.fieldLoadedFromRegister = fieldLoadedFromRegister;
}
public int getFieldLoadedFromRegister() {
return fieldLoadedFromRegister;
}
public Item(String signature, Object constantValue) {
this.signature = signature;
constValue = constantValue;
if (constantValue instanceof Integer) {
int value = (Integer) constantValue;
if (value != 0 && (value & 0xff) == 0)
specialKind = LOW_8_BITS_CLEAR;
if (value == 0) setCouldBeZero(true);
}
else if (constantValue instanceof Long) {
long value = (Long) constantValue;
if (value != 0 && (value & 0xff) == 0)
specialKind = LOW_8_BITS_CLEAR;
if (value == 0) setCouldBeZero(true);
}
}
public Item() {
signature = "Ljava/lang/Object;";
constValue = null;
setNull(true);
}
public JavaClass getJavaClass() throws ClassNotFoundException {
String baseSig;
if (isPrimitive())
return null;
if (isArray()) {
baseSig = getElementSignature();
} else {
baseSig = signature;
}
if (baseSig.length() == 0)
return null;
baseSig = baseSig.substring(1, baseSig.length() - 1);
baseSig = baseSig.replace('/', '.');
return Repository.lookupClass(baseSig);
}
public boolean isArray() {
return signature.startsWith("[");
}
public String getElementSignature() {
if (!isArray())
return signature;
else {
int pos = 0;
int len = signature.length();
while (pos < len) {
if (signature.charAt(pos) != '[')
break;
pos++;
}
return signature.substring(pos);
}
}
public boolean isNonNegative() {
if (specialKind == MASKED_NON_NEGATIVE) return true;
if (constValue instanceof Number) {
double value = ((Number) constValue).doubleValue();
return value >= 0;
}
return false;
}
public boolean isPrimitive() {
return !signature.startsWith("L");
}
public int getRegisterNumber() {
return registerNumber;
}
public String getSignature() {
return signature;
}
/**
* Returns a constant value for this Item, if known.
* NOTE: if the value is a constant Class object, the constant value returned is the name of the class.
*/
public Object getConstant() {
return constValue;
}
/** Use getXField instead */
@Deprecated
public FieldAnnotation getFieldAnnotation() {
return FieldAnnotation.fromXField(getXField());
}
public XField getXField() {
if (source instanceof XField) return (XField) source;
return null;
}
/**
* @param specialKind The specialKind to set.
*/
public void setSpecialKind(int specialKind) {
this.specialKind = specialKind;
}
/**
* @return Returns the specialKind.
*/
public int getSpecialKind() {
return specialKind;
}
/**
* attaches a detector specified value to this item
*
* @param value the custom value to set
*/
public void setUserValue(Object value) {
userValue = value;
}
/**
*
* @return if this value is the return value of a method, give the method
* invoked
*/
public @CheckForNull XMethod getReturnValueOf() {
if (source instanceof XMethod) return (XMethod) source;
return null;
}
public boolean couldBeZero() {
return isCouldBeZero();
}
public boolean mustBeZero() {
Object value = getConstant();
return value instanceof Number && ((Number)value).intValue() == 0;
}
/**
* gets the detector specified value for this item
*
* @return the custom value
*/
public Object getUserValue() {
return userValue;
}
public boolean valueCouldBeNegative() {
return (getSpecialKind() == Item.RANDOM_INT
|| getSpecialKind() == Item.SIGNED_BYTE
|| getSpecialKind() == Item.HASHCODE_INT
|| getSpecialKind() == Item.RANDOM_INT_REMAINDER || getSpecialKind() == Item.HASHCODE_INT_REMAINDER);
}
/**
* @param isInitialParameter The isInitialParameter to set.
*/
private void setInitialParameter(boolean isInitialParameter) {
setFlag(isInitialParameter, IS_INITIAL_PARAMETER_FLAG);
}
/**
* @return Returns the isInitialParameter.
*/
public boolean isInitialParameter() {
return (flags & IS_INITIAL_PARAMETER_FLAG) != 0;
}
/**
* @param couldBeZero The couldBeZero to set.
*/
private void setCouldBeZero(boolean couldBeZero) {
setFlag(couldBeZero, COULD_BE_ZERO_FLAG);
}
/**
* @return Returns the couldBeZero.
*/
private boolean isCouldBeZero() {
return (flags & COULD_BE_ZERO_FLAG) != 0;
}
/**
* @param isNull The isNull to set.
*/
private void setNull(boolean isNull) {
setFlag(isNull, IS_NULL_FLAG);
}
private void setFlag(boolean value, int flagBit) {
if (value)
flags |= flagBit;
else
flags &= ~flagBit;
}
/**
* @return Returns the isNull.
*/
public boolean isNull() {
return (flags & IS_NULL_FLAG) != 0;
}
}
@Override
public String toString() {
if (isTop())
return "TOP";
return stack.toString() + "::" + lvValues.toString();
}
public OpcodeStack()
{
stack = new ArrayList<Item>();
lvValues = new ArrayList<Item>();
lastUpdate = new ArrayList<Integer>();
}
boolean needToMerge = true;
private boolean reachOnlyByBranch = false;
public static String getExceptionSig(DismantleBytecode dbc, CodeException e) {
if (e.getCatchType() == 0) return "Ljava/lang/Throwable;";
Constant c = dbc.getConstantPool().getConstant(e.getCatchType());
if (c instanceof ConstantClass)
return "L"+((ConstantClass)c).getBytes(dbc.getConstantPool())+";";
return "Ljava/lang/Throwable;";
}
public void mergeJumps(DismantleBytecode dbc) {
if (!needToMerge) return;
needToMerge = false;
boolean stackUpdated = false;
if (!isTop() && (convertJumpToOneZeroState == 3 || convertJumpToZeroOneState == 3)) {
pop();
Item top = new Item("I");
top.setCouldBeZero(true);
push(top);
convertJumpToOneZeroState = convertJumpToZeroOneState = 0;
stackUpdated = true;
}
List<Item> jumpEntry = null;
if (jumpEntryLocations.get(dbc.getPC()))
jumpEntry = jumpEntries.get(dbc.getPC());
if (jumpEntry != null) {
setReachOnlyByBranch(false);
List<Item> jumpStackEntry = jumpStackEntries.get(dbc.getPC());
if (DEBUG2) {
System.out.println("XXXXXXX " + isReachOnlyByBranch());
System.out.println("merging lvValues at jump target " + dbc.getPC() + " -> " + Integer.toString(System.identityHashCode(jumpEntry),16) + " " + jumpEntry);
System.out.println(" current lvValues " + lvValues);
System.out.println(" merging stack entry " + jumpStackEntry);
System.out.println(" current stack values " + stack);
}
if (isTop()) {
lvValues = new ArrayList<Item>(jumpEntry);
if (jumpStackEntry != null) stack = new ArrayList<Item>(jumpStackEntry);
else stack.clear();
setTop(false);
return;
}
if (isReachOnlyByBranch()) {
setTop(false);
lvValues = new ArrayList<Item>(jumpEntry);
if (!stackUpdated) {
if (jumpStackEntry != null) stack = new ArrayList<Item>(jumpStackEntry);
else stack.clear();
}
}
else {
setTop(false);
mergeLists(lvValues, jumpEntry, false);
if (!stackUpdated && jumpStackEntry != null) mergeLists(stack, jumpStackEntry, false);
}
if (DEBUG)
System.out.println(" merged lvValues " + lvValues);
}
else if (isReachOnlyByBranch() && !stackUpdated) {
stack.clear();
for(CodeException e : dbc.getCode().getExceptionTable()) {
if (e.getHandlerPC() == dbc.getPC()) {
push(new Item(getExceptionSig(dbc, e)));
setReachOnlyByBranch(false);
setTop(false);
return;
}
}
setTop(true);
}
}
int convertJumpToOneZeroState = 0;
int convertJumpToZeroOneState = 0;
private void setLastUpdate(int reg, int pc) {
while (lastUpdate.size() <= reg) lastUpdate.add(0);
lastUpdate.set(reg, pc);
}
public int getLastUpdate(int reg) {
if (lastUpdate.size() <= reg) return 0;
return lastUpdate.get(reg);
}
public int getNumLastUpdates() {
return lastUpdate.size();
}
public void sawOpcode(DismantleBytecode dbc, int seen) {
int register;
String signature;
Item it, it2, it3;
Constant cons;
if (dbc.isRegisterStore())
setLastUpdate(dbc.getRegisterOperand(), dbc.getPC());
mergeJumps(dbc);
needToMerge = true;
try
{
if (isTop()) {
return;
}
switch (seen) {
case ICONST_1:
convertJumpToOneZeroState = 1;
break;
case GOTO:
if (convertJumpToOneZeroState == 1 && dbc.getBranchOffset() == 4)
convertJumpToOneZeroState = 2;
else
convertJumpToOneZeroState = 0;
break;
case ICONST_0:
if (convertJumpToOneZeroState == 2)
convertJumpToOneZeroState = 3;
else convertJumpToOneZeroState = 0;
break;
default:convertJumpToOneZeroState = 0;
}
switch (seen) {
case ICONST_0:
convertJumpToZeroOneState = 1;
break;
case GOTO:
if (convertJumpToZeroOneState == 1 && dbc.getBranchOffset() == 4)
convertJumpToZeroOneState = 2;
else
convertJumpToZeroOneState = 0;
break;
case ICONST_1:
if (convertJumpToZeroOneState == 2)
convertJumpToZeroOneState = 3;
else convertJumpToZeroOneState = 0;
break;
default:convertJumpToZeroOneState = 0;
}
switch (seen) {
case ALOAD:
pushByLocalObjectLoad(dbc, dbc.getRegisterOperand());
break;
case ALOAD_0:
case ALOAD_1:
case ALOAD_2:
case ALOAD_3:
pushByLocalObjectLoad(dbc, seen - ALOAD_0);
break;
case DLOAD:
pushByLocalLoad("D", dbc.getRegisterOperand());
break;
case DLOAD_0:
case DLOAD_1:
case DLOAD_2:
case DLOAD_3:
pushByLocalLoad("D", seen - DLOAD_0);
break;
case FLOAD:
pushByLocalLoad("F", dbc.getRegisterOperand());
break;
case FLOAD_0:
case FLOAD_1:
case FLOAD_2:
case FLOAD_3:
pushByLocalLoad("F", seen - FLOAD_0);
break;
case ILOAD:
pushByLocalLoad("I", dbc.getRegisterOperand());
break;
case ILOAD_0:
case ILOAD_1:
case ILOAD_2:
case ILOAD_3:
pushByLocalLoad("I", seen - ILOAD_0);
break;
case LLOAD:
pushByLocalLoad("J", dbc.getRegisterOperand());
break;
case LLOAD_0:
case LLOAD_1:
case LLOAD_2:
case LLOAD_3:
pushByLocalLoad("J", seen - LLOAD_0);
break;
case GETSTATIC:
{
FieldAnnotation field = FieldAnnotation.fromReferencedField(dbc);
Item i = new Item(dbc.getSigConstantOperand(), field, Integer.MAX_VALUE);
if (field.getFieldName().equals("separator") && field.getClassName().equals("java.io.File")) {
i.setSpecialKind(Item.FILE_SEPARATOR_STRING);
}
push(i);
break;
}
case LDC:
case LDC_W:
case LDC2_W:
cons = dbc.getConstantRefOperand();
pushByConstant(dbc, cons);
break;
case INSTANCEOF:
pop();
push(new Item("I"));
break;
case IFEQ:
case IFNE:
case IFLT:
case IFLE:
case IFGT:
case IFGE:
case IFNONNULL:
case IFNULL:
seenTransferOfControl = true;
{
Item top = pop();
// if we see a test comparing a special negative value with 0,
// reset all other such values on the opcode stack
if (top.valueCouldBeNegative()
&& (seen == IFLT || seen == IFLE || seen == IFGT || seen == IFGE)) {
int specialKind = top.getSpecialKind();
for(Item item : stack) if (item != null && item.getSpecialKind() == specialKind) item.setSpecialKind(0);
for(Item item : lvValues) if (item != null && item.getSpecialKind() == specialKind) item.setSpecialKind(0);
}
}
addJumpValue(dbc.getBranchTarget());
break;
case LOOKUPSWITCH:
case TABLESWITCH:
seenTransferOfControl = true;
setReachOnlyByBranch(true);
pop();
addJumpValue(dbc.getBranchTarget());
int pc = dbc.getBranchTarget() - dbc.getBranchOffset();
for(int offset : dbc.getSwitchOffsets())
addJumpValue(offset+pc);
break;
case ARETURN:
case DRETURN:
case FRETURN:
case IRETURN:
case LRETURN:
seenTransferOfControl = true;
setReachOnlyByBranch(true);
pop();
break;
case MONITORENTER:
case MONITOREXIT:
case POP:
case PUTSTATIC:
pop();
break;
case IF_ACMPEQ:
case IF_ACMPNE:
case IF_ICMPEQ:
case IF_ICMPNE:
case IF_ICMPLT:
case IF_ICMPLE:
case IF_ICMPGT:
case IF_ICMPGE:
{
seenTransferOfControl = true;
pop(2);
int branchTarget = dbc.getBranchTarget();
addJumpValue(branchTarget);
break;
}
case POP2:
it = pop();
if (it.getSize() == 1) pop();
break;
case PUTFIELD:
pop(2);
break;
case IALOAD:
case SALOAD:
pop(2);
push(new Item("I"));
break;
case DUP:
handleDup();
break;
case DUP2:
handleDup2();
break;
case DUP_X1:
handleDupX1();
break;
case DUP_X2:
handleDupX2();
break;
case DUP2_X1:
handleDup2X1();
break;
case DUP2_X2:
handleDup2X2();
break;
case IINC:
register = dbc.getRegisterOperand();
it = getLVValue( register );
it2 = new Item("I", dbc.getIntConstant());
pushByIntMath( IADD, it2, it);
pushByLocalStore(register);
break;
case ATHROW:
pop();
seenTransferOfControl = true;
setReachOnlyByBranch(true);
setTop(true);
break;
case CHECKCAST:
{
String castTo = dbc.getClassConstantOperand();
if (castTo.charAt(0) != '[') castTo = "L" + castTo + ";";
it = new Item(pop());
it.signature = castTo;
push(it);
break;
}
case NOP:
break;
case RET:
case RETURN:
seenTransferOfControl = true;
setReachOnlyByBranch(true);
break;
case GOTO:
case GOTO_W:
seenTransferOfControl = true;
setReachOnlyByBranch(true);
addJumpValue(dbc.getBranchTarget());
stack.clear();
setTop(true);
break;
case SWAP:
handleSwap();
break;
case ICONST_M1:
case ICONST_0:
case ICONST_1:
case ICONST_2:
case ICONST_3:
case ICONST_4:
case ICONST_5:
push(new Item("I", (seen-ICONST_0)));
break;
case LCONST_0:
case LCONST_1:
push(new Item("J", (long)(seen-LCONST_0)));
break;
case DCONST_0:
case DCONST_1:
push(new Item("D", (double)(seen-DCONST_0)));
break;
case FCONST_0:
case FCONST_1:
case FCONST_2:
push(new Item("F", (float)(seen-FCONST_0)));
break;
case ACONST_NULL:
push(new Item());
break;
case ASTORE:
case DSTORE:
case FSTORE:
case ISTORE:
case LSTORE:
pushByLocalStore(dbc.getRegisterOperand());
break;
case ASTORE_0:
case ASTORE_1:
case ASTORE_2:
case ASTORE_3:
pushByLocalStore(seen - ASTORE_0);
break;
case DSTORE_0:
case DSTORE_1:
case DSTORE_2:
case DSTORE_3:
pushByLocalStore(seen - DSTORE_0);
break;
case FSTORE_0:
case FSTORE_1:
case FSTORE_2:
case FSTORE_3:
pushByLocalStore(seen - FSTORE_0);
break;
case ISTORE_0:
case ISTORE_1:
case ISTORE_2:
case ISTORE_3:
pushByLocalStore(seen - ISTORE_0);
break;
case LSTORE_0:
case LSTORE_1:
case LSTORE_2:
case LSTORE_3:
pushByLocalStore(seen - LSTORE_0);
break;
case GETFIELD:
{
Item item = pop();
int reg = item.getRegisterNumber();
push(new Item(dbc.getSigConstantOperand(),
FieldAnnotation.fromReferencedField(dbc), reg));
}
break;
case ARRAYLENGTH:
pop();
push(new Item("I"));
break;
case BALOAD:
{
pop(2);
Item v = new Item("I");
v.setSpecialKind(Item.SIGNED_BYTE);
push(v);
break;
}
case CALOAD:
pop(2);
push(new Item("I"));
break;
case DALOAD:
pop(2);
push(new Item("D"));
break;
case FALOAD:
pop(2);
push(new Item("F"));
break;
case LALOAD:
pop(2);
push(new Item("J"));
break;
case AASTORE:
case BASTORE:
case CASTORE:
case DASTORE:
case FASTORE:
case IASTORE:
case LASTORE:
case SASTORE:
pop(3);
break;
case BIPUSH:
case SIPUSH:
push(new Item("I", (Integer)dbc.getIntConstant()));
break;
case IADD:
case ISUB:
case IMUL:
case IDIV:
case IAND:
case IOR:
case IXOR:
case ISHL:
case ISHR:
case IREM:
case IUSHR:
it = pop();
it2 = pop();
pushByIntMath(seen, it2, it);
break;
case INEG:
it = pop();
if (it.getConstant() instanceof Integer) {
push(new Item("I", ( Integer)(-(Integer) it.getConstant())));
} else {
push(new Item("I"));
}
break;
case LNEG:
it = pop();
if (it.getConstant() instanceof Long) {
push(new Item("J", ( Long)(-(Long) it.getConstant())));
} else {
push(new Item("J"));
}
break;
case FNEG:
it = pop();
if (it.getConstant() instanceof Float) {
push(new Item("F", ( Float)(-(Float) it.getConstant())));
} else {
push(new Item("F"));
}
break;
case DNEG:
it = pop();
if (it.getConstant() instanceof Double) {
push(new Item("D", ( Double)(-(Double) it.getConstant())));
} else {
push(new Item("D"));
}
break;
case LADD:
case LSUB:
case LMUL:
case LDIV:
case LAND:
case LOR:
case LXOR:
case LSHL:
case LSHR:
case LREM:
case LUSHR:
it = pop();
it2 = pop();
pushByLongMath(seen, it2, it);
break;
case LCMP:
handleLcmp();
break;
case FCMPG:
case FCMPL: handleFcmp(seen);
break;
case DCMPG:
case DCMPL:
handleDcmp(seen);
break;
case FADD:
case FSUB:
case FMUL:
case FDIV:
case FREM:
it = pop();
it2 = pop();
pushByFloatMath(seen, it, it2);
break;
case DADD:
case DSUB:
case DMUL:
case DDIV:
case DREM:
it = pop();
it2 = pop();
pushByDoubleMath(seen, it, it2);
break;
case I2B:
it = pop();
if (it.getConstant() != null) {
it =new Item("I", (byte)constantToInt(it));
} else {
it = new Item("I");
}
it.setSpecialKind(Item.SIGNED_BYTE);
push(it);
break;
case I2C:
it = pop();
if (it.getConstant() != null) {
it = new Item("I", (char)constantToInt(it));
} else {
it = new Item("I");
}
it.setSpecialKind(Item.MASKED_NON_NEGATIVE);
push(it);
break;
case I2L:
case D2L:
case F2L:{
it = pop();
Item newValue;
if (it.getConstant() != null) {
newValue = new Item("J", constantToLong(it));
} else {
newValue = new Item("J");
}
newValue.setSpecialKind(it.getSpecialKind());
push(newValue);
}
break;
case I2S:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", (short)constantToInt(it)));
} else {
push(new Item("I"));
}
break;
case L2I:
case D2I:
case F2I:
it = pop();
if (it.getConstant() != null) {
push(new Item("I",constantToInt(it)));
} else {
push(new Item("I"));
}
break;
case L2F:
case D2F:
case I2F:
it = pop();
if (it.getConstant() != null) {
push(new Item("F", (Float)(constantToFloat(it))));
} else {
push(new Item("F"));
}
break;
case F2D:
case I2D:
case L2D:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", constantToDouble(it)));
} else {
push(new Item("D"));
}
break;
case NEW:
pushBySignature("L" + dbc.getClassConstantOperand() + ";");
break;
case NEWARRAY:
pop();
signature = "[" + BasicType.getType((byte)dbc.getIntConstant()).getSignature();
pushBySignature(signature);
break;
// According to the VM Spec 4.4.1, anewarray and multianewarray
// can refer to normal class/interface types (encoded in
// "internal form"), or array classes (encoded as signatures
// beginning with "[").
case ANEWARRAY:
pop();
signature = dbc.getClassConstantOperand();
if (!signature.startsWith("[")) {
signature = "[L" + signature + ";";
}
pushBySignature(signature);
break;
case MULTIANEWARRAY:
int dims = dbc.getIntConstant();
while ((dims
pop();
}
signature = dbc.getClassConstantOperand();
if (!signature.startsWith("[")) {
dims = dbc.getIntConstant();
signature = "";
while ((dims
signature += "[";
signature += "L" + signature + ";";
}
pushBySignature(signature);
break;
case AALOAD:
pop();
it = pop();
pushBySignature(it.getElementSignature());
break;
case JSR:
seenTransferOfControl = true;
setReachOnlyByBranch(false);
push(new Item("")); // push return address on stack
addJumpValue(dbc.getBranchTarget());
pop();
setTop(false);
break;
case INVOKEINTERFACE:
case INVOKESPECIAL:
case INVOKESTATIC:
case INVOKEVIRTUAL:
processMethodCall(dbc, seen);
break;
default:
throw new UnsupportedOperationException("OpCode " + OPCODE_NAMES[seen] + " not supported " );
}
}
catch (RuntimeException e) {
//If an error occurs, we clear the stack and locals. one of two things will occur.
//Either the client will expect more stack items than really exist, and so they're condition check will fail,
//or the stack will resync with the code. But hopefully not false positives
String msg = "Error procssing opcode " + OPCODE_NAMES[seen] + " @ " + dbc.getPC() + " in " + dbc.getFullyQualifiedMethodName();
AnalysisContext.logError(msg , e);
if (DEBUG)
e.printStackTrace();
clear();
}
finally {
if (DEBUG) {
System.out.println(dbc.getNextPC() + "pc : " + OPCODE_NAMES[seen] + " stack depth: " + getStackDepth());
System.out.println(this);
}
}
}
/**
* @param it
* @return
*/
private int constantToInt(Item it) {
return ((Number)it.getConstant()).intValue();
}
/**
* @param it
* @return
*/
private float constantToFloat(Item it) {
return ((Number)it.getConstant()).floatValue();
}
/**
* @param it
* @return
*/
private double constantToDouble(Item it) {
return ((Number)it.getConstant()).doubleValue();
}
/**
* @param it
* @return
*/
private long constantToLong(Item it) {
return ((Number)it.getConstant()).longValue();
}
/**
* @param opcode TODO
*
*/
private void handleDcmp(int opcode) {
Item it;
Item it2;
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
double d = (Double) it.getConstant();
double d2 = (Double) it.getConstant();
if (Double.isNaN(d) || Double.isNaN(d2)) {
if (opcode == DCMPG)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(-1)));
}
if (d2 < d)
push(new Item("I", (Integer) (-1) ));
else if (d2 > d)
push(new Item("I", (Integer)1));
else
push(new Item("I", (Integer)0));
} else {
push(new Item("I"));
}
}
/**
* @param opcode TODO
*
*/
private void handleFcmp(int opcode) {
Item it;
Item it2;
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
float f = (Float) it.getConstant();
float f2 = (Float) it.getConstant();
if (Float.isNaN(f) || Float.isNaN(f2)) {
if (opcode == FCMPG)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(-1)));
}
if (f2 < f)
push(new Item("I", (Integer)(-1)));
else if (f2 > f)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(0)));
} else {
push(new Item("I"));
}
}
private void handleLcmp() {
Item it;
Item it2;
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
long l = (Long) it.getConstant();
long l2 = (Long) it.getConstant();
if (l2 < l)
push(new Item("I", (Integer)(-1)));
else if (l2 > l)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(0)));
} else {
push(new Item("I"));
}
}
private void handleSwap() {
Item i1 = pop();
Item i2 = pop();
push(i1);
push(i2);
}
private void handleDup() {
Item it;
it = pop();
push(it);
push(it);
}
private void handleDupX1() {
Item it;
Item it2;
it = pop();
it2 = pop();
push(it);
push(it2);
push(it);
}
private void handleDup2() {
Item it, it2;
it = pop();
if (it.getSize() == 2) {
push(it);
push(it);
}
else {
it2 = pop();
push(it2);
push(it);
push(it2);
push(it);
}
}
private void handleDup2X1() {
String signature;
Item it;
Item it2;
Item it3;
it = pop();
it2 = pop();
signature = it.getSignature();
if (signature.equals("J") || signature.equals("D")) {
push(it);
push(it2);
push(it);
} else {
it3 = pop();
push(it2);
push(it);
push(it3);
push(it2);
push(it);
}
}
private void handleDup2X2() {
String signature;
Item it = pop();
Item it2 = pop();
if (it.isWide()) {
if (it2.isWide()) {
push(it);
push(it2);
push(it);
} else {
Item it3 = pop();
push(it);
push(it3);
push(it2);
push(it);
}
} else {
Item it3 = pop();
if (it3.isWide()) {
push(it2);
push(it);
push(it3);
push(it2);
push(it);
} else {
Item it4 = pop();
push(it2);
push(it);
push(it4);
push(it3);
push(it2);
push(it);
}
}
}
private void handleDupX2() {
String signature;
Item it;
Item it2;
Item it3;
it = pop();
it2 = pop();
signature = it2.getSignature();
if (signature.equals("J") || signature.equals("D")) {
push(it);
push(it2);
push(it);
} else {
it3 = pop();
push(it);
push(it3);
push(it2);
push(it);
}
}
private void processMethodCall(DismantleBytecode dbc, int seen) {
String clsName = dbc.getClassConstantOperand();
String methodName = dbc.getNameConstantOperand();
String signature = dbc.getSigConstantOperand();
String appenderValue = null;
Item sbItem = null;
//TODO: stack merging for trinaries kills the constant.. would be nice to maintain.
if ("java/lang/StringBuffer".equals(clsName)
|| "java/lang/StringBuilder".equals(clsName)) {
if ("<init>".equals(methodName)) {
if ("(Ljava/lang/String;)V".equals(signature)) {
Item i = getStackItem(0);
appenderValue = (String)i.getConstant();
} else if ("()V".equals(signature)) {
appenderValue = "";
}
} else if ("toString".equals(methodName) && getStackDepth() >= 1) {
Item i = getStackItem(0);
appenderValue = (String)i.getConstant();
} else if ("append".equals(methodName) && signature.indexOf("II)") == -1 && getStackDepth() >= 2) {
sbItem = getStackItem(1);
Item i = getStackItem(0);
Object sbVal = sbItem.getConstant();
Object sVal = i.getConstant();
if ((sbVal != null) && (sVal != null)) {
appenderValue = sbVal + sVal.toString();
} else if (sbItem.registerNumber >= 0) {
OpcodeStack.Item item = getLVValue(sbItem.registerNumber);
if (item != null)
item.constValue = null;
}
}
}
pushByInvoke(dbc, seen != INVOKESTATIC);
if (appenderValue != null && getStackDepth() > 0) {
Item i = this.getStackItem(0);
i.constValue = appenderValue;
if (sbItem != null) {
i.registerNumber = sbItem.registerNumber;
i.source = sbItem.source;
i.userValue = sbItem.userValue;
if (sbItem.registerNumber >= 0)
setLVValue(sbItem.registerNumber, i );
}
return;
}
if ((clsName.equals("java/util/Random") || clsName.equals("java/security/SecureRandom")) && methodName.equals("nextInt") && signature.equals("()I")) {
Item i = pop();
i.setSpecialKind(Item.RANDOM_INT);
i.source = XFactory.createReferencedXMethod(dbc);
push(i);
}
if (clsName.equals("java/lang/Math") && methodName.equals("abs")) {
Item i = pop();
i.setSpecialKind(Item.MATH_ABS);
i.source = XFactory.createReferencedXMethod(dbc);
push(i);
}
else if (seen == INVOKEVIRTUAL && methodName.equals("hashCode") && signature.equals("()I")
|| seen == INVOKESTATIC && clsName.equals("java/lang/System") && methodName.equals("identityHashCode") && signature.equals("(Ljava/lang/Object;)I")) {
Item i = pop();
i.setSpecialKind(Item.HASHCODE_INT);
i.source = XFactory.createReferencedXMethod(dbc);
push(i);
} else if (!signature.endsWith(")V")) {
Item i = pop();
i.source = XFactory.createReferencedXMethod(dbc);
push(i);
}
}
private void mergeLists(List<Item> mergeInto, List<Item> mergeFrom, boolean errorIfSizesDoNotMatch) {
// merge stacks
int intoSize = mergeInto.size();
int fromSize = mergeFrom.size();
if (errorIfSizesDoNotMatch && intoSize != fromSize) {
if (DEBUG2) {
System.out.println("Bad merging items");
System.out.println("current items: " + mergeInto);
System.out.println("jump items: " + mergeFrom);
}
} else {
if (DEBUG2) {
if (intoSize == fromSize)
System.out.println("Merging items");
else
System.out.println("Bad merging items");
System.out.println("current items: " + mergeInto);
System.out.println("jump items: " + mergeFrom);
}
for (int i = 0; i < Math.min(intoSize, fromSize); i++)
mergeInto.set(i, Item.merge(mergeInto.get(i), mergeFrom.get(i)));
if (DEBUG2) {
System.out.println("merged items: " + mergeInto);
}
}
}
public void clear() {
stack.clear();
lvValues.clear();
}
BitSet exceptionHandlers = new BitSet();
private Map<Integer, List<Item>> jumpEntries = new HashMap<Integer, List<Item>>();
private Map<Integer, List<Item>> jumpStackEntries = new HashMap<Integer, List<Item>>();
private BitSet jumpEntryLocations = new BitSet();
private void addJumpValue(int target) {
if (DEBUG)
System.out.println("Set jump entry at " + methodName + ":" + target + "pc to " + stack + " : " + lvValues );
List<Item> atTarget = jumpEntries.get(target);
if (atTarget == null) {
if (DEBUG)
System.out.println("Was null");
jumpEntries.put(target, new ArrayList<Item>(lvValues));
jumpEntryLocations.set(target);
if (stack.size() > 0) {
jumpStackEntries.put(target, new ArrayList<Item>(stack));
}
return;
}
mergeLists(atTarget, lvValues, false);
List<Item> stackAtTarget = jumpStackEntries.get(target);
if (stack.size() > 0 && stackAtTarget != null)
mergeLists(stackAtTarget, stack, false);
if (DEBUG)
System.out.println("merge target for " + methodName + ":" + target + "pc is " + atTarget);
}
private String methodName;
DismantleBytecode v;
public int resetForMethodEntry(final DismantleBytecode v) {
this.v = v;
methodName = v.getMethodName();
setTop(false);
jumpEntries.clear();
jumpStackEntries.clear();
jumpEntryLocations.clear();
lastUpdate.clear();
convertJumpToOneZeroState = convertJumpToZeroOneState = 0;
setReachOnlyByBranch(false);
int result= resetForMethodEntry0(v);
Code code = v.getMethod().getCode();
if (code == null) return result;
if (useIterativeAnalysis) {
// FIXME: Be clever
if (DEBUG)
System.out.println(" --- Iterative analysis");
DismantleBytecode branchAnalysis = new DismantleBytecode() {
@Override
public void sawOpcode(int seen) {
OpcodeStack.this.sawOpcode(this, seen);
}
// perhaps we don't need this
// @Override
// public void sawBranchTo(int pc) {
// addJumpValue(pc);
};
branchAnalysis.setupVisitorForClass(v.getThisClass());
branchAnalysis.doVisitMethod(v.getMethod());
if (!jumpEntries.isEmpty()) {
int count = jumpEntries.size();
while (true) {
resetForMethodEntry0(v);
if (DEBUG) {
System.out.println("Found dataflow for jumps in " + v.getMethodName());
for (Integer pc : jumpEntries.keySet()) {
List<Item> list = jumpEntries.get(pc);
System.out.println(pc + " -> " + Integer.toString(System.identityHashCode(list),16) + " " + list);
}
}
branchAnalysis.doVisitMethod(v.getMethod());
int count2 = jumpEntries.size();
if (count2 <= count) break;
count = count2;
}
}
if (DEBUG && !jumpEntries.isEmpty()) {
System.out.println("Found dataflow for jumps in " + v.getMethodName());
for (Integer pc : jumpEntries.keySet()) {
List<Item> list = jumpEntries.get(pc);
System.out.println(pc + " -> " + Integer.toString(System.identityHashCode(list),16) + " " + list);
}
}
resetForMethodEntry0(v);
if (DEBUG)
System.out.println(" --- End of Iterative analysis");
}
return result;
}
private int resetForMethodEntry0(PreorderVisitor v) {
if (DEBUG) System.out.println("
stack.clear();
lvValues.clear();
top = false;
setReachOnlyByBranch(false);
seenTransferOfControl = false;
String className = v.getClassName();
String signature = v.getMethodSig();
exceptionHandlers.clear();
Method m = v.getMethod();
Code code = m.getCode();
if (code != null)
{
CodeException[] exceptionTable = code.getExceptionTable();
if (exceptionTable != null)
for(CodeException ex : exceptionTable)
exceptionHandlers.set(ex.getHandlerPC());
}
if (DEBUG) System.out.println(" --- " + className
+ " " + m.getName() + " " + signature);
Type[] argTypes = Type.getArgumentTypes(signature);
int reg = 0;
if (!m.isStatic()) {
Item it = new Item("L" + className+";");
it.setInitialParameter(true);
it.registerNumber = reg;
setLVValue( reg, it);
reg += it.getSize();
}
for (Type argType : argTypes) {
Item it = new Item(argType.getSignature());
it.registerNumber = reg;
it.setInitialParameter(true);
setLVValue(reg, it);
reg += it.getSize();
}
return reg;
}
public int getStackDepth() {
return stack.size();
}
public Item getStackItem(int stackOffset) {
if (stackOffset < 0 || stackOffset >= stack.size()) {
AnalysisContext.logError("Can't get stack offset " + stackOffset
+ " from " + stack.toString() +" @ " + v.getPC() + " in "
+ v.getFullyQualifiedMethodName(), new IllegalArgumentException());
return new Item("Lfindbugs/OpcodeStackError;");
}
int tos = stack.size() - 1;
int pos = tos - stackOffset;
try {
return stack.get(pos);
} catch (ArrayIndexOutOfBoundsException e) {
throw new ArrayIndexOutOfBoundsException(
"Requested item at offset " + stackOffset + " in a stack of size " + stack.size()
+", made request for position " + pos);
}
}
private Item pop() {
return stack.remove(stack.size()-1);
}
private void pop(int count)
{
while ((count
pop();
}
private void push(Item i) {
stack.add(i);
}
private void pushByConstant(DismantleBytecode dbc, Constant c) {
if (c instanceof ConstantClass)
push(new Item("Ljava/lang/Class;", ((ConstantClass)c).getConstantValue(dbc.getConstantPool())));
else if (c instanceof ConstantInteger)
push(new Item("I", (Integer)(((ConstantInteger) c).getBytes())));
else if (c instanceof ConstantString) {
int s = ((ConstantString) c).getStringIndex();
push(new Item("Ljava/lang/String;", getStringFromIndex(dbc, s)));
}
else if (c instanceof ConstantFloat)
push(new Item("F", (Float)(((ConstantFloat) c).getBytes())));
else if (c instanceof ConstantDouble)
push(new Item("D", (Double)(((ConstantDouble) c).getBytes())));
else if (c instanceof ConstantLong)
push(new Item("J", (Long)(((ConstantLong) c).getBytes())));
else
throw new UnsupportedOperationException("Constant type not expected" );
}
private void pushByLocalObjectLoad(DismantleBytecode dbc, int register) {
Method m = dbc.getMethod();
LocalVariableTable lvt = m.getLocalVariableTable();
if (lvt != null) {
LocalVariable lv = LVTHelper.getLocalVariableAtPC(lvt, register, dbc.getPC());
if (lv != null) {
String signature = lv.getSignature();
pushByLocalLoad(signature, register);
return;
}
}
pushByLocalLoad("", register);
}
private void pushByIntMath(int seen, Item lhs, Item rhs) {
if (DEBUG) System.out.println("pushByIntMath: " + rhs.getConstant() + " " + lhs.getConstant() );
Item newValue = new Item("I");
try {
if ((rhs.getConstant() != null) && lhs.getConstant() != null) {
Integer lhsValue = (Integer) lhs.getConstant();
Integer rhsValue = (Integer) rhs.getConstant();
if (seen == IADD)
newValue = new Item("I",lhsValue + rhsValue);
else if (seen == ISUB)
newValue = new Item("I",lhsValue - rhsValue);
else if (seen == IMUL)
newValue = new Item("I", lhsValue * rhsValue);
else if (seen == IDIV)
newValue = new Item("I", lhsValue / rhsValue);
else if (seen == IAND) {
newValue = new Item("I", lhsValue & rhsValue);
if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 )
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
} else if (seen == IOR)
newValue = new Item("I",lhsValue | rhsValue);
else if (seen == IXOR)
newValue = new Item("I",lhsValue ^ rhsValue);
else if (seen == ISHL) {
newValue = new Item("I",lhsValue << rhsValue);
if (rhsValue >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR;
}
else if (seen == ISHR)
newValue = new Item("I",lhsValue >> rhsValue);
else if (seen == IREM)
newValue = new Item("I", lhsValue % rhsValue);
else if (seen == IUSHR)
newValue = new Item("I", lhsValue >>> rhsValue);
} else if (rhs.getConstant() != null && seen == ISHL && (Integer) rhs.getConstant() >= 8)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (lhs.getConstant() != null && seen == IAND) {
int value = (Integer) lhs.getConstant();
if (value == 0)
newValue = new Item("I", 0);
else if ((value & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (value >= 0)
newValue.specialKind = Item.MASKED_NON_NEGATIVE;
} else if (rhs.getConstant() != null && seen == IAND) {
int value = (Integer) rhs.getConstant();
if (value == 0)
newValue = new Item("I", 0);
else if ((value & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (value >= 0)
newValue.specialKind = Item.MASKED_NON_NEGATIVE;
}
} catch (RuntimeException e) {
// ignore it
}
if (lhs.specialKind == Item.INTEGER_SUM && rhs.getConstant() != null ) {
int rhsValue = (Integer) rhs.getConstant();
if (seen == IDIV && rhsValue ==2 || seen == ISHR && rhsValue == 1)
newValue.specialKind = Item.AVERAGE_COMPUTED_USING_DIVISION;
}
if (seen == IADD && newValue.specialKind == 0 && lhs.getConstant() == null && rhs.getConstant() == null )
newValue.specialKind = Item.INTEGER_SUM;
if (seen == IREM && lhs.specialKind == Item.HASHCODE_INT)
newValue.specialKind = Item.HASHCODE_INT_REMAINDER;
if (seen == IREM && lhs.specialKind == Item.RANDOM_INT)
newValue.specialKind = Item.RANDOM_INT_REMAINDER;
if (DEBUG) System.out.println("push: " + newValue);
push(newValue);
}
private void pushByLongMath(int seen, Item lhs, Item rhs) {
Item newValue = new Item("J");
try {
if ((rhs.getConstant() != null) && lhs.getConstant() != null) {
Long lhsValue = ((Long) lhs.getConstant());
if (seen == LSHL) {
newValue =new Item("J", lhsValue << ((Number) rhs.getConstant()).intValue());
if (((Number) rhs.getConstant()).intValue() >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR;
}
else if (seen == LSHR)
newValue =new Item("J", lhsValue >> ((Number) rhs.getConstant()).intValue());
else if (seen == LUSHR)
newValue =new Item("J", lhsValue >>> ((Number) rhs.getConstant()).intValue());
else {
Long rhsValue = ((Long) rhs.getConstant());
if (seen == LADD)
newValue = new Item("J", lhsValue + rhsValue);
else if (seen == LSUB)
newValue = new Item("J", lhsValue - rhsValue);
else if (seen == LMUL)
newValue = new Item("J", lhsValue * rhsValue);
else if (seen == LDIV)
newValue =new Item("J", lhsValue / rhsValue);
else if (seen == LAND) {
newValue = new Item("J", lhsValue & rhsValue);
if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 )
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
}
else if (seen == LOR)
newValue = new Item("J", lhsValue | rhsValue);
else if (seen == LXOR)
newValue =new Item("J", lhsValue ^ rhsValue);
else if (seen == LREM)
newValue =new Item("J", lhsValue % rhsValue);
}
}
else if (rhs.getConstant() != null && seen == LSHL && ((Integer) rhs.getConstant()) >= 8)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (lhs.getConstant() != null && seen == LAND && (((Long) lhs.getConstant()) & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (rhs.getConstant() != null && seen == LAND && (((Long) rhs.getConstant()) & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
} catch (RuntimeException e) {
// ignore it
}
push(newValue);
}
private void pushByFloatMath(int seen, Item it, Item it2) {
Item result;
int specialKind = Item.FLOAT_MATH;
if ((it.getConstant() instanceof Float) && it2.getConstant() instanceof Float) {
if (seen == FADD)
result =new Item("F", ((Float) it2.getConstant()) + ((Float) it.getConstant()));
else if (seen == FSUB)
result =new Item("F", ((Float) it2.getConstant()) - ((Float) it.getConstant()));
else if (seen == FMUL)
result =new Item("F", ((Float) it2.getConstant()) * ((Float) it.getConstant()));
else if (seen == FDIV)
result =new Item("F", ((Float) it2.getConstant()) / ((Float) it.getConstant()));
else if (seen == FREM)
result =new Item("F", ((Float) it2.getConstant()) % ((Float) it.getConstant()));
else result =new Item("F");
} else {
result =new Item("F");
if (seen == DDIV)
specialKind = Item.NASTY_FLOAT_MATH;
}
result.setSpecialKind(specialKind);
push(result);
}
private void pushByDoubleMath(int seen, Item it, Item it2) {
Item result;
int specialKind = Item.FLOAT_MATH;
if ((it.getConstant() instanceof Double) && it2.getConstant() instanceof Double) {
if (seen == DADD)
result = new Item("D", ((Double) it2.getConstant()) + ((Double) it.getConstant()));
else if (seen == DSUB)
result = new Item("D", ((Double) it2.getConstant()) - ((Double) it.getConstant()));
else if (seen == DMUL)
result = new Item("D", ((Double) it2.getConstant()) * ((Double) it.getConstant()));
else if (seen == DDIV)
result = new Item("D", ((Double) it2.getConstant()) / ((Double) it.getConstant()));
else if (seen == DREM)
result = new Item("D", ((Double) it2.getConstant()) % ((Double) it.getConstant()));
else
result = new Item("D");
} else {
result = new Item("D");
if (seen == DDIV)
specialKind = Item.NASTY_FLOAT_MATH;
}
result.setSpecialKind(specialKind);
push(result);
}
private void pushByInvoke(DismantleBytecode dbc, boolean popThis) {
String signature = dbc.getSigConstantOperand();
pop(PreorderVisitor.getNumberArguments(signature)+(popThis ? 1 : 0));
pushBySignature(Type.getReturnType(signature).getSignature());
}
private String getStringFromIndex(DismantleBytecode dbc, int i) {
ConstantUtf8 name = (ConstantUtf8) dbc.getConstantPool().getConstant(i);
return name.getBytes();
}
private void pushBySignature(String s) {
if ("V".equals(s))
return;
push(new Item(s, (Object) null));
}
private void pushByLocalStore(int register) {
Item it = pop();
if (it.getRegisterNumber() != register) {
for(Item i : lvValues) if (i != null) {
if (i.registerNumber == register) i.registerNumber = -1;
if (i.fieldLoadedFromRegister == register) i.fieldLoadedFromRegister = -1;
}
for(Item i : stack) if (i != null) {
if (i.registerNumber == register) i.registerNumber = -1;
if (i.fieldLoadedFromRegister == register) i.fieldLoadedFromRegister = -1;
}
}
setLVValue( register, it );
}
private void pushByLocalLoad(String signature, int register) {
Item it = getLVValue(register);
if (it == null) {
Item item = new Item(signature);
item.registerNumber = register;
push(item);
}
else if (it.getRegisterNumber() >= 0)
push(it);
else {
push(new Item(it, register));
}
}
private void setLVValue(int index, Item value ) {
int addCount = index - lvValues.size() + 1;
while ((addCount
lvValues.add(null);
if (!useIterativeAnalysis && seenTransferOfControl)
value = Item.merge(value, lvValues.get(index) );
lvValues.set(index, value);
}
private Item getLVValue(int index) {
if (index >= lvValues.size())
return null;
return lvValues.get(index);
}
/**
* @param top The top to set.
*/
private void setTop(boolean top) {
if (top) {
if (!this.top)
this.top = true;
} else if (this.top)
this.top = false;
}
/**
* @return Returns the top.
*/
private boolean isTop() {
if (top)
return true;
return false;
}
/**
* @param reachOnlyByBranch The reachOnlyByBranch to set.
*/
void setReachOnlyByBranch(boolean reachOnlyByBranch) {
if (reachOnlyByBranch)
setTop(true);
this.reachOnlyByBranch = reachOnlyByBranch;
}
/**
* @return Returns the reachOnlyByBranch.
*/
boolean isReachOnlyByBranch() {
return reachOnlyByBranch;
}
}
// vim:ts=4 |
package edu.umd.cs.findbugs;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.CodeException;
import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantClass;
import org.apache.bcel.classfile.ConstantDouble;
import org.apache.bcel.classfile.ConstantFloat;
import org.apache.bcel.classfile.ConstantInteger;
import org.apache.bcel.classfile.ConstantLong;
import org.apache.bcel.classfile.ConstantString;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.LocalVariable;
import org.apache.bcel.classfile.LocalVariableTable;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.BasicType;
import org.apache.bcel.generic.Type;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.AnalysisFeatures;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.visitclass.Constants2;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
import edu.umd.cs.findbugs.visitclass.LVTHelper;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;
/**
* tracks the types and numbers of objects that are currently on the operand stack
* throughout the execution of method. To use, a detector should instantiate one for
* each method, and call <p>stack.sawOpcode(this,seen);</p> at the bottom of their sawOpcode method.
* at any point you can then inspect the stack and see what the types of objects are on
* the stack, including constant values if they were pushed. The types described are of
* course, only the static types.
* There are some outstanding opcodes that have yet to be implemented, I couldn't
* find any code that actually generated these, so i didn't put them in because
* I couldn't test them:
* <ul>
* <li>dup2_x2</li>
* <li>jsr_w</li>
* <li>wide</li>
* </ul>
*/
public class OpcodeStack implements Constants2
{
private static final boolean DEBUG
= SystemProperties.getBoolean("ocstack.debug");
private List<Item> stack;
private List<Item> lvValues;
private List<Integer> lastUpdate;
private int jumpTarget;
private Stack<List<Item>> jumpStack;
private boolean seenTransferOfControl = false;
private boolean useIterativeAnalysis
= AnalysisContext.currentAnalysisContext().getBoolProperty(AnalysisFeatures.INTERATIVE_OPCODE_STACK_ANALYSIS);
public static class Item
{
public static final int SIGNED_BYTE = 1;
public static final int RANDOM_INT = 2;
public static final int LOW_8_BITS_CLEAR = 3;
public static final int HASHCODE_INT = 4;
public static final int INTEGER_SUM = 5;
public static final int AVERAGE_COMPUTED_USING_DIVISION = 6;
public static final int FLOAT_MATH = 7;
public static final int RANDOM_INT_REMAINDER = 8;
public static final int HASHCODE_INT_REMAINDER = 9;
public static final int FILE_SEPARATOR_STRING = 10;
public static final Object UNKNOWN = null;
private int specialKind;
private String signature;
private Object constValue = UNKNOWN;
private FieldAnnotation field;
private XField xfield;
private boolean isNull = false;
private int registerNumber = -1;
private boolean isInitialParameter = false;
private boolean couldBeZero = false;
private Object userValue = null;
public int getSize() {
if (signature.equals("J") || signature.equals("D")) return 2;
return 1;
}
private static boolean equals(Object o1, Object o2) {
if (o1 == o2) return true;
if (o1 == null || o2 == null) return false;
return o1.equals(o2);
}
@Override
public int hashCode() {
int r = 42 + specialKind;
if (signature != null)
r+= signature.hashCode();
r *= 31;
if (constValue != null)
r+= constValue.hashCode();
r *= 31;
if (field != null)
r+= field.hashCode();
r *= 31;
if (isInitialParameter)
r += 17;
r += registerNumber;
return r;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Item)) return false;
Item that = (Item) o;
return equals(this.signature, that.signature)
&& equals(this.constValue, that.constValue)
&& equals(this.field, that.field)
&& this.isNull == that.isNull
&& this.specialKind == that.specialKind
&& this.registerNumber == that.registerNumber
&& this.isInitialParameter == that.isInitialParameter
&& this.couldBeZero == that.couldBeZero
&& this.userValue == that.userValue;
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer("< ");
buf.append(signature);
switch(specialKind) {
case SIGNED_BYTE:
buf.append(", byte_array_load");
break;
case RANDOM_INT:
buf.append(", random_int");
break;
case LOW_8_BITS_CLEAR:
buf.append(", low8clear");
break;
case HASHCODE_INT:
buf.append(", hashcode_int");
break;
case INTEGER_SUM:
buf.append(", int_sum");
break;
case AVERAGE_COMPUTED_USING_DIVISION:
buf.append(", averageComputingUsingDivision");
break;
case FLOAT_MATH:
buf.append(", floatMath");
break;
case HASHCODE_INT_REMAINDER:
buf.append(", hashcode_int_rem");
break;
case RANDOM_INT_REMAINDER:
buf.append(", random_int_rem");
break;
case FILE_SEPARATOR_STRING:
buf.append(", file_separator_string");
break;
case 0 :
break;
default:
buf.append(", #" + specialKind);
break;
}
if (constValue != UNKNOWN) {
buf.append(", ");
buf.append(constValue);
}
if (xfield!= UNKNOWN) {
buf.append(", ");
buf.append(xfield);
}
if (isInitialParameter) {
buf.append(", IP");
}
if (isNull) {
buf.append(", isNull");
}
if (registerNumber != -1) {
buf.append(", r");
buf.append(registerNumber);
}
if (couldBeZero) buf.append(", cbz");
buf.append(" >");
return buf.toString();
}
public static Item merge(Item i1, Item i2) {
if (i1 == null) return i2;
if (i2 == null) return i1;
if (i1.equals(i2)) return i1;
Item m = new Item();
m.isNull = false;
m.couldBeZero = i1.couldBeZero || i2.couldBeZero;
if (equals(i1.signature,i2.signature))
m.signature = i1.signature;
if (equals(i1.constValue,i2.constValue))
m.constValue = i1.constValue;
if (equals(i1.xfield,i2.xfield)) {
m.field = i1.field;
m.xfield = i1.xfield;
}
if (i1.isNull == i2.isNull)
m.isNull = i1.isNull;
if (i1.registerNumber == i2.registerNumber)
m.registerNumber = i1.registerNumber;
if (i1.specialKind == i2.specialKind)
m.specialKind = i1.specialKind;
else if (i1.specialKind == FLOAT_MATH || i2.specialKind == FLOAT_MATH)
m.specialKind = FLOAT_MATH;
if (DEBUG) System.out.println("Merge " + i1 + " and " + i2 + " gives " + m);
return m;
}
public Item(String signature, int constValue) {
this(signature, (Object)(Integer)constValue);
}
public Item(String signature) {
this(signature, UNKNOWN);
}
public Item(String signature, FieldAnnotation f, int reg) {
this.signature = signature;
field = f;
if (f != null)
xfield = XFactory.createXField(f);
registerNumber = reg;
}
public Item(Item it) {
this.signature = it.signature;
this.constValue = it.constValue;
this.field = it.field;
this.xfield = it.xfield;
this.isNull = it.isNull;
this.registerNumber = it.registerNumber;
this.couldBeZero = it.couldBeZero;
this.userValue = it.userValue;
this.isInitialParameter = it.isInitialParameter;
this.specialKind = it.specialKind;
}
public Item(Item it, int reg) {
this.signature = it.signature;
this.constValue = it.constValue;
this.field = it.field;
this.isNull = it.isNull;
this.registerNumber = reg;
this.couldBeZero = it.couldBeZero;
this.userValue = it.userValue;
this.isInitialParameter = it.isInitialParameter;
this.specialKind = it.specialKind;
}
public Item(String signature, FieldAnnotation f) {
this(signature, f, -1);
}
public Item(String signature, Object constantValue) {
this.signature = signature;
constValue = constantValue;
if (constantValue instanceof Integer) {
int value = (Integer) constantValue;
if (value != 0 && (value & 0xff) == 0)
specialKind = LOW_8_BITS_CLEAR;
if (value == 0) couldBeZero = true;
}
else if (constantValue instanceof Long) {
long value = (Long) constantValue;
if (value != 0 && (value & 0xff) == 0)
specialKind = LOW_8_BITS_CLEAR;
if (value == 0) couldBeZero = true;
}
}
public Item() {
signature = "Ljava/lang/Object;";
constValue = null;
isNull = true;
}
public JavaClass getJavaClass() throws ClassNotFoundException {
String baseSig;
if (isPrimitive())
return null;
if (isArray()) {
baseSig = getElementSignature();
} else {
baseSig = signature;
}
if (baseSig.length() == 0)
return null;
baseSig = baseSig.substring(1, baseSig.length() - 1);
baseSig = baseSig.replace('/', '.');
return Repository.lookupClass(baseSig);
}
public boolean isArray() {
return signature.startsWith("[");
}
public boolean isInitialParameter() {
return isInitialParameter;
}
public String getElementSignature() {
if (!isArray())
return signature;
else {
int pos = 0;
int len = signature.length();
while (pos < len) {
if (signature.charAt(pos) != '[')
break;
pos++;
}
return signature.substring(pos);
}
}
public boolean isPrimitive() {
return !signature.startsWith("L");
}
public int getRegisterNumber() {
return registerNumber;
}
public String getSignature() {
return signature;
}
public boolean isNull() {
return isNull;
}
public Object getConstant() {
return constValue;
}
public FieldAnnotation getField() {
return field;
}
public XField getXField() {
return xfield;
}
/**
* @param specialKind The specialKind to set.
*/
public void setSpecialKind(int specialKind) {
this.specialKind = specialKind;
}
/**
* @return Returns the specialKind.
*/
public int getSpecialKind() {
return specialKind;
}
/**
* attaches a detector specified value to this item
*
* @param value the custom value to set
*/
public void setUserValue(Object value) {
userValue = value;
}
public boolean couldBeZero() {
return couldBeZero;
}
public boolean mustBeZero() {
Object value = getConstant();
return value instanceof Number && ((Number)value).intValue() == 0;
}
/**
* gets the detector specified value for this item
*
* @return the custom value
*/
public Object getUserValue() {
return userValue;
}
public boolean valueCouldBeNegative() {
return (getSpecialKind() == Item.RANDOM_INT
|| getSpecialKind() == Item.SIGNED_BYTE
|| getSpecialKind() == Item.HASHCODE_INT
|| getSpecialKind() == Item.RANDOM_INT_REMAINDER || getSpecialKind() == Item.HASHCODE_INT_REMAINDER);
}
}
@Override
public String toString() {
return stack.toString() + "::" + lvValues.toString();
}
public OpcodeStack()
{
stack = new ArrayList<Item>();
lvValues = new ArrayList<Item>();
jumpStack = new Stack<List<Item>>();
lastUpdate = new ArrayList<Integer>();
}
boolean needToMerge = true;
boolean reachOnlyByBranch = false;
public void mergeJumps(DismantleBytecode dbc) {
if (!needToMerge) return;
needToMerge = false;
if (convertJumpToOneZeroState == 3 || convertJumpToZeroOneState == 3) {
pop();
Item top = new Item("I");
top.couldBeZero = true;
push(top);
convertJumpToOneZeroState = convertJumpToZeroOneState = 0;
}
List<Item> jumpEntry = jumpEntries.get(dbc.getPC());
if (jumpEntry != null) {
if (DEBUG) {
System.out.println("XXXXXXX " + reachOnlyByBranch);
System.out.println("merging lvValues at jump target " + dbc.getPC() + " -> " + Integer.toString(System.identityHashCode(jumpEntry),16) + " " + jumpEntry);
System.out.println(" current lvValues " + lvValues);
}
if (reachOnlyByBranch) lvValues = new ArrayList<Item>(jumpEntry);
else mergeLists(lvValues, jumpEntry, false);
if (DEBUG)
System.out.println(" merged lvValues " + lvValues);
}
else if (dbc.getPC() == jumpTarget) {
jumpTarget = -1;
if (!jumpStack.empty()) {
List<Item> stackToMerge = jumpStack.pop();
if (DEBUG) {
System.out.println("************");
System.out.println("merging stacks at " + dbc.getPC() + " -> " + stackToMerge);
System.out.println(" current stack " + stack);
}
if (reachOnlyByBranch) lvValues = new ArrayList<Item>(stackToMerge);
else mergeLists(stack, stackToMerge, true);
if (DEBUG)
System.out.println(" updated stack " + stack);
} }
reachOnlyByBranch = false;
}
int convertJumpToOneZeroState = 0;
int convertJumpToZeroOneState = 0;
private void setLastUpdate(int reg, int pc) {
while (lastUpdate.size() <= reg) lastUpdate.add(0);
lastUpdate.set(reg, pc);
}
public int getLastUpdate(int reg) {
if (lastUpdate.size() <= reg) return 0;
return lastUpdate.get(reg);
}
public int getNumLastUpdates() {
return lastUpdate.size();
}
public void sawOpcode(DismantleBytecode dbc, int seen) {
int register;
String signature;
Item it, it2, it3;
Constant cons;
if (dbc.isRegisterStore())
setLastUpdate(dbc.getRegisterOperand(), dbc.getPC());
mergeJumps(dbc);
needToMerge = true;
switch (seen) {
case ICONST_1:
convertJumpToOneZeroState = 1;
break;
case GOTO:
if (convertJumpToOneZeroState == 1 && dbc.getBranchOffset() == 4)
convertJumpToOneZeroState = 2;
else
convertJumpToOneZeroState = 0;
break;
case ICONST_0:
if (convertJumpToOneZeroState == 2)
convertJumpToOneZeroState = 3;
else convertJumpToOneZeroState = 0;
break;
default:convertJumpToOneZeroState = 0;
}
switch (seen) {
case ICONST_0:
convertJumpToZeroOneState = 1;
break;
case GOTO:
if (convertJumpToZeroOneState == 1 && dbc.getBranchOffset() == 4)
convertJumpToZeroOneState = 2;
else
convertJumpToZeroOneState = 0;
break;
case ICONST_1:
if (convertJumpToZeroOneState == 2)
convertJumpToZeroOneState = 3;
else convertJumpToZeroOneState = 0;
break;
default:convertJumpToZeroOneState = 0;
}
try
{
switch (seen) {
case ALOAD:
pushByLocalObjectLoad(dbc, dbc.getRegisterOperand());
break;
case ALOAD_0:
case ALOAD_1:
case ALOAD_2:
case ALOAD_3:
pushByLocalObjectLoad(dbc, seen - ALOAD_0);
break;
case DLOAD:
pushByLocalLoad("D", dbc.getRegisterOperand());
break;
case DLOAD_0:
case DLOAD_1:
case DLOAD_2:
case DLOAD_3:
pushByLocalLoad("D", seen - DLOAD_0);
break;
case FLOAD:
pushByLocalLoad("F", dbc.getRegisterOperand());
break;
case FLOAD_0:
case FLOAD_1:
case FLOAD_2:
case FLOAD_3:
pushByLocalLoad("F", seen - FLOAD_0);
break;
case ILOAD:
pushByLocalLoad("I", dbc.getRegisterOperand());
break;
case ILOAD_0:
case ILOAD_1:
case ILOAD_2:
case ILOAD_3:
pushByLocalLoad("I", seen - ILOAD_0);
break;
case LLOAD:
pushByLocalLoad("J", dbc.getRegisterOperand());
break;
case LLOAD_0:
case LLOAD_1:
case LLOAD_2:
case LLOAD_3:
pushByLocalLoad("J", seen - LLOAD_0);
break;
case GETSTATIC:
{
FieldAnnotation field = FieldAnnotation.fromReferencedField(dbc);
Item i = new Item(dbc.getSigConstantOperand(), field);
if (field.getFieldName().equals("separator") && field.getClassName().equals("java.io.File"))
i.setSpecialKind(Item.FILE_SEPARATOR_STRING);
push(i);
break;
}
case LDC:
case LDC_W:
case LDC2_W:
cons = dbc.getConstantRefOperand();
pushByConstant(dbc, cons);
break;
case INSTANCEOF:
pop();
push(new Item("I"));
break;
case IFEQ:
case IFNE:
case IFLT:
case IFLE:
case IFGT:
case IFGE:
case IFNONNULL:
case IFNULL:
seenTransferOfControl = true;
{
Item top = pop();
// if we see a test comparing a special negative value with 0,
// reset all other such values on the opcode stack
if (top.valueCouldBeNegative()
&& (seen == IFLT || seen == IFLE || seen == IFGT || seen == IFGE)) {
int specialKind = top.getSpecialKind();
for(Item item : stack) if (item.getSpecialKind() == specialKind) item.setSpecialKind(0);
for(Item item : lvValues) if (item.getSpecialKind() == specialKind) item.setSpecialKind(0);
}
}
addJumpValue(dbc.getBranchTarget());
break;
case LOOKUPSWITCH:
case TABLESWITCH:
seenTransferOfControl = true;
pop();
addJumpValue(dbc.getBranchTarget());
int pc = dbc.getBranchOffset() - dbc.getBranchTarget();
for(int offset : dbc.getSwitchOffsets())
addJumpValue(offset+pc);
break;
case ARETURN:
case DRETURN:
case FRETURN:
case IRETURN:
case LRETURN:
seenTransferOfControl = true;
pop();
break;
case MONITORENTER:
case MONITOREXIT:
case POP:
case PUTSTATIC:
pop();
break;
case IF_ACMPEQ:
case IF_ACMPNE:
case IF_ICMPEQ:
case IF_ICMPNE:
case IF_ICMPLT:
case IF_ICMPLE:
case IF_ICMPGT:
case IF_ICMPGE:
seenTransferOfControl = true;
pop(2);
addJumpValue(dbc.getBranchTarget());
break;
case POP2:
it = pop();
if (it.getSize() == 1) pop();
break;
case PUTFIELD:
pop(2);
break;
case IALOAD:
case SALOAD:
pop(2);
push(new Item("I"));
break;
case DUP:
handleDup();
break;
case DUP2:
handleDup2();
break;
case DUP_X1:
handleDupX1();
break;
case DUP_X2:
handleDupX2();
break;
case DUP2_X1:
handleDup2X1();
break;
case IINC:
register = dbc.getRegisterOperand();
it = getLVValue( register );
it2 = new Item("I", new Integer(dbc.getIntConstant()));
pushByIntMath( IADD, it2, it);
pushByLocalStore(register);
break;
case ATHROW:
pop();
seenTransferOfControl = true;
reachOnlyByBranch = true;
break;
case CHECKCAST:
{
String castTo = dbc.getClassConstantOperand();
if (castTo.charAt(0) != '[') castTo = "L" + castTo + ";";
it = new Item(pop());
it.signature = castTo;
push(it);
break;
}
case NOP:
break;
case RET:
case RETURN:
seenTransferOfControl = true;
reachOnlyByBranch = true;
break;
case GOTO:
case GOTO_W: //It is assumed that no stack items are present when
seenTransferOfControl = true;
reachOnlyByBranch = true;
if (getStackDepth() > 0) {
jumpStack.push(new ArrayList<Item>(stack));
pop();
jumpTarget = dbc.getBranchTarget();
}
addJumpValue(dbc.getBranchTarget());
break;
case SWAP:
handleSwap();
break;
case ICONST_M1:
case ICONST_0:
case ICONST_1:
case ICONST_2:
case ICONST_3:
case ICONST_4:
case ICONST_5:
push(new Item("I", (seen-ICONST_0)));
break;
case LCONST_0:
case LCONST_1:
push(new Item("J", (long)(seen-LCONST_0)));
break;
case DCONST_0:
case DCONST_1:
push(new Item("D", (double)(seen-DCONST_0)));
break;
case FCONST_0:
case FCONST_1:
case FCONST_2:
push(new Item("F", (float)(seen-FCONST_0)));
break;
case ACONST_NULL:
push(new Item());
break;
case ASTORE:
case DSTORE:
case FSTORE:
case ISTORE:
case LSTORE:
pushByLocalStore(dbc.getRegisterOperand());
break;
case ASTORE_0:
case ASTORE_1:
case ASTORE_2:
case ASTORE_3:
pushByLocalStore(seen - ASTORE_0);
break;
case DSTORE_0:
case DSTORE_1:
case DSTORE_2:
case DSTORE_3:
pushByLocalStore(seen - DSTORE_0);
break;
case FSTORE_0:
case FSTORE_1:
case FSTORE_2:
case FSTORE_3:
pushByLocalStore(seen - FSTORE_0);
break;
case ISTORE_0:
case ISTORE_1:
case ISTORE_2:
case ISTORE_3:
pushByLocalStore(seen - ISTORE_0);
break;
case LSTORE_0:
case LSTORE_1:
case LSTORE_2:
case LSTORE_3:
pushByLocalStore(seen - LSTORE_0);
break;
case GETFIELD:
pop();
push(new Item(dbc.getSigConstantOperand(),
FieldAnnotation.fromReferencedField(dbc)));
break;
case ARRAYLENGTH:
pop();
push(new Item("I"));
break;
case BALOAD:
{
pop(2);
Item v = new Item("I");
v.setSpecialKind(Item.SIGNED_BYTE);
push(v);
break;
}
case CALOAD:
pop(2);
push(new Item("I"));
break;
case DALOAD:
pop(2);
push(new Item("D"));
break;
case FALOAD:
pop(2);
push(new Item("F"));
break;
case LALOAD:
pop(2);
push(new Item("J"));
break;
case AASTORE:
case BASTORE:
case CASTORE:
case DASTORE:
case FASTORE:
case IASTORE:
case LASTORE:
case SASTORE:
pop(3);
break;
case BIPUSH:
case SIPUSH:
push(new Item("I", (Integer)dbc.getIntConstant()));
break;
case IADD:
case ISUB:
case IMUL:
case IDIV:
case IAND:
case IOR:
case IXOR:
case ISHL:
case ISHR:
case IREM:
case IUSHR:
it = pop();
it2 = pop();
pushByIntMath(seen, it2, it);
break;
case INEG:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer(-(Integer) it.getConstant())));
} else {
push(new Item("I"));
}
break;
case LNEG:
it = pop();
if (it.getConstant() != null) {
push(new Item("J", new Long(-(Long) it.getConstant())));
} else {
push(new Item("J"));
}
break;
case DNEG:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", new Double(-(Double) it.getConstant())));
} else {
push(new Item("D"));
}
break;
case LADD:
case LSUB:
case LMUL:
case LDIV:
case LAND:
case LOR:
case LXOR:
case LSHL:
case LSHR:
case LREM:
case LUSHR:
it = pop();
it2 = pop();
pushByLongMath(seen, it2, it);
break;
case LCMP:
handleLcmp();
break;
case FCMPG:
case FCMPL: handleFcmp();
break;
case DCMPG:
case DCMPL:
handleDcmp();
break;
case FADD:
case FSUB:
case FMUL:
case FDIV:
it = pop();
it2 = pop();
pushByFloatMath(seen, it, it2);
break;
case DADD:
case DSUB:
case DMUL:
case DDIV:
case DREM:
it = pop();
it2 = pop();
pushByDoubleMath(seen, it, it2);
break;
case I2B:
it = pop();
if (it.getConstant() != null) {
it =new Item("I", (byte)constantToInt(it));
} else {
it = new Item("I");
}
it.setSpecialKind(Item.SIGNED_BYTE);
push(it);
break;
case I2C:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", (char)constantToInt(it)));
} else {
push(new Item("I"));
}
break;
case I2L:
case D2L:{
it = pop();
Item newValue;
if (it.getConstant() != null) {
newValue = new Item("J", constantToLong(it));
} else {
newValue = new Item("J");
}
newValue.setSpecialKind(it.getSpecialKind());
push(newValue);
}
break;
case I2S:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", (short)constantToInt(it)));
} else {
push(new Item("I"));
}
break;
case L2I:
case D2I:
case F2I:
it = pop();
if (it.getConstant() != null) {
push(new Item("I",constantToInt(it)));
} else {
push(new Item("I"));
}
break;
case L2F:
case D2F:
case I2F:
it = pop();
if (it.getConstant() != null) {
push(new Item("F", new Float(constantToFloat(it))));
} else {
push(new Item("F"));
}
break;
case F2D:
case I2D:
case L2D:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", constantToDouble(it)));
} else {
push(new Item("D"));
}
break;
case NEW:
pushBySignature("L" + dbc.getClassConstantOperand() + ";");
break;
case NEWARRAY:
pop();
signature = "[" + BasicType.getType((byte)dbc.getIntConstant()).getSignature();
pushBySignature(signature);
break;
// According to the VM Spec 4.4.1, anewarray and multianewarray
// can refer to normal class/interface types (encoded in
// "internal form"), or array classes (encoded as signatures
// beginning with "[").
case ANEWARRAY:
pop();
signature = dbc.getClassConstantOperand();
if (!signature.startsWith("[")) {
signature = "[L" + signature + ";";
}
pushBySignature(signature);
break;
case MULTIANEWARRAY:
int dims = dbc.getIntConstant();
while ((dims
pop();
}
signature = dbc.getClassConstantOperand();
if (!signature.startsWith("[")) {
dims = dbc.getIntConstant();
signature = "";
while ((dims
signature += "[";
signature += "L" + signature + ";";
}
pushBySignature(signature);
break;
case AALOAD:
pop();
it = pop();
pushBySignature(it.getElementSignature());
break;
case JSR:
push(new Item(""));
break;
case INVOKEINTERFACE:
case INVOKESPECIAL:
case INVOKESTATIC:
case INVOKEVIRTUAL:
processMethodCall(dbc, seen);
break;
default:
throw new UnsupportedOperationException("OpCode " + OPCODE_NAMES[seen] + " not supported " );
}
}
catch (RuntimeException e) {
//If an error occurs, we clear the stack and locals. one of two things will occur.
//Either the client will expect more stack items than really exist, and so they're condition check will fail,
//or the stack will resync with the code. But hopefully not false positives
// TODO: log this
if (DEBUG)
e.printStackTrace();
clear();
}
finally {
if (exceptionHandlers.get(dbc.getNextPC()))
push(new Item());
if (DEBUG) {
System.out.println(dbc.getNextPC() + "pc : " + OPCODE_NAMES[seen] + " stack depth: " + getStackDepth());
System.out.println(this);
}
}
}
/**
* @param it
* @return
*/
private int constantToInt(Item it) {
return ((Number)it.getConstant()).intValue();
}
/**
* @param it
* @return
*/
private float constantToFloat(Item it) {
return ((Number)it.getConstant()).floatValue();
}
/**
* @param it
* @return
*/
private double constantToDouble(Item it) {
return ((Number)it.getConstant()).doubleValue();
}
/**
* @param it
* @return
*/
private long constantToLong(Item it) {
return ((Number)it.getConstant()).longValue();
}
private void handleDcmp() {
Item it;
Item it2;
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
double d = (Double) it.getConstant();
double d2 = (Double) it.getConstant();
if (d2 < d)
push(new Item("I", (Integer) (-1) ));
else if (d2 > d)
push(new Item("I", (Integer)1));
else
push(new Item("I", (Integer)0));
} else {
push(new Item("I"));
}
}
private void handleFcmp() {
Item it;
Item it2;
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
float f = (Float) it.getConstant();
float f2 = (Float) it.getConstant();
if (f2 < f)
push(new Item("I", new Integer(-1)));
else if (f2 > f)
push(new Item("I", new Integer(1)));
else
push(new Item("I", new Integer(0)));
} else {
push(new Item("I"));
}
}
private void handleLcmp() {
Item it;
Item it2;
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
long l = (Long) it.getConstant();
long l2 = (Long) it.getConstant();
if (l2 < l)
push(new Item("I", (Integer)(-1)));
else if (l2 > l)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(0)));
} else {
push(new Item("I"));
}
}
private void handleSwap() {
Item i1 = pop();
Item i2 = pop();
push(i1);
push(i2);
}
private void handleDup() {
Item it;
it = pop();
push(it);
push(it);
}
private void handleDupX1() {
Item it;
Item it2;
it = pop();
it2 = pop();
push(it);
push(it2);
push(it);
}
private void handleDup2() {
Item it, it2;
it = pop();
if (it.getSize() == 2) {
push(it);
push(it);
}
else {
it2 = pop();
push(it2);
push(it);
push(it2);
push(it);
}
}
private void handleDup2X1() {
String signature;
Item it;
Item it2;
Item it3;
it = pop();
it2 = pop();
signature = it.getSignature();
if (signature.equals("J") || signature.equals("D")) {
push(it);
push(it2);
push(it);
} else {
it3 = pop();
push(it2);
push(it);
push(it3);
push(it2);
push(it);
}
}
private void handleDupX2() {
String signature;
Item it;
Item it2;
Item it3;
it = pop();
it2 = pop();
signature = it2.getSignature();
if (signature.equals("J") || signature.equals("D")) {
push(it);
push(it2);
push(it);
} else {
it3 = pop();
push(it);
push(it3);
push(it2);
push(it);
}
}
private void processMethodCall(DismantleBytecode dbc, int seen) {
String clsName = dbc.getClassConstantOperand();
String methodName = dbc.getNameConstantOperand();
String signature = dbc.getSigConstantOperand();
String appenderValue = null;
Item sbItem = null;
//TODO: stack merging for trinaries kills the constant.. would be nice to maintain.
if ("java/lang/StringBuffer".equals(clsName)
|| "java/lang/StringBuilder".equals(clsName)) {
if ("<init>".equals(methodName)) {
if ("(Ljava/lang/String;)V".equals(signature)) {
Item i = getStackItem(0);
appenderValue = (String)i.getConstant();
} else if ("()V".equals(signature)) {
appenderValue = "";
}
} else if ("toString".equals(methodName)) {
Item i = getStackItem(0);
appenderValue = (String)i.getConstant();
} else if ("append".equals(methodName) && signature.indexOf("II)") == -1) {
sbItem = getStackItem(1);
Item i = getStackItem(0);
Object sbVal = sbItem.getConstant();
Object sVal = i.getConstant();
if ((sbVal != null) && (sVal != null)) {
appenderValue = sbVal + sVal.toString();
} else if (sbItem.registerNumber >= 0) {
OpcodeStack.Item item = getLVValue(sbItem.registerNumber);
if (item != null)
item.constValue = null;
}
}
}
pushByInvoke(dbc, seen != INVOKESTATIC);
if (appenderValue != null) {
Item i = this.getStackItem(0);
i.constValue = appenderValue;
if (sbItem != null) {
i.registerNumber = sbItem.registerNumber;
i.field = sbItem.field;
i.xfield = sbItem.xfield;
i.userValue = sbItem.userValue;
if (sbItem.registerNumber >= 0)
setLVValue(sbItem.registerNumber, i );
}
return;
}
if ((clsName.equals("java/util/Random") || clsName.equals("java/security/SecureRandom")) && methodName.equals("nextInt") && signature.equals("()I")) {
Item i = pop();
i.setSpecialKind(Item.RANDOM_INT);
push(i);
}
else if (seen == INVOKEVIRTUAL && methodName.equals("hashCode") && signature.equals("()I")
|| seen == INVOKESTATIC && clsName.equals("java/lang/System") && methodName.equals("identityHashCode") && signature.equals("(Ljava/lang/Object;)I")) {
Item i = pop();
i.setSpecialKind(Item.HASHCODE_INT);
push(i);
}
}
private void mergeLists(List<Item> mergeInto, List<Item> mergeFrom, boolean errorIfSizesDoNotMatch) {
// merge stacks
int intoSize = mergeInto.size();
int fromSize = mergeFrom.size();
if (errorIfSizesDoNotMatch && intoSize != fromSize) {
if (DEBUG) {
System.out.println("Bad merging items");
System.out.println("current items: " + mergeInto);
System.out.println("jump items: " + mergeFrom);
}
} else {
if (DEBUG) {
System.out.println("Merging items");
System.out.println("current items: " + mergeInto);
System.out.println("jump items: " + mergeFrom);
}
for (int i = 0; i < Math.min(intoSize, fromSize); i++)
mergeInto.set(i, Item.merge(mergeInto.get(i), mergeFrom.get(i)));
if (DEBUG) {
System.out.println("merged items: " + mergeInto);
}
}
}
public void clear() {
stack.clear();
lvValues.clear();
jumpStack.clear();
}
BitSet exceptionHandlers = new BitSet();
private Map<Integer, List<Item>> jumpEntries = new HashMap<Integer, List<Item>>();
private void addJumpValue(int target) {
if (DEBUG)
System.out.println("Set jump entry at " + methodName + ":" + target + "pc to " + lvValues);
List<Item> atTarget = jumpEntries.get(target);
if (atTarget == null) {
if (DEBUG)
System.out.println("Was null");
jumpEntries.put(target, new ArrayList<Item>(lvValues));
if (false) {
System.out.println("jump entires are now...");
for (Integer pc : jumpEntries.keySet()) {
List<Item> list = jumpEntries.get(pc);
System.out.println(pc + "pc -> " + Integer.toString(System.identityHashCode(list),16) + " " + list);
}}
return;
}
mergeLists(atTarget, lvValues, false);
if (DEBUG)
System.out.println("merge target for " + methodName + ":" + target + "pc is " + atTarget);
}
private String methodName;
public int resetForMethodEntry(final DismantleBytecode v) {
methodName = v.getMethodName();
jumpEntries.clear();
lastUpdate.clear();
convertJumpToOneZeroState = convertJumpToZeroOneState = 0;
reachOnlyByBranch = false;
int result= resetForMethodEntry0(v);
Code code = v.getMethod().getCode();
if (code == null) return result;
if (useIterativeAnalysis) {
// FIXME: Be clever
if (DEBUG)
System.out.println(" --- Iterative analysis");
DismantleBytecode branchAnalysis = new DismantleBytecode() {
@Override
public void sawOpcode(int seen) {
OpcodeStack.this.sawOpcode(this, seen);
}
// perhaps we don't need this
// @Override
// public void sawBranchTo(int pc) {
// addJumpValue(pc);
};
branchAnalysis.setupVisitorForClass(v.getThisClass());
branchAnalysis.doVisitMethod(v.getMethod());
if (!jumpEntries.isEmpty())
branchAnalysis.doVisitMethod(v.getMethod());
if (DEBUG && !jumpEntries.isEmpty()) {
System.out.println("Found dataflow for jumps in " + v.getMethodName());
for (Integer pc : jumpEntries.keySet()) {
List<Item> list = jumpEntries.get(pc);
System.out.println(pc + " -> " + Integer.toString(System.identityHashCode(list),16) + " " + list);
}
}
resetForMethodEntry0(v);
if (DEBUG)
System.out.println(" --- End of Iterative analysis");
}
return result;
}
private int resetForMethodEntry0(PreorderVisitor v) {
if (DEBUG) System.out.println("
stack.clear();
jumpTarget = -1;
lvValues.clear();
jumpStack.clear();
reachOnlyByBranch = false;
seenTransferOfControl = false;
String className = v.getClassName();
String signature = v.getMethodSig();
exceptionHandlers.clear();
Method m = v.getMethod();
Code code = m.getCode();
if (code != null)
{
CodeException[] exceptionTable = code.getExceptionTable();
if (exceptionTable != null)
for(CodeException ex : exceptionTable)
exceptionHandlers.set(ex.getHandlerPC());
}
if (DEBUG) System.out.println(" --- " + className
+ " " + m.getName() + " " + signature);
Type[] argTypes = Type.getArgumentTypes(signature);
int reg = 0;
if (!m.isStatic()) {
Item it = new Item("L" + className+";");
it.isInitialParameter = true;
it.registerNumber = reg;
setLVValue( reg, it);
reg += it.getSize();
}
for (Type argType : argTypes) {
Item it = new Item(argType.getSignature());
it.registerNumber = reg;
it.isInitialParameter = true;
setLVValue(reg, it);
reg += it.getSize();
}
return reg;
}
public int getStackDepth() {
return stack.size();
}
public Item getStackItem(int stackOffset) {
if (stackOffset < 0 || stackOffset >= stack.size()) {
// assert false : "Can't get stack offset " + stackOffset + " from " + stack.toString();
return new Item("Lfindbugs/OpcodeStackError;");
}
int tos = stack.size() - 1;
int pos = tos - stackOffset;
try {
return stack.get(pos);
} catch (ArrayIndexOutOfBoundsException e) {
throw new ArrayIndexOutOfBoundsException(
"Requested item at offset " + stackOffset + " in a stack of size " + stack.size()
+", made request for position " + pos);
}
}
private Item pop() {
return stack.remove(stack.size()-1);
}
private void pop(int count)
{
while ((count
pop();
}
private void push(Item i) {
stack.add(i);
}
private void pushByConstant(DismantleBytecode dbc, Constant c) {
if (c instanceof ConstantClass)
push(new Item("Ljava/lang/Class;", ((ConstantClass)c).getConstantValue(dbc.getConstantPool())));
else if (c instanceof ConstantInteger)
push(new Item("I", new Integer(((ConstantInteger) c).getBytes())));
else if (c instanceof ConstantString) {
int s = ((ConstantString) c).getStringIndex();
push(new Item("Ljava/lang/String;", getStringFromIndex(dbc, s)));
}
else if (c instanceof ConstantFloat)
push(new Item("F", new Float(((ConstantFloat) c).getBytes())));
else if (c instanceof ConstantDouble)
push(new Item("D", new Double(((ConstantDouble) c).getBytes())));
else if (c instanceof ConstantLong)
push(new Item("J", new Long(((ConstantLong) c).getBytes())));
else
throw new UnsupportedOperationException("Constant type not expected" );
}
private void pushByLocalObjectLoad(DismantleBytecode dbc, int register) {
Method m = dbc.getMethod();
LocalVariableTable lvt = m.getLocalVariableTable();
if (lvt != null) {
LocalVariable lv = LVTHelper.getLocalVariableAtPC(lvt, register, dbc.getPC());
if (lv != null) {
String signature = lv.getSignature();
pushByLocalLoad(signature, register);
return;
}
}
pushByLocalLoad("", register);
}
private void pushByIntMath(int seen, Item lhs, Item rhs) {
if (DEBUG) System.out.println("pushByIntMath: " + rhs.getConstant() + " " + lhs.getConstant() );
Item newValue = new Item("I");
try {
if ((rhs.getConstant() != null) && lhs.getConstant() != null) {
Integer lhsValue = (Integer) lhs.getConstant();
Integer rhsValue = (Integer) rhs.getConstant();
if (seen == IADD)
newValue = new Item("I",lhsValue + rhsValue);
else if (seen == ISUB)
newValue = new Item("I",lhsValue - rhsValue);
else if (seen == IMUL)
newValue = new Item("I", lhsValue * rhsValue);
else if (seen == IDIV)
newValue = new Item("I", lhsValue / rhsValue);
else if (seen == IAND) {
newValue = new Item("I", lhsValue & rhsValue);
if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 )
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
} else if (seen == IOR)
newValue = new Item("I",lhsValue | rhsValue);
else if (seen == IXOR)
newValue = new Item("I",lhsValue ^ rhsValue);
else if (seen == ISHL) {
newValue = new Item("I",lhsValue << rhsValue);
if (rhsValue >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR;
}
else if (seen == ISHR)
newValue = new Item("I",lhsValue >> rhsValue);
else if (seen == IREM)
newValue = new Item("I", lhsValue % rhsValue);
else if (seen == IUSHR)
newValue = new Item("I", lhsValue >>> rhsValue);
} else if (rhs.getConstant() != null && seen == ISHL && (Integer) rhs.getConstant() >= 8)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (lhs.getConstant() != null && seen == IAND && ((Integer) lhs.getConstant() & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (rhs.getConstant() != null && seen == IAND && ((Integer) rhs.getConstant() & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
} catch (RuntimeException e) {
// ignore it
}
if (lhs.specialKind == Item.INTEGER_SUM && rhs.getConstant() != null ) {
int rhsValue = (Integer) rhs.getConstant();
if (seen == IDIV && rhsValue ==2 || seen == ISHR && rhsValue == 1)
newValue.specialKind = Item.AVERAGE_COMPUTED_USING_DIVISION;
}
if (seen == IADD && newValue.specialKind == 0 && lhs.getConstant() == null && rhs.getConstant() == null )
newValue.specialKind = Item.INTEGER_SUM;
if (seen == IREM && lhs.specialKind == Item.HASHCODE_INT)
newValue.specialKind = Item.HASHCODE_INT_REMAINDER;
if (seen == IREM && lhs.specialKind == Item.RANDOM_INT)
newValue.specialKind = Item.RANDOM_INT_REMAINDER;
if (DEBUG) System.out.println("push: " + newValue);
push(newValue);
}
private void pushByLongMath(int seen, Item lhs, Item rhs) {
Item newValue = new Item("J");
try {
if ((rhs.getConstant() != null) && lhs.getConstant() != null) {
Long lhsValue = ((Long) lhs.getConstant());
if (seen == LSHL) {
newValue =new Item("J", lhsValue << ((Number) rhs.getConstant()).intValue());
if (((Number) rhs.getConstant()).intValue() >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR;
}
else if (seen == LSHR)
newValue =new Item("J", lhsValue >> ((Number) rhs.getConstant()).intValue());
else if (seen == LUSHR)
newValue =new Item("J", lhsValue >>> ((Number) rhs.getConstant()).intValue());
else {
Long rhsValue = ((Long) rhs.getConstant());
if (seen == LADD)
newValue = new Item("J", lhsValue + rhsValue);
else if (seen == LSUB)
newValue = new Item("J", lhsValue - rhsValue);
else if (seen == LMUL)
newValue = new Item("J", lhsValue * rhsValue);
else if (seen == LDIV)
newValue =new Item("J", lhsValue / rhsValue);
else if (seen == LAND) {
newValue = new Item("J", lhsValue & rhsValue);
if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 )
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
}
else if (seen == LOR)
newValue = new Item("J", lhsValue | rhsValue);
else if (seen == LXOR)
newValue =new Item("J", lhsValue ^ rhsValue);
else if (seen == LREM)
newValue =new Item("J", lhsValue % rhsValue);
}
}
else if (rhs.getConstant() != null && seen == LSHL && ((Integer) rhs.getConstant()) >= 8)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (lhs.getConstant() != null && seen == LAND && (((Long) lhs.getConstant()) & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (rhs.getConstant() != null && seen == LAND && (((Long) rhs.getConstant()) & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
} catch (RuntimeException e) {
// ignore it
}
push(newValue);
}
private void pushByFloatMath(int seen, Item it, Item it2) {
Item result;
if ((it.getConstant() != null) && it2.getConstant() != null) {
if (seen == FADD)
result =new Item("F", ((Float) it2.getConstant()) + ((Float) it.getConstant()));
else if (seen == FSUB)
result =new Item("F", ((Float) it2.getConstant()) - ((Float) it.getConstant()));
else if (seen == FMUL)
result =new Item("F", ((Float) it2.getConstant()) * ((Float) it.getConstant()));
else if (seen == FDIV)
result =new Item("F", ((Float) it2.getConstant()) / ((Float) it.getConstant()));
else result =new Item("F");
} else {
result =new Item("F");
}
result.setSpecialKind(Item.FLOAT_MATH);
push(result);
}
private void pushByDoubleMath(int seen, Item it, Item it2) {
Item result;
if ((it.getConstant() != null) && it2.getConstant() != null) {
if (seen == DADD)
result = new Item("D", ((Double) it2.getConstant()) + ((Double) it.getConstant()));
else if (seen == DSUB)
result = new Item("D", ((Double) it2.getConstant()) - ((Double) it.getConstant()));
else if (seen == DMUL)
result = new Item("D", ((Double) it2.getConstant()) * ((Double) it.getConstant()));
else if (seen == DDIV)
result = new Item("D", ((Double) it2.getConstant()) / ((Double) it.getConstant()));
else
result = new Item("D");
} else {
result = new Item("D");
}
result.setSpecialKind(Item.FLOAT_MATH);
push(result);
}
private void pushByInvoke(DismantleBytecode dbc, boolean popThis) {
String signature = dbc.getSigConstantOperand();
pop(PreorderVisitor.getNumberArguments(signature)+(popThis ? 1 : 0));
pushBySignature(Type.getReturnType(signature).getSignature());
}
private String getStringFromIndex(DismantleBytecode dbc, int i) {
ConstantUtf8 name = (ConstantUtf8) dbc.getConstantPool().getConstant(i);
return name.getBytes();
}
private void pushBySignature(String s) {
if ("V".equals(s))
return;
push(new Item(s, null));
}
private void pushByLocalStore(int register) {
Item it = pop();
setLVValue( register, it );
}
private void pushByLocalLoad(String signature, int register) {
Item it = getLVValue(register);
if (it == null) {
Item item = new Item(signature);
item.registerNumber = register;
push(item);
}
else if (it.getRegisterNumber() >= 0)
push(it);
else {
push(new Item(it, register));
}
}
private void setLVValue(int index, Item value ) {
int addCount = index - lvValues.size() + 1;
while ((addCount
lvValues.add(null);
if (!useIterativeAnalysis && seenTransferOfControl)
value = Item.merge(value, lvValues.get(index) );
lvValues.set(index, value);
}
private Item getLVValue(int index) {
if (index >= lvValues.size())
return null;
return lvValues.get(index);
}
}
// vim:ts=4 |
package gcUnrelatedTypes;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.google.common.base.Objects;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multiset;
import com.google.common.collect.Sets;
import com.google.common.collect.Table;
import edu.umd.cs.findbugs.annotations.ExpectWarning;
import edu.umd.cs.findbugs.annotations.NoWarning;
public class Guava {
static class Pair<A,B> {
final A a;
final B b;
public Pair(A a, B b) {
this.a = a;
this.b = b;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((a == null) ? 0 : a.hashCode());
result = prime * result + ((b == null) ? 0 : b.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (a == null) {
if (other.a != null)
return false;
} else if (!a.equals(other.a))
return false;
if (b == null) {
if (other.b != null)
return false;
} else if (!b.equals(other.b))
return false;
return true;
}
}
@ExpectWarning(value="GC", num=7)
public static void testMultimap(Multimap<String, Integer> mm) {
mm.containsEntry("x", "y");
mm.containsEntry(1, 5);
mm.containsKey(1);
mm.containsValue("x");
mm.remove("x", "x");
mm.remove(1, 2);
mm.removeAll(1);
}
@ExpectWarning("GC")
public static void testMultimap3( Multimap<Long, Long> counts, int minSize) {
List<Long> idsToRemove = new ArrayList<Long>();
for (Long id : counts.keySet()) {
if (counts.get(id).size() < minSize)
idsToRemove.add(id);
}
counts.removeAll(idsToRemove);
}
@NoWarning("GC")
public static void testMultimapOK(Multimap<String, Integer> mm) {
mm.containsEntry("x", 1);
mm.containsKey("x");
mm.containsValue(1);
mm.remove("x", 1);
mm.removeAll("x");
}
@NoWarning("GC")
public static void testMultimapOK2(Multimap<String, Pair<Integer,Long>> mm) {
Pair<Integer, Long> p = new Pair<Integer, Long>(1, 1L);
mm.containsEntry("x", p);
mm.containsKey("x");
mm.containsValue(p);
mm.remove("x", p);
mm.removeAll("x");
}
@ExpectWarning(value="GC", num=4)
public static void testMultiset(Multiset<String> ms) {
ms.contains(1);
ms.count(1);
ms.remove(1);
ms.remove(1, 2);
}
@NoWarning("GC")
public static void testMultisetOK(Multiset<String> ms) {
ms.contains("x");
ms.count("x");
ms.remove("x");
ms.remove("x", 2);
}
@ExpectWarning(value="GC", num=9)
public static void testTable(Table<String, Integer, Long> t) {
t.contains("x", "x");
t.contains(1, 1);
t.containsRow(1);
t.containsColumn("x");
t.containsValue(1);
t.get("x", "x");
t.get(1, 1);
t.remove("x", "x");
t.remove(1, 1);
}
@NoWarning(value="GC")
public static void testTableOK(Table<String, Integer, Long> t) {
t.contains("x", 1);
t.containsRow("x");
t.containsColumn(1);
t.containsValue(1L);
t.get("x", 1);
t.remove("x", 1);
}
@ExpectWarning(value="EC", num=2)
public static void testObjects() {
Objects.equal("x", 1);
Objects.equal("x", new int[1]);
}
@NoWarning("EC")
public static void testObjectsOK() {
Objects.equal("x", "X");
}
@ExpectWarning(value="GC", num=3)
public static void testSets(Set<String> s1, Set<Integer> s2) {
Sets.intersection(s1, s2);
Sets.difference(s1, s2);
Sets.symmetricDifference(s1, s2);
}
@NoWarning("GC")
public static void testSetsOK(Set<String> s1, Set<String> s2) {
Sets.intersection(s1, s2);
Sets.difference(s1, s2);
Sets.symmetricDifference(s1, s2);
}
@ExpectWarning(value="GC", num=2)
public static void testIterables(Iterable<String> i, Collection<Integer> c) {
Iterables.contains(i, 1);
Iterables.removeAll(i, c);
Iterables.retainAll(i, c);
Iterables.elementsEqual(i, c);
Iterables.frequency(i, 1);
}
@NoWarning("GC")
public static void testIterablesOK(Iterable<String> i, Collection<String> c) {
Iterables.contains(i, "x");
Iterables.removeAll(i, c);
Iterables.retainAll(i, c);
Iterables.elementsEqual(i, c);
Iterables.frequency(i, "x");
}
@ExpectWarning(value="GC", num=2)
public static void testIterators(Iterator<String> i, Collection<Integer> c) {
Iterators.contains(i, 1);
Iterators.removeAll(i,c);
Iterators.retainAll(i, c);
Iterators.elementsEqual(i, c.iterator());
Iterators.frequency(i, 1);
}
@NoWarning("GC")
public static void testIteratorsOK(Iterator<String> i, Collection<String> c) {
Iterators.contains(i, "x");
Iterators.removeAll(i,c);
Iterators.retainAll(i, c);
Iterators.elementsEqual(i, c.iterator());
Iterators.frequency(i, "x");
}
} |
package thread.lock;
public class Target {
synchronized public void outer() {
inner();
}
synchronized public void inner() {
}
}
class Target2{
MyLock lock = new MyLock();
public void outer() throws InterruptedException {
lock.lock();
inner();
lock.unlock();
}
public void inner() throws InterruptedException {
lock.lock();
// do something
lock.unlock();
}
} |
package org.zkoss.ganttz;
import java.util.List;
import org.joda.time.LocalDate;
import org.zkoss.ganttz.adapters.IDisabilityConfiguration;
import org.zkoss.ganttz.data.GanttDiagramGraph;
import org.zkoss.ganttz.data.Task;
import org.zkoss.ganttz.timetracker.TimeTracker;
import org.zkoss.ganttz.timetracker.TimeTrackerComponent;
import org.zkoss.ganttz.timetracker.zoom.IZoomLevelChangedListener;
import org.zkoss.ganttz.timetracker.zoom.ZoomLevel;
import org.zkoss.ganttz.util.Interval;
import org.zkoss.zk.au.out.AuInvoke;
import org.zkoss.zk.ui.ext.AfterCompose;
import org.zkoss.zul.impl.XulElement;
public class GanttPanel extends XulElement implements AfterCompose {
private TaskList tasksLists;
private TimeTrackerComponent timeTrackerComponent;
private DependencyList dependencyList;
private final GanttDiagramGraph diagramGraph;
private final Planner planner;
private transient IZoomLevelChangedListener zoomLevelChangedListener;
private LocalDate previousStart;
private Interval previousInterval;
public GanttPanel(
Planner planner,
List<? extends CommandOnTaskContextualized<?>> commandsOnTasksContextualized,
CommandOnTaskContextualized<?> doubleClickCommand,
IDisabilityConfiguration disabilityConfiguration,
FilterAndParentExpandedPredicates predicate) {
this.planner = planner;
FunctionalityExposedForExtensions<?> context = (FunctionalityExposedForExtensions<?>) planner
.getContext();
if (planner.isShowingCriticalPath()) {
context.showCriticalPath();
}
this.diagramGraph = context.getDiagramGraph();
timeTrackerComponent = timeTrackerForGanttPanel(context
.getTimeTracker());
appendChild(timeTrackerComponent);
dependencyList = new DependencyList(context);
tasksLists = TaskList.createFor(context, doubleClickCommand,
commandsOnTasksContextualized, disabilityConfiguration,
predicate);
appendChild(tasksLists);
appendChild(dependencyList);
}
private TimeTrackerComponent timeTrackerForGanttPanel(
TimeTracker timeTracker) {
return new TimeTrackerComponent(timeTracker) {
@Override
protected void scrollHorizontalPercentage(int daysDisplacement) {
response("scroll_horizontal", new AuInvoke(GanttPanel.this,
"scroll_horizontal", "" + daysDisplacement));
moveCurrentPositionScroll();
}
// FIXME: this is quite awful, it should be simple
@Override
protected void moveCurrentPositionScroll() {
// get the previous data.
LocalDate previousStart = getPreviousStart();
// get the current data
int diffDays = getTimeTrackerComponent().getDiffDays(
previousStart);
double pixelPerDay = getTimeTrackerComponent().getPixelPerDay();
response("move_scroll", new AuInvoke(GanttPanel.this,
"move_scroll", "" + diffDays, "" + pixelPerDay));
}
protected void updateCurrentDayScroll() {
double previousPixelPerDay = getTimeTracker().getMapper()
.getPixelsPerDay()
.doubleValue();
response("update_day_scroll", new AuInvoke(GanttPanel.this,
"update_day_scroll", "" + previousPixelPerDay));
}
};
}
@Override
public void afterCompose() {
tasksLists.afterCompose();
dependencyList.setDependencyComponents(tasksLists
.asDependencyComponents(diagramGraph.getVisibleDependencies()));
timeTrackerComponent.afterCompose();
dependencyList.afterCompose();
savePreviousData();
if (planner.isExpandAll()) {
FunctionalityExposedForExtensions<?> context = (FunctionalityExposedForExtensions<?>) planner
.getContext();
context.expandAll();
}
if (planner.isFlattenTree()) {
planner.getPredicate().setFilterContainers(true);
planner.setTaskListPredicate(planner.getPredicate());
}
registerZoomLevelChangedListener();
}
public void updateTooltips() {
for (Task task : this.tasksLists.getAllTasks()) {
task.updateTooltipText();
}
for (TaskComponent taskComponent : this.tasksLists.getTaskComponents()) {
taskComponent.invalidate();
}
}
public TimeTrackerComponent getTimeTrackerComponent() {
return timeTrackerComponent;
}
public TaskList getTaskList() {
return tasksLists;
}
public DependencyList getDependencyList() {
return dependencyList;
}
public void comingFromAnotherTab() {
timeTrackerComponent.recreate();
}
public void zoomIncrease() {
savePreviousData();
getTimeTrackerComponent().updateDayScroll();
getTimeTracker().zoomIncrease();
}
public void zoomDecrease() {
savePreviousData();
getTimeTrackerComponent().updateDayScroll();
getTimeTracker().zoomDecrease();
}
public TimeTracker getTimeTracker() {
return timeTrackerComponent.getTimeTracker();
}
public void setZoomLevel(ZoomLevel zoomLevel, int scrollLeft) {
savePreviousData();
getTimeTrackerComponent().updateDayScroll();
getTimeTrackerComponent().setZoomLevel(zoomLevel, scrollLeft);
}
private void savePreviousData() {
this.previousStart = getTimeTracker().getRealInterval().getStart();
this.previousInterval = getTimeTracker().getMapper().getInterval();
}
public Planner getPlanner() {
return planner;
}
private void registerZoomLevelChangedListener() {
if (zoomLevelChangedListener == null) {
zoomLevelChangedListener = new IZoomLevelChangedListener() {
@Override
public void zoomLevelChanged(ZoomLevel detailLevel) {
adjustZoomColumnsHeight();
}
};
getTimeTracker().addZoomListener(zoomLevelChangedListener);
}
}
public void adjustZoomColumnsHeight() {
response("adjust_dimensions", new AuInvoke(this, "adjust_dimensions"));
}
public LocalDate getPreviousStart() {
return previousStart;
}
public Interval getPreviousInterval() {
return previousInterval;
}
} |
package example;
//-*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.IOException;
import javax.imageio.*;
import javax.swing.*;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
BufferedImage bi = null;
try {
// symbol_scale_2.jpg: Real World Illustrator: Understanding 9-Slice Scaling
bi = ImageIO.read(getClass().getResource("symbol_scale_2.jpg"));
} catch (IOException ex) {
ex.printStackTrace();
}
JButton b1 = new ScalingButton("Scaling", bi);
JButton b2 = new NineSliceScalingButton("9-Slice Scaling", bi);
JPanel p1 = new JPanel(new GridLayout(1, 2, 5, 5));
p1.add(b1);
p1.add(b2);
try {
bi = ImageIO.read(getClass().getResource("blue.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
JButton b3 = new JButton("Scaling Icon", new NineSliceScalingIcon(bi, 0, 0, 0, 0));
b3.setContentAreaFilled(false);
b3.setBorder(BorderFactory.createEmptyBorder());
b3.setForeground(Color.WHITE);
b3.setHorizontalTextPosition(SwingConstants.CENTER);
b3.setPressedIcon(new NineSliceScalingIcon(makeFilteredImage(bi, new PressedImageFilter()), 0, 0, 0, 0));
b3.setRolloverIcon(new NineSliceScalingIcon(makeFilteredImage(bi, new RolloverImageFilter()), 0, 0, 0, 0));
JButton b4 = new JButton("9-Slice Scaling Icon", new NineSliceScalingIcon(bi, 8, 8, 8, 8));
b4.setContentAreaFilled(false);
b4.setBorder(BorderFactory.createEmptyBorder());
b4.setForeground(Color.WHITE);
b4.setHorizontalTextPosition(SwingConstants.CENTER);
b4.setPressedIcon(new NineSliceScalingIcon(makeFilteredImage(bi, new PressedImageFilter()), 8, 8, 8, 8));
b4.setRolloverIcon(new NineSliceScalingIcon(makeFilteredImage(bi, new RolloverImageFilter()), 8, 8, 8, 8));
JPanel p2 = new JPanel(new GridLayout(1, 2, 5, 5));
p2.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
p2.add(b3);
p2.add(b4);
add(p1);
add(p2, BorderLayout.SOUTH);
setPreferredSize(new Dimension(320, 240));
}
private static BufferedImage makeFilteredImage(BufferedImage src, ImageFilter filter) {
ImageProducer ip = src.getSource();
Image img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(ip, filter));
BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
return bi;
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class ScalingButton extends JButton {
private final transient BufferedImage image;
protected ScalingButton(String title, BufferedImage image) {
super();
this.image = image;
setModel(new DefaultButtonModel());
init(title, null);
setContentAreaFilled(false);
}
// @Override public Dimension getPreferredSize() {
// Insets i = getInsets();
// return new Dimension(image.getWidth(this) + i.right + i.left, 80);
// @Override public Dimension getMinimumSize() {
// return getPreferredSize();
@Override protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int bw = getWidth();
int bh = getHeight();
g2.drawImage(image, 0, 0, bw, bh, this);
g2.dispose();
super.paintComponent(g);
}
}
class NineSliceScalingButton extends JButton {
private final transient BufferedImage image;
protected NineSliceScalingButton(String title, BufferedImage image) {
super();
this.image = image;
setModel(new DefaultButtonModel());
init(title, null);
setContentAreaFilled(false);
}
// @Override public Dimension getPreferredSize() {
// Dimension dim = super.getPreferredSize();
// return new Dimension(dim.width + leftw + rightw, dim.height + toph + bottomh);
// @Override public Dimension getMinimumSize() {
// return getPreferredSize();
@Override protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int iw = image.getWidth(this);
int ih = image.getHeight(this);
int bw = getWidth();
int bh = getHeight();
int leftw = 37;
int rightw = 36;
int toph = 36;
int bottomh = 36;
g2.drawImage(image.getSubimage(leftw, toph, iw - leftw - rightw, ih - toph - bottomh), leftw, toph, bw - leftw - rightw, bh - toph - bottomh, this);
g2.drawImage(image.getSubimage(leftw, 0, iw - leftw - rightw, toph), leftw, 0, bw - leftw - rightw, toph, this);
g2.drawImage(image.getSubimage(leftw, ih - bottomh, iw - leftw - rightw, bottomh), leftw, bh - bottomh, bw - leftw - rightw, bottomh, this);
g2.drawImage(image.getSubimage(0, toph, leftw, ih - toph - bottomh), 0, toph, leftw, bh - toph - bottomh, this);
g2.drawImage(image.getSubimage(iw - rightw, toph, rightw, ih - toph - bottomh), bw - rightw, toph, rightw, bh - toph - bottomh, this);
g2.drawImage(image.getSubimage(0, 0, leftw, toph), 0, 0, this);
g2.drawImage(image.getSubimage(iw - rightw, 0, rightw, toph), bw - rightw, 0, this);
g2.drawImage(image.getSubimage(0, ih - bottomh, leftw, bottomh), 0, bh - bottomh, this);
g2.drawImage(image.getSubimage(iw - rightw, ih - bottomh, rightw, bottomh), bw - rightw, bh - bottomh, this);
g2.dispose();
super.paintComponent(g);
}
}
class NineSliceScalingIcon implements Icon {
private final BufferedImage image;
private final int leftw;
private final int rightw;
private final int toph;
private final int bottomh;
private int width;
private int height;
protected NineSliceScalingIcon(BufferedImage image, int leftw, int rightw, int toph, int bottomh) {
this.image = image;
this.leftw = leftw;
this.rightw = rightw;
this.toph = toph;
this.bottomh = bottomh;
}
@Override public int getIconWidth() {
return width; // Math.max(image.getWidth(null), width);
}
@Override public int getIconHeight() {
return Math.max(image.getHeight(null), height);
}
@Override public void paintIcon(Component cmp, Graphics g, int x, int y) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Insets i;
if (cmp instanceof JComponent) {
i = ((JComponent) cmp).getBorder().getBorderInsets(cmp);
} else {
i = new Insets(0, 0, 0, 0);
}
// g2.translate(x, y); // 1.8.0: work fine?
int iw = image.getWidth(cmp);
int ih = image.getHeight(cmp);
width = cmp.getWidth() - i.left - i.right;
height = cmp.getHeight() - i.top - i.bottom;
g2.drawImage(image.getSubimage(leftw, toph, iw - leftw - rightw, ih - toph - bottomh), leftw, toph, width - leftw - rightw, height - toph - bottomh, cmp);
if (leftw > 0 && rightw > 0 && toph > 0 && bottomh > 0) {
g2.drawImage(image.getSubimage(leftw, 0, iw - leftw - rightw, toph), leftw, 0, width - leftw - rightw, toph, cmp);
g2.drawImage(image.getSubimage(leftw, ih - bottomh, iw - leftw - rightw, bottomh), leftw, height - bottomh, width - leftw - rightw, bottomh, cmp);
g2.drawImage(image.getSubimage(0, toph, leftw, ih - toph - bottomh), 0, toph, leftw, height - toph - bottomh, cmp);
g2.drawImage(image.getSubimage(iw - rightw, toph, rightw, ih - toph - bottomh), width - rightw, toph, rightw, height - toph - bottomh, cmp);
g2.drawImage(image.getSubimage(0, 0, leftw, toph), 0, 0, cmp);
g2.drawImage(image.getSubimage(iw - rightw, 0, rightw, toph), width - rightw, 0, cmp);
g2.drawImage(image.getSubimage(0, ih - bottomh, leftw, bottomh), 0, height - bottomh, cmp);
g2.drawImage(image.getSubimage(iw - rightw, ih - bottomh, rightw, bottomh), width - rightw, height - bottomh, cmp);
}
g2.dispose();
}
}
class PressedImageFilter extends RGBImageFilter {
@Override public int filterRGB(int x, int y, int argb) {
int r = (int) (((argb >> 16) & 0xFF) * .6);
int g = (int) (((argb >> 8) & 0xFF) * 1d);
int b = (int) (((argb) & 0xFF) * 1d);
return (argb & 0xFF000000) | (r << 16) | (g << 8) | (b);
}
}
class RolloverImageFilter extends RGBImageFilter {
@Override public int filterRGB(int x, int y, int argb) {
int r = (int) Math.min(0xFF, ((argb >> 16) & 0xFF) * 1.0);
int g = (int) Math.min(0xFF, ((argb >> 8) & 0xFF) * 1.5);
int b = (int) Math.min(0xFF, ((argb) & 0xFF) * 1.5);
return (argb & 0xFF000000) | (r << 16) | (g << 8) | (b);
}
} |
package com.cloud.deploy;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.agent.manager.allocator.HostAllocator;
import com.cloud.api.ApiDBUtils;
import com.cloud.capacity.Capacity;
import com.cloud.capacity.CapacityManager;
import com.cloud.capacity.CapacityVO;
import com.cloud.capacity.dao.CapacityDao;
import com.cloud.capacity.dao.CapacityDaoImpl.SummedCapacity;
import com.cloud.configuration.Config;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.Pod;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.exception.InsufficientServerCapacityException;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.offering.ServiceOffering;
import com.cloud.org.Cluster;
import com.cloud.org.Grouping;
import com.cloud.resource.ResourceState;
import com.cloud.storage.DiskOfferingVO;
import com.cloud.storage.StoragePool;
import com.cloud.storage.StoragePoolHostVO;
import com.cloud.storage.StoragePoolVO;
import com.cloud.storage.Volume;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.allocator.StoragePoolAllocator;
import com.cloud.storage.dao.DiskOfferingDao;
import com.cloud.storage.dao.GuestOSCategoryDao;
import com.cloud.storage.dao.GuestOSDao;
import com.cloud.storage.dao.StoragePoolDao;
import com.cloud.storage.dao.StoragePoolHostDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.component.Adapters;
import com.cloud.utils.component.Inject;
import com.cloud.vm.DiskProfile;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao;
@Local(value=DeploymentPlanner.class)
public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
private static final Logger s_logger = Logger.getLogger(FirstFitPlanner.class);
@Inject protected HostDao _hostDao;
@Inject protected DataCenterDao _dcDao;
@Inject protected HostPodDao _podDao;
@Inject protected ClusterDao _clusterDao;
@Inject protected GuestOSDao _guestOSDao = null;
@Inject protected GuestOSCategoryDao _guestOSCategoryDao = null;
@Inject protected DiskOfferingDao _diskOfferingDao;
@Inject protected StoragePoolHostDao _poolHostDao;
@Inject protected UserVmDao _vmDao;
@Inject protected VMInstanceDao _vmInstanceDao;
@Inject protected VolumeDao _volsDao;
@Inject protected CapacityManager _capacityMgr;
@Inject protected ConfigurationDao _configDao;
@Inject protected StoragePoolDao _storagePoolDao;
@Inject protected CapacityDao _capacityDao;
@Inject(adapter=StoragePoolAllocator.class)
protected Adapters<StoragePoolAllocator> _storagePoolAllocators;
@Inject(adapter=HostAllocator.class)
protected Adapters<HostAllocator> _hostAllocators;
protected String _allocationAlgorithm = "random";
@Override
public DeployDestination plan(VirtualMachineProfile<? extends VirtualMachine> vmProfile,
DeploymentPlan plan, ExcludeList avoid)
throws InsufficientServerCapacityException {
VirtualMachine vm = vmProfile.getVirtualMachine();
DataCenter dc = _dcDao.findById(vm.getDataCenterIdToDeployIn());
//check if datacenter is in avoid set
if(avoid.shouldAvoid(dc)){
if (s_logger.isDebugEnabled()) {
s_logger.debug("DataCenter id = '"+ dc.getId() +"' provided is in avoid set, DeploymentPlanner cannot allocate the VM, returning.");
}
return null;
}
ServiceOffering offering = vmProfile.getServiceOffering();
int cpu_requested = offering.getCpu() * offering.getSpeed();
long ram_requested = offering.getRamSize() * 1024L * 1024L;
String opFactor = _configDao.getValue(Config.CPUOverprovisioningFactor.key());
float cpuOverprovisioningFactor = NumbersUtil.parseFloat(opFactor, 1);
if (s_logger.isDebugEnabled()) {
s_logger.debug("DeploymentPlanner allocation algorithm: "+_allocationAlgorithm);
s_logger.debug("Trying to allocate a host and storage pools from dc:" + plan.getDataCenterId() + ", pod:" + plan.getPodId() + ",cluster:" + plan.getClusterId() +
", requested cpu: " + cpu_requested + ", requested ram: " + ram_requested);
s_logger.debug("Is ROOT volume READY (pool already allocated)?: " + (plan.getPoolId()!=null ? "Yes": "No"));
}
if(plan.getHostId() != null){
Long hostIdSpecified = plan.getHostId();
if (s_logger.isDebugEnabled()){
s_logger.debug("DeploymentPlan has host_id specified, making no checks on this host, looks like admin test: "+hostIdSpecified);
}
HostVO host = _hostDao.findById(hostIdSpecified);
if (s_logger.isDebugEnabled()) {
if(host == null){
s_logger.debug("The specified host cannot be found");
}else{
s_logger.debug("Looking for suitable pools for this host under zone: "+host.getDataCenterId() +", pod: "+ host.getPodId()+", cluster: "+ host.getClusterId());
}
}
//search for storage under the zone, pod, cluster of the host.
DataCenterDeployment lastPlan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), hostIdSpecified, plan.getPoolId(), null);
Pair<Map<Volume, List<StoragePool>>, List<Volume>> result = findSuitablePoolsForVolumes(vmProfile, lastPlan, avoid, HostAllocator.RETURN_UPTO_ALL);
Map<Volume, List<StoragePool>> suitableVolumeStoragePools = result.first();
List<Volume> readyAndReusedVolumes = result.second();
//choose the potential pool for this VM for this host
if(!suitableVolumeStoragePools.isEmpty()){
List<Host> suitableHosts = new ArrayList<Host>();
suitableHosts.add(host);
Pair<Host, Map<Volume, StoragePool>> potentialResources = findPotentialDeploymentResources(suitableHosts, suitableVolumeStoragePools);
if(potentialResources != null){
Pod pod = _podDao.findById(host.getPodId());
Cluster cluster = _clusterDao.findById(host.getClusterId());
Map<Volume, StoragePool> storageVolMap = potentialResources.second();
// remove the reused vol<->pool from destination, since we don't have to prepare this volume.
for(Volume vol : readyAndReusedVolumes){
storageVolMap.remove(vol);
}
DeployDestination dest = new DeployDestination(dc, pod, cluster, host, storageVolMap);
s_logger.debug("Returning Deployment Destination: "+ dest);
return dest;
}
}
s_logger.debug("Cannnot deploy to specified host, returning.");
return null;
}
if (vm.getLastHostId() != null) {
s_logger.debug("This VM has last host_id specified, trying to choose the same host: " +vm.getLastHostId());
HostVO host = _hostDao.findById(vm.getLastHostId());
if(host == null){
s_logger.debug("The last host of this VM cannot be found");
}else{
if (host.getStatus() == Status.Up && host.getResourceState() == ResourceState.Enabled) {
if(_capacityMgr.checkIfHostHasCapacity(host.getId(), cpu_requested, ram_requested, true, cpuOverprovisioningFactor, true)){
s_logger.debug("The last host of this VM is UP and has enough capacity");
s_logger.debug("Now checking for suitable pools under zone: "+host.getDataCenterId() +", pod: "+ host.getPodId()+", cluster: "+ host.getClusterId());
//search for storage under the zone, pod, cluster of the last host.
DataCenterDeployment lastPlan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), host.getId(), plan.getPoolId(), null);
Pair<Map<Volume, List<StoragePool>>, List<Volume>> result = findSuitablePoolsForVolumes(vmProfile, lastPlan, avoid, HostAllocator.RETURN_UPTO_ALL);
Map<Volume, List<StoragePool>> suitableVolumeStoragePools = result.first();
List<Volume> readyAndReusedVolumes = result.second();
//choose the potential pool for this VM for this host
if(!suitableVolumeStoragePools.isEmpty()){
List<Host> suitableHosts = new ArrayList<Host>();
suitableHosts.add(host);
Pair<Host, Map<Volume, StoragePool>> potentialResources = findPotentialDeploymentResources(suitableHosts, suitableVolumeStoragePools);
if(potentialResources != null){
Pod pod = _podDao.findById(host.getPodId());
Cluster cluster = _clusterDao.findById(host.getClusterId());
Map<Volume, StoragePool> storageVolMap = potentialResources.second();
// remove the reused vol<->pool from destination, since we don't have to prepare this volume.
for(Volume vol : readyAndReusedVolumes){
storageVolMap.remove(vol);
}
DeployDestination dest = new DeployDestination(dc, pod, cluster, host, storageVolMap);
s_logger.debug("Returning Deployment Destination: "+ dest);
return dest;
}
}
}else{
s_logger.debug("The last host of this VM does not have enough capacity");
}
}else{
s_logger.debug("The last host of this VM is not UP or is not enabled, host status is: "+host.getStatus().name() + ", host resource state is: "+host.getResourceState());
}
}
s_logger.debug("Cannot choose the last host to deploy this VM ");
}
List<Long> clusterList = new ArrayList<Long>();
if (plan.getClusterId() != null) {
Long clusterIdSpecified = plan.getClusterId();
s_logger.debug("Searching resources only under specified Cluster: "+ clusterIdSpecified);
ClusterVO cluster = _clusterDao.findById(plan.getClusterId());
if (cluster != null ){
clusterList.add(clusterIdSpecified);
return checkClustersforDestination(clusterList, vmProfile, plan, avoid, dc);
}else{
s_logger.debug("The specified cluster cannot be found, returning.");
avoid.addCluster(plan.getClusterId());
return null;
}
}else if (plan.getPodId() != null) {
//consider clusters under this pod only
Long podIdSpecified = plan.getPodId();
s_logger.debug("Searching resources only under specified Pod: "+ podIdSpecified);
HostPodVO pod = _podDao.findById(podIdSpecified);
if (pod != null) {
DeployDestination dest = scanClustersForDestinationInZoneOrPod(podIdSpecified, false, vmProfile, plan, avoid);
if(dest == null){
avoid.addPod(plan.getPodId());
}
return dest;
} else {
s_logger.debug("The specified Pod cannot be found, returning.");
avoid.addPod(plan.getPodId());
return null;
}
}else{
s_logger.debug("Searching all possible resources under this Zone: "+ plan.getDataCenterId());
boolean applyAllocationAtPods = Boolean.parseBoolean(_configDao.getValue(Config.ApplyAllocationAlgorithmToPods.key()));
if(applyAllocationAtPods){
//start scan at all pods under this zone.
return scanPodsForDestination(vmProfile, plan, avoid);
}else{
//start scan at clusters under this zone.
return scanClustersForDestinationInZoneOrPod(plan.getDataCenterId(), true, vmProfile, plan, avoid);
}
}
}
private DeployDestination scanPodsForDestination(VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan, ExcludeList avoid){
ServiceOffering offering = vmProfile.getServiceOffering();
int requiredCpu = offering.getCpu() * offering.getSpeed();
long requiredRam = offering.getRamSize() * 1024L * 1024L;
String opFactor = _configDao.getValue(Config.CPUOverprovisioningFactor.key());
float cpuOverprovisioningFactor = NumbersUtil.parseFloat(opFactor, 1);
//list pods under this zone by cpu and ram capacity
List<Long> prioritizedPodIds = new ArrayList<Long>();
Pair<List<Long>, Map<Long, Double>> podCapacityInfo = listPodsByCapacity(plan.getDataCenterId(), requiredCpu, requiredRam, cpuOverprovisioningFactor);
List<Long> podsWithCapacity = podCapacityInfo.first();
if(!podsWithCapacity.isEmpty()){
if(avoid.getPodsToAvoid() != null){
if (s_logger.isDebugEnabled()) {
s_logger.debug("Removing from the podId list these pods from avoid set: "+ avoid.getPodsToAvoid());
}
podsWithCapacity.removeAll(avoid.getPodsToAvoid());
}
List<Long> disabledPods = listDisabledPods(plan.getDataCenterId());
if(!disabledPods.isEmpty()){
if (s_logger.isDebugEnabled()) {
s_logger.debug("Removing from the podId list these pods that are disabled: "+ disabledPods);
}
podsWithCapacity.removeAll(disabledPods);
}
}else{
if (s_logger.isDebugEnabled()) {
s_logger.debug("No pods found having a host with enough capacity, returning.");
}
return null;
}
if(!podsWithCapacity.isEmpty()){
prioritizedPodIds = reorderPods(podCapacityInfo, vmProfile, plan);
//loop over pods
for(Long podId : prioritizedPodIds){
s_logger.debug("Checking resources under Pod: "+podId);
DeployDestination dest = scanClustersForDestinationInZoneOrPod(podId, false, vmProfile, plan, avoid);
if(dest != null){
return dest;
}
avoid.addPod(podId);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("No Pods found for destination, returning.");
}
return null;
}else{
if (s_logger.isDebugEnabled()) {
s_logger.debug("No Pods found after removing disabled pods and pods in avoid list, returning.");
}
return null;
}
}
private DeployDestination scanClustersForDestinationInZoneOrPod(long id, boolean isZone, VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan, ExcludeList avoid){
VirtualMachine vm = vmProfile.getVirtualMachine();
ServiceOffering offering = vmProfile.getServiceOffering();
DataCenter dc = _dcDao.findById(vm.getDataCenterIdToDeployIn());
int requiredCpu = offering.getCpu() * offering.getSpeed();
long requiredRam = offering.getRamSize() * 1024L * 1024L;
String opFactor = _configDao.getValue(Config.CPUOverprovisioningFactor.key());
float cpuOverprovisioningFactor = NumbersUtil.parseFloat(opFactor, 1);
//list clusters under this zone by cpu and ram capacity
Pair<List<Long>, Map<Long, Double>> clusterCapacityInfo = listClustersByCapacity(id, requiredCpu, requiredRam, avoid, isZone, cpuOverprovisioningFactor);
List<Long> prioritizedClusterIds = clusterCapacityInfo.first();
if(!prioritizedClusterIds.isEmpty()){
if(avoid.getClustersToAvoid() != null){
if (s_logger.isDebugEnabled()) {
s_logger.debug("Removing from the clusterId list these clusters from avoid set: "+ avoid.getClustersToAvoid());
}
prioritizedClusterIds.removeAll(avoid.getClustersToAvoid());
}
List<Long> disabledClusters = new ArrayList<Long>();
if(isZone){
disabledClusters = listDisabledClusters(plan.getDataCenterId(), null);
}else{
disabledClusters = listDisabledClusters(plan.getDataCenterId(), id);
}
if(!disabledClusters.isEmpty()){
if (s_logger.isDebugEnabled()) {
s_logger.debug("Removing from the clusterId list these clusters that are disabled/clusters under disabled pods: "+ disabledClusters);
}
prioritizedClusterIds.removeAll(disabledClusters);
}
}else{
if (s_logger.isDebugEnabled()) {
s_logger.debug("No clusters found having a host with enough capacity, returning.");
}
return null;
}
if(!prioritizedClusterIds.isEmpty()){
List<Long> clusterList = reorderClusters(id, isZone, clusterCapacityInfo, vmProfile, plan);
return checkClustersforDestination(clusterList, vmProfile, plan, avoid, dc);
}else{
if (s_logger.isDebugEnabled()) {
s_logger.debug("No clusters found after removing disabled clusters and clusters in avoid list, returning.");
}
return null;
}
}
/**
* This method should reorder the given list of Cluster Ids by applying any necessary heuristic
* for this planner
* For FirstFitPlanner there is no specific heuristic to be applied
* other than the capacity based ordering which is done by default.
* @return List<Long> ordered list of Cluster Ids
*/
protected List<Long> reorderClusters(long id, boolean isZone, Pair<List<Long>, Map<Long, Double>> clusterCapacityInfo, VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan){
List<Long> reordersClusterIds = clusterCapacityInfo.first();
return reordersClusterIds;
}
/**
* This method should reorder the given list of Pod Ids by applying any necessary heuristic
* for this planner
* For FirstFitPlanner there is no specific heuristic to be applied
* other than the capacity based ordering which is done by default.
* @return List<Long> ordered list of Pod Ids
*/
protected List<Long> reorderPods(Pair<List<Long>, Map<Long, Double>> podCapacityInfo, VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan){
List<Long> podIdsByCapacity = podCapacityInfo.first();
return podIdsByCapacity;
}
private List<Long> listDisabledClusters(long zoneId, Long podId){
List<Long> disabledClusters = _clusterDao.listDisabledClusters(zoneId, podId);
if(podId == null){
//list all disabled clusters under this zone + clusters under any disabled pod of this zone
List<Long> clustersWithDisabledPods = _clusterDao.listClustersWithDisabledPods(zoneId);
disabledClusters.addAll(clustersWithDisabledPods);
}
return disabledClusters;
}
private List<Long> listDisabledPods(long zoneId){
List<Long> disabledPods = _podDao.listDisabledPods(zoneId);
return disabledPods;
}
private Map<Short,Float> getCapacityThresholdMap(){
// Lets build this real time so that the admin wont have to restart MS if he changes these values
Map<Short,Float> disableThresholdMap = new HashMap<Short, Float>();
String cpuDisableThresholdString = _configDao.getValue(Config.CPUCapacityDisableThreshold.key());
float cpuDisableThreshold = NumbersUtil.parseFloat(cpuDisableThresholdString, 0.85F);
disableThresholdMap.put(Capacity.CAPACITY_TYPE_CPU, cpuDisableThreshold);
String memoryDisableThresholdString = _configDao.getValue(Config.MemoryCapacityDisableThreshold.key());
float memoryDisableThreshold = NumbersUtil.parseFloat(memoryDisableThresholdString, 0.85F);
disableThresholdMap.put(Capacity.CAPACITY_TYPE_MEMORY, memoryDisableThreshold);
return disableThresholdMap;
}
private List<Short> getCapacitiesForCheckingThreshold(){
List<Short> capacityList = new ArrayList<Short>();
capacityList.add(Capacity.CAPACITY_TYPE_CPU);
capacityList.add(Capacity.CAPACITY_TYPE_MEMORY);
return capacityList;
}
private void removeClustersCrossingThreshold(List<Long> clusterList, ExcludeList avoid, VirtualMachineProfile<? extends VirtualMachine> vmProfile){
Map<Short,Float> capacityThresholdMap = getCapacityThresholdMap();
List<Short> capacityList = getCapacitiesForCheckingThreshold();
List<Long> clustersCrossingThreshold = new ArrayList<Long>();
ServiceOffering offering = vmProfile.getServiceOffering();
int cpu_requested = offering.getCpu() * offering.getSpeed();
long ram_requested = offering.getRamSize() * 1024L * 1024L;
// Iterate over the cluster List and check for each cluster whether it breaks disable threshold for any of the capacity types
for (Long clusterId : clusterList){
for(short capacity : capacityList){
List<SummedCapacity> summedCapacityList = _capacityDao.findCapacityBy(new Integer(capacity), null, null, clusterId);
if (summedCapacityList != null && summedCapacityList.size() != 0 && summedCapacityList.get(0).getTotalCapacity() != 0){
double used = (double)(summedCapacityList.get(0).getUsedCapacity() + summedCapacityList.get(0).getReservedCapacity());
double total = summedCapacityList.get(0).getTotalCapacity();
if (capacity == Capacity.CAPACITY_TYPE_CPU){
total = total * ApiDBUtils.getCpuOverprovisioningFactor();
used = used + cpu_requested;
}else{
used = used + ram_requested;
}
double usedPercentage = used/total;
if ( usedPercentage > capacityThresholdMap.get(capacity)){
avoid.addCluster(clusterId);
clustersCrossingThreshold.add(clusterId);
s_logger.debug("Cannot allocate cluster " + clusterId + " for vm creation since its allocated percentage: " +usedPercentage +
" will cross the disable capacity threshold: " + capacityThresholdMap.get(capacity) + " for capacity Type : " + capacity + ", skipping this cluster");
break;
}
}
}
}
clusterList.removeAll(clustersCrossingThreshold);
}
private DeployDestination checkClustersforDestination(List<Long> clusterList, VirtualMachineProfile<? extends VirtualMachine> vmProfile,
DeploymentPlan plan, ExcludeList avoid, DataCenter dc){
if (s_logger.isTraceEnabled()) {
s_logger.trace("ClusterId List to consider: " + clusterList);
}
removeClustersCrossingThreshold(clusterList, avoid, vmProfile);
for(Long clusterId : clusterList){
Cluster clusterVO = _clusterDao.findById(clusterId);
if (clusterVO.getHypervisorType() != vmProfile.getHypervisorType()) {
s_logger.debug("Cluster: "+clusterId + " has HyperVisorType that does not match the VM, skipping this cluster");
avoid.addCluster(clusterVO.getId());
continue;
}
s_logger.debug("Checking resources in Cluster: "+clusterId + " under Pod: "+clusterVO.getPodId());
//search for resources(hosts and storage) under this zone, pod, cluster.
DataCenterDeployment potentialPlan = new DataCenterDeployment(plan.getDataCenterId(), clusterVO.getPodId(), clusterVO.getId(), null, plan.getPoolId(), null);
//find suitable hosts under this cluster, need as many hosts as we get.
List<Host> suitableHosts = findSuitableHosts(vmProfile, potentialPlan, avoid, HostAllocator.RETURN_UPTO_ALL);
//if found suitable hosts in this cluster, find suitable storage pools for each volume of the VM
if(suitableHosts != null && !suitableHosts.isEmpty()){
if (vmProfile.getHypervisorType() == HypervisorType.BareMetal) {
Pod pod = _podDao.findById(clusterVO.getPodId());
DeployDestination dest = new DeployDestination(dc, pod, clusterVO, suitableHosts.get(0));
return dest;
}
Pair<Map<Volume, List<StoragePool>>, List<Volume>> result = findSuitablePoolsForVolumes(vmProfile, potentialPlan, avoid, StoragePoolAllocator.RETURN_UPTO_ALL);
Map<Volume, List<StoragePool>> suitableVolumeStoragePools = result.first();
List<Volume> readyAndReusedVolumes = result.second();
//choose the potential host and pool for the VM
if(!suitableVolumeStoragePools.isEmpty()){
Pair<Host, Map<Volume, StoragePool>> potentialResources = findPotentialDeploymentResources(suitableHosts, suitableVolumeStoragePools);
if(potentialResources != null){
Pod pod = _podDao.findById(clusterVO.getPodId());
Host host = _hostDao.findById(potentialResources.first().getId());
Map<Volume, StoragePool> storageVolMap = potentialResources.second();
// remove the reused vol<->pool from destination, since we don't have to prepare this volume.
for(Volume vol : readyAndReusedVolumes){
storageVolMap.remove(vol);
}
DeployDestination dest = new DeployDestination(dc, pod, clusterVO, host, storageVolMap );
s_logger.debug("Returning Deployment Destination: "+ dest);
return dest;
}
}else{
s_logger.debug("No suitable storagePools found under this Cluster: "+clusterId);
}
}else{
s_logger.debug("No suitable hosts found under this Cluster: "+clusterId);
}
avoid.addCluster(clusterVO.getId());
}
s_logger.debug("Could not find suitable Deployment Destination for this VM under any clusters, returning. ");
return null;
}
protected Pair<List<Long>, Map<Long, Double>> listClustersByCapacity(long id, int requiredCpu, long requiredRam, ExcludeList avoid, boolean isZone, float cpuOverprovisioningFactor){
//look at the aggregate available cpu and ram per cluster
//although an aggregate value may be false indicator that a cluster can host a vm, it will at the least eliminate those clusters which definitely cannot
//we need clusters having enough cpu AND RAM to host this particular VM and order them by aggregate cluster capacity
if (s_logger.isDebugEnabled()) {
s_logger.debug("Listing clusters in order of aggregate capacity, that have (atleast one host with) enough CPU and RAM capacity under this "+(isZone ? "Zone: " : "Pod: " )+id);
}
String capacityTypeToOrder = _configDao.getValue(Config.HostCapacityTypeToOrderClusters.key());
short capacityType = CapacityVO.CAPACITY_TYPE_CPU;
if("RAM".equalsIgnoreCase(capacityTypeToOrder)){
capacityType = CapacityVO.CAPACITY_TYPE_MEMORY;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("CPUOverprovisioningFactor considered: " + cpuOverprovisioningFactor);
}
List<Long> clusterIdswithEnoughCapacity = _capacityDao.listClustersInZoneOrPodByHostCapacities(id, requiredCpu, requiredRam, capacityType, isZone, cpuOverprovisioningFactor);
if (s_logger.isTraceEnabled()) {
s_logger.trace("ClusterId List having enough CPU and RAM capacity: " + clusterIdswithEnoughCapacity);
}
Pair<List<Long>, Map<Long, Double>> result = _capacityDao.orderClustersByAggregateCapacity(id, capacityType, isZone, cpuOverprovisioningFactor);
List<Long> clusterIdsOrderedByAggregateCapacity = result.first();
//only keep the clusters that have enough capacity to host this VM
if (s_logger.isTraceEnabled()) {
s_logger.trace("ClusterId List in order of aggregate capacity: " + clusterIdsOrderedByAggregateCapacity);
}
clusterIdsOrderedByAggregateCapacity.retainAll(clusterIdswithEnoughCapacity);
if (s_logger.isTraceEnabled()) {
s_logger.trace("ClusterId List having enough CPU and RAM capacity & in order of aggregate capacity: " + clusterIdsOrderedByAggregateCapacity);
}
return result;
}
protected Pair<List<Long>, Map<Long, Double>> listPodsByCapacity(long zoneId, int requiredCpu, long requiredRam, float cpuOverprovisioningFactor){
//look at the aggregate available cpu and ram per pod
//although an aggregate value may be false indicator that a pod can host a vm, it will at the least eliminate those pods which definitely cannot
//we need pods having enough cpu AND RAM to host this particular VM and order them by aggregate pod capacity
if (s_logger.isDebugEnabled()) {
s_logger.debug("Listing pods in order of aggregate capacity, that have (atleast one host with) enough CPU and RAM capacity under this Zone: "+zoneId);
}
String capacityTypeToOrder = _configDao.getValue(Config.HostCapacityTypeToOrderClusters.key());
short capacityType = CapacityVO.CAPACITY_TYPE_CPU;
if("RAM".equalsIgnoreCase(capacityTypeToOrder)){
capacityType = CapacityVO.CAPACITY_TYPE_MEMORY;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("CPUOverprovisioningFactor considered: " + cpuOverprovisioningFactor);
}
List<Long> podIdswithEnoughCapacity = _capacityDao.listPodsByHostCapacities(zoneId, requiredCpu, requiredRam, capacityType, cpuOverprovisioningFactor);
if (s_logger.isTraceEnabled()) {
s_logger.trace("PodId List having enough CPU and RAM capacity: " + podIdswithEnoughCapacity);
}
Pair<List<Long>, Map<Long, Double>> result = _capacityDao.orderPodsByAggregateCapacity(zoneId, capacityType, cpuOverprovisioningFactor);
List<Long> podIdsOrderedByAggregateCapacity = result.first();
//only keep the clusters that have enough capacity to host this VM
if (s_logger.isTraceEnabled()) {
s_logger.trace("PodId List in order of aggregate capacity: " + podIdsOrderedByAggregateCapacity);
}
podIdsOrderedByAggregateCapacity.retainAll(podIdswithEnoughCapacity);
if (s_logger.isTraceEnabled()) {
s_logger.trace("PodId List having enough CPU and RAM capacity & in order of aggregate capacity: " + podIdsOrderedByAggregateCapacity);
}
return result;
}
protected Pair<Host, Map<Volume, StoragePool>> findPotentialDeploymentResources(List<Host> suitableHosts, Map<Volume, List<StoragePool>> suitableVolumeStoragePools){
s_logger.debug("Trying to find a potenial host and associated storage pools from the suitable host/pool lists for this VM");
boolean hostCanAccessPool = false;
Map<Volume, StoragePool> storage = new HashMap<Volume, StoragePool>();
for(Host potentialHost : suitableHosts){
for(Volume vol : suitableVolumeStoragePools.keySet()){
s_logger.debug("Checking if host: "+potentialHost.getId() +" can access any suitable storage pool for volume: "+ vol.getVolumeType());
List<StoragePool> volumePoolList = suitableVolumeStoragePools.get(vol);
hostCanAccessPool = false;
for(StoragePool potentialSPool : volumePoolList){
if(hostCanAccessSPool(potentialHost, potentialSPool)){
storage.put(vol, potentialSPool);
hostCanAccessPool = true;
break;
}
}
if(!hostCanAccessPool){
break;
}
}
if(hostCanAccessPool){
s_logger.debug("Found a potential host " + "id: "+potentialHost.getId() + " name: " +potentialHost.getName()+ " and associated storage pools for this VM");
return new Pair<Host, Map<Volume, StoragePool>>(potentialHost, storage);
}
}
s_logger.debug("Could not find a potential host that has associated storage pools from the suitable host/pool lists for this VM");
return null;
}
protected boolean hostCanAccessSPool(Host host, StoragePool pool){
boolean hostCanAccessSPool = false;
StoragePoolHostVO hostPoolLinkage = _poolHostDao.findByPoolHost(pool.getId(), host.getId());
if(hostPoolLinkage != null){
hostCanAccessSPool = true;
}
s_logger.debug("Host: "+ host.getId() + (hostCanAccessSPool ?" can" : " cannot") + " access pool: "+ pool.getId());
return hostCanAccessSPool;
}
protected List<Host> findSuitableHosts(VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan, ExcludeList avoid, int returnUpTo){
List<Host> suitableHosts = new ArrayList<Host>();
Enumeration<HostAllocator> enHost = _hostAllocators.enumeration();
s_logger.debug("Calling HostAllocators to find suitable hosts");
while (enHost.hasMoreElements()) {
final HostAllocator allocator = enHost.nextElement();
suitableHosts = allocator.allocateTo(vmProfile, plan, Host.Type.Routing, avoid, returnUpTo);
if (suitableHosts != null && !suitableHosts.isEmpty()) {
break;
}
}
if(suitableHosts.isEmpty()){
s_logger.debug("No suitable hosts found");
}
return suitableHosts;
}
protected Pair<Map<Volume, List<StoragePool>>, List<Volume>> findSuitablePoolsForVolumes(VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan, ExcludeList avoid, int returnUpTo){
List<VolumeVO> volumesTobeCreated = _volsDao.findUsableVolumesForInstance(vmProfile.getId());
Map<Volume, List<StoragePool>> suitableVolumeStoragePools = new HashMap<Volume, List<StoragePool>>();
List<Volume> readyAndReusedVolumes = new ArrayList<Volume>();
//for each volume find list of suitable storage pools by calling the allocators
for (VolumeVO toBeCreated : volumesTobeCreated) {
s_logger.debug("Checking suitable pools for volume (Id, Type): ("+toBeCreated.getId() +"," +toBeCreated.getVolumeType().name() + ")");
//If the plan specifies a poolId, it means that this VM's ROOT volume is ready and the pool should be reused.
//In this case, also check if rest of the volumes are ready and can be reused.
if(plan.getPoolId() != null){
if (toBeCreated.getState() == Volume.State.Ready && toBeCreated.getPoolId() != null) {
s_logger.debug("Volume is in READY state and has pool already allocated, checking if pool can be reused, poolId: "+toBeCreated.getPoolId());
List<StoragePool> suitablePools = new ArrayList<StoragePool>();
StoragePoolVO pool = _storagePoolDao.findById(toBeCreated.getPoolId());
if(!pool.isInMaintenance()){
if(!avoid.shouldAvoid(pool)){
long exstPoolDcId = pool.getDataCenterId();
long exstPoolPodId = pool.getPodId() != null ? pool.getPodId() : -1;
long exstPoolClusterId = pool.getClusterId() != null ? pool.getClusterId() : -1;
if(plan.getDataCenterId() == exstPoolDcId && plan.getPodId() == exstPoolPodId && plan.getClusterId() == exstPoolClusterId){
s_logger.debug("Planner need not allocate a pool for this volume since its READY");
suitablePools.add(pool);
suitableVolumeStoragePools.put(toBeCreated, suitablePools);
readyAndReusedVolumes.add(toBeCreated);
continue;
}else{
s_logger.debug("Pool of the volume does not fit the specified plan, need to reallocate a pool for this volume");
}
}else{
s_logger.debug("Pool of the volume is in avoid set, need to reallocate a pool for this volume");
}
}else{
s_logger.debug("Pool of the volume is in maintenance, need to reallocate a pool for this volume");
}
}
}
if(s_logger.isDebugEnabled()){
s_logger.debug("We need to allocate new storagepool for this volume");
}
if(!isEnabledForAllocation(plan.getDataCenterId(), plan.getPodId(), plan.getClusterId())){
if(s_logger.isDebugEnabled()){
s_logger.debug("Cannot allocate new storagepool for this volume in this cluster, allocation state is disabled");
s_logger.debug("Cannot deploy to this specified plan, allocation state is disabled, returning.");
}
//Cannot find suitable storage pools under this cluster for this volume since allocation_state is disabled.
//- remove any suitable pools found for other volumes.
//All volumes should get suitable pools under this cluster; else we cant use this cluster.
suitableVolumeStoragePools.clear();
break;
}
s_logger.debug("Calling StoragePoolAllocators to find suitable pools");
DiskOfferingVO diskOffering = _diskOfferingDao.findById(toBeCreated.getDiskOfferingId());
DiskProfile diskProfile = new DiskProfile(toBeCreated, diskOffering, vmProfile.getHypervisorType());
boolean useLocalStorage = false;
if (vmProfile.getType() != VirtualMachine.Type.User) {
String ssvmUseLocalStorage = _configDao.getValue(Config.SystemVMUseLocalStorage.key());
if (ssvmUseLocalStorage.equalsIgnoreCase("true")) {
useLocalStorage = true;
}
} else {
useLocalStorage = diskOffering.getUseLocalStorage();
// TODO: this is a hacking fix for the problem of deploy ISO-based VM on local storage
// when deploying VM based on ISO, we have a service offering and an additional disk offering, use-local storage flag is actually
// saved in service offering, overrde the flag from service offering when it is a ROOT disk
if(!useLocalStorage && vmProfile.getServiceOffering().getUseLocalStorage()) {
if(toBeCreated.getVolumeType() == Volume.Type.ROOT)
useLocalStorage = true;
}
}
diskProfile.setUseLocalStorage(useLocalStorage);
boolean foundPotentialPools = false;
Enumeration<StoragePoolAllocator> enPool = _storagePoolAllocators.enumeration();
while (enPool.hasMoreElements()) {
final StoragePoolAllocator allocator = enPool.nextElement();
final List<StoragePool> suitablePools = allocator.allocateToPool(diskProfile, vmProfile, plan, avoid, returnUpTo);
if (suitablePools != null && !suitablePools.isEmpty()) {
suitableVolumeStoragePools.put(toBeCreated, suitablePools);
foundPotentialPools = true;
break;
}
}
if(!foundPotentialPools){
s_logger.debug("No suitable pools found for volume: "+toBeCreated +" under cluster: "+plan.getClusterId());
//No suitable storage pools found under this cluster for this volume. - remove any suitable pools found for other volumes.
//All volumes should get suitable pools under this cluster; else we cant use this cluster.
suitableVolumeStoragePools.clear();
break;
}
}
if(suitableVolumeStoragePools.isEmpty()){
s_logger.debug("No suitable pools found");
}
return new Pair<Map<Volume, List<StoragePool>>, List<Volume>>(suitableVolumeStoragePools, readyAndReusedVolumes);
}
@Override
public boolean check(VirtualMachineProfile<? extends VirtualMachine> vm, DeploymentPlan plan,
DeployDestination dest, ExcludeList exclude) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean canHandle(VirtualMachineProfile<? extends VirtualMachine> vm, DeploymentPlan plan, ExcludeList avoid) {
if(vm.getHypervisorType() != HypervisorType.BareMetal){
//check the allocation strategy
if (_allocationAlgorithm != null && (_allocationAlgorithm.equals(AllocationAlgorithm.random.toString()) || _allocationAlgorithm.equals(AllocationAlgorithm.firstfit.toString()))) {
return true;
}
}
return false;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
super.configure(name, params);
_allocationAlgorithm = _configDao.getValue(Config.VmAllocationAlgorithm.key());
return true;
}
private boolean isEnabledForAllocation(long zoneId, Long podId, Long clusterId){
// Check if the zone exists in the system
DataCenterVO zone = _dcDao.findById(zoneId);
if(zone != null && Grouping.AllocationState.Disabled == zone.getAllocationState()){
s_logger.info("Zone is currently disabled, cannot allocate to this zone: "+ zoneId);
return false;
}
Pod pod = _podDao.findById(podId);
if(pod != null && Grouping.AllocationState.Disabled == pod.getAllocationState()){
s_logger.info("Pod is currently disabled, cannot allocate to this pod: "+ podId);
return false;
}
Cluster cluster = _clusterDao.findById(clusterId);
if(cluster != null && Grouping.AllocationState.Disabled == cluster.getAllocationState()){
s_logger.info("Cluster is currently disabled, cannot allocate to this cluster: "+ clusterId);
return false;
}
return true;
}
} |
package verification.platu.logicAnalysis;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Stack;
import javax.swing.JOptionPane;
import lpn.parser.LhpnFile;
import lpn.parser.Transition;
import main.Gui;
import verification.platu.MDD.MDT;
import verification.platu.MDD.Mdd;
import verification.platu.MDD.mddNode;
import verification.platu.common.IndexObjMap;
import verification.platu.lpn.LPNTranRelation;
import verification.platu.lpn.LpnTranList;
import verification.platu.main.Options;
import verification.platu.partialOrders.DependentSet;
import verification.platu.partialOrders.DependentSetComparator;
import verification.platu.partialOrders.LpnTransitionPair;
import verification.platu.partialOrders.StaticSets;
import verification.platu.project.PrjState;
import verification.platu.stategraph.State;
import verification.platu.stategraph.StateGraph;
import verification.timed_state_exploration.zoneProject.EventSet;
import verification.timed_state_exploration.zoneProject.TimedPrjState;
import verification.timed_state_exploration.zoneProject.StateSet;
public class Analysis {
private LinkedList<Transition> traceCex;
protected Mdd mddMgr = null;
private HashMap<LpnTransitionPair, HashSet<LpnTransitionPair>> cachedNecessarySets = new HashMap<LpnTransitionPair, HashSet<LpnTransitionPair>>();
private String PORdebugFileName;
private FileWriter PORdebugFileStream;
private BufferedWriter PORdebugBufferedWriter;
public Analysis(StateGraph[] lpnList, State[] initStateArray, LPNTranRelation lpnTranRelation, String method) {
traceCex = new LinkedList<Transition>();
mddMgr = new Mdd(lpnList.length);
if (method.equals("dfs")) {
//if (Options.getPOR().equals("off")) {
//this.search_dfs(lpnList, initStateArray);
//this.search_dfs_mdd_1(lpnList, initStateArray);
//this.search_dfs_mdd_2(lpnList, initStateArray);
//else
// this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "state");
}
else if (method.equals("bfs")==true)
this.search_bfs(lpnList, initStateArray);
else if (method == "dfs_noDisabling")
//this.search_dfs_noDisabling(lpnList, initStateArray);
this.search_dfs_noDisabling_fireOrder(lpnList, initStateArray);
}
/**
* This constructor performs dfs.
* @param lpnList
*/
public Analysis(StateGraph[] lpnList){
traceCex = new LinkedList<Transition>();
mddMgr = new Mdd(lpnList.length);
// if (method.equals("dfs")) {
// //if (Options.getPOR().equals("off")) {
// this.search_dfs(lpnList, initStateArray, applyPOR);
// //this.search_dfs_mdd_1(lpnList, initStateArray);
// //this.search_dfs_mdd_2(lpnList, initStateArray);
// //else
// // this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "state");
// else if (method.equals("bfs")==true)
// this.search_bfs(lpnList, initStateArray);
// else if (method == "dfs_noDisabling")
// //this.search_dfs_noDisabling(lpnList, initStateArray);
// this.search_dfs_noDisabling_fireOrder(lpnList, initStateArray);
}
/**
* Recursively find all reachable project states.
*/
int iterations = 0;
int stack_depth = 0;
int max_stack_depth = 0;
public void search_recursive(final StateGraph[] lpnList,
final State[] curPrjState,
final ArrayList<LinkedList<Transition>> enabledList,
HashSet<PrjState> stateTrace) {
int lpnCnt = lpnList.length;
HashSet<PrjState> prjStateSet = new HashSet<PrjState>();
stack_depth++;
if (stack_depth > max_stack_depth)
max_stack_depth = stack_depth;
iterations++;
if (iterations % 50000 == 0)
System.out.println("iterations: " + iterations
+ ", # of prjStates found: " + prjStateSet.size()
+ ", max_stack_depth: " + max_stack_depth);
for (int index = 0; index < lpnCnt; index++) {
LinkedList<Transition> curEnabledSet = enabledList.get(index);
if (curEnabledSet == null)
continue;
for (Transition firedTran : curEnabledSet) {
// while(curEnabledSet.size() != 0) {
// LPNTran firedTran = curEnabledSet.removeFirst();
// TODO: (check) Not sure if lpnList[index] is correct
State[] nextStateArray = lpnList[index].fire(lpnList, curPrjState, firedTran);
// Add nextPrjState into prjStateSet
// If nextPrjState has been traversed before, skip to the next
// enabled transition.
PrjState nextPrjState = new PrjState(nextStateArray);
if (stateTrace.contains(nextPrjState) == true)
;// System.out.println("found a cycle");
if (prjStateSet.add(nextPrjState) == false) {
continue;
}
// Get the list of enabled transition sets, and call
// findsg_recursive.
ArrayList<LinkedList<Transition>> nextEnabledList = new ArrayList<LinkedList<Transition>>();
for (int i = 0; i < lpnCnt; i++) {
if (curPrjState[i] != nextStateArray[i]) {
StateGraph Lpn_tmp = lpnList[i];
nextEnabledList.add(i, Lpn_tmp.getEnabled(nextStateArray[i]));// firedTran,
// enabledList.get(i),
// false));
} else {
nextEnabledList.add(i, enabledList.get(i));
}
}
stateTrace.add(nextPrjState);
search_recursive(lpnList, nextStateArray, nextEnabledList,
stateTrace);
stateTrace.remove(nextPrjState);
}
}
}
/**
* An iterative implement of findsg_recursive().
*
* @param sgList
* @param start
* @param curLocalStateArray
* @param enabledArray
*/
public StateGraph[] search_dfs(final StateGraph[] sgList, final State[] initStateArray) {
System.out.println("---> calling function search_dfs");
double peakUsedMem = 0;
double peakTotalMem = 0;
boolean failure = false;
int tranFiringCnt = 0;
int totalStates = 1;
int numLpns = sgList.length;
//Stack<State[]> stateStack = new Stack<State[]>();
HashSet<PrjState> stateStack = new HashSet<PrjState>();
Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>();
Stack<Integer> curIndexStack = new Stack<Integer>();
//HashSet<PrjState> prjStateSet = new HashSet<PrjState>();
// Set of PrjStates that have been seen before. Set class documentation
// for how it behaves. Timing Change.
StateSet prjStateSet = new StateSet();
PrjState initPrjState;
// Create the appropriate type for the PrjState depending on whether timing is
// being used or not. Timing Change.
if(!Options.getTimingAnalysisFlag()){
// If not doing timing.
initPrjState = new PrjState(initStateArray);
}
else{
// If timing is enabled.
initPrjState = new TimedPrjState(initStateArray);
// Set the initial values of the inequality variables.
((TimedPrjState) initPrjState).updateInequalityVariables();
}
prjStateSet.add(initPrjState);
PrjState stateStackTop = initPrjState;
if (Options.getDebugMode()) {
System.out.println("%%%%%%% stateStackTop %%%%%%%%");
printStateArray(stateStackTop.toStateArray());
}
stateStack.add(stateStackTop);
constructDstLpnList(sgList);
if (Options.getDebugMode())
printDstLpnList(sgList);
boolean init = true;
LpnTranList initEnabled;
if(!Options.getTimingAnalysisFlag()){ // Timing Change.
initEnabled = sgList[0].getEnabled(initStateArray[0], init);
}
else
{
// When timing is enabled, it is the project state that will determine
// what is enabled since it contains the zone. This indicates the zeroth zone
// contained in the project and the zeroth LPN to get the transitions from.
initEnabled = ((TimedPrjState) stateStackTop).getPossibleEvents(0, 0);
}
lpnTranStack.push(initEnabled.clone());
curIndexStack.push(0);
init = false;
if (Options.getDebugMode()) {
System.out.println("call getEnabled on initStateArray at 0: ");
System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
printTransitionSet(initEnabled, "");
}
boolean memExceedsLimit = false;
main_while_loop: while (failure == false && stateStack.size() != 0) {
if (Options.getDebugMode())
System.out.println("$$$$$$$$$$$ loop begins $$$$$$$$$$");
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
if (iterations % 100000 == 0) {
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStates
+ ", stack_depth: " + stateStack.size()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
}
if (!memExceedsLimit && Options.getMemUpperBoundFlag() && iterations % 100 == 0) {
if (curUsedMem > Options.getMemUpperBound()) {
System.out.println("******* Used memory exceeds memory upper bound (" + (float)Options.getMemUpperBound()/1000000 + "MB) *******");
System.out.println("******* Used memory = " + (float)curUsedMem/1000000 + "MB *******");
memExceedsLimit = true;
}
}
State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek();
int curIndex = curIndexStack.peek();
LinkedList<Transition> curEnabled = lpnTranStack.peek();
if (failureTranIsEnabled(curEnabled)) {
return null;
}
if (Options.getDebugMode()) {
System.out.println("
printStateArray(curStateArray);
System.out.println("+++++++ curEnabled trans ++++++++");
printTransLinkedList(curEnabled);
}
// If all enabled transitions of the current LPN are considered,
// then consider the next LPN
// by increasing the curIndex.
// Otherwise, if all enabled transitions of all LPNs are considered,
// then pop the stacks.
if (curEnabled.size() == 0) {
lpnTranStack.pop();
if (Options.getDebugMode()) {
System.out.println("+++++++ Pop trans off lpnTranStack ++++++++");
System.out.println("
printLpnTranStack(lpnTranStack);
}
curIndexStack.pop();
curIndex++;
while (curIndex < numLpns) {
// System.out.println("call getEnabled on curStateArray at 1: ");
if(!Options.getTimingAnalysisFlag()){ // Timing Change
curEnabled = (sgList[curIndex].getEnabled(curStateArray[curIndex], init)).clone();
}
else{
// Get the enabled transitions from the zone that are associated with
// the current LPN.
curEnabled = ((TimedPrjState) stateStackTop).getPossibleEvents(0, curIndex);
}
if (curEnabled.size() > 0) {
if (Options.getDebugMode()) {
System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
printTransLinkedList(curEnabled);
}
lpnTranStack.push(curEnabled);
curIndexStack.push(curIndex);
if (Options.getDebugMode())
printIntegerStack("curIndexStack after push 1", curIndexStack);
break;
}
curIndex++;
}
}
if (curIndex == numLpns) {
// prjStateSet.add(stateStackTop);
if (Options.getDebugMode()) {
System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%");
printStateArray(stateStackTop.toStateArray());
}
stateStack.remove(stateStackTop);
stateStackTop = stateStackTop.getFather();
continue;
}
Transition firedTran = curEnabled.removeLast();
if (Options.getDebugMode()) {
System.out.println("
System.out.println("Fired transition: " + firedTran.getLpn().getLabel() + "(" + firedTran.getName() + ")");
System.out.println("
}
State[] nextStateArray;
PrjState nextPrjState; // Moved this definition up. Timing Change.
// The next state depends on whether timing is in use or not.
// Timing Change.
if(!Options.getTimingAnalysisFlag()){
// Get the next states from the fire method and define the next project state.
nextStateArray = sgList[curIndex].fire(sgList, curStateArray, firedTran);
nextPrjState = new PrjState(nextStateArray);
}
else{
// Get the next timed state and extract the next un-timed states.
nextPrjState = sgList[curIndex].fire(sgList, stateStackTop,
(EventSet) firedTran);
nextStateArray = nextPrjState.toStateArray();
}
tranFiringCnt++;
// Check if the firedTran causes disabling error or deadlock.
@SuppressWarnings("unchecked")
LinkedList<Transition>[] curEnabledArray = new LinkedList[numLpns];
@SuppressWarnings("unchecked")
LinkedList<Transition>[] nextEnabledArray = new LinkedList[numLpns];
for (int i = 0; i < numLpns; i++) {
StateGraph sg = sgList[i];
LinkedList<Transition> enabledList;
if(!Options.getTimingAnalysisFlag()){ // Timing Change.
enabledList = sg.getEnabled(curStateArray[i], init);
}
else{
// Get the enabled transitions from the Zone for the appropriate
// LPN.
//enabledList = ((TimedPrjState) stateStackTop).getEnabled(i);
enabledList = ((TimedPrjState) stateStackTop).getPossibleEvents(0, i);
}
curEnabledArray[i] = enabledList;
if(!Options.getTimingAnalysisFlag()){ // Timing Change.
enabledList = sg.getEnabled(nextStateArray[i], init);
}
else{
//enabledList = ((TimedPrjState) nextPrjState).getEnabled(i);
enabledList = ((TimedPrjState) nextPrjState).getPossibleEvents(0, i);
}
nextEnabledArray[i] = enabledList;
if (Options.getReportDisablingError()) {
Transition disabledTran = firedTran.disablingError(
curEnabledArray[i], nextEnabledArray[i]);
if (disabledTran != null) {
System.err.println("Disabling Error: "
+ disabledTran.getFullLabel() + " is disabled by "
+ firedTran.getFullLabel());
failure = true;
break main_while_loop;
}
}
}
if (Analysis.deadLock(sgList, nextStateArray) == true) {
System.out.println("*** Verification failed: deadlock.");
failure = true;
break main_while_loop;
}
//PrjState nextPrjState = new PrjState(nextStateArray); // Moved earlier. Timing Change.
Boolean existingState = prjStateSet.contains(nextPrjState); //|| stateStack.contains(nextPrjState);
if (existingState == false) {
prjStateSet.add(nextPrjState);
stateStackTop.setChild(nextPrjState);
nextPrjState.setFather(stateStackTop);
if (Options.getOutputSgFlag()) {
if (Options.getDebugMode()) {
System.out.println("******* curStateArray *******");
printStateArray(curStateArray);
System.out.println("******* nextStateArray *******");
printStateArray(nextStateArray);
System.out.println("stateStackTop: ");
printStateArray(stateStackTop.toStateArray());
System.out.println("firedTran = " + firedTran.getName());
System.out.println("***nextStateMap for stateStackTop before firedTran being added: ");
printNextStateMap(stateStackTop.getNextStateMap());
}
stateStackTop.setTranOut(firedTran, nextPrjState);
if (Options.getDebugMode()) {
System.out.println("***nextStateMap for stateStackTop after firedTran being added: ");
printNextStateMap(stateStackTop.getNextStateMap());
}
for (PrjState prjState : prjStateSet) {
if (prjState.equals(stateStackTop)) {
prjState.setTranOut(firedTran, nextPrjState);
if (Options.getDebugMode()) {
System.out.println("***nextStateMap for prjState: ");
printNextStateMap(prjState.getNextStateMap());
}
}
}
}
stateStackTop = nextPrjState;
if (Options.getDebugMode()) {
System.out.println("%%%%%%% Add global state to stateStack %%%%%%%%");
printStateArray(stateStackTop.toStateArray());
}
stateStack.add(stateStackTop);
if (Options.getDebugMode()) {
System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
printTransitionSet((LpnTranList) nextEnabledArray[0], "");
}
lpnTranStack.push((LpnTranList) nextEnabledArray[0].clone());
if (Options.getDebugMode()) {
System.out.println("******** lpnTranStack ***********");
printLpnTranStack(lpnTranStack);
}
curIndexStack.push(0);
totalStates++;
}
else {
if (Options.getOutputSgFlag()) {
if (Options.getDebugMode()) {
System.out.println("******* curStateArray *******");
printStateArray(curStateArray);
System.out.println("******* nextStateArray *******");
printStateArray(nextStateArray);
}
for (PrjState prjState : prjStateSet) {
if (prjState.equals(nextPrjState)) {
nextPrjState.setNextStateMap((HashMap<Transition, PrjState>) prjState.getNextStateMap().clone());
}
}
if (Options.getDebugMode()) {
System.out.println("stateStackTop: ");
printStateArray(stateStackTop.toStateArray());
System.out.println("firedTran = " + firedTran.getName());
System.out.println("nextStateMap for stateStackTop before firedTran being added: ");
printNextStateMap(stateStackTop.getNextStateMap());
}
stateStackTop.setTranOut(firedTran, nextPrjState);
if (Options.getDebugMode()) {
System.out.println("***nextStateMap for stateStackTop after firedTran being added: ");
printNextStateMap(stateStackTop.getNextStateMap());
}
for (PrjState prjState : prjStateSet) {
if (prjState == stateStackTop) {
prjState.setNextStateMap((HashMap<Transition, PrjState>) stateStackTop.getNextStateMap().clone());
if (Options.getDebugMode()) {
System.out.println("***nextStateMap for prjState: ");
printNextStateMap(prjState.getNextStateMap());
}
}
}
}
}
}
double totalStateCnt = prjStateSet.size();
System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt
//+ ", # of prjStates found: " + totalStateCnt
+ ", " + prjStateSet.stateString()
+ ", max_stack_depth: " + max_stack_depth
+ ", peak total memory: " + peakTotalMem / 1000000 + " MB"
+ ", peak used memory: " + peakUsedMem / 1000000 + " MB");
if (Options.getOutputLogFlag())
writePerformanceResultsToLogFile(false, tranFiringCnt, totalStateCnt, peakTotalMem / 1000000, peakUsedMem / 1000000);
if (Options.getOutputSgFlag())
drawGlobalStateGraph(sgList, prjStateSet.toHashSet(), true);
return sgList;
}
private boolean failureTranIsEnabled(LinkedList<Transition> curEnabled) {
boolean failureTranIsEnabled = false;
for (Transition tran : curEnabled) {
if (tran.isFail()) {
JOptionPane.showMessageDialog(Gui.frame,
"Failure transition " + tran.getName() + "is enabled.", "Error",
JOptionPane.ERROR_MESSAGE);
failureTranIsEnabled = true;
break;
}
}
return failureTranIsEnabled;
}
private void drawGlobalStateGraph(StateGraph[] sgList, HashSet<PrjState> prjStateSet, boolean fullSG) {
try {
String fileName = null;
if (fullSG) {
fileName = Options.getPrjSgPath() + "full_sg.dot";
}
else {
fileName = Options.getPrjSgPath() + Options.getPOR().toLowerCase() + "_"
+ Options.getCycleClosingMthd().toLowerCase() + "_"
+ Options.getCycleClosingAmpleMethd().toLowerCase() + "_sg.dot";
}
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
out.write("digraph G {\n");
for (PrjState curGlobalState : prjStateSet) {
// Build composite current global state.
String curVarNames = "";
String curVarValues = "";
String curMarkings = "";
String curEnabledTrans = "";
String curGlobalStateIndex = "";
HashMap<String, Integer> vars = new HashMap<String, Integer>();
for (State curLocalState : curGlobalState.toStateArray()) {
LhpnFile curLpn = curLocalState.getLpn();
for(int i = 0; i < curLpn.getVarIndexMap().size(); i++) {
//System.out.println(curLpn.getVarIndexMap().getKey(i) + " = " + curLocalState.getVector()[i]);
vars.put(curLpn.getVarIndexMap().getKey(i), curLocalState.getVector()[i]);
}
curMarkings = curMarkings + "," + intArrayToString("markings", curLocalState);
if (!boolArrayToString("enabled trans", curLocalState).equals(""))
curEnabledTrans = curEnabledTrans + "," + boolArrayToString("enabled trans", curLocalState);
curGlobalStateIndex = curGlobalStateIndex + "_" + "S" + curLocalState.getIndex();
}
for (String vName : vars.keySet()) {
Integer vValue = vars.get(vName);
curVarValues = curVarValues + vValue + ", ";
curVarNames = curVarNames + vName + ", ";
}
curVarNames = curVarNames.substring(0, curVarNames.lastIndexOf(","));
curVarValues = curVarValues.substring(0, curVarValues.lastIndexOf(","));
curMarkings = curMarkings.substring(curMarkings.indexOf(",")+1, curMarkings.length());
curEnabledTrans = curEnabledTrans.substring(curEnabledTrans.indexOf(",")+1, curEnabledTrans.length());
curGlobalStateIndex = curGlobalStateIndex.substring(curGlobalStateIndex.indexOf("_")+1, curGlobalStateIndex.length());
out.write("Inits[shape=plaintext, label=\"<" + curVarNames + ">\"]\n");
out.write(curGlobalStateIndex + "[shape=\"ellipse\",label=\"" + curGlobalStateIndex + "\\n<"+curVarValues+">" + "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\"]\n");
// // Build composite next global states.
HashMap<Transition, PrjState> nextStateMap = curGlobalState.getNextStateMap();
for (Transition outTran : nextStateMap.keySet()) {
PrjState nextGlobalState = nextStateMap.get(outTran);
String nextVarNames = "";
String nextVarValues = "";
String nextMarkings = "";
String nextEnabledTrans = "";
String nextGlobalStateIndex = "";
for (State nextLocalState : nextGlobalState.toStateArray()) {
LhpnFile nextLpn = nextLocalState.getLpn();
for(int i = 0; i < nextLpn.getVarIndexMap().size(); i++) {
vars.put(nextLpn.getVarIndexMap().getKey(i), nextLocalState.getVector()[i]);
}
nextMarkings = nextMarkings + "," + intArrayToString("markings", nextLocalState);
if (!boolArrayToString("enabled trans", nextLocalState).equals(""))
nextEnabledTrans = nextEnabledTrans + "," + boolArrayToString("enabled trans", nextLocalState);
nextGlobalStateIndex = nextGlobalStateIndex + "_" + "S" + nextLocalState.getIndex();
}
for (String vName : vars.keySet()) {
Integer vValue = vars.get(vName);
nextVarValues = nextVarValues + vValue + ", ";
nextVarNames = nextVarNames + vName + ", ";
}
nextVarNames = nextVarNames.substring(0, nextVarNames.lastIndexOf(","));
nextVarValues = nextVarValues.substring(0, nextVarValues.lastIndexOf(","));
nextMarkings = nextMarkings.substring(nextMarkings.indexOf(",")+1, nextMarkings.length());
nextEnabledTrans = nextEnabledTrans.substring(nextEnabledTrans.indexOf(",")+1, nextEnabledTrans.length());
nextGlobalStateIndex = nextGlobalStateIndex.substring(nextGlobalStateIndex.indexOf("_")+1, nextGlobalStateIndex.length());
out.write("Inits[shape=plaintext, label=\"<" + nextVarNames + ">\"]\n");
out.write(nextGlobalStateIndex + "[shape=\"ellipse\",label=\"" + nextGlobalStateIndex + "\\n<"+nextVarValues+">" + "\\n<"+nextEnabledTrans+">" + "\\n<"+nextMarkings+">" + "\"]\n");
String outTranName = outTran.getName();
if (outTran.isFail() && !outTran.isPersistent())
out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=red]\n");
else if (!outTran.isFail() && outTran.isPersistent())
out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=blue]\n");
else if (outTran.isFail() && outTran.isPersistent())
out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=purple]\n");
else
out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\"]\n");
}
}
out.write("}");
out.close();
}
catch (Exception e) {
e.printStackTrace();
System.err.println("Error producing local state graph as dot file.");
}
}
/*
private void drawDependencyGraphsForNecessarySets(LhpnFile[] lpnList,
HashMap<LpnTransitionPair, StaticSets> staticSetsMap) {
String fileName = Options.getPrjSgPath() + "_necessarySet.dot";
BufferedWriter out;
try {
out = new BufferedWriter(new FileWriter(fileName));
out.write("digraph G {\n");
for (LpnTransitionPair seedTran : staticSetsMap.keySet()) {
for (LpnTransitionPair canEnableTran : staticSetsMap.get(seedTran).getEnableSet()) {
}
}
out.write("}");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
*/
private String intArrayToString(String type, State curState) {
String arrayStr = "";
if (type.equals("markings")) {
for (int i=0; i< curState.getMarking().length; i++) {
if (curState.getMarking()[i] == 1) {
arrayStr = arrayStr + curState.getLpn().getPlaceList()[i] + ",";
}
// String tranName = curState.getLpn().getAllTransitions()[i].getName();
// if (curState.getTranVector()[i])
// System.out.println(tranName + " " + "Enabled");
// else
// System.out.println(tranName + " " + "Not Enabled");
}
arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(","));
}
else if (type.equals("vars")) {
for (int i=0; i< curState.getVector().length; i++) {
arrayStr = arrayStr + curState.getVector()[i] + ",";
}
if (arrayStr.contains(","))
arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(","));
}
return arrayStr;
}
private String boolArrayToString(String type, State curState) {
String arrayStr = "";
if (type.equals("enabled trans")) {
for (int i=0; i< curState.getTranVector().length; i++) {
if (curState.getTranVector()[i]) {
arrayStr = arrayStr + curState.getLpn().getAllTransitions()[i].getName() + ",";
}
}
if (arrayStr != "")
arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(","));
}
return arrayStr;
}
private void printStateArray(State[] stateArray) {
for (int i=0; i<stateArray.length; i++) {
System.out.print("S" + stateArray[i].getIndex() + "(" + stateArray[i].getLpn().getLabel() +") -> ");
System.out.print("markings: " + intArrayToString("markings", stateArray[i]) + " / ");
System.out.print("enabled trans: " + boolArrayToString("enabled trans", stateArray[i]) + " / ");
System.out.print("var values: " + intArrayToString("vars", stateArray[i]) + " / ");
System.out.print("\n");
}
}
private void printTransLinkedList(LinkedList<Transition> curPop) {
for (int i=0; i< curPop.size(); i++) {
System.out.print(curPop.get(i).getName() + " ");
}
System.out.println("");
}
private void printIntegerStack(String stackName, Stack<Integer> curIndexStack) {
System.out.println("+++++++++" + stackName + "+++++++++");
for (int i=0; i < curIndexStack.size(); i++) {
System.out.println(stackName + "[" + i + "]" + curIndexStack.get(i));
}
System.out.println("
}
private void printDstLpnList(StateGraph[] lpnList) {
System.out.println("++++++ dstLpnList ++++++");
for (int i=0; i<lpnList.length; i++) {
LhpnFile curLPN = lpnList[i].getLpn();
System.out.println("LPN: " + curLPN.getLabel());
Transition[] allTrans = curLPN.getAllTransitions();
for (int j=0; j< allTrans.length; j++) {
System.out.print(allTrans[j].getName() + ": ");
for (int k=0; k< allTrans[j].getDstLpnList().size(); k++) {
System.out.print(allTrans[j].getDstLpnList().get(k).getLabel() + ",");
}
System.out.print("\n");
}
System.out.println("
}
System.out.println("++++++++++++++++++++");
}
private void constructDstLpnList(StateGraph[] lpnList) {
for (int i=0; i<lpnList.length; i++) {
LhpnFile curLPN = lpnList[i].getLpn();
Transition[] allTrans = curLPN.getAllTransitions();
for (int j=0; j<allTrans.length; j++) {
Transition curTran = allTrans[j];
for (int k=0; k<lpnList.length; k++) {
curTran.setDstLpnList(lpnList[k].getLpn());
}
}
}
}
/**
* This method performs first-depth search on an array of LPNs and applies partial order reduction technique with the traceback.
* @param sgList
* @param initStateArray
* @param cycleClosingMthdIndex
* @return
*/
@SuppressWarnings("unchecked")
public StateGraph[] search_dfsPOR(final StateGraph[] sgList, final State[] initStateArray) {
System.out.println("---> calling function search_dfsPOR");
System.out.println("---> " + Options.getPOR());
System.out.println("---> " + Options.getCycleClosingMthd());
System.out.println("---> " + Options.getCycleClosingAmpleMethd());
double peakUsedMem = 0;
double peakTotalMem = 0;
boolean failure = false;
int tranFiringCnt = 0;
int totalStates = 1;
int numLpns = sgList.length;
LhpnFile[] lpnList = new LhpnFile[numLpns];
for (int i=0; i<numLpns; i++) {
lpnList[i] = sgList[i].getLpn();
}
HashSet<PrjState> stateStack = new HashSet<PrjState>();
Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>();
HashSet<PrjState> prjStateSet = new HashSet<PrjState>();
PrjState initPrjState = new PrjState(initStateArray);
prjStateSet.add(initPrjState);
PrjState stateStackTop = initPrjState;
if (Options.getDebugMode()) {
System.out.println("%%%%%%% stateStackTop %%%%%%%%");
printStateArray(stateStackTop.toStateArray());
}
stateStack.add(stateStackTop);
constructDstLpnList(sgList);
if (Options.getDebugMode()) {
printDstLpnList(sgList);
createPORDebugFile();
}
// Find static pieces for POR.
HashMap<Integer, Transition[]> allTransitions = new HashMap<Integer, Transition[]>(lpnList.length);
HashMap<LpnTransitionPair, StaticSets> staticSetsMap = new HashMap<LpnTransitionPair, StaticSets>();
for (int i=0; i<lpnList.length; i++)
allTransitions.put(i, lpnList[i].getAllTransitions());
HashMap<LpnTransitionPair, Integer> tranFiringFreq = new HashMap<LpnTransitionPair, Integer>(allTransitions.keySet().size());
for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) {
if (Options.getDebugMode())
System.out.println("LPN = " + lpnList[lpnIndex].getLabel());
for (Transition curTran: allTransitions.get(lpnIndex)) {
StaticSets curStatic = new StaticSets(curTran, allTransitions);
curStatic.buildCurTranDisableOtherTransSet(lpnIndex);
if (Options.getPORdeadlockPreserve())
curStatic.buildOtherTransDisableCurTranSet(lpnIndex);
curStatic.buildModifyAssignSet();
curStatic.buildEnableBySettingEnablingTrue();
// if (Options.getDebugMode())
// curStatic.buildEnableByBringingToken();
LpnTransitionPair lpnTranPair = new LpnTransitionPair(lpnIndex,curTran.getIndex());
staticSetsMap.put(lpnTranPair, curStatic);
//if (!Options.getNecessaryUsingDependencyGraphs())
tranFiringFreq.put(lpnTranPair, 0);
}
}
if (Options.getDebugMode()) {
printStaticSetsMap(lpnList, staticSetsMap);
writeStaticSetsMapToPORDebugFile(lpnList, staticSetsMap);
// if (Options.getNecessaryUsingDependencyGraphs())
// drawDependencyGraphsForNecessarySets(lpnList, staticSetsMap);
}
boolean init = true;
LpnTranList initAmpleTrans = new LpnTranList();
if (Options.getDebugMode())
System.out.println("call getAmple on curStateArray at 0: ");
// if (Options.getNecessaryUsingDependencyGraphs())
// tranFiringFreq = null;
initAmpleTrans = getAmple(initStateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop);
lpnTranStack.push(initAmpleTrans);
init = false;
if (Options.getDebugMode()) {
System.out.println("+++++++ Push trans onto lpnTranStack @ 1++++++++");
printTransitionSet(initAmpleTrans, "");
}
HashSet<LpnTransitionPair> initAmple = new HashSet<LpnTransitionPair>();
for (Transition t: initAmpleTrans) {
initAmple.add(new LpnTransitionPair(t.getLpn().getLpnIndex(), t.getIndex()));
}
updateLocalAmpleTbl(initAmple, sgList, initStateArray);
boolean memExceedsLimit = false;
main_while_loop: while (failure == false && stateStack.size() != 0) {
if (Options.getDebugMode()) {
System.out.println("~~~~~~~~~~~ loop begins ~~~~~~~~~~~");
writeStringWithNewLineToPORDebugFile("~~~~~~~~~~~ loop begins ~~~~~~~~~~~");
}
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
if (iterations % 100000 == 0) {
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStates
+ ", stack_depth: " + stateStack.size()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
}
if (!memExceedsLimit && Options.getMemUpperBoundFlag() && iterations % 100 == 0) {
if (curUsedMem > Options.getMemUpperBound()) {
System.out.println("******* Used memory exceeds memory upper bound (" + (float)Options.getMemUpperBound()/1000000 + "MB) *******");
System.out.println("******* Used memory = " + (float)curUsedMem/1000000 + "MB *******");
memExceedsLimit = true;
}
}
State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek();
LinkedList<Transition> curAmpleTrans = lpnTranStack.peek();
if (failureTranIsEnabled(curAmpleTrans)) {
return null;
}
if (curAmpleTrans.size() == 0) {
lpnTranStack.pop();
prjStateSet.add(stateStackTop);
if (Options.getDebugMode()) {
System.out.println("+++++++ Pop trans off lpnTranStack ++++++++");
System.out.println("
printLpnTranStack(lpnTranStack);
// System.out.println("
// printStateStack(stateStack);
System.out.println("
printPrjStateSet(prjStateSet);
System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%");
}
stateStack.remove(stateStackTop);
stateStackTop = stateStackTop.getFather();
continue;
}
Transition firedTran = curAmpleTrans.removeLast();
if (Options.getDebugMode()) {
System.out.println("
System.out.println("Fired Transition: " + firedTran.getLpn().getLabel() + "(" + firedTran.getName() + ")");
System.out.println("
writeStringWithNewLineToPORDebugFile("
writeStringWithNewLineToPORDebugFile("Fired Transition: " + firedTran.getLpn().getLabel() + "(" + firedTran.getName() + ")");
writeStringWithNewLineToPORDebugFile("
}
LpnTransitionPair firedLpnTranPair = new LpnTransitionPair(firedTran.getLpn().getLpnIndex(), firedTran.getIndex());
// if (!Options.getNecessaryUsingDependencyGraphs()) {
Integer freq = tranFiringFreq.get(firedLpnTranPair) + 1;
tranFiringFreq.put(firedLpnTranPair, freq);
if (Options.getDebugMode()) {
System.out.println("~~~~~~tranFiringFreq~~~~~~~");
printHashMap(tranFiringFreq, sgList);
}
State[] nextStateArray = sgList[firedLpnTranPair.getLpnIndex()].fire(sgList, curStateArray, firedTran);
tranFiringCnt++;
// Check if the firedTran causes disabling error or deadlock.
if (Options.getReportDisablingError()) {
for (int i=0; i<numLpns; i++) {
Transition disabledTran = firedTran.disablingError(curStateArray[i].getEnabledTransitions(), nextStateArray[i].getEnabledTransitions());
if (disabledTran != null) {
System.err.println("Disabling Error: "
+ disabledTran.getFullLabel() + " is disabled by "
+ firedTran.getFullLabel());
failure = true;
break main_while_loop;
}
}
}
LpnTranList nextAmpleTrans = new LpnTranList();
// if (Options.getNecessaryUsingDependencyGraphs())
// nextAmpleTrans = getAmple(curStateArray, nextStateArray, staticSetsMap, init, null, sgList, prjStateSet, stateStackTop);
// else
nextAmpleTrans = getAmple(curStateArray, nextStateArray, staticSetsMap, init, tranFiringFreq, sgList, prjStateSet, stateStackTop);
// check for possible deadlock
if (nextAmpleTrans.size() == 0) {
System.out.println("*** Verification failed: deadlock.");
failure = true;
break main_while_loop;
}
HashSet<LpnTransitionPair> nextAmple = getLpnTransitionPair(nextAmpleTrans);
PrjState nextPrjState = new PrjState(nextStateArray);
Boolean existingState = prjStateSet.contains(nextPrjState) || stateStack.contains(nextPrjState);
if (existingState == false) {
if (Options.getDebugMode())
System.out.println("%%%%%%% existingSate == false %%%%%%%%");
if (Options.getOutputSgFlag()) {
if (Options.getDebugMode()) {
System.out.println("******* curStateArray *******");
printStateArray(curStateArray);
System.out.println("******* nextStateArray *******");
printStateArray(nextStateArray);
System.out.println("stateStackTop: ");
printStateArray(stateStackTop.toStateArray());
System.out.println("firedTran = " + firedTran.getName());
System.out.println("***nextStateMap for stateStackTop before firedTran being added: ");
printNextStateMap(stateStackTop.getNextStateMap());
}
stateStackTop.setTranOut(firedTran, nextPrjState);
if (Options.getDebugMode()) {
System.out.println("***nextStateMap for stateStackTop after firedTran being added: ");
printNextStateMap(stateStackTop.getNextStateMap());
}
for (PrjState prjState : prjStateSet) {
if (prjState.equals(stateStackTop)) {
prjState.setTranOut(firedTran, nextPrjState);
if (Options.getDebugMode()) {
System.out.println("***nextStateMap for prjState: ");
printNextStateMap(prjState.getNextStateMap());
}
}
}
}
updateLocalAmpleTbl(nextAmple, sgList, nextStateArray);
stateStackTop.setChild(nextPrjState);
nextPrjState.setFather(stateStackTop);
stateStackTop = nextPrjState;
stateStack.add(stateStackTop);
if (Options.getDebugMode()) {
System.out.println("%%%%%%% Add global state to stateStack %%%%%%%%");
printStateArray(stateStackTop.toStateArray());
System.out.println("+++++++ Push trans onto lpnTranStack @ 2++++++++");
printTransitionSet((LpnTranList) nextAmpleTrans, "");
}
lpnTranStack.push((LpnTranList) nextAmpleTrans.clone());
totalStates++;
}
else {
if (Options.getOutputSgFlag()) {
if (Options.getDebugMode()) {
System.out.println("******* curStateArray *******");
printStateArray(curStateArray);
System.out.println("******* nextStateArray *******");
printStateArray(nextStateArray);
}
for (PrjState prjState : prjStateSet) {
if (prjState.equals(nextPrjState)) {
nextPrjState.setNextStateMap((HashMap<Transition, PrjState>) prjState.getNextStateMap().clone());
}
}
if (Options.getDebugMode()) {
System.out.println("stateStackTop: ");
printStateArray(stateStackTop.toStateArray());
System.out.println("firedTran = " + firedTran.getName());
System.out.println("nextStateMap for stateStackTop before firedTran being added: ");
printNextStateMap(stateStackTop.getNextStateMap());
}
stateStackTop.setTranOut(firedTran, nextPrjState);
if (Options.getDebugMode()) {
System.out.println("***nextStateMap for stateStackTop after firedTran being added: ");
printNextStateMap(stateStackTop.getNextStateMap());
}
for (PrjState prjState : prjStateSet) {
if (prjState == stateStackTop) {
prjState.setNextStateMap((HashMap<Transition, PrjState>) stateStackTop.getNextStateMap().clone());
if (Options.getDebugMode()) {
System.out.println("***nextStateMap for prjState: ");
printNextStateMap(prjState.getNextStateMap());
}
}
}
}
if (!Options.getCycleClosingMthd().toLowerCase().equals("no_cycleclosing")) {
// Cycle closing check
if (prjStateSet.contains(nextPrjState) && stateStack.contains(nextPrjState)) {
if (Options.getDebugMode())
System.out.println("%%%%%%% Cycle Closing %%%%%%%%");
HashSet<LpnTransitionPair> nextAmpleSet = new HashSet<LpnTransitionPair>();
HashSet<LpnTransitionPair> curAmpleSet = new HashSet<LpnTransitionPair>();
for (Transition t : nextAmpleTrans) {
nextAmpleSet.add(new LpnTransitionPair(t.getLpn().getLpnIndex(), t.getIndex()));
}
for (Transition t: curAmpleTrans) {
curAmpleSet.add(new LpnTransitionPair(t.getLpn().getLpnIndex(), t.getIndex()));
}
curAmpleSet.add(new LpnTransitionPair(firedTran.getLpn().getLpnIndex(), firedTran.getIndex()));
HashSet<LpnTransitionPair> newNextAmple = new HashSet<LpnTransitionPair>();
// if (Options.getNecessaryUsingDependencyGraphs())
// newNextAmple = computeCycleClosingTrans(curStateArray, nextStateArray, staticSetsMap,
// null, sgList, prjStateSet, nextPrjState, nextAmpleSet, curAmpleSet, stateStack);
// else
newNextAmple = computeCycleClosingTrans(curStateArray, nextStateArray, staticSetsMap,
tranFiringFreq, sgList, prjStateSet, nextPrjState, nextAmpleSet, curAmpleSet, stateStack);
if (newNextAmple != null && !newNextAmple.isEmpty()) {
LpnTranList newNextAmpleTrans = getLpnTranList(newNextAmple, sgList);
stateStackTop.setChild(nextPrjState);
nextPrjState.setFather(stateStackTop);
if (Options.getDebugMode()) {
System.out.println("nextPrjState: ");
printStateArray(nextPrjState.toStateArray());
System.out.println("nextStateMap for nextPrjState: ");
printNextStateMap(nextPrjState.getNextStateMap());
}
stateStackTop = nextPrjState;
stateStack.add(stateStackTop);
if (Options.getDebugMode()) {
System.out.println("%%%%%%% Add state to stateStack %%%%%%%%");
printStateArray(stateStackTop.toStateArray());
System.out.println("stateStackTop: ");
printStateArray(stateStackTop.toStateArray());
System.out.println("nextStateMap for stateStackTop: ");
printNextStateMap(nextPrjState.getNextStateMap());
}
lpnTranStack.push(newNextAmpleTrans.clone());
if (Options.getDebugMode()) {
System.out.println("+++++++ Push these trans onto lpnTranStack @ Cycle Closing ++++++++");
printTransitionSet((LpnTranList) newNextAmpleTrans, "");
System.out.println("******* lpnTranStack ***************");
printLpnTranStack(lpnTranStack);
}
}
}
}
updateLocalAmpleTbl(nextAmple, sgList, nextStateArray);
}
}
if (Options.getDebugMode()) {
try {
PORdebugBufferedWriter.close();
PORdebugFileStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
double totalStateCnt = prjStateSet.size();
System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStateCnt
+ ", max_stack_depth: " + max_stack_depth
+ ", peak total memory: " + peakTotalMem / 1000000 + " MB"
+ ", peak used memory: " + peakUsedMem / 1000000 + " MB");
if (Options.getOutputLogFlag())
writePerformanceResultsToLogFile(true, tranFiringCnt, totalStateCnt, peakTotalMem / 1000000, peakUsedMem / 1000000);
if (Options.getOutputSgFlag()) {
drawGlobalStateGraph(sgList, prjStateSet, false);
}
return sgList;
}
private void createPORDebugFile() {
try {
PORdebugFileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_"
+ Options.getCycleClosingMthd() + "_" + Options.getCycleClosingAmpleMethd() + ".dbg";
PORdebugFileStream = new FileWriter(PORdebugFileName);
PORdebugBufferedWriter = new BufferedWriter(PORdebugFileStream);
}
catch (Exception e) {
e.printStackTrace();
System.err.println("Error producing the debugging file for partial order reduction.");
}
}
private void writeStringWithNewLineToPORDebugFile(String string) {
try {
PORdebugBufferedWriter.append(string);
PORdebugBufferedWriter.newLine();
PORdebugBufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void writeStringToPORDebugFile(String string) {
try {
PORdebugBufferedWriter.append(string);
//PORdebugBufferedWriter.newLine();
PORdebugBufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void writePerformanceResultsToLogFile(boolean isPOR, int tranFiringCnt, double totalStateCnt,
double peakTotalMem, double peakUsedMem) {
try {
String fileName = null;
if (isPOR) {
if (Options.getNecessaryUsingDependencyGraphs())
fileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_"
+ Options.getCycleClosingMthd() + "_" + Options.getCycleClosingAmpleMethd() + ".log";
else
fileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_"
+ Options.getCycleClosingMthd() + "_" + Options.getCycleClosingAmpleMethd() + ".log";
}
else
fileName = Options.getPrjSgPath() + Options.getLogName() + "_full" + ".log";
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
out.write("tranFiringCnt" + "\t" + "prjStateCnt" + "\t" + "maxStackDepth" + "\t" + "peakTotalMem(MB)" + "\t" + "peakUsedMem(MB)\n");
out.write(tranFiringCnt + "\t" + totalStateCnt + "\t" + max_stack_depth + "\t" + peakTotalMem + "\t"
+ peakUsedMem + "\n");
out.close();
}
catch (Exception e) {
e.printStackTrace();
System.err.println("Error producing local state graph as dot file.");
}
}
private void printLpnTranStack(Stack<LinkedList<Transition>> lpnTranStack) {
for (int i=0; i<lpnTranStack.size(); i++) {
LinkedList<Transition> tranList = lpnTranStack.get(i);
for (int j=0; j<tranList.size(); j++) {
System.out.println(tranList.get(j).getName());
}
System.out.println("
}
}
private void printNextStateMap(HashMap<Transition, PrjState> nextStateMap) {
for (Transition t: nextStateMap.keySet()) {
System.out.print(t.getName() + " -> ");
State[] stateArray = nextStateMap.get(t).getStateArray();
for (int i=0; i<stateArray.length; i++) {
System.out.print("S" + stateArray[i].getIndex() + ", ");
}
System.out.print("\n");
}
}
private HashSet<LpnTransitionPair> getLpnTransitionPair(LpnTranList ampleTrans) {
HashSet<LpnTransitionPair> ample = new HashSet<LpnTransitionPair>();
for (Transition tran : ampleTrans) {
ample.add(new LpnTransitionPair(tran.getLpn().getLpnIndex(), tran.getIndex()));
}
return ample;
}
private LpnTranList getLpnTranList(HashSet<LpnTransitionPair> newNextAmple,
StateGraph[] sgList) {
LpnTranList newNextAmpleTrans = new LpnTranList();
for (LpnTransitionPair lpnTran : newNextAmple) {
Transition tran = sgList[lpnTran.getLpnIndex()].getLpn().getTransition(lpnTran.getTranIndex());
newNextAmpleTrans.add(tran);
}
return newNextAmpleTrans;
}
private HashSet<LpnTransitionPair> computeCycleClosingTrans(State[] curStateArray,
State[] nextStateArray,
HashMap<LpnTransitionPair, StaticSets> staticSetsMap,
HashMap<LpnTransitionPair, Integer> tranFiringFreq, StateGraph[] sgList, HashSet<PrjState> prjStateSet,
PrjState nextPrjState, HashSet<LpnTransitionPair> nextAmple,
HashSet<LpnTransitionPair> curAmple, HashSet<PrjState> stateStack) {
for (State s : nextStateArray)
if (s == null)
throw new NullPointerException();
String cycleClosingMthd = Options.getCycleClosingMthd();
HashSet<LpnTransitionPair> newNextAmple = new HashSet<LpnTransitionPair>();
HashSet<LpnTransitionPair> nextEnabled = new HashSet<LpnTransitionPair>();
HashSet<LpnTransitionPair> curEnabled = new HashSet<LpnTransitionPair>();
LhpnFile[] lpnList = new LhpnFile[sgList.length];
for (int i=0; i<sgList.length; i++)
lpnList[i] = sgList[i].getLpn();
for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) {
LhpnFile curLpn = sgList[lpnIndex].getLpn();
for (int i=0; i < curLpn.getAllTransitions().length; i++) {
Transition tran = curLpn.getAllTransitions()[i];
if (nextStateArray[lpnIndex].getTranVector()[i])
nextEnabled.add(new LpnTransitionPair(curLpn.getLpnIndex(), tran.getIndex()));
if (curStateArray[lpnIndex].getTranVector()[i])
curEnabled.add(new LpnTransitionPair(curLpn.getLpnIndex(), tran.getIndex()));
}
}
// Cycle closing on global state graph
if (Options.getDebugMode())
System.out.println("~~~~~~~ existing global state ~~~~~~~~");
if (cycleClosingMthd.equals("strong")) {
newNextAmple.addAll(getIntSetSubstraction(curEnabled, nextAmple));
updateLocalAmpleTbl(newNextAmple, sgList, nextStateArray);
}
else if (cycleClosingMthd.equals("behavioral")) {
if (Options.getDebugMode())
System.out.println("****** behavioral: cycle closing check ********");
HashSet<LpnTransitionPair> curReduced = getIntSetSubstraction(curEnabled, curAmple);
HashSet<LpnTransitionPair> oldNextAmple = new HashSet<LpnTransitionPair>();
DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq);
PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(nextEnabled.size(), depComp);
// TODO: Is oldNextAmple correctly obtained below?
if (Options.getDebugMode()) {
System.out.println("******* nextStateArray *******");
printStateArray(nextStateArray);
}
for (int lpnIndex=0; lpnIndex < sgList.length; lpnIndex++) {
if (sgList[lpnIndex].getEnabledSetTbl().get(nextStateArray[lpnIndex]) != null) {
LpnTranList oldLocalNextAmpleTrans = sgList[lpnIndex].getEnabledSetTbl().get(nextStateArray[lpnIndex]);
if (Options.getDebugMode())
printTransitionSet(oldLocalNextAmpleTrans, "oldLocalNextAmpleTrans");
for (Transition oldLocalTran : oldLocalNextAmpleTrans)
oldNextAmple.add(new LpnTransitionPair(lpnIndex, oldLocalTran.getIndex()));
}
}
HashSet<LpnTransitionPair> ignored = getIntSetSubstraction(curReduced, oldNextAmple);
boolean isCycleClosingAmpleComputation = true;
for (LpnTransitionPair seed : ignored) {
HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>();
dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList, isCycleClosingAmpleComputation);
if (Options.getDebugMode()) {
printIntegerSet(dependent, sgList, "dependent set for ignored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel()
+ "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
}
// TODO: Is this still necessary?
// boolean dependentOnlyHasDummyTrans = true;
// for (LpnTransitionPair dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if ((newNextAmple.size() == 0 || dependent.size() < newNextAmple.size()) && !dependentOnlyHasDummyTrans)
// newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone();
// DependentSet dependentSet = new DependentSet(newNextAmple, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
DependentSet dependentSet = new DependentSet(dependent, seed,
isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
dependentSetQueue.add(dependentSet);
}
cachedNecessarySets.clear();
if (!dependentSetQueue.isEmpty()) {
// System.out.println("depdentSetQueue is NOT empty.");
// newNextAmple = dependentSetQueue.poll().getDependent();
// TODO: Will newNextAmpleTmp - oldNextAmple be safe?
HashSet<LpnTransitionPair> newNextAmpleTmp = dependentSetQueue.poll().getDependent();
newNextAmple = getIntSetSubstraction(newNextAmpleTmp, oldNextAmple);
updateLocalAmpleTbl(newNextAmple, sgList, nextStateArray);
}
if (Options.getDebugMode()) {
printIntegerSet(newNextAmple, sgList, "newNextAmple");
System.out.println("******** behavioral: end of cycle closing check *****");
}
}
else if (cycleClosingMthd.equals("state_search")) {
// TODO: complete cycle closing check for state search.
}
return newNextAmple;
}
private void updateLocalAmpleTbl(HashSet<LpnTransitionPair> newNextAmple,
StateGraph[] sgList, State[] nextStateArray) {
// Ample set at each state is stored in the enabledSetTbl in each state graph.
for (LpnTransitionPair lpnTran : newNextAmple) {
State nextState = nextStateArray[lpnTran.getLpnIndex()];
Transition tran = sgList[lpnTran.getLpnIndex()].getLpn().getTransition(lpnTran.getTranIndex());
if (sgList[lpnTran.getLpnIndex()].getEnabledSetTbl().get(nextState) != null) {
if (!sgList[lpnTran.getLpnIndex()].getEnabledSetTbl().get(nextState).contains(tran))
sgList[lpnTran.getLpnIndex()].getEnabledSetTbl().get(nextState).add(tran);
}
else {
LpnTranList newLpnTranList = new LpnTranList();
newLpnTranList.add(tran);
sgList[lpnTran.getLpnIndex()].getEnabledSetTbl().put(nextStateArray[lpnTran.getLpnIndex()], newLpnTranList);
if (Options.getDebugMode()) {
System.out.println("@ updateLocalAmpleTbl: ");
System.out.println("Add S" + nextStateArray[lpnTran.getLpnIndex()].getIndex() + " to the enabledSetTbl of "
+ sgList[lpnTran.getLpnIndex()].getLpn().getLabel() + ".");
}
}
}
if (Options.getDebugMode())
printEnabledSetTbl(sgList);
}
private void printPrjStateSet(HashSet<PrjState> prjStateSet) {
for (PrjState curGlobal : prjStateSet) {
State[] curStateArray = curGlobal.toStateArray();
printStateArray(curStateArray);
System.out.println("
}
}
// /**
// * This method performs first-depth search on multiple LPNs and applies partial order reduction technique with the trace-back.
// * @param sgList
// * @param initStateArray
// * @param cycleClosingMthdIndex
// * @return
// */
// public StateGraph[] search_dfsPORrefinedCycleRule(final StateGraph[] sgList, final State[] initStateArray, int cycleClosingMthdIndex) {
// if (cycleClosingMthdIndex == 1)
// else if (cycleClosingMthdIndex == 2)
// else if (cycleClosingMthdIndex == 4)
// double peakUsedMem = 0;
// double peakTotalMem = 0;
// boolean failure = false;
// int tranFiringCnt = 0;
// int totalStates = 1;
// int numLpns = sgList.length;
// HashSet<PrjState> stateStack = new HashSet<PrjState>();
// Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>();
// Stack<Integer> curIndexStack = new Stack<Integer>();
// HashSet<PrjState> prjStateSet = new HashSet<PrjState>();
// PrjState initPrjState = new PrjState(initStateArray);
// prjStateSet.add(initPrjState);
// PrjState stateStackTop = initPrjState;
// System.out.println("%%%%%%% Add states to stateStack %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
// stateStack.add(stateStackTop);
// // Prepare static pieces for POR
// HashMap<Integer, HashMap<Integer, StaticSets>> staticSetsMap = new HashMap<Integer, HashMap<Integer, StaticSets>>();
// Transition[] allTransitions = sgList[0].getLpn().getAllTransitions();
// HashMap<Integer, StaticSets> tmpMap = new HashMap<Integer, StaticSets>();
// HashMap<Integer, Integer> tranFiringFreq = new HashMap<Integer, Integer>(allTransitions.length);
// for (Transition curTran: allTransitions) {
// StaticSets curStatic = new StaticSets(sgList[0].getLpn(), curTran, allTransitions);
// curStatic.buildDisableSet();
// curStatic.buildEnableSet();
// curStatic.buildModifyAssignSet();
// tmpMap.put(curTran.getIndex(), curStatic);
// tranFiringFreq.put(curTran.getIndex(), 0);
// staticSetsMap.put(sgList[0].getLpn().getLpnIndex(), tmpMap);
// printStaticSetMap(staticSetsMap);
// System.out.println("call getAmple on initStateArray at 0: ");
// boolean init = true;
// AmpleSet initAmple = new AmpleSet();
// initAmple = sgList[0].getAmple(initStateArray[0], staticSetsMap, init, tranFiringFreq);
// HashMap<State, LpnTranList> initEnabledSetTbl = (HashMap<State, LpnTranList>) sgList[0].copyEnabledSetTbl();
// lpnTranStack.push(initAmple.getAmpleSet());
// curIndexStack.push(0);
// System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
// printTransitionSet((LpnTranList) initAmple.getAmpleSet(), "");
// main_while_loop: while (failure == false && stateStack.size() != 0) {
// System.out.println("$$$$$$$$$$$ loop begins $$$$$$$$$$");
// long curTotalMem = Runtime.getRuntime().totalMemory();
// long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
// if (curTotalMem > peakTotalMem)
// peakTotalMem = curTotalMem;
// if (curUsedMem > peakUsedMem)
// peakUsedMem = curUsedMem;
// if (stateStack.size() > max_stack_depth)
// max_stack_depth = stateStack.size();
// iterations++;
// if (iterations % 100000 == 0) {
// System.out.println("---> #iteration " + iterations
// + "> # LPN transition firings: " + tranFiringCnt
// + ", # of prjStates found: " + totalStates
// + ", stack_depth: " + stateStack.size()
// + " used memory: " + (float) curUsedMem / 1000000
// + " free memory: "
// + (float) Runtime.getRuntime().freeMemory() / 1000000);
// State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek();
// int curIndex = curIndexStack.peek();
//// System.out.println("curIndex = " + curIndex);
// //AmpleSet curAmple = new AmpleSet();
// //LinkedList<Transition> curAmpleTrans = curAmple.getAmpleSet();
// LinkedList<Transition> curAmpleTrans = lpnTranStack.peek();
//// printStateArray(curStateArray);
//// System.out.println("+++++++ curAmple trans ++++++++");
//// printTransLinkedList(curAmpleTrans);
// // If all enabled transitions of the current LPN are considered,
// // then consider the next LPN
// // by increasing the curIndex.
// // Otherwise, if all enabled transitions of all LPNs are considered,
// // then pop the stacks.
// if (curAmpleTrans.size() == 0) {
// lpnTranStack.pop();
//// System.out.println("+++++++ Pop trans off lpnTranStack ++++++++");
// curIndexStack.pop();
//// System.out.println("+++++++ Pop index off curIndexStack ++++++++");
// curIndex++;
//// System.out.println("curIndex = " + curIndex);
// while (curIndex < numLpns) {
// System.out.println("call getEnabled on curStateArray at 1: ");
// LpnTranList tmpAmpleTrans = (LpnTranList) (sgList[curIndex].getAmple(curStateArray[curIndex], staticSetsMap, init, tranFiringFreq)).getAmpleSet();
// curAmpleTrans = tmpAmpleTrans.clone();
// //printTransitionSet(curEnabled, "curEnabled set");
// if (curAmpleTrans.size() > 0) {
// System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
// printTransLinkedList(curAmpleTrans);
// lpnTranStack.push(curAmpleTrans);
// curIndexStack.push(curIndex);
// printIntegerStack("curIndexStack after push 1", curIndexStack);
// break;
// curIndex++;
// if (curIndex == numLpns) {
// prjStateSet.add(stateStackTop);
// System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
// stateStack.remove(stateStackTop);
// stateStackTop = stateStackTop.getFather();
// continue;
// Transition firedTran = curAmpleTrans.removeLast();
// System.out.println("
// System.out.println("Fired transition: " + firedTran.getName());
// System.out.println("
// Integer freq = tranFiringFreq.get(firedTran.getIndex()) + 1;
// tranFiringFreq.put(firedTran.getIndex(), freq);
// System.out.println("~~~~~~tranFiringFreq~~~~~~~");
// printHashMap(tranFiringFreq, allTransitions);
// State[] nextStateArray = sgList[curIndex].fire(sgList, curStateArray, firedTran);
// tranFiringCnt++;
// Check if the firedTran causes disabling error or deadlock.
// @SuppressWarnings("unchecked")
// LinkedList<Transition>[] curAmpleArray = new LinkedList[numLpns];
// @SuppressWarnings("unchecked")
// LinkedList<Transition>[] nextAmpleArray = new LinkedList[numLpns];
// boolean updatedAmpleDueToCycleRule = false;
// for (int i = 0; i < numLpns; i++) {
// StateGraph sg_tmp = sgList[i];
// System.out.println("call getAmple on curStateArray at 2: i = " + i);
// AmpleSet ampleList = new AmpleSet();
// if (init) {
// ampleList = initAmple;
// sg_tmp.setEnabledSetTbl(initEnabledSetTbl);
// init = false;
// else
// ampleList = sg_tmp.getAmple(curStateArray[i], staticSetsMap, init, tranFiringFreq);
// curAmpleArray[i] = ampleList.getAmpleSet();
// System.out.println("call getAmpleRefinedCycleRule on nextStateArray at 3: i = " + i);
// ampleList = sg_tmp.getAmpleRefinedCycleRule(curStateArray[i], nextStateArray[i], staticSetsMap, stateStack, stateStackTop, init, cycleClosingMthdIndex, i, tranFiringFreq);
// nextAmpleArray[i] = ampleList.getAmpleSet();
// if (!updatedAmpleDueToCycleRule && ampleList.getAmpleChanged()) {
// updatedAmpleDueToCycleRule = true;
// for (LinkedList<Transition> tranList : curAmpleArray) {
// printTransLinkedList(tranList);
//// for (LinkedList<Transition> tranList : curAmpleArray) {
//// printTransLinkedList(tranList);
//// for (LinkedList<Transition> tranList : nextAmpleArray) {
//// printTransLinkedList(tranList);
// Transition disabledTran = firedTran.disablingError(
// curStateArray[i].getEnabledTransitions(), nextStateArray[i].getEnabledTransitions());
// if (disabledTran != null) {
// System.err.println("Disabling Error: "
// + disabledTran.getFullLabel() + " is disabled by "
// + firedTran.getFullLabel());
// failure = true;
// break main_while_loop;
// if (Analysis.deadLock(sgList, nextStateArray, staticSetsMap, init, tranFiringFreq) == true) {
// failure = true;
// break main_while_loop;
// PrjState nextPrjState = new PrjState(nextStateArray);
// Boolean existingState = prjStateSet.contains(nextPrjState) || stateStack.contains(nextPrjState);
// if (existingState == true && updatedAmpleDueToCycleRule) {
// // cycle closing
// System.out.println("%%%%%%% existingSate == true %%%%%%%%");
// stateStackTop.setChild(nextPrjState);
// nextPrjState.setFather(stateStackTop);
// stateStackTop = nextPrjState;
// stateStack.add(stateStackTop);
// System.out.println("%%%%%%% Add state to stateStack %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
// System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
// printTransitionSet((LpnTranList) nextAmpleArray[0], "");
// lpnTranStack.push((LpnTranList) nextAmpleArray[0].clone());
// curIndexStack.push(0);
// if (existingState == false) {
// System.out.println("%%%%%%% existingSate == false %%%%%%%%");
// stateStackTop.setChild(nextPrjState);
// nextPrjState.setFather(stateStackTop);
// stateStackTop = nextPrjState;
// stateStack.add(stateStackTop);
// System.out.println("%%%%%%% Add state to stateStack %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
// System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
// printTransitionSet((LpnTranList) nextAmpleArray[0], "");
// lpnTranStack.push((LpnTranList) nextAmpleArray[0].clone());
// curIndexStack.push(0);
// totalStates++;
// // end of main_while_loop
// double totalStateCnt = prjStateSet.size();
// System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt
// + ", # of prjStates found: " + totalStateCnt
// + ", max_stack_depth: " + max_stack_depth
// + ", peak total memory: " + peakTotalMem / 1000000 + " MB"
// + ", peak used memory: " + peakUsedMem / 1000000 + " MB");
// // This currently works for a single LPN.
// return sgList;
// return null;
private void printHashMap(HashMap<LpnTransitionPair, Integer> tranFiringFreq, StateGraph[] sgList) {
for (LpnTransitionPair curIndex : tranFiringFreq.keySet()) {
LhpnFile curLpn = sgList[curIndex.getLpnIndex()].getLpn();
Transition curTran = curLpn.getTransition(curIndex.getTranIndex());
System.out.println(curLpn.getLabel() + "(" + curTran.getName() + ")" + " -> " + tranFiringFreq.get(curIndex));
}
}
private void printStaticSetsMap(
LhpnFile[] lpnList, HashMap<LpnTransitionPair,StaticSets> staticSetsMap) {
System.out.println("
for (LpnTransitionPair lpnTranPair : staticSetsMap.keySet()) {
StaticSets statSets = staticSetsMap.get(lpnTranPair);
printLpnTranPair(lpnList, statSets.getTran(), statSets.getDisableSet(), "disableSet");
printLpnTranPair(lpnList, statSets.getTran(), statSets.getEnableBySettingEnablingTrue(), "enableBySetingEnablingTrue");
}
}
private void writeStaticSetsMapToPORDebugFile(
LhpnFile[] lpnList, HashMap<LpnTransitionPair,StaticSets> staticSetsMap) {
try {
PORdebugBufferedWriter.write("
PORdebugBufferedWriter.newLine();
for (LpnTransitionPair lpnTranPair : staticSetsMap.keySet()) {
StaticSets statSets = staticSetsMap.get(lpnTranPair);
writeLpnTranPairToPORDebugFile(lpnList, statSets.getTran(), statSets.getDisableSet(), "disableSet");
writeLpnTranPairToPORDebugFile(lpnList, statSets.getTran(), statSets.getEnableBySettingEnablingTrue(), "enableBySetingEnablingTrue");
}
} catch (IOException e) {
e.printStackTrace();
}
}
// private Transition[] assignStickyTransitions(LhpnFile lpn) {
// // allProcessTrans is a hashmap from a transition to its process color (integer).
// HashMap<Transition, Integer> allProcessTrans = new HashMap<Transition, Integer>();
// // create an Abstraction object to call the divideProcesses method.
// Abstraction abs = new Abstraction(lpn);
// abs.decomposeLpnIntoProcesses();
// allProcessTrans.putAll(
// (HashMap<Transition, Integer>)abs.getTransWithProcIDs().clone());
// HashMap<Integer, LpnProcess> processMap = new HashMap<Integer, LpnProcess>();
// for (Iterator<Transition> tranIter = allProcessTrans.keySet().iterator(); tranIter.hasNext();) {
// Transition curTran = tranIter.next();
// Integer procId = allProcessTrans.get(curTran);
// if (!processMap.containsKey(procId)) {
// LpnProcess newProcess = new LpnProcess(procId);
// newProcess.addTranToProcess(curTran);
// if (curTran.getPreset() != null) {
// Place[] preset = curTran.getPreset();
// for (Place p : preset) {
// newProcess.addPlaceToProcess(p);
// processMap.put(procId, newProcess);
// else {
// LpnProcess curProcess = processMap.get(procId);
// curProcess.addTranToProcess(curTran);
// if (curTran.getPreset() != null) {
// Place[] preset = curTran.getPreset();
// for (Place p : preset) {
// curProcess.addPlaceToProcess(p);
// for(Iterator<Integer> processMapIter = processMap.keySet().iterator(); processMapIter.hasNext();) {
// LpnProcess curProc = processMap.get(processMapIter.next());
// curProc.assignStickyTransitions();
// curProc.printProcWithStickyTrans();
// return lpn.getAllTransitions();
// private void printPlacesIndices(ArrayList<String> allPlaces) {
// System.out.println("Indices of all places: ");
// for (int i=0; i < allPlaces.size(); i++) {
// System.out.println(allPlaces.get(i) + "\t" + i);
// private void printTransIndices(Transition[] allTransitions) {
// System.out.println("Indices of all transitions: ");
// for (int i=0; i < allTransitions.length; i++) {
// System.out.println(allTransitions[i].getName() + "\t" + allTransitions[i].getIndex());
private void printLpnTranPair(LhpnFile[] lpnList, Transition curTran,
HashSet<LpnTransitionPair> curDisable, String setName) {
System.out.print(setName + " for " + curTran.getName() + "(" + curTran.getIndex() + ")" + " is: ");
if (curDisable.isEmpty()) {
System.out.println("empty");
}
else {
for (LpnTransitionPair lpnTranPair: curDisable) {
System.out.print("(" + lpnList[lpnTranPair.getLpnIndex()].getLabel()
+ ", " + lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ")," + "\t");
}
System.out.print("\n");
}
}
private void writeLpnTranPairToPORDebugFile(LhpnFile[] lpnList, Transition curTran,
HashSet<LpnTransitionPair> curDisable, String setName) {
try {
//PORdebugBufferedWriter.write(setName + " for " + curTran.getName() + "(" + curTran.getIndex() + ")" + " is: ");
PORdebugBufferedWriter.write(setName + " for (" + curTran.getLpn().getLabel() + " , " + curTran.getName() + ") is: ");
if (curDisable.isEmpty()) {
PORdebugBufferedWriter.write("empty");
PORdebugBufferedWriter.newLine();
}
else {
for (LpnTransitionPair lpnTranPair: curDisable) {
PORdebugBufferedWriter.append("(" + lpnList[lpnTranPair.getLpnIndex()].getLabel()
+ ", " + lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ")," + "\t");
}
PORdebugBufferedWriter.newLine();
}
PORdebugBufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void printTransitionSet(LpnTranList transitionSet, String setName) {
if (!setName.isEmpty())
System.out.print(setName + " is: ");
if (transitionSet.isEmpty()) {
System.out.println("empty");
}
else {
for (Iterator<Transition> curTranIter = transitionSet.iterator(); curTranIter.hasNext();) {
Transition tranInDisable = curTranIter.next();
System.out.print(tranInDisable.getName() + " ");
}
System.out.print("\n");
}
}
// private void printTransitionSet(LinkedList<Transition> transitionSet, String setName) {
// System.out.print(setName + " is: ");
// if (transitionSet.isEmpty()) {
// System.out.println("empty");
// else {
// for (Iterator<Transition> curTranIter = transitionSet.iterator(); curTranIter.hasNext();) {
// Transition tranInDisable = curTranIter.next();
// System.out.print(tranInDisable.getIndex() + " ");
// System.out.print("\n");
/**
* Return the set of all LPN transitions that are enabled in 'state'. The "init" flag indicates whether a transition
* needs to be evaluated. The enabledSetTbl (for each StateGraph obj) stores the AMPLE set for each state of each LPN.
* @param stateArray
* @param stateStack
* @param enable
* @param disableByStealingToken
* @param disable
* @param init
* @param tranFiringFreq
* @param sgList
* @return
*/
public LpnTranList getAmple(State[] curStateArray, State[] nextStateArray, HashMap<LpnTransitionPair,StaticSets> staticSetsMap,
boolean init, HashMap<LpnTransitionPair, Integer> tranFiringFreq, StateGraph[] sgList,
HashSet<PrjState> stateStack, PrjState stateStackTop) {
State[] stateArray = null;
if (nextStateArray == null)
stateArray = curStateArray;
else
stateArray = nextStateArray;
for (State s : stateArray)
if (s == null)
throw new NullPointerException();
LpnTranList ample = new LpnTranList();
HashSet<LpnTransitionPair> curEnabled = new HashSet<LpnTransitionPair>();
for (int lpnIndex=0; lpnIndex<stateArray.length; lpnIndex++) {
State state = stateArray[lpnIndex];
if (init) {
LhpnFile curLpn = sgList[lpnIndex].getLpn();
for (int i=0; i < curLpn.getAllTransitions().length; i++) {
Transition tran = curLpn.getAllTransitions()[i];
if (sgList[lpnIndex].isEnabled(tran,state)){
curEnabled.add(new LpnTransitionPair(curLpn.getLpnIndex(), i));
}
}
}
else {
LhpnFile curLpn = sgList[lpnIndex].getLpn();
for (int i=0; i < curLpn.getAllTransitions().length; i++) {
if (stateArray[lpnIndex].getTranVector()[i]) {
curEnabled.add(new LpnTransitionPair(curLpn.getLpnIndex(), i));
}
}
}
}
HashSet<LpnTransitionPair> ready = new HashSet<LpnTransitionPair>();
if (Options.getDebugMode()) {
System.out.println("******** Partial Order Reduction ************");
printIntegerSet(curEnabled, sgList, "Enabled set");
System.out.println("******* Begin POR");
writeStringWithNewLineToPORDebugFile("******* Partial Order Reduction *******");
writeIntegerSetToPORDebugFile(curEnabled, sgList, "Enabled set");
writeStringWithNewLineToPORDebugFile("******* Begin POR *******");
}
if (curEnabled.isEmpty()) {
return ample;
}
// if (Options.getNecessaryUsingDependencyGraphs())
// ready = partialOrderReductionUsingDependencyGraphs(stateArray, curEnabled, staticSetsMap, sgList);
// else
ready = partialOrderReduction(stateArray, curEnabled, staticSetsMap, tranFiringFreq, sgList);
if (Options.getDebugMode()) {
System.out.println("******* End POR *******");
printIntegerSet(ready, sgList, "Ready set");
System.out.println("********************");
writeStringWithNewLineToPORDebugFile("******* End POR *******");
writeIntegerSetToPORDebugFile(ready, sgList, "Ready set");
writeStringWithNewLineToPORDebugFile("********************");
}
//if (tranFiringFreq != null) {
LinkedList<LpnTransitionPair> readyList = new LinkedList<LpnTransitionPair>();
for (LpnTransitionPair inReady : ready) {
readyList.add(inReady);
}
mergeSort(readyList, tranFiringFreq);
for (LpnTransitionPair inReady : readyList) {
LhpnFile lpn = sgList[inReady.getLpnIndex()].getLpn();
Transition tran = lpn.getTransition(inReady.getTranIndex());
ample.addFirst(tran);
}
// else {
// for (LpnTransitionPair inReady : ready) {
// LhpnFile lpn = sgList[inReady.getLpnIndex()].getLpn();
// Transition tran = lpn.getTransition(inReady.getTranIndex());
// ample.add(tran);
return ample;
}
private LinkedList<LpnTransitionPair> mergeSort(LinkedList<LpnTransitionPair> array, HashMap<LpnTransitionPair, Integer> tranFiringFreq) {
if (array.size() == 1)
return array;
int middle = array.size() / 2;
LinkedList<LpnTransitionPair> left = new LinkedList<LpnTransitionPair>();
LinkedList<LpnTransitionPair> right = new LinkedList<LpnTransitionPair>();
for (int i=0; i<middle; i++) {
left.add(i, array.get(i));
}
for (int i=middle; i<array.size();i++) {
right.add(i-middle, array.get(i));
}
left = mergeSort(left, tranFiringFreq);
right = mergeSort(right, tranFiringFreq);
return merge(left, right, tranFiringFreq);
}
private LinkedList<LpnTransitionPair> merge(LinkedList<LpnTransitionPair> left,
LinkedList<LpnTransitionPair> right, HashMap<LpnTransitionPair, Integer> tranFiringFreq) {
LinkedList<LpnTransitionPair> result = new LinkedList<LpnTransitionPair>();
while (left.size() > 0 || right.size() > 0) {
if (left.size() > 0 && right.size() > 0) {
if (tranFiringFreq.get(left.peek()) <= tranFiringFreq.get(right.peek())) {
result.addLast(left.poll());
}
else {
result.addLast(right.poll());
}
}
else if (left.size()>0) {
result.addLast(left.poll());
}
else if (right.size()>0) {
result.addLast(right.poll());
}
}
return result;
}
/**
* Return the set of all LPN transitions that are enabled in 'state'. The "init" flag indicates whether a transition
* needs to be evaluated.
* @param nextState
* @param stateStackTop
* @param enable
* @param disableByStealingToken
* @param disable
* @param init
* @param cycleClosingMthdIndex
* @param lpnIndex
* @param isNextState
* @return
*/
public LpnTranList getAmpleRefinedCycleRule(State[] curStateArray, State[] nextStateArray, HashMap<LpnTransitionPair,StaticSets> staticSetsMap,
boolean init, HashMap<LpnTransitionPair,Integer> tranFiringFreq, StateGraph[] sgList,
HashSet<PrjState> stateStack, PrjState stateStackTop) {
// AmpleSet nextAmple = new AmpleSet();
// if (nextState == null) {
// throw new NullPointerException();
// if(ampleSetTbl.containsKey(nextState) == true && stateOnStack(nextState, stateStack)) {
// System.out.println("~~~~~~~ existing state in enabledSetTbl and on stateStack: S" + nextState.getIndex() + "~~~~~~~~");
// printTransitionSet((LpnTranList)ampleSetTbl.get(nextState), "Old ample at this state: ");
// // Cycle closing check
// LpnTranList nextAmpleTransOld = (LpnTranList) nextAmple.getAmpleSet();
// nextAmpleTransOld = ampleSetTbl.get(nextState);
// LpnTranList curAmpleTrans = ampleSetTbl.get(curState);
// LpnTranList curReduced = new LpnTranList();
// LpnTranList curEnabled = curState.getEnabledTransitions();
// for (int i=0; i<curEnabled.size(); i++) {
// if (!curAmpleTrans.contains(curEnabled.get(i))) {
// curReduced.add(curEnabled.get(i));
// if (!nextAmpleTransOld.containsAll(curReduced)) {
// System.out.println("((((((((((((((((((((()))))))))))))))))))))");
// printTransitionSet(curEnabled, "curEnabled:");
// printTransitionSet(curAmpleTrans, "curAmpleTrans:");
// printTransitionSet(curReduced, "curReduced:");
// printTransitionSet(nextState.getEnabledTransitions(), "nextEnabled:");
// printTransitionSet(nextAmpleTransOld, "nextAmpleTransOld:");
// nextAmple.setAmpleChanged();
// HashSet<LpnTransitionPair> curEnabledIndicies = new HashSet<LpnTransitionPair>();
// for (int i=0; i<curEnabled.size(); i++) {
// curEnabledIndicies.add(curEnabled.get(i).getIndex());
// // transToAdd = curReduced - nextAmpleOld
// LpnTranList overlyReducedTrans = getSetSubtraction(curReduced, nextAmpleTransOld);
// HashSet<Integer> transToAddIndices = new HashSet<Integer>();
// for (int i=0; i<overlyReducedTrans.size(); i++) {
// transToAddIndices.add(overlyReducedTrans.get(i).getIndex());
// HashSet<Integer> nextAmpleNewIndices = (HashSet<Integer>) curEnabledIndicies.clone();
// for (Integer tranToAdd : transToAddIndices) {
// HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>();
// //Transition enabledTransition = this.lpn.getAllTransitions()[tranToAdd];
// dependent = getDependentSet(curState,tranToAdd,dependent,curEnabledIndicies,staticMap);
// // printIntegerSet(dependent, "dependent set for enabled transition " + this.lpn.getAllTransitions()[enabledTran]);
// boolean dependentOnlyHasDummyTrans = true;
// for (Integer curTranIndex : dependent) {
// Transition curTran = this.lpn.getAllTransitions()[curTranIndex];
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans && isDummyTran(curTran.getName());
// if (dependent.size() < nextAmpleNewIndices.size() && !dependentOnlyHasDummyTrans)
// nextAmpleNewIndices = (HashSet<Integer>) dependent.clone();
// if (nextAmpleNewIndices.size() == 1)
// break;
// LpnTranList nextAmpleNew = new LpnTranList();
// for (Integer nextAmpleNewIndex : nextAmpleNewIndices) {
// nextAmpleNew.add(this.getLpn().getTransition(nextAmpleNewIndex));
// LpnTranList transToAdd = getSetSubtraction(nextAmpleNew, nextAmpleTransOld);
// boolean allTransToAddFired = false;
// if (cycleClosingMthdIndex == 2) {
// // For every transition t in transToAdd, if t was fired in the any state on stateStack, there is no need to put it to the new ample of nextState.
// if (transToAdd != null) {
// LpnTranList transToAddCopy = transToAdd.copy();
// HashSet<Integer> stateVisited = new HashSet<Integer>();
// stateVisited.add(nextState.getIndex());
// allTransToAddFired = allTransToAddFired(transToAddCopy,
// allTransToAddFired, stateVisited, stateStackTop, lpnIndex);
// // Update the old ample of the next state
// if (!allTransToAddFired || cycleClosingMthdIndex == 1) {
// nextAmple.getAmpleSet().clear();
// nextAmple.getAmpleSet().addAll(transToAdd);
// ampleSetTbl.get(nextState).addAll(transToAdd);
// printTransitionSet(nextAmpleNew, "nextAmpleNew:");
// printTransitionSet(transToAdd, "transToAdd:");
// System.out.println("((((((((((((((((((((()))))))))))))))))))))");
// if (cycleClosingMthdIndex == 4) {
// nextAmple.getAmpleSet().clear();
// nextAmple.getAmpleSet().addAll(overlyReducedTrans);
// ampleSetTbl.get(nextState).addAll(overlyReducedTrans);
// printTransitionSet(nextAmpleNew, "nextAmpleNew:");
// printTransitionSet(transToAdd, "transToAdd:");
// System.out.println("((((((((((((((((((((()))))))))))))))))))))");
// // enabledSetTble stores the ample set at curState.
// // The fully enabled set at each state is stored in the tranVector in each state.
// return (AmpleSet) nextAmple;
// for (State s : nextStateArray)
// if (s == null)
// throw new NullPointerException();
// cachedNecessarySets.clear();
// String cycleClosingMthd = Options.getCycleClosingMthd();
// AmpleSet nextAmple = new AmpleSet();
// HashSet<LpnTransitionPair> nextEnabled = new HashSet<LpnTransitionPair>();
//// boolean allEnabledAreSticky = false;
// for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) {
// State nextState = nextStateArray[lpnIndex];
// if (init) {
// LhpnFile curLpn = sgList[lpnIndex].getLpn();
// //allEnabledAreSticky = true;
// for (int i=0; i < curLpn.getAllTransitions().length; i++) {
// Transition tran = curLpn.getAllTransitions()[i];
// if (sgList[lpnIndex].isEnabled(tran,nextState)){
// nextEnabled.add(new LpnTransitionPair(curLpn.getLpnIndex(), i));
// //allEnabledAreSticky = allEnabledAreSticky && tran.isSticky();
// //sgList[lpnIndex].getEnabledSetTbl().put(nextStateArray[lpnIndex], new LpnTranList());
// else {
// LhpnFile curLpn = sgList[lpnIndex].getLpn();
// for (int i=0; i < curLpn.getAllTransitions().length; i++) {
// Transition tran = curLpn.getAllTransitions()[i];
// if (nextStateArray[lpnIndex].getTranVector()[i]) {
// nextEnabled.add(new LpnTransitionPair(curLpn.getLpnIndex(), i));
// //allEnabledAreSticky = allEnabledAreSticky && tran.isSticky();
// //sgList[lpnIndex].getEnabledSetTbl().put(nextStateArray[lpnIndex], new LpnTranList());
// DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq);
// PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(nextEnabled.size(), depComp);
// LhpnFile[] lpnList = new LhpnFile[sgList.length];
// for (int i=0; i<sgList.length; i++)
// lpnList[i] = sgList[i].getLpn();
// HashMap<LpnTransitionPair, LpnTranList> transToAddMap = new HashMap<LpnTransitionPair, LpnTranList>();
// Integer cycleClosingLpnIndex = -1;
// for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) {
// State curState = curStateArray[lpnIndex];
// State nextState = nextStateArray[lpnIndex];
// if(sgList[lpnIndex].getEnabledSetTbl().containsKey(nextState) == true
// && !sgList[lpnIndex].getEnabledSetTbl().get(nextState).isEmpty()
// && stateOnStack(lpnIndex, nextState, stateStack)
// && nextState.getIndex() != curState.getIndex()) {
// cycleClosingLpnIndex = lpnIndex;
// System.out.println("~~~~~~~ existing state in enabledSetTbl for LPN " + sgList[lpnIndex].getLpn().getLabel() +": S" + nextState.getIndex() + "~~~~~~~~");
// printAmpleSet((LpnTranList)sgList[lpnIndex].getEnabledSetTbl().get(nextState), "Old ample at this state: ");
// LpnTranList oldLocalNextAmpleTrans = sgList[lpnIndex].getEnabledSetTbl().get(nextState);
// LpnTranList curLocalAmpleTrans = sgList[lpnIndex].getEnabledSetTbl().get(curState);
// LpnTranList reducedLocalTrans = new LpnTranList();
// LpnTranList curLocalEnabledTrans = curState.getEnabledTransitions();
// System.out.println("The firedTran is a cycle closing transition.");
// if (cycleClosingMthd.toLowerCase().equals("behavioral") || cycleClosingMthd.toLowerCase().equals("state_search")) {
// // firedTran is a cycle closing transition.
// for (int i=0; i<curLocalEnabledTrans.size(); i++) {
// if (!curLocalAmpleTrans.contains(curLocalEnabledTrans.get(i))) {
// reducedLocalTrans.add(curLocalEnabledTrans.get(i));
// if (!oldLocalNextAmpleTrans.containsAll(reducedLocalTrans)) {
// printTransitionSet(curLocalEnabledTrans, "curLocalEnabled:");
// printTransitionSet(curLocalAmpleTrans, "curAmpleTrans:");
// printTransitionSet(reducedLocalTrans, "reducedLocalTrans:");
// printTransitionSet(nextState.getEnabledTransitions(), "nextLocalEnabled:");
// printTransitionSet(oldLocalNextAmpleTrans, "nextAmpleTransOld:");
// // nextAmple.setAmpleChanged();
// // ignoredTrans should not be empty here.
// LpnTranList ignoredTrans = getSetSubtraction(reducedLocalTrans, oldLocalNextAmpleTrans);
// HashSet<LpnTransitionPair> ignored = new HashSet<LpnTransitionPair>();
// for (int i=0; i<ignoredTrans.size(); i++) {
// ignored.add(new LpnTransitionPair(lpnIndex, ignoredTrans.get(i).getIndex()));
// HashSet<LpnTransitionPair> newNextAmple = (HashSet<LpnTransitionPair>) nextEnabled.clone();
// if (cycleClosingMthd.toLowerCase().equals("behavioral")) {
// for (LpnTransitionPair seed : ignored) {
// HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>();
// dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList);
// printIntegerSet(dependent, sgList, "dependent set for ignored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
// boolean dependentOnlyHasDummyTrans = true;
// for (LpnTransitionPair dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans)
// newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone();
//// if (nextAmpleNewIndices.size() == 1)
//// break;
// DependentSet dependentSet = new DependentSet(newNextAmple, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
// dependentSetQueue.add(dependentSet);
// LpnTranList newLocalNextAmpleTrans = new LpnTranList();
// for (LpnTransitionPair tran : newNextAmple) {
// if (tran.getLpnIndex() == lpnIndex)
// newLocalNextAmpleTrans.add(sgList[lpnIndex].getLpn().getTransition(tran.getTranIndex()));
// LpnTranList transToAdd = getSetSubtraction(newLocalNextAmpleTrans, oldLocalNextAmpleTrans);
// transToAddMap.put(seed, transToAdd);
// else if (cycleClosingMthd.toLowerCase().equals("state_search")) {
// // For every transition t in ignored, if t was fired in any state on stateStack, there is no need to put it to the new ample of nextState.
// HashSet<Integer> stateVisited = new HashSet<Integer>();
// stateVisited.add(nextState.getIndex());
// LpnTranList trulyIgnoredTrans = ignoredTrans.copy();
// trulyIgnoredTrans = allIgnoredTransFired(trulyIgnoredTrans, stateVisited, stateStackTop, lpnIndex, sgList[lpnIndex]);
// if (!trulyIgnoredTrans.isEmpty()) {
// HashSet<LpnTransitionPair> trulyIgnored = new HashSet<LpnTransitionPair>();
// for (Transition tran : trulyIgnoredTrans) {
// trulyIgnored.add(new LpnTransitionPair(tran.getLpn().getLpnIndex(), tran.getIndex()));
// for (LpnTransitionPair seed : trulyIgnored) {
// HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>();
// dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList);
// printIntegerSet(dependent, sgList, "dependent set for trulyIgnored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
// boolean dependentOnlyHasDummyTrans = true;
// for (LpnTransitionPair dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans)
// newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone();
// DependentSet dependentSet = new DependentSet(newNextAmple, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
// dependentSetQueue.add(dependentSet);
// LpnTranList newLocalNextAmpleTrans = new LpnTranList();
// for (LpnTransitionPair tran : newNextAmple) {
// if (tran.getLpnIndex() == lpnIndex)
// newLocalNextAmpleTrans.add(sgList[lpnIndex].getLpn().getTransition(tran.getTranIndex()));
// LpnTranList transToAdd = getSetSubtraction(newLocalNextAmpleTrans, oldLocalNextAmpleTrans);
// transToAddMap.put(seed, transToAdd);
// else { // All ignored transitions were fired before. It is safe to close the current cycle.
// HashSet<LpnTransitionPair> oldLocalNextAmple = new HashSet<LpnTransitionPair>();
// for (Transition tran : oldLocalNextAmpleTrans)
// oldLocalNextAmple.add(new LpnTransitionPair(tran.getLpn().getLpnIndex(), tran.getIndex()));
// for (LpnTransitionPair seed : oldLocalNextAmple) {
// HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>();
// dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList);
// printIntegerSet(dependent, sgList, "dependent set for transition in oldNextAmple is " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
// boolean dependentOnlyHasDummyTrans = true;
// for (LpnTransitionPair dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans)
// newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone();
// DependentSet dependentSet = new DependentSet(newNextAmple, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
// dependentSetQueue.add(dependentSet);
// else {
// // oldNextAmpleTrans.containsAll(curReducedTrans) == true (safe to close the current cycle)
// HashSet<LpnTransitionPair> newNextAmple = (HashSet<LpnTransitionPair>) nextEnabled.clone();
// HashSet<LpnTransitionPair> oldLocalNextAmple = new HashSet<LpnTransitionPair>();
// for (Transition tran : oldLocalNextAmpleTrans)
// oldLocalNextAmple.add(new LpnTransitionPair(tran.getLpn().getLpnIndex(), tran.getIndex()));
// for (LpnTransitionPair seed : oldLocalNextAmple) {
// HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>();
// dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList);
// printIntegerSet(dependent, sgList, "dependent set for transition in oldNextAmple is " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
// boolean dependentOnlyHasDummyTrans = true;
// for (LpnTransitionPair dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans)
// newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone();
// DependentSet dependentSet = new DependentSet(newNextAmple, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
// dependentSetQueue.add(dependentSet);
// else if (cycleClosingMthd.toLowerCase().equals("strong")) {
// LpnTranList ignoredTrans = getSetSubtraction(reducedLocalTrans, oldLocalNextAmpleTrans);
// HashSet<LpnTransitionPair> ignored = new HashSet<LpnTransitionPair>();
// for (int i=0; i<ignoredTrans.size(); i++) {
// ignored.add(new LpnTransitionPair(lpnIndex, ignoredTrans.get(i).getIndex()));
// HashSet<LpnTransitionPair> allNewNextAmple = new HashSet<LpnTransitionPair>();
// for (LpnTransitionPair seed : ignored) {
// HashSet<LpnTransitionPair> newNextAmple = (HashSet<LpnTransitionPair>) nextEnabled.clone();
// HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>();
// dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList);
// printIntegerSet(dependent, sgList, "dependent set for transition in curLocalEnabled is " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
// boolean dependentOnlyHasDummyTrans = true;
// for (LpnTransitionPair dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans)
// newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone();
// allNewNextAmple.addAll(newNextAmple);
// // The strong cycle condition requires all seeds in ignored to be included in the allNewNextAmple, as well as dependent set for each seed.
// // So each seed should have the same new ample set.
// for (LpnTransitionPair seed : ignored) {
// DependentSet dependentSet = new DependentSet(allNewNextAmple, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
// dependentSetQueue.add(dependentSet);
// else { // firedTran is not a cycle closing transition. Compute next ample.
//// if (nextEnabled.size() == 1)
//// return nextEnabled;
// System.out.println("The firedTran is NOT a cycle closing transition.");
// HashSet<LpnTransitionPair> ready = null;
// for (LpnTransitionPair seed : nextEnabled) {
// System.out.println("@ partialOrderReduction, consider transition " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "("+ sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()) + ")");
// HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>();
// Transition enabledTransition = sgList[seed.getLpnIndex()].getLpn().getAllTransitions()[seed.getTranIndex()];
// boolean enabledIsDummy = false;
//// if (enabledTransition.isSticky()) {
//// dependent = (HashSet<LpnTransitionPair>) nextEnabled.clone();
//// else {
//// dependent = computeDependent(curStateArray,seed,dependent,nextEnabled,staticMap, lpnList);
// dependent = computeDependent(curStateArray,seed,dependent,nextEnabled,staticSetsMap,lpnList);
// printIntegerSet(dependent, sgList, "dependent set for enabled transition " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + enabledTransition.getName() + ")");
// if (isDummyTran(enabledTransition.getName()))
// enabledIsDummy = true;
// for (LpnTransitionPair inDependent : dependent) {
// if(inDependent.getLpnIndex() == cycleClosingLpnIndex) {
// // check cycle closing condition
// break;
// DependentSet dependentSet = new DependentSet(dependent, seed, enabledIsDummy);
// dependentSetQueue.add(dependentSet);
// ready = dependentSetQueue.poll().getDependent();
//// // Update the old ample of the next state
//// boolean allTransToAddFired = false;
//// if (cycleClosingMthdIndex == 2) {
//// // For every transition t in transToAdd, if t was fired in the any state on stateStack, there is no need to put it to the new ample of nextState.
//// if (transToAdd != null) {
//// LpnTranList transToAddCopy = transToAdd.copy();
//// HashSet<Integer> stateVisited = new HashSet<Integer>();
//// stateVisited.add(nextState.getIndex());
//// allTransToAddFired = allTransToAddFired(transToAddCopy,
//// allTransToAddFired, stateVisited, stateStackTop, lpnIndex);
//// // Update the old ample of the next state
//// if (!allTransToAddFired || cycleClosingMthdIndex == 1) {
//// nextAmple.getAmpleSet().clear();
//// nextAmple.getAmpleSet().addAll(transToAdd);
//// ampleSetTbl.get(nextState).addAll(transToAdd);
//// printTransitionSet(nextAmpleNew, "nextAmpleNew:");
//// printTransitionSet(transToAdd, "transToAdd:");
//// System.out.println("((((((((((((((((((((()))))))))))))))))))))");
//// if (cycleClosingMthdIndex == 4) {
//// nextAmple.getAmpleSet().clear();
//// nextAmple.getAmpleSet().addAll(ignoredTrans);
//// ampleSetTbl.get(nextState).addAll(ignoredTrans);
//// printTransitionSet(nextAmpleNew, "nextAmpleNew:");
//// printTransitionSet(transToAdd, "transToAdd:");
//// System.out.println("((((((((((((((((((((()))))))))))))))))))))");
//// // enabledSetTble stores the ample set at curState.
//// // The fully enabled set at each state is stored in the tranVector in each state.
//// return (AmpleSet) nextAmple;
return null;
}
private LpnTranList allIgnoredTransFired(LpnTranList ignoredTrans,
HashSet<Integer> stateVisited, PrjState stateStackEntry, int lpnIndex, StateGraph sg) {
State state = stateStackEntry.get(lpnIndex);
System.out.println("state = " + state.getIndex());
State predecessor = stateStackEntry.getFather().get(lpnIndex);
if (predecessor != null)
System.out.println("predecessor = " + predecessor.getIndex());
if (predecessor == null || stateVisited.contains(predecessor.getIndex())) {
return ignoredTrans;
}
else
stateVisited.add(predecessor.getIndex());
LpnTranList predecessorOldAmple = sg.getEnabledSetTbl().get(predecessor);//enabledSetTbl.get(predecessor);
for (Transition oldAmpleTran : predecessorOldAmple) {
State tmpState = sg.getNextStateMap().get(predecessor).get(oldAmpleTran);
if (tmpState.getIndex() == state.getIndex()) {
ignoredTrans.remove(oldAmpleTran);
break;
}
}
if (ignoredTrans.size()==0) {
return ignoredTrans;
}
else {
ignoredTrans = allIgnoredTransFired(ignoredTrans, stateVisited, stateStackEntry.getFather(), lpnIndex, sg);
}
return ignoredTrans;
}
// for (Transition oldAmpleTran : oldAmple) {
// State successor = nextStateMap.get(nextState).get(oldAmpleTran);
// if (stateVisited.contains(successor.getIndex())) {
// break;
// else
// stateVisited.add(successor.getIndex());
// LpnTranList successorOldAmple = enabledSetTbl.get(successor);
// // Either successor or sucessorOldAmple should not be null for a nonterminal state graph.
// HashSet<Transition> transToAddFired = new HashSet<Transition>();
// for (Transition tran : transToAddCopy) {
// if (successorOldAmple.contains(tran))
// transToAddFired.add(tran);
// transToAddCopy.removeAll(transToAddFired);
// if (transToAddCopy.size() == 0) {
// allTransFired = true;
// break;
// else {
// allTransFired = allTransToAddFired(successorOldAmple, nextState, successor,
// transToAddCopy, allTransFired, stateVisited, stateStackEntry, lpnIndex);
// return allTransFired;
/**
* An iterative implement of findsg_recursive().
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
*/
/**
* An iterative implement of findsg_recursive().
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
*/
public Stack<State[]> search_dfs_noDisabling_fireOrder(final StateGraph[] lpnList, final State[] initStateArray) {
boolean firingOrder = false;
long peakUsedMem = 0;
long peakTotalMem = 0;
boolean failure = false;
int tranFiringCnt = 0;
int arraySize = lpnList.length;
HashSet<PrjLpnState> globalStateTbl = new HashSet<PrjLpnState>();
@SuppressWarnings("unchecked")
IndexObjMap<LpnState>[] lpnStateCache = new IndexObjMap[arraySize];
//HashMap<LpnState, LpnState>[] lpnStateCache1 = new HashMap[arraySize];
Stack<LpnState[]> stateStack = new Stack<LpnState[]>();
Stack<LpnTranList[]> lpnTranStack = new Stack<LpnTranList[]>();
//get initial enable transition set
LpnTranList initEnabled = new LpnTranList();
LpnTranList initFireFirst = new LpnTranList();
LpnState[] initLpnStateArray = new LpnState[arraySize];
for (int i = 0; i < arraySize; i++)
{
lpnStateCache[i] = new IndexObjMap<LpnState>();
LinkedList<Transition> enabledTrans = lpnList[i].getEnabled(initStateArray[i]);
HashSet<Transition> enabledSet = new HashSet<Transition>();
if(!enabledTrans.isEmpty())
{
for(Transition tran : enabledTrans) {
enabledSet.add(tran);
initEnabled.add(tran);
}
}
LpnState curLpnState = new LpnState(lpnList[i].getLpn(), initStateArray[i], enabledSet);
lpnStateCache[i].add(curLpnState);
initLpnStateArray[i] = curLpnState;
}
LpnTranList[] initEnabledSet = new LpnTranList[2];
initEnabledSet[0] = initFireFirst;
initEnabledSet[1] = initEnabled;
lpnTranStack.push(initEnabledSet);
stateStack.push(initLpnStateArray);
globalStateTbl.add(new PrjLpnState(initLpnStateArray));
main_while_loop: while (failure == false && stateStack.empty() == false) {
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory()
- Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
//if(iterations>2)break;
if (iterations % 100000 == 0)
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + globalStateTbl.size()
+ ", current_stack_depth: " + stateStack.size()
+ ", total MDD nodes: " + mddMgr.nodeCnt()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
LpnTranList[] curEnabled = lpnTranStack.peek();
LpnState[] curLpnStateArray = stateStack.peek();
// If all enabled transitions of the current LPN are considered,
// then consider the next LPN
// by increasing the curIndex.
// Otherwise, if all enabled transitions of all LPNs are considered,
// then pop the stacks.
if(curEnabled[0].size()==0 && curEnabled[1].size()==0){
lpnTranStack.pop();
stateStack.pop();
continue;
}
Transition firedTran = null;
if(curEnabled[0].size() != 0)
firedTran = curEnabled[0].removeFirst();
else
firedTran = curEnabled[1].removeFirst();
traceCex.addLast(firedTran);
State[] curStateArray = new State[arraySize];
for( int i = 0; i < arraySize; i++)
curStateArray[i] = curLpnStateArray[i].getState();
StateGraph sg = null;
for (int i=0; i<lpnList.length; i++) {
if (lpnList[i].getLpn().equals(firedTran.getLpn())) {
sg = lpnList[i];
}
}
State[] nextStateArray = sg.fire(lpnList, curStateArray, firedTran);
// Check if the firedTran causes disabling error or deadlock.
@SuppressWarnings("unchecked")
HashSet<Transition>[] extendedNextEnabledArray = new HashSet[arraySize];
for (int i = 0; i < arraySize; i++) {
HashSet<Transition> curEnabledSet = curLpnStateArray[i].getEnabled();
LpnTranList nextEnabledList = lpnList[i].getEnabled(nextStateArray[i]);
HashSet<Transition> nextEnabledSet = new HashSet<Transition>();
for(Transition tran : nextEnabledList) {
nextEnabledSet.add(tran);
}
extendedNextEnabledArray[i] = nextEnabledSet;
//non_disabling
for(Transition curTran : curEnabledSet) {
if(curTran == firedTran)
continue;
if(nextEnabledSet.contains(curTran) == false) {
int[] nextMarking = nextStateArray[i].getMarking();
// Not sure if the code below is correct.
int[] preset = lpnList[i].getLpn().getPresetIndex(curTran.getName());
boolean included = true;
if (preset != null && preset.length > 0) {
for (int pp : preset) {
boolean temp = false;
for (int mi = 0; mi < nextMarking.length; mi++) {
if (nextMarking[mi] == pp) {
temp = true;
break;
}
}
if (temp == false)
{
included = false;
break;
}
}
}
if(preset==null || preset.length==0 || included==true) {
extendedNextEnabledArray[i].add(curTran);
}
}
}
}
boolean deadlock=true;
for(int i = 0; i < arraySize; i++) {
if(extendedNextEnabledArray[i].size() != 0){
deadlock = false;
break;
}
}
if(deadlock==true) {
failure = true;
break main_while_loop;
}
// Add nextPrjState into prjStateSet
// If nextPrjState has been traversed before, skip to the next
// enabled transition.
LpnState[] nextLpnStateArray = new LpnState[arraySize];
for(int i = 0; i < arraySize; i++) {
HashSet<Transition> lpnEnabledSet = new HashSet<Transition>();
for(Transition tran : extendedNextEnabledArray[i]) {
lpnEnabledSet.add(tran);
}
LpnState tmp = new LpnState(lpnList[i].getLpn(), nextStateArray[i], lpnEnabledSet);
LpnState tmpCached = (LpnState)(lpnStateCache[i].add(tmp));
nextLpnStateArray[i] = tmpCached;
}
boolean newState = globalStateTbl.add(new PrjLpnState(nextLpnStateArray));
if(newState == false) {
traceCex.removeLast();
continue;
}
stateStack.push(nextLpnStateArray);
LpnTranList[] nextEnabledSet = new LpnTranList[2];
LpnTranList fireFirstTrans = new LpnTranList();
LpnTranList otherTrans = new LpnTranList();
for(int i = 0; i < arraySize; i++)
{
for(Transition tran : nextLpnStateArray[i].getEnabled())
{
if(firingOrder == true)
if(curLpnStateArray[i].getEnabled().contains(tran))
otherTrans.add(tran);
else
fireFirstTrans.add(tran);
else
fireFirstTrans.add(tran);
}
}
nextEnabledSet[0] = fireFirstTrans;
nextEnabledSet[1] = otherTrans;
lpnTranStack.push(nextEnabledSet);
}// END while (stateStack.empty() == false)
// graph.write(String.format("graph_%s_%s-tran_%s-state.gv",mode,tranFiringCnt,
// prjStateSet.size()));
System.out.println("SUMMARY: # LPN transition firings: "
+ tranFiringCnt + ", # of prjStates found: "
+ globalStateTbl.size() + ", max_stack_depth: " + max_stack_depth);
/*
* by looking at stateStack, generate the trace showing the counter-example.
*/
if (failure == true) {
System.out.println("
System.out.println("the deadlock trace:");
//update traceCex from stateStack
// LpnState[] cur = null;
// LpnState[] next = null;
for(Transition tran : traceCex)
System.out.println(tran.getFullLabel());
}
System.out.println("Modules' local states: ");
for (int i = 0; i < arraySize; i++) {
System.out.println("module " + lpnList[i].getLpn().getLabel() + ": "
+ lpnList[i].reachSize());
}
return null;
}
/**
* findsg using iterative approach based on DFS search. The states found are
* stored in MDD.
*
* When a state is considered during DFS, only one enabled transition is
* selected to fire in an iteration.
*
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
* @return a linked list of a sequence of LPN transitions leading to the
* failure if it is not empty.
*/
public Stack<State[]> search_dfs_mdd_1(final StateGraph[] lpnList, final State[] initStateArray) {
System.out.println("---> calling function search_dfs_mdd_1");
long peakUsedMem = 0;
long peakTotalMem = 0;
long peakMddNodeCnt = 0;
int memUpBound = 500; // Set an upper bound of memory in MB usage to
// trigger MDD compression.
boolean compressed = false;
boolean failure = false;
int tranFiringCnt = 0;
int totalStates = 1;
int arraySize = lpnList.length;
int newStateCnt = 0;
Stack<State[]> stateStack = new Stack<State[]>();
Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>();
Stack<Integer> curIndexStack = new Stack<Integer>();
mddNode reachAll = null;
mddNode reach = mddMgr.newNode();
int[] localIdxArray = Analysis.getLocalStateIdxArray(lpnList, initStateArray, true);
mddMgr.add(reach, localIdxArray, compressed);
stateStack.push(initStateArray);
LpnTranList initEnabled = lpnList[0].getEnabled(initStateArray[0]);
lpnTranStack.push(initEnabled.clone());
curIndexStack.push(0);
int numMddCompression = 0;
main_while_loop: while (failure == false && stateStack.empty() == false) {
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
if (iterations % 100000 == 0) {
long curMddNodeCnt = mddMgr.nodeCnt();
peakMddNodeCnt = peakMddNodeCnt > curMddNodeCnt ? peakMddNodeCnt : curMddNodeCnt;
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStates
+ ", stack depth: " + stateStack.size()
+ ", total MDD nodes: " + curMddNodeCnt
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
if (curUsedMem >= memUpBound * 1000000) {
mddMgr.compress(reach);
numMddCompression++;
if (reachAll == null)
reachAll = reach;
else {
mddNode newReachAll = mddMgr.union(reachAll, reach);
if (newReachAll != reachAll) {
mddMgr.remove(reachAll);
reachAll = newReachAll;
}
}
mddMgr.remove(reach);
reach = mddMgr.newNode();
if(memUpBound < 1500)
memUpBound *= numMddCompression;
}
}
State[] curStateArray = stateStack.peek();
int curIndex = curIndexStack.peek();
LinkedList<Transition> curEnabled = lpnTranStack.peek();
// If all enabled transitions of the current LPN are considered,
// then consider the next LPN
// by increasing the curIndex.
// Otherwise, if all enabled transitions of all LPNs are considered,
// then pop the stacks.
if (curEnabled.size() == 0) {
lpnTranStack.pop();
curIndexStack.pop();
curIndex++;
while (curIndex < arraySize) {
LpnTranList enabledCached = (lpnList[curIndex].getEnabled(curStateArray[curIndex]));
if (enabledCached.size() > 0) {
curEnabled = enabledCached.clone();
lpnTranStack.push(curEnabled);
curIndexStack.push(curIndex);
break;
} else
curIndex++;
}
}
if (curIndex == arraySize) {
stateStack.pop();
continue;
}
Transition firedTran = curEnabled.removeLast();
State[] nextStateArray = lpnList[curIndex].fire(lpnList, curStateArray,firedTran);
tranFiringCnt++;
// Check if the firedTran causes disabling error or deadlock.
LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize];
LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize];
for (int i = 0; i < arraySize; i++) {
StateGraph lpn_tmp = lpnList[i];
LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]);
curEnabledArray[i] = enabledList;
enabledList = lpn_tmp.getEnabled(nextStateArray[i]);
nextEnabledArray[i] = enabledList;
Transition disabledTran = firedTran.disablingError(
curEnabledArray[i], nextEnabledArray[i]);
if (disabledTran != null) {
System.err.println("Disabling Error: "
+ disabledTran.getFullLabel() + " is disabled by "
+ firedTran.getFullLabel());
failure = true;
break main_while_loop;
}
}
if (Analysis.deadLock(lpnList, nextStateArray) == true) {
failure = true;
break main_while_loop;
}
/*
* Check if the local indices of nextStateArray already exist.
* if not, add it into reachable set, and push it onto stack.
*/
localIdxArray = Analysis.getLocalStateIdxArray(lpnList, nextStateArray, true);
Boolean existingState = false;
if (reachAll != null && mddMgr.contains(reachAll, localIdxArray) == true)
existingState = true;
else if (mddMgr.contains(reach, localIdxArray) == true)
existingState = true;
if (existingState == false) {
mddMgr.add(reach, localIdxArray, compressed);
newStateCnt++;
stateStack.push(nextStateArray);
lpnTranStack.push((LpnTranList) nextEnabledArray[0].clone());
curIndexStack.push(0);
totalStates++;
}
}
double totalStateCnt = mddMgr.numberOfStates(reach);
System.out.println("---> run statistics: \n"
+ "# LPN transition firings: " + tranFiringCnt + "\n"
+ "# of prjStates found: " + totalStateCnt + "\n"
+ "max_stack_depth: " + max_stack_depth + "\n"
+ "peak MDD nodes: " + peakMddNodeCnt + "\n"
+ "peak used memory: " + peakUsedMem / 1000000 + " MB\n"
+ "peak total memory: " + peakTotalMem / 1000000 + " MB\n");
return null;
}
/**
* findsg using iterative approach based on DFS search. The states found are
* stored in MDD.
*
* It is similar to findsg_dfs_mdd_1 except that when a state is considered
* during DFS, all enabled transition are fired, and all its successor
* states are found in an iteration.
*
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
* @return a linked list of a sequence of LPN transitions leading to the
* failure if it is not empty.
*/
public Stack<State[]> search_dfs_mdd_2(final StateGraph[] lpnList, final State[] initStateArray) {
System.out.println("---> calling function search_dfs_mdd_2");
int tranFiringCnt = 0;
int totalStates = 0;
int arraySize = lpnList.length;
long peakUsedMem = 0;
long peakTotalMem = 0;
long peakMddNodeCnt = 0;
int memUpBound = 1000; // Set an upper bound of memory in MB usage to
// trigger MDD compression.
boolean failure = false;
MDT state2Explore = new MDT(arraySize);
state2Explore.push(initStateArray);
totalStates++;
long peakState2Explore = 0;
Stack<Integer> searchDepth = new Stack<Integer>();
searchDepth.push(1);
boolean compressed = false;
mddNode reachAll = null;
mddNode reach = mddMgr.newNode();
main_while_loop:
while (failure == false && state2Explore.empty() == false) {
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
iterations++;
if (iterations % 100000 == 0) {
int mddNodeCnt = mddMgr.nodeCnt();
peakMddNodeCnt = peakMddNodeCnt > mddNodeCnt ? peakMddNodeCnt : mddNodeCnt;
int state2ExploreSize = state2Explore.size();
peakState2Explore = peakState2Explore > state2ExploreSize ? peakState2Explore : state2ExploreSize;
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStates
+ ", # states to explore: " + state2ExploreSize
+ ", # MDT nodes: " + state2Explore.nodeCnt()
+ ", total MDD nodes: " + mddNodeCnt
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
if (curUsedMem >= memUpBound * 1000000) {
mddMgr.compress(reach);
if (reachAll == null)
reachAll = reach;
else {
mddNode newReachAll = mddMgr.union(reachAll, reach);
if (newReachAll != reachAll) {
mddMgr.remove(reachAll);
reachAll = newReachAll;
}
}
mddMgr.remove(reach);
reach = mddMgr.newNode();
}
}
State[] curStateArray = state2Explore.pop();
State[] nextStateArray = null;
int states2ExploreCurLevel = searchDepth.pop();
if(states2ExploreCurLevel > 1)
searchDepth.push(states2ExploreCurLevel-1);
int[] localIdxArray = Analysis.getLocalStateIdxArray(lpnList, curStateArray, false);
mddMgr.add(reach, localIdxArray, compressed);
int nextStates2Explore = 0;
for (int index = arraySize - 1; index >= 0; index
StateGraph curLpn = lpnList[index];
State curState = curStateArray[index];
LinkedList<Transition> curEnabledSet = curLpn.getEnabled(curState);
LpnTranList curEnabled = (LpnTranList) curEnabledSet.clone();
while (curEnabled.size() > 0) {
Transition firedTran = curEnabled.removeLast();
// TODO: (check) Not sure if curLpn.fire is correct.
nextStateArray = curLpn.fire(lpnList, curStateArray, firedTran);
tranFiringCnt++;
for (int i = 0; i < arraySize; i++) {
StateGraph lpn_tmp = lpnList[i];
if (curStateArray[i] == nextStateArray[i])
continue;
LinkedList<Transition> curEnabled_l = lpn_tmp.getEnabled(curStateArray[i]);
LinkedList<Transition> nextEnabled = lpn_tmp.getEnabled(nextStateArray[i]);
Transition disabledTran = firedTran.disablingError(curEnabled_l, nextEnabled);
if (disabledTran != null) {
System.err.println("Verification failed: disabling error: "
+ disabledTran.getFullLabel()
+ " disabled by "
+ firedTran.getFullLabel() + "!!!");
failure = true;
break main_while_loop;
}
}
if (Analysis.deadLock(lpnList, nextStateArray) == true) {
System.err.println("Verification failed: deadlock.");
failure = true;
break main_while_loop;
}
/*
* Check if the local indices of nextStateArray already exist.
*/
localIdxArray = Analysis.getLocalStateIdxArray(lpnList, nextStateArray, false);
Boolean existingState = false;
if (reachAll != null && mddMgr.contains(reachAll, localIdxArray) == true)
existingState = true;
else if (mddMgr.contains(reach, localIdxArray) == true)
existingState = true;
else if(state2Explore.contains(nextStateArray)==true)
existingState = true;
if (existingState == false) {
totalStates++;
//mddMgr.add(reach, localIdxArray, compressed);
state2Explore.push(nextStateArray);
nextStates2Explore++;
}
}
}
if(nextStates2Explore > 0)
searchDepth.push(nextStates2Explore);
}
endoffunction: System.out.println("
+ "---> run statistics: \n"
+ " # Depth of search (Length of Cex): " + searchDepth.size() + "\n"
+ " # LPN transition firings: " + (double)tranFiringCnt/1000000 + " M\n"
+ " # of prjStates found: " + (double)totalStates / 1000000 + " M\n"
+ " peak states to explore : " + (double) peakState2Explore / 1000000 + " M\n"
+ " peak MDD nodes: " + peakMddNodeCnt + "\n"
+ " peak used memory: " + peakUsedMem / 1000000 + " MB\n"
+ " peak total memory: " + peakTotalMem /1000000 + " MB\n"
+ "_____________________________________");
return null;
}
public LinkedList<Transition> search_bfs(final StateGraph[] sgList, final State[] initStateArray) {
System.out.println("---> starting search_bfs");
long peakUsedMem = 0;
long peakTotalMem = 0;
long peakMddNodeCnt = 0;
int memUpBound = 1000; // Set an upper bound of memory in MB usage to
// trigger MDD compression.
int arraySize = sgList.length;
for (int i = 0; i < arraySize; i++)
sgList[i].addState(initStateArray[i]);
mddNode reachSet = null;
mddNode reach = mddMgr.newNode();
MDT frontier = new MDT(arraySize);
MDT image = new MDT(arraySize);
frontier.push(initStateArray);
State[] curStateArray = null;
int tranFiringCnt = 0;
int totalStates = 0;
int imageSize = 0;
boolean verifyError = false;
bfsWhileLoop: while (true) {
if (verifyError == true)
break;
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
long curMddNodeCnt = mddMgr.nodeCnt();
peakMddNodeCnt = peakMddNodeCnt > curMddNodeCnt ? peakMddNodeCnt : curMddNodeCnt;
iterations++;
System.out.println("iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStates
+ ", total MDD nodes: " + curMddNodeCnt
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
if (curUsedMem >= memUpBound * 1000000) {
mddMgr.compress(reach);
if (reachSet == null)
reachSet = reach;
else {
mddNode newReachSet = mddMgr.union(reachSet, reach);
if (newReachSet != reachSet) {
mddMgr.remove(reachSet);
reachSet = newReachSet;
}
}
mddMgr.remove(reach);
reach = mddMgr.newNode();
}
while(frontier.empty() == false) {
boolean deadlock = true;
// Stack<State[]> curStateArrayList = frontier.pop();
// while(curStateArrayList.empty() == false) {
// curStateArray = curStateArrayList.pop();
{
curStateArray = frontier.pop();
int[] localIdxArray = Analysis.getLocalStateIdxArray(sgList, curStateArray, false);
mddMgr.add(reach, localIdxArray, false);
totalStates++;
for (int i = 0; i < arraySize; i++) {
LinkedList<Transition> curEnabled = sgList[i].getEnabled(curStateArray[i]);
if (curEnabled.size() > 0)
deadlock = false;
for (Transition firedTran : curEnabled) {
// TODO: (check) Not sure if sgList[i].fire is correct.
State[] nextStateArray = sgList[i].fire(sgList, curStateArray, firedTran);
tranFiringCnt++;
/*
* Check if any transitions can be disabled by fireTran.
*/
LinkedList<Transition> nextEnabled = sgList[i].getEnabled(nextStateArray[i]);
Transition disabledTran = firedTran.disablingError(curEnabled, nextEnabled);
if (disabledTran != null) {
System.err.println("*** Verification failed: disabling error: "
+ disabledTran.getFullLabel()
+ " disabled by "
+ firedTran.getFullLabel() + "!!!");
verifyError = true;
break bfsWhileLoop;
}
localIdxArray = Analysis.getLocalStateIdxArray(sgList, nextStateArray, false);
if (mddMgr.contains(reachSet, localIdxArray) == false && mddMgr.contains(reach, localIdxArray) == false && frontier.contains(nextStateArray) == false) {
if(image.contains(nextStateArray)==false) {
image.push(nextStateArray);
imageSize++;
}
}
}
}
}
/*
* If curStateArray deadlocks (no enabled transitions), terminate.
*/
if (deadlock == true) {
System.err.println("*** Verification failed: deadlock.");
verifyError = true;
break bfsWhileLoop;
}
}
if(image.empty()==true) break;
System.out.println("---> size of image: " + imageSize);
frontier = image;
image = new MDT(arraySize);
imageSize = 0;
}
System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt / 1000000 + "M\n"
+ "---> # of prjStates found: " + (double) totalStates / 1000000 + "M\n"
+ "---> peak total memory: " + peakTotalMem / 1000000F + " MB\n"
+ "---> peak used memory: " + peakUsedMem / 1000000F + " MB\n"
+ "---> peak MDD nodes: " + peakMddNodeCnt);
return null;
}
/**
* BFS findsg using iterative approach. THe states found are stored in MDD.
*
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
* @return a linked list of a sequence of LPN transitions leading to the
* failure if it is not empty.
*/
public LinkedList<Transition> search_bfs_mdd_localFirings(final StateGraph[] lpnList, final State[] initStateArray) {
System.out.println("---> starting search_bfs");
long peakUsedMem = 0;
long peakTotalMem = 0;
int arraySize = lpnList.length;
for (int i = 0; i < arraySize; i++)
lpnList[i].addState(initStateArray[i]);
// mddNode reachSet = mddMgr.newNode();
// mddMgr.add(reachSet, curLocalStateArray);
mddNode reachSet = null;
mddNode exploredSet = null;
LinkedList<State>[] nextSetArray = (LinkedList<State>[]) (new LinkedList[arraySize]);
for (int i = 0; i < arraySize; i++)
nextSetArray[i] = new LinkedList<State>();
mddNode initMdd = mddMgr.doLocalFirings(lpnList, initStateArray, null);
mddNode curMdd = initMdd;
reachSet = curMdd;
mddNode nextMdd = null;
int[] curStateArray = null;
int tranFiringCnt = 0;
boolean verifyError = false;
bfsWhileLoop: while (true) {
if (verifyError == true)
break;
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
curStateArray = mddMgr.next(curMdd, curStateArray);
if (curStateArray == null) {
// Break the loop if no new next states are found.
// System.out.println("nextSet size " + nextSet.size());
if (nextMdd == null)
break bfsWhileLoop;
if (exploredSet == null)
exploredSet = curMdd;
else {
mddNode newExplored = mddMgr.union(exploredSet, curMdd);
if (newExplored != exploredSet)
mddMgr.remove(exploredSet);
exploredSet = newExplored;
}
mddMgr.remove(curMdd);
curMdd = nextMdd;
nextMdd = null;
iterations++;
System.out.println("iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of union calls: " + mddNode.numCalls
+ ", # of union cache nodes: " + mddNode.cacheNodes
+ ", total MDD nodes: " + mddMgr.nodeCnt()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
System.out.println("---> # of prjStates found: " + mddMgr.numberOfStates(reachSet)
+ ", CurSet.Size = " + mddMgr.numberOfStates(curMdd));
continue;
}
if (exploredSet != null && mddMgr.contains(exploredSet, curStateArray) == true)
continue;
// If curStateArray deadlocks (no enabled transitions), terminate.
if (Analysis.deadLock(lpnList, curStateArray) == true) {
System.err.println("*** Verification failed: deadlock.");
verifyError = true;
break bfsWhileLoop;
}
// Do firings of non-local LPN transitions.
for (int index = arraySize - 1; index >= 0; index
StateGraph curLpn = lpnList[index];
LinkedList<Transition> curLocalEnabled = curLpn.getEnabled(curStateArray[index]);
if (curLocalEnabled.size() == 0 || curLocalEnabled.getFirst().isLocal() == true)
continue;
for (Transition firedTran : curLocalEnabled) {
if (firedTran.isLocal() == true)
continue;
// TODO: (check) Not sure if curLpn.fire is correct.
State[] nextStateArray = curLpn.fire(lpnList, curStateArray, firedTran);
tranFiringCnt++;
@SuppressWarnings("unused")
ArrayList<LinkedList<Transition>> nextEnabledArray = new ArrayList<LinkedList<Transition>>(1);
for (int i = 0; i < arraySize; i++) {
if (curStateArray[i] == nextStateArray[i].getIndex())
continue;
StateGraph lpn_tmp = lpnList[i];
LinkedList<Transition> curEnabledList = lpn_tmp.getEnabled(curStateArray[i]);
LinkedList<Transition> nextEnabledList = lpn_tmp.getEnabled(nextStateArray[i].getIndex());
Transition disabledTran = firedTran.disablingError(curEnabledList, nextEnabledList);
if (disabledTran != null) {
System.err.println("Verification failed: disabling error: "
+ disabledTran.getFullLabel()
+ ": is disabled by "
+ firedTran.getFullLabel() + "!!!");
verifyError = true;
break bfsWhileLoop;
}
}
if (Analysis.deadLock(lpnList, nextStateArray) == true) {
verifyError = true;
break bfsWhileLoop;
}
// Add nextPrjState into prjStateSet
// If nextPrjState has been traversed before, skip to the
// next
// enabled transition.
int[] nextIdxArray = Analysis.getIdxArray(nextStateArray);
if (reachSet != null && mddMgr.contains(reachSet, nextIdxArray) == true)
continue;
mddNode newNextMdd = mddMgr.doLocalFirings(lpnList, nextStateArray, reachSet);
mddNode newReachSet = mddMgr.union(reachSet, newNextMdd);
if (newReachSet != reachSet)
mddMgr.remove(reachSet);
reachSet = newReachSet;
if (nextMdd == null)
nextMdd = newNextMdd;
else {
mddNode tmpNextMdd = mddMgr.union(nextMdd, newNextMdd);
if (tmpNextMdd != nextMdd)
mddMgr.remove(nextMdd);
nextMdd = tmpNextMdd;
mddMgr.remove(newNextMdd);
}
}
}
}
System.out.println("---> final numbers: # LPN transition firings: "
+ tranFiringCnt + "\n" + "---> # of prjStates found: "
+ (mddMgr.numberOfStates(reachSet)) + "\n"
+ "---> peak total memory: " + peakTotalMem / 1000000F
+ " MB\n" + "---> peak used memory: " + peakUsedMem / 1000000F
+ " MB\n" + "---> peak MMD nodes: " + mddMgr.peakNodeCnt());
return null;
}
/**
* partial order reduction
*
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
*/
public Stack<State[]> search_dfs_por(final StateGraph[] lpnList, final State[] initStateArray, LPNTranRelation lpnTranRelation, String approach) {
System.out.println("---> Calling search_dfs with partial order reduction");
long peakUsedMem = 0;
long peakTotalMem = 0;
double stateCount = 1;
int max_stack_depth = 0;
int iterations = 0;
boolean useMdd = true;
mddNode reach = mddMgr.newNode();
//init por
verification.platu.por1.AmpleSet ampleClass = new verification.platu.por1.AmpleSet();
//AmpleSubset ampleClass = new AmpleSubset();
HashMap<Transition,HashSet<Transition>> indepTranSet = new HashMap<Transition,HashSet<Transition>>();
if(approach == "state")
indepTranSet = ampleClass.getIndepTranSet_FromState(lpnList, lpnTranRelation);
else if (approach == "lpn")
indepTranSet = ampleClass.getIndepTranSet_FromLPN(lpnList);
System.out.println("finish get independent set!!!!");
boolean failure = false;
int tranFiringCnt = 0;
int arraySize = lpnList.length;;
HashSet<PrjState> stateStack = new HashSet<PrjState>();
Stack<LpnTranList> lpnTranStack = new Stack<LpnTranList>();
Stack<HashSet<Transition>> firedTranStack = new Stack<HashSet<Transition>>();
//get initial enable transition set
@SuppressWarnings("unchecked")
LinkedList<Transition>[] initEnabledArray = new LinkedList[arraySize];
for (int i = 0; i < arraySize; i++) {
lpnList[i].getLpn().setLpnIndex(i);
initEnabledArray[i] = lpnList[i].getEnabled(initStateArray[i]);
}
//set initEnableSubset
//LPNTranSet initEnableSubset = ampleClass.generateAmpleList(false, approach,initEnabledArray, indepTranSet);
LpnTranList initEnableSubset = ampleClass.generateAmpleTranSet(initEnabledArray, indepTranSet);
/*
* Initialize the reach state set with the initial state.
*/
HashSet<PrjState> prjStateSet = new HashSet<PrjState>();
PrjState initPrjState = new PrjState(initStateArray);
if (useMdd) {
int[] initIdxArray = Analysis.getIdxArray(initStateArray);
mddMgr.add(reach, initIdxArray, true);
}
else
prjStateSet.add(initPrjState);
stateStack.add(initPrjState);
PrjState stateStackTop = initPrjState;
lpnTranStack.push(initEnableSubset);
firedTranStack.push(new HashSet<Transition>());
/*
* Start the main search loop.
*/
main_while_loop:
while(failure == false && stateStack.size() != 0) {
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
if (iterations % 500000 == 0) {
if (useMdd==true)
stateCount = mddMgr.numberOfStates(reach);
else
stateCount = prjStateSet.size();
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + stateCount
+ ", max_stack_depth: " + max_stack_depth
+ ", total MDD nodes: " + mddMgr.nodeCnt()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
}
State[] curStateArray = stateStackTop.toStateArray();
LpnTranList curEnabled = lpnTranStack.peek();
// for (LPNTran tran : curEnabled)
// for (int i = 0; i < arraySize; i++)
// if (lpnList[i] == tran.getLpn())
// if (tran.isEnabled(curStateArray[i]) == false) {
// System.out.println("transition " + tran.getFullLabel() + " not enabled in the current state");
// System.exit(0);
// If all enabled transitions of the current LPN are considered, then consider the next LPN
// by increasing the curIndex.
// Otherwise, if all enabled transitions of all LPNs are considered, then pop the stacks.
if(curEnabled.size() == 0) {
lpnTranStack.pop();
firedTranStack.pop();
stateStack.remove(stateStackTop);
stateStackTop = stateStackTop.getFather();
if (stateStack.size() > 0)
traceCex.removeLast();
continue;
}
Transition firedTran = curEnabled.removeFirst();
firedTranStack.peek().add(firedTran);
traceCex.addLast(firedTran);
//System.out.println(tranFiringCnt + ": firedTran: "+ firedTran.getFullLabel());
// TODO: (??) Not sure if the state graph sg below is correct.
StateGraph sg = null;
for (int i=0; i<lpnList.length; i++) {
if (lpnList[i].getLpn().equals(firedTran.getLpn())) {
sg = lpnList[i];
}
}
State[] nextStateArray = sg.fire(lpnList, curStateArray, firedTran);
tranFiringCnt++;
// Check if the firedTran causes disabling error or deadlock.
@SuppressWarnings("unchecked")
LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize];
@SuppressWarnings("unchecked")
LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize];
for (int i = 0; i < arraySize; i++) {
lpnList[i].getLpn().setLpnIndex(i);
StateGraph lpn_tmp = lpnList[i];
LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]);
curEnabledArray[i] = enabledList;
enabledList = lpn_tmp.getEnabled(nextStateArray[i]);
nextEnabledArray[i] = enabledList;
Transition disabledTran = firedTran.disablingError(curEnabledArray[i], nextEnabledArray[i]);
if(disabledTran != null) {
System.out.println("---> Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel());
System.out.println("Current state:");
for(int ii = 0; ii < arraySize; ii++) {
System.out.println("module " + lpnList[ii].getLpn().getLabel());
System.out.println(curStateArray[ii]);
System.out.println("Enabled set: " + curEnabledArray[ii]);
}
System.out.println("======================\nNext state:");
for(int ii = 0; ii < arraySize; ii++) {
System.out.println("module " + lpnList[ii].getLpn().getLabel());
System.out.println(nextStateArray[ii]);
System.out.println("Enabled set: " + nextEnabledArray[ii]);
}
System.out.println();
failure = true;
break main_while_loop;
}
}
if (Analysis.deadLock(lpnList, nextStateArray) == true) {
System.out.println("---> Deadlock.");
// System.out.println("Deadlock state:");
// for(int ii = 0; ii < arraySize; ii++) {
// System.out.println("module " + lpnList[ii].getLabel());
// System.out.println(nextStateArray[ii]);
// System.out.println("Enabled set: " + nextEnabledArray[ii]);
failure = true;
break main_while_loop;
}
/*
// Add nextPrjState into prjStateSet
// If nextPrjState has been traversed before, skip to the next
// enabled transition.
//exist cycle
*/
PrjState nextPrjState = new PrjState(nextStateArray);
boolean isExisting = false;
int[] nextIdxArray = null;
if(useMdd==true)
nextIdxArray = Analysis.getIdxArray(nextStateArray);
if (useMdd == true)
isExisting = mddMgr.contains(reach, nextIdxArray);
else
isExisting = prjStateSet.contains(nextPrjState);
if (isExisting == false) {
if (useMdd == true) {
mddMgr.add(reach, nextIdxArray, true);
}
else
prjStateSet.add(nextPrjState);
//get next enable transition set
//LPNTranSet nextEnableSubset = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet);
LpnTranList nextEnableSubset = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet);
// LPNTranSet nextEnableSubset = new LPNTranSet();
// for (int i = 0; i < arraySize; i++)
// for (LPNTran tran : nextEnabledArray[i])
// nextEnableSubset.addLast(tran);
stateStack.add(nextPrjState);
stateStackTop.setChild(nextPrjState);
nextPrjState.setFather(stateStackTop);
stateStackTop = nextPrjState;
lpnTranStack.push(nextEnableSubset);
firedTranStack.push(new HashSet<Transition>());
// for (int i = 0; i < arraySize; i++)
// for (LPNTran tran : nextEnabledArray[i])
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for (LPNTran tran : nextEnableSubset)
// System.out.print(tran.getFullLabel() + ", ");
// HashSet<LPNTran> allEnabledSet = new HashSet<LPNTran>();
// for (int i = 0; i < arraySize; i++) {
// for (LPNTran tran : nextEnabledArray[i]) {
// allEnabledSet.add(tran);
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// if(nextEnableSubset.size() > 0) {
// for (LPNTran tran : nextEnableSubset) {
// if (allEnabledSet.contains(tran) == false) {
// System.out.println("\n\n" + tran.getFullLabel() + " in reduced set but not enabled\n");
// System.exit(0);
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n
continue;
}
/*
* Remove firedTran from traceCex if its successor state already exists.
*/
traceCex.removeLast();
/*
* When firedTran forms a cycle in the state graph, consider all enabled transitions except those
* 1. already fired in the current state,
* 2. in the ample set of the next state.
*/
if(stateStack.contains(nextPrjState)==true && curEnabled.size()==0) {
//System.out.println("formed a cycle......");
LpnTranList original = new LpnTranList();
LpnTranList reduced = new LpnTranList();
//LPNTranSet nextStateAmpleSet = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet);
LpnTranList nextStateAmpleSet = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet);
// System.out.println("Back state's ample set:");
// for(LPNTran tran : nextStateAmpleSet)
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
int enabledTranCnt = 0;
LpnTranList[] tmp = new LpnTranList[arraySize];
for (int i = 0; i < arraySize; i++) {
tmp[i] = new LpnTranList();
for (Transition tran : curEnabledArray[i]) {
original.addLast(tran);
if (firedTranStack.peek().contains(tran)==false && nextStateAmpleSet.contains(tran)==false) {
tmp[i].addLast(tran);
reduced.addLast(tran);
enabledTranCnt++;
}
}
}
LpnTranList ampleSet = new LpnTranList();
if(enabledTranCnt > 0)
//ampleSet = ampleClass.generateAmpleList(false, approach, tmp, indepTranSet);
ampleSet = ampleClass.generateAmpleTranSet(tmp, indepTranSet);
LpnTranList sortedAmpleSet = ampleSet;
/*
* Sort transitions in ampleSet for better performance for MDD.
* Not needed for hash table.
*/
if (useMdd == true) {
LpnTranList[] newCurEnabledArray = new LpnTranList[arraySize];
for (int i = 0; i < arraySize; i++)
newCurEnabledArray[i] = new LpnTranList();
for (Transition tran : ampleSet)
newCurEnabledArray[tran.getLpn().getLpnIndex()].addLast(tran);
sortedAmpleSet = new LpnTranList();
for (int i = 0; i < arraySize; i++) {
LpnTranList localEnabledSet = newCurEnabledArray[i];
for (Transition tran : localEnabledSet)
sortedAmpleSet.addLast(tran);
}
}
// for(LPNTran tran : original)
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for(LPNTran tran : ampleSet)
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for(LPNTran tran : firedTranStack.peek())
// allCurEnabled.remove(tran);
lpnTranStack.pop();
lpnTranStack.push(sortedAmpleSet);
// for (int i = 0; i < arraySize; i++) {
// for (LPNTran tran : curEnabledArray[i]) {
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for(LPNTran tran : allCurEnabled)
// System.out.print(tran.getFullLabel() + ", ");
}
//System.out.println("Backtrack........\n");
}//END while (stateStack.empty() == false)
if (useMdd==true)
stateCount = mddMgr.numberOfStates(reach);
else
stateCount = prjStateSet.size();
//long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
System.out.println("SUMMARY: # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + stateCount
+ ", max_stack_depth: " + max_stack_depth
+ ", used memory: " + (float) curUsedMem / 1000000
+ ", free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
return null;
}
// /**
// * Check if this project deadlocks in the current state 'stateArray'.
// * @param sgList
// * @param stateArray
// * @param staticSetsMap
// * @param enableSet
// * @param disableByStealingToken
// * @param disableSet
// * @param init
// * @return
// */
// // Called by search search_dfsPOR
// public boolean deadLock(StateGraph[] sgList, State[] stateArray, HashMap<LpnTransitionPair,StaticSets> staticSetsMap,
// boolean init, HashMap<LpnTransitionPair, Integer> tranFiringFreq, HashSet<PrjState> stateStack, PrjState stateStackTop, int cycleClosingMethdIndex) {
// boolean deadlock = true;
// System.out.println("@ deadlock:");
//// for (int i = 0; i < stateArray.length; i++) {
//// LinkedList<Transition> tmp = getAmple(stateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop, cycleClosingMethdIndex).getAmpleSet();
//// if (tmp.size() > 0) {
//// deadlock = false;
//// break;
// LinkedList<Transition> tmp = getAmple(stateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop, cycleClosingMethdIndex).getAmpleSet();
// if (tmp.size() > 0) {
// deadlock = false;
// System.out.println("@ end of deadlock");
// return deadlock;
public static boolean deadLock(StateGraph[] lpnArray, State[] stateArray) {
boolean deadlock = true;
for (int i = 0; i < stateArray.length; i++) {
LinkedList<Transition> tmp = lpnArray[i].getEnabled(stateArray[i]);
if (tmp.size() > 0) {
deadlock = false;
break;
}
}
return deadlock;
}
public static boolean deadLock(StateGraph[] lpnArray, int[] stateIdxArray) {
boolean deadlock = true;
for (int i = 0; i < stateIdxArray.length; i++) {
LinkedList<Transition> tmp = lpnArray[i].getEnabled(stateIdxArray[i]);
if (tmp.size() > 0) {
deadlock = false;
break;
}
}
return deadlock;
}
// /*
// * Scan enabledArray, identify all sticky transitions other the firedTran, and return them.
// *
// * Arguments remain constant.
// */
// public static LpnTranList[] getStickyTrans(LpnTranList[] enabledArray, Transition firedTran) {
// int arraySize = enabledArray.length;
// LpnTranList[] stickyTranArray = new LpnTranList[arraySize];
// for (int i = 0; i < arraySize; i++) {
// stickyTranArray[i] = new LpnTranList();
// for (Transition tran : enabledArray[i]) {
// if (tran != firedTran)
// stickyTranArray[i].add(tran);
// if(stickyTranArray[i].size()==0)
// stickyTranArray[i] = null;
// return stickyTranArray;
/**
* Identify if any sticky transitions in currentStickyTransArray can existing in the nextState. If so, add them to
* nextStickyTransArray.
*
* Arguments: curStickyTransArray and nextState are constant, nextStickyTransArray may be added with sticky transitions
* from curStickyTransArray.
*
* Return: sticky transitions from curStickyTransArray that are not marking disabled in nextState.
*/
public static LpnTranList[] checkStickyTrans(
LpnTranList[] curStickyTransArray, LpnTranList[] nextEnabledArray,
LpnTranList[] nextStickyTransArray, State nextState, LhpnFile LPN) {
int arraySize = curStickyTransArray.length;
LpnTranList[] stickyTransArray = new LpnTranList[arraySize];
boolean[] hasStickyTrans = new boolean[arraySize];
for (int i = 0; i < arraySize; i++) {
HashSet<Transition> tmp = new HashSet<Transition>();
if(nextStickyTransArray[i] != null)
for(Transition tran : nextStickyTransArray[i])
tmp.add(tran);
stickyTransArray[i] = new LpnTranList();
hasStickyTrans[i] = false;
for (Transition tran : curStickyTransArray[i]) {
if (tran.isPersistent() == true && tmp.contains(tran)==false) {
int[] nextMarking = nextState.getMarking();
int[] preset = LPN.getPresetIndex(tran.getName());//tran.getPreSet();
boolean included = false;
if (preset != null && preset.length > 0) {
for (int pp : preset) {
for (int mi = 0; i < nextMarking.length; i++) {
if (nextMarking[mi] == pp) {
included = true;
break;
}
}
if (included == false)
break;
}
}
if(preset==null || preset.length==0 || included==true) {
stickyTransArray[i].add(tran);
hasStickyTrans[i] = true;
}
}
}
if(stickyTransArray[i].size()==0)
stickyTransArray[i] = null;
}
return stickyTransArray;
}
/*
* Return an array of indices for the given stateArray.
*/
private static int[] getIdxArray(State[] stateArray) {
int[] idxArray = new int[stateArray.length];
for(int i = 0; i < stateArray.length; i++) {
idxArray[i] = stateArray[i].getIndex();
}
return idxArray;
}
private static int[] getLocalStateIdxArray(StateGraph[] sgList, State[] stateArray, boolean reverse) {
int arraySize = sgList.length;
int[] localIdxArray = new int[arraySize];
for(int i = 0; i < arraySize; i++) {
if(reverse == false)
localIdxArray[i] = sgList[i].getLocalState(stateArray[i]).getIndex();
else
localIdxArray[arraySize - i - 1] = sgList[i].getLocalState(stateArray[i]).getIndex();
//System.out.print(localIdxArray[i] + " ");
}
//System.out.println();
return localIdxArray;
}
private void printEnabledSetTbl(StateGraph[] sgList) {
for (int i=0; i<sgList.length; i++) {
System.out.println("******* enabledSetTbl for " + sgList[i].getLpn().getLabel() + " **********");
for (State s : sgList[i].getEnabledSetTbl().keySet()) {
System.out.print("S" + s.getIndex() + " -> ");
printTransitionSet(sgList[i].getEnabledSetTbl().get(s), "");
}
}
}
private HashSet<LpnTransitionPair> partialOrderReductionUsingDependencyGraphs(State[] curStateArray,
HashSet<LpnTransitionPair> curEnabled, HashMap<LpnTransitionPair, StaticSets> staticMap,
StateGraph[] sgList) {
if (curEnabled.size() == 1)
return curEnabled;
HashSet<LpnTransitionPair> ready = new HashSet<LpnTransitionPair>();
LhpnFile[] lpnList = new LhpnFile[sgList.length];
for (int i=0; i<sgList.length; i++) {
lpnList[i] = sgList[i].getLpn();
}
// enabledTran is independent of other transitions
for (LpnTransitionPair enabledTran : curEnabled) {
if (staticMap.get(enabledTran).getDisableSet().isEmpty()) {
ready.add(enabledTran);
return ready;
}
}
for (LpnTransitionPair enabledTran : curEnabled) {
if (Options.getDebugMode()) {
System.out.println("@ partialOrderReduction, consider transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel()
+ "("+ sgList[enabledTran.getLpnIndex()].getLpn().getTransition(enabledTran.getTranIndex()) + "). Compute its dependent set.");
writeStringWithNewLineToPORDebugFile("@ partialOrderReduction, consider transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel()
+ "("+ sgList[enabledTran.getLpnIndex()].getLpn().getTransition(enabledTran.getTranIndex()) + "). Compute its dependent set.");
}
HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>();
boolean isCycleClosingAmpleComputation = false;
dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap, lpnList, isCycleClosingAmpleComputation);
// printIntegerSet(dependent, sgList, "dependent set for enabled transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel()
// + "(" + enabledTransition.getName() + ")");
if (ready.isEmpty())
ready = (HashSet<LpnTransitionPair>) dependent.clone();
else if (dependent.size() < ready.size() && !ready.isEmpty())
ready = (HashSet<LpnTransitionPair>) dependent.clone();
if (ready.size() == 1) {
cachedNecessarySets.clear();
return ready;
}
}
cachedNecessarySets.clear();
return ready;
}
private HashSet<LpnTransitionPair> partialOrderReduction(State[] curStateArray,
HashSet<LpnTransitionPair> curEnabled, HashMap<LpnTransitionPair, StaticSets> staticMap,
HashMap<LpnTransitionPair,Integer> tranFiringFreqMap, StateGraph[] sgList) {
if (curEnabled.size() == 1)
return curEnabled;
HashSet<LpnTransitionPair> ready = null;
LhpnFile[] lpnList = new LhpnFile[sgList.length];
for (int i=0; i<sgList.length; i++) {
lpnList[i] = sgList[i].getLpn();
}
DependentSetComparator depComp = new DependentSetComparator(tranFiringFreqMap);
PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(curEnabled.size(), depComp);
for (LpnTransitionPair enabledTran : curEnabled) {
if (Options.getDebugMode()){
System.out.println("@ partialOrderReduction, consider transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel()
+ "("+ sgList[enabledTran.getLpnIndex()].getLpn().getTransition(enabledTran.getTranIndex()) + ")");
writeStringWithNewLineToPORDebugFile("@ partialOrderReduction, consider transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel()
+ "("+ sgList[enabledTran.getLpnIndex()].getLpn().getTransition(enabledTran.getTranIndex()) + ")");
}
HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>();
Transition enabledTransition = sgList[enabledTran.getLpnIndex()].getLpn().getAllTransitions()[enabledTran.getTranIndex()];
boolean enabledIsDummy = false;
boolean isCycleClosingAmpleComputation = false;
dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap, lpnList, isCycleClosingAmpleComputation);
// printIntegerSet(dependent, sgList, "dependent set for enabled transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel()
// + "(" + enabledTransition.getName() + ")");
// TODO: temporarily dealing with dummy transitions (This requires the dummy transitions to have "_dummy" in their names.)
if(isDummyTran(enabledTransition.getName()))
enabledIsDummy = true;
DependentSet dependentSet = new DependentSet(dependent, enabledTran, enabledIsDummy);
dependentSetQueue.add(dependentSet);
// if (ready.isEmpty())
// ready = (HashSet<LpnTransitionPair>) dependent.clone();
// else if (dependent.size() < ready.size() && !ready.isEmpty())
// ready = (HashSet<LpnTransitionPair>) dependent.clone();
// if (ready.size() == 1) {
// cachedNecessarySets.clear();
// return ready;
}
cachedNecessarySets.clear();
ready = dependentSetQueue.poll().getDependent();
return ready;
}
private boolean isDummyTran(String tranName) {
if (tranName.contains("_dummy"))
return true;
else
return false;
}
private HashSet<LpnTransitionPair> computeDependent(State[] curStateArray,
LpnTransitionPair seedTran, HashSet<LpnTransitionPair> dependent, HashSet<LpnTransitionPair> curEnabled,
HashMap<LpnTransitionPair, StaticSets> staticMap, LhpnFile[] lpnList, boolean isCycleClosingAmpleComputation) {
// disableSet is the set of transitions that can be disabled by firing enabledLpnTran, or can disable enabledLpnTran.
HashSet<LpnTransitionPair> disableSet = staticMap.get(seedTran).getDisableSet();
HashSet<LpnTransitionPair> otherTransDisableEnabledTran = staticMap.get(seedTran).getOtherTransDisableCurTranSet();
if (Options.getDebugMode()) {
System.out.println("@ getDependentSet, consider transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()).getName());
//printIntegerSet(canModifyAssign, lpnList, lpnList[enabledLpnTran.getLpnIndex()].getTransition(enabledLpnTran.getTranIndex()) + " can modify assignments");
printIntegerSet(disableSet, lpnList, "Disable set for " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()));
writeStringWithNewLineToPORDebugFile("@ getDependentSet, consider transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()).getName());
writeIntegerSetToPORDebugFile(disableSet, lpnList, "Disable set for " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()));
}
dependent.add(seedTran);
// for (LpnTransitionPair lpnTranPair : canModifyAssign) {
// if (curEnabled.contains(lpnTranPair))
// dependent.add(lpnTranPair);
if (Options.getDebugMode()) {
printIntegerSet(dependent, lpnList, "@ getDependentSet at 0, dependent set for " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()));
writeIntegerSetToPORDebugFile(dependent, lpnList, "@ getDependentSet at 0, dependent set for " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()));
}
// // dependent is equal to enabled. Terminate.
// if (dependent.size() == curEnabled.size()) {
// if (Options.getDebugMode())
// System.out.println("Check 0: dependent == curEnabled. Return dependent.");
// return dependent;
for (LpnTransitionPair tranInDisableSet : disableSet) {
if (Options.getDebugMode()) {
System.out.println("Consider transition in the disable set of "
+ lpnList[seedTran.getLpnIndex()].getLabel()
+ "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + "): "
+ lpnList[tranInDisableSet.getLpnIndex()].getLabel()
+"(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()) + ")");
writeStringWithNewLineToPORDebugFile("Consider transition in the disable set of "
+ lpnList[seedTran.getLpnIndex()].getLabel()
+ "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + "): "
+ lpnList[tranInDisableSet.getLpnIndex()].getLabel()
+"(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()) + ")");
}
boolean tranInDisableSetIsPersistent = lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()).isPersistent();
if (curEnabled.contains(tranInDisableSet) && !dependent.contains(tranInDisableSet)
&& (!tranInDisableSetIsPersistent || otherTransDisableEnabledTran.contains(tranInDisableSet))) {
dependent.addAll(computeDependent(curStateArray,tranInDisableSet,dependent,curEnabled,staticMap, lpnList, isCycleClosingAmpleComputation));
if (Options.getDebugMode()) {
printIntegerSet(dependent, lpnList, "@ getDependentSet at 1 for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()));
writeIntegerSetToPORDebugFile(dependent, lpnList, "@ getDependentSet at 1 for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()));
}
}
else if (!curEnabled.contains(tranInDisableSet)) {
if(Options.getPOR().toLowerCase().equals("tboff") // no trace-back
|| (Options.getCycleClosingAmpleMethd().toLowerCase().equals("cctboff") && isCycleClosingAmpleComputation)) {
dependent.addAll(curEnabled);
break;
}
LpnTransitionPair origTran = new LpnTransitionPair(tranInDisableSet.getLpnIndex(), tranInDisableSet.getTranIndex());
HashSet<LpnTransitionPair> necessary = null;
if (Options.getDebugMode()) {
printCachedNecessarySets(lpnList);
writeCachedNecessarySetsToPORDebugFile(lpnList);
}
if (cachedNecessarySets.containsKey(tranInDisableSet)) {
if (Options.getDebugMode()) {
System.out.println("Found transition " + lpnList[tranInDisableSet.getLpnIndex()].getLabel() + "("
+ lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()).getName() + ") in the cached necessary sets.");
writeStringWithNewLineToPORDebugFile("Found transition " + lpnList[tranInDisableSet.getLpnIndex()].getLabel() + "("
+ lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()).getName() + ") in the cached necessary sets.");
}
necessary = cachedNecessarySets.get(tranInDisableSet);
}
else {
if (Options.getNecessaryUsingDependencyGraphs()) {
if (Options.getDebugMode()) {
System.out.println("==== Compute necessary using BFS ====");
writeStringWithNewLineToPORDebugFile("==== Compute necessary using BFS ====");
}
necessary = computeNecessaryUsingDependencyGraphs(curStateArray,tranInDisableSet,curEnabled, staticMap, lpnList);
}
else {
if (Options.getDebugMode()) {
System.out.println("==== Compute necessary using DFS ====");
writeStringWithNewLineToPORDebugFile("==== Compute necessary using DFS ====");
}
necessary = computeNecessary(curStateArray,tranInDisableSet,dependent,curEnabled, staticMap, lpnList, origTran);
}
}
if (necessary != null && !necessary.isEmpty()) {
cachedNecessarySets.put(tranInDisableSet, necessary);
if (Options.getDebugMode()) {
printIntegerSet(necessary, lpnList, "necessary set for transition " + lpnList[tranInDisableSet.getLpnIndex()].getLabel()
+ "(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()) + ")");
writeIntegerSetToPORDebugFile(necessary, lpnList, "necessary set for transition " + lpnList[tranInDisableSet.getLpnIndex()].getLabel()
+ "(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()) + ")");
}
for (LpnTransitionPair tranNecessary : necessary) {
if (!dependent.contains(tranNecessary)) {
if (Options.getDebugMode()) {
printIntegerSet(dependent, lpnList, "Dependent set for " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + "):");
System.out.println("It does not contain this transition found by computeNecessary: " +
lpnList[tranNecessary.getLpnIndex()].getLabel() + "(" + lpnList[tranNecessary.getLpnIndex()].getTransition(tranNecessary.getTranIndex()) + ")"
+ ". Compute its dependent set.");
writeIntegerSetToPORDebugFile(dependent, lpnList, "Dependent set for " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + "):");
writeStringWithNewLineToPORDebugFile("It does not contain this transition found by computeNecessary: " +
lpnList[tranNecessary.getLpnIndex()].getLabel() + "(" + lpnList[tranNecessary.getLpnIndex()].getTransition(tranNecessary.getTranIndex()) + ")"
+ ". Compute its dependent set.");
}
dependent.addAll(computeDependent(curStateArray,tranNecessary,dependent,curEnabled,staticMap, lpnList, isCycleClosingAmpleComputation));
}
}
}
else {
if (Options.getDebugMode()) {
System.out.println("necessary set for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + " is empty.");
writeStringWithNewLineToPORDebugFile("necessary set for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + " is empty.");
}
dependent.addAll(curEnabled);
}
if (Options.getDebugMode()) {
printIntegerSet(dependent, lpnList, "@ getDependentSet at 2, dependent set for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()));
writeIntegerSetToPORDebugFile(dependent, lpnList, "@ getDependentSet at 2, dependent set for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()));
}
}
}
return dependent;
}
@SuppressWarnings("unchecked")
private HashSet<LpnTransitionPair> computeNecessary(State[] curStateArray,
LpnTransitionPair tran, HashSet<LpnTransitionPair> dependent,
HashSet<LpnTransitionPair> curEnabledIndices, HashMap<LpnTransitionPair, StaticSets> staticMap,
LhpnFile[] lpnList, LpnTransitionPair origTran) {
if (Options.getDebugMode()) {
System.out.println("@ getNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")");
writeStringWithNewLineToPORDebugFile("@ getNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")");
}
if (cachedNecessarySets.containsKey(tran)) {
if (Options.getDebugMode()) {
System.out.println("Found transition" + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")"
+ "'s necessary set in the cached necessary sets. ");
writeStringWithNewLineToPORDebugFile("Found transition" + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")"
+ "'s necessary set in the cached necessary sets. ");
}
return cachedNecessarySets.get(tran);
}
// Search for transition(s) that can help to bring the marking(s).
HashSet<LpnTransitionPair> nMarking = null;
Transition transition = lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex());
int[] presetPlaces = lpnList[tran.getLpnIndex()].getPresetIndex(transition.getName());
for (int i=0; i < presetPlaces.length; i++) {
int place = presetPlaces[i];
if (curStateArray[tran.getLpnIndex()].getMarking()[place]==0) {
if (Options.getDebugMode()) {
System.out.println("
+ "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ") " + "
writeStringWithNewLineToPORDebugFile("
+ "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ") " + "
}
HashSet<LpnTransitionPair> nMarkingTemp = new HashSet<LpnTransitionPair>();
String placeName = lpnList[tran.getLpnIndex()].getAllPlaces().get(place);
if (Options.getDebugMode()) {
System.out.println("preset place of " + transition.getName() + " is " + placeName);
writeStringWithNewLineToPORDebugFile("preset place of " + transition.getName() + " is " + placeName);
}
int[] presetTrans = lpnList[tran.getLpnIndex()].getPresetIndex(placeName);
for (int j=0; j < presetTrans.length; j++) {
LpnTransitionPair presetTran = new LpnTransitionPair(tran.getLpnIndex(), presetTrans[j]);
if (Options.getDebugMode()) {
System.out.println("preset transition of " + placeName + " is " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()) + ")");
writeStringWithNewLineToPORDebugFile("preset transition of " + placeName + " is " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()) + ")");
}
if (origTran.getVisitedTrans().contains(presetTran)) {
if (Options.getDebugMode()) {
System.out.println("Transition " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()) + ") is visted before by "
+ lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ").");
writeStringWithNewLineToPORDebugFile("Transition " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()) + ") is visted before by "
+ lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ").");
}
if (cachedNecessarySets.containsKey(presetTran)) {
if (Options.getDebugMode()) {
System.out.println("Found transition" + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + ")"
+ "'s necessary set in the cached necessary sets. Add it to nMarkingTemp.");
writeStringWithNewLineToPORDebugFile("Found transition" + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + ")"
+ "'s necessary set in the cached necessary sets. Add it to nMarkingTemp.");
}
nMarkingTemp = cachedNecessarySets.get(presetTran);
}
if (curEnabledIndices.contains(presetTran)) {
if (Options.getDebugMode()) {
System.out.println("@ nMarking: curEnabled contains transition " + lpnList[presetTran.getLpnIndex()].getLabel()
+ "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + "). Add to nMarkingTmp.");
writeStringWithNewLineToPORDebugFile("@ nMarking: curEnabled contains transition " + lpnList[presetTran.getLpnIndex()].getLabel()
+ "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + "). Add to nMarkingTmp.");
}
nMarkingTemp.add(new LpnTransitionPair(tran.getLpnIndex(), presetTrans[j]));;
}
continue;
}
else
origTran.addVisitedTran(presetTran);
if (Options.getDebugMode()) {
System.out.println("~~~~~~~~~ transVisited for transition " + lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ")~~~~~~~~~");
writeStringWithNewLineToPORDebugFile("~~~~~~~~~ transVisited for transition " + lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ")~~~~~~~~~");
for (LpnTransitionPair visitedTran : origTran.getVisitedTrans()) {
System.out.println(lpnList[visitedTran.getLpnIndex()].getLabel() + "(" + lpnList[visitedTran.getLpnIndex()].getTransition(visitedTran.getTranIndex()).getName() + ") ");
writeStringWithNewLineToPORDebugFile(lpnList[visitedTran.getLpnIndex()].getLabel() + "(" + lpnList[visitedTran.getLpnIndex()].getTransition(visitedTran.getTranIndex()).getName() + ") ");
}
System.out.println("@ getNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + ").");
writeStringWithNewLineToPORDebugFile("@ getNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + ").");
}
if (curEnabledIndices.contains(presetTran)) {
if (Options.getDebugMode()) {
System.out.println("@ nMarking: curEnabled contains transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + "). Add to nMarkingTmp.");
writeStringWithNewLineToPORDebugFile("@ nMarking: curEnabled contains transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + "). Add to nMarkingTmp.");
}
nMarkingTemp.add(new LpnTransitionPair(tran.getLpnIndex(), presetTrans[j]));
}
else {
if (Options.getDebugMode()) {
System.out.println("@ nMarking: transition " + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + " is not enabled. Compute its necessary set.");
writeStringWithNewLineToPORDebugFile("@ nMarking: transition " + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + " is not enabled. Compute its necessary set.");
}
HashSet<LpnTransitionPair> tmp = null;
tmp = computeNecessary(curStateArray, presetTran, dependent,
curEnabledIndices, staticMap, lpnList, origTran);
if (tmp != null)
nMarkingTemp.addAll(tmp);
else
if (Options.getDebugMode()) {
System.out.println("@ nMarking: necessary set for transition " + lpnList[tran.getLpnIndex()].getLabel()
+ "(" + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + ") is null.");
writeStringWithNewLineToPORDebugFile("@ nMarking: necessary set for transition " + lpnList[tran.getLpnIndex()].getLabel()
+ "(" + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + ") is null.");
}
}
}
if (nMarkingTemp != null)
if (nMarking == null || nMarkingTemp.size() < nMarking.size())
nMarking = (HashSet<LpnTransitionPair>) nMarkingTemp.clone();
}
else
if (Options.getDebugMode()) {
System.out.println("Place " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getAllPlaces().get(place) + ") is marked.");
writeStringWithNewLineToPORDebugFile("Place " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getAllPlaces().get(place) + ") is marked.");
}
}
// Search for transition(s) that can help to enable the current transition.
HashSet<LpnTransitionPair> nEnable = null;
int[] varValueVector = curStateArray[tran.getLpnIndex()].getVector();//curState.getVector();
HashSet<LpnTransitionPair> canEnable = staticMap.get(tran).getEnableBySettingEnablingTrue();
if (Options.getDebugMode()) {
System.out.println("
printIntegerSet(canEnable, lpnList, lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()) + ") can be enabled by");
writeStringWithNewLineToPORDebugFile("
writeIntegerSetToPORDebugFile(canEnable, lpnList, lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()) + ") can be enabled by");
}
if (transition.getEnablingTree() != null
&& transition.getEnablingTree().evaluateExpr(lpnList[tran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) == 0.0
&& !canEnable.isEmpty()) {
nEnable = new HashSet<LpnTransitionPair>();
for (LpnTransitionPair tranCanEnable : canEnable) {
if (curEnabledIndices.contains(tranCanEnable)) {
nEnable.add(tranCanEnable);
if (Options.getDebugMode()) {
System.out.println("@ nEnable: curEnabled contains transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + "). Add to nEnable.");
writeStringWithNewLineToPORDebugFile("@ nEnable: curEnabled contains transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + "). Add to nEnable.");
}
}
else {
if (origTran.getVisitedTrans().contains(tranCanEnable)) {
if (Options.getDebugMode()) {
System.out.println("Transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()) + ") is visted before by "
+ lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ").");
writeStringWithNewLineToPORDebugFile("Transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()) + ") is visted before by "
+ lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ").");
}
if (cachedNecessarySets.containsKey(tranCanEnable)) {
if (Options.getDebugMode()) {
System.out.println("Found transition" + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + ")"
+ "'s necessary set in the cached necessary sets. Add it to nMarkingTemp.");
writeStringWithNewLineToPORDebugFile("Found transition" + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + ")"
+ "'s necessary set in the cached necessary sets. Add it to nMarkingTemp.");
}
nEnable.addAll(cachedNecessarySets.get(tranCanEnable));
}
continue;
}
else
origTran.addVisitedTran(tranCanEnable);
if (Options.getDebugMode()) {
System.out.println("@ nEnable: transition " + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + " is not enabled. Compute its necessary set.");
writeStringWithNewLineToPORDebugFile("@ nEnable: transition " + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + " is not enabled. Compute its necessary set.");
}
HashSet<LpnTransitionPair> tmp = null;
tmp = computeNecessary(curStateArray, tranCanEnable, dependent,
curEnabledIndices, staticMap, lpnList, origTran);
if (tmp != null)
nEnable.addAll(tmp);
else
if (Options.getDebugMode()) {
System.out.println("@ nEnable: necessary set for transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + ") is null.");
writeStringWithNewLineToPORDebugFile("@ nEnable: necessary set for transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + ") is null.");
}
}
}
}
if (Options.getDebugMode()) {
if (transition.getEnablingTree() == null) {
System.out.println("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ") has no enabling condition.");
writeStringWithNewLineToPORDebugFile("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ") has no enabling condition.");
}
else if (transition.getEnablingTree().evaluateExpr(lpnList[tran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) !=0.0) {
System.out.println("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")'s enabling condition is true.");
writeStringWithNewLineToPORDebugFile("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")'s enabling condition is true.");
}
else if (transition.getEnablingTree() != null
&& transition.getEnablingTree().evaluateExpr(lpnList[tran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) == 0.0
&& canEnable.isEmpty()) {
System.out.println("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName()
+ ")'s enabling condition is false, but no other transitions that can help to enable it were found .");
writeStringWithNewLineToPORDebugFile("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName()
+ ")'s enabling condition is false, but no other transitions that can help to enable it were found .");
}
printIntegerSet(nMarking, lpnList, "nMarking for transition " + transition.getName());
printIntegerSet(nEnable, lpnList, "nEnable for transition " + transition.getName());
writeIntegerSetToPORDebugFile(nMarking, lpnList, "nMarking for transition " + transition.getName());
writeIntegerSetToPORDebugFile(nEnable, lpnList, "nEnable for transition " + transition.getName());
}
if (nEnable == null && nMarking != null) {
if (!nMarking.isEmpty())
cachedNecessarySets.put(tran, nMarking);
if (Options.getDebugMode()) {
printCachedNecessarySets(lpnList);
writeCachedNecessarySetsToPORDebugFile(lpnList);
}
return nMarking;
}
else if (nMarking == null && nEnable != null) {
if (!nEnable.isEmpty())
cachedNecessarySets.put(tran, nEnable);
if (Options.getDebugMode()) {
printCachedNecessarySets(lpnList);
writeCachedNecessarySetsToPORDebugFile(lpnList);
}
return nEnable;
}
// else if (nMarking == null && nEnable == null) {
// return null;
else {
if (!nMarking.isEmpty() && !nEnable.isEmpty()) {
if (getIntSetSubstraction(nMarking, dependent).size() < getIntSetSubstraction(nEnable, dependent).size()) {
cachedNecessarySets.put(tran, nMarking);
if (Options.getDebugMode()) {
printCachedNecessarySets(lpnList);
writeCachedNecessarySetsToPORDebugFile(lpnList);
}
return nMarking;
}
else {
cachedNecessarySets.put(tran, nEnable);
if (Options.getDebugMode()) {
printCachedNecessarySets(lpnList);
writeCachedNecessarySetsToPORDebugFile(lpnList);
}
return nEnable;
}
}
else if (nMarking.isEmpty() && !nEnable.isEmpty()) {
cachedNecessarySets.put(tran, nEnable);
if (Options.getDebugMode()) {
printCachedNecessarySets(lpnList);
writeCachedNecessarySetsToPORDebugFile(lpnList);
}
return nEnable;
}
else {
cachedNecessarySets.put(tran, nMarking);
if (Options.getDebugMode()) {
printCachedNecessarySets(lpnList);
writeCachedNecessarySetsToPORDebugFile(lpnList);
}
return nMarking;
}
}
}
private HashSet<LpnTransitionPair> computeNecessaryUsingDependencyGraphs(State[] curStateArray,
LpnTransitionPair seedTran, HashSet<LpnTransitionPair> curEnabled,
HashMap<LpnTransitionPair, StaticSets> staticMap,
LhpnFile[] lpnList) {
if (Options.getDebugMode()) {
System.out.println("@ getNecessary, consider transition: " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()).getName() + ")");
writeStringWithNewLineToPORDebugFile("@ getNecessary, consider transition: " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()).getName() + ")");
}
// Use breadth-first search to find the shorted path from the seed transition to an enabled transition.
LinkedList<LpnTransitionPair> exploredTransQueue = new LinkedList<LpnTransitionPair>();
HashSet<LpnTransitionPair> allExploredTrans = new HashSet<LpnTransitionPair>();
exploredTransQueue.add(seedTran);
//boolean foundEnabledTran = false;
HashSet<LpnTransitionPair> canEnable = new HashSet<LpnTransitionPair>();
while(!exploredTransQueue.isEmpty()){
LpnTransitionPair curTran = exploredTransQueue.poll();
allExploredTrans.add(curTran);
if (cachedNecessarySets.containsKey(curTran)) {
if (Options.getDebugMode()) {
System.out.println("Found transition" + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()).getName() + ")"
+ "'s necessary set in the cached necessary sets. Terminate BFS.");
writeStringWithNewLineToPORDebugFile("Found transition" + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()).getName() + ")"
+ "'s necessary set in the cached necessary sets. Terminate BFS.");
}
return cachedNecessarySets.get(curTran);
}
canEnable = buildCanBringTokenSet(curTran,lpnList, curStateArray);
// Decide if canSetEnablingTrue set can help to enable curTran.
Transition curTransition = lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex());
int[] varValueVector = curStateArray[curTran.getLpnIndex()].getVector();
if (curTransition.getEnablingTree() != null
&& curTransition.getEnablingTree().evaluateExpr(lpnList[curTran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) == 0.0)
canEnable.addAll(staticMap.get(curTran).getEnableBySettingEnablingTrue());
if (Options.getDebugMode()) {
printIntegerSet(canEnable, lpnList, "Neighbors that can help to enable trnasition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") ");
writeIntegerSetToPORDebugFile(canEnable, lpnList, "Neighbors that can help to enable trnasition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") ");
}
for (LpnTransitionPair neighborTran : canEnable) {
if (curEnabled.contains(neighborTran)) {
HashSet<LpnTransitionPair> necessarySet = new HashSet<LpnTransitionPair>();
necessarySet.add(neighborTran);
// TODO: Is it true that the necessary set for a disabled transition only contains a single element before the dependent set of the element is computed?
cachedNecessarySets.put(seedTran, necessarySet);
if (Options.getDebugMode()) {
System.out.println("Enabled neighbor that can help to enable trnasition " + lpnList[curTran.getLpnIndex()].getLabel()
+ "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel()
+ "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ")");
writeStringWithNewLineToPORDebugFile("Enabled neighbor that can help to enable trnasition " + lpnList[curTran.getLpnIndex()].getLabel()
+ "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel()
+ "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ")");
}
return necessarySet;
}
if (!allExploredTrans.contains(neighborTran)) {
allExploredTrans.add(neighborTran);
exploredTransQueue.add(neighborTran);
}
}
canEnable.clear();
}
return null;
}
private HashSet<LpnTransitionPair> buildCanBringTokenSet(
LpnTransitionPair curTran, LhpnFile[] lpnList, State[] curStateArray) {
// Build transition(s) set that can help to bring the marking(s).
Transition curTransition = lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex());
int[] presetPlaces = lpnList[curTran.getLpnIndex()].getPresetIndex(curTransition.getName());
HashSet<LpnTransitionPair> canBringToken = new HashSet<LpnTransitionPair>();
for (int i=0; i < presetPlaces.length; i++) {
int place = presetPlaces[i];
if (curStateArray[curTran.getLpnIndex()].getMarking()[place]==0) {
String placeName = lpnList[curTran.getLpnIndex()].getAllPlaces().get(place);
int[] presetTrans = lpnList[curTran.getLpnIndex()].getPresetIndex(placeName);
for (int j=0; j < presetTrans.length; j++) {
LpnTransitionPair presetTran = new LpnTransitionPair(curTran.getLpnIndex(), presetTrans[j]);
canBringToken.add(presetTran);
}
}
}
return canBringToken;
}
private void printCachedNecessarySets(LhpnFile[] lpnList) {
System.out.println("================ cachedNecessarySets =================");
for (LpnTransitionPair key : cachedNecessarySets.keySet()) {
System.out.print(lpnList[key.getLpnIndex()].getLabel() + "(" + lpnList[key.getLpnIndex()].getTransition(key.getTranIndex()).getName() + ") => ");
HashSet<LpnTransitionPair> necessarySet = cachedNecessarySets.get(key);
for (LpnTransitionPair necessary : necessarySet) {
System.out.print(lpnList[necessary.getLpnIndex()].getLabel() + "(" + lpnList[necessary.getLpnIndex()].getTransition(necessary.getTranIndex()).getName() + ") ");
}
System.out.print("\n");
}
}
private void writeCachedNecessarySetsToPORDebugFile(LhpnFile[] lpnList) {
writeStringWithNewLineToPORDebugFile("================ cachedNecessarySets =================");
for (LpnTransitionPair key : cachedNecessarySets.keySet()) {
writeStringToPORDebugFile(lpnList[key.getLpnIndex()].getLabel() + "(" + lpnList[key.getLpnIndex()].getTransition(key.getTranIndex()).getName() + ") => ");
HashSet<LpnTransitionPair> necessarySet = cachedNecessarySets.get(key);
for (LpnTransitionPair necessary : necessarySet) {
writeStringToPORDebugFile(lpnList[necessary.getLpnIndex()].getLabel() + "(" + lpnList[necessary.getLpnIndex()].getTransition(necessary.getTranIndex()).getName() + ") ");
}
writeStringWithNewLineToPORDebugFile("");
}
}
private HashSet<LpnTransitionPair> getIntSetSubstraction(
HashSet<LpnTransitionPair> left, HashSet<LpnTransitionPair> right) {
HashSet<LpnTransitionPair> sub = new HashSet<LpnTransitionPair>();
for (LpnTransitionPair lpnTranPair : left) {
if (!right.contains(lpnTranPair))
sub.add(lpnTranPair);
}
return sub;
}
// private LpnTranList getSetSubtraction(LpnTranList left, LpnTranList right) {
// LpnTranList sub = new LpnTranList();
// for (Transition lpnTran : left) {
// if (!right.contains(lpnTran))
// sub.add(lpnTran);
// return sub;
public boolean stateOnStack(int lpnIndex, State curState, HashSet<PrjState> stateStack) {
boolean isStateOnStack = false;
for (PrjState prjState : stateStack) {
State[] stateArray = prjState.toStateArray();
if (stateArray[lpnIndex] == curState) {
isStateOnStack = true;
break;
}
}
return isStateOnStack;
}
private void printIntegerSet(HashSet<LpnTransitionPair> indicies, StateGraph[] sgList, String setName) {
if (!setName.isEmpty())
System.out.print(setName + ": ");
if (indicies == null) {
System.out.println("null");
}
else if (indicies.isEmpty()) {
System.out.println("empty");
}
else {
for (LpnTransitionPair lpnTranPair : indicies) {
System.out.print("\t" + sgList[lpnTranPair.getLpnIndex()].getLpn().getLabel() + "("
+ sgList[lpnTranPair.getLpnIndex()].getLpn().getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ") \t");
}
System.out.print("\n");
}
}
private void writeIntegerSetToPORDebugFile(HashSet<LpnTransitionPair> indicies, StateGraph[] sgList, String setName) {
if (!setName.isEmpty())
writeStringToPORDebugFile(setName + ": ");
if (indicies == null) {
writeStringWithNewLineToPORDebugFile("null");
}
else if (indicies.isEmpty()) {
writeStringWithNewLineToPORDebugFile("empty");
}
else {
for (LpnTransitionPair lpnTranPair : indicies) {
writeStringToPORDebugFile("\t" + sgList[lpnTranPair.getLpnIndex()].getLpn().getLabel() + "("
+ sgList[lpnTranPair.getLpnIndex()].getLpn().getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ") \t");
}
writeStringWithNewLineToPORDebugFile("");
}
}
private void printIntegerSet(HashSet<LpnTransitionPair> indicies,
LhpnFile[] lpnList, String setName) {
if (!setName.isEmpty())
System.out.print(setName + ": ");
if (indicies == null) {
System.out.println("null");
}
else if (indicies.isEmpty()) {
System.out.println("empty");
}
else {
for (LpnTransitionPair lpnTranPair : indicies) {
System.out.print(lpnList[lpnTranPair.getLpnIndex()].getLabel() + "("
+ lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ") \t");
}
System.out.print("\n");
}
}
private void writeIntegerSetToPORDebugFile(HashSet<LpnTransitionPair> indicies,
LhpnFile[] lpnList, String setName) {
if (!setName.isEmpty())
writeStringToPORDebugFile(setName + ": ");
if (indicies == null) {
writeStringWithNewLineToPORDebugFile("null");
}
else if (indicies.isEmpty()) {
writeStringWithNewLineToPORDebugFile("empty");
}
else {
for (LpnTransitionPair lpnTranPair : indicies) {
writeStringToPORDebugFile(lpnList[lpnTranPair.getLpnIndex()].getLabel() + "("
+ lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ") \t");
}
writeStringWithNewLineToPORDebugFile("");
}
}
} |
package ol.source;
import com.google.gwt.core.client.JavaScriptObject;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;
/**
* XYZ options.
*
* @author Tino Desjardins
*
*/
@JsType(isNative = true)
public interface XyzOptions extends TileImageOptions {
/**
* Set the optional max zoom level. Default is 18.
*
* @param maxZoom max zoom
*/
@JsProperty
void setMaxZoom(int maxZoom);
/**
* Optional function to get tile URL given a tile coordinate and the
* projection. Required if url or urls are not provided.
*/
@JsProperty
void setTileUrlFunction(JavaScriptObject tileUrlFunction);
/**
* Optional function to load a tile given a URL. The default is
*
* function(imageTile, src) { imageTile.getImage().src = src; };
*/
@JsProperty
void setTileLoadFunction(JavaScriptObject tileLoadFunction);
} |
package org.wisdom.test.http;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.message.BasicNameValuePair;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.Map.Entry;
public class MultipartBody extends BaseRequest implements Body {
private Map<String, Object> parameters = new HashMap<String, Object>();
private boolean hasFile;
private HttpRequest httpRequestObj;
public MultipartBody(HttpRequest httpRequest) {
super(httpRequest);
this.httpRequestObj = httpRequest;
}
public MultipartBody field(String name, String value) {
parameters.put(name, value);
return this;
}
public MultipartBody field(String name, File file) {
this.parameters.put(name, file);
hasFile = true;
return this;
}
public MultipartBody basicAuth(String username, String password) {
httpRequestObj.basicAuth(username, password);
return this;
}
public HttpEntity getEntity() {
if (hasFile) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
for (Entry<String, Object> part : parameters.entrySet()) {
if (part.getValue() instanceof File) {
hasFile = true;
builder.addPart(part.getKey(), new FileBody((File) part.getValue()));
} else {
builder.addPart(part.getKey(), new StringBody(part.getValue().toString(), ContentType.APPLICATION_FORM_URLENCODED));
}
}
return builder.build();
} else {
try {
return new UrlEncodedFormEntity(getList(parameters), UTF_8);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
public static List<NameValuePair> getList(Map<String, Object> parameters) {
List<NameValuePair> result = new ArrayList<NameValuePair>();
if (parameters != null) {
for (Map.Entry<String, Object> entry : parameters.entrySet()) {
if (entry.getValue() != null) {
result.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
}
}
return result;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.